2021-01-20 00:37:02 +00:00
|
|
|
// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package impersonator
|
|
|
|
|
|
|
|
import (
|
2021-02-16 14:09:54 +00:00
|
|
|
"context"
|
2021-01-20 00:37:02 +00:00
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
2021-03-02 22:56:54 +00:00
|
|
|
"regexp"
|
2021-01-20 00:37:02 +00:00
|
|
|
"strings"
|
2021-02-23 01:23:11 +00:00
|
|
|
"time"
|
2021-01-20 00:37:02 +00:00
|
|
|
|
|
|
|
"github.com/go-logr/logr"
|
2021-02-15 23:00:10 +00:00
|
|
|
"k8s.io/apimachinery/pkg/runtime"
|
2021-02-18 15:13:24 +00:00
|
|
|
"k8s.io/apiserver/pkg/authentication/authenticator"
|
|
|
|
"k8s.io/apiserver/pkg/authentication/request/bearertoken"
|
2021-01-20 00:37:02 +00:00
|
|
|
"k8s.io/apiserver/pkg/authentication/user"
|
|
|
|
"k8s.io/client-go/rest"
|
|
|
|
"k8s.io/client-go/transport"
|
|
|
|
|
2021-02-18 18:37:28 +00:00
|
|
|
"go.pinniped.dev/generated/latest/apis/concierge/login"
|
2021-02-18 15:13:24 +00:00
|
|
|
"go.pinniped.dev/internal/constable"
|
2021-01-20 00:37:02 +00:00
|
|
|
"go.pinniped.dev/internal/controller/authenticator/authncache"
|
2021-02-09 20:28:56 +00:00
|
|
|
"go.pinniped.dev/internal/kubeclient"
|
2021-01-20 00:37:02 +00:00
|
|
|
)
|
|
|
|
|
2021-03-02 22:56:54 +00:00
|
|
|
var impersonateHeaderRegex = regexp.MustCompile("Impersonate-.*")
|
2021-01-20 00:37:02 +00:00
|
|
|
|
2021-02-12 01:22:47 +00:00
|
|
|
type proxy struct {
|
2021-02-15 23:00:10 +00:00
|
|
|
cache *authncache.Cache
|
|
|
|
jsonDecoder runtime.Decoder
|
|
|
|
proxy *httputil.ReverseProxy
|
|
|
|
log logr.Logger
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
|
|
|
|
2021-02-15 23:00:10 +00:00
|
|
|
func New(cache *authncache.Cache, jsonDecoder runtime.Decoder, log logr.Logger) (http.Handler, error) {
|
|
|
|
return newInternal(cache, jsonDecoder, log, func() (*rest.Config, error) {
|
2021-02-09 20:28:56 +00:00
|
|
|
client, err := kubeclient.New()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return client.JSONConfig, nil
|
|
|
|
})
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
|
|
|
|
2021-02-15 23:00:10 +00:00
|
|
|
func newInternal(cache *authncache.Cache, jsonDecoder runtime.Decoder, log logr.Logger, getConfig func() (*rest.Config, error)) (*proxy, error) {
|
2021-01-20 00:37:02 +00:00
|
|
|
kubeconfig, err := getConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not get in-cluster config: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
serverURL, err := url.Parse(kubeconfig.Host)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not parse host URL from in-cluster config: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
kubeTransportConfig, err := kubeconfig.TransportConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not get in-cluster transport config: %w", err)
|
|
|
|
}
|
2021-02-23 01:23:11 +00:00
|
|
|
kubeTransportConfig.TLS.NextProtos = []string{"http/1.1"} // TODO huh?
|
2021-01-20 00:37:02 +00:00
|
|
|
|
|
|
|
kubeRoundTripper, err := transport.New(kubeTransportConfig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not get in-cluster transport: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:22:47 +00:00
|
|
|
reverseProxy := httputil.NewSingleHostReverseProxy(serverURL)
|
|
|
|
reverseProxy.Transport = kubeRoundTripper
|
2021-02-23 01:23:11 +00:00
|
|
|
reverseProxy.FlushInterval = 200 * time.Millisecond // the "watch" verb will not work without this line
|
2021-01-20 00:37:02 +00:00
|
|
|
|
2021-02-12 01:22:47 +00:00
|
|
|
return &proxy{
|
2021-02-15 23:00:10 +00:00
|
|
|
cache: cache,
|
|
|
|
jsonDecoder: jsonDecoder,
|
|
|
|
proxy: reverseProxy,
|
|
|
|
log: log,
|
2021-01-20 00:37:02 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:22:47 +00:00
|
|
|
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2021-01-20 00:37:02 +00:00
|
|
|
log := p.log.WithValues(
|
|
|
|
"url", r.URL.String(),
|
|
|
|
"method", r.Method,
|
|
|
|
)
|
|
|
|
|
2021-02-16 13:15:50 +00:00
|
|
|
if err := ensureNoImpersonationHeaders(r); err != nil {
|
|
|
|
log.Error(err, "impersonation header already exists")
|
|
|
|
http.Error(w, "impersonation header already exists", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-18 15:13:24 +00:00
|
|
|
// Never mutate request (see http.Handler docs).
|
|
|
|
newR := r.Clone(r.Context())
|
|
|
|
|
|
|
|
authentication, authenticated, err := bearertoken.New(authenticator.TokenFunc(func(ctx context.Context, token string) (*authenticator.Response, bool, error) {
|
|
|
|
tokenCredentialReq, err := extractToken(token, p.jsonDecoder)
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err, "invalid token encoding")
|
|
|
|
return nil, false, &httpError{message: "invalid token encoding", code: http.StatusBadRequest}
|
|
|
|
}
|
|
|
|
|
|
|
|
log = log.WithValues(
|
|
|
|
"authenticator", tokenCredentialReq.Spec.Authenticator,
|
|
|
|
)
|
|
|
|
|
|
|
|
userInfo, err := p.cache.AuthenticateTokenCredentialRequest(newR.Context(), tokenCredentialReq)
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err, "received invalid token")
|
|
|
|
return nil, false, &httpError{message: "invalid token", code: http.StatusUnauthorized}
|
|
|
|
}
|
|
|
|
if userInfo == nil {
|
|
|
|
log.Info("received token that did not authenticate")
|
|
|
|
return nil, false, &httpError{message: "not authenticated", code: http.StatusUnauthorized}
|
|
|
|
}
|
|
|
|
log = log.WithValues("userID", userInfo.GetUID())
|
2021-01-20 00:37:02 +00:00
|
|
|
|
2021-02-18 15:13:24 +00:00
|
|
|
return &authenticator.Response{User: userInfo}, true, nil
|
|
|
|
})).AuthenticateRequest(newR)
|
2021-01-20 00:37:02 +00:00
|
|
|
if err != nil {
|
2021-02-18 15:13:24 +00:00
|
|
|
httpErr, ok := err.(*httpError)
|
|
|
|
if !ok {
|
|
|
|
log.Error(err, "unrecognized error")
|
|
|
|
http.Error(w, "unrecognized error", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
http.Error(w, httpErr.message, httpErr.code)
|
2021-01-20 00:37:02 +00:00
|
|
|
return
|
|
|
|
}
|
2021-02-18 15:13:24 +00:00
|
|
|
if !authenticated {
|
|
|
|
log.Error(constable.Error("token authenticator did not find token"), "invalid token encoding")
|
|
|
|
http.Error(w, "invalid token encoding", http.StatusBadRequest)
|
2021-01-20 00:37:02 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-18 15:13:24 +00:00
|
|
|
newR.Header = getProxyHeaders(authentication.User, r.Header)
|
2021-01-20 00:37:02 +00:00
|
|
|
|
|
|
|
log.Info("proxying authenticated request")
|
2021-02-09 18:25:24 +00:00
|
|
|
p.proxy.ServeHTTP(w, newR)
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
|
|
|
|
2021-02-18 15:13:24 +00:00
|
|
|
type httpError struct {
|
|
|
|
message string
|
|
|
|
code int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *httpError) Error() string { return e.message }
|
|
|
|
|
2021-02-16 13:15:50 +00:00
|
|
|
func ensureNoImpersonationHeaders(r *http.Request) error {
|
2021-03-02 22:56:54 +00:00
|
|
|
for key := range r.Header {
|
|
|
|
if impersonateHeaderRegex.MatchString(key) {
|
|
|
|
return fmt.Errorf("%q header already exists", key)
|
2021-02-16 13:15:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-16 14:09:54 +00:00
|
|
|
type roundTripperFunc func(*http.Request) (*http.Response, error)
|
|
|
|
|
|
|
|
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
|
|
|
|
2021-01-20 00:37:02 +00:00
|
|
|
func getProxyHeaders(userInfo user.Info, requestHeaders http.Header) http.Header {
|
|
|
|
newHeaders := http.Header{}
|
2021-02-16 14:09:54 +00:00
|
|
|
|
|
|
|
// Leverage client-go's impersonation RoundTripper to set impersonation headers for us in the new
|
|
|
|
// request. The client-go RoundTripper not only sets all of the impersonation headers for us, but
|
|
|
|
// it also does some helpful escaping of characters that can't go into an HTTP header. To do this,
|
|
|
|
// we make a fake call to the impersonation RoundTripper with a fake HTTP request and a delegate
|
|
|
|
// RoundTripper that captures the impersonation headers set on the request.
|
|
|
|
impersonateConfig := transport.ImpersonationConfig{
|
|
|
|
UserName: userInfo.GetName(),
|
|
|
|
Groups: userInfo.GetGroups(),
|
|
|
|
Extra: userInfo.GetExtra(),
|
|
|
|
}
|
|
|
|
impersonateHeaderSpy := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
|
|
|
newHeaders.Set(transport.ImpersonateUserHeader, r.Header.Get(transport.ImpersonateUserHeader))
|
|
|
|
for _, groupHeaderValue := range r.Header.Values(transport.ImpersonateGroupHeader) {
|
|
|
|
newHeaders.Add(transport.ImpersonateGroupHeader, groupHeaderValue)
|
|
|
|
}
|
|
|
|
for headerKey, headerValues := range r.Header {
|
|
|
|
if strings.HasPrefix(headerKey, transport.ImpersonateUserExtraHeaderPrefix) {
|
|
|
|
for _, headerValue := range headerValues {
|
|
|
|
newHeaders.Add(headerKey, headerValue)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, nil
|
|
|
|
})
|
|
|
|
fakeReq, _ := http.NewRequestWithContext(context.Background(), "", "", nil)
|
|
|
|
//nolint:bodyclose // We return a nil http.Response above, so there is nothing to close.
|
|
|
|
_, _ = transport.NewImpersonatingRoundTripper(impersonateConfig, impersonateHeaderSpy).RoundTrip(fakeReq)
|
|
|
|
|
2021-03-02 22:56:54 +00:00
|
|
|
// Copy over all headers except the Authorization header from the original request to the new request.
|
|
|
|
for key := range requestHeaders {
|
|
|
|
if key != "Authorization" {
|
|
|
|
for _, val := range requestHeaders.Values(key) {
|
|
|
|
newHeaders.Add(key, val)
|
|
|
|
}
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
|
|
|
}
|
2021-02-16 14:09:54 +00:00
|
|
|
|
2021-01-20 00:37:02 +00:00
|
|
|
return newHeaders
|
|
|
|
}
|
|
|
|
|
2021-02-18 15:13:24 +00:00
|
|
|
func extractToken(token string, jsonDecoder runtime.Decoder) (*login.TokenCredentialRequest, error) {
|
2021-02-23 01:23:11 +00:00
|
|
|
tokenCredentialRequestJSON, err := base64.StdEncoding.DecodeString(token)
|
2021-01-20 00:37:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid base64 in encoded bearer token: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-02-15 23:00:10 +00:00
|
|
|
obj, err := runtime.Decode(jsonDecoder, tokenCredentialRequestJSON)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid object encoded in bearer token: %w", err)
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
2021-02-18 15:13:24 +00:00
|
|
|
|
2021-02-15 23:00:10 +00:00
|
|
|
tokenCredentialRequest, ok := obj.(*login.TokenCredentialRequest)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("invalid TokenCredentialRequest encoded in bearer token: got %T", obj)
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|
2021-02-15 23:00:10 +00:00
|
|
|
|
|
|
|
return tokenCredentialRequest, nil
|
2021-01-20 00:37:02 +00:00
|
|
|
}
|