| 1 |
/* |
| 2 |
Copyright 2015 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
/* |
| 18 |
oidc implements the authenticator.Token interface using the OpenID Connect protocol. |
| 19 |
|
| 20 |
config := oidc.Options{ |
| 21 |
IssuerURL: "https://accounts.google.com", |
| 22 |
ClientID: os.Getenv("GOOGLE_CLIENT_ID"), |
| 23 |
UsernameClaim: "email", |
| 24 |
} |
| 25 |
tokenAuthenticator, err := oidc.New(config) |
| 26 |
*/ |
| 27 |
package oidc |
| 28 |
|
| 29 |
import ( |
| 30 |
"context" |
| 31 |
"crypto/tls" |
| 32 |
"crypto/x509" |
| 33 |
"encoding/base64" |
| 34 |
"encoding/json" |
| 35 |
"fmt" |
| 36 |
"io/ioutil" |
| 37 |
"net/http" |
| 38 |
"net/url" |
| 39 |
"reflect" |
| 40 |
"strings" |
| 41 |
"sync" |
| 42 |
"sync/atomic" |
| 43 |
"time" |
| 44 |
|
| 45 |
"github.com/coreos/go-oidc" |
| 46 |
celgo "github.com/google/cel-go/cel" |
| 47 |
"github.com/google/cel-go/common/types/ref" |
| 48 |
|
| 49 |
authenticationv1 "k8s.io/api/authentication/v1" |
| 50 |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 51 |
"k8s.io/apimachinery/pkg/runtime" |
| 52 |
"k8s.io/apimachinery/pkg/util/net" |
| 53 |
"k8s.io/apimachinery/pkg/util/sets" |
| 54 |
"k8s.io/apimachinery/pkg/util/wait" |
| 55 |
"k8s.io/apiserver/pkg/apis/apiserver" |
| 56 |
apiservervalidation "k8s.io/apiserver/pkg/apis/apiserver/validation" |
| 57 |
"k8s.io/apiserver/pkg/authentication/authenticator" |
| 58 |
authenticationcel "k8s.io/apiserver/pkg/authentication/cel" |
| 59 |
authenticationtokenjwt "k8s.io/apiserver/pkg/authentication/token/jwt" |
| 60 |
"k8s.io/apiserver/pkg/authentication/user" |
| 61 |
certutil "k8s.io/client-go/util/cert" |
| 62 |
"k8s.io/klog/v2" |
| 63 |
) |
| 64 |
|
| 65 |
var ( |
| 66 |
// synchronizeTokenIDVerifierForTest should be set to true to force a |
| 67 |
// wait until the token ID verifiers are ready. |
| 68 |
synchronizeTokenIDVerifierForTest = false |
| 69 |
) |
| 70 |
|
| 71 |
const ( |
| 72 |
wellKnownEndpointPath = "/.well-known/openid-configuration" |
| 73 |
) |
| 74 |
|
| 75 |
type Options struct { |
| 76 |
// JWTAuthenticator is the authenticator that will be used to verify the JWT. |
| 77 |
JWTAuthenticator apiserver.JWTAuthenticator |
| 78 |
|
| 79 |
// Optional KeySet to allow for synchronous initialization instead of fetching from the remote issuer. |
| 80 |
// Mutually exclusive with JWTAuthenticator.Issuer.DiscoveryURL. |
| 81 |
KeySet oidc.KeySet |
| 82 |
|
| 83 |
// PEM encoded root certificate contents of the provider. Mutually exclusive with Client. |
| 84 |
CAContentProvider CAContentProvider |
| 85 |
|
| 86 |
// Optional http.Client used to make all requests to the remote issuer. Mutually exclusive with CAContentProvider. |
| 87 |
Client *http.Client |
| 88 |
|
| 89 |
// Optional CEL compiler used to compile the CEL expressions. This is useful to use a shared instance |
| 90 |
// of the compiler as these compilers holding a CEL environment are expensive to create. If not provided, |
| 91 |
// a default compiler will be created. |
| 92 |
// Note: the compiler construction depends on feature gates and the compatibility version to be initialized. |
| 93 |
Compiler authenticationcel.Compiler |
| 94 |
|
| 95 |
// SupportedSigningAlgs sets the accepted set of JOSE signing algorithms that |
| 96 |
// can be used by the provider to sign tokens. |
| 97 |
// |
| 98 |
// https://tools.ietf.org/html/rfc7518#section-3.1 |
| 99 |
// |
| 100 |
// This value defaults to RS256, the value recommended by the OpenID Connect |
| 101 |
// spec: |
| 102 |
// |
| 103 |
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation |
| 104 |
SupportedSigningAlgs []string |
| 105 |
|
| 106 |
DisallowedIssuers []string |
| 107 |
|
| 108 |
// now is used for testing. It defaults to time.Now. |
| 109 |
now func() time.Time |
| 110 |
} |
| 111 |
|
| 112 |
// Subset of dynamiccertificates.CAContentProvider that can be used to dynamically load root CAs. |
| 113 |
type CAContentProvider interface { |
| 114 |
CurrentCABundleContent() []byte |
| 115 |
} |
| 116 |
|
| 117 |
// initVerifier creates a new ID token verifier for the given configuration and issuer URL. On success, calls setVerifier with the |
| 118 |
// resulting verifier. |
| 119 |
func initVerifier(ctx context.Context, config *oidc.Config, iss string, audiences sets.Set[string]) (*idTokenVerifier, error) { |
| 120 |
provider, err := oidc.NewProvider(ctx, iss) |
| 121 |
if err != nil { |
| 122 |
return nil, fmt.Errorf("init verifier failed: %v", err) |
| 123 |
} |
| 124 |
return &idTokenVerifier{provider.Verifier(config), audiences}, nil |
| 125 |
} |
| 126 |
|
| 127 |
// asyncIDTokenVerifier is an ID token verifier that allows async initialization |
| 128 |
// of the issuer check. Must be passed by reference as it wraps sync.Mutex. |
| 129 |
type asyncIDTokenVerifier struct { |
| 130 |
m sync.Mutex |
| 131 |
|
| 132 |
// v is the ID token verifier initialized asynchronously. It remains nil |
| 133 |
// up until it is eventually initialized. |
| 134 |
// Guarded by m |
| 135 |
v *idTokenVerifier |
| 136 |
} |
| 137 |
|
| 138 |
// newAsyncIDTokenVerifier creates a new asynchronous token verifier. The |
| 139 |
// verifier is available immediately, but may remain uninitialized for some time |
| 140 |
// after creation. |
| 141 |
func newAsyncIDTokenVerifier(ctx context.Context, c *oidc.Config, iss string, audiences sets.Set[string]) *asyncIDTokenVerifier { |
| 142 |
t := &asyncIDTokenVerifier{} |
| 143 |
|
| 144 |
sync := make(chan struct{}) |
| 145 |
// Polls indefinitely in an attempt to initialize the distributed claims |
| 146 |
// verifier, or until context canceled. |
| 147 |
initFn := func(ctx context.Context) (done bool, err error) { |
| 148 |
klog.V(4).Infof("oidc authenticator: attempting init: iss=%v", iss) |
| 149 |
v, err := initVerifier(ctx, c, iss, audiences) |
| 150 |
if err != nil { |
| 151 |
klog.Errorf("oidc authenticator: async token verifier for issuer: %q: %v", iss, err) |
| 152 |
return false, nil |
| 153 |
} |
| 154 |
t.m.Lock() |
| 155 |
defer t.m.Unlock() |
| 156 |
t.v = v |
| 157 |
close(sync) |
| 158 |
return true, nil |
| 159 |
} |
| 160 |
|
| 161 |
go func() { |
| 162 |
_ = wait.PollUntilContextCancel(ctx, 10*time.Second, true, initFn) |
| 163 |
}() |
| 164 |
|
| 165 |
if synchronizeTokenIDVerifierForTest { |
| 166 |
select { |
| 167 |
case <-sync: |
| 168 |
case <-ctx.Done(): |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
return t |
| 173 |
} |
| 174 |
|
| 175 |
// verifier returns the underlying ID token verifier, or nil if one is not yet initialized. |
| 176 |
func (a *asyncIDTokenVerifier) verifier() *idTokenVerifier { |
| 177 |
a.m.Lock() |
| 178 |
defer a.m.Unlock() |
| 179 |
return a.v |
| 180 |
} |
| 181 |
|
| 182 |
type jwtAuthenticator struct { |
| 183 |
jwtAuthenticator apiserver.JWTAuthenticator |
| 184 |
|
| 185 |
// Contains an *oidc.IDTokenVerifier. Do not access directly use the |
| 186 |
// idTokenVerifier method. |
| 187 |
verifier atomic.Value |
| 188 |
|
| 189 |
// resolver is used to resolve distributed claims. |
| 190 |
resolver *claimResolver |
| 191 |
|
| 192 |
// celMapper contains the compiled CEL expressions for |
| 193 |
// username, groups, uid, extra, claimMapping and claimValidation |
| 194 |
celMapper authenticationcel.CELMapper |
| 195 |
|
| 196 |
// requiredClaims contains the list of claims that must be present in the token. |
| 197 |
requiredClaims map[string]string |
| 198 |
|
| 199 |
healthCheck atomic.Pointer[errorHolder] |
| 200 |
} |
| 201 |
|
| 202 |
// idTokenVerifier is a wrapper around oidc.IDTokenVerifier. It uses the oidc.IDTokenVerifier |
| 203 |
// to verify the raw ID token and then performs audience validation locally. |
| 204 |
type idTokenVerifier struct { |
| 205 |
verifier *oidc.IDTokenVerifier |
| 206 |
audiences sets.Set[string] |
| 207 |
} |
| 208 |
|
| 209 |
func (a *jwtAuthenticator) setVerifier(v *idTokenVerifier) { |
| 210 |
a.verifier.Store(v) |
| 211 |
if v != nil { |
| 212 |
// this must be done after the verifier has been stored so that a nil error |
| 213 |
// from HealthCheck always means that the authenticator is ready for use. |
| 214 |
a.healthCheck.Store(&errorHolder{}) |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
func (a *jwtAuthenticator) idTokenVerifier() (*idTokenVerifier, bool) { |
| 219 |
if v := a.verifier.Load(); v != nil { |
| 220 |
return v.(*idTokenVerifier), true |
| 221 |
} |
| 222 |
return nil, false |
| 223 |
} |
| 224 |
|
| 225 |
func AllValidSigningAlgorithms() []string { |
| 226 |
return sets.List(sets.KeySet(allowedSigningAlgs)) |
| 227 |
} |
| 228 |
|
| 229 |
// allowlist of signing algorithms to ensure users don't mistakenly pass something goofy. |
| 230 |
var allowedSigningAlgs = map[string]bool{ |
| 231 |
oidc.RS256: true, |
| 232 |
oidc.RS384: true, |
| 233 |
oidc.RS512: true, |
| 234 |
oidc.ES256: true, |
| 235 |
oidc.ES384: true, |
| 236 |
oidc.ES512: true, |
| 237 |
oidc.PS256: true, |
| 238 |
oidc.PS384: true, |
| 239 |
oidc.PS512: true, |
| 240 |
} |
| 241 |
|
| 242 |
type AuthenticatorTokenWithHealthCheck interface { |
| 243 |
authenticator.Token |
| 244 |
HealthCheck() error |
| 245 |
} |
| 246 |
|
| 247 |
// New returns an authenticator that is asynchronously initialized when opts.KeySet is not set. |
| 248 |
// The input lifecycleCtx is used to: |
| 249 |
// - terminate background goroutines that are needed for asynchronous initialization |
| 250 |
// - as the base context for any requests that are made (i.e. for key fetching) |
| 251 |
// Thus, once the lifecycleCtx is canceled, the authenticator must not be used. |
| 252 |
// A caller may check if the authenticator is healthy by calling the HealthCheck method. |
| 253 |
func New(lifecycleCtx context.Context, opts Options) (AuthenticatorTokenWithHealthCheck, error) { |
| 254 |
compiler := opts.Compiler |
| 255 |
if compiler == nil { |
| 256 |
compiler = authenticationcel.NewDefaultCompiler() |
| 257 |
} |
| 258 |
celMapper, fieldErr := apiservervalidation.CompileAndValidateJWTAuthenticator(compiler, opts.JWTAuthenticator, opts.DisallowedIssuers) |
| 259 |
if err := fieldErr.ToAggregate(); err != nil { |
| 260 |
return nil, err |
| 261 |
} |
| 262 |
|
| 263 |
supportedSigningAlgs := opts.SupportedSigningAlgs |
| 264 |
if len(supportedSigningAlgs) == 0 { |
| 265 |
// RS256 is the default recommended by OpenID Connect and an 'alg' value |
| 266 |
// providers are required to implement. |
| 267 |
supportedSigningAlgs = []string{oidc.RS256} |
| 268 |
} |
| 269 |
for _, alg := range supportedSigningAlgs { |
| 270 |
if !allowedSigningAlgs[alg] { |
| 271 |
return nil, fmt.Errorf("oidc: unsupported signing alg: %q", alg) |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
if opts.Client != nil && opts.CAContentProvider != nil { |
| 276 |
return nil, fmt.Errorf("oidc: Client and CAContentProvider are mutually exclusive") |
| 277 |
} |
| 278 |
|
| 279 |
client := opts.Client |
| 280 |
|
| 281 |
if client == nil { |
| 282 |
var roots *x509.CertPool |
| 283 |
var err error |
| 284 |
if opts.CAContentProvider != nil { |
| 285 |
// TODO(enj): make this reload CA data dynamically |
| 286 |
roots, err = certutil.NewPoolFromBytes(opts.CAContentProvider.CurrentCABundleContent()) |
| 287 |
if err != nil { |
| 288 |
return nil, fmt.Errorf("Failed to read the CA contents: %v", err) |
| 289 |
} |
| 290 |
} else { |
| 291 |
klog.Info("OIDC: No x509 certificates provided, will use host's root CA set") |
| 292 |
} |
| 293 |
|
| 294 |
// Copied from http.DefaultTransport. |
| 295 |
tr := net.SetTransportDefaults(&http.Transport{ |
| 296 |
// According to golang's doc, if RootCAs is nil, |
| 297 |
// TLS uses the host's root CA set. |
| 298 |
TLSClientConfig: &tls.Config{RootCAs: roots}, |
| 299 |
}) |
| 300 |
|
| 301 |
client = &http.Client{Transport: tr, Timeout: 30 * time.Second} |
| 302 |
} |
| 303 |
|
| 304 |
// If the discovery URL is set in authentication configuration, we set up a |
| 305 |
// roundTripper to rewrite the {url}/.well-known/openid-configuration to |
| 306 |
// the discovery URL. This is useful for self-hosted providers, for example, |
| 307 |
// providers that run on top of Kubernetes itself. |
| 308 |
if len(opts.JWTAuthenticator.Issuer.DiscoveryURL) > 0 { |
| 309 |
if opts.KeySet != nil { |
| 310 |
return nil, fmt.Errorf("oidc: KeySet and DiscoveryURL are mutually exclusive") |
| 311 |
} |
| 312 |
|
| 313 |
discoveryURL, err := url.Parse(opts.JWTAuthenticator.Issuer.DiscoveryURL) |
| 314 |
if err != nil { |
| 315 |
return nil, fmt.Errorf("oidc: invalid discovery URL: %w", err) |
| 316 |
} |
| 317 |
|
| 318 |
clientWithDiscoveryURL := *client |
| 319 |
baseTransport := clientWithDiscoveryURL.Transport |
| 320 |
if baseTransport == nil { |
| 321 |
baseTransport = http.DefaultTransport |
| 322 |
} |
| 323 |
// This matches the url construction in oidc.NewProvider as of go-oidc v2.2.1. |
| 324 |
// xref: https://github.com/coreos/go-oidc/blob/40cd342c4a2076195294612a834d11df23c1b25a/oidc.go#L114 |
| 325 |
urlToRewrite := strings.TrimSuffix(opts.JWTAuthenticator.Issuer.URL, "/") + wellKnownEndpointPath |
| 326 |
clientWithDiscoveryURL.Transport = &discoveryURLRoundTripper{baseTransport, discoveryURL, urlToRewrite} |
| 327 |
client = &clientWithDiscoveryURL |
| 328 |
} |
| 329 |
|
| 330 |
lifecycleCtx = oidc.ClientContext(lifecycleCtx, client) |
| 331 |
|
| 332 |
now := opts.now |
| 333 |
if now == nil { |
| 334 |
now = time.Now |
| 335 |
} |
| 336 |
|
| 337 |
audiences := sets.New[string](opts.JWTAuthenticator.Issuer.Audiences...) |
| 338 |
verifierConfig := &oidc.Config{ |
| 339 |
ClientID: opts.JWTAuthenticator.Issuer.Audiences[0], |
| 340 |
SupportedSigningAlgs: supportedSigningAlgs, |
| 341 |
Now: now, |
| 342 |
} |
| 343 |
if audiences.Len() > 1 { |
| 344 |
verifierConfig.ClientID = "" |
| 345 |
// SkipClientIDCheck is set to true because we want to support multiple audiences |
| 346 |
// in the authentication configuration. |
| 347 |
// The go oidc library does not support validating |
| 348 |
// multiple audiences, so we have to skip the client ID check and do it ourselves. |
| 349 |
// xref: https://github.com/coreos/go-oidc/issues/397 |
| 350 |
verifierConfig.SkipClientIDCheck = true |
| 351 |
} |
| 352 |
|
| 353 |
var resolver *claimResolver |
| 354 |
groupsClaim := opts.JWTAuthenticator.ClaimMappings.Groups.Claim |
| 355 |
if groupsClaim != "" { |
| 356 |
resolver = newClaimResolver(lifecycleCtx, groupsClaim, client, verifierConfig, audiences) |
| 357 |
} |
| 358 |
|
| 359 |
requiredClaims := make(map[string]string) |
| 360 |
for _, claimValidationRule := range opts.JWTAuthenticator.ClaimValidationRules { |
| 361 |
if len(claimValidationRule.Claim) > 0 { |
| 362 |
requiredClaims[claimValidationRule.Claim] = claimValidationRule.RequiredValue |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
authn := &jwtAuthenticator{ |
| 367 |
jwtAuthenticator: opts.JWTAuthenticator, |
| 368 |
resolver: resolver, |
| 369 |
celMapper: celMapper, |
| 370 |
requiredClaims: requiredClaims, |
| 371 |
} |
| 372 |
authn.healthCheck.Store(&errorHolder{ |
| 373 |
err: fmt.Errorf("oidc: authenticator for issuer %q is not initialized", authn.jwtAuthenticator.Issuer.URL), |
| 374 |
}) |
| 375 |
|
| 376 |
issuerURL := opts.JWTAuthenticator.Issuer.URL |
| 377 |
if opts.KeySet != nil { |
| 378 |
// We already have a key set, synchronously initialize the verifier. |
| 379 |
authn.setVerifier(&idTokenVerifier{ |
| 380 |
oidc.NewVerifier(issuerURL, opts.KeySet, verifierConfig), |
| 381 |
audiences, |
| 382 |
}) |
| 383 |
} else { |
| 384 |
// Asynchronously attempt to initialize the authenticator. This enables |
| 385 |
// self-hosted providers, providers that run on top of Kubernetes itself. |
| 386 |
go func() { |
| 387 |
// we ignore any errors from polling because they can only come from the context being canceled |
| 388 |
_ = wait.PollUntilContextCancel(lifecycleCtx, 10*time.Second, true, func(_ context.Context) (done bool, err error) { |
| 389 |
// this must always use lifecycleCtx because NewProvider uses that context for future key set fetching. |
| 390 |
// this also means that there is no correct way to control the timeout of the discovery request made by NewProvider. |
| 391 |
// the global timeout of the http.Client is still honored. |
| 392 |
provider, err := oidc.NewProvider(lifecycleCtx, issuerURL) |
| 393 |
if err != nil { |
| 394 |
klog.Errorf("oidc authenticator: initializing plugin: %v", err) |
| 395 |
authn.healthCheck.Store(&errorHolder{err: err}) |
| 396 |
return false, nil |
| 397 |
} |
| 398 |
|
| 399 |
verifier := provider.Verifier(verifierConfig) |
| 400 |
authn.setVerifier(&idTokenVerifier{verifier, audiences}) |
| 401 |
return true, nil |
| 402 |
}) |
| 403 |
}() |
| 404 |
} |
| 405 |
|
| 406 |
return newInstrumentedAuthenticator(issuerURL, authn), nil |
| 407 |
} |
| 408 |
|
| 409 |
type errorHolder struct { |
| 410 |
err error |
| 411 |
} |
| 412 |
|
| 413 |
// discoveryURLRoundTripper is a http.RoundTripper that rewrites the |
| 414 |
// {url}/.well-known/openid-configuration to the discovery URL. |
| 415 |
type discoveryURLRoundTripper struct { |
| 416 |
base http.RoundTripper |
| 417 |
// discoveryURL is the URL to use to fetch the openid configuration |
| 418 |
discoveryURL *url.URL |
| 419 |
// urlToRewrite is the URL to rewrite to the discovery URL |
| 420 |
urlToRewrite string |
| 421 |
} |
| 422 |
|
| 423 |
func (t *discoveryURLRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 424 |
if req.Method == http.MethodGet && req.URL.String() == t.urlToRewrite { |
| 425 |
clone := req.Clone(req.Context()) |
| 426 |
clone.Host = "" |
| 427 |
clone.URL = t.discoveryURL |
| 428 |
return t.base.RoundTrip(clone) |
| 429 |
} |
| 430 |
return t.base.RoundTrip(req) |
| 431 |
} |
| 432 |
|
| 433 |
// untrustedIssuer extracts an untrusted "iss" claim from the given JWT token, |
| 434 |
// or returns an error if the token can not be parsed. Since the JWT is not |
| 435 |
// verified, the returned issuer should not be trusted. |
| 436 |
func untrustedIssuer(token string) (string, error) { |
| 437 |
if strings.HasPrefix(strings.TrimSpace(token), "{") { |
| 438 |
return "", fmt.Errorf("token is not compact JWT") |
| 439 |
} |
| 440 |
parts := strings.Split(token, ".") |
| 441 |
if len(parts) != 3 { |
| 442 |
return "", fmt.Errorf("malformed token") |
| 443 |
} |
| 444 |
payload, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| 445 |
if err != nil { |
| 446 |
return "", fmt.Errorf("error decoding token: %v", err) |
| 447 |
} |
| 448 |
claims := struct { |
| 449 |
// WARNING: this JWT is not verified. Do not trust these claims. |
| 450 |
Issuer string `json:"iss"` |
| 451 |
}{} |
| 452 |
if err := json.Unmarshal(payload, &claims); err != nil { |
| 453 |
return "", fmt.Errorf("while unmarshaling token: %v", err) |
| 454 |
} |
| 455 |
// Coalesce the legacy GoogleIss with the new one. |
| 456 |
// |
| 457 |
// http://openid.net/specs/openid-connect-core-1_0.html#GoogleIss |
| 458 |
if claims.Issuer == "accounts.google.com" { |
| 459 |
return "https://accounts.google.com", nil |
| 460 |
} |
| 461 |
return claims.Issuer, nil |
| 462 |
} |
| 463 |
|
| 464 |
func hasCorrectIssuer(iss, tokenData string) bool { |
| 465 |
uiss, err := untrustedIssuer(tokenData) |
| 466 |
if err != nil { |
| 467 |
return false |
| 468 |
} |
| 469 |
if uiss != iss { |
| 470 |
return false |
| 471 |
} |
| 472 |
return true |
| 473 |
} |
| 474 |
|
| 475 |
// endpoint represents an OIDC distributed claims endpoint. |
| 476 |
type endpoint struct { |
| 477 |
// URL to use to request the distributed claim. This URL is expected to be |
| 478 |
// prefixed by one of the known issuer URLs. |
| 479 |
URL string `json:"endpoint,omitempty"` |
| 480 |
// AccessToken is the bearer token to use for access. If empty, it is |
| 481 |
// not used. Access token is optional per the OIDC distributed claims |
| 482 |
// specification. |
| 483 |
// See: http://openid.net/specs/openid-connect-core-1_0.html#DistributedExample |
| 484 |
AccessToken string `json:"access_token,omitempty"` |
| 485 |
// JWT is the container for aggregated claims. Not supported at the moment. |
| 486 |
// See: http://openid.net/specs/openid-connect-core-1_0.html#AggregatedExample |
| 487 |
JWT string `json:"JWT,omitempty"` |
| 488 |
} |
| 489 |
|
| 490 |
// claimResolver expands distributed claims by calling respective claim source |
| 491 |
// endpoints. |
| 492 |
type claimResolver struct { |
| 493 |
ctx context.Context |
| 494 |
|
| 495 |
// claim is the distributed claim that may be resolved. |
| 496 |
claim string |
| 497 |
|
| 498 |
// audiences is the set of acceptable audiences the JWT must be issued to. |
| 499 |
// At least one of the entries must match the "aud" claim in presented JWTs. |
| 500 |
audiences sets.Set[string] |
| 501 |
|
| 502 |
// client is the to use for resolving distributed claims |
| 503 |
client *http.Client |
| 504 |
|
| 505 |
// config is the OIDC configuration used for resolving distributed claims. |
| 506 |
config *oidc.Config |
| 507 |
|
| 508 |
// verifierPerIssuer contains, for each issuer, the appropriate verifier to use |
| 509 |
// for this claim. It is assumed that there will be very few entries in |
| 510 |
// this map. |
| 511 |
// Guarded by m. |
| 512 |
verifierPerIssuer map[string]*asyncIDTokenVerifier |
| 513 |
|
| 514 |
m sync.Mutex |
| 515 |
} |
| 516 |
|
| 517 |
// newClaimResolver creates a new resolver for distributed claims. |
| 518 |
// the input ctx is retained and is used as the base context for background requests such as key fetching. |
| 519 |
func newClaimResolver(ctx context.Context, claim string, client *http.Client, config *oidc.Config, audiences sets.Set[string]) *claimResolver { |
| 520 |
return &claimResolver{ |
| 521 |
ctx: ctx, |
| 522 |
claim: claim, |
| 523 |
audiences: audiences, |
| 524 |
client: client, |
| 525 |
config: config, |
| 526 |
verifierPerIssuer: map[string]*asyncIDTokenVerifier{}, |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
// Verifier returns either the verifier for the specified issuer, or error. |
| 531 |
func (r *claimResolver) Verifier(iss string) (*idTokenVerifier, error) { |
| 532 |
r.m.Lock() |
| 533 |
av := r.verifierPerIssuer[iss] |
| 534 |
if av == nil { |
| 535 |
// This lazy init should normally be very quick. |
| 536 |
ctx := oidc.ClientContext(r.ctx, r.client) |
| 537 |
av = newAsyncIDTokenVerifier(ctx, r.config, iss, r.audiences) |
| 538 |
r.verifierPerIssuer[iss] = av |
| 539 |
} |
| 540 |
r.m.Unlock() |
| 541 |
|
| 542 |
v := av.verifier() |
| 543 |
if v == nil { |
| 544 |
return nil, fmt.Errorf("verifier not initialized for issuer: %q", iss) |
| 545 |
} |
| 546 |
return v, nil |
| 547 |
} |
| 548 |
|
| 549 |
// expand extracts the distributed claims from claim names and claim sources. |
| 550 |
// The extracted claim value is pulled up into the supplied claims. |
| 551 |
// |
| 552 |
// Distributed claims are of the form as seen below, and are defined in the |
| 553 |
// OIDC Connect Core 1.0, section 5.6.2. |
| 554 |
// See: https://openid.net/specs/openid-connect-core-1_0.html#AggregatedDistributedClaims |
| 555 |
// |
| 556 |
// { |
| 557 |
// ... (other normal claims)... |
| 558 |
// "_claim_names": { |
| 559 |
// "groups": "src1" |
| 560 |
// }, |
| 561 |
// "_claim_sources": { |
| 562 |
// "src1": { |
| 563 |
// "endpoint": "https://www.example.com", |
| 564 |
// "access_token": "f005ba11" |
| 565 |
// }, |
| 566 |
// }, |
| 567 |
// } |
| 568 |
func (r *claimResolver) expand(ctx context.Context, c claims) error { |
| 569 |
const ( |
| 570 |
// The claim containing a map of endpoint references per claim. |
| 571 |
// OIDC Connect Core 1.0, section 5.6.2. |
| 572 |
claimNamesKey = "_claim_names" |
| 573 |
// The claim containing endpoint specifications. |
| 574 |
// OIDC Connect Core 1.0, section 5.6.2. |
| 575 |
claimSourcesKey = "_claim_sources" |
| 576 |
) |
| 577 |
|
| 578 |
_, ok := c[r.claim] |
| 579 |
if ok { |
| 580 |
// There already is a normal claim, skip resolving. |
| 581 |
return nil |
| 582 |
} |
| 583 |
names, ok := c[claimNamesKey] |
| 584 |
if !ok { |
| 585 |
// No _claim_names, no keys to look up. |
| 586 |
return nil |
| 587 |
} |
| 588 |
|
| 589 |
claimToSource := map[string]string{} |
| 590 |
if err := json.Unmarshal([]byte(names), &claimToSource); err != nil { |
| 591 |
return fmt.Errorf("oidc: error parsing distributed claim names: %v", err) |
| 592 |
} |
| 593 |
|
| 594 |
rawSources, ok := c[claimSourcesKey] |
| 595 |
if !ok { |
| 596 |
// Having _claim_names claim, but no _claim_sources is not an expected |
| 597 |
// state. |
| 598 |
return fmt.Errorf("oidc: no claim sources") |
| 599 |
} |
| 600 |
|
| 601 |
var sources map[string]endpoint |
| 602 |
if err := json.Unmarshal([]byte(rawSources), &sources); err != nil { |
| 603 |
// The claims sources claim is malformed, this is not an expected state. |
| 604 |
return fmt.Errorf("oidc: could not parse claim sources: %v", err) |
| 605 |
} |
| 606 |
|
| 607 |
src, ok := claimToSource[r.claim] |
| 608 |
if !ok { |
| 609 |
// No distributed claim present. |
| 610 |
return nil |
| 611 |
} |
| 612 |
ep, ok := sources[src] |
| 613 |
if !ok { |
| 614 |
return fmt.Errorf("id token _claim_names contained a source %s missing in _claims_sources", src) |
| 615 |
} |
| 616 |
if ep.URL == "" { |
| 617 |
// This is maybe an aggregated claim (ep.JWT != ""). |
| 618 |
return nil |
| 619 |
} |
| 620 |
return r.resolve(ctx, ep, c) |
| 621 |
} |
| 622 |
|
| 623 |
// resolve requests distributed claims from all endpoints passed in, |
| 624 |
// and inserts the lookup results into allClaims. |
| 625 |
func (r *claimResolver) resolve(ctx context.Context, endpoint endpoint, allClaims claims) error { |
| 626 |
// TODO: cache resolved claims. |
| 627 |
jwt, err := getClaimJWT(ctx, r.client, endpoint.URL, endpoint.AccessToken) |
| 628 |
if err != nil { |
| 629 |
return fmt.Errorf("while getting distributed claim %q: %v", r.claim, err) |
| 630 |
} |
| 631 |
untrustedIss, err := untrustedIssuer(jwt) |
| 632 |
if err != nil { |
| 633 |
return fmt.Errorf("getting untrusted issuer from endpoint %v failed for claim %q: %v", endpoint.URL, r.claim, err) |
| 634 |
} |
| 635 |
v, err := r.Verifier(untrustedIss) |
| 636 |
if err != nil { |
| 637 |
return fmt.Errorf("verifying untrusted issuer %v failed: %v", untrustedIss, err) |
| 638 |
} |
| 639 |
t, err := v.Verify(ctx, jwt) |
| 640 |
if err != nil { |
| 641 |
return fmt.Errorf("verify distributed claim token: %v", err) |
| 642 |
} |
| 643 |
var distClaims claims |
| 644 |
if err := t.Claims(&distClaims); err != nil { |
| 645 |
return fmt.Errorf("could not parse distributed claims for claim %v: %v", r.claim, err) |
| 646 |
} |
| 647 |
value, ok := distClaims[r.claim] |
| 648 |
if !ok { |
| 649 |
return fmt.Errorf("jwt returned by distributed claim endpoint %q did not contain claim: %v", endpoint.URL, r.claim) |
| 650 |
} |
| 651 |
allClaims[r.claim] = value |
| 652 |
return nil |
| 653 |
} |
| 654 |
|
| 655 |
func (v *idTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error) { |
| 656 |
t, err := v.verifier.Verify(ctx, rawIDToken) |
| 657 |
if err != nil { |
| 658 |
return nil, err |
| 659 |
} |
| 660 |
if err := v.verifyAudience(t); err != nil { |
| 661 |
return nil, err |
| 662 |
} |
| 663 |
return t, nil |
| 664 |
} |
| 665 |
|
| 666 |
// verifyAudience verifies the audience field in the ID token matches the expected audience. |
| 667 |
// This is added based on https://github.com/coreos/go-oidc/blob/b203e58c24394ddf5e816706a7645f01280245c7/oidc/verify.go#L275-L281 |
| 668 |
// with the difference that we allow multiple audiences. |
| 669 |
// |
| 670 |
// AuthenticationConfiguration has a audienceMatchPolicy field, but the only supported value now is "MatchAny". |
| 671 |
// So, The default match behavior is to match at least one of the audiences in the ID token. |
| 672 |
func (v *idTokenVerifier) verifyAudience(t *oidc.IDToken) error { |
| 673 |
// We validate audience field is not empty in the authentication configuration. |
| 674 |
// This check ensures callers of "Verify" using idTokenVerifier are not passing |
| 675 |
// an empty audience. |
| 676 |
if v.audiences.Len() == 0 { |
| 677 |
return fmt.Errorf("oidc: invalid configuration, audiences cannot be empty") |
| 678 |
} |
| 679 |
if v.audiences.HasAny(t.Audience...) { |
| 680 |
return nil |
| 681 |
} |
| 682 |
|
| 683 |
return fmt.Errorf("oidc: expected audience in %q got %q", sets.List(v.audiences), t.Audience) |
| 684 |
} |
| 685 |
|
| 686 |
func (a *jwtAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) { |
| 687 |
if !hasCorrectIssuer(a.jwtAuthenticator.Issuer.URL, token) { |
| 688 |
return nil, false, nil |
| 689 |
} |
| 690 |
|
| 691 |
verifier, ok := a.idTokenVerifier() |
| 692 |
if !ok { |
| 693 |
return nil, false, fmt.Errorf("oidc: authenticator not initialized") |
| 694 |
} |
| 695 |
|
| 696 |
idToken, err := verifier.Verify(ctx, token) |
| 697 |
if err != nil { |
| 698 |
return nil, false, fmt.Errorf("oidc: verify token: %v", err) |
| 699 |
} |
| 700 |
|
| 701 |
var c claims |
| 702 |
if err := idToken.Claims(&c); err != nil { |
| 703 |
return nil, false, fmt.Errorf("oidc: parse claims: %v", err) |
| 704 |
} |
| 705 |
if a.resolver != nil { |
| 706 |
if err := a.resolver.expand(ctx, c); err != nil { |
| 707 |
return nil, false, fmt.Errorf("oidc: could not expand distributed claims: %v", err) |
| 708 |
} |
| 709 |
} |
| 710 |
|
| 711 |
var claimsUnstructured *unstructured.Unstructured |
| 712 |
// Convert the claims to unstructured so that we can evaluate the CEL expressions |
| 713 |
// against the claims. This is done once here so that we don't have to convert |
| 714 |
// the claims to unstructured multiple times in the CEL mapper for each mapping. |
| 715 |
// Only perform this conversion if any of the mapping or validation rules contain |
| 716 |
// CEL expressions. |
| 717 |
// TODO(aramase): In the future when we look into making distributed claims work, |
| 718 |
// we should see if we can skip this function and use a dynamic type resolver for |
| 719 |
// both json.RawMessage and the distributed claim fetching. |
| 720 |
if a.celMapper.Username != nil || a.celMapper.Groups != nil || a.celMapper.UID != nil || a.celMapper.Extra != nil || a.celMapper.ClaimValidationRules != nil { |
| 721 |
if claimsUnstructured, err = convertObjectToUnstructured(&c); err != nil { |
| 722 |
return nil, false, fmt.Errorf("oidc: could not convert claims to unstructured: %w", err) |
| 723 |
} |
| 724 |
} |
| 725 |
|
| 726 |
var username string |
| 727 |
if username, err = a.getUsername(ctx, c, claimsUnstructured); err != nil { |
| 728 |
return nil, false, err |
| 729 |
} |
| 730 |
|
| 731 |
info := &user.DefaultInfo{Name: username} |
| 732 |
if info.Groups, err = a.getGroups(ctx, c, claimsUnstructured); err != nil { |
| 733 |
return nil, false, err |
| 734 |
} |
| 735 |
|
| 736 |
if info.UID, err = a.getUID(ctx, c, claimsUnstructured); err != nil { |
| 737 |
return nil, false, err |
| 738 |
} |
| 739 |
|
| 740 |
extra, err := a.getExtra(ctx, c, claimsUnstructured) |
| 741 |
if err != nil { |
| 742 |
return nil, false, err |
| 743 |
} |
| 744 |
if len(extra) > 0 { |
| 745 |
info.Extra = extra |
| 746 |
} |
| 747 |
|
| 748 |
// check to ensure all required claims are present in the ID token and have matching values. |
| 749 |
for claim, value := range a.requiredClaims { |
| 750 |
if !c.hasClaim(claim) { |
| 751 |
return nil, false, fmt.Errorf("oidc: required claim %s not present in ID token", claim) |
| 752 |
} |
| 753 |
|
| 754 |
// NOTE: Only string values are supported as valid required claim values. |
| 755 |
var claimValue string |
| 756 |
if err := c.unmarshalClaim(claim, &claimValue); err != nil { |
| 757 |
return nil, false, fmt.Errorf("oidc: parse claim %s: %w", claim, err) |
| 758 |
} |
| 759 |
if claimValue != value { |
| 760 |
return nil, false, fmt.Errorf("oidc: required claim %s value does not match. Got = %s, want = %s", claim, claimValue, value) |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
if a.celMapper.ClaimValidationRules != nil { |
| 765 |
evalResult, err := a.celMapper.ClaimValidationRules.EvalClaimMappings(ctx, claimsUnstructured) |
| 766 |
if err != nil { |
| 767 |
return nil, false, fmt.Errorf("oidc: error evaluating claim validation expression: %w", err) |
| 768 |
} |
| 769 |
if err := checkValidationRulesEvaluation(evalResult, func(a authenticationcel.ExpressionAccessor) (string, error) { |
| 770 |
claimValidationCondition, ok := a.(*authenticationcel.ClaimValidationCondition) |
| 771 |
if !ok { |
| 772 |
return "", fmt.Errorf("invalid type conversion, expected ClaimValidationCondition") |
| 773 |
} |
| 774 |
return claimValidationCondition.Message, nil |
| 775 |
}); err != nil { |
| 776 |
return nil, false, fmt.Errorf("oidc: error evaluating claim validation expression: %w", err) |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
if a.celMapper.UserValidationRules != nil { |
| 781 |
// Convert the user info to unstructured so that we can evaluate the CEL expressions |
| 782 |
// against the user info. This is done once here so that we don't have to convert |
| 783 |
// the user info to unstructured multiple times in the CEL mapper for each mapping. |
| 784 |
userInfoUnstructured, err := convertUserInfoToUnstructured(info) |
| 785 |
if err != nil { |
| 786 |
return nil, false, fmt.Errorf("oidc: could not convert user info to unstructured: %w", err) |
| 787 |
} |
| 788 |
|
| 789 |
evalResult, err := a.celMapper.UserValidationRules.EvalUser(ctx, userInfoUnstructured) |
| 790 |
if err != nil { |
| 791 |
return nil, false, fmt.Errorf("oidc: error evaluating user info validation rule: %w", err) |
| 792 |
} |
| 793 |
if err := checkValidationRulesEvaluation(evalResult, func(a authenticationcel.ExpressionAccessor) (string, error) { |
| 794 |
userValidationCondition, ok := a.(*authenticationcel.UserValidationCondition) |
| 795 |
if !ok { |
| 796 |
return "", fmt.Errorf("invalid type conversion, expected UserValidationCondition") |
| 797 |
} |
| 798 |
return userValidationCondition.Message, nil |
| 799 |
}); err != nil { |
| 800 |
return nil, false, fmt.Errorf("oidc: error evaluating user info validation rule: %w", err) |
| 801 |
} |
| 802 |
} |
| 803 |
|
| 804 |
return &authenticator.Response{User: info}, true, nil |
| 805 |
} |
| 806 |
|
| 807 |
func (a *jwtAuthenticator) HealthCheck() error { |
| 808 |
if holder := *a.healthCheck.Load(); holder.err != nil { |
| 809 |
return fmt.Errorf("oidc: authenticator for issuer %q is not healthy: %w", a.jwtAuthenticator.Issuer.URL, holder.err) |
| 810 |
} |
| 811 |
|
| 812 |
return nil |
| 813 |
} |
| 814 |
|
| 815 |
func (a *jwtAuthenticator) getUsername(ctx context.Context, c claims, claimsUnstructured *unstructured.Unstructured) (string, error) { |
| 816 |
if a.celMapper.Username != nil { |
| 817 |
evalResult, err := a.celMapper.Username.EvalClaimMapping(ctx, claimsUnstructured) |
| 818 |
if err != nil { |
| 819 |
return "", fmt.Errorf("oidc: error evaluating username claim expression: %w", err) |
| 820 |
} |
| 821 |
if evalResult.EvalResult.Type() != celgo.StringType { |
| 822 |
return "", fmt.Errorf("oidc: error evaluating username claim expression: %w", fmt.Errorf("username claim expression must return a string")) |
| 823 |
} |
| 824 |
|
| 825 |
username := evalResult.EvalResult.Value().(string) |
| 826 |
|
| 827 |
if len(username) == 0 { |
| 828 |
return "", fmt.Errorf("oidc: empty username via CEL expression is not allowed") |
| 829 |
} |
| 830 |
|
| 831 |
return username, nil |
| 832 |
} |
| 833 |
|
| 834 |
var username string |
| 835 |
usernameClaim := a.jwtAuthenticator.ClaimMappings.Username.Claim |
| 836 |
if err := c.unmarshalClaim(usernameClaim, &username); err != nil { |
| 837 |
return "", fmt.Errorf("oidc: parse username claims %q: %v", usernameClaim, err) |
| 838 |
} |
| 839 |
|
| 840 |
if usernameClaim == "email" { |
| 841 |
// If the email_verified claim is present, ensure the email is valid. |
| 842 |
// https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims |
| 843 |
if hasEmailVerified := c.hasClaim("email_verified"); hasEmailVerified { |
| 844 |
var emailVerified bool |
| 845 |
if err := c.unmarshalClaim("email_verified", &emailVerified); err != nil { |
| 846 |
return "", fmt.Errorf("oidc: parse 'email_verified' claim: %v", err) |
| 847 |
} |
| 848 |
|
| 849 |
// If the email_verified claim is present we have to verify it is set to `true`. |
| 850 |
if !emailVerified { |
| 851 |
return "", fmt.Errorf("oidc: email not verified") |
| 852 |
} |
| 853 |
} |
| 854 |
} |
| 855 |
|
| 856 |
userNamePrefix := a.jwtAuthenticator.ClaimMappings.Username.Prefix |
| 857 |
if userNamePrefix != nil && *userNamePrefix != "" { |
| 858 |
return *userNamePrefix + username, nil |
| 859 |
} |
| 860 |
return username, nil |
| 861 |
} |
| 862 |
|
| 863 |
func (a *jwtAuthenticator) getGroups(ctx context.Context, c claims, claimsUnstructured *unstructured.Unstructured) ([]string, error) { |
| 864 |
groupsClaim := a.jwtAuthenticator.ClaimMappings.Groups.Claim |
| 865 |
if len(groupsClaim) > 0 { |
| 866 |
if _, ok := c[groupsClaim]; ok { |
| 867 |
// Some admins want to use string claims like "role" as the group value. |
| 868 |
// Allow the group claim to be a single string instead of an array. |
| 869 |
// |
| 870 |
// See: https://github.com/kubernetes/kubernetes/issues/33290 |
| 871 |
var groups stringOrArray |
| 872 |
if err := c.unmarshalClaim(groupsClaim, &groups); err != nil { |
| 873 |
return nil, fmt.Errorf("oidc: parse groups claim %q: %w", groupsClaim, err) |
| 874 |
} |
| 875 |
|
| 876 |
prefix := a.jwtAuthenticator.ClaimMappings.Groups.Prefix |
| 877 |
if prefix != nil && *prefix != "" { |
| 878 |
for i, group := range groups { |
| 879 |
groups[i] = *prefix + group |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
return []string(groups), nil |
| 884 |
} |
| 885 |
} |
| 886 |
|
| 887 |
if a.celMapper.Groups == nil { |
| 888 |
return nil, nil |
| 889 |
} |
| 890 |
|
| 891 |
evalResult, err := a.celMapper.Groups.EvalClaimMapping(ctx, claimsUnstructured) |
| 892 |
if err != nil { |
| 893 |
return nil, fmt.Errorf("oidc: error evaluating group claim expression: %w", err) |
| 894 |
} |
| 895 |
|
| 896 |
groups, err := convertCELValueToStringList(evalResult.EvalResult) |
| 897 |
if err != nil { |
| 898 |
return nil, fmt.Errorf("oidc: error evaluating group claim expression: %w", err) |
| 899 |
} |
| 900 |
return groups, nil |
| 901 |
} |
| 902 |
|
| 903 |
func (a *jwtAuthenticator) getUID(ctx context.Context, c claims, claimsUnstructured *unstructured.Unstructured) (string, error) { |
| 904 |
uidClaim := a.jwtAuthenticator.ClaimMappings.UID.Claim |
| 905 |
if len(uidClaim) > 0 { |
| 906 |
var uid string |
| 907 |
if err := c.unmarshalClaim(uidClaim, &uid); err != nil { |
| 908 |
return "", fmt.Errorf("oidc: parse uid claim %q: %w", uidClaim, err) |
| 909 |
} |
| 910 |
return uid, nil |
| 911 |
} |
| 912 |
|
| 913 |
if a.celMapper.UID == nil { |
| 914 |
return "", nil |
| 915 |
} |
| 916 |
|
| 917 |
evalResult, err := a.celMapper.UID.EvalClaimMapping(ctx, claimsUnstructured) |
| 918 |
if err != nil { |
| 919 |
return "", fmt.Errorf("oidc: error evaluating uid claim expression: %w", err) |
| 920 |
} |
| 921 |
if evalResult.EvalResult.Type() != celgo.StringType { |
| 922 |
return "", fmt.Errorf("oidc: error evaluating uid claim expression: %w", fmt.Errorf("uid claim expression must return a string")) |
| 923 |
} |
| 924 |
|
| 925 |
return evalResult.EvalResult.Value().(string), nil |
| 926 |
} |
| 927 |
|
| 928 |
func (a *jwtAuthenticator) getExtra(ctx context.Context, c claims, claimsUnstructured *unstructured.Unstructured) (map[string][]string, error) { |
| 929 |
extra := make(map[string][]string) |
| 930 |
|
| 931 |
if credentialID := getCredentialID(c); len(credentialID) > 0 { |
| 932 |
extra[user.CredentialIDKey] = []string{credentialID} |
| 933 |
} |
| 934 |
|
| 935 |
if a.celMapper.Extra == nil { |
| 936 |
return extra, nil |
| 937 |
} |
| 938 |
|
| 939 |
evalResult, err := a.celMapper.Extra.EvalClaimMappings(ctx, claimsUnstructured) |
| 940 |
if err != nil { |
| 941 |
return nil, err |
| 942 |
} |
| 943 |
for _, result := range evalResult { |
| 944 |
extraMapping, ok := result.ExpressionAccessor.(*authenticationcel.ExtraMappingExpression) |
| 945 |
if !ok { |
| 946 |
return nil, fmt.Errorf("oidc: error evaluating extra claim expression: %w", fmt.Errorf("invalid type conversion, expected ExtraMappingCondition")) |
| 947 |
} |
| 948 |
|
| 949 |
extraValues, err := convertCELValueToStringList(result.EvalResult) |
| 950 |
if err != nil { |
| 951 |
return nil, fmt.Errorf("oidc: error evaluating extra claim expression: %s: %w", extraMapping.Expression, err) |
| 952 |
} |
| 953 |
|
| 954 |
if len(extraValues) > 0 { |
| 955 |
extra[extraMapping.Key] = extraValues |
| 956 |
} |
| 957 |
} |
| 958 |
|
| 959 |
return extra, nil |
| 960 |
} |
| 961 |
|
| 962 |
func getCredentialID(c claims) string { |
| 963 |
if _, ok := c["jti"]; ok { |
| 964 |
var jti string |
| 965 |
if err := c.unmarshalClaim("jti", &jti); err == nil { |
| 966 |
return authenticationtokenjwt.CredentialIDForJTI(jti) |
| 967 |
} |
| 968 |
} |
| 969 |
|
| 970 |
return "" |
| 971 |
} |
| 972 |
|
| 973 |
// getClaimJWT gets a distributed claim JWT from url, using the supplied access |
| 974 |
// token as bearer token. If the access token is "", the authorization header |
| 975 |
// will not be set. |
| 976 |
// TODO: Allow passing in JSON hints to the IDP. |
| 977 |
func getClaimJWT(ctx context.Context, client *http.Client, url, accessToken string) (string, error) { |
| 978 |
// TODO: Allow passing request body with configurable information. |
| 979 |
req, err := http.NewRequest("GET", url, nil) |
| 980 |
if err != nil { |
| 981 |
return "", fmt.Errorf("while calling %v: %v", url, err) |
| 982 |
} |
| 983 |
if accessToken != "" { |
| 984 |
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", accessToken)) |
| 985 |
} |
| 986 |
req = req.WithContext(ctx) |
| 987 |
response, err := client.Do(req) |
| 988 |
if err != nil { |
| 989 |
return "", err |
| 990 |
} |
| 991 |
defer response.Body.Close() |
| 992 |
// Report non-OK status code as an error. |
| 993 |
if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusIMUsed { |
| 994 |
return "", fmt.Errorf("error while getting distributed claim JWT: %v", response.Status) |
| 995 |
} |
| 996 |
responseBytes, err := ioutil.ReadAll(response.Body) |
| 997 |
if err != nil { |
| 998 |
return "", fmt.Errorf("could not decode distributed claim response") |
| 999 |
} |
| 1000 |
return string(responseBytes), nil |
| 1001 |
} |
| 1002 |
|
| 1003 |
type stringOrArray []string |
| 1004 |
|
| 1005 |
func (s *stringOrArray) UnmarshalJSON(b []byte) error { |
| 1006 |
var a []string |
| 1007 |
if err := json.Unmarshal(b, &a); err == nil { |
| 1008 |
*s = a |
| 1009 |
return nil |
| 1010 |
} |
| 1011 |
var str string |
| 1012 |
if err := json.Unmarshal(b, &str); err != nil { |
| 1013 |
return err |
| 1014 |
} |
| 1015 |
*s = []string{str} |
| 1016 |
return nil |
| 1017 |
} |
| 1018 |
|
| 1019 |
type claims map[string]json.RawMessage |
| 1020 |
|
| 1021 |
func (c claims) unmarshalClaim(name string, v interface{}) error { |
| 1022 |
val, ok := c[name] |
| 1023 |
if !ok { |
| 1024 |
return fmt.Errorf("claim not present") |
| 1025 |
} |
| 1026 |
return json.Unmarshal([]byte(val), v) |
| 1027 |
} |
| 1028 |
|
| 1029 |
func (c claims) hasClaim(name string) bool { |
| 1030 |
if _, ok := c[name]; !ok { |
| 1031 |
return false |
| 1032 |
} |
| 1033 |
return true |
| 1034 |
} |
| 1035 |
|
| 1036 |
// convertCELValueToStringList converts the CEL value to a string list. |
| 1037 |
// The CEL value needs to be either a string or a list of strings. |
| 1038 |
// "", [] are treated as not being present and will return nil. |
| 1039 |
// Empty string in a list of strings is treated as not being present and will be filtered out. |
| 1040 |
func convertCELValueToStringList(val ref.Val) ([]string, error) { |
| 1041 |
switch val.Type().TypeName() { |
| 1042 |
case celgo.StringType.TypeName(): |
| 1043 |
out := val.Value().(string) |
| 1044 |
if len(out) == 0 { |
| 1045 |
return nil, nil |
| 1046 |
} |
| 1047 |
return []string{out}, nil |
| 1048 |
|
| 1049 |
case celgo.ListType(nil).TypeName(): |
| 1050 |
var result []string |
| 1051 |
switch val.Value().(type) { |
| 1052 |
case []interface{}: |
| 1053 |
for _, v := range val.Value().([]interface{}) { |
| 1054 |
out, ok := v.(string) |
| 1055 |
if !ok { |
| 1056 |
return nil, fmt.Errorf("expression must return a string or a list of strings") |
| 1057 |
} |
| 1058 |
if len(out) == 0 { |
| 1059 |
continue |
| 1060 |
} |
| 1061 |
result = append(result, out) |
| 1062 |
} |
| 1063 |
case []ref.Val: |
| 1064 |
for _, v := range val.Value().([]ref.Val) { |
| 1065 |
out, ok := v.Value().(string) |
| 1066 |
if !ok { |
| 1067 |
return nil, fmt.Errorf("expression must return a string or a list of strings") |
| 1068 |
} |
| 1069 |
if len(out) == 0 { |
| 1070 |
continue |
| 1071 |
} |
| 1072 |
result = append(result, out) |
| 1073 |
} |
| 1074 |
default: |
| 1075 |
return nil, fmt.Errorf("expression must return a string or a list of strings") |
| 1076 |
} |
| 1077 |
|
| 1078 |
if len(result) == 0 { |
| 1079 |
return nil, nil |
| 1080 |
} |
| 1081 |
|
| 1082 |
return result, nil |
| 1083 |
case celgo.NullType.TypeName(): |
| 1084 |
return nil, nil |
| 1085 |
default: |
| 1086 |
return nil, fmt.Errorf("expression must return a string or a list of strings") |
| 1087 |
} |
| 1088 |
} |
| 1089 |
|
| 1090 |
// messageFunc is a function that returns a message for a validation rule. |
| 1091 |
type messageFunc func(authenticationcel.ExpressionAccessor) (string, error) |
| 1092 |
|
| 1093 |
// checkValidationRulesEvaluation checks if the validation rules evaluation results |
| 1094 |
// are valid. If the validation rules evaluation results are not valid, it returns |
| 1095 |
// an error with an optional message that was set in the validation rule. |
| 1096 |
func checkValidationRulesEvaluation(results []authenticationcel.EvaluationResult, messageFn messageFunc) error { |
| 1097 |
for _, result := range results { |
| 1098 |
if result.EvalResult.Type() != celgo.BoolType { |
| 1099 |
return fmt.Errorf("validation expression must return a boolean") |
| 1100 |
} |
| 1101 |
if !result.EvalResult.Value().(bool) { |
| 1102 |
expression := result.ExpressionAccessor.GetExpression() |
| 1103 |
|
| 1104 |
message, err := messageFn(result.ExpressionAccessor) |
| 1105 |
if err != nil { |
| 1106 |
return err |
| 1107 |
} |
| 1108 |
|
| 1109 |
return fmt.Errorf("validation expression '%s' failed: %s", expression, message) |
| 1110 |
} |
| 1111 |
} |
| 1112 |
|
| 1113 |
return nil |
| 1114 |
} |
| 1115 |
|
| 1116 |
func convertObjectToUnstructured(obj interface{}) (*unstructured.Unstructured, error) { |
| 1117 |
if obj == nil || reflect.ValueOf(obj).IsNil() { |
| 1118 |
return &unstructured.Unstructured{Object: nil}, nil |
| 1119 |
} |
| 1120 |
ret, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) |
| 1121 |
if err != nil { |
| 1122 |
return nil, err |
| 1123 |
} |
| 1124 |
return &unstructured.Unstructured{Object: ret}, nil |
| 1125 |
} |
| 1126 |
|
| 1127 |
func convertUserInfoToUnstructured(info user.Info) (*unstructured.Unstructured, error) { |
| 1128 |
userInfo := &authenticationv1.UserInfo{ |
| 1129 |
Extra: make(map[string]authenticationv1.ExtraValue), |
| 1130 |
Groups: info.GetGroups(), |
| 1131 |
UID: info.GetUID(), |
| 1132 |
Username: info.GetName(), |
| 1133 |
} |
| 1134 |
// Convert the extra information in the user object |
| 1135 |
for key, val := range info.GetExtra() { |
| 1136 |
userInfo.Extra[key] = authenticationv1.ExtraValue(val) |
| 1137 |
} |
| 1138 |
|
| 1139 |
// Convert the user info to unstructured so that we can evaluate the CEL expressions |
| 1140 |
// against the user info. This is done once here so that we don't have to convert |
| 1141 |
// the user info to unstructured multiple times in the CEL mapper for each mapping. |
| 1142 |
userInfoUnstructured, err := convertObjectToUnstructured(userInfo) |
| 1143 |
if err != nil { |
| 1144 |
return nil, err |
| 1145 |
} |
| 1146 |
|
| 1147 |
// check if the user info contains the required fields. If not, set them to empty values. |
| 1148 |
// This is done because the CEL expressions expect these fields to be present. |
| 1149 |
if userInfoUnstructured.Object["username"] == nil { |
| 1150 |
userInfoUnstructured.Object["username"] = "" |
| 1151 |
} |
| 1152 |
if userInfoUnstructured.Object["uid"] == nil { |
| 1153 |
userInfoUnstructured.Object["uid"] = "" |
| 1154 |
} |
| 1155 |
if userInfoUnstructured.Object["groups"] == nil { |
| 1156 |
userInfoUnstructured.Object["groups"] = []string{} |
| 1157 |
} |
| 1158 |
if userInfoUnstructured.Object["extra"] == nil { |
| 1159 |
userInfoUnstructured.Object["extra"] = map[string]authenticationv1.ExtraValue{} |
| 1160 |
} |
| 1161 |
return userInfoUnstructured, nil |
| 1162 |
} |