Просмотр исходного кода

Add support for Bearer token and Authentication header in webhook requests

Clean up code implementation
Jean-Baptiste Pin 8 месяцев назад
Родитель
Сommit
b496d2fa55
5 измененных файлов с 85 добавлено и 80 удалено
  1. 10 48
      authority/provisioner/est_auth.go
  2. 33 14
      est/api/api.go
  3. 26 18
      est/auth_context.go
  4. 13 0
      webhook/options.go
  5. 3 0
      webhook/types.go

+ 10 - 48
authority/provisioner/est_auth.go

@@ -19,15 +19,6 @@ var (
 	ErrESTAuthDenied              = errors.New("est authentication denied")
 )
 
-// ESTAuthMethod identifies the EST authentication method used.
-type ESTAuthMethod string
-
-const (
-	ESTAuthMethodTLSClientCertificate         ESTAuthMethod = "tls-client-certificate"
-	ESTAuthMethodTLSExternalClientCertificate ESTAuthMethod = "tls-external-client-certificate"
-	ESTAuthMethodHTTPBasicAuth                ESTAuthMethod = "http-basic-auth"
-)
-
 // ESTAuthRequest contains authentication material extracted from the request.
 type ESTAuthRequest struct {
 	CSR                    *x509.CertificateRequest
@@ -35,8 +26,10 @@ type ESTAuthRequest struct {
 	ClientCertificateChain []*x509.Certificate
 	CARoots                []*x509.Certificate
 	CAIntermediates        []*x509.Certificate
+	AuthenticationHeader   string
 	BasicAuthUsername      string
 	BasicAuthPassword      string
+	BearerToken            string
 }
 
 // AuthorizeRequest validates the request against configured EST auth methods.
@@ -44,43 +37,11 @@ func (s *EST) AuthorizeRequest(ctx context.Context, req ESTAuthRequest) ([]SignC
 	if s.hasAuthWebhooks() {
 		return s.authorizeWithWebhook(ctx, &req)
 	}
-	return s.authorizeRequestLocal(ctx, req)
-}
-
-// AuthorizeTLSClientCertificate validates a CA-issued client certificate.
-func (s *EST) AuthorizeTLSClientCertificate(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, chain, roots, intermediates []*x509.Certificate) error {
-	_, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
-		CSR:                    csr,
-		ClientCertificate:      cert,
-		ClientCertificateChain: chain,
-		CARoots:                roots,
-		CAIntermediates:        intermediates,
-	})
-	return err
-}
-
-// AuthorizeTLSExternalClientCertificate validates a client certificate against external roots.
-func (s *EST) AuthorizeTLSExternalClientCertificate(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, chain []*x509.Certificate) error {
-	_, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
-		CSR:                    csr,
-		ClientCertificate:      cert,
-		ClientCertificateChain: chain,
-	})
-	return err
-}
-
-// AuthorizeHTTPBasicAuth validates a username/password pair for EST.
-func (s *EST) AuthorizeHTTPBasicAuth(ctx context.Context, csr *x509.CertificateRequest, username, password string) error {
-	_, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
-		CSR:               csr,
-		BasicAuthUsername: username,
-		BasicAuthPassword: password,
-	})
-	return err
+	return s.authorizeRequestLocal(req)
 }
 
 // authorizeRequestLocal validates the request using provisioner configuration.
