diff --git a/cmd/api/config/config.go b/cmd/api/config/config.go index 95fa7a676..2051e28b0 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/accesstoken" "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"` + // OAuth names the authorization servers whose access tokens are accepted + // as API tokens, and the audiences those tokens must be issued for. + OAuth accesstoken.Config `koanf:"oauth"` + Network NetworkConfig `koanf:"network"` Caddy CaddyConfig `koanf:"caddy"` ACME ACMEConfig `koanf:"acme"` @@ -580,6 +586,17 @@ func Load(configPath string) (*Config, error) { if err := k.Unmarshal("", &cfg); err != nil { return nil, fmt.Errorf("failed to unmarshal config: %w", err) } + // Decode the oauth block again, rejecting unknown keys: a misspelled key + // would otherwise be dropped and leave the block meaning something else. + cfg.OAuth = accesstoken.Config{} + if err := k.UnmarshalWithConf("oauth", &cfg.OAuth, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{ + TagName: "koanf", + WeaklyTypedInput: true, + ErrorUnused: true, + Result: &cfg.OAuth, + }}); err != nil { + return nil, fmt.Errorf("invalid oauth config: %w", err) + } cfg.expandPathFields() return &cfg, nil @@ -615,6 +632,9 @@ func (c *Config) Validate() error { return fmt.Errorf("jwt_verification_secrets entry %d must not be empty", i) } } + if _, err := accesstoken.New(c.OAuth, nil, nil); 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/oauth_test.go b/cmd/api/config/oauth_test.go new file mode 100644 index 000000000..40b21f2ef --- /dev/null +++ b/cmd/api/config/oauth_test.go @@ -0,0 +1,62 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/kernel/hypeman/lib/accesstoken" + "github.com/stretchr/testify/require" +) + +func loadYAML(t *testing.T, body string) (*Config, error) { + t.Helper() + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) + return Load(path) +} + +func TestLoadOAuth(t *testing.T) { + cfg, err := loadYAML(t, ` +oauth: + audiences: [prod, https://host-1.example.test] + authorization_servers: + - issuer: https://auth.example.test + - issuer: https://other.example.test + jwks: + type: explicit_url + url: https://other.example.test/keys.json +`) + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + require.Equal(t, []string{"prod", "https://host-1.example.test"}, cfg.OAuth.Audiences) + require.Len(t, cfg.OAuth.AuthorizationServers, 2) + require.Equal(t, "https://auth.example.test", cfg.OAuth.AuthorizationServers[0].Issuer) + require.Equal(t, "https://other.example.test/keys.json", cfg.OAuth.AuthorizationServers[1].JWKS.URL) + + // Without the block nothing is configured. + cfg, err = loadYAML(t, "port: 4973\n") + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + require.Empty(t, cfg.OAuth.AuthorizationServers) +} + +func TestOAuthRejectsUnknownKeysAndInvalidSettings(t *testing.T) { + for _, body := range []string{ + "oauth:\n audience: [prod]\n", + "oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n jwks_url: https://auth.example.test/keys\n", + "oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n jwks:\n kind: discovery\n", + } { + _, err := loadYAML(t, body) + require.ErrorContains(t, err, "invalid oauth config", body) + } + for _, body := range []string{ + "oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n", + "oauth:\n audiences: [prod]\n", + "oauth:\n audiences: [prod]\n authorization_servers:\n - issuer: http://auth.example.test\n", + } { + cfg, err := loadYAML(t, body) + require.NoError(t, err, body) + require.ErrorIs(t, cfg.Validate(), accesstoken.ErrInvalidConfig, body) + } +} diff --git a/cmd/api/main.go b/cmd/api/main.go index 636c28d88..98fd952cd 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -24,6 +24,7 @@ import ( "github.com/kernel/hypeman" "github.com/kernel/hypeman/cmd/api/api" "github.com/kernel/hypeman/cmd/api/config" + "github.com/kernel/hypeman/lib/accesstoken" "github.com/kernel/hypeman/lib/devices" "github.com/kernel/hypeman/lib/guest" "github.com/kernel/hypeman/lib/hypervisor/qemu" @@ -286,6 +287,14 @@ func run() error { if err != nil { return fmt.Errorf("initialize JWT verifier: %w", err) } + accessTokens, err := accesstoken.New(app.Config.OAuth, accesstoken.NewFileKeyStore(paths.New(app.Config.DataDir).OAuthKeysDir(), logger), logger) + if err != nil { + return fmt.Errorf("initialize OAuth access tokens: %w", err) + } + if accessTokens.Enabled() { + logger.Info("accepting access tokens from authorization servers", "authorization_servers", len(app.Config.OAuth.AuthorizationServers), "audiences", app.Config.OAuth.Audiences) + jwtVerifier = jwtVerifier.WithAccessTokens(accessTokens) + } revokedTokens, err := tokenrevocation.New(app.Config.RevokedTokenHashes) if err != nil { return fmt.Errorf("invalid revoked_token_hashes: %w", err) diff --git a/config.example.yaml b/config.example.yaml index 870d530a2..e07b0e5cc 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -25,6 +25,15 @@ jwt_secret: "" # revoked_token_hashes: # - 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef +# Optional - also accept access tokens issued by an OAuth authorization server. +# The server only verifies them, with the authorization server's public keys. +# See docs/oauth-access-tokens.md. +# oauth: +# audiences: +# - https://hypeman.example.com +# authorization_servers: +# - issuer: https://auth.example.com + # Data directory (default: /var/lib/hypeman) data_dir: /var/lib/hypeman diff --git a/docs/oauth-access-tokens.md b/docs/oauth-access-tokens.md new file mode 100644 index 000000000..bf7b90f96 --- /dev/null +++ b/docs/oauth-access-tokens.md @@ -0,0 +1,94 @@ +# OAuth access tokens + +Hypeman can accept access tokens issued by an OAuth authorization server, beside the tokens signed +with `jwt_secret`. For these tokens the server is a resource server: it holds the authorization +server's public keys, so it can verify the tokens and cannot issue them. + +## Configure + +```yaml +oauth: + audiences: + - https://hypeman.example.com + authorization_servers: + - issuer: https://auth.example.com +``` + +| Key | Meaning | +|---|---| +| `audiences` | The names this server answers to. A token is accepted only if its `aud` holds at least one of them. Servers that share an audience accept the same tokens. | +| `authorization_servers[].issuer` | The authorization server's issuer URL. It must equal a token's `iss` exactly. | +| `authorization_servers[].jwks` | Where the server's public keys come from; see [Keys](#keys). Optional. | + +Restart after a change. A block that is not valid stops the server from starting, and so does a +key it does not know. `jwt_secret` is still required, and tokens signed with it work as before. + +## What a token needs + +Access tokens follow the JWT format of [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068). + +| Part | Requirement | +|---|---| +| `typ` header | `at+jwt`. A token without it is never checked against an authorization server's keys, and a token with it is never checked against `jwt_secret`. | +| `alg` header | An asymmetric algorithm: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512 or EdDSA. The key must be of that algorithm's kind, and for ES256, ES384 and ES512 on its curve. | +| `kid` header | Names the signing key. It may be left out only when the server publishes a single key. | +| `iss` | A configured `issuer`. | +| `aud` | A string or a list holding at least one configured audience. | +| `sub` | Who the token is for. It is the user in logs. | +| `client_id` | The client the token was issued to. Required. | +| `iat`, `exp` | Required. `nbf` is honoured if present. Clocks may differ by 30 seconds. | +| `scope` | Optional. Space-separated permissions such as `instance:read image:read`, or `*` for all of them. | +| `jti` | The token's ID. Required. | + +A token is at most 16 KB. Its lifetime is the authorization server's to choose. + +A token without a `scope` has no permissions. This differs from a token signed with `jwt_secret`, +where a missing `permissions` claim means full access. As for every API token, the registry under +`/v2` does not check permissions. + +`revoked_token_hashes` applies to access tokens as it does to the others. Revoking a token signed +with ES256, ES384 or ES512 also revokes the second token string that carries the same signature. + +## Keys + +`jwks.type` selects the source: + +| Type | Source | +|---|---| +| `discovery` (default) | The key set named by `jwks_uri` in the server's [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) metadata, at `/.well-known/oauth-authorization-server`. | +| `explicit_url` | The key set at `jwks.url`. | +| `inline` | The public JWKs listed in `jwks.keys`. Nothing is fetched. | + +`jwks.ca_cert_pem` replaces the system roots for the fetch. + +Fetched keys are handled so that requests do not wait on the authorization server: + +- Keys are fetched over HTTPS from public addresses only, without redirects or a proxy, and kept + for five minutes. After that they are refreshed in the background while requests are still + verified with the last key set. +- A token signed with a key the last set lacks triggers a refresh, at most one a minute. This is + how a new signing key is picked up without a restart. +- The last key set is also saved under `/oauth/keys/`, with the time it was fetched. A + server that restarts continues from that copy as if it had kept running: a copy fetched less + than five minutes ago is used until those five minutes are over, and an older one is used while + the key set is fetched again. Only a server with no saved copy, such as one that has just been + configured, makes its first requests wait for a fetch. +- If a fetched key set cannot be saved, the older copy is removed, so that a restart cannot bring + back keys the authorization server has withdrawn since. The restart then waits for a fetch. + +A key removed from the authorization server stops being trusted at the next successful fetch, at +most five minutes later while the authorization server is reachable, whether or not the server +restarted in between. A key set that is empty, or holds only valid public keys for other purposes +such as encryption, is such a fetch too, and withdraws every key. While the authorization server +is unreachable or answers with anything else, the last key set stays trusted, for as long as that +lasts. To drop it at once, delete the saved copy and restart: until a fetch succeeds, no access +token is then accepted. + +## Monitor + +`hypeman_jwt_validations_total{key_role="authorization_server"}` counts verified access tokens. + +A key fetch that fails is logged as a warning, with whether the last key set is still in use, at +most every ten seconds for each authorization server. A copy that could not be saved is logged as a +warning as well, or as an error if the older copy could not be removed either. A start from the +saved copy is logged at info level, with the copy's fetch time. diff --git a/lib/accesstoken/README.md b/lib/accesstoken/README.md new file mode 100644 index 000000000..0572041eb --- /dev/null +++ b/lib/accesstoken/README.md @@ -0,0 +1,15 @@ +# accesstoken + +Verifies the access tokens an OAuth authorization server issues for this server, in the JWT format +of RFC 9068. Operator documentation is in +[docs/oauth-access-tokens.md](../../docs/oauth-access-tokens.md). + +`New` validates the `oauth` block of the server configuration. `Verifier.Verify` selects the +authorization server a token names in `iss`, has `lib/oidcfederation` check the signature, type +and time claims against that server's keys, and then requires a subject, a client ID, a token ID +and one of this server's audiences. The token's `scope` becomes `Claims.Permissions`, which is never nil. + +`lib/jwtauth` calls it for tokens whose `typ` header is `at+jwt` (`Typed`), and only for those. + +`FileKeyStore` keeps each authorization server's last fetched key set in a file, with the time it +was fetched, so that a restarted server continues with the key cache it had. diff --git a/lib/accesstoken/accesstoken.go b/lib/accesstoken/accesstoken.go new file mode 100644 index 000000000..9ee8901a8 --- /dev/null +++ b/lib/accesstoken/accesstoken.go @@ -0,0 +1,198 @@ +// Package accesstoken verifies the access tokens an OAuth authorization server +// issues for this server, in the JWT format of RFC 9068. +package accesstoken + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "log/slog" + "slices" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/oidcfederation" +) + +const ( + maxAudiences = 16 + maxServers = 8 +) + +var ( + ErrInvalidConfig = errors.New("invalid oauth configuration") + // ErrToken is returned for every token that is not accepted, whatever the reason. + ErrToken = errors.New("invalid access token") + // ErrUnavailable means no key of the token's authorization server could be obtained. + ErrUnavailable = errors.New("authorization server keys unavailable") + + // tokenTypes are the `typ` headers RFC 9068 gives an access token. A + // token without one is not an access token. + tokenTypes = []string{"at+jwt", "application/at+jwt"} +) + +// AuthorizationServer is one issuer of access tokens this server accepts. +type AuthorizationServer struct { + // Issuer is the server's issuer URL, compared exactly with a token's `iss`. + Issuer string `koanf:"issuer"` + // JWKS says where the server's public keys come from. The default, + // discovery, reads the key set the server's RFC 8414 metadata names. + JWKS oidcfederation.KeySource `koanf:"jwks"` +} + +// Config is the `oauth` block of the server configuration. +type Config struct { + // Audiences are the names this server answers to. A token is accepted + // only if its `aud` holds at least one of them. + Audiences []string `koanf:"audiences"` + AuthorizationServers []AuthorizationServer `koanf:"authorization_servers"` +} + +// Claims are the verified claims of an access token. +type Claims struct { + Issuer string + Subject string + ClientID string + // ID is the token's `jti`. + ID string + Audience []string + IssuedAt time.Time + ExpiresAt time.Time + // Permissions are the entries of the token's `scope`. A token without a + // scope has none: it never has the full access of a token signed with the + // server's own secret that lacks a permissions claim. + Permissions []string +} + +// Verifier checks access tokens against the configured authorization servers. +// It is safe for concurrent use. +type Verifier struct { + audiences []string + servers map[string]oidcfederation.IssuerSpec + keys *oidcfederation.Verifier +} + +// New validates the configuration. A nil store keeps fetched keys in memory +// only, and a nil log leaves a failing key fetch unreported. +func New(cfg Config, store oidcfederation.KeyStore, log *slog.Logger) (*Verifier, error) { + if len(cfg.AuthorizationServers) == 0 { + if len(cfg.Audiences) != 0 { + return nil, fmt.Errorf("%w: oauth.audiences is set without any oauth.authorization_servers", ErrInvalidConfig) + } + return &Verifier{}, nil + } + if len(cfg.Audiences) == 0 || len(cfg.Audiences) > maxAudiences { + return nil, fmt.Errorf("%w: oauth.audiences needs between 1 and %d entries", ErrInvalidConfig, maxAudiences) + } + for i, audience := range cfg.Audiences { + if audience == "" || len(audience) > 2048 || slices.Contains(cfg.Audiences[:i], audience) { + return nil, fmt.Errorf("%w: oauth.audiences[%d] is empty, too long or repeated", ErrInvalidConfig, i) + } + } + if len(cfg.AuthorizationServers) > maxServers { + return nil, fmt.Errorf("%w: at most %d oauth.authorization_servers are supported", ErrInvalidConfig, maxServers) + } + servers := make(map[string]oidcfederation.IssuerSpec, len(cfg.AuthorizationServers)) + for i, server := range cfg.AuthorizationServers { + spec, err := oidcfederation.AuthorizationServer(server.Issuer, server.JWKS) + if err != nil { + return nil, fmt.Errorf("%w: oauth.authorization_servers[%d]: %w", ErrInvalidConfig, i, err) + } + if _, exists := servers[spec.IssuerURL]; exists { + return nil, fmt.Errorf("%w: oauth.authorization_servers[%d]: issuer is configured twice", ErrInvalidConfig, i) + } + servers[spec.IssuerURL] = spec + } + return &Verifier{audiences: slices.Clone(cfg.Audiences), servers: servers, keys: oidcfederation.NewVerifierWithKeyStore(store, log)}, nil +} + +// Enabled reports whether any authorization server is configured. +func (v *Verifier) Enabled() bool { + return v != nil && len(v.servers) > 0 +} + +// Verify accepts a signed, unexpired access token that a configured +// authorization server issued for one of this server's audiences. +func (v *Verifier) Verify(ctx context.Context, raw string) (Claims, error) { + if !v.Enabled() { + return Claims{}, ErrToken + } + // The issuer claim only selects whose keys to check the signature with. + server, known := v.servers[unverifiedIssuer(raw)] + if !known { + return Claims{}, ErrToken + } + verified, err := v.keys.VerifySignature(ctx, server, raw, tokenTypes) + if errors.Is(err, oidcfederation.ErrUnavailable) { + return Claims{}, fmt.Errorf("%w: %w", ErrUnavailable, err) + } + if err != nil { + return Claims{}, ErrToken + } + // RFC 9068 requires every claim read here except the scope. + claims := jwt.MapClaims(verified) + subject, _ := claims["sub"].(string) + client, _ := claims["client_id"].(string) + id, _ := claims["jti"].(string) + expires, expErr := claims.GetExpirationTime() + issued, iatErr := claims.GetIssuedAt() + audiences, audErr := claims.GetAudience() + if subject == "" || len(subject) > 1024 || client == "" || len(client) > 1024 || id == "" || len(id) > 512 || + expErr != nil || iatErr != nil || audErr != nil || expires == nil || issued == nil || + !slices.ContainsFunc(audiences, func(audience string) bool { return slices.Contains(v.audiences, audience) }) { + return Claims{}, ErrToken + } + out := Claims{Issuer: server.IssuerURL, Subject: subject, ClientID: client, ID: id, Audience: audiences, IssuedAt: issued.Time, ExpiresAt: expires.Time, Permissions: []string{}} + if scope, exists := claims["scope"]; exists { + text, ok := scope.(string) + if !ok { + return Claims{}, ErrToken + } + out.Permissions = strings.Fields(text) + } + return out, nil +} + +// Typed reports whether raw declares itself an access token in its `typ` +// header, whatever else is wrong with it. Nothing about the token is verified. +func Typed(raw string) bool { + encoded, _, found := strings.Cut(raw, ".") + decoded, err := base64.RawURLEncoding.DecodeString(encoded) + if !found || err != nil { + return false + } + tokenType, _ := member(decoded, "typ") + return slices.ContainsFunc(tokenTypes, func(allowed string) bool { return strings.EqualFold(allowed, tokenType) }) +} + +// unverifiedIssuer reads the `iss` claim of a compact JWT of acceptable size. +// It is empty for anything else. +func unverifiedIssuer(raw string) string { + if len(raw) > oidcfederation.MaxAssertionBytes { + return "" + } + parts := strings.Split(raw, ".") + if len(parts) != 3 { + return "" + } + decoded, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return "" + } + issuer, _ := member(decoded, "iss") + return issuer +} + +// member reads a text member of a JSON object by its exact name, as +// verification does: a struct field would also match another capitalization. +func member(object []byte, name string) (string, bool) { + var members map[string]json.RawMessage + var value string + if json.Unmarshal(object, &members) != nil || json.Unmarshal(members[name], &value) != nil { + return "", false + } + return value, true +} diff --git a/lib/accesstoken/accesstoken_test.go b/lib/accesstoken/accesstoken_test.go new file mode 100644 index 000000000..e701dc865 --- /dev/null +++ b/lib/accesstoken/accesstoken_test.go @@ -0,0 +1,225 @@ +package accesstoken_test + +import ( + "context" + "encoding/base64" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken" + "github.com/kernel/hypeman/lib/accesstoken/accesstokentest" + "github.com/kernel/hypeman/lib/oidcfederation" + "github.com/stretchr/testify/require" +) + +func TestVerifyAcceptsATokenIssuedForThisServer(t *testing.T) { + server := accesstokentest.NewServer(t) + verifier := server.Verifier(t) + require.True(t, verifier.Enabled()) + + claims := accesstokentest.Claims("federation:ci", "instance:read instance:write") + claims["jti"] = "token-1" + // A token may name other audiences beside this server's. + claims["aud"] = []string{"https://other.example.test", accesstokentest.Audience} + verified, err := verifier.Verify(context.Background(), server.Token(t, claims, nil)) + require.NoError(t, err) + require.Equal(t, accesstokentest.Issuer, verified.Issuer) + require.Equal(t, "federation:ci", verified.Subject) + require.Equal(t, "token-1", verified.ID) + require.Equal(t, "test-client", verified.ClientID) + require.Equal(t, []string{"instance:read", "instance:write"}, verified.Permissions) + require.Equal(t, claims["exp"], verified.ExpiresAt.Unix()) + require.Equal(t, claims["iat"], verified.IssuedAt.Unix()) + + _, err = verifier.Verify(context.Background(), server.Token(t, accesstokentest.Claims("admin", "*"), map[string]any{"typ": "application/at+jwt"})) + require.NoError(t, err) +} + +// A token without a scope has no permissions, and the list is never nil: a +// nil list reads as the full access of a token that predates permissions. +func TestVerifyGivesATokenWithoutScopeNoPermissions(t *testing.T) { + server := accesstokentest.NewServer(t) + for _, scope := range []any{nil, "", " "} { + claims := accesstokentest.Claims("user", "") + delete(claims, "scope") + if scope != nil { + claims["scope"] = scope + } + verified, err := server.Verifier(t).Verify(context.Background(), server.Token(t, claims, nil)) + require.NoError(t, err) + require.NotNil(t, verified.Permissions) + require.Empty(t, verified.Permissions) + } +} + +func TestVerifyRejectsOtherTokens(t *testing.T) { + server := accesstokentest.NewServer(t) + other := accesstokentest.NewServer(t) + verifier := server.Verifier(t) + now := time.Now() + for name, alter := range map[string]func(jwt.MapClaims){ + "unknown issuer": func(c jwt.MapClaims) { c["iss"] = "https://other.example.test" }, + "no issuer": func(c jwt.MapClaims) { delete(c, "iss") }, + "other audience": func(c jwt.MapClaims) { c["aud"] = "https://other.example.test" }, + "no audience": func(c jwt.MapClaims) { delete(c, "aud") }, + "no subject": func(c jwt.MapClaims) { delete(c, "sub") }, + "empty subject": func(c jwt.MapClaims) { c["sub"] = "" }, + "no client": func(c jwt.MapClaims) { delete(c, "client_id") }, + "empty client": func(c jwt.MapClaims) { c["client_id"] = "" }, + "client not text": func(c jwt.MapClaims) { c["client_id"] = 7 }, + "no token ID": func(c jwt.MapClaims) { delete(c, "jti") }, + "empty token ID": func(c jwt.MapClaims) { c["jti"] = "" }, + "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"] = now.Add(-time.Minute).Unix() }, + "issued later": func(c jwt.MapClaims) { c["iat"] = now.Add(5 * time.Minute).Unix() }, + "not valid yet": func(c jwt.MapClaims) { c["nbf"] = now.Add(5 * time.Minute).Unix() }, + "scope not text": func(c jwt.MapClaims) { c["scope"] = []string{"instance:read"} }, + "token ID not text": func(c jwt.MapClaims) { c["jti"] = 12 }, + } { + t.Run(name, func(t *testing.T) { + claims := accesstokentest.Claims("user", "instance:read") + alter(claims) + _, err := verifier.Verify(context.Background(), server.Token(t, claims, nil)) + require.ErrorIs(t, err, accesstoken.ErrToken) + }) + } + + claims := accesstokentest.Claims("user", "instance:read") + for name, token := range map[string]string{ + // An identity token or any other JWT from the same issuer is not an access token. + "typ JWT": server.Token(t, claims, map[string]any{"typ": "JWT"}), + "other typ": server.Token(t, claims, map[string]any{"typ": "dpop+jwt"}), + "another server key": other.Token(t, claims, nil), + "unknown key ID": server.Token(t, claims, map[string]any{"kid": "key-b"}), + "not a token": "at+jwt", + "too large": strings.Repeat("a", oidcfederation.MaxAssertionBytes) + ".e30.e30", + } { + t.Run(name, func(t *testing.T) { + _, err := verifier.Verify(context.Background(), token) + require.ErrorIs(t, err, accesstoken.ErrToken) + }) + } + + // A token signed with the server's public key as an HMAC secret, or not + // signed at all, declares an algorithm no authorization server key accepts. + for _, method := range []jwt.SigningMethod{jwt.SigningMethodHS256, jwt.SigningMethodNone} { + token := jwt.NewWithClaims(method, claims) + token.Header["kid"], token.Header["typ"] = "key-a", "at+jwt" + var key any = jwt.UnsafeAllowNoneSignatureType + if method == jwt.SigningMethodHS256 { + key = server.Key.PublicKey.X.Bytes() + } + raw, err := token.SignedString(key) + require.NoError(t, err) + _, err = verifier.Verify(context.Background(), raw) + require.ErrorIs(t, err, accesstoken.ErrToken, method.Alg()) + } +} + +func TestTypedReadsOnlyTheHeader(t *testing.T) { + server := accesstokentest.NewServer(t) + claims := accesstokentest.Claims("user", "") + require.True(t, accesstoken.Typed(server.Token(t, claims, nil))) + require.True(t, accesstoken.Typed(server.Token(t, claims, map[string]any{"typ": "AT+JWT"}))) + require.True(t, accesstoken.Typed(server.Token(t, claims, map[string]any{"typ": "application/at+jwt"}))) + require.False(t, accesstoken.Typed(server.Token(t, claims, map[string]any{"typ": "JWT"}))) + require.False(t, accesstoken.Typed(server.Token(t, claims, map[string]any{"typ": 1}))) + require.False(t, accesstoken.Typed("not.a.token")) + require.False(t, accesstoken.Typed("")) + + // The member named exactly "typ" decides, as it does in verification. + encode := base64.RawURLEncoding.EncodeToString + require.False(t, accesstoken.Typed(encode([]byte(`{"alg":"ES256","typ":"JWT","TYP":"at+jwt"}`))+".e30.c2ln")) + require.True(t, accesstoken.Typed(encode([]byte(`{"alg":"ES256","typ":"at+jwt","Typ":"JWT"}`))+".e30.c2ln")) + + // The type is read from the header whatever the size of the rest, so no + // token escapes being treated as the access token it says it is. + oversized := accesstokentest.Claims("user", strings.Repeat("instance:read ", 2000)) + token := server.Token(t, oversized, nil) + require.Greater(t, len(token), oidcfederation.MaxAssertionBytes) + require.True(t, accesstoken.Typed(token)) + _, err := server.Verifier(t).Verify(context.Background(), token) + require.ErrorIs(t, err, accesstoken.ErrToken) +} + +func TestNewValidatesTheConfiguration(t *testing.T) { + disabled, err := accesstoken.New(accesstoken.Config{}, nil, nil) + require.NoError(t, err) + require.False(t, disabled.Enabled()) + _, err = disabled.Verify(context.Background(), "a.b.c") + require.ErrorIs(t, err, accesstoken.ErrToken) + var none *accesstoken.Verifier + require.False(t, none.Enabled()) + + valid := func() accesstoken.Config { + return accesstoken.Config{Audiences: []string{"prod"}, AuthorizationServers: []accesstoken.AuthorizationServer{{Issuer: "https://auth.example.test"}}} + } + _, err = accesstoken.New(valid(), nil, nil) + require.NoError(t, err) + for name, alter := range map[string]func(*accesstoken.Config){ + "audiences without a server": func(c *accesstoken.Config) { c.AuthorizationServers = nil }, + "no audience": func(c *accesstoken.Config) { c.Audiences = nil }, + "empty audience": func(c *accesstoken.Config) { c.Audiences = []string{""} }, + "repeated audience": func(c *accesstoken.Config) { c.Audiences = []string{"prod", "prod"} }, + "plain http issuer": func(c *accesstoken.Config) { c.AuthorizationServers[0].Issuer = "http://auth.example.test" }, + "no issuer": func(c *accesstoken.Config) { c.AuthorizationServers[0].Issuer = "" }, + "issuer twice": func(c *accesstoken.Config) { + c.AuthorizationServers = append(c.AuthorizationServers, c.AuthorizationServers[0]) + }, + "unknown key source": func(c *accesstoken.Config) { c.AuthorizationServers[0].JWKS.Type = "file" }, + "inline without keys": func(c *accesstoken.Config) { c.AuthorizationServers[0].JWKS.Type = "inline" }, + "metadata from elsewhere": func(c *accesstoken.Config) { + c.AuthorizationServers[0].JWKS.DiscoveryBaseURL = "https://metadata.example.test" + }, + } { + t.Run(name, func(t *testing.T) { + cfg := valid() + alter(&cfg) + _, err := accesstoken.New(cfg, nil, nil) + require.ErrorIs(t, err, accesstoken.ErrInvalidConfig) + }) + } +} + +func TestFileKeyStoreKeepsOneCopyPerID(t *testing.T) { + dir := filepath.Join(t.TempDir(), "oauth", "keys") + store := accesstoken.NewFileKeyStore(dir, slog.New(slog.DiscardHandler)) + first, second := strings.Repeat("a", 64), strings.Repeat("b", 64) + _, found := store.Load(first) + require.False(t, found) + + store.Save(first, "https://auth.example.test", []byte(`{"keys":[1]}`)) + store.Save(second, "https://other.example.test", []byte(`{"keys":[2]}`)) + store.Save(first, "https://auth.example.test", []byte(`{"keys":[3]}`)) + keySet, found := store.Load(first) + require.True(t, found) + require.JSONEq(t, `{"keys":[3]}`, string(keySet)) + keySet, found = store.Load(second) + require.True(t, found) + require.JSONEq(t, `{"keys":[2]}`, string(keySet)) + + // Only the verifier's hex digests name a file. + for _, id := range []string{"", "../" + first, strings.Repeat("A", 64), first + "0"} { + store.Save(id, "https://auth.example.test", []byte(`{"keys":[4]}`)) + _, found = store.Load(id) + require.False(t, found, id) + } + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + require.Len(t, entries, 2, "no temporary or stray file is left behind") + for _, entry := range entries { + info, err := entry.Info() + require.NoError(t, err) + require.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + require.NoError(t, os.WriteFile(filepath.Join(dir, entry.Name()), make([]byte, 300<<10), 0o600)) + } + _, found = store.Load(first) + require.False(t, found, "a copy larger than a key set can be is not read") +} diff --git a/lib/accesstoken/accesstokentest/accesstokentest.go b/lib/accesstoken/accesstokentest/accesstokentest.go new file mode 100644 index 000000000..cf4b48881 --- /dev/null +++ b/lib/accesstoken/accesstokentest/accesstokentest.go @@ -0,0 +1,80 @@ +// Package accesstokentest issues access tokens for tests of the code that +// accepts them. +package accesstokentest + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/hex" + "encoding/json" + "maps" + "testing" + "time" + + jose "github.com/go-jose/go-jose/v4" + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken" + "github.com/stretchr/testify/require" +) + +const ( + Issuer = "https://auth.example.test" + Audience = "https://hypeman.example.test" + keyID = "key-a" +) + +// Server stands in for an authorization server whose public key is +// configured inline, so nothing is fetched. +type Server struct { + Key *ecdsa.PrivateKey + // Config trusts the server for Audience. + Config accesstoken.Config +} + +// NewServer generates a signing key and the configuration that trusts it. +func NewServer(t *testing.T) *Server { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + raw, err := json.Marshal(jose.JSONWebKey{Key: &key.PublicKey, KeyID: keyID, Algorithm: "ES256", Use: "sig"}) + require.NoError(t, err) + var public map[string]any + require.NoError(t, json.Unmarshal(raw, &public)) + server := &Server{Key: key} + server.Config.Audiences = []string{Audience} + server.Config.AuthorizationServers = []accesstoken.AuthorizationServer{{Issuer: Issuer}} + server.Config.AuthorizationServers[0].JWKS.Type = "inline" + server.Config.AuthorizationServers[0].JWKS.Keys = []map[string]any{public} + return server +} + +// Verifier returns a verifier that trusts the server. +func (s *Server) Verifier(t *testing.T) *accesstoken.Verifier { + t.Helper() + verifier, err := accesstoken.New(s.Config, nil, nil) + require.NoError(t, err) + return verifier +} + +// Claims are those of a token for subject, valid for an hour around now, with +// a token ID of its own. +func Claims(subject, scope string) jwt.MapClaims { + now := time.Now() + var id [16]byte + _, _ = rand.Read(id[:]) + return jwt.MapClaims{"iss": Issuer, "sub": subject, "client_id": "test-client", "aud": Audience, "iat": now.Add(-time.Minute).Unix(), "exp": now.Add(time.Hour).Unix(), "jti": hex.EncodeToString(id[:]), "scope": scope} +} + +// Token signs claims as an access token. Entries of header replace the +// defaults, among them the `typ` that marks an access token. +func (s *Server) Token(t *testing.T, claims jwt.MapClaims, header map[string]any) string { + t.Helper() + token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + token.Header["kid"] = keyID + token.Header["typ"] = "at+jwt" + maps.Copy(token.Header, header) + raw, err := token.SignedString(s.Key) + require.NoError(t, err) + return raw +} diff --git a/lib/accesstoken/keystore.go b/lib/accesstoken/keystore.go new file mode 100644 index 000000000..73d0d8e39 --- /dev/null +++ b/lib/accesstoken/keystore.go @@ -0,0 +1,99 @@ +package accesstoken + +import ( + "errors" + "io/fs" + "log/slog" + "os" + "path/filepath" + "strings" +) + +// maxKeySetBytes bounds a stored key set, as the fetched one is bounded. +const maxKeySetBytes = 256 << 10 + +// FileKeyStore keeps each authorization server's last fetched public key set +// in one file of a directory, with the time it was fetched. A server that +// restarts continues from that copy. +// +// The copy is a convenience, not a record: a write that fails is logged and +// the fetched keys stay in memory. The older copy is then removed, so that a +// restart cannot bring back keys the server has withdrawn since. +type FileKeyStore struct { + dir string + log *slog.Logger + // write replaces the file at a path. Tests make it fail. + write func(path string, keySet []byte) error +} + +// NewFileKeyStore stores key sets under dir, which is created when first needed. +func NewFileKeyStore(dir string, log *slog.Logger) *FileKeyStore { + s := &FileKeyStore{dir: dir, log: log} + s.write = s.replace + return s +} + +// path is the file of one key set. The id is the hex digest the verifier +// derives from an issuer and its key source; anything else names no file. +func (s *FileKeyStore) path(id string) (string, bool) { + if len(id) != 64 || strings.Trim(id, "0123456789abcdef") != "" { + return "", false + } + return filepath.Join(s.dir, id+".json"), true +} + +// Save replaces the stored key set. +func (s *FileKeyStore) Save(id, issuerURL string, keySet []byte) { + path, ok := s.path(id) + if !ok { + return + } + err := s.write(path, keySet) + if err == nil { + return + } + // The copy that was not replaced may hold keys this fetch no longer + // lists. Without a copy, a restart waits for a fetch. + if removeErr := os.Remove(path); removeErr != nil && !errors.Is(removeErr, fs.ErrNotExist) { + s.log.Error("authorization server keys were not saved and the older copy could not be removed; a restart would start from the older keys", "issuer", issuerURL, "error", err, "remove_error", removeErr) + return + } + s.log.Warn("authorization server keys were not saved; a restart will fetch them", "issuer", issuerURL, "error", err) +} + +func (s *FileKeyStore) replace(path string, keySet []byte) error { + if err := os.MkdirAll(s.dir, 0o700); err != nil { + return err + } + temporary, err := os.CreateTemp(s.dir, ".keys-*") + if err != nil { + return err + } + defer os.Remove(temporary.Name()) + if _, err := temporary.Write(keySet); err != nil { + temporary.Close() + return err + } + if err := temporary.Sync(); err != nil { + temporary.Close() + return err + } + if err := temporary.Close(); err != nil { + return err + } + return os.Rename(temporary.Name(), path) +} + +// Load returns the stored key set, if there is a readable one. +func (s *FileKeyStore) Load(id string) ([]byte, bool) { + path, ok := s.path(id) + if !ok { + return nil, false + } + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > maxKeySetBytes { + return nil, false + } + keySet, err := os.ReadFile(path) + return keySet, err == nil +} diff --git a/lib/accesstoken/keystore_internal_test.go b/lib/accesstoken/keystore_internal_test.go new file mode 100644 index 000000000..8221fa1db --- /dev/null +++ b/lib/accesstoken/keystore_internal_test.go @@ -0,0 +1,35 @@ +package accesstoken + +import ( + "errors" + "log/slog" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// A key set that could not be saved must not leave the older copy behind: +// that copy may list keys the authorization server has withdrawn, and a +// restart would trust them again. +func TestFailedSaveRemovesTheOlderCopy(t *testing.T) { + store := NewFileKeyStore(t.TempDir(), slog.New(slog.DiscardHandler)) + id := strings.Repeat("a", 64) + store.Save(id, "https://auth.example.test", []byte(`{"keys":["older"]}`)) + _, found := store.Load(id) + require.True(t, found) + + replace := store.write + store.write = func(string, []byte) error { return errors.New("no space left on device") } + store.Save(id, "https://auth.example.test", []byte(`{"keys":[]}`)) + _, found = store.Load(id) + require.False(t, found, "a restart has no copy and fetches the keys") + // Nothing to remove is not a second failure. + store.Save(id, "https://auth.example.test", []byte(`{"keys":[]}`)) + + store.write = replace + store.Save(id, "https://auth.example.test", []byte(`{"keys":["newer"]}`)) + keySet, found := store.Load(id) + require.True(t, found) + require.JSONEq(t, `{"keys":["newer"]}`, string(keySet)) +} diff --git a/lib/jwtauth/access_token_test.go b/lib/jwtauth/access_token_test.go new file mode 100644 index 000000000..f127b5313 --- /dev/null +++ b/lib/jwtauth/access_token_test.go @@ -0,0 +1,87 @@ +package jwtauth + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken" + "github.com/kernel/hypeman/lib/accesstoken/accesstokentest" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/metric/noop" +) + +func hmacToken(t *testing.T, secret string, header map[string]any) string { + t.Helper() + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": "admin", "exp": time.Now().Add(time.Hour).Unix()}) + for name, value := range header { + token.Header[name] = value + } + raw, err := token.SignedString([]byte(secret)) + require.NoError(t, err) + return raw +} + +func TestAccessTokensAreVerifiedAgainstTheAuthorizationServerOnly(t *testing.T) { + server := accesstokentest.NewServer(t) + hmacOnly, err := NewVerifier("secret", nil, noop.NewMeterProvider().Meter("test")) + require.NoError(t, err) + verifier := hmacOnly.WithAccessTokens(server.Verifier(t)) + + accessClaims := accesstokentest.Claims("federation:ci", "instance:read image:read") + accessClaims["jti"] = "token-1" + access := server.Token(t, accessClaims, nil) + + // The claims arrive in the shape of an HMAC token's. + claims := jwt.MapClaims{} + token, err := verifier.ParseWithClaims(context.Background(), access, claims) + require.NoError(t, err) + require.True(t, token.Valid) + require.Equal(t, "federation:ci", claims["sub"]) + require.Equal(t, []any{"instance:read", "image:read"}, claims["permissions"]) + require.Equal(t, "token-1", claims["jti"]) + require.NotContains(t, claims, "scope", "a scope claim marks a registry token to the callers") + + var registered jwt.RegisteredClaims + token, err = verifier.ParseWithClaims(context.Background(), access, ®istered) + require.NoError(t, err) + require.Same(t, ®istered, token.Claims) + require.Equal(t, "federation:ci", registered.Subject) + require.Equal(t, jwt.ClaimStrings{accesstokentest.Audience}, registered.Audience) + + // A token without a scope still carries a permissions list, an empty one. + unscoped := accesstokentest.Claims("user", "") + delete(unscoped, "scope") + claims = jwt.MapClaims{} + _, err = verifier.ParseWithClaims(context.Background(), server.Token(t, unscoped, nil), claims) + require.NoError(t, err) + require.Equal(t, []any{}, claims["permissions"]) + + // Tokens signed with the server's own secret work as before. + claims = jwt.MapClaims{} + _, err = verifier.ParseWithClaims(context.Background(), hmacToken(t, "secret", nil), claims) + require.NoError(t, err) + require.Equal(t, "admin", claims["sub"]) + require.NotContains(t, claims, "permissions") + + // Neither kind of key accepts the other kind of token. + _, err = verifier.ParseWithClaims(context.Background(), hmacToken(t, "secret", map[string]any{"typ": "at+jwt"}), jwt.MapClaims{}) + require.ErrorIs(t, err, accesstoken.ErrToken, "the secret does not sign access tokens") + _, err = verifier.ParseWithClaims(context.Background(), hmacToken(t, "secret", map[string]any{"typ": "at+jwt", "pad": strings.Repeat("a", 20<<10)}), jwt.MapClaims{}) + require.ErrorIs(t, err, accesstoken.ErrToken, "nor a large one") + _, err = verifier.ParseWithClaims(context.Background(), server.Token(t, accessClaims, map[string]any{"typ": "JWT"}), jwt.MapClaims{}) + require.Error(t, err, "an authorization server key does not sign other tokens") + require.NotErrorIs(t, err, accesstoken.ErrToken) + + // With no authorization server configured, an access token is just a + // token the secret did not sign. + _, err = hmacOnly.ParseWithClaims(context.Background(), access, jwt.MapClaims{}) + require.Error(t, err) + disabled, err := accesstoken.New(accesstoken.Config{}, nil, nil) + require.NoError(t, err) + _, err = hmacOnly.WithAccessTokens(disabled).ParseWithClaims(context.Background(), access, jwt.MapClaims{}) + require.Error(t, err) + require.NotErrorIs(t, err, accesstoken.ErrToken) +} diff --git a/lib/jwtauth/verifier.go b/lib/jwtauth/verifier.go index 464d2edb3..6f395b050 100644 --- a/lib/jwtauth/verifier.go +++ b/lib/jwtauth/verifier.go @@ -1,12 +1,16 @@ -// Package jwtauth verifies HMAC tokens during signing-key rotation. +// Package jwtauth verifies API tokens: HMAC tokens signed with the server's +// own secret, during signing-key rotation too, and access tokens issued by a +// configured authorization server. package jwtauth import ( "context" + "encoding/json" "errors" "fmt" "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" ) @@ -14,8 +18,17 @@ import ( // Verifier accepts the signing key and additional verification-only keys. // It is immutable and safe for concurrent use. type Verifier struct { - keys [][]byte - validations metric.Int64Counter + keys [][]byte + validations metric.Int64Counter + accessTokens *accesstoken.Verifier +} + +// WithAccessTokens returns a Verifier that also accepts the access tokens +// that verifier does. +func (v *Verifier) WithAccessTokens(verifier *accesstoken.Verifier) *Verifier { + out := *v + out.accessTokens = verifier + return &out } func NewVerifier(signingSecret string, verificationSecrets []string, meter metric.Meter) (*Verifier, error) { @@ -40,6 +53,12 @@ func NewVerifier(signingSecret string, verificationSecrets []string, meter metri // ParseWithClaims preserves JWT claim validation and only tries another key on // a signature mismatch. Callers still enforce revocation and authorization. func (v *Verifier) ParseWithClaims(ctx context.Context, tokenString string, claims jwt.Claims) (*jwt.Token, error) { + // A token that declares itself an access token is never checked against + // the HMAC keys, and no other token is checked against an authorization + // server's keys. + if v.accessTokens.Enabled() && accesstoken.Typed(tokenString) { + return v.parseAccessToken(ctx, tokenString, claims) + } if len(v.keys) == 0 { return nil, errors.New("JWT secret not configured") } @@ -66,3 +85,38 @@ func (v *Verifier) ParseWithClaims(ctx context.Context, tokenString string, clai } return nil, err } + +// parseAccessToken verifies an authorization server's access token and hands +// its claims to the caller in the shape of an HMAC token's: the scope becomes +// the permissions list. The list is always present, so such a token is never +// read as a token without one, which has full access. +func (v *Verifier) parseAccessToken(ctx context.Context, tokenString string, claims jwt.Claims) (*jwt.Token, error) { + verified, err := v.accessTokens.Verify(ctx, tokenString) + if err != nil { + return nil, err + } + fields := map[string]any{ + "iss": verified.Issuer, + "sub": verified.Subject, + "aud": verified.Audience, + "iat": verified.IssuedAt.Unix(), + "exp": verified.ExpiresAt.Unix(), + "jti": verified.ID, + "permissions": verified.Permissions, + } + encoded, err := json.Marshal(fields) + if err != nil { + return nil, err + } + // MapClaims is passed by value; decoding through its address fills the caller's map. + if mapped, ok := claims.(jwt.MapClaims); ok { + err = json.Unmarshal(encoded, &mapped) + } else { + err = json.Unmarshal(encoded, claims) + } + if err != nil { + return nil, err + } + v.validations.Add(ctx, 1, metric.WithAttributes(attribute.String("key_role", "authorization_server"))) + return &jwt.Token{Raw: tokenString, Claims: claims, Valid: true}, nil +} diff --git a/lib/middleware/README.md b/lib/middleware/README.md index 2b9391066..82427489b 100644 --- a/lib/middleware/README.md +++ b/lib/middleware/README.md @@ -6,6 +6,8 @@ HTTP middleware for the hypeman API. JWT bearer token validation for protected endpoints. Extracts user identity and adds it to the request context. +A token is either signed with `jwt_secret` or, when `oauth.authorization_servers` is configured, an access token one of those servers issued; see [docs/oauth-access-tokens.md](../../docs/oauth-access-tokens.md). An access token's `scope` is read as the permissions list. + Tokens whose SHA-256 appears in `revoked_token_hashes` are rejected even when they are correctly signed and unexpired, so a single leaked token can be revoked without rotating `jwt_secret`. Revoked tokens are logged at warn level with the request path and remote address. ## Resource Resolution diff --git a/lib/middleware/oapi_auth_test.go b/lib/middleware/oapi_auth_test.go index ee93e25e6..2360eefa1 100644 --- a/lib/middleware/oapi_auth_test.go +++ b/lib/middleware/oapi_auth_test.go @@ -2,15 +2,22 @@ package middleware import ( "context" + "crypto/elliptic" + "crypto/sha256" "encoding/base64" + "encoding/hex" + "fmt" + "math/big" "net/http" "net/http/httptest" + "strings" "testing" "time" "github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3filter" "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken/accesstokentest" "github.com/kernel/hypeman/lib/jwtauth" "github.com/kernel/hypeman/lib/scopes" "github.com/kernel/hypeman/lib/tokenrevocation" @@ -618,3 +625,83 @@ func TestRevokedTokensAreRejected(t *testing.T) { assert.NoError(t, authFunc(context.Background(), newBearerAuthInput(t, activeToken))) }) } + +// An authorization server's access token authenticates like a token signed +// with the server's secret: its scope is the permissions list, and its +// subject is the user. +func TestJwtAuth_AccessTokens(t *testing.T) { + server := accesstokentest.NewServer(t) + verifier := newTestVerifier(t, testJWTSecret).WithAccessTokens(server.Verifier(t)) + nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-User-ID", GetUserIDFromContext(r.Context())) + w.Header().Set("X-Full-Access", fmt.Sprint(scopes.HasFullAccess(r.Context()))) + w.Header().Set("X-Instance-Read", fmt.Sprint(scopes.HasScope(r.Context(), scopes.InstanceRead))) + w.Header().Set("X-Instance-Write", fmt.Sprint(scopes.HasScope(r.Context(), scopes.InstanceWrite))) + w.WriteHeader(http.StatusOK) + }) + revoked := server.Token(t, accesstokentest.Claims("revoked", "*"), nil) + digest := sha256.Sum256([]byte(revoked)) + revocations, err := tokenrevocation.New([]string{hex.EncodeToString(digest[:])}) + require.NoError(t, err) + handler := JwtAuth(verifier, revocations)(nextHandler) + serve := func(path, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+token) + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + return rr + } + + rr := serve("/instances", server.Token(t, accesstokentest.Claims("federation:ci", "instance:read"), nil)) + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, "federation:ci", rr.Header().Get("X-User-ID")) + assert.Equal(t, "false", rr.Header().Get("X-Full-Access")) + assert.Equal(t, "true", rr.Header().Get("X-Instance-Read")) + assert.Equal(t, "false", rr.Header().Get("X-Instance-Write")) + + // Full access is the wildcard scope, never the absence of a scope. + rr = serve("/instances", server.Token(t, accesstokentest.Claims("admin", "*"), nil)) + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, "true", rr.Header().Get("X-Full-Access")) + unscoped := accesstokentest.Claims("user", "") + delete(unscoped, "scope") + rr = serve("/instances", server.Token(t, unscoped, nil)) + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, "false", rr.Header().Get("X-Full-Access")) + assert.Equal(t, "false", rr.Header().Get("X-Instance-Read")) + + // The registry accepts it as it accepts any API token. + rr = serve("/v2/test-image/manifests/latest", server.Token(t, accesstokentest.Claims("federation:ci", "image:read"), nil)) + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, "federation:ci", rr.Header().Get("X-User-ID")) + + // The other token with the same ECDSA signature is revoked with it. + separator := strings.LastIndexByte(revoked, '.') + signature, err := base64.RawURLEncoding.DecodeString(revoked[separator+1:]) + require.NoError(t, err) + s := new(big.Int).SetBytes(signature[32:]) + new(big.Int).Sub(elliptic.P256().Params().N, s).FillBytes(signature[32:]) + revokedTwin := revoked[:separator+1] + base64.RawURLEncoding.EncodeToString(signature) + _, err = server.Verifier(t).Verify(context.Background(), revokedTwin) + require.NoError(t, err, "it must verify, otherwise the test proves nothing") + + for name, token := range map[string]string{ + "revoked": revoked, + "revoked twin": revokedTwin, + "other audience": func() string { + claims := accesstokentest.Claims("user", "*") + claims["aud"] = "other" + return server.Token(t, claims, nil) + }(), + "builder subject": server.Token(t, accesstokentest.Claims("builder-abc", "*"), nil), + "signed with the secret": func() string { + token := jwt.NewWithClaims(jwt.SigningMethodHS256, accesstokentest.Claims("admin", "*")) + token.Header["typ"] = "at+jwt" + raw, err := token.SignedString([]byte(testJWTSecret)) + require.NoError(t, err) + return raw + }(), + } { + assert.Equal(t, http.StatusUnauthorized, serve("/instances", token).Code, name) + } +} diff --git a/lib/oidcfederation/README.md b/lib/oidcfederation/README.md index fb9a54752..aaabc8312 100644 --- a/lib/oidcfederation/README.md +++ b/lib/oidcfederation/README.md @@ -41,6 +41,7 @@ their JSON text; objects and arrays never match. 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. + The key must be of the algorithm's kind, and an ECDSA key on the algorithm's curve. - 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 @@ -49,3 +50,19 @@ their JSON text; objects and arrays never match. 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. + +## Authorization servers + +`AuthorizationServer` describes an OAuth authorization server whose access tokens a resource +server accepts, and `Verifier.VerifySignature` checks a token's signature, issuer and time claims +against its keys, leaving the audience and other claims to the caller; `lib/accesstoken` applies +the access token rules. Two things differ from an identity issuer: + +- Its metadata is read from the RFC 8414 location, `/.well-known/oauth-authorization-server`. +- Its last key set stays in use while a refresh runs or fails, and is handed to a `KeyStore` with + the time it was fetched, so that a restarted server continues with the cache it had. A resource + server checks every request against those keys, so it must not stop when the authorization + server does. An identity issuer's keys are never kept past their five minutes. +- A key set that is empty or holds only valid public keys for other purposes is its answer that every + key is withdrawn, and replaces the last key set. For an identity issuer it is a configuration + problem. diff --git a/lib/oidcfederation/authorizationserver_test.go b/lib/oidcfederation/authorizationserver_test.go new file mode 100644 index 000000000..11fbb19bb --- /dev/null +++ b/lib/oidcfederation/authorizationserver_test.go @@ -0,0 +1,534 @@ +package oidcfederation + +import ( + "context" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/sha512" + "encoding/base64" + "encoding/json" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + jose "github.com/go-jose/go-jose/v4" + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/require" +) + +var accessTokenTypes = []string{"at+jwt", "application/at+jwt"} + +type authorizationServerFixture struct { + now time.Time + spec IssuerSpec + keys map[string]*ecdsa.PrivateKey +} + +func newAuthorizationServerFixture(t *testing.T) *authorizationServerFixture { + t.Helper() + spec, err := AuthorizationServer("https://auth.example.test", KeySource{}) + require.NoError(t, err) + return &authorizationServerFixture{now: time.Unix(1700000000, 0), spec: spec, keys: map[string]*ecdsa.PrivateKey{}} +} + +// keySet generates the named keys that the fixture does not hold yet and +// returns the key set document publishing all of the named ones. +func (f *authorizationServerFixture) keySet(t *testing.T, ids ...string) []byte { + t.Helper() + var set jose.JSONWebKeySet + for _, id := range ids { + if f.keys[id] == nil { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + f.keys[id] = key + } + set.Keys = append(set.Keys, jose.JSONWebKey{Key: &f.keys[id].PublicKey, KeyID: id, Algorithm: "ES256", Use: "sig"}) + } + raw, err := json.Marshal(set) + require.NoError(t, err) + return raw +} + +func (f *authorizationServerFixture) token(t *testing.T, keyID, typ string) string { + t.Helper() + token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{"iss": f.spec.IssuerURL, "sub": "federation:ci", "aud": "prod", "iat": f.now.Unix(), "exp": f.now.Add(24 * time.Hour).Unix()}) + token.Header["kid"], token.Header["typ"] = keyID, typ + raw, err := token.SignedString(f.keys[keyID]) + require.NoError(t, err) + return raw +} + +type memoryKeyStore struct { + mu sync.Mutex + saved map[string][]byte + loads int +} + +func (s *memoryKeyStore) Save(id, _ string, keySet []byte) { + s.mu.Lock() + defer s.mu.Unlock() + if s.saved == nil { + s.saved = map[string][]byte{} + } + s.saved[id] = keySet +} + +func (s *memoryKeyStore) Load(id string) ([]byte, bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.loads++ + keySet, ok := s.saved[id] + return keySet, ok +} + +func TestVerifySignatureAppliesOnlyTheGivenTokenTypes(t *testing.T) { + f := newAuthorizationServerFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + keys := f.keySet(t, "key-a") + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return keys, nil } + + claims, err := v.VerifySignature(context.Background(), f.spec, f.token(t, "key-a", "at+jwt"), accessTokenTypes) + require.NoError(t, err) + require.Equal(t, "federation:ci", claims["sub"]) + require.Equal(t, "prod", claims["aud"], "the audience is the caller's to judge") + + for _, typ := range []string{"JWT", "", "dpop+jwt"} { + _, err = v.VerifySignature(context.Background(), f.spec, f.token(t, "key-a", typ), accessTokenTypes) + require.ErrorIs(t, err, ErrAssertion, typ) + } + // An access token is not an identity assertion either. + _, err = v.VerifySignature(context.Background(), f.spec, f.token(t, "key-a", "at+jwt"), assertionTypes) + require.ErrorIs(t, err, ErrAssertion) +} + +func TestAuthorizationServerMetadataFollowsRFC8414(t *testing.T) { + for issuer, metadata := range map[string]string{ + "https://auth.example.test": "https://auth.example.test/.well-known/oauth-authorization-server", + "https://auth.example.test/": "https://auth.example.test/.well-known/oauth-authorization-server", + "https://auth.example.test/tenant-1": "https://auth.example.test/.well-known/oauth-authorization-server/tenant-1", + } { + spec, err := AuthorizationServer(issuer, KeySource{}) + require.NoError(t, err) + require.Equal(t, "discovery", spec.JWKS.Type) + require.Equal(t, metadata, metadataURL(spec)) + } + identity, err := normalizeIssuer(IssuerSpec{Name: "idp", IssuerURL: "https://auth.example.test/tenant-1"}) + require.NoError(t, err) + require.Equal(t, "https://auth.example.test/tenant-1/.well-known/openid-configuration", metadataURL(identity)) + + _, err = AuthorizationServer("https://auth.example.test", KeySource{DiscoveryBaseURL: "https://metadata.example.test"}) + require.ErrorIs(t, err, ErrInvalid) + _, err = AuthorizationServer(GitHubIssuer, KeySource{}) + require.ErrorIs(t, err, ErrInvalid, "an identity provider with its own rules is not an authorization server") +} + +// A resource server checks every request against these keys, so the last key +// set keeps answering while the authorization server cannot be reached. +func TestAuthorizationServerKeysStayInUseWhileARefreshFails(t *testing.T) { + f := newAuthorizationServerFixture(t) + v := NewVerifier() + v.now = func() time.Time { return f.now } + var fetches atomic.Int32 + var mu sync.Mutex + published, failing := f.keySet(t, "key-a"), false + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + fetches.Add(1) + mu.Lock() + defer mu.Unlock() + if failing { + return nil, ErrUnavailable + } + return published, nil + } + verify := func(keyID string) error { + _, err := v.VerifySignature(context.Background(), f.spec, f.token(t, keyID, "at+jwt"), accessTokenTypes) + return err + } + require.NoError(t, verify("key-a")) + require.EqualValues(t, 1, fetches.Load()) + + // The cached set expires while the server is down. + mu.Lock() + failing = true + mu.Unlock() + f.now = f.now.Add(keyCacheTTL + time.Second) + require.NoError(t, verify("key-a"), "answered from the last key set without waiting for the refresh") + require.Eventually(t, func() bool { return fetches.Load() == 2 }, time.Second, time.Millisecond, "a refresh runs in the background") + require.Eventually(t, func() bool { v.mu.Lock(); defer v.mu.Unlock(); return len(v.loading) == 0 }, time.Second, time.Millisecond) + require.NoError(t, verify("key-a")) + require.EqualValues(t, 2, fetches.Load(), "a failed fetch is not repeated at once") + + // A key the last set lacks cannot be vouched for by it. + f.keySet(t, "key-b") + require.ErrorIs(t, verify("key-b"), ErrUnavailable) + + // The server returns, publishing a new key beside the old one. + mu.Lock() + published, failing = f.keySet(t, "key-a", "key-b"), false + mu.Unlock() + f.now = f.now.Add(keyFailureTTL + time.Second) + require.NoError(t, verify("key-b")) + require.NoError(t, verify("key-a")) +} + +// A restart continues from the saved copy as if the process had kept running: +// a copy still within the cache lifetime needs no fetch, and an older one +// answers while it is fetched again. +func TestAuthorizationServerKeyCacheSurvivesARestart(t *testing.T) { + f := newAuthorizationServerFixture(t) + published := f.keySet(t, "key-a") + store := &memoryKeyStore{} + token := f.token(t, "key-a", "at+jwt") + fetchedAt := f.now + unreachable := func(context.Context, IssuerSpec) ([]byte, error) { return nil, ErrUnavailable } + idle := func(v *Verifier) bool { v.mu.Lock(); defer v.mu.Unlock(); return len(v.loading) == 0 } + // A request that waited for a fetch would end with this deadline. + waiting, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + first := NewVerifierWithKeyStore(store, nil) + first.now = func() time.Time { return fetchedAt } + first.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return published, nil } + _, err := first.VerifySignature(waiting, f.spec, token, accessTokenTypes) + require.NoError(t, err) + saved := string(store.saved[keyCacheKey(f.spec)]) + require.Contains(t, saved, `"fetched_at":"`+fetchedAt.UTC().Format(time.RFC3339)+`"`) + require.NotContains(t, saved, `"d"`, "only public keys are kept") + require.Equal(t, 1, store.loads, "a copy was looked for; there was none, so the first request waited for the fetch") + + // restart returns a new process at the given time whose fetches block + // until released and then fail. + restart := func(now time.Time) (*Verifier, *atomic.Int32, func()) { + v := NewVerifierWithKeyStore(store, nil) + v.now = func() time.Time { return now } + blocked := make(chan struct{}) + release := sync.OnceFunc(func() { close(blocked) }) + t.Cleanup(release) + fetches := new(atomic.Int32) + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + fetches.Add(1) + <-blocked + return nil, ErrUnavailable + } + return v, fetches, release + } + verify := func(v *Verifier) error { + _, err := v.VerifySignature(waiting, f.spec, token, accessTokenTypes) + return err + } + + // Within the cache lifetime nothing is fetched at all. + fresh, fetches, _ := restart(fetchedAt.Add(keyCacheTTL - time.Second)) + for range 3 { + require.NoError(t, verify(fresh)) + } + require.True(t, idle(fresh)) + require.Zero(t, fetches.Load()) + + // Past it, and when the fetch time cannot be right, the copy answers + // while one fetch runs, and stays in use when that fetch fails. + for name, now := range map[string]time.Time{ + "past the cache lifetime": fetchedAt.Add(keyCacheTTL), + "hours after": fetchedAt.Add(12 * time.Hour), + "fetched later than now": fetchedAt.Add(-time.Second), + } { + restarted, fetches, release := restart(now) + for range 3 { + require.NoError(t, verify(restarted), name) + } + require.Eventually(t, func() bool { return fetches.Load() == 1 }, time.Second, time.Millisecond, name) + release() + require.Eventually(t, func() bool { return idle(restarted) }, time.Second, time.Millisecond, name) + require.NoError(t, verify(restarted), name) + } + require.Equal(t, 5, store.loads, "each process reads the copy once") + + // A copy without a fetch time is due for a refresh at once. + undated := &memoryKeyStore{saved: map[string][]byte{keyCacheKey(f.spec): published}} + old := NewVerifierWithKeyStore(undated, nil) + old.now = func() time.Time { return fetchedAt } + var started atomic.Int32 + old.fetch = func(context.Context, IssuerSpec) ([]byte, error) { started.Add(1); return nil, ErrUnavailable } + require.NoError(t, verify(old)) + require.Eventually(t, func() bool { return started.Load() == 1 && idle(old) }, time.Second, time.Millisecond) + + // A copy fetched from one key source does not stand in for another. + moved, err := AuthorizationServer(f.spec.IssuerURL, KeySource{Type: "explicit_url", URL: "https://keys.example.test/jwks.json"}) + require.NoError(t, err) + fresh.fetch = unreachable + _, err = fresh.VerifySignature(waiting, moved, token, accessTokenTypes) + require.ErrorIs(t, err, ErrUnavailable) + + // Without a usable copy there is nothing to verify with. + for _, v := range []*Verifier{ + NewVerifier(), + NewVerifierWithKeyStore(&memoryKeyStore{}, nil), + NewVerifierWithKeyStore(&memoryKeyStore{saved: map[string][]byte{keyCacheKey(f.spec): []byte(`{"keys":`)}}, nil), + } { + v.now = func() time.Time { return fetchedAt } + v.fetch = unreachable + require.ErrorIs(t, verify(v), ErrUnavailable) + } +} + +// A server that answers with a key set holding no signing key has withdrawn +// its keys. That is not a failed fetch: the last key set must not outlive it, +// in memory or in the saved copy. +func TestAuthorizationServerCanWithdrawEveryKey(t *testing.T) { + f := newAuthorizationServerFixture(t) + store := &memoryKeyStore{} + published := f.keySet(t, "key-a") + token := f.token(t, "key-a", "at+jwt") + v := NewVerifierWithKeyStore(store, nil) + v.now = func() time.Time { return f.now } + var mu sync.Mutex + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + mu.Lock() + defer mu.Unlock() + return published, nil + } + verify := func(v *Verifier) error { + _, err := v.VerifySignature(context.Background(), f.spec, token, accessTokenTypes) + return err + } + require.NoError(t, verify(v)) + + // A valid public key published for encryption only, as a JWK. + encryptionKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + encryption, err := json.Marshal(jose.JSONWebKey{Key: &encryptionKey.PublicKey, KeyID: "enc-1", Algorithm: "RSA-OAEP", Use: "enc"}) + require.NoError(t, err) + unsigning := strings.Replace(string(encryption), `"use":"enc"`, `"key_ops":["encrypt","wrapKey"]`, 1) + require.NotEqual(t, string(encryption), unsigning) + + for _, withdrawn := range []string{`{"keys":[]}`, `{"keys":[` + string(encryption) + `]}`, `{"keys":[` + unsigning + `]}`} { + mu.Lock() + published = []byte(withdrawn) + mu.Unlock() + f.now = f.now.Add(keyCacheTTL + keyRefreshPeriod + time.Second) + // The first request after the cache expires is still answered from the + // last key set; the refresh it starts removes that set. + _ = verify(v) + require.Eventually(t, func() bool { v.mu.Lock(); defer v.mu.Unlock(); return len(v.loading) == 0 }, time.Second, time.Millisecond) + require.ErrorIs(t, verify(v), ErrAssertion, withdrawn) + require.Contains(t, string(store.saved[keyCacheKey(f.spec)]), `"keys":[]`, "the saved copy is replaced too") + + // A restart does not bring the withdrawn key back, reachable or not. + // Which refusal it is depends on whether the failed fetch has ended. + restarted := NewVerifierWithKeyStore(store, nil) + restarted.now = func() time.Time { return f.now } + restarted.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return nil, ErrUnavailable } + require.Error(t, verify(restarted), withdrawn) + require.Eventually(t, func() bool { restarted.mu.Lock(); defer restarted.mu.Unlock(); return len(restarted.loading) == 0 }, time.Second, time.Millisecond) + require.Error(t, verify(restarted), withdrawn) + + // Publishing the key again restores it. + mu.Lock() + published = f.keySet(t, "key-a") + mu.Unlock() + f.now = f.now.Add(keyCacheTTL + keyRefreshPeriod + time.Second) + require.NoError(t, verify(v)) + } + + // A response that is not a key set at all is a failed fetch, and the last + // key set stays. + for _, broken := range []string{ + `{"keys":null}`, `{}`, `not json`, + `{"keys":[{"kty":"RSA","use":"sig","kid":"bad"}]}`, + // Entries that are skipped but are not valid public keys say nothing + // about the server's keys. + `{"keys":[{"use":"enc"}]}`, + `{"keys":[{"kty":"oct","use":"enc","kid":"secret"}]}`, + `{"keys":[{"kty":"RSA","use":"enc","e":"AQAB"}]}`, + `{"keys":[{"kty":"RSA","use":"enc","n":"not base64url!","e":"AQAB"}]}`, + `{"keys":[{"kty":"RSA","use":"enc","n":"AQAB","e":"AQAB"}]}`, + `{"keys":[{"kty":"EC","use":"enc","crv":"P-256","x":"AQAB","y":"AQAB"}]}`, + `{"keys":[{"kty":"OKP","use":"enc","crv":"X25519","x":"hSDwCYkwp1R0i33ctD73Wg2_Og0mOBr066SpjqqbTmo"}]}`, + `{"keys":[` + strings.Replace(string(encryption), `"use":"enc"`, `"key_ops":null`, 1) + `]}`, + `{"keys":[` + strings.Replace(string(encryption), `"use":"enc"`, `"use":"enc","key_ops":null`, 1) + `]}`, + `{"keys":[` + strings.Replace(string(encryption), `"use":"enc"`, `"use":"enc","key_ops":["verify"]`, 1) + `]}`, + `{"keys":[` + strings.Replace(string(encryption), `"use":"enc"`, `"use":"enc","d":"AQAB"`, 1) + `]}`, + `{"keys":[` + string(encryption) + `,{"use":"enc"}]}`, + } { + mu.Lock() + published = []byte(broken) + mu.Unlock() + f.now = f.now.Add(keyCacheTTL + keyRefreshPeriod + time.Second) + require.NoError(t, verify(v), broken) + require.Eventually(t, func() bool { v.mu.Lock(); defer v.mu.Unlock(); return len(v.loading) == 0 }, time.Second, time.Millisecond) + require.NoError(t, verify(v), broken) + } + + // An identity issuer that publishes no signing key is misconfigured, as before. + identity, err := normalizeIssuer(IssuerSpec{Name: "idp", IssuerURL: f.spec.IssuerURL}) + require.NoError(t, err) + empty := NewVerifier() + empty.now = func() time.Time { return f.now } + empty.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return []byte(`{"keys":[]}`), nil } + _, err = empty.VerifySignature(context.Background(), identity, f.token(t, "key-a", "JWT"), assertionTypes) + var problem *KeyProblem + require.ErrorAs(t, err, &problem) +} + +// An identity issuer's keys are neither kept past their lifetime nor stored: +// only an authorization server's are. +func TestIdentityIssuerKeysAreNotKept(t *testing.T) { + f := newAuthorizationServerFixture(t) + published := f.keySet(t, "key-a") + identity, err := normalizeIssuer(IssuerSpec{Name: "idp", IssuerURL: f.spec.IssuerURL}) + require.NoError(t, err) + store := &memoryKeyStore{} + v := NewVerifierWithKeyStore(store, nil) + v.now = func() time.Time { return f.now } + failing := false + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { + if failing { + return nil, errors.New("down") + } + return published, nil + } + token := f.token(t, "key-a", "JWT") + _, err = v.VerifySignature(context.Background(), identity, token, assertionTypes) + require.NoError(t, err) + require.Empty(t, store.saved) + + failing = true + f.now = f.now.Add(keyCacheTTL + time.Second) + _, err = v.VerifySignature(context.Background(), identity, token, assertionTypes) + require.ErrorIs(t, err, ErrUnavailable) + require.Zero(t, store.loads) +} + +// The JWT library checks an ECDSA signature's width against the algorithm +// and verifies it on the key's own curve. A token must not name one curve's +// algorithm while being signed on another, or the rest of the server would +// reason about its signature on the wrong curve. +func TestKeyMustBeOnTheCurveOfTheAlgorithm(t *testing.T) { + f := newAuthorizationServerFixture(t) + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + // Published without an algorithm, so only its curve can rule out ES512. + published, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "key-a", Use: "sig"}}}) + require.NoError(t, err) + v := NewVerifier() + v.now = func() time.Time { return f.now } + v.fetch = func(context.Context, IssuerSpec) ([]byte, error) { return published, nil } + + encode := base64.RawURLEncoding.EncodeToString + payload, err := json.Marshal(map[string]any{"iss": f.spec.IssuerURL, "sub": "federation:ci", "aud": "prod", "iat": f.now.Unix(), "exp": f.now.Add(time.Hour).Unix()}) + require.NoError(t, err) + sign := func(algorithm string, width int) string { + input := encode([]byte(`{"alg":"`+algorithm+`","kid":"key-a","typ":"at+jwt"}`)) + "." + encode(payload) + hash := sha256.Sum256([]byte(input)) + digest := hash[:] + if algorithm == "ES512" { + long := sha512.Sum512([]byte(input)) + digest = long[:] + } + r, s, err := ecdsa.Sign(rand.Reader, key, digest) + require.NoError(t, err) + signature := make([]byte, 2*width) + r.FillBytes(signature[:width]) + s.FillBytes(signature[width:]) + return input + "." + encode(signature) + } + + _, err = v.VerifySignature(context.Background(), f.spec, sign("ES256", 32), accessTokenTypes) + require.NoError(t, err) + + mislabelled := sign("ES512", 66) + _, err = jwt.Parse(mislabelled, func(*jwt.Token) (any, error) { return &key.PublicKey, nil }, jwt.WithValidMethods([]string{"ES512"}), jwt.WithTimeFunc(func() time.Time { return f.now })) + require.NoError(t, err, "the library alone accepts it, otherwise the test proves nothing") + _, err = v.VerifySignature(context.Background(), f.spec, mislabelled, accessTokenTypes) + require.ErrorIs(t, err, ErrAssertion) +} + +func TestKeyFitsItsAlgorithm(t *testing.T) { + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + p384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + require.NoError(t, err) + edKey, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + fits := map[string][]string{} + for _, algorithm := range []string{"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA", "HS256", "none"} { + for name, key := range map[string]any{"rsa": &rsaKey.PublicKey, "p384": &p384.PublicKey, "ed25519": edKey, "secret": []byte("secret")} { + if keyFits(key, algorithm) { + fits[name] = append(fits[name], algorithm) + } + } + } + require.Equal(t, map[string][]string{"rsa": {"RS256", "RS384", "RS512", "PS256", "PS384", "PS512"}, "p384": {"ES384"}, "ed25519": {"EdDSA"}}, fits) +} + +// A key set with no signing key withdraws the server's keys only when every +// entry is a valid public key whose usage plainly names another purpose. +// Anything less certain is a failed fetch. +func TestOnlyValidKeysForAnotherPurposeWithdraw(t *testing.T) { + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + raw, err := json.Marshal(jose.JSONWebKey{Key: &rsaKey.PublicKey, KeyID: "key-1"}) + require.NoError(t, err) + // entry is the public key with the given usage members added. + entry := func(usage string) string { + return strings.Replace(string(raw), "{", "{"+usage+",", 1) + } + set := func(entries ...string) []byte { return []byte(`{"keys":[` + strings.Join(entries, ",") + `]}`) } + + for _, usage := range []string{ + `"use":"enc"`, + `"key_ops":["encrypt"]`, + `"key_ops":["encrypt","wrapKey"]`, + `"use":"enc","key_ops":["encrypt","wrapKey"]`, + `"use":"enc","key_ops":[]`, + `"key_ops":["decrypt","unwrapKey","deriveKey","deriveBits"]`, + } { + _, err := parseKeySet(set(entry(usage))) + require.ErrorIs(t, err, errNoSigningKeys, usage) + } + _, err = parseKeySet(set()) + require.ErrorIs(t, err, errNoSigningKeys) + + for _, usage := range []string{ + // The usage is missing, malformed, misspelt or says nothing. + `"use":""`, + `"use":"Sig"`, + `"use":"encryption"`, + `"key_ops":["Verify"]`, + `"key_ops":["encrypt","unknown"]`, + `"key_ops":[]`, + `"key_ops":null`, + `"use":"enc","key_ops":null`, + `"use":"enc","key_ops":"encrypt"`, + `"use":"enc","key_ops":[1]`, + // The usage contradicts itself, or is for signatures after all. + `"use":"enc","key_ops":["verify"]`, + `"use":"enc","key_ops":["sign"]`, + `"use":"enc","key_ops":["encrypt","verify"]`, + `"use":"sig","key_ops":["encrypt"]`, + `"use":"sig","key_ops":["sign"]`, + `"key_ops":["sign"]`, + } { + _, err := parseKeySet(set(entry(usage))) + require.ErrorIs(t, err, ErrInvalid, usage) + require.NotErrorIs(t, err, errNoSigningKeys, usage) + } + + // None of this changes which keys a mixed set yields: the signing key is + // used and the other entry is passed over, whatever its usage says. + signing := strings.Replace(entry(`"use":"sig"`), `"kid":"key-1"`, `"kid":"key-2"`, 1) + for _, usage := range []string{`"use":"enc"`, `"use":"enc","key_ops":null`, `"use":"enc","key_ops":["verify"]`, `"key_ops":["sign"]`, `"key_ops":null`, `"use":""`} { + keys, err := parseKeySet(set(entry(usage), signing)) + require.NoError(t, err, usage) + require.Len(t, keys, 1, usage) + require.Equal(t, "key-2", keys[0].KeyID) + } +} diff --git a/lib/oidcfederation/issuer.go b/lib/oidcfederation/issuer.go index 8ffd7b126..d51b8c166 100644 --- a/lib/oidcfederation/issuer.go +++ b/lib/oidcfederation/issuer.go @@ -125,6 +125,23 @@ func normalizeIssuer(out IssuerSpec) (IssuerSpec, error) { return out, nil } +// AuthorizationServer describes an OAuth authorization server whose access +// tokens a resource server verifies. It differs from an identity issuer in two +// ways: its metadata is read from the RFC 8414 location, and its last key set +// stays in use while a refresh fails, because every request to the resource +// server depends on those keys. +func AuthorizationServer(issuerURL string, keys KeySource) (IssuerSpec, error) { + spec, err := normalizeIssuer(IssuerSpec{Name: "authorization-server", IssuerURL: issuerURL, PresetType: "custom_oidc", JWKS: keys}) + if err != nil { + return spec, err + } + if spec.JWKS.DiscoveryBaseURL != "" { + return spec, fmt.Errorf("%w: an authorization server publishes its own metadata", ErrInvalid) + } + spec.authorizationServer = true + return spec, nil +} + // entraTenant returns the tenant an Entra v1 or v2 issuer URL names. func entraTenant(issuerURL string) string { groups := entraIssuer.FindStringSubmatch(issuerURL) diff --git a/lib/oidcfederation/keyfetch.go b/lib/oidcfederation/keyfetch.go index 18e90622c..d8745095b 100644 --- a/lib/oidcfederation/keyfetch.go +++ b/lib/oidcfederation/keyfetch.go @@ -14,6 +14,7 @@ import ( "net" "net/http" "net/netip" + "net/url" "strings" "time" ) @@ -205,6 +206,23 @@ func fetchKeyDocument(ctx context.Context, client *http.Client, endpoint string) return body, nil } +// metadataURL is where an issuer publishes the document naming its key set. +// OpenID Connect discovery appends a suffix to the issuer URL. RFC 8414 puts +// an authorization server's suffix between the host and the path. +func metadataURL(issuer IssuerSpec) string { + if issuer.authorizationServer { + if parsed, err := url.Parse(issuer.IssuerURL); err == nil { + parsed.Path = "/.well-known/oauth-authorization-server" + strings.TrimRight(parsed.Path, "/") + return parsed.String() + } + } + base := issuer.IssuerURL + if issuer.JWKS.DiscoveryBaseURL != "" { + base = issuer.JWKS.DiscoveryBaseURL + } + return strings.TrimRight(base, "/") + "/.well-known/openid-configuration" +} + func fetchIssuerKeys(ctx context.Context, issuer IssuerSpec) ([]byte, error) { if issuer.JWKS.Type == "inline" { return json.Marshal(map[string]any{"keys": issuer.JWKS.Keys}) @@ -216,11 +234,7 @@ func fetchIssuerKeys(ctx context.Context, issuer IssuerSpec) ([]byte, error) { 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") + raw, err := fetchKeyDocument(ctx, client, metadataURL(issuer)) if err != nil { return nil, err } diff --git a/lib/oidcfederation/model.go b/lib/oidcfederation/model.go index 1038eb6b2..2dbc0d553 100644 --- a/lib/oidcfederation/model.go +++ b/lib/oidcfederation/model.go @@ -56,6 +56,10 @@ type IssuerSpec struct { PresetType string `koanf:"preset_type" json:"preset_type,omitempty"` JWKS KeySource `koanf:"jwks" json:"jwks"` TokenValidation TokenValidation `koanf:"token_validation" json:"token_validation"` + + // authorizationServer marks an OAuth authorization server, as + // AuthorizationServer returns it. + authorizationServer bool } // Match contains conditions that must all hold on verified identity claims. diff --git a/lib/oidcfederation/verifier.go b/lib/oidcfederation/verifier.go index 94fb51099..08ac96418 100644 --- a/lib/oidcfederation/verifier.go +++ b/lib/oidcfederation/verifier.go @@ -6,13 +6,16 @@ import ( "context" "crypto/ecdsa" "crypto/ed25519" + "crypto/elliptic" "crypto/rsa" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" + "fmt" "io" + "log/slog" "slices" "strings" "sync" @@ -49,6 +52,9 @@ type cachedKeys struct { refreshAfter time.Time // failure is what the last load reported, returned again until failureUntil. failure error + // restored is set once the stored copy of an authorization server's key + // set has been looked for. + restored bool } type keyLoad struct { @@ -57,18 +63,43 @@ type keyLoad struct { err error } -// Verifier bounds issuer key fetching and validates the supported OIDC assertion profile. +// KeyStore keeps the last key set fetched from an authorization server and +// the time of that fetch, so that a restarted server continues with the cache +// it had. +// A copy that is missing or unreadable is simply not used. The id names one +// issuer URL together with its configured key source, so a copy is not reused +// after either changes; the issuer URL is for the store's own reporting. +type KeyStore interface { + Save(id, issuerURL string, keySet []byte) + Load(id string) ([]byte, bool) +} + +// Verifier bounds issuer key fetching and validates the supported token profiles. 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 + store KeyStore + log *slog.Logger } // 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} + return &Verifier{cache: make(map[string]cachedKeys), loading: make(map[string]*keyLoad), fetch: fetchIssuerKeys, now: time.Now, log: slog.New(slog.DiscardHandler)} +} + +// NewVerifierWithKeyStore is NewVerifier for a resource server: store keeps +// the key sets of authorization servers between starts, and log is told when +// one of them cannot be refreshed. Either may be nil. +func NewVerifierWithKeyStore(store KeyStore, log *slog.Logger) *Verifier { + v := NewVerifier() + v.store = store + if log != nil { + v.log = log + } + return v } func keyCacheKey(issuer IssuerSpec) string { @@ -99,21 +130,30 @@ func (v *Verifier) keySet(ctx context.Context, issuer IssuerSpec, force bool) ([ now := v.now() v.mu.Lock() entry := v.cache[key] + if issuer.authorizationServer && !entry.restored { + entry = v.restoreLocked(key, issuer, entry, now) + } if now.Before(entry.expiresAt) && !force { v.mu.Unlock() return entry.keys, nil } + // An authorization server's last key set keeps answering while a refresh + // runs or fails. Only a key ID it does not hold waits for one, and shares + // that refresh's outcome: the last key set is no answer for it. + retained := issuer.authorizationServer && !force && entry.keys != nil load, loading := v.loading[key] if !loading { - if now.Before(entry.failureUntil) { + switch { + case now.Before(entry.failureUntil) && retained, len(v.loading) >= maxKeyLoads && retained: + v.mu.Unlock() + return entry.keys, nil + case now.Before(entry.failureUntil): v.mu.Unlock() return nil, cmp.Or(entry.failure, ErrUnavailable) - } - if force && now.Before(entry.refreshAfter) { + case force && now.Before(entry.refreshAfter): v.mu.Unlock() return entry.keys, nil - } - if len(v.loading) >= maxKeyLoads { + case len(v.loading) >= maxKeyLoads: v.mu.Unlock() return nil, ErrUnavailable } @@ -126,6 +166,9 @@ func (v *Verifier) keySet(ctx context.Context, issuer IssuerSpec, force bool) ([ go v.loadKeys(key, issuer, load, now) } v.mu.Unlock() + if retained { + return entry.keys, nil + } select { case <-ctx.Done(): return nil, ctx.Err() @@ -134,16 +177,80 @@ func (v *Verifier) keySet(ctx context.Context, issuer IssuerSpec, force bool) ([ } } +// savedKeySet is an authorization server's key set as a KeyStore keeps it: +// the public keys and when they were fetched, which is what a cache entry +// consists of. +type savedKeySet struct { + FetchedAt time.Time `json:"fetched_at"` + Keys []jose.JSONWebKey `json:"keys"` +} + +// restoreLocked continues an authorization server's cache entry from the +// stored copy of its key set, as if the server had not restarted: a copy +// fetched within the cache lifetime is used until that lifetime ends, and an +// older one is used while the set is fetched again. The copy is read with the +// lock held, once for each issuer. +func (v *Verifier) restoreLocked(key string, issuer IssuerSpec, entry cachedKeys, now time.Time) cachedKeys { + entry.restored = true + if v.store != nil && issuer.JWKS.Type != "inline" && entry.keys == nil { + if copied, ok := v.store.Load(key); ok { + if keys, err := parseAuthorizationServerKeySet(copied); err == nil { + entry.keys = keys + // A fetch time that is missing, or later than now because a + // clock was wrong, leaves the copy due for a refresh at once. + var saved struct { + FetchedAt time.Time `json:"fetched_at"` + } + if json.Unmarshal(copied, &saved) == nil && !saved.FetchedAt.IsZero() && !saved.FetchedAt.After(now) { + entry.expiresAt = saved.FetchedAt.Add(keyCacheTTL) + } + v.log.Info("authorization server keys restored from the saved copy", "issuer", issuer.IssuerURL, "fetched_at", saved.FetchedAt, "refresh_due", !now.Before(entry.expiresAt)) + } + } + } + v.putLocked(key, entry) + return entry +} + +// parseAuthorizationServerKeySet reads a key set in which no signing key is +// an answer, not an error: the server has withdrawn every key it had. The +// result is then empty and not nil. +func parseAuthorizationServerKeySet(raw []byte) ([]jose.JSONWebKey, error) { + keys, err := parseKeySet(raw) + if errors.Is(err, errNoSigningKeys) { + return []jose.JSONWebKey{}, nil + } + return keys, 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 { + if issuer.authorizationServer { + keys, err = parseAuthorizationServerKeySet(raw) + } else { + keys, err = parseKeySet(raw) + } + if err != nil { err = &KeyProblem{"the key set is not valid or holds an unsupported key"} } } + if err == nil && v.store != nil && issuer.authorizationServer && issuer.JWKS.Type != "inline" { + if public, marshalErr := json.Marshal(savedKeySet{FetchedAt: startedAt.UTC(), Keys: keys}); marshalErr == nil { + v.store.Save(key, issuer.IssuerURL, public) + } + } + // Deferred first, so that it runs after the lock is released. + var failure error + lastKeySetInUse := false + defer func() { + if failure != nil && issuer.authorizationServer { + v.log.Warn("authorization server keys could not be fetched", "issuer", issuer.IssuerURL, "error", failure, "last_key_set_in_use", lastKeySetInUse) + } + }() v.mu.Lock() defer v.mu.Unlock() entry := v.cache[key] @@ -157,6 +264,7 @@ func (v *Verifier) loadKeys(key string, issuer IssuerSpec, load *keyLoad, starte load.err = problem } entry.failure = load.err + failure, lastKeySetInUse = load.err, entry.keys != nil } else { entry.keys = keys entry.expiresAt = startedAt.Add(keyCacheTTL) @@ -168,78 +276,96 @@ func (v *Verifier) loadKeys(key string, issuer IssuerSpec, load *keyLoad, starte 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 +// assertionTypes are the `typ` headers an identity assertion may carry. It may +// also carry none. +var assertionTypes = []string{"", "JWT", "application/jwt"} + +// verifySigned checks a token's shape, type, issuer and algorithm before any +// key is fetched, then its signature and its time claims. +func (v *Verifier) verifySigned(ctx context.Context, spec IssuerSpec, raw string, types []string, options ...jwt.ParserOption) (jwt.MapClaims, error) { + if spec.Name == "" || len(raw) > MaxAssertionBytes { + return nil, ErrAssertion } parts := strings.Split(raw, ".") if len(parts) != 3 { - return Assertion{}, ErrAssertion + return nil, ErrAssertion } header, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil || !uniqueJSONObject(header) { - return Assertion{}, ErrAssertion + return nil, ErrAssertion } payload, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil || !uniqueJSONObject(payload) { - return Assertion{}, ErrAssertion + return nil, ErrAssertion } var protected struct{ Algorithm, KeyID, Type string } var fields map[string]json.RawMessage if json.Unmarshal(header, &fields) != nil { - return Assertion{}, ErrAssertion + return nil, ErrAssertion } if _, critical := fields["crit"]; critical { - return Assertion{}, ErrAssertion + return nil, 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 + return nil, ErrAssertion } } } - if len(protected.KeyID) > 256 || (protected.Type != "" && !strings.EqualFold(protected.Type, "JWT") && !strings.EqualFold(protected.Type, "application/jwt")) { - return Assertion{}, ErrAssertion + if len(protected.KeyID) > 256 || !slices.ContainsFunc(types, func(allowed string) bool { return strings.EqualFold(allowed, protected.Type) }) { + return nil, ErrAssertion } var unverified map[string]json.RawMessage if json.Unmarshal(payload, &unverified) != nil { - return Assertion{}, ErrAssertion + return nil, ErrAssertion } var claimedIssuer string if json.Unmarshal(unverified["iss"], &claimedIssuer) != nil || claimedIssuer != spec.IssuerURL { - return Assertion{}, ErrAssertion + return nil, 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 + return nil, ErrAssertion } keys, err := v.keySet(ctx, spec, false) if err != nil { - return Assertion{}, err + return nil, err } key, ok := matchingKey(keys, protected.KeyID, protected.Algorithm) if !ok { keys, err = v.keySet(ctx, spec, true) if err != nil { - return Assertion{}, err + return nil, err } key, ok = matchingKey(keys, protected.KeyID, protected.Algorithm) if !ok { - return Assertion{}, ErrAssertion + return nil, 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()) + options = append([]jwt.ParserOption{jwt.WithValidMethods(algorithms), jwt.WithIssuer(spec.IssuerURL), jwt.WithExpirationRequired(), jwt.WithIssuedAt(), jwt.WithLeeway(clockLeeway), jwt.WithTimeFunc(v.now), jwt.WithJSONNumber()}, options...) + token, err := jwt.ParseWithClaims(raw, claims, func(*jwt.Token) (any, error) { return key.Key, nil }, options...) if err != nil || token == nil || !token.Valid { + return nil, ErrAssertion + } + return claims, nil +} + +// 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.TokenValidation.MaxLifetimeSeconds == nil || audience == "" || len(audience) > 2048 { return Assertion{}, ErrAssertion } + claims, err := v.verifySigned(ctx, spec, raw, assertionTypes, jwt.WithAudience(audience)) + if err != nil { + return Assertion{}, err + } subject, subjectOK := claims["sub"].(string) expires, expErr := claims.GetExpirationTime() issued, iatErr := claims.GetIssuedAt() @@ -261,11 +387,37 @@ func (v *Verifier) Verify(ctx context.Context, spec IssuerSpec, audience, raw st return Assertion{Subject: subject, JTI: jti, IssuedAt: issued.Time, ExpiresAt: expires.Time, Claims: map[string]any(claims), SingleUse: singleUse}, nil } +// VerifySignature accepts a compact JWT that spec's issuer signed and that has +// not expired, carrying one of the given `typ` headers; "" allows the header +// to be absent. It applies no audience, subject or lifetime rule. Verify does +// that for identity assertions, and a caller with another token profile +// applies its own to the returned claims. +func (v *Verifier) VerifySignature(ctx context.Context, spec IssuerSpec, raw string, types []string) (map[string]any, error) { + return v.verifySigned(ctx, spec, raw, types) +} + +// keyFits reports whether key is of the kind algorithm signs with, and for +// ECDSA on its curve. The JWT library checks an ECDSA signature's width +// against the algorithm but verifies it on whatever curve the key has, so +// without this a token could name one curve's algorithm and be signed on another. +func keyFits(key any, algorithm string) bool { + switch public := key.(type) { + case *rsa.PublicKey: + return strings.HasPrefix(algorithm, "RS") || strings.HasPrefix(algorithm, "PS") + case *ecdsa.PublicKey: + curve, known := map[string]elliptic.Curve{"ES256": elliptic.P256(), "ES384": elliptic.P384(), "ES512": elliptic.P521()}[algorithm] + return known && public.Curve == curve + case ed25519.PublicKey: + return algorithm == "EdDSA" + } + return false +} + 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) { + if (kid != "" && key.KeyID != kid) || (kid == "" && len(keys) != 1) || (key.Algorithm != "" && key.Algorithm != algorithm) || !keyFits(key.Key, algorithm) { continue } if matched != nil { @@ -279,6 +431,10 @@ func matchingKey(keys []jose.JSONWebKey, kid, algorithm string) (jose.JSONWebKey return *matched, true } +// errNoSigningKeys is ErrInvalid for a well-formed key set in which every +// entry, if there is any, is a valid public key for a purpose other than signing. +var errNoSigningKeys = fmt.Errorf("%w: the key set holds no signing key", ErrInvalid) + func parseKeySet(raw []byte) ([]jose.JSONWebKey, error) { if len(raw) > maxKeyDocumentBytes || !uniqueJSONObject(raw) { return nil, ErrInvalid @@ -288,80 +444,113 @@ func parseKeySet(raw []byte) ([]jose.JSONWebKey, error) { return nil, ErrInvalid } var entries []map[string]json.RawMessage - if json.Unmarshal(root["keys"], &entries) != nil || len(entries) == 0 || len(entries) > 16 { + if json.Unmarshal(root["keys"], &entries) != nil || entries == nil || len(entries) > 16 { return nil, ErrInvalid } keys := make([]jose.JSONWebKey, 0, len(entries)) seen := make(map[string]bool, len(entries)) + // skippedUnread is set when an entry was skipped that is not plainly a + // valid public key for another purpose. Such a set still yields its + // signing keys, but it is not taken as a statement that there are none. + skippedUnread := false 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. + signing := true if use, exists := entry["use"]; exists { var purpose string if json.Unmarshal(use, &purpose) != nil { return nil, ErrInvalid } - if purpose != "sig" { - continue - } + signing = purpose == "sig" } - if operations, exists := entry["key_ops"]; exists { + if operations, exists := entry["key_ops"]; exists && signing { 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 { + if signing = slices.Contains(ops, "verify"); signing && len(ops) != 1 { 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 + key, valid := publicKey(entry) + if !signing { + skippedUnread = skippedUnread || !valid || !forAnotherPurpose(entry) + continue } - 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: + if !valid || (key.Use != "" && key.Use != "sig") || len(key.KeyID) > 256 || seen[key.KeyID] { return nil, ErrInvalid } seen[key.KeyID] = true keys = append(keys, key) } - if len(keys) == 0 { + if len(keys) == 0 && skippedUnread { return nil, ErrInvalid } + if len(keys) == 0 { + return nil, errNoSigningKeys + } return keys, nil } +// otherOperations are the registered key operations that have nothing to do +// with signatures. +var otherOperations = []string{"encrypt", "decrypt", "wrapKey", "unwrapKey", "deriveKey", "deriveBits"} + +// forAnotherPurpose reports whether a skipped entry says, in registered terms +// and without contradicting itself, that its key is for something other than +// signatures: the use "enc", or operations that are all of the other kind. +// A misspelt or unknown value says nothing. +func forAnotherPurpose(entry map[string]json.RawMessage) bool { + use, hasUse := entry["use"] + operations, hasOperations := entry["key_ops"] + if hasUse { + var purpose string + if json.Unmarshal(use, &purpose) != nil || purpose != "enc" { + return false + } + } + if hasOperations { + var ops []string + if json.Unmarshal(operations, &ops) != nil || ops == nil || (len(ops) == 0 && !hasUse) || + slices.ContainsFunc(ops, func(op string) bool { return !slices.Contains(otherOperations, op) }) { + return false + } + } + return hasUse || hasOperations +} + +// publicKey decodes one JWK entry and reports whether it is a public key of +// a supported kind with sound key material, whatever it is published for. +func publicKey(entry map[string]json.RawMessage) (jose.JSONWebKey, bool) { + var key jose.JSONWebKey + for _, private := range []string{"d", "p", "q", "dp", "dq", "qi", "oth", "k"} { + if _, exists := entry[private]; exists { + return key, false + } + } + 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 || json.Unmarshal(encoded, &key) != nil || !key.Valid() || !key.IsPublic() { + return key, false + } + switch public := key.Key.(type) { + case *rsa.PublicKey: + return key, public.N.Sign() > 0 && public.N.BitLen() >= 2048 && public.N.BitLen() <= 8192 && public.N.Bit(0) == 1 && public.E >= 3 && public.E%2 == 1 + case *ecdsa.PublicKey: + return key, public.Curve.IsOnCurve(public.X, public.Y) + case ed25519.PublicKey: + return key, len(public) == ed25519.PublicKeySize + } + return key, false +} + func decodeDiscovery(raw []byte) (struct{ Issuer, JWKSURI string }, error) { var result struct{ Issuer, JWKSURI string } if !uniqueJSONObject(raw) { diff --git a/lib/paths/paths.go b/lib/paths/paths.go index 648e7dcc4..15cdb9d28 100644 --- a/lib/paths/paths.go +++ b/lib/paths/paths.go @@ -551,3 +551,9 @@ func (p *Paths) BuildSourceDir(id string) string { func (p *Paths) BuildConfig(id string) string { return filepath.Join(p.BuildDir(id), "config.json") } + +// OAuthKeysDir returns the directory holding the last key set fetched from +// each configured authorization server. +func (p *Paths) OAuthKeysDir() string { + return filepath.Join(p.dataDir, "oauth", "keys") +} diff --git a/lib/tokenrevocation/revocation.go b/lib/tokenrevocation/revocation.go index d2ea28bf5..db4fb3c22 100644 --- a/lib/tokenrevocation/revocation.go +++ b/lib/tokenrevocation/revocation.go @@ -2,14 +2,18 @@ // // Tokens are identified by the hex SHA-256 of the raw token string, so // revoking a token does not require it to carry a jti claim and the -// configuration never holds a usable credential. +// configuration never holds a usable credential. Revoking a token also +// revokes every other spelling of it that would verify. package tokenrevocation import ( + "crypto/elliptic" "crypto/sha256" "encoding/base64" "encoding/hex" + "encoding/json" "fmt" + "math/big" "strings" ) @@ -61,13 +65,64 @@ func canonicalize(token string) string { return token[:i+1] + base64.RawURLEncoding.EncodeToString(sig) } -// IsRevoked reports whether the raw token string has been revoked. +// ecdsaTwin returns the other token that carries the same ECDSA signature. +// For a signature (r, s), (r, n-s) verifies as well, where n is the order of +// the curve, so anyone holding an ECDSA-signed token can write a second token +// string that is just as valid. A token signed any other way has no twin. +// +// The algorithm is read from the unverified header. A holder cannot use that +// to hide the twin: the header is part of the signing input, so a token with +// a changed header does not verify. +func ecdsaTwin(token string) (string, bool) { + encodedHeader, _, _ := strings.Cut(token, ".") + rawHeader, err := base64.RawURLEncoding.DecodeString(encodedHeader) + // The member is looked up by its exact name, as verification does: a + // struct field would also match "ALG". + var header map[string]json.RawMessage + var algorithm string + if err != nil || json.Unmarshal(rawHeader, &header) != nil || json.Unmarshal(header["alg"], &algorithm) != nil { + return "", false + } + var curve elliptic.Curve + switch algorithm { + case "ES256": + curve = elliptic.P256() + case "ES384": + curve = elliptic.P384() + case "ES512": + curve = elliptic.P521() + default: + return "", false + } + i := strings.LastIndexByte(token, '.') + signature, err := base64.RawURLEncoding.DecodeString(token[i+1:]) + size := (curve.Params().BitSize + 7) / 8 + if err != nil || len(signature) != 2*size { + return "", false + } + order := curve.Params().N + s := new(big.Int).SetBytes(signature[size:]) + if s.Sign() <= 0 || s.Cmp(order) >= 0 { + return "", false + } + new(big.Int).Sub(order, s).FillBytes(signature[size:]) + return token[:i+1] + base64.RawURLEncoding.EncodeToString(signature), true +} + +// IsRevoked reports whether the token has been revoked: its own hash is +// listed, or that of the other token carrying the same ECDSA signature. func (l *List) IsRevoked(token string) bool { if l == nil || len(l.hashes) == 0 { return false } - _, ok := l.hashes[Hash(token)] - return ok + if _, ok := l.hashes[Hash(token)]; ok { + return true + } + if twin, ok := ecdsaTwin(token); ok { + _, ok = l.hashes[Hash(twin)] + return ok + } + return false } // Len returns the number of revoked token hashes. diff --git a/lib/tokenrevocation/revocation_test.go b/lib/tokenrevocation/revocation_test.go index 50d5ce632..7ed25018c 100644 --- a/lib/tokenrevocation/revocation_test.go +++ b/lib/tokenrevocation/revocation_test.go @@ -1,8 +1,13 @@ package tokenrevocation import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" "crypto/sha256" + "encoding/base64" "encoding/hex" + "math/big" "strings" "testing" @@ -73,3 +78,85 @@ func signedToken(t *testing.T) string { require.NoError(t, err) return token } + +// An ECDSA signature (r, s) verifies as (r, n-s) too, so every token signed +// that way has a second spelling its holder can compute. Revoking either +// revokes both. +func TestBothTokensOfAnECDSASignatureAreRevoked(t *testing.T) { + for _, tc := range []struct { + method *jwt.SigningMethodECDSA + curve elliptic.Curve + }{ + {jwt.SigningMethodES256, elliptic.P256()}, + {jwt.SigningMethodES384, elliptic.P384()}, + {jwt.SigningMethodES512, elliptic.P521()}, + } { + t.Run(tc.method.Alg(), func(t *testing.T) { + key, err := ecdsa.GenerateKey(tc.curve, rand.Reader) + require.NoError(t, err) + token, err := jwt.NewWithClaims(tc.method, jwt.MapClaims{"sub": "user"}).SignedString(key) + require.NoError(t, err) + + // Build the other token here, apart from the code under test. + i := strings.LastIndexByte(token, '.') + signature, err := base64.RawURLEncoding.DecodeString(token[i+1:]) + require.NoError(t, err) + half := len(signature) / 2 + s := new(big.Int).SetBytes(signature[half:]) + new(big.Int).Sub(tc.curve.Params().N, s).FillBytes(signature[half:]) + twin := token[:i+1] + base64.RawURLEncoding.EncodeToString(signature) + require.NotEqual(t, token, twin) + for _, spelling := range []string{token, twin} { + _, err = jwt.Parse(spelling, func(*jwt.Token) (interface{}, error) { return &key.PublicKey, nil }) + require.NoError(t, err, "both must verify, otherwise the test proves nothing") + } + require.NotEqual(t, Hash(token), Hash(twin)) + + for _, listed := range []string{token, twin} { + l, err := New([]string{Hash(listed)}) + require.NoError(t, err) + assert.True(t, l.IsRevoked(token)) + assert.True(t, l.IsRevoked(twin)) + assert.True(t, l.IsRevoked(twin[:len(twin)-5]+"\n"+twin[len(twin)-5:]), "another spelling of the other token") + } + other, err := jwt.NewWithClaims(tc.method, jwt.MapClaims{"sub": "other"}).SignedString(key) + require.NoError(t, err) + l, err := New([]string{Hash(token)}) + require.NoError(t, err) + assert.False(t, l.IsRevoked(other)) + }) + } +} + +// The algorithm is the header member named exactly "alg", the one +// verification reads. Another capitalization beside it changes nothing. +func TestTheSecondFormFollowsTheExactAlgorithmMember(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + encode := base64.RawURLEncoding.EncodeToString + input := encode([]byte(`{"alg":"ES256","typ":"JWT","ALG":"HS256","Alg":"none"}`)) + "." + encode([]byte(`{"sub":"user"}`)) + signature, err := jwt.SigningMethodES256.Sign(input, key) + require.NoError(t, err) + token := input + "." + encode(signature) + _, err = jwt.Parse(token, func(*jwt.Token) (interface{}, error) { return &key.PublicKey, nil }, jwt.WithValidMethods([]string{"ES256"})) + require.NoError(t, err, "it must verify, otherwise the test proves nothing") + + twin, ok := ecdsaTwin(token) + require.True(t, ok) + _, err = jwt.Parse(twin, func(*jwt.Token) (interface{}, error) { return &key.PublicKey, nil }, jwt.WithValidMethods([]string{"ES256"})) + require.NoError(t, err) + l, err := New([]string{Hash(token)}) + require.NoError(t, err) + assert.True(t, l.IsRevoked(twin)) +} + +// Only an ECDSA signature has a second form. Other tokens are looked up by +// their own hash alone, whatever their header claims. +func TestOtherTokensHaveNoSecondForm(t *testing.T) { + _, ok := ecdsaTwin(signedToken(t)) + assert.False(t, ok) + for _, token := range []string{"", "revoked-token", "a.b.c", "e30.e30.", "eyJhbGciOiJFUzI1NiJ9", "eyJhbGciOiJFUzI1NiJ9.e30.AAAA"} { + _, ok := ecdsaTwin(token) + assert.False(t, ok, token) + } +}