diff --git a/cmd/api/config/config.go b/cmd/api/config/config.go index 95fa7a676..5e455f882 100644 --- a/cmd/api/config/config.go +++ b/cmd/api/config/config.go @@ -12,6 +12,8 @@ import ( "time" "github.com/c2h5oh/datasize" + "github.com/go-viper/mapstructure/v2" + "github.com/kernel/hypeman/lib/oidcfederation" "github.com/kernel/hypeman/lib/snapshot" "github.com/knadh/koanf/parsers/yaml" "github.com/knadh/koanf/providers/env" @@ -297,6 +299,10 @@ type Config struct { // even though they are signed with JwtSecret and not yet expired. RevokedTokenHashes []string `koanf:"revoked_token_hashes"` + // OIDC configures the external issuers and federation rules whose identity + // tokens can be exchanged for short-lived API tokens. + OIDC oidcfederation.Config `koanf:"oidc"` + Network NetworkConfig `koanf:"network"` Caddy CaddyConfig `koanf:"caddy"` ACME ACMEConfig `koanf:"acme"` @@ -564,8 +570,14 @@ func Load(configPath string) (*Config, error) { return nil, fmt.Errorf("JWT_VERIFICATION_SECRETS must be a JSON array of strings") } } + var oidc map[string]interface{} + if value := os.Getenv("OIDC"); value != "" { + if err := json.Unmarshal([]byte(value), &oidc); err != nil || oidc == nil { + return nil, fmt.Errorf("OIDC must be a JSON object") + } + } envProvider := env.ProviderWithValue("", "__", func(key string, value string) (string, interface{}) { - if value == "" { + if value == "" || key == "OIDC" { return "", nil } if key == "JWT_VERIFICATION_SECRETS" { @@ -574,12 +586,31 @@ func Load(configPath string) (*Config, error) { return strings.ToLower(key), value }) _ = k.Load(envProvider, nil) + // OIDC replaces the YAML block as a whole: merging would leave rules from + // the file trusting issuers the environment redefined. + if oidc != nil { + k.Delete("oidc") + if err := k.Set("oidc", oidc); err != nil { + return nil, fmt.Errorf("failed to load OIDC: %w", err) + } + } // 4. Unmarshal to Config struct var cfg Config if err := k.Unmarshal("", &cfg); err != nil { return nil, fmt.Errorf("failed to unmarshal config: %w", err) } + // Decode the oidc block again, rejecting unknown keys: a misspelled + // restriction would otherwise be dropped and leave its rule wider than written. + cfg.OIDC = oidcfederation.Config{} + if err := k.UnmarshalWithConf("oidc", &cfg.OIDC, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{ + TagName: "koanf", + WeaklyTypedInput: true, + ErrorUnused: true, + Result: &cfg.OIDC, + }}); err != nil { + return nil, fmt.Errorf("invalid oidc config: %w", err) + } cfg.expandPathFields() return &cfg, nil @@ -615,6 +646,9 @@ func (c *Config) Validate() error { return fmt.Errorf("jwt_verification_secrets entry %d must not be empty", i) } } + if _, err := oidcfederation.Compile(c.OIDC); err != nil { + return err + } if c.MacOSOnly && (runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" || c.Hypervisor.Default != "vz") { return fmt.Errorf("macos_only requires vz on Apple silicon") } diff --git a/cmd/api/config/oidc_test.go b/cmd/api/config/oidc_test.go new file mode 100644 index 000000000..50605e66d --- /dev/null +++ b/cmd/api/config/oidc_test.go @@ -0,0 +1,139 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/kernel/hypeman/lib/oidcfederation" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const oidcYAML = ` +oidc: + issuers: + - name: github-actions + preset_type: github_actions + - name: cluster + preset_type: kubernetes + issuer_url: https://cluster.example.test + token_validation: + max_lifetime_seconds: 600 + federation_rules: + - name: ci + issuer: github-actions + expected_audience: https://hypeman.example.test + match: + type: github_actions + repository_id: 12 + repository_owner_id: "34" + workflow: .github/workflows/test.yml + ref: refs/heads/main + event_names: [schedule] + claims: + /runner_environment: github-hosted + authorization: + permissions: [instance:read, instance:write] + - name: pods + issuer: cluster + expected_audience: https://hypeman.example.test + match: + type: kubernetes + namespace: ci + service_account: runner + claims: + /kubernetes.io/namespace: ci + authorization: + permissions: [image:read] + max_token_ttl_seconds: 120 +` + +func writeConfig(t *testing.T, body string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(body), 0600)) + return path +} + +func TestLoadOIDC(t *testing.T) { + t.Setenv("OIDC", "") + cfg, err := Load(writeConfig(t, oidcYAML)) + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + registry, err := oidcfederation.Compile(cfg.OIDC) + require.NoError(t, err) + + ci, ok := registry.Rule("ci") + require.True(t, ok) + assert.Equal(t, oidcfederation.GitHubIssuer, ci.IssuerSpec.IssuerURL) + assert.Equal(t, "12", ci.Match.RepositoryID, "an unquoted numeric ID is read as text") + assert.Equal(t, []string{"schedule"}, ci.Match.EventNames) + assert.Equal(t, "github-hosted", ci.Match.Claims["/runner_environment"]) + assert.Equal(t, []string{"instance:read", "instance:write"}, ci.Authorization.Permissions) + + pods, ok := registry.Rule("pods") + require.True(t, ok) + assert.Equal(t, "ci", pods.Match.Claims["/kubernetes.io/namespace"], "a dotted claim pointer is one key") + assert.Equal(t, 600, *pods.IssuerSpec.TokenValidation.MaxLifetimeSeconds) + assert.Equal(t, 120, *pods.Authorization.MaxTokenTTLSeconds) +} + +func TestLoadWithoutOIDC(t *testing.T) { + t.Setenv("OIDC", "") + cfg, err := Load(writeConfig(t, "{}\n")) + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + registry, err := oidcfederation.Compile(cfg.OIDC) + require.NoError(t, err) + assert.False(t, registry.Enabled()) +} + +// The environment replaces the file's block; it is not merged into it. +func TestLoadOIDCFromEnvironment(t *testing.T) { + t.Setenv("OIDC", `{"issuers":[{"name":"idp","issuer_url":"https://idp.example.test"}],"federation_rules":[{"name":"deploy","issuer":"idp","expected_audience":"https://hypeman.example.test","match":{"type":"custom_oidc","subject":"deployer"},"authorization":{"permissions":["image:write"],"max_token_ttl_seconds":60}}]}`) + cfg, err := Load(writeConfig(t, oidcYAML)) + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + registry, err := oidcfederation.Compile(cfg.OIDC) + require.NoError(t, err) + _, ok := registry.Rule("ci") + assert.False(t, ok, "rules from the file do not survive the override") + deploy, ok := registry.Rule("deploy") + require.True(t, ok) + assert.Equal(t, 60, *deploy.Authorization.MaxTokenTTLSeconds) + + t.Setenv("OIDC", `{}`) + cfg, err = Load(writeConfig(t, oidcYAML)) + require.NoError(t, err) + assert.Empty(t, cfg.OIDC.FederationRules, "an empty object turns federation off") +} + +func TestLoadOIDCRejectsInvalidConfig(t *testing.T) { + for name, body := range map[string]string{ + // A misspelled restriction must not be dropped silently. + "unknown rule key": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s, subject_prefx: t}\n authorization: {permissions: [image:read]}\n", + "unknown block key": "oidc:\n issuer: []\n", + // A repository name is pinned through claims; a field the matcher ignored would look enforced. + "repository name key": "oidc:\n issuers: [{name: gh, preset_type: github_actions}]\n federation_rules:\n - name: r\n issuer: gh\n expected_audience: a\n match: {type: github_actions, repository: owner/name, repository_id: 1, repository_owner_id: 2, workflow: .github/workflows/ci.yml, ref: refs/heads/main}\n authorization: {permissions: [image:read]}\n", + "unknown issuer": "oidc:\n federation_rules:\n - name: r\n issuer: missing\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n authorization: {permissions: [image:read]}\n", + "no permissions": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n", + "wildcard permission": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n authorization: {permissions: ['*']}\n", + } { + t.Run(name, func(t *testing.T) { + t.Setenv("OIDC", "") + cfg, err := Load(writeConfig(t, body)) + if err == nil { + err = cfg.Validate() + } + require.Error(t, err) + }) + } + for _, value := range []string{`[]`, `null`, `"oidc"`, `{"issuers":`, `{"unknown":true}`} { + t.Run(value, func(t *testing.T) { + t.Setenv("OIDC", value) + _, err := Load(writeConfig(t, "{}\n")) + require.Error(t, err) + }) + } +} diff --git a/go.mod b/go.mod index 98dbd6a61..06c35df97 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,8 @@ require ( github.com/getkin/kin-openapi v0.133.0 github.com/ghodss/yaml v1.0.0 github.com/go-chi/chi/v5 v5.3.0 + github.com/go-jose/go-jose/v4 v4.1.5 + github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.3.0 github.com/google/go-containerregistry v0.20.6 github.com/google/uuid v1.6.0 @@ -97,7 +99,6 @@ require ( github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/go-test/deep v1.1.1 // indirect - github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect github.com/josharian/intern v1.0.0 // indirect diff --git a/go.sum b/go.sum index ad9465561..cc4d836b6 100644 --- a/go.sum +++ b/go.sum @@ -216,6 +216,8 @@ github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM= github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA= +github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= diff --git a/lib/oidcfederation/README.md b/lib/oidcfederation/README.md new file mode 100644 index 000000000..36d6aa5e2 --- /dev/null +++ b/lib/oidcfederation/README.md @@ -0,0 +1,51 @@ +# oidcfederation + +Validates OIDC identity tokens from operator-configured issuers, so a workload can prove who it +is with a token it already holds instead of a stored Hypeman API token. + +Trust is two kinds of object, both written in the `oidc` block of the server configuration: + +- An **issuer** names who signs: an issuer URL, where its public keys come from (`discovery`, + `explicit_url` or `inline`), the longest assertion lifetime accepted, and whether an assertion + may be presented more than once. +- A **federation rule** names which workload of one issuer is accepted and what it receives: the + audience the assertion must carry, the conditions its claims must meet, a `permissions` scope + list and a token lifetime. + +`Compile` validates a configuration and returns a `Registry` of rules. `Verifier.Verify` checks one +assertion against a rule's issuer and audience, and `Match.Matches` evaluates the rule's conditions +on the verified claims. + +## Presets + +Each issuer has a `preset_type`, and a rule's `match.type` must be the same type. A preset carries +its provider's mandatory identity checks, so a rule cannot trade them for a generic matcher. + +| Preset | Recognized by | A rule must name | +|---|---|---| +| `github_actions` | issuer URL | numeric `repository_id` and `repository_owner_id`, one of `workflow`, `workflow_ref` or `job_workflow_ref`, and `ref` or `environment`. `event_names` defaults to `push` and `workflow_dispatch`. | +| `google_cloud` | issuer URL | a numeric `subject` | +| `microsoft_entra` | issuer URL | `subject`, or an `/oid`, `/appid` or `/azp` claim. The tenant is pinned from the issuer URL. Tokens carrying delegated scopes are refused. | +| `kubernetes` | configuration | `namespace` and `service_account` | +| `aws`, `custom_oidc` | configuration | `subject`, `subject_prefix` or at least one claim | + +`claims` maps a JSON Pointer to the text a scalar claim must equal. Booleans and numbers compare by +their JSON text; objects and arrays never match. + +## Verification + +- The token's `iss` must equal the configured issuer URL before any key is fetched. Key locations + come only from configuration, never from the token. +- Keys are fetched over HTTPS from public addresses only, without redirects or an ambient proxy, + and cached for five minutes. An unknown `kid` forces a refresh: after one that succeeds, the + next waits a minute; after a fetch that fails, the next attempt waits ten seconds. Keys + published for another purpose, such as encryption, are ignored. +- Only asymmetric signature algorithms are accepted, and only RS256 for GitHub, Google and Entra. +- An assertion needs `sub`, `iat`, `exp` and exactly one `aud` equal to the rule's + `expected_audience`. Its lifetime must fit the issuer's `max_lifetime_seconds`. +- A single-use issuer's assertion needs a token ID (`jti`, or `uti` for Entra). GitHub and AWS are + always single-use. Google identity tokens carry no ID, so Google always allows reuse. Kubernetes + allows reuse by default, because a pod reads the same projected token until it is rotated. + +The verifier reports only that an assertion is invalid or that keys are unavailable. A +`KeyProblem` carries the reason an issuer's keys cannot be used, for the operator's logs. diff --git a/lib/oidcfederation/claims.go b/lib/oidcfederation/claims.go new file mode 100644 index 000000000..096dc38cc --- /dev/null +++ b/lib/oidcfederation/claims.go @@ -0,0 +1,76 @@ +package oidcfederation + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" +) + +func pointerParts(pointer string) ([]string, error) { + if pointer == "" || !strings.HasPrefix(pointer, "/") || len(pointer) > 1024 { + return nil, fmt.Errorf("%w: claim selector must be a JSON Pointer", ErrInvalid) + } + parts := strings.Split(pointer[1:], "/") + for i, part := range parts { + var decoded strings.Builder + for j := 0; j < len(part); j++ { + if part[j] != '~' { + decoded.WriteByte(part[j]) + continue + } + j++ + if j == len(part) || (part[j] != '0' && part[j] != '1') { + return nil, ErrInvalid + } + if part[j] == '0' { + decoded.WriteByte('~') + } else { + decoded.WriteByte('/') + } + } + parts[i] = decoded.String() + } + return parts, nil +} + +// ClaimString resolves a JSON Pointer to a scalar claim as text. Providers send +// some claims as booleans or numbers (Google's email_verified is true, not +// "true"), so those compare by their JSON text. Objects and arrays never match. +func ClaimString(claims map[string]any, pointer string) (string, bool) { + parts, err := pointerParts(pointer) + if err != nil { + return "", false + } + var value any = claims + for _, part := range parts { + switch node := value.(type) { + case map[string]any: + var ok bool + value, ok = node[part] + if !ok { + return "", false + } + case []any: + index, err := strconv.Atoi(part) + if err != nil || index < 0 || index >= len(node) || strconv.Itoa(index) != part { + return "", false + } + value = node[index] + default: + return "", false + } + } + switch scalar := value.(type) { + case string: + return scalar, true + case bool: + return strconv.FormatBool(scalar), true + case json.Number: + return scalar.String(), true + case float64: + return strconv.FormatFloat(scalar, 'f', -1, 64), true + default: + return "", false + } +} diff --git a/lib/oidcfederation/issuer.go b/lib/oidcfederation/issuer.go new file mode 100644 index 000000000..8ffd7b126 --- /dev/null +++ b/lib/oidcfederation/issuer.go @@ -0,0 +1,148 @@ +package oidcfederation + +import ( + "cmp" + "encoding/json" + "fmt" + "slices" + "strings" +) + +var presetTypes = []string{"github_actions", "aws", "google_cloud", "microsoft_entra", "kubernetes", "custom_oidc"} + +// normalizeIssuer derives preset defaults and validates supported key and assertion settings. +func normalizeIssuer(out IssuerSpec) (IssuerSpec, error) { + if err := validateName(out.Name); err != nil { + return out, err + } + switch out.PresetType { + case "github_actions": + if out.IssuerURL == "" { + out.IssuerURL = GitHubIssuer + } + case "google_cloud": + if out.IssuerURL == "" { + out.IssuerURL = GoogleIssuer + } + } + issuerURL, err := httpsURL(out.IssuerURL) + if err != nil || issuerURL.RawQuery != "" { + return out, fmt.Errorf("%w: invalid issuer URL", ErrInvalid) + } + known := presetForIssuer(out.IssuerURL) + if out.PresetType == "" { + out.PresetType = cmp.Or(known, "custom_oidc") + } + if !slices.Contains(presetTypes, out.PresetType) { + return out, fmt.Errorf("%w: unsupported issuer preset", ErrInvalid) + } + // GitHub, Google and Entra issuers are recognized by URL, so no other preset can relax their rules. + if known != out.PresetType && (known != "" || slices.Contains([]string{"github_actions", "google_cloud", "microsoft_entra"}, out.PresetType)) { + return out, fmt.Errorf("%w: preset and issuer URL disagree", ErrInvalid) + } + if out.JWKS.Type == "" { + out.JWKS.Type = "discovery" + } + if out.TokenValidation.MaxLifetimeSeconds == nil { + v := 3600 + if out.PresetType == "microsoft_entra" { + v = 7500 + } + out.TokenValidation.MaxLifetimeSeconds = &v + } + if n := *out.TokenValidation.MaxLifetimeSeconds; n < 1 || n > MaxIncomingLifetimeSeconds { + return out, fmt.Errorf("%w: incoming lifetime must be between 1 and %d seconds", ErrInvalid, MaxIncomingLifetimeSeconds) + } + if out.TokenValidation.ReplayProtection == "" { + out.TokenValidation.ReplayProtection = ReplaySingleUse + // A pod reads the same projected token until the kubelet rotates it, so + // single use would fail every exchange after the first. + if out.PresetType == "google_cloud" || out.PresetType == "kubernetes" { + out.TokenValidation.ReplayProtection = ReplayAllowReuse + } + } + if !slices.Contains([]string{ReplaySingleUse, ReplayAllowReuse}, out.TokenValidation.ReplayProtection) { + return out, fmt.Errorf("%w: unsupported replay policy", ErrInvalid) + } + if out.TokenValidation.ReplayProtection == ReplayAllowReuse && !slices.Contains([]string{"google_cloud", "microsoft_entra", "kubernetes", "custom_oidc"}, out.PresetType) { + return out, fmt.Errorf("%w: GitHub and AWS assertions are always single-use", ErrInvalid) + } + // A Google identity token carries no token ID, so there is nothing to consume. + if out.TokenValidation.ReplayProtection == ReplaySingleUse && out.PresetType == "google_cloud" { + return out, fmt.Errorf("%w: Google identity tokens carry no token ID and require allow_reuse", ErrInvalid) + } + if err := validateCA(out.JWKS.CACertPEM); err != nil { + return out, err + } + switch out.JWKS.Type { + case "discovery": + if out.JWKS.URL != "" || len(out.JWKS.Keys) != 0 { + return out, fmt.Errorf("%w: conflicting key sources", ErrInvalid) + } + if strings.HasPrefix(out.IssuerURL, "https://sts.windows.net/") && out.PresetType == "microsoft_entra" && out.JWKS.DiscoveryBaseURL == "" { + out.JWKS.DiscoveryBaseURL = "https://login.microsoftonline.com/" + entraTenant(out.IssuerURL) + } + if out.JWKS.DiscoveryBaseURL != "" { + base, err := httpsURL(out.JWKS.DiscoveryBaseURL) + if err != nil || base.RawQuery != "" { + return out, fmt.Errorf("%w: invalid discovery base URL", ErrInvalid) + } + } + case "explicit_url": + if out.JWKS.DiscoveryBaseURL != "" || len(out.JWKS.Keys) != 0 { + return out, fmt.Errorf("%w: conflicting key sources", ErrInvalid) + } + if _, err := httpsURL(out.JWKS.URL); err != nil { + return out, err + } + case "inline": + if out.JWKS.URL != "" || out.JWKS.DiscoveryBaseURL != "" || out.JWKS.CACertPEM != "" || len(out.JWKS.Keys) == 0 { + return out, fmt.Errorf("%w: conflicting or missing inline keys", ErrInvalid) + } + raw, err := json.Marshal(map[string]any{"keys": out.JWKS.Keys}) + if err != nil { + return out, fmt.Errorf("%w: invalid public keys", ErrInvalid) + } + keys, err := parseKeySet(raw) + if err != nil { + return out, fmt.Errorf("%w: invalid public keys", ErrInvalid) + } + // Keep only the signing keys and public fields the parser accepted, in + // a new slice: decoding into the configured one would rewrite the + // caller's entries in place. + var accepted []map[string]any + raw, err = json.Marshal(keys) + if err != nil || json.Unmarshal(raw, &accepted) != nil { + return out, fmt.Errorf("%w: invalid public keys", ErrInvalid) + } + out.JWKS.Keys = accepted + default: + return out, fmt.Errorf("%w: unsupported key source", ErrInvalid) + } + if out.IssuerURL == GitHubIssuer && (out.TokenValidation.ReplayProtection != ReplaySingleUse || out.JWKS.Type != "discovery" || out.JWKS.DiscoveryBaseURL != "" || out.JWKS.CACertPEM != "") { + return out, fmt.Errorf("%w: GitHub requires its canonical discovery and single-use assertions", ErrInvalid) + } + return out, nil +} + +// entraTenant returns the tenant an Entra v1 or v2 issuer URL names. +func entraTenant(issuerURL string) string { + groups := entraIssuer.FindStringSubmatch(issuerURL) + if groups == nil { + return "" + } + return cmp.Or(groups[1], groups[2]) +} + +// presetForIssuer returns the preset an issuer URL belongs to, if any. +func presetForIssuer(issuerURL string) string { + switch { + case issuerURL == GitHubIssuer: + return "github_actions" + case issuerURL == GoogleIssuer: + return "google_cloud" + case entraTenant(issuerURL) != "": + return "microsoft_entra" + } + return "" +} diff --git a/lib/oidcfederation/keyfetch.go b/lib/oidcfederation/keyfetch.go new file mode 100644 index 000000000..18e90622c --- /dev/null +++ b/lib/oidcfederation/keyfetch.go @@ -0,0 +1,240 @@ +package oidcfederation + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "mime" + "net" + "net/http" + "net/netip" + "strings" + "time" +) + +const maxKeyDocumentBytes = 256 << 10 + +// KeyProblem says why an issuer's keys cannot be used, for the operator who +// configured it. Retrying does not help. To the token endpoint it reads as +// ErrUnavailable, so a caller learns nothing about the issuer. +type KeyProblem struct{ Reason string } + +func (p *KeyProblem) Error() string { return "issuer keys cannot be used: " + p.Reason } + +func (p *KeyProblem) Is(target error) bool { return target == ErrUnavailable } + +type publicResolver interface { + LookupNetIP(context.Context, string, string) ([]netip.Addr, error) +} + +// nonPublicPrefixes are the ranges that are not globally reachable: private, +// loopback, link-local, multicast, and the other entries of the IANA +// special-purpose address registries. +var nonPublicPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), // "this network" + netip.MustParsePrefix("10.0.0.0/8"), // private + netip.MustParsePrefix("100.64.0.0/10"), // shared address space (CGNAT) + netip.MustParsePrefix("127.0.0.0/8"), // loopback + netip.MustParsePrefix("169.254.0.0/16"), // link-local + netip.MustParsePrefix("172.16.0.0/12"), // private + netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments + netip.MustParsePrefix("192.0.2.0/24"), // documentation + netip.MustParsePrefix("192.88.99.0/24"), // deprecated 6to4 relay anycast + netip.MustParsePrefix("192.168.0.0/16"), // private + netip.MustParsePrefix("198.18.0.0/15"), // benchmarking + netip.MustParsePrefix("198.51.100.0/24"), // documentation + netip.MustParsePrefix("203.0.113.0/24"), // documentation + netip.MustParsePrefix("224.0.0.0/4"), // multicast + netip.MustParsePrefix("240.0.0.0/4"), // reserved, including broadcast + netip.MustParsePrefix("2001::/23"), // IETF protocol assignments + netip.MustParsePrefix("2001:db8::/32"), // documentation + netip.MustParsePrefix("2002::/16"), // 6to4 + netip.MustParsePrefix("3fff::/20"), // documentation +} + +// globalUnicastIPv6 excludes the IPv6 loopback, ULA, link-local, multicast and +// IPv4-mapped ranges. +var globalUnicastIPv6 = netip.MustParsePrefix("2000::/3") + +func publicAddress(addr netip.Addr) bool { + addr = addr.Unmap() + if !addr.IsValid() || (addr.Is6() && !globalUnicastIPv6.Contains(addr)) { + return false + } + for _, nonPublic := range nonPublicPrefixes { + if nonPublic.Contains(addr) { + return false + } + } + return true +} + +func publicDial(resolver publicResolver, dial func(context.Context, string, string) (net.Conn, error)) func(context.Context, string, string) (net.Conn, error) { + return func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, ErrUnavailable + } + ips, err := resolver.LookupNetIP(ctx, "ip", host) + if err != nil || len(ips) == 0 || len(ips) > 32 { + return nil, ErrUnavailable + } + for _, ip := range ips { + if !publicAddress(ip) { + return nil, &KeyProblem{"the address is not on the public internet"} + } + } + for _, ip := range ips { + conn, err := dial(ctx, network, net.JoinHostPort(ip.Unmap().String(), port)) + if err == nil { + return conn, nil + } + } + return nil, ErrUnavailable + } +} + +func validateCA(caPEM string) error { + if caPEM == "" { + return nil + } + if len(caPEM) > 64<<10 { + return fmt.Errorf("%w: CA certificate is too large", ErrInvalid) + } + data := []byte(strings.TrimSpace(caPEM)) + count := 0 + for len(data) > 0 { + if !bytes.HasPrefix(data, []byte("-----BEGIN CERTIFICATE-----")) { + return fmt.Errorf("%w: only public CA certificates are accepted", ErrInvalid) + } + block, rest := pem.Decode(data) + if block == nil || block.Type != "CERTIFICATE" || len(block.Headers) != 0 { + return fmt.Errorf("%w: only public CA certificates are accepted", ErrInvalid) + } + certificate, err := x509.ParseCertificate(block.Bytes) + if err != nil || !certificate.IsCA || !certificate.BasicConstraintsValid { + return fmt.Errorf("%w: invalid CA certificate", ErrInvalid) + } + count++ + if count > 16 { + return fmt.Errorf("%w: too many CA certificates", ErrInvalid) + } + data = []byte(strings.TrimSpace(string(rest))) + } + if count == 0 { + return fmt.Errorf("%w: CA certificate is required", ErrInvalid) + } + return nil +} + +func keyHTTPClient(caPEM string) (*http.Client, error) { + if err := validateCA(caPEM); err != nil { + return nil, err + } + // A configured CA replaces the system roots, so only it can vouch for the key endpoint. + var roots *x509.CertPool + if caPEM != "" { + roots = x509.NewCertPool() + if !roots.AppendCertsFromPEM([]byte(caPEM)) { + return nil, fmt.Errorf("%w: invalid CA certificate", ErrInvalid) + } + } + dialer := &net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second} + transport := &http.Transport{ + Proxy: nil, + DialContext: publicDial(net.DefaultResolver, dialer.DialContext), + TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}, + TLSHandshakeTimeout: 3 * time.Second, + ResponseHeaderTimeout: 5 * time.Second, + DisableCompression: true, + MaxResponseHeaderBytes: 16 << 10, + } + return &http.Client{ + Transport: transport, + Timeout: 5 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + }, nil +} + +func fetchKeyDocument(ctx context.Context, client *http.Client, endpoint string) ([]byte, error) { + if _, err := httpsURL(endpoint); err != nil { + return nil, ErrUnavailable + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, ErrUnavailable + } + req.Header.Set("Accept", "application/json, application/jwk-set+json") + response, err := client.Do(req) + if err != nil { + var problem *KeyProblem + if errors.As(err, &problem) { + return nil, problem + } + return nil, ErrUnavailable + } + defer response.Body.Close() + if response.StatusCode >= 500 { + return nil, ErrUnavailable + } + if response.StatusCode != http.StatusOK { + return nil, &KeyProblem{fmt.Sprintf("the key endpoint returned HTTP %d", response.StatusCode)} + } + media, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")) + if err != nil || (media != "application/json" && !strings.HasSuffix(media, "+json")) { + return nil, &KeyProblem{"the key endpoint did not return JSON"} + } + if response.Header.Get("Content-Encoding") != "" { + return nil, &KeyProblem{"the key endpoint returned a compressed response"} + } + body, err := io.ReadAll(io.LimitReader(response.Body, maxKeyDocumentBytes+1)) + if err != nil { + return nil, ErrUnavailable + } + if len(body) > maxKeyDocumentBytes { + return nil, &KeyProblem{"the key document is larger than 256 KB"} + } + return body, nil +} + +func fetchIssuerKeys(ctx context.Context, issuer IssuerSpec) ([]byte, error) { + if issuer.JWKS.Type == "inline" { + return json.Marshal(map[string]any{"keys": issuer.JWKS.Keys}) + } + client, err := keyHTTPClient(issuer.JWKS.CACertPEM) + if err != nil { + return nil, err + } + defer client.CloseIdleConnections() + endpoint := issuer.JWKS.URL + if issuer.JWKS.Type == "discovery" { + base := issuer.IssuerURL + if issuer.JWKS.DiscoveryBaseURL != "" { + base = issuer.JWKS.DiscoveryBaseURL + } + raw, err := fetchKeyDocument(ctx, client, strings.TrimRight(base, "/")+"/.well-known/openid-configuration") + if err != nil { + return nil, err + } + metadata, err := decodeDiscovery(raw) + if err != nil { + return nil, &KeyProblem{"the discovery document is not valid"} + } + if metadata.Issuer != issuer.IssuerURL { + return nil, &KeyProblem{"the discovery document names a different issuer"} + } + endpoint = metadata.JWKSURI + } + if endpoint == "" { + return nil, &KeyProblem{"no key URL is configured or published"} + } + return fetchKeyDocument(ctx, client, endpoint) +} diff --git a/lib/oidcfederation/keyfetch_test.go b/lib/oidcfederation/keyfetch_test.go new file mode 100644 index 000000000..34d6b1535 --- /dev/null +++ b/lib/oidcfederation/keyfetch_test.go @@ -0,0 +1,138 @@ +package oidcfederation + +import ( + "context" + "crypto/x509" + "encoding/pem" + "errors" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type resolverFixture struct { + ips []netip.Addr + calls int +} + +func (r *resolverFixture) LookupNetIP(context.Context, string, string) ([]netip.Addr, error) { + r.calls++ + return r.ips, nil +} + +func TestPublicDialUsesTheValidatedAddresses(t *testing.T) { + resolver := &resolverFixture{ips: []netip.Addr{netip.MustParseAddr("8.8.8.8")}} + var target string + dial := publicDial(resolver, func(_ context.Context, network, address string) (net.Conn, error) { + target = address + left, right := net.Pipe() + right.Close() + return left, nil + }) + conn, err := dial(context.Background(), "tcp", "identity.example.test:443") + require.NoError(t, err) + conn.Close() + require.Equal(t, "8.8.8.8:443", target) + require.Equal(t, 1, resolver.calls, "the dialer must not resolve the hostname again") +} + +func TestPublicDialRejectsMixedAndPrivateAnswers(t *testing.T) { + for _, address := range []string{"127.0.0.1", "10.1.2.3", "169.254.169.254", "100.100.100.200", "0.0.0.1", "192.0.2.1", "224.0.0.1", "::1", "fe80::1", "fc00::1", "::ffff:127.0.0.1", "2001:db8::1"} { + t.Run(address, func(t *testing.T) { + resolver := &resolverFixture{ips: []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr(address)}} + called := false + dial := publicDial(resolver, func(context.Context, string, string) (net.Conn, error) { called = true; return nil, nil }) + _, err := dial(context.Background(), "tcp", "identity.example.test:443") + var problem *KeyProblem + require.ErrorAs(t, err, &problem, "a blocked address is a configuration problem, not an outage") + require.ErrorIs(t, err, ErrUnavailable, "the token endpoint still sees only unavailability") + require.False(t, called) + }) + } +} + +func TestKeyHTTPClientCannotUseAnAmbientProxyOrRedirect(t *testing.T) { + t.Setenv("HTTPS_PROXY", "http://127.0.0.1:9999") + client, err := keyHTTPClient("") + require.NoError(t, err) + defer client.CloseIdleConnections() + transport := client.Transport.(*http.Transport) + require.Nil(t, transport.Proxy) + require.True(t, transport.DisableCompression) + require.Equal(t, http.ErrUseLastResponse, client.CheckRedirect(&http.Request{}, nil)) +} + +func TestKeyDocumentStatusTypeEncodingAndSizeBounds(t *testing.T) { + reasons := map[string]string{"redirect": "HTTP 302", "missing": "HTTP 404", "html": "did not return JSON", "compressed": "compressed", "large": "larger than"} + for _, mode := range []string{"ok", "redirect", "missing", "outage", "html", "compressed", "large"} { + t.Run(mode, func(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Empty(t, r.Header.Get("Authorization")) + require.Empty(t, r.Header.Get("Cookie")) + w.Header().Set("Content-Type", "application/json") + switch mode { + case "redirect": + w.Header().Set("Location", "/other") + w.WriteHeader(http.StatusFound) + case "missing": + w.WriteHeader(http.StatusNotFound) + case "outage": + w.WriteHeader(http.StatusBadGateway) + case "html": + w.Header().Set("Content-Type", "text/html") + w.Write([]byte("not-json")) + case "compressed": + w.Header().Set("Content-Encoding", "gzip") + w.Write([]byte("not-gzip")) + case "large": + w.Write([]byte(strings.Repeat("x", maxKeyDocumentBytes+1))) + default: + w.Write([]byte(`{"keys":[]}`)) + } + })) + defer server.Close() + client := server.Client() + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + client.Transport.(*http.Transport).DisableCompression = true // as keyHTTPClient does + _, err := fetchKeyDocument(context.Background(), client, server.URL+"?public-policy=example") + var problem *KeyProblem + switch mode { + case "ok": + require.NoError(t, err) + case "outage": + require.ErrorIs(t, err, ErrUnavailable) + require.False(t, errors.As(err, &problem), "a server error may pass, so it is not a configuration problem") + default: + require.ErrorIs(t, err, ErrUnavailable) + require.ErrorAs(t, err, &problem) + require.Contains(t, problem.Reason, reasons[mode]) + } + }) + } +} + +func TestConfiguredCAReplacesSystemRoots(t *testing.T) { + server := httptest.NewTLSServer(http.NotFoundHandler()) + defer server.Close() + ca := server.Certificate() + client, err := keyHTTPClient(string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.Raw}))) + require.NoError(t, err) + only := x509.NewCertPool() + only.AddCert(ca) + require.True(t, client.Transport.(*http.Transport).TLSClientConfig.RootCAs.Equal(only)) + + client, err = keyHTTPClient("") + require.NoError(t, err) + require.Nil(t, client.Transport.(*http.Transport).TLSClientConfig.RootCAs, "without a configured CA the system roots apply") +} + +func TestOnlyPublicCACertificatesCanBeConfigured(t *testing.T) { + for _, data := range []string{" ", "not-a-certificate", string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("synthetic")}))} { + require.Error(t, validateCA(data)) + } +} diff --git a/lib/oidcfederation/match.go b/lib/oidcfederation/match.go new file mode 100644 index 000000000..f3f0b0bbb --- /dev/null +++ b/lib/oidcfederation/match.go @@ -0,0 +1,131 @@ +package oidcfederation + +import ( + "fmt" + "path" + "slices" + "strings" +) + +func normalizeMatch(m *Match, issuer IssuerSpec) error { + if len(m.Subject) > 1024 || len(m.SubjectPrefix) > 1024 || len(m.Claims) > 32 { + return ErrInvalid + } + for key, value := range m.Claims { + if _, err := pointerParts(key); err != nil || value == "" || len(value) > 1024 { + return fmt.Errorf("%w: invalid claim condition", ErrInvalid) + } + } + // Each matcher carries its provider's mandatory identity checks, so a rule + // cannot choose a weaker one than its issuer's. + if m.Type != issuer.PresetType { + return fmt.Errorf("%w: the matcher type must be the issuer's type, %s", ErrInvalid, issuer.PresetType) + } + if m.Type != "github_actions" && (m.RepositoryID != "" || m.RepositoryOwnerID != "" || m.Workflow != "" || m.WorkflowRef != "" || m.JobWorkflowRef != "" || m.Ref != "" || m.Environment != "" || len(m.EventNames) != 0) { + return fmt.Errorf("%w: GitHub conditions require the GitHub matcher", ErrInvalid) + } + if m.Type != "kubernetes" && (m.Namespace != "" || m.ServiceAccount != "") { + return fmt.Errorf("%w: Kubernetes conditions require the Kubernetes matcher", ErrInvalid) + } + switch m.Type { + case "github_actions": + if issuer.IssuerURL != GitHubIssuer || !numericID.MatchString(m.RepositoryID) || !numericID.MatchString(m.RepositoryOwnerID) || (m.Workflow == "" && m.WorkflowRef == "" && m.JobWorkflowRef == "") { + return fmt.Errorf("%w: repository/owner IDs and a workflow restriction are required", ErrInvalid) + } + if m.Workflow != "" && (!strings.HasPrefix(m.Workflow, ".github/workflows/") || path.Clean(m.Workflow) != m.Workflow || len(m.Workflow) > 512) { + return fmt.Errorf("%w: invalid workflow path", ErrInvalid) + } + if m.EventNames == nil { + m.EventNames = []string{"push", "workflow_dispatch"} + } + if len(m.EventNames) == 0 || len(m.EventNames) > 20 { + return fmt.Errorf("%w: event restrictions are required", ErrInvalid) + } + case "kubernetes": + if !kubeLabel.MatchString(m.Namespace) || len(m.Namespace) > 63 || len(m.ServiceAccount) > 253 || m.ServiceAccount == "" { + return fmt.Errorf("%w: Kubernetes namespace and service account are required", ErrInvalid) + } + for _, label := range strings.Split(m.ServiceAccount, ".") { + if !kubeLabel.MatchString(label) || len(label) > 63 { + return ErrInvalid + } + } + case "google_cloud": + if !numericID.MatchString(m.Subject) { + return fmt.Errorf("%w: numeric Google workload subject is required", ErrInvalid) + } + case "microsoft_entra": + if m.Subject == "" && m.Claims["/oid"] == "" && m.Claims["/appid"] == "" && m.Claims["/azp"] == "" { + return fmt.Errorf("%w: an Entra workload identity restriction is required", ErrInvalid) + } + if m.Claims == nil { + m.Claims = make(map[string]string) + } + if tenant := entraTenant(issuer.IssuerURL); tenant != "" { + if value, exists := m.Claims["/tid"]; exists && value != tenant { + return fmt.Errorf("%w: tenant claim disagrees with issuer", ErrInvalid) + } + m.Claims["/tid"] = tenant + } + // A client ID names the app a token was issued through, not who it acts + // for. Without a pinned object ID, accept only tokens Entra marks as the + // app's own. + if m.Subject == "" && m.Claims["/oid"] == "" { + if value, exists := m.Claims["/idtyp"]; exists && value != "app" { + return fmt.Errorf("%w: a rule matched by client ID accepts only app tokens", ErrInvalid) + } + m.Claims["/idtyp"] = "app" + } + case "aws", "custom_oidc": + if m.Subject == "" && m.SubjectPrefix == "" && len(m.Claims) == 0 { + return fmt.Errorf("%w: workload restrictions are required", ErrInvalid) + } + default: + return fmt.Errorf("%w: unsupported matcher", ErrInvalid) + } + return nil +} + +// Matches evaluates an already validated matcher against verified claims. +func (m Match) Matches(claims map[string]any) bool { + subject, ok := claims["sub"].(string) + if !ok || (m.Subject != "" && subject != m.Subject) || (m.SubjectPrefix != "" && !strings.HasPrefix(subject, m.SubjectPrefix)) { + return false + } + for key, expected := range m.Claims { + value, ok := ClaimString(claims, key) + if !ok || value != expected { + return false + } + } + switch m.Type { + case "github_actions": + if claims["repository_id"] != m.RepositoryID || claims["repository_owner_id"] != m.RepositoryOwnerID || !slices.Contains(m.EventNames, stringClaim(claims, "event_name")) { + return false + } + if (m.Ref != "" && stringClaim(claims, "ref") != m.Ref) || (m.Environment != "" && stringClaim(claims, "environment") != m.Environment) || (m.WorkflowRef != "" && stringClaim(claims, "workflow_ref") != m.WorkflowRef) || (m.JobWorkflowRef != "" && stringClaim(claims, "job_workflow_ref") != m.JobWorkflowRef) { + return false + } + if m.Workflow != "" { + repository, ref := stringClaim(claims, "repository"), stringClaim(claims, "ref") + return repository != "" && ref != "" && stringClaim(claims, "workflow_ref") == repository+"/"+m.Workflow+"@"+ref + } + return true + case "kubernetes": + return subject == "system:serviceaccount:"+m.Namespace+":"+m.ServiceAccount + case "microsoft_entra": + // A token issued to a signed-in user carries delegated scopes. Only an + // application's own token stands for a workload. + _, delegated := claims["scp"] + return !delegated + case "aws", "google_cloud", "custom_oidc": + return true + default: + return false + } +} + +func stringClaim(claims map[string]any, name string) string { + value, _ := claims[name].(string) + return value +} diff --git a/lib/oidcfederation/model.go b/lib/oidcfederation/model.go new file mode 100644 index 000000000..219416746 --- /dev/null +++ b/lib/oidcfederation/model.go @@ -0,0 +1,115 @@ +// Package oidcfederation validates externally issued OIDC identity tokens against +// operator-configured issuers and federation rules. +package oidcfederation + +import ( + "errors" + "fmt" + "net/url" + "regexp" + "strings" +) + +const ( + ReplaySingleUse = "single_use" + ReplayAllowReuse = "allow_reuse" + GitHubIssuer = "https://token.actions.githubusercontent.com" + GoogleIssuer = "https://accounts.google.com" + DefaultTokenTTL = 300 + MaxTokenTTL = 600 + MaxAssertionBytes = 16 << 10 + // Azure managed identity tokens live slightly over 24 hours (exp minus iat + // is about 86700 seconds), so the cap leaves room above a full day. + MaxIncomingLifetimeSeconds = 48 * 60 * 60 +) + +var ( + ErrInvalid = errors.New("invalid oidc federation configuration") + ErrAssertion = errors.New("invalid oidc assertion") + ErrUnavailable = errors.New("oidc issuer keys unavailable") + namePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,127}$`) + numericID = regexp.MustCompile(`^[0-9]{1,32}$`) + entraIssuer = regexp.MustCompile(`^https://(?:sts\.windows\.net/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/|login\.microsoftonline\.com/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/v2\.0)$`) + kubeLabel = regexp.MustCompile(`^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$`) +) + +// KeySource selects one configured public verification-key source. +type KeySource struct { + Type string `koanf:"type" json:"type"` + URL string `koanf:"url" json:"url,omitempty"` + DiscoveryBaseURL string `koanf:"discovery_base_url" json:"discovery_base_url,omitempty"` + CACertPEM string `koanf:"ca_cert_pem" json:"ca_cert_pem,omitempty"` + // Keys holds public JWKs for the inline source. + Keys []map[string]any `koanf:"keys" json:"keys,omitempty"` +} + +// TokenValidation bounds incoming assertion lifetime and sets the replay policy. +type TokenValidation struct { + MaxLifetimeSeconds *int `koanf:"max_lifetime_seconds" json:"max_lifetime_seconds,omitempty"` + ReplayProtection string `koanf:"replay_protection" json:"replay_protection,omitempty"` +} + +// IssuerSpec is the operator's explicit external trust configuration. +type IssuerSpec struct { + Name string `koanf:"name" json:"name"` + IssuerURL string `koanf:"issuer_url" json:"issuer_url"` + PresetType string `koanf:"preset_type" json:"preset_type,omitempty"` + JWKS KeySource `koanf:"jwks" json:"jwks"` + TokenValidation TokenValidation `koanf:"token_validation" json:"token_validation"` +} + +// Match contains conditions that must all hold on verified identity claims. +type Match struct { + Type string `koanf:"type" json:"type"` + Subject string `koanf:"subject" json:"subject,omitempty"` + SubjectPrefix string `koanf:"subject_prefix" json:"subject_prefix,omitempty"` + Claims map[string]string `koanf:"claims" json:"claims,omitempty"` + RepositoryID string `koanf:"repository_id" json:"repository_id,omitempty"` + RepositoryOwnerID string `koanf:"repository_owner_id" json:"repository_owner_id,omitempty"` + Workflow string `koanf:"workflow" json:"workflow,omitempty"` + WorkflowRef string `koanf:"workflow_ref" json:"workflow_ref,omitempty"` + JobWorkflowRef string `koanf:"job_workflow_ref" json:"job_workflow_ref,omitempty"` + Ref string `koanf:"ref" json:"ref,omitempty"` + Environment string `koanf:"environment" json:"environment,omitempty"` + EventNames []string `koanf:"event_names" json:"event_names,omitempty"` + Namespace string `koanf:"namespace" json:"namespace,omitempty"` + ServiceAccount string `koanf:"service_account" json:"service_account,omitempty"` +} + +// RuleAuthorization is what a matching workload receives: a scope list and a token lifetime. +type RuleAuthorization struct { + Permissions []string `koanf:"permissions" json:"permissions"` + MaxTokenTTLSeconds *int `koanf:"max_token_ttl_seconds" json:"max_token_ttl_seconds,omitempty"` +} + +// RuleSpec maps a matching external identity to a scoped Hypeman token. +type RuleSpec struct { + Name string `koanf:"name" json:"name"` + Issuer string `koanf:"issuer" json:"issuer"` + ExpectedAudience string `koanf:"expected_audience" json:"expected_audience"` + Match Match `koanf:"match" json:"match"` + Authorization RuleAuthorization `koanf:"authorization" json:"authorization"` +} + +// Config is the `oidc` block of the server configuration. +type Config struct { + Issuers []IssuerSpec `koanf:"issuers" json:"issuers"` + FederationRules []RuleSpec `koanf:"federation_rules" json:"federation_rules"` +} + +// validateName enforces alphanumeric-and-hyphen names. +func validateName(name string) error { + if !namePattern.MatchString(name) { + return fmt.Errorf("%w: name must contain only alphanumeric characters and hyphens", ErrInvalid) + } + return nil +} + +// httpsURL validates endpoint syntax; the HTTP transport also validates its dial address. +func httpsURL(raw string) (*url.URL, error) { + parsed, err := url.Parse(raw) + if err != nil || len(raw) > 2048 || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" || strings.Contains(parsed.Hostname(), "%") { + return nil, fmt.Errorf("%w: an HTTPS URL without credentials or fragment is required", ErrInvalid) + } + return parsed, nil +} diff --git a/lib/oidcfederation/model_test.go b/lib/oidcfederation/model_test.go new file mode 100644 index 000000000..5aed87943 --- /dev/null +++ b/lib/oidcfederation/model_test.go @@ -0,0 +1,428 @@ +package oidcfederation + +import ( + "encoding/json" + "maps" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func githubConfig() Config { + return Config{ + Issuers: []IssuerSpec{{Name: "github-actions", PresetType: "github_actions"}}, + FederationRules: []RuleSpec{{ + Name: "ci", + Issuer: "github-actions", + ExpectedAudience: "https://auth.example.test", + Match: Match{Type: "github_actions", RepositoryID: "12", RepositoryOwnerID: "34", Workflow: ".github/workflows/test.yml", Ref: "refs/heads/main"}, + Authorization: RuleAuthorization{Permissions: []string{"instance:write", "instance:read"}}, + }}, + } +} + +func githubRule(t *testing.T) Rule { + t.Helper() + registry, err := Compile(githubConfig()) + require.NoError(t, err) + rule, ok := registry.Rule("ci") + require.True(t, ok) + return rule +} + +func githubClaims() map[string]any { + return map[string]any{ + "sub": "repo:renamed/tests:environment:staging", + "repository": "renamed/tests", + "repository_id": "12", + "repository_owner_id": "34", + "workflow_ref": "renamed/tests/.github/workflows/test.yml@refs/heads/main", + "ref": "refs/heads/main", + "event_name": "push", + "environment": "staging", + } +} + +// ruleFor compiles one rule against one issuer, as a configuration would. +func ruleFor(issuer IssuerSpec, match Match) (Rule, error) { + registry, err := Compile(Config{ + Issuers: []IssuerSpec{issuer}, + FederationRules: []RuleSpec{{ + Name: "rule", Issuer: issuer.Name, ExpectedAudience: "https://auth.example.test", Match: match, + Authorization: RuleAuthorization{Permissions: []string{"instance:read"}}, + }}, + }) + if err != nil { + return Rule{}, err + } + rule, _ := registry.Rule("rule") + return rule, nil +} + +func TestIssuerPresetNormalization(t *testing.T) { + const tenant = "11111111-2222-3333-4444-555555555555" + for _, test := range []struct { + name, given, issuer, preset, want string + }{ + {"github", "", GitHubIssuer, "github_actions", "github_actions"}, + {"github by url", GitHubIssuer, GitHubIssuer, "", "github_actions"}, + {"google", "", GoogleIssuer, "google_cloud", "google_cloud"}, + {"aws", "https://sts.example.test/account", "https://sts.example.test/account", "aws", "aws"}, + {"entra-v1", "https://sts.windows.net/" + tenant + "/", "https://sts.windows.net/" + tenant + "/", "microsoft_entra", "microsoft_entra"}, + {"entra-v2 by url", "https://login.microsoftonline.com/" + tenant + "/v2.0", "https://login.microsoftonline.com/" + tenant + "/v2.0", "", "microsoft_entra"}, + {"kubernetes", "https://cluster.example.test", "https://cluster.example.test", "kubernetes", "kubernetes"}, + {"custom by default", "https://identity.example.test/path", "https://identity.example.test/path", "", "custom_oidc"}, + } { + t.Run(test.name, func(t *testing.T) { + out, err := normalizeIssuer(IssuerSpec{Name: "issuer", IssuerURL: test.given, PresetType: test.preset}) + require.NoError(t, err) + require.Equal(t, test.issuer, out.IssuerURL) + require.Equal(t, test.want, out.PresetType) + replay := ReplaySingleUse + if test.name == "google" || test.name == "kubernetes" { + replay = ReplayAllowReuse + } + require.Equal(t, replay, out.TokenValidation.ReplayProtection) + if test.name == "entra-v1" { + require.Equal(t, "https://login.microsoftonline.com/"+tenant, out.JWKS.DiscoveryBaseURL) + require.Equal(t, 7500, *out.TokenValidation.MaxLifetimeSeconds) + } + }) + } +} + +func TestIssuerRejectsConflictingSettings(t *testing.T) { + for _, input := range []IssuerSpec{ + {Name: "bad_name", IssuerURL: "https://identity.example.test"}, + {Name: "issuer", IssuerURL: "https://wrong.example.test", PresetType: "github_actions"}, + {Name: "issuer", IssuerURL: "https://identity.example.test", PresetType: "microsoft_entra"}, + {Name: "issuer", IssuerURL: "https://identity.example.test", PresetType: "unknown"}, + {Name: "issuer", PresetType: "aws"}, + {Name: "issuer", IssuerURL: GitHubIssuer, PresetType: "custom_oidc"}, + {Name: "issuer", IssuerURL: GoogleIssuer, PresetType: "kubernetes", TokenValidation: TokenValidation{ReplayProtection: ReplayAllowReuse}}, + {Name: "issuer", PresetType: "google_cloud", TokenValidation: TokenValidation{ReplayProtection: ReplaySingleUse}}, + {Name: "issuer", PresetType: "github_actions", TokenValidation: TokenValidation{ReplayProtection: ReplayAllowReuse}}, + {Name: "issuer", IssuerURL: "https://sts.example.test/account", PresetType: "aws", TokenValidation: TokenValidation{ReplayProtection: ReplayAllowReuse}}, + {Name: "issuer", IssuerURL: GitHubIssuer, JWKS: KeySource{Type: "explicit_url", URL: "https://keys.example.test"}}, + {Name: "issuer", IssuerURL: "https://identity.example.test", JWKS: KeySource{Type: "inline"}}, + {Name: "issuer", IssuerURL: "https://identity.example.test", JWKS: KeySource{Type: "inline", Keys: []map[string]any{{"kty": "oct", "k": "c2VjcmV0"}}}}, + {Name: "issuer", IssuerURL: "https://identity.example.test", JWKS: KeySource{Type: "discovery", URL: "https://keys.example.test"}}, + {Name: "issuer", IssuerURL: "https://user:password@identity.example.test"}, + {Name: "issuer", IssuerURL: "http://identity.example.test"}, + } { + _, err := normalizeIssuer(input) + require.ErrorIs(t, err, ErrInvalid, "%+v", input) + } +} + +func TestIssuerIncomingLifetimeBounds(t *testing.T) { + for limit, ok := range map[int]bool{0: false, 1: true, 86400: true, 86700: true, MaxIncomingLifetimeSeconds: true, MaxIncomingLifetimeSeconds + 1: false} { + _, err := normalizeIssuer(IssuerSpec{Name: "issuer", IssuerURL: "https://identity.example.test", TokenValidation: TokenValidation{MaxLifetimeSeconds: &limit}}) + if ok { + require.NoError(t, err, limit) + } else { + require.ErrorIs(t, err, ErrInvalid, limit) + } + } +} + +// A pod reads the same projected token until it is rotated, so reuse is the +// Kubernetes default. A workload that fetches a fresh token each time can still +// ask for single use. +func TestKubernetesAllowsReuseUnlessToldOtherwise(t *testing.T) { + spec := IssuerSpec{Name: "cluster", IssuerURL: "https://cluster.example.test", PresetType: "kubernetes"} + out, err := normalizeIssuer(spec) + require.NoError(t, err) + require.Equal(t, ReplayAllowReuse, out.TokenValidation.ReplayProtection) + spec.TokenValidation.ReplayProtection = ReplaySingleUse + out, err = normalizeIssuer(spec) + require.NoError(t, err) + require.Equal(t, ReplaySingleUse, out.TokenValidation.ReplayProtection) +} + +// A generic matcher on a shared provider would accept every customer of that provider. +func TestRuleMatcherMustBeTheIssuersType(t *testing.T) { + const tenant = "11111111-2222-3333-4444-555555555555" + for _, test := range []struct { + issuer IssuerSpec + match Match + ok bool + }{ + {IssuerSpec{Name: "google", PresetType: "google_cloud"}, Match{Type: "google_cloud", Subject: "107517467455664443765"}, true}, + {IssuerSpec{Name: "google", PresetType: "google_cloud"}, Match{Type: "custom_oidc", Claims: map[string]string{"/iss": GoogleIssuer}}, false}, + {IssuerSpec{Name: "google", PresetType: "google_cloud"}, Match{Type: "aws", SubjectPrefix: "1"}, false}, + {IssuerSpec{Name: "entra", IssuerURL: "https://login.microsoftonline.com/" + tenant + "/v2.0"}, Match{Type: "microsoft_entra", Subject: "workload"}, true}, + {IssuerSpec{Name: "entra", IssuerURL: "https://login.microsoftonline.com/" + tenant + "/v2.0"}, Match{Type: "custom_oidc", Subject: "workload"}, false}, + {IssuerSpec{Name: "cluster", IssuerURL: "https://cluster.example.test", PresetType: "kubernetes"}, Match{Type: "custom_oidc", SubjectPrefix: "system:serviceaccount:"}, false}, + {IssuerSpec{Name: "cluster", IssuerURL: "https://cluster.example.test", PresetType: "kubernetes"}, Match{Type: "kubernetes", Namespace: "ci", ServiceAccount: "runner"}, true}, + {IssuerSpec{Name: "custom", IssuerURL: "https://identity.example.test"}, Match{Type: "google_cloud", Subject: "107517467455664443765"}, false}, + {IssuerSpec{Name: "custom", IssuerURL: "https://identity.example.test"}, Match{Type: "custom_oidc", Subject: "build"}, true}, + {IssuerSpec{Name: "custom", IssuerURL: "https://identity.example.test"}, Match{Type: "custom_oidc"}, false}, + } { + _, err := ruleFor(test.issuer, test.match) + if test.ok { + require.NoError(t, err, "%s issuer with a %s matcher", test.issuer.Name, test.match.Type) + } else { + require.ErrorIs(t, err, ErrInvalid, "%s issuer with a %s matcher", test.issuer.Name, test.match.Type) + } + } +} + +// A client ID names the app a token was issued through. A user signed in through +// that app gets a token with the same client ID, so it must not stand for the workload. +func TestEntraRulesAcceptOnlyTheApplicationsOwnTokens(t *testing.T) { + const tenant = "11111111-2222-3333-4444-555555555555" + issuer := IssuerSpec{Name: "entra", IssuerURL: "https://login.microsoftonline.com/" + tenant + "/v2.0"} + app := map[string]any{"sub": "sp-object", "oid": "sp-object", "tid": tenant, "azp": "client-a", "idtyp": "app"} + user := map[string]any{"sub": "pairwise-user", "oid": "user-object", "tid": tenant, "azp": "client-a", "scp": "access_as_user"} + + byClient, err := ruleFor(issuer, Match{Type: "microsoft_entra", Claims: map[string]string{"/azp": "client-a"}}) + require.NoError(t, err) + require.Equal(t, "app", byClient.Match.Claims["/idtyp"], "a rule matched by client ID requires the app marker") + require.Equal(t, tenant, byClient.Match.Claims["/tid"]) + require.True(t, byClient.Match.Matches(app)) + require.False(t, byClient.Match.Matches(user)) + unmarked := maps.Clone(app) + delete(unmarked, "idtyp") + require.False(t, byClient.Match.Matches(unmarked), "without the marker a client ID does not identify the workload") + _, err = ruleFor(issuer, Match{Type: "microsoft_entra", Claims: map[string]string{"/azp": "client-a", "/idtyp": "user"}}) + require.ErrorIs(t, err, ErrInvalid) + + byObject, err := ruleFor(issuer, Match{Type: "microsoft_entra", Claims: map[string]string{"/oid": "sp-object"}}) + require.NoError(t, err) + require.NotContains(t, byObject.Match.Claims, "/idtyp") + require.True(t, byObject.Match.Matches(unmarked)) + delegated := maps.Clone(unmarked) + delegated["scp"] = "access_as_user" + require.False(t, byObject.Match.Matches(delegated), "a delegated token never stands for a workload") +} + +func TestGitHubConditionsAreANDedAndNamesDoNotRebind(t *testing.T) { + rule := githubRule(t) + claims := githubClaims() + require.True(t, rule.Match.Matches(claims), "immutable IDs permit environment-based subjects and survive a rename") + for name, value := range map[string]any{ + "repository_id": "99", + "repository_owner_id": "99", + "workflow_ref": "another/tests/.github/workflows/test.yml@refs/heads/main", + "ref": "refs/heads/other", + "event_name": "pull_request_target", + } { + changed := maps.Clone(claims) + changed[name] = value + require.False(t, rule.Match.Matches(changed), name) + } + delete(claims, "event_name") + require.False(t, rule.Match.Matches(claims)) + rule.Match.JobWorkflowRef = "central/ci/.github/workflows/run.yml@refs/heads/main" + claims = githubClaims() + require.False(t, rule.Match.Matches(claims)) + claims["job_workflow_ref"] = rule.Match.JobWorkflowRef + require.True(t, rule.Match.Matches(claims)) +} + +// A repository name is pinned like any other claim. There is no separate field +// for it that a rule could set and the matcher ignore. +func TestGitHubRepositoryNameIsPinnedByClaim(t *testing.T) { + cfg := githubConfig() + cfg.FederationRules[0].Match.Claims = map[string]string{"/repository": "renamed/tests"} + registry, err := Compile(cfg) + require.NoError(t, err) + rule, _ := registry.Rule("ci") + claims := githubClaims() + require.True(t, rule.Match.Matches(claims)) + claims["repository"] = "other/tests" + require.False(t, rule.Match.Matches(claims)) +} + +func TestGitHubRestrictionsCannotBeWeakened(t *testing.T) { + for name, alter := range map[string]func(*Match){ + "generic matcher": func(m *Match) { m.Type = "custom_oidc" }, + "no repository id": func(m *Match) { m.RepositoryID = "" }, + "no owner id": func(m *Match) { m.RepositoryOwnerID = "" }, + "no workflow": func(m *Match) { m.Workflow = "" }, + "no ref": func(m *Match) { m.Ref = "" }, + "empty event list": func(m *Match) { m.EventNames = []string{} }, + "workflow traversal": func(m *Match) { m.Workflow = ".github/workflows/../../other.yml" }, + } { + cfg := githubConfig() + alter(&cfg.FederationRules[0].Match) + _, err := Compile(cfg) + require.ErrorIs(t, err, ErrInvalid, name) + } +} + +func TestRulePermissionsAreExplicit(t *testing.T) { + rule := githubRule(t) + require.Equal(t, []string{"instance:read", "instance:write"}, rule.Authorization.Permissions) + require.Equal(t, DefaultTokenTTL, *rule.Authorization.MaxTokenTTLSeconds) + require.Equal(t, []string{"push", "workflow_dispatch"}, rule.Match.EventNames) + for name, permissions := range map[string][]string{ + "none": nil, + "wildcard": {"*"}, + "unknown": {"instance:admin"}, + "duplicate": {"instance:read", "instance:read"}, + } { + cfg := githubConfig() + cfg.FederationRules[0].Authorization.Permissions = permissions + _, err := Compile(cfg) + require.ErrorIs(t, err, ErrInvalid, name) + } + for _, ttl := range []int{0, MaxTokenTTL + 1} { + cfg := githubConfig() + cfg.FederationRules[0].Authorization.MaxTokenTTLSeconds = &ttl + _, err := Compile(cfg) + require.ErrorIs(t, err, ErrInvalid, ttl) + } +} + +func TestCompileResolvesIssuersAndRejectsAmbiguity(t *testing.T) { + empty, err := Compile(Config{}) + require.NoError(t, err) + require.False(t, empty.Enabled()) + _, ok := empty.Rule("ci") + require.False(t, ok) + var none *Registry + require.False(t, none.Enabled()) + + registry, err := Compile(githubConfig()) + require.NoError(t, err) + require.True(t, registry.Enabled()) + + for name, alter := range map[string]func(*Config){ + "unknown issuer": func(c *Config) { c.FederationRules[0].Issuer = "other" }, + "duplicate rule": func(c *Config) { c.FederationRules = append(c.FederationRules, c.FederationRules[0]) }, + "duplicate issuer": func(c *Config) { c.Issuers = append(c.Issuers, c.Issuers[0]) }, + "duplicate issuer url": func(c *Config) { c.Issuers = append(c.Issuers, IssuerSpec{Name: "second", IssuerURL: GitHubIssuer}) }, + "no audience": func(c *Config) { c.FederationRules[0].ExpectedAudience = "" }, + "bad rule name": func(c *Config) { c.FederationRules[0].Name = "ci:main" }, + } { + cfg := githubConfig() + alter(&cfg) + _, err := Compile(cfg) + require.ErrorIs(t, err, ErrInvalid, name) + } +} + +// A token issued under one configuration must not survive a change to its rule or issuer. +func TestRevisionFollowsRuleAndIssuer(t *testing.T) { + base := githubRule(t).Revision + require.Len(t, base, 16) + require.Equal(t, base, githubRule(t).Revision, "the same configuration keeps its revision") + for name, alter := range map[string]func(*Config){ + "permissions": func(c *Config) { c.FederationRules[0].Authorization.Permissions = []string{"instance:read"} }, + "match": func(c *Config) { c.FederationRules[0].Match.Ref = "refs/heads/release" }, + "audience": func(c *Config) { c.FederationRules[0].ExpectedAudience = "https://other.example.test" }, + "issuer": func(c *Config) { + limit := 600 + c.Issuers[0].TokenValidation.MaxLifetimeSeconds = &limit + }, + } { + cfg := githubConfig() + alter(&cfg) + registry, err := Compile(cfg) + require.NoError(t, err, name) + rule, _ := registry.Rule("ci") + require.NotEqual(t, base, rule.Revision, name) + } +} + +func TestCompileDoesNotAliasItsInput(t *testing.T) { + cfg := githubConfig() + cfg.FederationRules[0].Match.Claims = map[string]string{"/actor": "octocat"} + registry, err := Compile(cfg) + require.NoError(t, err) + cfg.FederationRules[0].Match.Claims["/actor"] = "other" + cfg.FederationRules[0].Authorization.Permissions[0] = "image:delete" + rule, _ := registry.Rule("ci") + require.Equal(t, "octocat", rule.Match.Claims["/actor"]) + require.Equal(t, []string{"instance:read", "instance:write"}, rule.Authorization.Permissions) +} + +// The server compiles its configuration once to validate it and again to use +// it, so normalizing inline keys must leave the configured entries alone. +func TestCompileLeavesInlineKeysAsConfigured(t *testing.T) { + f := newAssertionFixture(t) + var set map[string][]map[string]any + require.NoError(t, json.Unmarshal(f.keys, &set)) + signing := set["keys"][0] + encryption := maps.Clone(signing) + encryption["use"], encryption["alg"] = "enc", "RSA-OAEP" + cfg := Config{ + Issuers: []IssuerSpec{{Name: "idp", IssuerURL: "https://idp.example.test", JWKS: KeySource{Type: "inline", Keys: []map[string]any{encryption, signing}}}}, + FederationRules: []RuleSpec{{ + Name: "ci", Issuer: "idp", ExpectedAudience: "https://auth.example.test", + Match: Match{Type: "custom_oidc", Subject: "build"}, + Authorization: RuleAuthorization{Permissions: []string{"image:read"}}, + }}, + } + var revisions []string + for range 2 { + registry, err := Compile(cfg) + require.NoError(t, err) + rule, _ := registry.Rule("ci") + require.Len(t, rule.IssuerSpec.JWKS.Keys, 1, "only the signing key is kept") + require.Equal(t, "sig", rule.IssuerSpec.JWKS.Keys[0]["use"]) + revisions = append(revisions, rule.Revision) + } + require.Equal(t, revisions[0], revisions[1]) + require.Len(t, cfg.Issuers[0].JWKS.Keys, 2) + require.Equal(t, "enc", cfg.Issuers[0].JWKS.Keys[0]["use"]) + require.Equal(t, "sig", cfg.Issuers[0].JWKS.Keys[1]["use"]) +} + +func TestJSONPointerStringClaims(t *testing.T) { + claims := map[string]any{"literal/key": map[string]any{"a~b": "proj_a"}, "kubernetes.io": map[string]any{"namespace": "ns"}, "values": []any{"first"}, "number": 12} + for pointer, expected := range map[string]string{"/literal~1key/a~0b": "proj_a", "/kubernetes.io/namespace": "ns", "/values/0": "first"} { + value, ok := ClaimString(claims, pointer) + require.True(t, ok) + require.Equal(t, expected, value) + } + for _, pointer := range []string{"", "kubernetes.io.namespace", "/bad~2escape", "/values/00", "/values/-", "/values/1", "/missing", "/number"} { + _, ok := ClaimString(claims, pointer) + require.False(t, ok, pointer) + } +} + +func TestExpiryClipsToTheAssertion(t *testing.T) { + now := time.Unix(1000, 0) + for _, test := range []struct{ assertion, expected int64 }{ + {2000, 1300}, + {1010, 1010}, + } { + expiry, err := AccessExpiry(now, time.Unix(test.assertion, 0), DefaultTokenTTL) + require.NoError(t, err) + require.Equal(t, test.expected, expiry.Unix()) + } + _, err := AccessExpiry(now, now, DefaultTokenTTL) + require.ErrorIs(t, err, ErrAssertion) + _, err = AccessExpiry(now, now.Add(time.Hour), MaxTokenTTL+1) + require.ErrorIs(t, err, ErrInvalid) +} + +// Google sends email_verified as a boolean and project numbers as numbers. A +// condition written as text has to match them, or the rule can never succeed. +func TestClaimConditionsMatchBooleansAndNumbersByTheirText(t *testing.T) { + claims := map[string]any{ + "sub": "107517467455664443765", "email_verified": true, "disabled": false, + "google": map[string]any{"compute_engine": map[string]any{"project_number": json.Number("739419398126")}}, + "ratio": 1.5, "groups": []any{"a"}, "nested": map[string]any{"k": "v"}, + } + for pointer, expected := range map[string]string{ + "/email_verified": "true", "/disabled": "false", + "/google/compute_engine/project_number": "739419398126", "/ratio": "1.5", + } { + value, ok := ClaimString(claims, pointer) + require.True(t, ok, pointer) + require.Equal(t, expected, value, pointer) + } + for _, pointer := range []string{"/groups", "/nested"} { + _, ok := ClaimString(claims, pointer) + require.False(t, ok, "%s is not a scalar", pointer) + } + match := Match{Type: "google_cloud", Subject: "107517467455664443765", Claims: map[string]string{"/email_verified": "true"}} + require.True(t, match.Matches(claims)) + match.Claims["/email_verified"] = "false" + require.False(t, match.Matches(claims)) +} diff --git a/lib/oidcfederation/registry.go b/lib/oidcfederation/registry.go new file mode 100644 index 000000000..c21a69053 --- /dev/null +++ b/lib/oidcfederation/registry.go @@ -0,0 +1,80 @@ +package oidcfederation + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" +) + +// Rule is a validated federation rule together with the issuer it trusts. +type Rule struct { + RuleSpec + IssuerSpec IssuerSpec + // Revision changes whenever the rule or its issuer changes, so tokens + // issued under an earlier configuration can be told apart. + Revision string +} + +// Registry holds the validated issuers and rules of one configuration. +type Registry struct { + rules map[string]Rule +} + +// Compile validates the configuration and resolves each rule's issuer. +func Compile(cfg Config) (*Registry, error) { + issuers := make(map[string]IssuerSpec, len(cfg.Issuers)) + urls := make(map[string]string, len(cfg.Issuers)) + for i, spec := range cfg.Issuers { + issuer, err := normalizeIssuer(spec) + if err != nil { + return nil, fmt.Errorf("oidc.issuers[%d] (%q): %w", i, spec.Name, err) + } + if _, exists := issuers[issuer.Name]; exists { + return nil, fmt.Errorf("oidc.issuers[%d] (%q): %w: duplicate issuer name", i, issuer.Name, ErrInvalid) + } + if other, exists := urls[issuer.IssuerURL]; exists { + return nil, fmt.Errorf("oidc.issuers[%d] (%q): %w: issuer URL is already configured as %q", i, issuer.Name, ErrInvalid, other) + } + issuers[issuer.Name] = issuer + urls[issuer.IssuerURL] = issuer.Name + } + rules := make(map[string]Rule, len(cfg.FederationRules)) + for i, spec := range cfg.FederationRules { + issuer, exists := issuers[spec.Issuer] + if !exists { + return nil, fmt.Errorf("oidc.federation_rules[%d] (%q): %w: unknown issuer %q", i, spec.Name, ErrInvalid, spec.Issuer) + } + rule, err := normalizeRule(spec, issuer) + if err != nil { + return nil, fmt.Errorf("oidc.federation_rules[%d] (%q): %w", i, spec.Name, err) + } + if _, exists := rules[rule.Name]; exists { + return nil, fmt.Errorf("oidc.federation_rules[%d] (%q): %w: duplicate rule name", i, rule.Name, ErrInvalid) + } + raw, err := json.Marshal(struct { + Rule RuleSpec + Issuer IssuerSpec + }{rule, issuer}) + if err != nil { + return nil, fmt.Errorf("oidc.federation_rules[%d] (%q): %w", i, spec.Name, ErrInvalid) + } + digest := sha256.Sum256(raw) + rules[rule.Name] = Rule{RuleSpec: rule, IssuerSpec: issuer, Revision: hex.EncodeToString(digest[:8])} + } + return &Registry{rules: rules}, nil +} + +// Rule returns the named federation rule. +func (r *Registry) Rule(name string) (Rule, bool) { + if r == nil { + return Rule{}, false + } + rule, ok := r.rules[name] + return rule, ok +} + +// Enabled reports whether any federation rule is configured. +func (r *Registry) Enabled() bool { + return r != nil && len(r.rules) > 0 +} diff --git a/lib/oidcfederation/rule.go b/lib/oidcfederation/rule.go new file mode 100644 index 000000000..b27cfc643 --- /dev/null +++ b/lib/oidcfederation/rule.go @@ -0,0 +1,79 @@ +package oidcfederation + +import ( + "fmt" + "slices" + "time" + + "github.com/kernel/hypeman/lib/scopes" +) + +// normalizeRule validates a rule against its already normalized issuer. +func normalizeRule(out RuleSpec, issuer IssuerSpec) (RuleSpec, error) { + if out.Match.EventNames != nil && len(out.Match.EventNames) == 0 { + return out, fmt.Errorf("%w: event restrictions cannot be empty", ErrInvalid) + } + if err := validateName(out.Name); err != nil { + return out, err + } + if out.ExpectedAudience == "" || len(out.ExpectedAudience) > 2048 { + return out, fmt.Errorf("%w: expected_audience is required", ErrInvalid) + } + if out.Authorization.MaxTokenTTLSeconds == nil { + n := DefaultTokenTTL + out.Authorization.MaxTokenTTLSeconds = &n + } + if n := *out.Authorization.MaxTokenTTLSeconds; n < 1 || n > MaxTokenTTL { + return out, fmt.Errorf("%w: token lifetime must be between 1 and %d seconds", ErrInvalid, MaxTokenTTL) + } + // A federated token never falls back to the full access a token without a + // permissions claim has, so the list is explicit and has no wildcard. + if len(out.Authorization.Permissions) == 0 { + return out, fmt.Errorf("%w: authorization.permissions is required", ErrInvalid) + } + out.Authorization.Permissions = slices.Clone(out.Authorization.Permissions) + slices.Sort(out.Authorization.Permissions) + if len(slices.Compact(slices.Clone(out.Authorization.Permissions))) != len(out.Authorization.Permissions) { + return out, fmt.Errorf("%w: duplicate permission", ErrInvalid) + } + for _, permission := range out.Authorization.Permissions { + if scope := scopes.Scope(permission); scope == scopes.All || !scope.Valid() { + return out, fmt.Errorf("%w: unsupported permission %q", ErrInvalid, permission) + } + } + out.Match.Claims = cloneClaims(out.Match.Claims) + out.Match.EventNames = slices.Clone(out.Match.EventNames) + if err := normalizeMatch(&out.Match, issuer); err != nil { + return out, err + } + if out.Match.Type == "github_actions" && out.Match.Ref == "" && out.Match.Environment == "" { + return out, fmt.Errorf("%w: GitHub requires a branch or environment restriction", ErrInvalid) + } + return out, nil +} + +func cloneClaims(claims map[string]string) map[string]string { + if claims == nil { + return nil + } + out := make(map[string]string, len(claims)) + for key, value := range claims { + out[key] = value + } + return out +} + +// AccessExpiry clips an issued token's lifetime to the assertion's own expiry. +func AccessExpiry(now, assertionExpiry time.Time, ttlSeconds int) (time.Time, error) { + if ttlSeconds < 1 || ttlSeconds > MaxTokenTTL { + return time.Time{}, ErrInvalid + } + expiry := now.Add(time.Duration(ttlSeconds) * time.Second).Truncate(time.Second) + if !assertionExpiry.IsZero() && assertionExpiry.Before(expiry) { + expiry = assertionExpiry.Truncate(time.Second) + } + if assertionExpiry.IsZero() || !expiry.After(now) { + return time.Time{}, ErrAssertion + } + return expiry, nil +} diff --git a/lib/oidcfederation/verifier.go b/lib/oidcfederation/verifier.go new file mode 100644 index 000000000..94fb51099 --- /dev/null +++ b/lib/oidcfederation/verifier.go @@ -0,0 +1,425 @@ +package oidcfederation + +import ( + "bytes" + "cmp" + "context" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" + "slices" + "strings" + "sync" + "time" + + jose "github.com/go-jose/go-jose/v4" + "github.com/golang-jwt/jwt/v5" +) + +const ( + keyCacheTTL = 5 * time.Minute + keyFailureTTL = 10 * time.Second + keyRefreshPeriod = time.Minute + maxKeyCaches = 128 + maxKeyLoads = 64 + // clockLeeway is how far the issuer's clock may differ from this host's. + clockLeeway = 30 * time.Second +) + +// Assertion contains verified identity claims, never permissions inferred from those claims. +type Assertion struct { + Subject string + JTI string + IssuedAt time.Time + ExpiresAt time.Time + Claims map[string]any + SingleUse bool +} + +type cachedKeys struct { + keys []jose.JSONWebKey + expiresAt time.Time + failureUntil time.Time + refreshAfter time.Time + // failure is what the last load reported, returned again until failureUntil. + failure error +} + +type keyLoad struct { + done chan struct{} + keys []jose.JSONWebKey + err error +} + +// Verifier bounds issuer key fetching and validates the supported OIDC assertion profile. +type Verifier struct { + mu sync.Mutex + cache map[string]cachedKeys + loading map[string]*keyLoad + fetch func(context.Context, IssuerSpec) ([]byte, error) + now func() time.Time +} + +// NewVerifier uses HTTPS public-address-only key retrieval and an in-memory bounded cache. +func NewVerifier() *Verifier { + return &Verifier{cache: make(map[string]cachedKeys), loading: make(map[string]*keyLoad), fetch: fetchIssuerKeys, now: time.Now} +} + +func keyCacheKey(issuer IssuerSpec) string { + raw, _ := json.Marshal(struct { + Name string + Issuer string + Source KeySource + }{issuer.Name, issuer.IssuerURL, issuer.JWKS}) + digest := sha256.Sum256(raw) + return hex.EncodeToString(digest[:]) +} + +func (v *Verifier) putLocked(key string, entry cachedKeys) { + if _, exists := v.cache[key]; !exists && len(v.cache) >= maxKeyCaches { + for oldKey := range v.cache { + delete(v.cache, oldKey) + break + } + } + v.cache[key] = entry +} + +func (v *Verifier) keySet(ctx context.Context, issuer IssuerSpec, force bool) ([]jose.JSONWebKey, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + key := keyCacheKey(issuer) + now := v.now() + v.mu.Lock() + entry := v.cache[key] + if now.Before(entry.expiresAt) && !force { + v.mu.Unlock() + return entry.keys, nil + } + load, loading := v.loading[key] + if !loading { + if now.Before(entry.failureUntil) { + v.mu.Unlock() + return nil, cmp.Or(entry.failure, ErrUnavailable) + } + if force && now.Before(entry.refreshAfter) { + v.mu.Unlock() + return entry.keys, nil + } + if len(v.loading) >= maxKeyLoads { + v.mu.Unlock() + return nil, ErrUnavailable + } + if force { + entry.refreshAfter = now.Add(keyRefreshPeriod) + v.putLocked(key, entry) + } + load = &keyLoad{done: make(chan struct{})} + v.loading[key] = load + go v.loadKeys(key, issuer, load, now) + } + v.mu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-load.done: + return load.keys, load.err + } +} + +func (v *Verifier) loadKeys(key string, issuer IssuerSpec, load *keyLoad, startedAt time.Time) { + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + raw, err := v.fetch(ctx, issuer) + var keys []jose.JSONWebKey + if err == nil { + if keys, err = parseKeySet(raw); err != nil { + err = &KeyProblem{"the key set is not valid or holds an unsupported key"} + } + } + v.mu.Lock() + defer v.mu.Unlock() + entry := v.cache[key] + if err != nil { + entry.failureUntil = v.now().Add(keyFailureTTL) + // A refresh that failed did not use up the refresh allowance. + entry.refreshAfter = time.Time{} + // Only a problem the operator can fix keeps its reason. + var problem *KeyProblem + if load.err = ErrUnavailable; errors.As(err, &problem) { + load.err = problem + } + entry.failure = load.err + } else { + entry.keys = keys + entry.expiresAt = startedAt.Add(keyCacheTTL) + entry.failureUntil, entry.failure = time.Time{}, nil + load.keys = keys + } + v.putLocked(key, entry) + delete(v.loading, key) + close(load.done) +} + +// Verify accepts only a signed, unexpired assertion for the configured audience and issuer. +// The issuer must come from a compiled Registry, which normalizes it. +func (v *Verifier) Verify(ctx context.Context, spec IssuerSpec, audience, raw string) (Assertion, error) { + if spec.Name == "" || spec.TokenValidation.MaxLifetimeSeconds == nil || audience == "" || len(audience) > 2048 || len(raw) > MaxAssertionBytes { + return Assertion{}, ErrAssertion + } + parts := strings.Split(raw, ".") + if len(parts) != 3 { + return Assertion{}, ErrAssertion + } + header, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil || !uniqueJSONObject(header) { + return Assertion{}, ErrAssertion + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil || !uniqueJSONObject(payload) { + return Assertion{}, ErrAssertion + } + var protected struct{ Algorithm, KeyID, Type string } + var fields map[string]json.RawMessage + if json.Unmarshal(header, &fields) != nil { + return Assertion{}, ErrAssertion + } + if _, critical := fields["crit"]; critical { + return Assertion{}, ErrAssertion + } + for name, destination := range map[string]*string{"alg": &protected.Algorithm, "kid": &protected.KeyID, "typ": &protected.Type} { + if value, exists := fields[name]; exists { + value = bytes.TrimSpace(value) + if len(value) == 0 || value[0] != '"' || json.Unmarshal(value, destination) != nil { + return Assertion{}, ErrAssertion + } + } + } + if len(protected.KeyID) > 256 || (protected.Type != "" && !strings.EqualFold(protected.Type, "JWT") && !strings.EqualFold(protected.Type, "application/jwt")) { + return Assertion{}, ErrAssertion + } + var unverified map[string]json.RawMessage + if json.Unmarshal(payload, &unverified) != nil { + return Assertion{}, ErrAssertion + } + var claimedIssuer string + if json.Unmarshal(unverified["iss"], &claimedIssuer) != nil || claimedIssuer != spec.IssuerURL { + return Assertion{}, ErrAssertion + } + algorithms := []string{"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA"} + if spec.IssuerURL == GitHubIssuer || spec.IssuerURL == GoogleIssuer || spec.PresetType == "microsoft_entra" { + algorithms = []string{"RS256"} + } + if !slices.Contains(algorithms, protected.Algorithm) { + return Assertion{}, ErrAssertion + } + keys, err := v.keySet(ctx, spec, false) + if err != nil { + return Assertion{}, err + } + key, ok := matchingKey(keys, protected.KeyID, protected.Algorithm) + if !ok { + keys, err = v.keySet(ctx, spec, true) + if err != nil { + return Assertion{}, err + } + key, ok = matchingKey(keys, protected.KeyID, protected.Algorithm) + if !ok { + return Assertion{}, ErrAssertion + } + } + claims := jwt.MapClaims{} + token, err := jwt.ParseWithClaims(raw, claims, func(*jwt.Token) (any, error) { return key.Key, nil }, jwt.WithValidMethods(algorithms), jwt.WithIssuer(spec.IssuerURL), jwt.WithAudience(audience), jwt.WithExpirationRequired(), jwt.WithIssuedAt(), jwt.WithLeeway(clockLeeway), jwt.WithTimeFunc(v.now), jwt.WithJSONNumber()) + if err != nil || token == nil || !token.Valid { + return Assertion{}, ErrAssertion + } + subject, subjectOK := claims["sub"].(string) + expires, expErr := claims.GetExpirationTime() + issued, iatErr := claims.GetIssuedAt() + audiences, audErr := claims.GetAudience() + if !subjectOK || subject == "" || len(subject) > 1024 || expErr != nil || iatErr != nil || audErr != nil || expires == nil || issued == nil || len(audiences) != 1 || audiences[0] != audience || !expires.After(v.now()) || !expires.After(issued.Time) || expires.Sub(issued.Time) > time.Duration(*spec.TokenValidation.MaxLifetimeSeconds)*time.Second { + return Assertion{}, ErrAssertion + } + // Entra names its token ID uti. + idClaim := "jti" + if spec.PresetType == "microsoft_entra" { + idClaim = "uti" + } + jti, jtiOK := claims[idClaim].(string) + _, hasJTI := claims[idClaim] + singleUse := spec.TokenValidation.ReplayProtection == ReplaySingleUse + if ((singleUse || hasJTI) && (!jtiOK || jti == "")) || len(jti) > 512 { + return Assertion{}, ErrAssertion + } + return Assertion{Subject: subject, JTI: jti, IssuedAt: issued.Time, ExpiresAt: expires.Time, Claims: map[string]any(claims), SingleUse: singleUse}, nil +} + +func matchingKey(keys []jose.JSONWebKey, kid, algorithm string) (jose.JSONWebKey, bool) { + var matched *jose.JSONWebKey + for i := range keys { + key := &keys[i] + if (kid != "" && key.KeyID != kid) || (kid == "" && len(keys) != 1) || (key.Algorithm != "" && key.Algorithm != algorithm) { + continue + } + if matched != nil { + return jose.JSONWebKey{}, false + } + matched = key + } + if matched == nil { + return jose.JSONWebKey{}, false + } + return *matched, true +} + +func parseKeySet(raw []byte) ([]jose.JSONWebKey, error) { + if len(raw) > maxKeyDocumentBytes || !uniqueJSONObject(raw) { + return nil, ErrInvalid + } + var root map[string]json.RawMessage + if json.Unmarshal(raw, &root) != nil { + return nil, ErrInvalid + } + var entries []map[string]json.RawMessage + if json.Unmarshal(root["keys"], &entries) != nil || len(entries) == 0 || len(entries) > 16 { + return nil, ErrInvalid + } + keys := make([]jose.JSONWebKey, 0, len(entries)) + seen := make(map[string]bool, len(entries)) + for _, entry := range entries { + // An issuer may publish its encryption keys in the same set. Entries + // marked for another purpose are skipped; every other entry must be a + // usable public signing key. + if use, exists := entry["use"]; exists { + var purpose string + if json.Unmarshal(use, &purpose) != nil { + return nil, ErrInvalid + } + if purpose != "sig" { + continue + } + } + if operations, exists := entry["key_ops"]; exists { + var ops []string + if json.Unmarshal(operations, &ops) != nil { + return nil, ErrInvalid + } + if !slices.Contains(ops, "verify") { + continue + } + if len(ops) != 1 { + return nil, ErrInvalid + } + } + for _, private := range []string{"d", "p", "q", "dp", "dq", "qi", "oth", "k"} { + if _, exists := entry[private]; exists { + return nil, ErrInvalid + } + } + filtered := make(map[string]json.RawMessage) + for _, field := range []string{"kty", "kid", "alg", "use", "n", "e", "crv", "x", "y"} { + if value, exists := entry[field]; exists { + filtered[field] = value + } + } + encoded, err := json.Marshal(filtered) + if err != nil { + return nil, ErrInvalid + } + var key jose.JSONWebKey + if json.Unmarshal(encoded, &key) != nil || !key.Valid() || !key.IsPublic() || (key.Use != "" && key.Use != "sig") || len(key.KeyID) > 256 || seen[key.KeyID] { + return nil, ErrInvalid + } + switch public := key.Key.(type) { + case *rsa.PublicKey: + if public.N.Sign() <= 0 || public.N.BitLen() < 2048 || public.N.BitLen() > 8192 || public.N.Bit(0) == 0 || public.E < 3 || public.E%2 == 0 { + return nil, ErrInvalid + } + case *ecdsa.PublicKey: + if !public.Curve.IsOnCurve(public.X, public.Y) { + return nil, ErrInvalid + } + case ed25519.PublicKey: + if len(public) != ed25519.PublicKeySize { + return nil, ErrInvalid + } + default: + return nil, ErrInvalid + } + seen[key.KeyID] = true + keys = append(keys, key) + } + if len(keys) == 0 { + return nil, ErrInvalid + } + return keys, nil +} + +func decodeDiscovery(raw []byte) (struct{ Issuer, JWKSURI string }, error) { + var result struct{ Issuer, JWKSURI string } + if !uniqueJSONObject(raw) { + return result, ErrInvalid + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || json.Unmarshal(fields["issuer"], &result.Issuer) != nil || json.Unmarshal(fields["jwks_uri"], &result.JWKSURI) != nil || result.Issuer == "" || result.JWKSURI == "" { + return result, ErrInvalid + } + return result, nil +} + +func uniqueJSONObject(raw []byte) bool { + return uniqueJSON(raw, true) +} + +func uniqueJSON(raw []byte, objectOnly bool) bool { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + budget := 16384 + var value func(int, json.Token) error + value = func(depth int, token json.Token) error { + budget-- + if depth > 16 || budget < 0 { + return ErrInvalid + } + delimiter, container := token.(json.Delim) + if !container { + return nil + } + if delimiter != '{' && delimiter != '[' { + return ErrInvalid + } + seen := make(map[string]bool) + for decoder.More() { + if delimiter == '{' { + key, err := decoder.Token() + name, ok := key.(string) + if err != nil || !ok || seen[name] { + return ErrInvalid + } + seen[name] = true + } + next, err := decoder.Token() + if err != nil || value(depth+1, next) != nil { + return ErrInvalid + } + } + close, err := decoder.Token() + if err != nil || (delimiter == '{' && close != json.Delim('}')) || (delimiter == '[' && close != json.Delim(']')) { + return ErrInvalid + } + return nil + } + first, err := decoder.Token() + if err != nil || (objectOnly && first != json.Delim('{')) || value(0, first) != nil { + return false + } + _, err = decoder.Token() + return err == io.EOF +} diff --git a/lib/oidcfederation/verifier_test.go b/lib/oidcfederation/verifier_test.go new file mode 100644 index 000000000..54bd0dbed --- /dev/null +++ b/lib/oidcfederation/verifier_test.go @@ -0,0 +1,448 @@ +package oidcfederation + +import ( + "context" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "maps" + "sync" + "sync/atomic" + "testing" + "time" + + jose "github.com/go-jose/go-jose/v4" + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/require" +) + +type assertionFixture struct { + key *rsa.PrivateKey + now time.Time + keys []byte +} + +func newAssertionFixture(t *testing.T) assertionFixture { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + raw, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "key-a", Algorithm: "RS256", Use: "sig"}}}) + require.NoError(t, err) + return assertionFixture{key, time.Unix(1700000000, 0), raw} +} + +func (f assertionFixture) claims() jwt.MapClaims { + var nonce [16]byte + _, _ = rand.Read(nonce[:]) + return jwt.MapClaims{"iss": GitHubIssuer, "sub": "repo:example/tests:environment:staging", "aud": "https://auth.example.test", "iat": f.now.Unix(), "exp": f.now.Add(5 * time.Minute).Unix(), "jti": base64.RawURLEncoding.EncodeToString(nonce[:])} +} + +func (f assertionFixture) sign(t *testing.T, claims jwt.MapClaims, header map[string]any) string { + t.Helper() + token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) + token.Header["kid"] = "key-a" + for key, value := range header { + token.Header[key] = value + } + raw, err := token.SignedString(f.key) + require.NoError(t, err) + return raw +} + +func (f assertionFixture) trust(t *testing.T) IssuerSpec { + t.Helper() + return githubRule(t).IssuerSpec +} + +func TestVerifySignedAssertionAndCacheKeys(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + var calls atomic.Int32 + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { calls.Add(1); return f.keys, nil } + for range 2 { + claims := f.claims() + result, err := v.Verify(context.Background(), f.trust(t), "https://auth.example.test", f.sign(t, claims, nil)) + require.NoError(t, err) + require.Equal(t, claims["sub"], result.Subject) + require.Equal(t, claims["jti"], result.JTI) + require.Equal(t, f.now, result.IssuedAt) + require.Equal(t, f.now.Add(5*time.Minute), result.ExpiresAt) + require.True(t, result.SingleUse) + } + require.EqualValues(t, 1, calls.Load()) +} + +func TestVerifyRejectsInvalidClaimsAndProfiles(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return f.keys, nil } + for name, alter := range map[string]func(jwt.MapClaims){ + "issuer": func(c jwt.MapClaims) { c["iss"] = "https://other.example.test" }, + "audience": func(c jwt.MapClaims) { c["aud"] = "https://other.example.test" }, + "multiple-aud": func(c jwt.MapClaims) { c["aud"] = []string{"https://auth.example.test", "other"} }, + "no-subject": func(c jwt.MapClaims) { delete(c, "sub") }, + "no-issued-at": func(c jwt.MapClaims) { delete(c, "iat") }, + "no-expiry": func(c jwt.MapClaims) { delete(c, "exp") }, + "expired": func(c jwt.MapClaims) { c["exp"] = f.now.Add(-time.Second).Unix() }, + "future-iat": func(c jwt.MapClaims) { c["iat"] = f.now.Add(time.Minute).Unix() }, + "future-nbf": func(c jwt.MapClaims) { c["nbf"] = f.now.Add(time.Minute).Unix() }, + "long-lifetime": func(c jwt.MapClaims) { c["exp"] = f.now.Add(2 * time.Hour).Unix() }, + "no-jti": func(c jwt.MapClaims) { delete(c, "jti") }, + "nonstring-jti": func(c jwt.MapClaims) { c["jti"] = 12 }, + } { + t.Run(name, func(t *testing.T) { + claims := f.claims() + alter(claims) + _, err := v.Verify(context.Background(), f.trust(t), "https://auth.example.test", f.sign(t, claims, nil)) + require.ErrorIs(t, err, ErrAssertion) + }) + } + for _, header := range []map[string]any{{"typ": "oauth-wag+jwt"}, {"typ": "oauth-id-jag+jwt"}, {"typ": "at+jwt"}, {"kid": 1}, {"crit": []string{"unknown"}}} { + _, err := v.Verify(context.Background(), f.trust(t), "https://auth.example.test", f.sign(t, f.claims(), header)) + require.ErrorIs(t, err, ErrAssertion) + } +} + +// Google identity tokens carry no token ID, and Entra names its token ID uti. +func TestVerifyUsesEachProvidersTokenID(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return f.keys, nil } + verify := func(spec IssuerSpec, alter func(jwt.MapClaims)) (Assertion, error) { + issuer, err := normalizeIssuer(spec) + require.NoError(t, err) + claims := f.claims() + claims["iss"] = issuer.IssuerURL + delete(claims, "jti") + alter(claims) + return v.Verify(context.Background(), issuer, "https://auth.example.test", f.sign(t, claims, nil)) + } + + google := IssuerSpec{Name: "google", PresetType: "google_cloud"} + result, err := verify(google, func(jwt.MapClaims) {}) + require.NoError(t, err) + require.Empty(t, result.JTI) + require.False(t, result.SingleUse) + + entra := IssuerSpec{Name: "entra", IssuerURL: "https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/v2.0"} + result, err = verify(entra, func(c jwt.MapClaims) { c["uti"] = "token-a" }) + require.NoError(t, err) + require.Equal(t, "token-a", result.JTI) + require.True(t, result.SingleUse) + _, err = verify(entra, func(jwt.MapClaims) {}) + require.ErrorIs(t, err, ErrAssertion, "a single-use Entra token must carry uti") + _, err = verify(entra, func(c jwt.MapClaims) { c["jti"] = "token-a" }) + require.ErrorIs(t, err, ErrAssertion, "jti does not stand in for uti") + + entra.TokenValidation.ReplayProtection = ReplayAllowReuse + result, err = verify(entra, func(jwt.MapClaims) {}) + require.NoError(t, err) + require.False(t, result.SingleUse) + + // Azure managed identity tokens live slightly over 24 hours. + limit := 90000 + entra.TokenValidation.MaxLifetimeSeconds = &limit + _, err = verify(entra, func(c jwt.MapClaims) { c["exp"] = f.now.Add(86700 * time.Second).Unix() }) + require.NoError(t, err) + _, err = verify(entra, func(c jwt.MapClaims) { c["exp"] = f.now.Add(time.Duration(limit+1) * time.Second).Unix() }) + require.ErrorIs(t, err, ErrAssertion) +} + +func TestMalformedAssertionsDoNotFetchKeys(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + var calls atomic.Int32 + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { calls.Add(1); return f.keys, nil } + badClaims := f.claims() + badClaims["iss"] = "https://unknown.example.test" + for _, raw := range []string{"not-a-jwt", f.sign(t, badClaims, nil), f.sign(t, f.claims(), map[string]any{"typ": "oauth-wag+jwt"})} { + _, err := v.Verify(context.Background(), f.trust(t), "https://auth.example.test", raw) + require.ErrorIs(t, err, ErrAssertion) + } + duplicateHeader := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","alg":"RS256","kid":"key-a"}`)) + _, err := v.Verify(context.Background(), f.trust(t), "https://auth.example.test", duplicateHeader+".e30.signature") + require.ErrorIs(t, err, ErrAssertion) + require.Zero(t, calls.Load()) +} + +func TestKeyRotationUnknownKidIsRateLimited(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + now := f.now + v.now = func() time.Time { return now } + var calls int + keys := f.keys + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { calls++; return keys, nil } + trust := f.trust(t) + _, err := v.Verify(context.Background(), trust, "https://auth.example.test", f.sign(t, f.claims(), nil)) + require.NoError(t, err) + for range 3 { + _, err = v.Verify(context.Background(), trust, "https://auth.example.test", f.sign(t, f.claims(), map[string]any{"kid": "unknown"})) + require.ErrorIs(t, err, ErrAssertion) + } + require.Equal(t, 2, calls) + keys, err = json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &f.key.PublicKey, KeyID: "new", Algorithm: "RS256"}}}) + require.NoError(t, err) + now = now.Add(keyRefreshPeriod + time.Second) + claims := f.claims() + claims["iat"], claims["exp"] = now.Unix(), now.Add(5*time.Minute).Unix() + _, err = v.Verify(context.Background(), trust, "https://auth.example.test", f.sign(t, claims, map[string]any{"kid": "new"})) + require.NoError(t, err) + require.Equal(t, 3, calls) +} + +type observedWaitContext struct { + context.Context + once sync.Once + waiting chan struct{} +} + +func (c *observedWaitContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.waiting) }) + return c.Context.Done() +} + +func TestFailedKeyRefreshRetriesAfterTheFailureCooldown(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + now := f.now + v.now = func() time.Time { return now } + keys, failing := f.keys, false + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + if failing { + return nil, ErrUnavailable + } + return keys, nil + } + trust := f.trust(t) + verify := func(kid string) error { + claims := f.claims() + claims["iat"], claims["exp"] = now.Unix(), now.Add(5*time.Minute).Unix() + _, err := v.Verify(context.Background(), trust, "https://auth.example.test", f.sign(t, claims, map[string]any{"kid": kid})) + return err + } + require.NoError(t, verify("key-a")) + // The issuer rotates while its key endpoint is briefly down. + failing = true + require.ErrorIs(t, verify("new"), ErrUnavailable) + rotated, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &f.key.PublicKey, KeyID: "new", Algorithm: "RS256"}}}) + require.NoError(t, err) + keys, failing = rotated, false + now = now.Add(keyFailureTTL + time.Second) + require.NoError(t, verify("new")) +} + +func TestConcurrentRotationVerificationsJoinTheRefresh(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + newKeys, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &f.key.PublicKey, KeyID: "new", Algorithm: "RS256"}}}) + require.NoError(t, err) + started, release := make(chan struct{}), make(chan struct{}) + var unblock sync.Once + defer unblock.Do(func() { close(release) }) + var calls atomic.Int32 + v.fetch = func(ctx context.Context, _ IssuerSpec) ([]byte, error) { + if calls.Add(1) == 1 { + return f.keys, nil + } + close(started) + select { + case <-release: + return newKeys, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + trust := f.trust(t) + _, err = v.Verify(context.Background(), trust, "https://auth.example.test", f.sign(t, f.claims(), nil)) + require.NoError(t, err) + first, second := make(chan error, 1), make(chan error, 1) + firstToken := f.sign(t, f.claims(), map[string]any{"kid": "new"}) + secondToken := f.sign(t, f.claims(), map[string]any{"kid": "new"}) + go func() { + _, err := v.Verify(context.Background(), trust, "https://auth.example.test", firstToken) + first <- err + }() + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("rotation refresh did not start") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + observer := &observedWaitContext{Context: ctx, waiting: make(chan struct{})} + go func() { _, err := v.Verify(observer, trust, "https://auth.example.test", secondToken); second <- err }() + select { + case <-observer.waiting: + case err := <-second: + t.Fatalf("second verification returned before joining the refresh: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("second verification did not join the refresh") + } + unblock.Do(func() { close(release) }) + require.NoError(t, <-first) + require.NoError(t, <-second) + require.EqualValues(t, 2, calls.Load(), "one initial load and one shared rotation refresh") +} + +func TestConcurrentKeyFetchAndCanceledWaiter(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + started, release := make(chan struct{}), make(chan struct{}) + var calls atomic.Int32 + v.fetch = func(ctx context.Context, _ IssuerSpec) ([]byte, error) { + if calls.Add(1) == 1 { + close(started) + } + select { + case <-release: + return f.keys, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + trust := f.trust(t) + ctx, cancel := context.WithCancel(context.Background()) + first := make(chan error, 1) + go func() { _, err := v.keySet(ctx, trust, false); first <- err }() + <-started + cancel() + require.ErrorIs(t, <-first, context.Canceled) + var wg sync.WaitGroup + results := make(chan error, 10) + for range 10 { + wg.Go(func() { _, err := v.keySet(context.Background(), trust, false); results <- err }) + } + close(release) + wg.Wait() + close(results) + for err := range results { + require.NoError(t, err) + } + require.EqualValues(t, 1, calls.Load()) +} + +func TestKeyCacheDoesNotServeExpiredKeysOnOutage(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + now := f.now + v.now = func() time.Time { return now } + outage := false + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + if outage { + return nil, errors.New("synthetic outage") + } + return f.keys, nil + } + _, err := v.keySet(context.Background(), f.trust(t), false) + require.NoError(t, err) + outage, now = true, now.Add(keyCacheTTL+time.Second) + _, err = v.keySet(context.Background(), f.trust(t), false) + require.ErrorIs(t, err, ErrUnavailable) +} + +func TestOnlyPublicAsymmetricKeysAreAccepted(t *testing.T) { + f := newAssertionFixture(t) + for _, key := range []jose.JSONWebKey{{Key: f.key}, {Key: []byte("symmetric-secret")}} { + raw, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{key}}) + require.NoError(t, err) + _, err = parseKeySet(raw) + require.Error(t, err) + } + curve, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + raw, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &curve.PublicKey, KeyID: "ec", Algorithm: "ES256"}}}) + require.NoError(t, err) + keys, err := parseKeySet(raw) + require.NoError(t, err) + require.Len(t, keys, 1) + edPublic, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + raw, err = json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: edPublic, KeyID: "ed", Algorithm: "EdDSA"}}}) + require.NoError(t, err) + _, err = parseKeySet(raw) + require.NoError(t, err) + weakKey := `{"keys":[{"kty":"OKP","crv":"Ed25519","kid":"weak","x":"` + base64.RawURLEncoding.EncodeToString(make([]byte, ed25519.PublicKeySize)) + `"}]}` + _, err = parseKeySet([]byte(weakKey)) + require.Error(t, err) + var set map[string][]map[string]any + require.NoError(t, json.Unmarshal(f.keys, &set)) + key := maps.Clone(set["keys"][0]) + key["p"] = "private-prime" + raw, err = json.Marshal(map[string]any{"keys": []map[string]any{key}}) + require.NoError(t, err) + _, err = parseKeySet(raw) + require.Error(t, err) +} + +// OIDC discovery lets an issuer publish signing and encryption keys in one set. +func TestKeySetSkipsKeysForOtherPurposes(t *testing.T) { + f := newAssertionFixture(t) + var set map[string][]map[string]any + require.NoError(t, json.Unmarshal(f.keys, &set)) + signing := set["keys"][0] + encryption := maps.Clone(signing) + encryption["use"], encryption["alg"] = "enc", "RSA-OAEP" + wrapping := maps.Clone(signing) + delete(wrapping, "use") + wrapping["kid"], wrapping["key_ops"] = "wrap", []string{"wrapKey"} + parse := func(entries ...map[string]any) ([]jose.JSONWebKey, error) { + raw, err := json.Marshal(map[string]any{"keys": entries}) + require.NoError(t, err) + return parseKeySet(raw) + } + + keys, err := parse(encryption, signing, wrapping) + require.NoError(t, err) + require.Len(t, keys, 1) + require.Equal(t, "key-a", keys[0].KeyID) + require.Equal(t, "sig", keys[0].Use) + + _, err = parse(encryption, wrapping) + require.Error(t, err, "a set without a signing key is unusable") + both := maps.Clone(signing) + delete(both, "use") + both["key_ops"] = []string{"sign", "verify"} + _, err = parse(both) + require.Error(t, err, "a signing candidate is still validated strictly") + _, err = parse(map[string]any{"kty": "RSA", "use": 1}) + require.Error(t, err) +} + +func TestDuplicateJSONAndDiscoveryIdentity(t *testing.T) { + for _, raw := range []string{`{"iss":"a","\u0069ss":"b"}`, `{"x":{"n":1,"n":2}}`, `{} {}`, `[]`} { + require.False(t, uniqueJSONObject([]byte(raw)), raw) + } + require.True(t, uniqueJSONObject([]byte(`{"a":[1,{"b":true}],"c":null}`))) + _, err := decodeDiscovery([]byte(`{"Issuer":"wrong","jwks_uri":"https://keys.example.test"}`)) + require.Error(t, err) + metadata, err := decodeDiscovery([]byte(`{"issuer":"https://identity.example.test","jwks_uri":"https://keys.example.test?p=public-policy"}`)) + require.NoError(t, err) + require.Equal(t, "https://identity.example.test", metadata.Issuer) +} + +func TestKeyCacheIsBounded(t *testing.T) { + f := newAssertionFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return f.keys, nil } + for i := range maxKeyCaches + 8 { + trust := f.trust(t) + trust.Name = fmt.Sprintf("issuer-%d", i) + _, err := v.keySet(context.Background(), trust, false) + require.NoError(t, err) + } + require.LessOrEqual(t, len(v.cache), maxKeyCaches) +}