-func (s *EST) authorizeRequestLocal(ctx context.Context, req ESTAuthRequest) ([]SignCSROption, error) {
+func (s *EST) authorizeRequestLocal(req ESTAuthRequest) ([]SignCSROption, error) {
 	var lastErr error = ErrESTAuthMethodNotFound
 	if req.ClientCertificate != nil {
 		if boolValue(s.EnableTLSClientCertificate, false) {
@@ -144,12 +105,14 @@ func (s *EST) authorizeWithWebhook(ctx context.Context, req *ESTAuthRequest) ([]
 		if err != nil {
 			return nil, fmt.Errorf("failed creating webhook request: %w", err)
 		}
-	case req.hasBasicAuth():
-		whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithAuthorizationPrincipal(req.BasicAuthUsername))
+	case req.AuthenticationHeader != "":
+		whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithAuthenticationHeader(req.AuthenticationHeader))
 		if err != nil {
 			return nil, fmt.Errorf("failed creating webhook request: %w", err)
 		}
-		whreq.SCEPChallenge = req.BasicAuthPassword
+		if req.BearerToken != "" {
+			whreq.BearerToken = req.BearerToken
+		}
 	default:
 		return nil, errors.New("missing certificate or basic auth for webhook validation")
 	}
@@ -187,12 +150,11 @@ func (s *EST) hasAuthWebhooks() bool {
 
 // normalizeAuthConfig applies defaults and validates auth configuration.
 func (s *EST) normalizeAuthConfig() error {
+	enable := true
 	if !s.authMethodsConfigured() {
-		enable := true
 		s.EnableHTTPBasicAuth = &enable
 	}
 	if s.EnableHTTPBasicAuth == nil && (s.BasicAuthUsername != "" || s.BasicAuthPassword != "") {
-		enable := true
 		s.EnableHTTPBasicAuth = &enable
 	}
 	if boolValue(s.EnableHTTPBasicAuth, false) && s.BasicAuthPassword == "" && !s.hasAuthWebhooks() {

+ 33 - 14
est/api/api.go

@@ -26,6 +26,17 @@ const (
 	maxPayloadSize = 2 << 20
 )
 
+// Util to extract bearer token from request
+func BearerToken(r *http.Request) (string, bool) {
+	auth := r.Header.Get("Authorization")
+	const prefix = "Bearer "
+	// Case insensitive prefix match. See Issue 22736.
+	if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
+		return "", false
+	}
+	return auth[len(prefix):], true
+}
+
 // Route configures the EST routes under the provided router.
 func Route(r api.Router) {
 	r.MethodFunc(http.MethodGet, "/{provisionerName}/cacerts", getCACerts)
@@ -120,9 +131,6 @@ func enrollHandler(w http.ResponseWriter, r *http.Request) {
 	ctx := r.Context()
 	ctx, err := authContextFromRequest(ctx, r)
 	if err != nil {
-		if errors.Is(err, errMissingClientCertificateOrBasicAuth) {
-			w.Header().Set("WWW-Authenticate", `Basic realm="EST"`)
-		}
 		failWithStatus(w, r, http.StatusUnauthorized, err)
 		return
 	}
@@ -178,7 +186,7 @@ func enrollHandler(w http.ResponseWriter, r *http.Request) {
 	writeResponse(w, r, signed, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
 }
 
-var errMissingClientCertificateOrBasicAuth = errors.New("missing client certificate or basic auth")
+var errMissingAuth = errors.New("missing authentication material")
 
 // authContextFromRequest extracts auth material from the request into the context.
 func authContextFromRequest(ctx context.Context, r *http.Request) (context.Context, error) {
@@ -191,16 +199,21 @@ func authContextFromRequest(ctx context.Context, r *http.Request) (context.Conte
 		ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
 	}
 
-	if username, password, ok := r.BasicAuth(); ok {
-		ctx = est.NewBasicAuthContext(ctx, est.BasicAuth{
-			Username: username,
-			Password: password,
-		})
+	if authHeader := r.Header.Get("Authorization"); authHeader != "" {
+		ctx = est.NewAuthenticationHeaderContext(ctx, authHeader)
+		if token, ok := BearerToken(r); ok {
+			ctx = est.NewBearerTokenContext(ctx, token)
+		} else if username, password, ok := r.BasicAuth(); ok {
+			ctx = est.NewBasicAuthContext(ctx, est.BasicAuth{
+				Username: username,
+				Password: password,
+			})
+		}
 	}
 
 	if _, ok := est.ClientCertificateFromContext(ctx); !ok {
-		if _, ok := est.BasicAuthFromContext(ctx); !ok {
-			return ctx, errMissingClientCertificateOrBasicAuth
+		if _, ok := est.AuthenticationHeaderFromContext(ctx); !ok {
+			return ctx, errMissingAuth
 		}
 	}
 	return ctx, nil
@@ -220,9 +233,15 @@ func authorizeEnrollRequest(ctx context.Context, csr *x509.CertificateRequest) (
 		req.ClientCertificate = cert
 		req.ClientCertificateChain, _ = est.ClientCertificateChainFromContext(ctx)
 	}
-	if auth, ok := est.BasicAuthFromContext(ctx); ok {
-		req.BasicAuthUsername = auth.Username
-		req.BasicAuthPassword = auth.Password
+	if authHeader, ok := est.AuthenticationHeaderFromContext(ctx); ok {
+		req.AuthenticationHeader = authHeader
+		if auth, ok := est.BasicAuthFromContext(ctx); ok {
+			req.BasicAuthUsername = auth.Username
+			req.BasicAuthPassword = auth.Password
+		}
+		if token, ok := est.BearerTokenFromContext(ctx); ok {
+			req.BearerToken = token
+		}
 	}
 
 	opts, err := prov.AuthorizeRequest(ctx, req)

+ 26 - 18
est/auth_context.go

@@ -2,29 +2,21 @@ package est
 
 import "context"
 
-// AuthMethod describes the authentication method used for an EST request.
-type AuthMethod string
+// AuthenticationHeaderKey is the context key used to store the EST authentication header.
+type AuthenticationHeaderKey struct{}
 
-const (
-	AuthMethodTLSClientCertificate         AuthMethod = "tls-client-certificate"
-	AuthMethodTLSExternalClientCertificate AuthMethod = "tls-external-client-certificate"
-	AuthMethodHTTPBasicAuth                AuthMethod = "http-basic-auth"
-)
-
-type authMethodKey struct{}
-
-// NewAuthMethodContext stores the EST authentication method in the context.
-func NewAuthMethodContext(ctx context.Context, method AuthMethod) context.Context {
-	if method == "" {
+// NewAuthenticationHeaderContext stores the EST authentication header in the context.
+func NewAuthenticationHeaderContext(ctx context.Context, header string) context.Context {
+	if header == "" {
 		return ctx
 	}
-	return context.WithValue(ctx, authMethodKey{}, method)
+	return context.WithValue(ctx, AuthenticationHeaderKey{}, header)
 }
 
-// AuthMethodFromContext returns the EST authentication method stored in the context.
-func AuthMethodFromContext(ctx context.Context) (AuthMethod, bool) {
-	method, ok := ctx.Value(authMethodKey{}).(AuthMethod)
-	return method, ok
+// AuthenticationHeaderFromContext returns the EST authentication header stored in the context.
+func AuthenticationHeaderFromContext(ctx context.Context) (string, bool) {
+	header, ok := ctx.Value(AuthenticationHeaderKey{}).(string)
+	return header, ok
 }
 
 // BasicAuth holds the HTTP basic auth credentials for an EST request.
@@ -48,3 +40,19 @@ func BasicAuthFromContext(ctx context.Context) (BasicAuth, bool) {
 	auth, ok := ctx.Value(basicAuthKey{}).(BasicAuth)
 	return auth, ok
 }
+
+type BearerTokenKey struct{}
+
+// NewBearerTokenContext stores the HTTP bearer token in the context.
+func NewBearerTokenContext(ctx context.Context, token string) context.Context {
+	if token == "" {
+		return ctx
+	}
+	return context.WithValue(ctx, BearerTokenKey{}, token)
+}
+
+// BearerTokenFromContext returns the HTTP bearer token stored in the context.
+func BearerTokenFromContext(ctx context.Context) (string, bool) {
+	token, ok := ctx.Value(BearerTokenKey{}).(string)
+	return token, ok
+}

+ 13 - 0
webhook/options.go

@@ -134,7 +134,20 @@ func WithX5CCertificate(leaf *x509.Certificate) RequestBodyOption {
 			}
 			rb.X5CCertificate.PublicKey = key
 		}
+		return nil
+	}
+}
 
+func WithAuthenticationHeader(header string) RequestBodyOption {
+	return func(rb *RequestBody) error {
+		rb.AuthenticationHeader = header
+		return nil
+	}
+}
+
+func WithBearerToken(token string) RequestBodyOption {
+	return func(rb *RequestBody) error {
+		rb.BearerToken = token
 		return nil
 	}
 }

+ 3 - 0
webhook/types.go

@@ -102,4 +102,7 @@ type RequestBody struct {
 	X5CCertificate *X5CCertificate `json:"x5cCertificate,omitempty"`
 	// Set for X5C, AWS, GCP, and Azure provisioners
 	AuthorizationPrincipal string `json:"authorizationPrincipal,omitempty"`
+	// Set for EST webhook requests
+	AuthenticationHeader string `json:"authenticationHeader,omitempty"`
+	BearerToken          string `json:"bearerToken,omitempty"`
 }