From 36e718f09e11ca75ed18e9ae596d64ada3b7e800 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:52:12 +0000 Subject: [PATCH 1/3] Add hypeman-auth, the OAuth authorization server hypeman-auth exchanges a workload's OIDC identity token for a short-lived access token that Hypeman servers verify with its public keys. It is a separate binary, so a Hypeman server holds no key that can issue a token. The token endpoint is the RFC 7523 JWT bearer grant, with the audience named as in RFC 8707. Tokens are signed with an ECDSA P-256 key in the RFC 9068 format hypeman-api accepts, and the keys are published through RFC 8414 metadata. A federation rule now names the audiences a token may be issued for, and optionally the identity token claim that names the caller. Single-use identity tokens are recorded by one insert in a PostgreSQL table shared by every instance, so several instances can run and a restart loses nothing. --- cmd/auth/Dockerfile | 12 ++ cmd/auth/config/config.go | 141 +++++++++++++ cmd/auth/config/config_test.go | 173 ++++++++++++++++ cmd/auth/main.go | 144 +++++++++++++ docs/authorization-server.md | 149 ++++++++++++++ docs/oauth-access-tokens.md | 3 +- go.mod | 4 + go.sum | 8 + lib/authserver/README.md | 13 ++ lib/authserver/exchange.go | 236 ++++++++++++++++++++++ lib/authserver/exchange_test.go | 334 +++++++++++++++++++++++++++++++ lib/authserver/handler.go | 163 +++++++++++++++ lib/authserver/handler_test.go | 129 ++++++++++++ lib/authserver/keys.go | 106 ++++++++++ lib/authserver/keys_test.go | 100 +++++++++ lib/authserver/store.go | 117 +++++++++++ lib/authserver/store_test.go | 125 ++++++++++++ lib/oidcfederation/README.md | 4 +- lib/oidcfederation/model.go | 9 +- lib/oidcfederation/model_test.go | 16 +- lib/oidcfederation/registry.go | 14 ++ lib/oidcfederation/rule.go | 14 ++ 22 files changed, 2007 insertions(+), 7 deletions(-) create mode 100644 cmd/auth/Dockerfile create mode 100644 cmd/auth/config/config.go create mode 100644 cmd/auth/config/config_test.go create mode 100644 cmd/auth/main.go create mode 100644 docs/authorization-server.md create mode 100644 lib/authserver/README.md create mode 100644 lib/authserver/exchange.go create mode 100644 lib/authserver/exchange_test.go create mode 100644 lib/authserver/handler.go create mode 100644 lib/authserver/handler_test.go create mode 100644 lib/authserver/keys.go create mode 100644 lib/authserver/keys_test.go create mode 100644 lib/authserver/store.go create mode 100644 lib/authserver/store_test.go diff --git a/cmd/auth/Dockerfile b/cmd/auth/Dockerfile new file mode 100644 index 000000000..bc78020a7 --- /dev/null +++ b/cmd/auth/Dockerfile @@ -0,0 +1,12 @@ +# Build from the repository root: docker build -f cmd/auth/Dockerfile -t hypeman-auth . +FROM golang:1.26 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -trimpath -o /hypeman-auth ./cmd/auth + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /hypeman-auth /hypeman-auth +EXPOSE 8080 +ENTRYPOINT ["/hypeman-auth"] diff --git a/cmd/auth/config/config.go b/cmd/auth/config/config.go new file mode 100644 index 000000000..5a571f80a --- /dev/null +++ b/cmd/auth/config/config.go @@ -0,0 +1,141 @@ +// Package config loads the configuration of hypeman-auth. +package config + +import ( + "encoding/json" + "errors" + "fmt" + "os" + + "github.com/go-viper/mapstructure/v2" + "github.com/kernel/hypeman/lib/oidcfederation" + "github.com/knadh/koanf/parsers/yaml" + "github.com/knadh/koanf/providers/file" + "github.com/knadh/koanf/providers/structs" + "github.com/knadh/koanf/v2" +) + +// Key names a PEM-encoded key, given inline or as the path of a file. +type Key struct { + PEM string `koanf:"pem"` + File string `koanf:"file"` +} + +// Read returns the PEM text of the key. +func (k Key) Read() ([]byte, error) { + switch { + case k.PEM != "" && k.File != "": + return nil, errors.New("give a key as pem or as file, not both") + case k.PEM != "": + return []byte(k.PEM), nil + case k.File != "": + return os.ReadFile(k.File) + } + return nil, errors.New("a key needs pem or file") +} + +// ReplayStore says where spent single-use identity tokens are recorded. +type ReplayStore struct { + // PostgresURL is a PostgreSQL connection string. Every instance of the + // server must use the same database. + PostgresURL string `koanf:"postgres_url"` +} + +// Config is the configuration of hypeman-auth. +type Config struct { + // Issuer is the server's issuer URL: the `iss` of its tokens and the URL + // under which its endpoints are reached. + Issuer string `koanf:"issuer"` + ListenAddress string `koanf:"listen_address"` + // MetricsListenAddress serves Prometheus metrics when set. It is a + // separate listener so that it need not be reachable from outside. + MetricsListenAddress string `koanf:"metrics_listen_address"` + + // SigningKey is the P-256 private key access tokens are signed with. + SigningKey Key `koanf:"signing_key"` + // PublishedKeys are P-256 public keys published beside the signing key. + PublishedKeys []Key `koanf:"published_keys"` + + ReplayStore ReplayStore `koanf:"replay_store"` + // OIDC holds the trusted identity issuers and the federation rules. + OIDC oidcfederation.Config `koanf:"oidc"` + // OtelEndpoint is the URL of an OTLP gRPC collector that metrics are + // pushed to, such as http://collector:4317. Empty turns the push off. + OtelEndpoint string `koanf:"otel_endpoint"` +} + +// environment maps the environment variables that override the file to their +// keys. Only these are read: the rest of the environment is not configuration. +var environment = map[string]string{ + "ISSUER": "issuer", + "LISTEN_ADDRESS": "listen_address", + "METRICS_LISTEN_ADDRESS": "metrics_listen_address", + "SIGNING_KEY__PEM": "signing_key.pem", + "SIGNING_KEY__FILE": "signing_key.file", + "REPLAY_STORE__POSTGRES_URL": "replay_store.postgres_url", + "OTEL_ENDPOINT": "otel_endpoint", +} + +// structured are the environment variables that hold a JSON document and +// replace their block of the file as a whole. Merging would leave rules from +// the file trusting issuers the environment redefined. +var structured = map[string]string{ + "OIDC": "oidc", + "PUBLISHED_KEYS": "published_keys", +} + +// Load reads the YAML file at path, if path is not empty, and then the +// environment. A key the configuration does not know is an error wherever it +// appears, and so is a number or boolean written where text belongs: a +// misspelled restriction would otherwise be dropped and leave its rule wider +// than written, and a number written for a text value such as an account ID +// could be rounded on the way in. The file is checked on its own first, so +// that its mistakes show even in blocks the environment then replaces. +func Load(path string) (*Config, error) { + k := koanf.New(".") + if err := k.Load(structs.Provider(Config{ListenAddress: ":8080"}, "koanf"), nil); err != nil { + return nil, fmt.Errorf("load default config: %w", err) + } + if path != "" { + if err := k.Load(file.Provider(path), yaml.Parser()); err != nil { + return nil, fmt.Errorf("load config from %s: %w", path, err) + } + if _, err := decode(k); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + } + for name, key := range environment { + if value := os.Getenv(name); value != "" { + if err := k.Set(key, value); err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + } + } + for name, key := range structured { + value := os.Getenv(name) + if value == "" { + continue + } + var document any + if err := json.Unmarshal([]byte(value), &document); err != nil { + return nil, fmt.Errorf("%s must be a JSON document", name) + } + k.Delete(key) + if err := k.Set(key, document); err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + } + return decode(k) +} + +func decode(k *koanf.Koanf) (*Config, error) { + var cfg Config + if err := k.UnmarshalWithConf("", &cfg, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{ + TagName: "koanf", + ErrorUnused: true, + Result: &cfg, + }}); err != nil { + return nil, fmt.Errorf("invalid config: %w", err) + } + return &cfg, nil +} diff --git a/cmd/auth/config/config_test.go b/cmd/auth/config/config_test.go new file mode 100644 index 000000000..e7f960769 --- /dev/null +++ b/cmd/auth/config/config_test.go @@ -0,0 +1,173 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +const fileConfig = ` +issuer: https://auth.example.test +otel_endpoint: http://collector.example.test:4317 +signing_key: + file: /etc/hypeman-auth/signing-key.pem +published_keys: + - pem: previous +replay_store: + postgres_url: postgres://file +oidc: + issuers: + - name: github-actions + preset_type: github_actions + federation_rules: + - name: ci + issuer: github-actions + expected_audience: https://auth.example.test + match: + type: github_actions + repository_id: "12" + repository_owner_id: "34" + workflow: .github/workflows/test.yml + ref: refs/heads/main + authorization: + audiences: [https://hypeman.example.test] + permissions: [instance:read] + subject_claim: /actor +` + +func load(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 TestLoadFile(t *testing.T) { + cfg, err := load(t, fileConfig) + require.NoError(t, err) + require.Equal(t, "https://auth.example.test", cfg.Issuer) + require.Equal(t, ":8080", cfg.ListenAddress) + require.Empty(t, cfg.MetricsListenAddress) + require.Equal(t, Key{File: "/etc/hypeman-auth/signing-key.pem"}, cfg.SigningKey) + require.Equal(t, []Key{{PEM: "previous"}}, cfg.PublishedKeys) + require.Equal(t, "postgres://file", cfg.ReplayStore.PostgresURL) + require.Equal(t, "http://collector.example.test:4317", cfg.OtelEndpoint) + require.Len(t, cfg.OIDC.FederationRules, 1) + rule := cfg.OIDC.FederationRules[0] + require.Equal(t, "12", rule.Match.RepositoryID) + require.Equal(t, []string{"https://hypeman.example.test"}, rule.Authorization.Audiences) + require.Equal(t, "/actor", rule.Authorization.SubjectClaim) +} + +// A deployment without a file is configured by the environment alone, and +// the environment wins over a file. +func TestEnvironmentOverridesTheFile(t *testing.T) { + t.Setenv("ISSUER", "https://env.example.test") + t.Setenv("LISTEN_ADDRESS", ":9000") + t.Setenv("SIGNING_KEY__PEM", "from the environment") + t.Setenv("REPLAY_STORE__POSTGRES_URL", "postgres://env") + t.Setenv("OTEL_ENDPOINT", "https://env.example.test:4317") + t.Setenv("PUBLISHED_KEYS", `[{"pem":"one"},{"file":"/keys/two.pem"}]`) + t.Setenv("OIDC", `{"issuers":[{"name":"cluster","preset_type":"kubernetes","issuer_url":"https://cluster.example.test"}]}`) + // The rest of the environment is not configuration. + t.Setenv("HOME_DIRECTORY_OF_SOMETHING", "/tmp") + + for _, withFile := range []bool{false, true} { + cfg, err := Load("") + if withFile { + cfg, err = load(t, fileConfig) + } + require.NoError(t, err) + require.Equal(t, "https://env.example.test", cfg.Issuer) + require.Equal(t, ":9000", cfg.ListenAddress) + require.Equal(t, "from the environment", cfg.SigningKey.PEM) + require.Equal(t, "postgres://env", cfg.ReplayStore.PostgresURL) + require.Equal(t, "https://env.example.test:4317", cfg.OtelEndpoint) + require.Equal(t, []Key{{PEM: "one"}, {File: "/keys/two.pem"}}, cfg.PublishedKeys) + // The block from the environment replaces the file's as a whole. + require.Len(t, cfg.OIDC.Issuers, 1) + require.Equal(t, "cluster", cfg.OIDC.Issuers[0].Name) + require.Empty(t, cfg.OIDC.FederationRules) + } +} + +func TestUnknownKeysAreErrors(t *testing.T) { + for _, body := range []string{ + "isuer: https://auth.example.test\n", + "replay_store:\n postgres: postgres://x\n", + "signing_key:\n path: /key.pem\n", + "oidc:\n federation_rules:\n - name: ci\n match:\n repository: kernel/hypeman\n", + "oidc:\n federation_rules:\n - name: ci\n authorization:\n audience: [prod]\n", + } { + _, err := load(t, body) + require.ErrorContains(t, err, "invalid config", body) + } + t.Setenv("OIDC", `{"rules":[]}`) + _, err := Load("") + require.ErrorContains(t, err, "invalid config") + t.Setenv("OIDC", `not json`) + _, err = Load("") + require.ErrorContains(t, err, "OIDC must be a JSON document") + + _, err = Load(filepath.Join(t.TempDir(), "missing.yaml")) + require.Error(t, err) + + // A mistake in the file shows even in a block the environment replaces. + t.Setenv("OIDC", `{"issuers":[]}`) + _, err = load(t, "oidc:\n isuers: []\n") + require.ErrorContains(t, err, "invalid config") +} + +// A value must have the type its key takes. A number written for a text +// value is not converted: 9007199254740993 would arrive as 9007199254740992 +// and the rule would name another account. +func TestValuesAreNotConvertedBetweenTypes(t *testing.T) { + rule := func(match, authorization string) string { + return `{"issuers":[{"name":"idp","issuer_url":"https://idp.example.test"}],"federation_rules":[{"name":"ci","issuer":"idp","expected_audience":"https://auth.example.test","match":{"type":"custom_oidc",` + match + `},"authorization":{"audiences":["prod"],"permissions":["instance:read"]` + authorization + `}}]}` + } + t.Setenv("OIDC", rule(`"subject":"9007199254740993"`, `,"max_token_ttl_seconds":120`)) + cfg, err := Load("") + require.NoError(t, err) + require.Equal(t, "9007199254740993", cfg.OIDC.FederationRules[0].Match.Subject) + require.Equal(t, 120, *cfg.OIDC.FederationRules[0].Authorization.MaxTokenTTLSeconds) + + for _, document := range []string{ + rule(`"subject":9007199254740993`, ""), + rule(`"subject":"build","claims":{"/account":9007199254740993}`, ""), + rule(`"subject":"build","claims":{"/verified":true}`, ""), + rule(`"subject":"build"`, `,"max_token_ttl_seconds":"120"`), + } { + t.Setenv("OIDC", document) + _, err := Load("") + require.ErrorContains(t, err, "invalid config", document) + } + t.Setenv("OIDC", "") + for _, body := range []string{ + "oidc:\n federation_rules:\n - name: ci\n match:\n repository_id: 12\n", + "oidc:\n federation_rules:\n - name: ci\n match:\n subject: 112345678901234567890\n", + "listen_address: 8080\n", + } { + _, err := load(t, body) + require.ErrorContains(t, err, "invalid config", body) + } + cfg, err = load(t, "oidc:\n federation_rules:\n - name: ci\n authorization:\n max_token_ttl_seconds: 120\n") + require.NoError(t, err) + require.Equal(t, 120, *cfg.OIDC.FederationRules[0].Authorization.MaxTokenTTLSeconds) +} + +func TestKeyRead(t *testing.T) { + path := filepath.Join(t.TempDir(), "key.pem") + require.NoError(t, os.WriteFile(path, []byte("from a file"), 0o600)) + encoded, err := Key{File: path}.Read() + require.NoError(t, err) + require.Equal(t, "from a file", string(encoded)) + encoded, err = Key{PEM: "inline"}.Read() + require.NoError(t, err) + require.Equal(t, "inline", string(encoded)) + for _, key := range []Key{{}, {PEM: "inline", File: path}, {File: filepath.Join(t.TempDir(), "missing.pem")}} { + _, err := key.Read() + require.Error(t, err) + } +} diff --git a/cmd/auth/main.go b/cmd/auth/main.go new file mode 100644 index 000000000..a087a90f6 --- /dev/null +++ b/cmd/auth/main.go @@ -0,0 +1,144 @@ +// Command hypeman-auth is the OAuth authorization server for Hypeman. It +// exchanges OIDC identity tokens for short-lived access tokens and publishes +// the keys Hypeman servers verify them with. +package main + +import ( + "context" + "crypto/ecdsa" + "errors" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/kernel/hypeman/cmd/auth/config" + "github.com/kernel/hypeman/lib/authserver" + "github.com/kernel/hypeman/lib/oidcfederation" + "github.com/kernel/hypeman/lib/otel" +) + +func main() { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + if err := run(log); err != nil { + log.Error("hypeman-auth stopped", "error", err) + os.Exit(1) + } +} + +func run(log *slog.Logger) error { + cfg, err := config.Load(os.Getenv("CONFIG_PATH")) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + telemetryConfig := otel.Config{ServiceName: "hypeman-auth"} + if cfg.OtelEndpoint != "" { + // Only the scheme, host and port reach the gRPC client, so anything + // else in the URL would be dropped without a word. + endpoint, err := url.Parse(cfg.OtelEndpoint) + if err != nil || endpoint.Hostname() == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || + endpoint.User != nil || strings.Trim(endpoint.EscapedPath(), "/") != "" || strings.ContainsAny(cfg.OtelEndpoint, "?#") { + return errors.New("otel_endpoint must be http or https with a host and an optional port, and nothing else") + } + telemetryConfig.Enabled, telemetryConfig.Endpoint, telemetryConfig.Insecure = true, endpoint.Host, endpoint.Scheme == "http" + } + telemetry, shutdownTelemetry, err := otel.Init(ctx, telemetryConfig) + if err != nil { + return fmt.Errorf("initialize telemetry: %w", err) + } + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = shutdownTelemetry(shutdownCtx) + }() + + encoded, err := cfg.SigningKey.Read() + if err != nil { + return fmt.Errorf("signing_key: %w", err) + } + key, err := authserver.ParseSigningKey(encoded) + if err != nil { + return fmt.Errorf("signing_key: %w", err) + } + var published []*ecdsa.PublicKey + for i, entry := range cfg.PublishedKeys { + encoded, err := entry.Read() + if err != nil { + return fmt.Errorf("published_keys[%d]: %w", i, err) + } + public, err := authserver.ParsePublicKey(encoded) + if err != nil { + return fmt.Errorf("published_keys[%d]: %w", i, err) + } + published = append(published, public) + } + rules, err := oidcfederation.Compile(cfg.OIDC) + if err != nil { + return err + } + options := authserver.Options{Issuer: cfg.Issuer, Key: key, PublishedKeys: published, Rules: rules, Meter: telemetry.Meter, Log: log} + if cfg.ReplayStore.PostgresURL != "" { + openCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + store, err := authserver.OpenPostgresStore(openCtx, cfg.ReplayStore.PostgresURL) + cancel() + if err != nil { + return err + } + defer store.Close() + go store.Cleanup(ctx, log) + options.Spent = store + } + server, err := authserver.New(options) + if err != nil { + return err + } + + // No route streams, so the whole request and response are bounded here. + // The token endpoint gives itself 20 seconds from the end of the request + // header, which the write deadline and the drain below leave room for. + api := &http.Server{ + Addr: cfg.ListenAddress, + Handler: server.Handler(), + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: time.Minute, + MaxHeaderBytes: 16 << 10, + } + servers := []*http.Server{api} + if cfg.MetricsListenAddress != "" { + mux := http.NewServeMux() + mux.Handle("GET /metrics", telemetry.MetricsHandler) + servers = append(servers, &http.Server{Addr: cfg.MetricsListenAddress, Handler: mux, ReadHeaderTimeout: 5 * time.Second}) + } + failed := make(chan error, len(servers)) + for _, s := range servers { + go func() { + if err := s.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + failed <- fmt.Errorf("listen on %s: %w", s.Addr, err) + } + }() + } + log.Info("hypeman-auth started", "issuer", cfg.Issuer, "listen_address", cfg.ListenAddress, "key_id", key.ID, "published_keys", len(published), "federation_rules", len(cfg.OIDC.FederationRules), "replay_store", options.Spent != nil) + + select { + case err = <-failed: + case <-ctx.Done(): + } + shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + for _, s := range servers { + if shutdownErr := s.Shutdown(shutdownCtx); shutdownErr != nil { + log.Warn("requests were still running when the server stopped", "listen_address", s.Addr, "error", shutdownErr) + } + } + return err +} diff --git a/docs/authorization-server.md b/docs/authorization-server.md new file mode 100644 index 000000000..4cd1535ad --- /dev/null +++ b/docs/authorization-server.md @@ -0,0 +1,149 @@ +# Authorization server + +`hypeman-auth` is an OAuth authorization server for Hypeman. A workload proves who it is with an +OIDC identity token it already has, from GitHub Actions, AWS, Google Cloud, Microsoft Entra, +Kubernetes or another OIDC issuer, and receives a short-lived access token. Hypeman servers verify +that token with the authorization server's public keys; see +[OAuth access tokens](oauth-access-tokens.md). No Hypeman server holds a key that can issue one. + +It is a separate program from `hypeman-api` and needs no hypervisor: `go build ./cmd/auth`, or +the image built by `cmd/auth/Dockerfile`. Several instances can run behind one address. + +## Configure + +Configuration comes from a YAML file named by `CONFIG_PATH`, from environment variables, or both; +the environment wins. A key that is not known is an error, and so is a number or `true` written +where text belongs: write IDs and other text values in quotes, because a bare number is not +converted. + +```yaml +issuer: https://auth.example.com +signing_key: + file: /etc/hypeman-auth/signing-key.pem +replay_store: + postgres_url: postgres://hypeman_auth:...@db.example.com:5432/hypeman_auth?sslmode=verify-full +oidc: + issuers: + - name: github-actions + preset_type: github_actions + federation_rules: + - name: ci-nightly + issuer: github-actions + expected_audience: https://auth.example.com + match: + type: github_actions + repository_id: "123" + repository_owner_id: "456" + workflow: .github/workflows/nightly.yml + ref: refs/heads/main + authorization: + audiences: [https://hypeman.example.com] + permissions: [instance:read, instance:write] +``` + +| Key | Environment | Meaning | +|---|---|---| +| `issuer` | `ISSUER` | The server's URL, without a path. It is the `iss` of every token and the address Hypeman servers are configured with, so it should not change. | +| `listen_address` | `LISTEN_ADDRESS` | Default `:8080`. The server speaks plain HTTP and expects TLS to end in front of it. | +| `metrics_listen_address` | `METRICS_LISTEN_ADDRESS` | Serves Prometheus metrics at `/metrics` on a separate listener. Off by default. | +| `signing_key.file`, `signing_key.pem` | `SIGNING_KEY__FILE`, `SIGNING_KEY__PEM` | The ECDSA P-256 private key tokens are signed with, as a PEM file or as PEM text. | +| `published_keys` | `PUBLISHED_KEYS` (JSON) | Public keys published beside the signing key; see [Rotate the signing key](#rotate-the-signing-key). | +| `replay_store.postgres_url` | `REPLAY_STORE__POSTGRES_URL` | A PostgreSQL database shared by every instance; see [Single use](#single-use). | +| `oidc` | `OIDC` (JSON) | The trusted identity issuers and the federation rules. From the environment it replaces the file's block as a whole. | +| `otel_endpoint` | `OTEL_ENDPOINT` | An OTLP gRPC collector to push metrics to, as scheme, host and optional port, such as `http://collector:4317`; `http` means without TLS. Off by default. | + +Create a signing key with `openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256`. + +### Issuers and rules + +An issuer says who signs identity tokens, and a rule says which workload of one issuer gets what. +Their checks are described in [`lib/oidcfederation`](../lib/oidcfederation/README.md). A rule's +`authorization` holds what this server adds: + +| Key | Meaning | +|---|---| +| `audiences` | The audiences a token may be issued for, each a name some Hypeman server lists in its `oauth.audiences`. Required. | +| `permissions` | The token's scope. Required, and never `*`. | +| `max_token_ttl_seconds` | Default 300, at most 600. A token never outlives the identity token it was issued for. | +| `subject_claim` | Optional JSON Pointer to the identity token claim that names the caller, such as `/email`. The token's subject is then `federation::`; without it, `federation:`. | + +`expected_audience` is the audience the workload asks its identity provider for. Use the +authorization server's own URL. + +## Get a token + +```sh +curl https://auth.example.com/oauth/token \ + --data-urlencode grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \ + --data-urlencode assertion="$IDENTITY_TOKEN" \ + --data-urlencode federation_rule_id=ci-nightly \ + --data-urlencode resource=https://hypeman.example.com +``` + +```json +{"access_token":"...","token_type":"Bearer","expires_in":300,"scope":"instance:read instance:write"} +``` + +The request is the JWT bearer grant of [RFC 7523](https://www.rfc-editor.org/rfc/rfc7523), with +the audience named as in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707). `resource` may be +left out when the rule has a single audience. The request carries no client authentication, the +parameters go in the body, and parameters other than these four are refused. + +| Error | Status | Meaning | +|---|---|---| +| `invalid_request` | 400 | The request is malformed, has parameters in the URL, repeats a parameter, carries an unknown one or an `Authorization` header. This is checked before the grant type. | +| `unsupported_grant_type` | 400 | Another grant type, in a request that is otherwise well-formed. | +| `invalid_grant` | 400 | The identity token was not accepted. The answer is the same whatever the reason: an unknown rule, a signature, a claim, a token already used. The reason is in the server's log. | +| `invalid_target` | 400 | The caller is the rule's workload, and the rule does not allow the audience it asked for. | +| `temporarily_unavailable` | 503 | No token can be issued right now: the issuer's keys or the replay store cannot be reached. Retry. | + +Hypeman servers find the keys through `/.well-known/oauth-authorization-server`, which names the +key set at `/.well-known/jwks.json`. `/healthz` answers 204. + +## Single use + +Identity tokens from GitHub Actions and AWS, and by default from Entra and custom issuers, are +accepted once. The server records each one in the table `public.hypeman_auth_spent_assertions` by +a single insert on the primary key: two instances given the same identity token cannot both issue +for it. The record holds a hash of the issuer and token ID and the expiry, nothing else, and is +deleted a day after the identity token expired. + +Every instance must use the same database, as the same role. The server creates the table and +its index at every start unless they exist, and PostgreSQL checks the privileges for that either +way: the role needs `USAGE` and `CREATE` on the `public` schema and must own the table. For a +database on another machine use `sslmode=verify-full`: the server acts on the result of the +insert, and the connection carries a password. + +If the insert fails no token is issued. The identity token is usually still good, but the +database may have recorded it before the failure showed, so a caller whose retry is answered +`invalid_grant` should get a new identity token. The server does not start without +`replay_store.postgres_url` when any rule's issuer is single-use. Issuers whose identity tokens +may be presented again (Google Cloud, and Kubernetes by default) need no store. + +## Rotate the signing key + +A token's `kid` is the thumbprint of the key that signed it, so keys need no names. + +1. Add the new key's public half to `published_keys` and restart. +2. Make the new key the `signing_key`, move the old key's public half to `published_keys`, and + restart. +3. Once every token the old key signed has expired, remove it from `published_keys` and restart. + +A Hypeman server keeps a key set for five minutes and fetches it again when a request needs it +after that, so it learns of a published or removed key at its first fetch after those five +minutes, and of a key ID it does not know at once, or within a minute if it has just fetched. +Leave that long between the steps. The key set is served with `Cache-Control: no-cache`; do not +put a cache in front of it. + +For a compromised key, do steps 2 and 3 at once: replace `signing_key` and leave the old key out +of `published_keys`. Each Hypeman server stops trusting the old key at its next successful fetch. +To cut it off on a server without waiting for that, delete the server's saved copy and restart +it, as described in [OAuth access tokens](oauth-access-tokens.md#keys). + +## Monitor + +- `hypeman_auth_exchanges_total{issuer,rule,result}` counts exchanges; `result` is `issued`, + `rejected` or `unavailable`. +- Each exchange is one log line with the rule, the issuer, the result, the reason, a hash of the + identity token's subject and, when a token was issued, its `jti` and audience. Identity tokens + and access tokens are never logged. diff --git a/docs/oauth-access-tokens.md b/docs/oauth-access-tokens.md index bf7b90f96..31812f465 100644 --- a/docs/oauth-access-tokens.md +++ b/docs/oauth-access-tokens.md @@ -2,7 +2,8 @@ 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. +server's public keys, so it can verify the tokens and cannot issue them. `hypeman-auth` is such an +authorization server; see [Authorization server](authorization-server.md). ## Configure diff --git a/go.mod b/go.mod index 06c35df97..dcf76cf8a 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/google/wire v0.7.0 github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 + github.com/jackc/pgx/v5 v5.9.0 github.com/joho/godotenv v1.5.1 github.com/klauspost/compress v1.18.0 github.com/knadh/koanf/parsers/yaml v1.1.0 @@ -101,6 +102,9 @@ require ( github.com/go-test/deep v1.1.1 // indirect github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/klauspost/pgzip v1.2.6 // indirect github.com/knadh/koanf/maps v0.1.2 // indirect diff --git a/go.sum b/go.sum index cc4d836b6..714fd0d06 100644 --- a/go.sum +++ b/go.sum @@ -320,6 +320,14 @@ github.com/iris-contrib/schema v0.0.6 h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvP github.com/iris-contrib/schema v0.0.6/go.mod h1:iYszG0IOsuIsfzjymw1kMzTL8YQcCWlm65f3wX8J5iA= github.com/ishidawataru/sctp v0.0.0-20230406120618-7ff4192f6ff2 h1:i2fYnDurfLlJH8AyyMOnkLHnHeP8Ff/DDpuZA/D3bPo= github.com/ishidawataru/sctp v0.0.0-20230406120618-7ff4192f6ff2/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE= +github.com/jackc/pgx/v5 v5.9.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jaypipes/ghw v0.12.0 h1:xU2/MDJfWmBhJnujHY9qwXQLs3DBsf0/Xa9vECY0Tho= github.com/jaypipes/ghw v0.12.0/go.mod h1:jeJGbkRB2lL3/gxYzNYzEDETV1ZJ56OKr+CSeSEym+g= github.com/jaypipes/pcidb v1.0.0 h1:vtZIfkiCUE42oYbJS0TAq9XSfSmcsgo9IdxSm9qzYU8= diff --git a/lib/authserver/README.md b/lib/authserver/README.md new file mode 100644 index 000000000..626ba08f6 --- /dev/null +++ b/lib/authserver/README.md @@ -0,0 +1,13 @@ +# authserver + +The OAuth authorization server behind `hypeman-auth`. Operator documentation is in +[docs/authorization-server.md](../../docs/authorization-server.md). + +`Server.Exchange` checks an identity token against the federation rule the caller names, with +`lib/oidcfederation`, records it in the `SpentStore` if its issuer makes identity tokens +single-use, and signs an access token in the format `lib/accesstoken` verifies. `Server.Handler` +serves that exchange as the RFC 7523 token endpoint, beside the RFC 8414 metadata and the key set. + +`PostgresStore` is the `SpentStore` for more than one instance: the insert on the primary key +decides which of two concurrent exchanges of one identity token is first. Its test needs a +database and is skipped unless `HYPEMAN_AUTH_TEST_POSTGRES_URL` is set. diff --git a/lib/authserver/exchange.go b/lib/authserver/exchange.go new file mode 100644 index 000000000..6ec6ec376 --- /dev/null +++ b/lib/authserver/exchange.go @@ -0,0 +1,236 @@ +// Package authserver is the OAuth authorization server for Hypeman: it +// exchanges a workload's OIDC identity token for a short-lived access token +// that Hypeman servers verify with its public keys. +package authserver + +import ( + "context" + "crypto/ecdsa" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "net/url" + "slices" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/oidcfederation" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" +) + +// SubjectPrefix starts the `sub` of every token issued for a federation rule. +const SubjectPrefix = "federation:" + +var ( + // ErrGrant is returned for every identity token that is not accepted, + // whatever the reason. + ErrGrant = errors.New("identity token not accepted") + // ErrTarget means the caller was identified but may not have a token for + // the audience it asked for. + ErrTarget = errors.New("audience not allowed") + // ErrUnavailable means no token can be issued right now, whatever the + // identity token. + ErrUnavailable = errors.New("token issuing unavailable") +) + +// Options configure a Server. +type Options struct { + // Issuer is the server's issuer URL, the `iss` of its tokens. + Issuer string + Key *SigningKey + // PublishedKeys are public keys published beside the signing key: the + // previous key while its tokens are in use, or the next one before it signs. + PublishedKeys []*ecdsa.PublicKey + Rules *oidcfederation.Registry + // Spent records single-use identity tokens. It may be nil only if no + // rule's issuer makes its identity tokens single-use. + Spent SpentStore + Meter metric.Meter + Log *slog.Logger +} + +// Server issues access tokens for the configured federation rules. +type Server struct { + issuer string + key *SigningKey + keySet []byte + metadata []byte + rules *oidcfederation.Registry + verifier *oidcfederation.Verifier + spent SpentStore + exchanges metric.Int64Counter + log *slog.Logger + now func() time.Time +} + +// New validates the options. +func New(options Options) (*Server, error) { + issuer, err := url.Parse(options.Issuer) + if err != nil || issuer.Scheme != "https" || issuer.Hostname() == "" || issuer.User != nil || strings.Trim(issuer.EscapedPath(), "/") != "" || strings.ContainsAny(options.Issuer, "?#") { + return nil, fmt.Errorf("issuer must be an https URL without a path, query or fragment") + } + if options.Key == nil { + return nil, fmt.Errorf("a signing key is required") + } + if options.Spent == nil && options.Rules.SingleUse() { + return nil, fmt.Errorf("a replay store is required: at least one configured issuer's identity tokens are single-use") + } + exchanges, err := options.Meter.Int64Counter("hypeman_auth_exchanges_total", + metric.WithDescription("Identity token exchanges by federation rule, issuer and result")) + if err != nil { + return nil, err + } + s := &Server{ + issuer: strings.TrimRight(options.Issuer, "/"), + key: options.Key, + rules: options.Rules, + verifier: oidcfederation.NewVerifier(), + spent: options.Spent, + exchanges: exchanges, + log: options.Log, + now: time.Now, + } + if s.keySet, err = keySet(options.Key, options.PublishedKeys); err != nil { + return nil, err + } + if s.metadata, err = metadata(s.issuer); err != nil { + return nil, err + } + return s, nil +} + +// Token is an issued access token. +type Token struct { + AccessToken string + ExpiresIn int + Scope string +} + +// Exchange verifies the identity token against the one rule the caller names +// and issues an access token for audience, or for the rule's only audience +// when audience is empty. The rule name is an untrusted selector: it picks +// which rule to check, never what is granted. +func (s *Server) Exchange(ctx context.Context, ruleName, assertion, audience string) (Token, error) { + token, outcome := s.exchange(ctx, ruleName, assertion, audience) + s.exchanges.Add(ctx, 1, metric.WithAttributes( + attribute.String("issuer", outcome.issuer), + attribute.String("rule", outcome.rule), + attribute.String("result", outcome.result), + )) + attrs := []any{"rule", outcome.rule, "issuer", outcome.issuer, "result", outcome.result, "reason", outcome.reason} + if outcome.subject != "" { + digest := sha256.Sum256([]byte(outcome.subject)) + attrs = append(attrs, "subject_sha256", hex.EncodeToString(digest[:])) + } + if outcome.tokenID != "" { + attrs = append(attrs, "token_jti", outcome.tokenID, "audience", outcome.audience) + } + level := slog.LevelInfo + if outcome.result == "unavailable" { + level = slog.LevelWarn + } + s.log.Log(ctx, level, "identity token exchange", attrs...) + return token, outcome.err +} + +// exchangeOutcome is what the metric and the log line record. The rule and +// issuer are left empty unless the caller named a configured rule, so request +// input never becomes a metric label. +type exchangeOutcome struct { + rule, issuer string + result, reason string + subject, tokenID, audience string + err error +} + +func (s *Server) exchange(ctx context.Context, ruleName, raw, audience string) (Token, exchangeOutcome) { + fail := func(o exchangeOutcome, result, reason string, err error) (Token, exchangeOutcome) { + o.result, o.reason, o.err = result, reason, err + return Token{}, o + } + rule, ok := s.rules.Rule(ruleName) + if !ok { + return fail(exchangeOutcome{}, "rejected", "unknown rule", ErrGrant) + } + outcome := exchangeOutcome{rule: rule.Name, issuer: rule.Issuer} + assertion, err := s.verifier.Verify(ctx, rule.IssuerSpec, rule.ExpectedAudience, raw) + if errors.Is(err, oidcfederation.ErrAssertion) { + return fail(outcome, "rejected", "identity token not valid for this issuer and audience", ErrGrant) + } + if err != nil { + return fail(outcome, "unavailable", err.Error(), ErrUnavailable) + } + outcome.subject = assertion.Subject + if !rule.Match.Matches(assertion.Claims) { + return fail(outcome, "rejected", "claims do not match the rule", ErrGrant) + } + subject := SubjectPrefix + rule.Name + if pointer := rule.Authorization.SubjectClaim; pointer != "" { + caller, found := oidcfederation.ClaimString(assertion.Claims, pointer) + if !found || caller == "" || len(caller) > 256 || strings.ContainsFunc(caller, func(r rune) bool { return r < ' ' || r == 0x7f }) { + return fail(outcome, "rejected", "the subject claim is missing or not usable", ErrGrant) + } + subject += ":" + caller + } + // The caller is now known to be the workload the rule names, so it may be + // told that the audience it asked for is not one of the rule's. + audiences := rule.Authorization.Audiences + if audience == "" && len(audiences) == 1 { + audience = audiences[0] + } + if !slices.Contains(audiences, audience) { + return fail(outcome, "rejected", "audience not allowed by the rule", ErrTarget) + } + ttl := *rule.Authorization.MaxTokenTTLSeconds + if _, err := oidcfederation.AccessExpiry(s.now(), assertion.ExpiresAt, ttl); err != nil { + return fail(outcome, "rejected", "identity token expires too soon", ErrGrant) + } + // Everything above leaves a refused identity token usable. Once recorded it is spent. + if assertion.SingleUse { + digest := sha256.Sum256([]byte(rule.IssuerSpec.IssuerURL + "\n" + assertion.JTI)) + first, err := s.spent.Spend(ctx, hex.EncodeToString(digest[:]), assertion.ExpiresAt) + if err != nil { + return fail(outcome, "unavailable", "the spent identity token could not be recorded: "+err.Error(), ErrUnavailable) + } + if !first { + return fail(outcome, "rejected", "identity token was already used", ErrGrant) + } + } + // Recording can take a while. The token's lifetime starts now, so that a + // token is never returned already expired. + now := s.now() + expiry, err := oidcfederation.AccessExpiry(now, assertion.ExpiresAt, ttl) + if err != nil { + return fail(outcome, "rejected", "identity token expired while it was being recorded", ErrGrant) + } + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + return fail(outcome, "unavailable", "token ID generation failed", ErrUnavailable) + } + tokenID := hex.EncodeToString(id[:]) + scope := strings.Join(rule.Authorization.Permissions, " ") + token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ + "iss": s.issuer, + "sub": subject, + "aud": []string{audience}, + "client_id": rule.Name, + "scope": scope, + "iat": now.Unix(), + "exp": expiry.Unix(), + "jti": tokenID, + }) + token.Header["typ"] = "at+jwt" + token.Header["kid"] = s.key.ID + signed, err := token.SignedString(s.key.private) + if err != nil { + return fail(outcome, "unavailable", "token signing failed", ErrUnavailable) + } + outcome.result, outcome.reason, outcome.tokenID, outcome.audience = "issued", "issued", tokenID, audience + // The lifetime the token itself states: exp minus iat, both whole seconds. + return Token{AccessToken: signed, ExpiresIn: int(expiry.Unix() - now.Unix()), Scope: scope}, outcome +} diff --git a/lib/authserver/exchange_test.go b/lib/authserver/exchange_test.go new file mode 100644 index 000000000..498ff0255 --- /dev/null +++ b/lib/authserver/exchange_test.go @@ -0,0 +1,334 @@ +package authserver + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "sync" + "testing" + "time" + + jose "github.com/go-jose/go-jose/v4" + "github.com/golang-jwt/jwt/v5" + "github.com/kernel/hypeman/lib/accesstoken" + "github.com/kernel/hypeman/lib/oidcfederation" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/metric/noop" +) + +const ( + testIssuer = "https://auth.example.test" + testIdP = "https://idp.example.test" + testAudience = "https://hypeman.example.test" +) + +// memorySpent is a SpentStore for one process. +type memorySpent struct { + mu sync.Mutex + spent map[string]time.Time + err error +} + +func (m *memorySpent) Spend(_ context.Context, id string, expires time.Time) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return false, m.err + } + if _, exists := m.spent[id]; exists { + return false, nil + } + if m.spent == nil { + m.spent = map[string]time.Time{} + } + m.spent[id] = expires + return true, nil +} + +// fixture is an identity provider whose public key is configured inline, a +// rule that trusts one of its workloads, and a server with that rule. +type fixture struct { + idp *ecdsa.PrivateKey + config oidcfederation.Config + spent *memorySpent + server *Server +} + +func newFixture(t *testing.T, alter func(*oidcfederation.Config)) *fixture { + t.Helper() + idp, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + raw, err := json.Marshal(jose.JSONWebKey{Key: &idp.PublicKey, KeyID: "idp-key", Algorithm: "ES256", Use: "sig"}) + require.NoError(t, err) + var public map[string]any + require.NoError(t, json.Unmarshal(raw, &public)) + f := &fixture{idp: idp, spent: &memorySpent{}} + f.config = oidcfederation.Config{ + Issuers: []oidcfederation.IssuerSpec{{Name: "idp", IssuerURL: testIdP, JWKS: oidcfederation.KeySource{Type: "inline", Keys: []map[string]any{public}}}}, + FederationRules: []oidcfederation.RuleSpec{{ + Name: "ci", Issuer: "idp", ExpectedAudience: testIssuer, + Match: oidcfederation.Match{Type: "custom_oidc", Subject: "build"}, + Authorization: oidcfederation.RuleAuthorization{Audiences: []string{testAudience}, Permissions: []string{"instance:write", "instance:read"}}, + }}, + } + if alter != nil { + alter(&f.config) + } + f.server = f.start(t, f.spent) + return f +} + +// start returns another instance of the server on the same configuration. +func (f *fixture) start(t *testing.T, spent SpentStore) *Server { + t.Helper() + rules, err := oidcfederation.Compile(f.config) + require.NoError(t, err) + server, err := New(Options{Issuer: testIssuer, Key: newSigningKey(t), Rules: rules, Spent: spent, Meter: noop.NewMeterProvider().Meter("test"), Log: discardLog}) + require.NoError(t, err) + return server +} + +// identity signs an identity token the fixture's rule accepts. It outlives +// any access token issued for it, so that lifetimes are the rule's. +func (f *fixture) identity(t *testing.T, alter func(jwt.MapClaims)) string { + t.Helper() + var id [16]byte + _, _ = rand.Read(id[:]) + now := time.Now() + claims := jwt.MapClaims{"iss": testIdP, "sub": "build", "aud": testIssuer, "iat": now.Unix(), "exp": now.Add(30 * time.Minute).Unix(), "jti": hex.EncodeToString(id[:])} + if alter != nil { + alter(claims) + } + token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + token.Header["kid"] = "idp-key" + raw, err := token.SignedString(f.idp) + require.NoError(t, err) + return raw +} + +// resource returns what a Hypeman server configured to trust the fixture's +// server for audience makes of a token: its own verifier, with the server's +// published key set. +func (f *fixture) resource(t *testing.T, server *Server, audience string) *accesstoken.Verifier { + t.Helper() + var set struct { + Keys []map[string]any `json:"keys"` + } + require.NoError(t, json.Unmarshal(server.keySet, &set)) + cfg := accesstoken.Config{Audiences: []string{audience}, AuthorizationServers: []accesstoken.AuthorizationServer{{Issuer: testIssuer}}} + cfg.AuthorizationServers[0].JWKS.Type = "inline" + cfg.AuthorizationServers[0].JWKS.Keys = set.Keys + verifier, err := accesstoken.New(cfg, nil, nil) + require.NoError(t, err) + return verifier +} + +func TestExchangeIssuesATokenAHypemanServerAccepts(t *testing.T) { + f := newFixture(t, nil) + token, err := f.server.Exchange(context.Background(), "ci", f.identity(t, nil), "") + require.NoError(t, err) + require.Equal(t, oidcfederation.DefaultTokenTTL, token.ExpiresIn) + require.Equal(t, "instance:read instance:write", token.Scope) + + verified, err := f.resource(t, f.server, testAudience).Verify(context.Background(), token.AccessToken) + require.NoError(t, err) + require.Equal(t, testIssuer, verified.Issuer) + require.Equal(t, "federation:ci", verified.Subject) + require.Equal(t, "ci", verified.ClientID) + require.Len(t, verified.ID, 32) + require.Equal(t, []string{testAudience}, verified.Audience) + require.Equal(t, []string{"instance:read", "instance:write"}, verified.Permissions) + require.Equal(t, int64(oidcfederation.DefaultTokenTTL), verified.ExpiresAt.Unix()-verified.IssuedAt.Unix()) + + // A server with another audience, or one that trusts another key, refuses it. + _, err = f.resource(t, f.server, "https://other.example.test").Verify(context.Background(), token.AccessToken) + require.ErrorIs(t, err, accesstoken.ErrToken) + _, err = f.resource(t, f.start(t, f.spent), testAudience).Verify(context.Background(), token.AccessToken) + require.ErrorIs(t, err, accesstoken.ErrToken) + + parsed, _, err := jwt.NewParser().ParseUnverified(token.AccessToken, jwt.MapClaims{}) + require.NoError(t, err) + require.Equal(t, "at+jwt", parsed.Header["typ"]) + require.Equal(t, "ES256", parsed.Header["alg"]) + require.Equal(t, f.server.key.ID, parsed.Header["kid"]) +} + +// An identity token from a single-use issuer buys one access token, from +// whichever instance of the server it reaches. +func TestIdentityTokenIsSpentAcrossInstances(t *testing.T) { + f := newFixture(t, nil) + other := f.start(t, f.spent) + identity := f.identity(t, nil) + _, err := f.server.Exchange(context.Background(), "ci", identity, "") + require.NoError(t, err) + for _, server := range []*Server{f.server, other} { + _, err = server.Exchange(context.Background(), "ci", identity, "") + require.ErrorIs(t, err, ErrGrant) + } + _, err = other.Exchange(context.Background(), "ci", f.identity(t, nil), "") + require.NoError(t, err) + + // Raced, exactly one exchange of a token succeeds. + raced := f.identity(t, nil) + results := make(chan error, 16) + for i := range cap(results) { + go func() { + _, err := []*Server{f.server, other}[i%2].Exchange(context.Background(), "ci", raced, "") + results <- err + }() + } + issued := 0 + for range cap(results) { + if err := <-results; err == nil { + issued++ + } else { + require.ErrorIs(t, err, ErrGrant) + } + } + require.Equal(t, 1, issued) +} + +// Nothing is issued for an identity token that could not be recorded, and the +// identity token is still good once the store is back. +func TestNoTokenWithoutARecordOfTheSpentIdentityToken(t *testing.T) { + f := newFixture(t, nil) + identity := f.identity(t, nil) + f.spent.err = errors.New("connection refused") + _, err := f.server.Exchange(context.Background(), "ci", identity, "") + require.ErrorIs(t, err, ErrUnavailable) + f.spent.err = nil + _, err = f.server.Exchange(context.Background(), "ci", identity, "") + require.NoError(t, err) + + // A single-use issuer cannot be configured without a store at all. + rules, err := oidcfederation.Compile(f.config) + require.NoError(t, err) + _, err = New(Options{Issuer: testIssuer, Key: newSigningKey(t), Rules: rules, Meter: noop.NewMeterProvider().Meter("test"), Log: discardLog}) + require.ErrorContains(t, err, "replay store") +} + +// An issuer whose identity tokens may be presented again needs no store. +func TestReusableIdentityTokensNeedNoStore(t *testing.T) { + f := newFixture(t, func(c *oidcfederation.Config) { + c.Issuers[0].TokenValidation.ReplayProtection = oidcfederation.ReplayAllowReuse + }) + server := f.start(t, nil) + identity := f.identity(t, func(c jwt.MapClaims) { delete(c, "jti") }) + for range 2 { + _, err := server.Exchange(context.Background(), "ci", identity, "") + require.NoError(t, err) + } +} + +func TestExchangeRefusals(t *testing.T) { + f := newFixture(t, nil) + for name, tc := range map[string]struct { + rule string + alter func(jwt.MapClaims) + }{ + "unknown rule": {"other", nil}, + "another workload": {"ci", func(c jwt.MapClaims) { c["sub"] = "deploy" }}, + "another audience": {"ci", func(c jwt.MapClaims) { c["aud"] = testAudience }}, + "another issuer": {"ci", func(c jwt.MapClaims) { c["iss"] = "https://other.example.test" }}, + "expired": {"ci", func(c jwt.MapClaims) { c["exp"] = time.Now().Add(-time.Minute).Unix() }}, + "no token ID": {"ci", func(c jwt.MapClaims) { delete(c, "jti") }}, + "lifetime too long": {"ci", func(c jwt.MapClaims) { c["exp"] = time.Now().Add(3 * time.Hour).Unix() }}, + "issue time unusable": {"ci", func(c jwt.MapClaims) { c["iat"] = "now" }}, + "not valid yet": {"ci", func(c jwt.MapClaims) { c["nbf"] = time.Now().Add(time.Hour).Unix() }}, + } { + t.Run(name, func(t *testing.T) { + _, err := f.server.Exchange(context.Background(), tc.rule, f.identity(t, tc.alter), "") + require.ErrorIs(t, err, ErrGrant) + }) + } + _, err := f.server.Exchange(context.Background(), "ci", "not a token", "") + require.ErrorIs(t, err, ErrGrant) + require.Empty(t, f.spent.spent, "a refused identity token is not spent") +} + +// A rule may allow several audiences. The caller names the one it wants, and +// is told when it may not have it only after it has proven who it is. +func TestExchangeIssuesForOneOfTheRulesAudiences(t *testing.T) { + f := newFixture(t, func(c *oidcfederation.Config) { + c.FederationRules[0].Authorization.Audiences = []string{"prod", "staging"} + }) + token, err := f.server.Exchange(context.Background(), "ci", f.identity(t, nil), "staging") + require.NoError(t, err) + verified, err := f.resource(t, f.server, "staging").Verify(context.Background(), token.AccessToken) + require.NoError(t, err) + require.Equal(t, []string{"staging"}, verified.Audience) + _, err = f.resource(t, f.server, "prod").Verify(context.Background(), token.AccessToken) + require.ErrorIs(t, err, accesstoken.ErrToken) + + identity := f.identity(t, nil) + for _, audience := range []string{"", "dev", "prod staging"} { + _, err = f.server.Exchange(context.Background(), "ci", identity, audience) + require.ErrorIs(t, err, ErrTarget, audience) + } + _, err = f.server.Exchange(context.Background(), "ci", identity, "prod") + require.NoError(t, err, "asking for the wrong audience did not spend the identity token") + + _, err = f.server.Exchange(context.Background(), "ci", f.identity(t, func(c jwt.MapClaims) { c["sub"] = "deploy" }), "dev") + require.ErrorIs(t, err, ErrGrant, "a caller that is not the rule's workload learns nothing about audiences") + + // With one audience the caller need not name it, and may not name another. + single := newFixture(t, nil) + _, err = single.server.Exchange(context.Background(), "ci", single.identity(t, nil), testAudience) + require.NoError(t, err) + _, err = single.server.Exchange(context.Background(), "ci", single.identity(t, nil), "prod") + require.ErrorIs(t, err, ErrTarget) +} + +func TestTokenLifetimeIsClippedToTheIdentityToken(t *testing.T) { + ttl := 600 + f := newFixture(t, func(c *oidcfederation.Config) { c.FederationRules[0].Authorization.MaxTokenTTLSeconds = &ttl }) + token, err := f.server.Exchange(context.Background(), "ci", f.identity(t, nil), "") + require.NoError(t, err) + require.Equal(t, 600, token.ExpiresIn) + + token, err = f.server.Exchange(context.Background(), "ci", f.identity(t, func(c jwt.MapClaims) { c["exp"] = time.Now().Add(40 * time.Second).Unix() }), "") + require.NoError(t, err) + require.InDelta(t, 39, token.ExpiresIn, 1.5, "the identity token has forty seconds left") + + // An identity token that runs out while it is being recorded buys nothing. + clock := time.Now() + f.server.now = func() time.Time { clock = clock.Add(20 * time.Minute); return clock } + _, err = f.server.Exchange(context.Background(), "ci", f.identity(t, nil), "") + require.ErrorIs(t, err, ErrGrant) +} + +// The subject names the rule, and the caller too when the rule says which +// claim of the identity token names it. +func TestSubjectNamesTheCallerWhenTheRuleSaysHow(t *testing.T) { + f := newFixture(t, func(c *oidcfederation.Config) { c.FederationRules[0].Authorization.SubjectClaim = "/email" }) + token, err := f.server.Exchange(context.Background(), "ci", f.identity(t, func(c jwt.MapClaims) { c["email"] = "dev@example.test" }), "") + require.NoError(t, err) + verified, err := f.resource(t, f.server, testAudience).Verify(context.Background(), token.AccessToken) + require.NoError(t, err) + require.Equal(t, "federation:ci:dev@example.test", verified.Subject) + + for name, email := range map[string]any{"missing": nil, "empty": "", "an object": map[string]any{"a": 1}, "a control character": "dev\n@example.test", "too long": string(make([]byte, 300))} { + _, err = f.server.Exchange(context.Background(), "ci", f.identity(t, func(c jwt.MapClaims) { + if email != nil { + c["email"] = email + } + }), "") + require.ErrorIs(t, err, ErrGrant, name) + } +} + +func TestNewValidatesTheIssuer(t *testing.T) { + for _, issuer := range []string{"", "auth.example.test", "http://auth.example.test", "https://auth.example.test/tenant", "https://auth.example.test?x=1", "https://auth.example.test?", "https://auth.example.test#", "https://auth.example.test/%2F", "https://:443", "https://user@auth.example.test"} { + _, err := New(Options{Issuer: issuer, Key: newSigningKey(t), Meter: noop.NewMeterProvider().Meter("test"), Log: discardLog}) + require.Error(t, err, issuer) + } + server, err := New(Options{Issuer: testIssuer + "/", Key: newSigningKey(t), Meter: noop.NewMeterProvider().Meter("test"), Log: discardLog}) + require.NoError(t, err) + require.Equal(t, testIssuer, server.issuer) + _, err = New(Options{Issuer: testIssuer, Meter: noop.NewMeterProvider().Meter("test"), Log: discardLog}) + require.ErrorContains(t, err, "signing key") +} diff --git a/lib/authserver/handler.go b/lib/authserver/handler.go new file mode 100644 index 000000000..a2578376c --- /dev/null +++ b/lib/authserver/handler.go @@ -0,0 +1,163 @@ +package authserver + +import ( + "context" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "net/url" + "time" + + "github.com/kernel/hypeman/lib/oidcfederation" +) + +// GrantTypeJWTBearer is the RFC 7523 assertion grant. +const GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + +const ( + tokenPath = "/oauth/token" + metadataPath = "/.well-known/oauth-authorization-server" + keySetPath = "/.well-known/jwks.json" + + // A URL-encoded identity token of the largest accepted size, with room for the other parameters. + maxTokenRequestBytes = 3*oidcfederation.MaxAssertionBytes + 8<<10 + exchangeTimeout = 20 * time.Second +) + +// metadata is the RFC 8414 document, from which a resource server learns +// where the keys are. +func metadata(issuer string) ([]byte, error) { + return json.Marshal(map[string]any{ + "issuer": issuer, + "token_endpoint": issuer + tokenPath, + "jwks_uri": issuer + keySetPath, + "grant_types_supported": []string{GrantTypeJWTBearer}, + "token_endpoint_auth_methods_supported": []string{"none"}, + }) +} + +// Handler serves the token endpoint, the metadata and the key set. +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST "+tokenPath, s.serveToken) + mux.HandleFunc("GET "+metadataPath, public(s.metadata)) + mux.HandleFunc("GET "+keySetPath, public(s.keySet)) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) + return mux +} + +// public serves a fixed JSON document that anyone may read. Nothing between +// here and a Hypeman server should hold on to it: a server decides for itself +// how long it keeps the key set. +func public(document []byte) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-cache") + _, _ = w.Write(document) + } +} + +type tokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + Scope string `json:"scope"` +} + +type tokenError struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` +} + +// serveToken handles the identity token exchange: +// +// POST /oauth/token +// Content-Type: application/x-www-form-urlencoded +// +// grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=&federation_rule_id=&resource= +// +// The request carries no client authentication; the identity token is the +// only credential. resource may be left out when the rule has one audience. +func (s *Server) serveToken(w http.ResponseWriter, r *http.Request) { + // One deadline for reading the request and for the exchange, short of the + // server's write deadline, so that an identity token is never spent for a + // response that can no longer be written. + ctx, cancel := context.WithTimeout(r.Context(), exchangeTimeout) + defer cancel() + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || media != "application/x-www-form-urlencoded" { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "The request must be form-encoded") + return + } + // Parameters belong in the body. One in the URL would be ignored, not obeyed. + if r.URL.RawQuery != "" || r.URL.ForceQuery { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "Parameters must be sent in the request body") + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxTokenRequestBytes)) + if err != nil { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "The request is malformed or too large") + return + } + form, err := url.ParseQuery(string(body)) + if err != nil { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "The request is malformed or too large") + return + } + for key, values := range form { + if len(values) != 1 { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "Repeated parameter") + return + } + switch key { + case "grant_type", "assertion", "federation_rule_id", "resource": + default: + writeTokenError(w, http.StatusBadRequest, "invalid_request", "Unsupported parameter") + return + } + } + if _, present := r.Header["Authorization"]; present { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "The identity token exchange does not accept client authentication") + return + } + if form.Get("grant_type") == "" { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "Missing required parameter: grant_type") + return + } + if form.Get("grant_type") != GrantTypeJWTBearer { + writeTokenError(w, http.StatusBadRequest, "unsupported_grant_type", "Unsupported grant type") + return + } + for _, required := range []string{"assertion", "federation_rule_id"} { + if form.Get(required) == "" { + writeTokenError(w, http.StatusBadRequest, "invalid_request", "Missing required parameter: "+required) + return + } + } + token, err := s.Exchange(ctx, form.Get("federation_rule_id"), form.Get("assertion"), form.Get("resource")) + switch { + case errors.Is(err, ErrGrant): + // One answer for every refusal: the caller learns nothing about the rule or the issuer. + writeTokenError(w, http.StatusBadRequest, "invalid_grant", "The identity token was not accepted") + case errors.Is(err, ErrTarget): + writeTokenError(w, http.StatusBadRequest, "invalid_target", "The requested resource is not allowed") + case err != nil: + writeTokenError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "A token cannot be issued right now") + default: + writeTokenJSON(w, http.StatusOK, tokenResponse{AccessToken: token.AccessToken, TokenType: "Bearer", ExpiresIn: token.ExpiresIn, Scope: token.Scope}) + } +} + +func writeTokenError(w http.ResponseWriter, status int, code, description string) { + writeTokenJSON(w, status, tokenError{Error: code, ErrorDescription: description}) +} + +func writeTokenJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} diff --git a/lib/authserver/handler_test.go b/lib/authserver/handler_test.go new file mode 100644 index 000000000..ac8ce0aec --- /dev/null +++ b/lib/authserver/handler_test.go @@ -0,0 +1,129 @@ +package authserver + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func postToken(server *Server, form url.Values, alter func(*http.Request)) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodPost, tokenPath, strings.NewReader(form.Encode())) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if alter != nil { + alter(request) + } + recorder := httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, request) + return recorder +} + +func TestTokenEndpoint(t *testing.T) { + f := newFixture(t, nil) + form := func(identity string) url.Values { + return url.Values{"grant_type": {GrantTypeJWTBearer}, "assertion": {identity}, "federation_rule_id": {"ci"}} + } + response := postToken(f.server, form(f.identity(t, nil)), nil) + require.Equal(t, http.StatusOK, response.Code) + require.Equal(t, "no-store", response.Header().Get("Cache-Control")) + var body map[string]any + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &body)) + require.Equal(t, "Bearer", body["token_type"]) + require.EqualValues(t, 300, body["expires_in"]) + require.Equal(t, "instance:read instance:write", body["scope"]) + _, err := f.resource(t, f.server, testAudience).Verify(t.Context(), body["access_token"].(string)) + require.NoError(t, err) + + withResource := form(f.identity(t, nil)) + withResource.Set("resource", testAudience) + require.Equal(t, http.StatusOK, postToken(f.server, withResource, nil).Code) + + for name, tc := range map[string]struct { + form func() url.Values + alter func(*http.Request) + status int + code string + }{ + "not form-encoded": {func() url.Values { return form("x") }, func(r *http.Request) { r.Header.Set("Content-Type", "application/json") }, 400, "invalid_request"}, + "no grant type": {func() url.Values { v := form("x"); v.Del("grant_type"); return v }, nil, 400, "invalid_request"}, + "another grant type": {func() url.Values { v := form("x"); v.Set("grant_type", "client_credentials"); return v }, nil, 400, "unsupported_grant_type"}, + "another grant type alone": {func() url.Values { return url.Values{"grant_type": {"client_credentials"}} }, nil, 400, "unsupported_grant_type"}, + "no identity token": {func() url.Values { v := form("x"); v.Del("assertion"); return v }, nil, 400, "invalid_request"}, + "no rule": {func() url.Values { v := form("x"); v.Del("federation_rule_id"); return v }, nil, 400, "invalid_request"}, + "unknown parameter": {func() url.Values { v := form("x"); v.Set("scope", "instance:read"); return v }, nil, 400, "invalid_request"}, + "repeated parameter": {func() url.Values { v := form("x"); v.Add("federation_rule_id", "other"); return v }, nil, 400, "invalid_request"}, + "client authentication": {func() url.Values { return form("x") }, func(r *http.Request) { r.Header.Set("Authorization", "Bearer x") }, 400, "invalid_request"}, + // The request as a whole is judged before its grant type is. + "another grant type with an unknown parameter": {func() url.Values { + v := form("x") + v.Set("grant_type", "client_credentials") + v.Set("client_secret", "x") + return v + }, nil, 400, "invalid_request"}, + // A parameter in the URL would be ignored, so it is refused: here the + // caller asks for an audience the rule does not have. + "parameter in the URL": {func() url.Values { return form(f.identity(t, nil)) }, func(r *http.Request) { r.URL.RawQuery = "resource=prod" }, 400, "invalid_request"}, + "too large": {func() url.Values { return form(strings.Repeat("a", maxTokenRequestBytes)) }, nil, 400, "invalid_request"}, + "identity not accepted": {func() url.Values { return form("x") }, nil, 400, "invalid_grant"}, + "unknown rule": {func() url.Values { v := form(f.identity(t, nil)); v.Set("federation_rule_id", "other"); return v }, nil, 400, "invalid_grant"}, + "audience not allowed": {func() url.Values { v := form(f.identity(t, nil)); v.Set("resource", "prod"); return v }, nil, 400, "invalid_target"}, + } { + t.Run(name, func(t *testing.T) { + response := postToken(f.server, tc.form(), tc.alter) + require.Equal(t, tc.status, response.Code) + var body map[string]string + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &body)) + require.Equal(t, tc.code, body["error"]) + require.NotEmpty(t, body["error_description"]) + require.Equal(t, "no-store", response.Header().Get("Cache-Control")) + }) + } + + f.spent.err = http.ErrHandlerTimeout + response = postToken(f.server, form(f.identity(t, nil)), nil) + require.Equal(t, http.StatusServiceUnavailable, response.Code) + require.Contains(t, response.Body.String(), "temporarily_unavailable") + require.NotContains(t, response.Body.String(), http.ErrHandlerTimeout.Error(), "the cause stays in the log") + + request := httptest.NewRequest(http.MethodGet, tokenPath, nil) + recorder := httptest.NewRecorder() + f.server.Handler().ServeHTTP(recorder, request) + require.Equal(t, http.StatusMethodNotAllowed, recorder.Code) +} + +// A Hypeman server finds the key set through the metadata, and the key set +// lets it verify what the token endpoint issues. +func TestMetadataAndKeySet(t *testing.T) { + f := newFixture(t, nil) + get := func(path string) (*httptest.ResponseRecorder, map[string]any) { + recorder := httptest.NewRecorder() + f.server.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + var body map[string]any + if recorder.Code == http.StatusOK { + require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &body)) + } + return recorder, body + } + response, metadata := get(metadataPath) + require.Equal(t, http.StatusOK, response.Code) + require.Equal(t, "application/json", response.Header().Get("Content-Type")) + require.Equal(t, testIssuer, metadata["issuer"]) + require.Equal(t, testIssuer+"/oauth/token", metadata["token_endpoint"]) + require.Equal(t, testIssuer+"/.well-known/jwks.json", metadata["jwks_uri"]) + require.Equal(t, []any{GrantTypeJWTBearer}, metadata["grant_types_supported"]) + require.Equal(t, "no-cache", response.Header().Get("Cache-Control")) + + response, set := get(keySetPath) + require.Equal(t, http.StatusOK, response.Code) + require.Len(t, set["keys"], 1) + require.Equal(t, f.server.key.ID, set["keys"].([]any)[0].(map[string]any)["kid"]) + + response, _ = get("/healthz") + require.Equal(t, http.StatusNoContent, response.Code) + response, _ = get("/metrics") + require.Equal(t, http.StatusNotFound, response.Code, "metrics are not served to callers") +} diff --git a/lib/authserver/keys.go b/lib/authserver/keys.go new file mode 100644 index 000000000..009bb1c0e --- /dev/null +++ b/lib/authserver/keys.go @@ -0,0 +1,106 @@ +package authserver + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + + jose "github.com/go-jose/go-jose/v4" +) + +// ErrKey is returned for a key that cannot sign or vouch for access tokens. +var ErrKey = errors.New("invalid access token key") + +// SigningKey signs access tokens with ES256. ID is the `kid` its tokens carry. +type SigningKey struct { + private *ecdsa.PrivateKey + ID string +} + +// ParseSigningKey reads a PEM-encoded P-256 private key, in PKCS #8 or SEC 1 form. +func ParseSigningKey(encoded []byte) (*SigningKey, error) { + block, _ := pem.Decode(encoded) + if block == nil { + return nil, fmt.Errorf("%w: the signing key is not PEM", ErrKey) + } + var private *ecdsa.PrivateKey + switch block.Type { + case "PRIVATE KEY": + parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%w: the signing key does not parse", ErrKey) + } + private, _ = parsed.(*ecdsa.PrivateKey) + case "EC PRIVATE KEY": + parsed, err := x509.ParseECPrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%w: the signing key does not parse", ErrKey) + } + private = parsed + } + if private == nil || private.Curve != elliptic.P256() { + return nil, fmt.Errorf("%w: the signing key must be an ECDSA P-256 private key", ErrKey) + } + id, err := keyID(&private.PublicKey) + if err != nil { + return nil, err + } + return &SigningKey{private: private, ID: id}, nil +} + +// ParsePublicKey reads a PEM-encoded P-256 public key, as published beside +// the signing key while tokens it signed are still in use. +func ParsePublicKey(encoded []byte) (*ecdsa.PublicKey, error) { + block, _ := pem.Decode(encoded) + if block == nil || block.Type != "PUBLIC KEY" { + return nil, fmt.Errorf("%w: a published key must be a PEM public key", ErrKey) + } + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + public, _ := parsed.(*ecdsa.PublicKey) + if err != nil || public == nil || public.Curve != elliptic.P256() { + return nil, fmt.Errorf("%w: a published key must be an ECDSA P-256 public key", ErrKey) + } + return public, nil +} + +// keyID is the RFC 7638 thumbprint of a public key, so a key has the same ID +// wherever it is configured. +func keyID(public *ecdsa.PublicKey) (string, error) { + thumbprint, err := (&jose.JSONWebKey{Key: public}).Thumbprint(crypto.SHA256) + if err != nil { + return "", fmt.Errorf("%w: %w", ErrKey, err) + } + return base64.RawURLEncoding.EncodeToString(thumbprint), nil +} + +// maxKeys is how many keys a Hypeman server accepts in one key set. +const maxKeys = 16 + +// keySet is the JWKS document: the signing key first, then the published +// keys. Each key is listed once, because a Hypeman server refuses a key set +// in which a key ID repeats. +func keySet(signing *SigningKey, published []*ecdsa.PublicKey) ([]byte, error) { + set := jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &signing.private.PublicKey, KeyID: signing.ID, Algorithm: "ES256", Use: "sig"}}} + listed := map[string]bool{signing.ID: true} + for _, public := range published { + id, err := keyID(public) + if err != nil { + return nil, err + } + if listed[id] { + continue + } + listed[id] = true + set.Keys = append(set.Keys, jose.JSONWebKey{Key: public, KeyID: id, Algorithm: "ES256", Use: "sig"}) + } + if len(set.Keys) > maxKeys { + return nil, fmt.Errorf("%w: at most %d keys can be published", ErrKey, maxKeys) + } + return json.Marshal(set) +} diff --git a/lib/authserver/keys_test.go b/lib/authserver/keys_test.go new file mode 100644 index 000000000..57540c155 --- /dev/null +++ b/lib/authserver/keys_test.go @@ -0,0 +1,100 @@ +package authserver + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/json" + "encoding/pem" + "log/slog" + "testing" + + "github.com/stretchr/testify/require" +) + +var discardLog = slog.New(slog.DiscardHandler) + +func encodePEM(t *testing.T, kind string, der []byte, err error) []byte { + t.Helper() + require.NoError(t, err) + return pem.EncodeToMemory(&pem.Block{Type: kind, Bytes: der}) +} + +func newSigningKey(t *testing.T) *SigningKey { + t.Helper() + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(private) + key, err := ParseSigningKey(encodePEM(t, "PRIVATE KEY", der, err)) + require.NoError(t, err) + return key +} + +func TestSigningKeyFormsAndItsID(t *testing.T) { + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + pkcs8, err := x509.MarshalPKCS8PrivateKey(private) + first, err := ParseSigningKey(encodePEM(t, "PRIVATE KEY", pkcs8, err)) + require.NoError(t, err) + sec1, err := x509.MarshalECPrivateKey(private) + second, err := ParseSigningKey(encodePEM(t, "EC PRIVATE KEY", sec1, err)) + require.NoError(t, err) + require.Len(t, first.ID, 43, "an RFC 7638 thumbprint") + require.Equal(t, first.ID, second.ID, "the ID follows the key, not its encoding") + require.NotEqual(t, first.ID, newSigningKey(t).ID) + + pkix, err := x509.MarshalPKIXPublicKey(&private.PublicKey) + publicPEM := encodePEM(t, "PUBLIC KEY", pkix, err) + public, err := ParsePublicKey(publicPEM) + require.NoError(t, err) + require.True(t, public.Equal(&private.PublicKey)) + + larger, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + require.NoError(t, err) + largerDER, err := x509.MarshalPKCS8PrivateKey(larger) + largerPEM := encodePEM(t, "PRIVATE KEY", largerDER, err) + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + rsaDER, err := x509.MarshalPKCS8PrivateKey(rsaKey) + rsaPEM := encodePEM(t, "PRIVATE KEY", rsaDER, err) + for name, encoded := range map[string][]byte{"another curve": largerPEM, "another algorithm": rsaPEM, "a public key": publicPEM, "not PEM": []byte("secret"), "not a key": encodePEM(t, "PRIVATE KEY", []byte("x"), nil)} { + _, err := ParseSigningKey(encoded) + require.ErrorIs(t, err, ErrKey, name) + } + largerPKIX, err := x509.MarshalPKIXPublicKey(&larger.PublicKey) + for name, encoded := range map[string][]byte{"another curve": encodePEM(t, "PUBLIC KEY", largerPKIX, err), "a private key": encodePEM(t, "PRIVATE KEY", pkcs8, nil), "not PEM": []byte("key")} { + _, err := ParsePublicKey(encoded) + require.ErrorIs(t, err, ErrKey, name) + } +} + +// The key set lists the signing key first and each published key once, and +// never anything private. +func TestKeySetPublishesOnlyPublicKeys(t *testing.T) { + signing, previous := newSigningKey(t), newSigningKey(t) + raw, err := keySet(signing, []*ecdsa.PublicKey{&previous.private.PublicKey, &signing.private.PublicKey, &previous.private.PublicKey}) + require.NoError(t, err) + var set struct { + Keys []map[string]string `json:"keys"` + } + require.NoError(t, json.Unmarshal(raw, &set)) + require.Len(t, set.Keys, 2, "each key is listed once, however often it is configured") + require.Equal(t, signing.ID, set.Keys[0]["kid"]) + require.Equal(t, previous.ID, set.Keys[1]["kid"]) + for _, key := range set.Keys { + require.Equal(t, "EC", key["kty"]) + require.Equal(t, "P-256", key["crv"]) + require.Equal(t, "ES256", key["alg"]) + require.Equal(t, "sig", key["use"]) + require.NotContains(t, key, "d") + } + + var many []*ecdsa.PublicKey + for range maxKeys { + many = append(many, &newSigningKey(t).private.PublicKey) + } + _, err = keySet(signing, many) + require.ErrorIs(t, err, ErrKey, "more keys than a Hypeman server accepts") +} diff --git a/lib/authserver/store.go b/lib/authserver/store.go new file mode 100644 index 000000000..ff4b3466c --- /dev/null +++ b/lib/authserver/store.go @@ -0,0 +1,117 @@ +package authserver + +import ( + "context" + "database/sql" + "fmt" + "log/slog" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/stdlib" +) + +// SpentStore remembers the single-use identity tokens that were exchanged, +// for every instance of the server at once. +type SpentStore interface { + // Spend records id and reports whether this call was the first to do so. + // It reports true to exactly one caller, however many ask at the same time. + Spend(ctx context.Context, id string, expires time.Time) (first bool, err error) +} + +const ( + // spentRetention is how long a record outlives its identity token. A token + // is refused once it has expired, so the record is no longer needed then; + // keeping it a day longer leaves no room for a wrong clock to matter. + spentRetention = 24 * time.Hour + spentCleanup = 10 * time.Minute + + // The table is named with its schema, so that every instance uses the + // same one whatever its role's search path is. + spentSchema = `CREATE TABLE IF NOT EXISTS public.hypeman_auth_spent_assertions ( + id TEXT PRIMARY KEY, + expires_at TIMESTAMPTZ NOT NULL +)` + spentIndex = `CREATE INDEX IF NOT EXISTS hypeman_auth_spent_assertions_expires_at ON public.hypeman_auth_spent_assertions (expires_at)` + spentInsert = `INSERT INTO public.hypeman_auth_spent_assertions (id, expires_at) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING` + // The database's clock decides, so the instances agree on what is old. + spentDelete = `DELETE FROM public.hypeman_auth_spent_assertions WHERE expires_at < now() - make_interval(secs => $1)` + // spentSchemaLock serializes instances that start together: CREATE ... + // IF NOT EXISTS alone can fail when two sessions create the table at once. + spentSchemaLock = `SELECT pg_advisory_xact_lock(4801270353920264117)` +) + +// PostgresStore keeps spent identity tokens in a PostgreSQL table. The insert +// is one statement on the primary key, so two instances exchanging the same +// identity token cannot both be first. +type PostgresStore struct { + db *sql.DB +} + +// OpenPostgresStore connects to url and creates the table if it is missing. +func OpenPostgresStore(ctx context.Context, url string) (*PostgresStore, error) { + config, err := pgx.ParseConfig(url) + if err != nil { + // The URL holds a password, so the parse error is not passed on. + return nil, fmt.Errorf("the replay store URL is not a PostgreSQL connection string") + } + // Plain statements work through a transaction pooler as well as directly. + config.DefaultQueryExecMode = pgx.QueryExecModeExec + db := stdlib.OpenDB(*config) + db.SetMaxOpenConns(10) + db.SetConnMaxIdleTime(5 * time.Minute) + if err := createSpentTable(ctx, db); err != nil { + db.Close() + return nil, fmt.Errorf("prepare the replay store: %w", err) + } + return &PostgresStore{db: db}, nil +} + +func createSpentTable(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + for _, statement := range []string{spentSchemaLock, spentSchema, spentIndex} { + if _, err := tx.ExecContext(ctx, statement); err != nil { + return err + } + } + return tx.Commit() +} + +func (s *PostgresStore) Spend(ctx context.Context, id string, expires time.Time) (bool, error) { + result, err := s.db.ExecContext(ctx, spentInsert, id, expires.UTC()) + if err != nil { + return false, err + } + inserted, err := result.RowsAffected() + return inserted == 1, err +} + +// Cleanup deletes the records that are no longer needed, now and then until +// ctx ends. Every instance may run it. +func (s *PostgresStore) Cleanup(ctx context.Context, log *slog.Logger) { + ticker := time.NewTicker(spentCleanup) + defer ticker.Stop() + for { + if err := s.deleteOld(ctx); err != nil && ctx.Err() == nil { + log.Warn("old records of spent identity tokens were not deleted", "error", err) + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (s *PostgresStore) deleteOld(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, spentDelete, spentRetention.Seconds()) + return err +} + +func (s *PostgresStore) Close() error { + return s.db.Close() +} diff --git a/lib/authserver/store_test.go b/lib/authserver/store_test.go new file mode 100644 index 000000000..746075bba --- /dev/null +++ b/lib/authserver/store_test.go @@ -0,0 +1,125 @@ +package authserver + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "net/url" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// postgresTestURL is the URL of a PostgreSQL server on which the test may +// create a database of its own, for example +// postgres://postgres:postgres@localhost:5432/postgres. Nothing that is +// already there is touched. +const postgresTestURL = "HYPEMAN_AUTH_TEST_POSTGRES_URL" + +func TestPostgresStore(t *testing.T) { + server := os.Getenv(postgresTestURL) + if server == "" { + t.Skipf("%s is not set", postgresTestURL) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + newID := func() string { + var id [32]byte + _, _ = rand.Read(id[:]) + return hex.EncodeToString(id[:]) + } + + // A new, empty database for this run. + admin, err := sql.Open("pgx", server) + require.NoError(t, err) + database := "hypeman_auth_test_" + newID()[:16] + _, err = admin.ExecContext(ctx, `CREATE DATABASE `+database) + require.NoError(t, err) + t.Cleanup(func() { + _, err := admin.Exec(`DROP DATABASE ` + database + ` WITH (FORCE)`) + assert.NoError(t, err) + admin.Close() + }) + // The stores go to that database whatever the URL said: pgx lets the + // dbname and database parameters override the path. + location, err := url.Parse(server) + require.NoError(t, err) + query := location.Query() + query.Del("dbname") + query.Del("database") + location.Path, location.RawQuery = "/"+database, query.Encode() + + // Instances that start together on a database without the table all come up. + stores := make(chan *PostgresStore, 8) + for range cap(stores) { + go func() { + store, err := OpenPostgresStore(ctx, location.String()) + assert.NoError(t, err) + stores <- store + }() + } + var opened []*PostgresStore + for range cap(stores) { + if store := <-stores; store != nil { + defer store.Close() + opened = append(opened, store) + } + } + require.Len(t, opened, cap(stores)) + first, second := opened[0], opened[1] + var connected string + require.NoError(t, first.db.QueryRowContext(ctx, `SELECT current_database()`).Scan(&connected)) + require.Equal(t, database, connected) + + id := newID() + spent, err := first.Spend(ctx, id, time.Now().Add(5*time.Minute)) + require.NoError(t, err) + require.True(t, spent) + for _, store := range []*PostgresStore{first, second} { + spent, err = store.Spend(ctx, id, time.Now().Add(5*time.Minute)) + require.NoError(t, err) + require.False(t, spent) + } + + // Raced across both instances, one caller is first. + raced := newID() + results := make(chan bool, 32) + for i := range cap(results) { + go func() { + spent, err := []*PostgresStore{first, second}[i%2].Spend(ctx, raced, time.Now().Add(5*time.Minute)) + results <- spent && err == nil + }() + } + winners := 0 + for range cap(results) { + if <-results { + winners++ + } + } + require.Equal(t, 1, winners) + + // A record outlives its identity token by the retention, then goes. + recent, old := newID(), newID() + _, err = first.Spend(ctx, recent, time.Now().Add(-spentRetention+time.Hour)) + require.NoError(t, err) + _, err = first.Spend(ctx, old, time.Now().Add(-spentRetention-time.Hour)) + require.NoError(t, err) + require.NoError(t, second.deleteOld(ctx)) + spent, err = first.Spend(ctx, recent, time.Now()) + require.NoError(t, err) + require.False(t, spent, "still on record") + spent, err = first.Spend(ctx, old, time.Now()) + require.NoError(t, err) + require.True(t, spent, "deleted, so recorded anew") + spent, err = first.Spend(ctx, id, time.Now()) + require.NoError(t, err) + require.False(t, spent) + + _, err = OpenPostgresStore(ctx, "postgres://user:secret-password@%zz") + require.Error(t, err) + require.NotContains(t, err.Error(), "secret-password") +} diff --git a/lib/oidcfederation/README.md b/lib/oidcfederation/README.md index aaabc8312..ff929edc5 100644 --- a/lib/oidcfederation/README.md +++ b/lib/oidcfederation/README.md @@ -9,8 +9,8 @@ Trust is two kinds of object, both written by the operator in a `Config`: `explicit_url` or `inline`), the longest assertion lifetime accepted, and whether an assertion may be presented more than once. - A **federation rule** names which workload of one issuer is accepted and what it receives: the - audience the assertion must carry, the conditions its claims must meet, a `permissions` scope - list and a token lifetime. + audience the assertion must carry, the conditions its claims must meet, the audiences a token + may be issued for, a `permissions` scope list and a token lifetime. `Compile` validates a configuration and returns a `Registry` of rules. `Verifier.Verify` checks one assertion against a rule's issuer and audience, and `Match.Matches` evaluates the rule's conditions diff --git a/lib/oidcfederation/model.go b/lib/oidcfederation/model.go index 2dbc0d553..38c03d061 100644 --- a/lib/oidcfederation/model.go +++ b/lib/oidcfederation/model.go @@ -80,10 +80,17 @@ type Match struct { ServiceAccount string `koanf:"service_account" json:"service_account,omitempty"` } -// RuleAuthorization is what a matching workload receives: a scope list and a token lifetime. +// RuleAuthorization is what a matching workload receives: the servers its +// token may be for, a scope list and a token lifetime. type RuleAuthorization struct { + // Audiences are the audiences a token may be issued for. A token names one. + Audiences []string `koanf:"audiences" json:"audiences"` Permissions []string `koanf:"permissions" json:"permissions"` MaxTokenTTLSeconds *int `koanf:"max_token_ttl_seconds" json:"max_token_ttl_seconds,omitempty"` + // SubjectClaim is an optional JSON Pointer to the identity token claim + // that names the caller, such as /email. Its value is added to the + // issued token's subject, which otherwise names only the rule. + SubjectClaim string `koanf:"subject_claim" json:"subject_claim,omitempty"` } // RuleSpec maps a matching external identity to a scoped Hypeman token. diff --git a/lib/oidcfederation/model_test.go b/lib/oidcfederation/model_test.go index 3c9f0727e..dc2ac8374 100644 --- a/lib/oidcfederation/model_test.go +++ b/lib/oidcfederation/model_test.go @@ -17,7 +17,7 @@ func githubConfig() Config { Issuer: "github-actions", ExpectedAudience: "https://auth.example.test", Match: Match{Type: "github_actions", RepositoryID: "12", RepositoryOwnerID: "34", Workflow: ".github/workflows/test.yml", Ref: "refs/heads/main"}, - Authorization: RuleAuthorization{Permissions: []string{"instance:write", "instance:read"}}, + Authorization: RuleAuthorization{Audiences: []string{"https://hypeman.example.test"}, Permissions: []string{"instance:write", "instance:read"}}, }}, } } @@ -50,7 +50,7 @@ func ruleFor(issuer IssuerSpec, match Match) (Rule, error) { Issuers: []IssuerSpec{issuer}, FederationRules: []RuleSpec{{ Name: "rule", Issuer: issuer.Name, ExpectedAudience: "https://auth.example.test", Match: match, - Authorization: RuleAuthorization{Permissions: []string{"instance:read"}}, + Authorization: RuleAuthorization{Audiences: []string{"https://hypeman.example.test"}, Permissions: []string{"instance:read"}}, }}, }) if err != nil { @@ -297,6 +297,12 @@ func TestCompileResolvesIssuersAndRejectsAmbiguity(t *testing.T) { "duplicate issuer url": func(c *Config) { c.Issuers = append(c.Issuers, IssuerSpec{Name: "second", IssuerURL: GitHubIssuer}) }, "no audience": func(c *Config) { c.FederationRules[0].ExpectedAudience = "" }, "bad rule name": func(c *Config) { c.FederationRules[0].Name = "ci:main" }, + "no token audience": func(c *Config) { c.FederationRules[0].Authorization.Audiences = nil }, + "empty token audience": func(c *Config) { c.FederationRules[0].Authorization.Audiences = []string{""} }, + "repeated token audience": func(c *Config) { + c.FederationRules[0].Authorization.Audiences = []string{"prod", "prod"} + }, + "subject claim not a pointer": func(c *Config) { c.FederationRules[0].Authorization.SubjectClaim = "email" }, } { cfg := githubConfig() alter(&cfg) @@ -308,12 +314,16 @@ func TestCompileResolvesIssuersAndRejectsAmbiguity(t *testing.T) { func TestCompileDoesNotAliasItsInput(t *testing.T) { cfg := githubConfig() cfg.FederationRules[0].Match.Claims = map[string]string{"/actor": "octocat"} + cfg.FederationRules[0].Authorization.SubjectClaim = "/actor" registry, err := Compile(cfg) require.NoError(t, err) cfg.FederationRules[0].Match.Claims["/actor"] = "other" cfg.FederationRules[0].Authorization.Permissions[0] = "image:delete" + cfg.FederationRules[0].Authorization.Audiences[0] = "https://other.example.test" rule, _ := registry.Rule("ci") require.Equal(t, "octocat", rule.Match.Claims["/actor"]) + require.Equal(t, []string{"https://hypeman.example.test"}, rule.Authorization.Audiences) + require.Equal(t, "/actor", rule.Authorization.SubjectClaim) require.Equal(t, []string{"instance:read", "instance:write"}, rule.Authorization.Permissions) } @@ -331,7 +341,7 @@ func TestCompileLeavesInlineKeysAsConfigured(t *testing.T) { FederationRules: []RuleSpec{{ Name: "ci", Issuer: "idp", ExpectedAudience: "https://auth.example.test", Match: Match{Type: "custom_oidc", Subject: "build"}, - Authorization: RuleAuthorization{Permissions: []string{"image:read"}}, + Authorization: RuleAuthorization{Audiences: []string{"https://hypeman.example.test"}, Permissions: []string{"image:read"}}, }}, } for range 2 { diff --git a/lib/oidcfederation/registry.go b/lib/oidcfederation/registry.go index be7aec7f8..41fba3f95 100644 --- a/lib/oidcfederation/registry.go +++ b/lib/oidcfederation/registry.go @@ -62,3 +62,17 @@ func (r *Registry) Rule(name string) (Rule, bool) { func (r *Registry) Enabled() bool { return r != nil && len(r.rules) > 0 } + +// SingleUse reports whether any rule's issuer lets an identity token be +// exchanged only once, which takes a record of the spent ones. +func (r *Registry) SingleUse() bool { + if r == nil { + return false + } + for _, rule := range r.rules { + if rule.IssuerSpec.TokenValidation.ReplayProtection == ReplaySingleUse { + return true + } + } + return false +} diff --git a/lib/oidcfederation/rule.go b/lib/oidcfederation/rule.go index b27cfc643..697cc9f90 100644 --- a/lib/oidcfederation/rule.go +++ b/lib/oidcfederation/rule.go @@ -26,6 +26,20 @@ func normalizeRule(out RuleSpec, issuer IssuerSpec) (RuleSpec, error) { if n := *out.Authorization.MaxTokenTTLSeconds; n < 1 || n > MaxTokenTTL { return out, fmt.Errorf("%w: token lifetime must be between 1 and %d seconds", ErrInvalid, MaxTokenTTL) } + if len(out.Authorization.Audiences) == 0 { + return out, fmt.Errorf("%w: authorization.audiences is required", ErrInvalid) + } + out.Authorization.Audiences = slices.Clone(out.Authorization.Audiences) + for i, audience := range out.Authorization.Audiences { + if audience == "" || len(audience) > 2048 || slices.Contains(out.Authorization.Audiences[:i], audience) { + return out, fmt.Errorf("%w: authorization.audiences[%d] is empty, too long or repeated", ErrInvalid, i) + } + } + if out.Authorization.SubjectClaim != "" { + if _, err := pointerParts(out.Authorization.SubjectClaim); err != nil { + return out, fmt.Errorf("%w: authorization.subject_claim must be a JSON Pointer", ErrInvalid) + } + } // A federated token never falls back to the full access a token without a // permissions claim has, so the list is explicit and has no wildcard. if len(out.Authorization.Permissions) == 0 { From a28a1cda0c01bae938aa3916e44662942a168457 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:21:52 +0000 Subject: [PATCH 2/3] Let a signing key from the environment replace the file's SIGNING_KEY__PEM or SIGNING_KEY__FILE set one half of the signing_key block and left the other half from the file in place, so a file naming a key path and an environment giving the key text left both set and the server refused to start. Either variable now replaces the block. The image also names its non-root user, which the base image already ran as. --- cmd/auth/Dockerfile | 1 + cmd/auth/config/config.go | 5 +++++ cmd/auth/config/config_test.go | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cmd/auth/Dockerfile b/cmd/auth/Dockerfile index bc78020a7..1cc4b6418 100644 --- a/cmd/auth/Dockerfile +++ b/cmd/auth/Dockerfile @@ -8,5 +8,6 @@ RUN CGO_ENABLED=0 go build -trimpath -o /hypeman-auth ./cmd/auth FROM gcr.io/distroless/static-debian12:nonroot COPY --from=build /hypeman-auth /hypeman-auth +USER nonroot:nonroot EXPOSE 8080 ENTRYPOINT ["/hypeman-auth"] diff --git a/cmd/auth/config/config.go b/cmd/auth/config/config.go index 5a571f80a..78f9c93a5 100644 --- a/cmd/auth/config/config.go +++ b/cmd/auth/config/config.go @@ -104,6 +104,11 @@ func Load(path string) (*Config, error) { return nil, fmt.Errorf("%s: %w", path, err) } } + // A key from the environment replaces the file's key, not one half of it: + // the file may name a path where the environment gives the text. + if os.Getenv("SIGNING_KEY__PEM") != "" || os.Getenv("SIGNING_KEY__FILE") != "" { + k.Delete("signing_key") + } for name, key := range environment { if value := os.Getenv(name); value != "" { if err := k.Set(key, value); err != nil { diff --git a/cmd/auth/config/config_test.go b/cmd/auth/config/config_test.go index e7f960769..4ea400657 100644 --- a/cmd/auth/config/config_test.go +++ b/cmd/auth/config/config_test.go @@ -82,7 +82,7 @@ func TestEnvironmentOverridesTheFile(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://env.example.test", cfg.Issuer) require.Equal(t, ":9000", cfg.ListenAddress) - require.Equal(t, "from the environment", cfg.SigningKey.PEM) + require.Equal(t, Key{PEM: "from the environment"}, cfg.SigningKey, "the file's key path is gone with it") require.Equal(t, "postgres://env", cfg.ReplayStore.PostgresURL) require.Equal(t, "https://env.example.test:4317", cfg.OtelEndpoint) require.Equal(t, []Key{{PEM: "one"}, {File: "/keys/two.pem"}}, cfg.PublishedKeys) From 1ea05db11d7bcd1c3ba6930a65b9941a6378027c Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:53:19 +0000 Subject: [PATCH 3/3] Keep the replay store's schema in migration files The table and its index were SQL strings in Go that ran at every start, with no record of what a database already had, so a later schema change would have needed its own if-not-exists logic. The schema is now numbered SQL files built into the binary. At start the store applies the ones the database has no record of, in one transaction behind the advisory lock that was already there, and records them in public.hypeman_auth_schema_migrations. A later change is a new file. --- docs/authorization-server.md | 13 ++-- lib/authserver/README.md | 6 +- .../migrations/0001_spent_assertions.sql | 7 ++ lib/authserver/store.go | 66 +++++++++++++++---- lib/authserver/store_test.go | 38 ++++++++++- 5 files changed, 108 insertions(+), 22 deletions(-) create mode 100644 lib/authserver/migrations/0001_spent_assertions.sql diff --git a/docs/authorization-server.md b/docs/authorization-server.md index 4cd1535ad..b74beccdc 100644 --- a/docs/authorization-server.md +++ b/docs/authorization-server.md @@ -108,11 +108,14 @@ a single insert on the primary key: two instances given the same identity token for it. The record holds a hash of the issuer and token ID and the expiry, nothing else, and is deleted a day after the identity token expired. -Every instance must use the same database, as the same role. The server creates the table and -its index at every start unless they exist, and PostgreSQL checks the privileges for that either -way: the role needs `USAGE` and `CREATE` on the `public` schema and must own the table. For a -database on another machine use `sslmode=verify-full`: the server acts on the result of the -insert, and the connection carries a password. +Every instance must use the same database, as the same role. The schema is a set of numbered SQL +files built into the server. At start the server applies the ones the database has no record of, +in one transaction, and records them in `public.hypeman_auth_schema_migrations`; instances that +start together take turns. The role therefore needs `USAGE` and `CREATE` on the `public` schema +and must own the tables. A release that adds a file leaves the schema usable by the release +before it, so instances of both can run during an upgrade. For a database on another machine use +`sslmode=verify-full`: the server acts on the result of the insert, and the connection carries a +password. If the insert fails no token is issued. The identity token is usually still good, but the database may have recorded it before the failure showed, so a caller whose retry is answered diff --git a/lib/authserver/README.md b/lib/authserver/README.md index 626ba08f6..68c6a2a52 100644 --- a/lib/authserver/README.md +++ b/lib/authserver/README.md @@ -9,5 +9,7 @@ single-use, and signs an access token in the format `lib/accesstoken` verifies. serves that exchange as the RFC 7523 token endpoint, beside the RFC 8414 metadata and the key set. `PostgresStore` is the `SpentStore` for more than one instance: the insert on the primary key -decides which of two concurrent exchanges of one identity token is first. Its test needs a -database and is skipped unless `HYPEMAN_AUTH_TEST_POSTGRES_URL` is set. +decides which of two concurrent exchanges of one identity token is first. Its schema is the +files in `migrations/`, which the store applies when it opens; a schema change is a new file +there, never an edit to one that was released. Its test needs a database and is skipped unless +`HYPEMAN_AUTH_TEST_POSTGRES_URL` is set. diff --git a/lib/authserver/migrations/0001_spent_assertions.sql b/lib/authserver/migrations/0001_spent_assertions.sql new file mode 100644 index 000000000..e89ceb073 --- /dev/null +++ b/lib/authserver/migrations/0001_spent_assertions.sql @@ -0,0 +1,7 @@ +CREATE TABLE public.hypeman_auth_spent_assertions ( + id TEXT PRIMARY KEY, + expires_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX hypeman_auth_spent_assertions_expires_at + ON public.hypeman_auth_spent_assertions (expires_at); diff --git a/lib/authserver/store.go b/lib/authserver/store.go index ff4b3466c..0b088f37b 100644 --- a/lib/authserver/store.go +++ b/lib/authserver/store.go @@ -3,7 +3,9 @@ package authserver import ( "context" "database/sql" + "embed" "fmt" + "io/fs" "log/slog" "time" @@ -26,19 +28,21 @@ const ( spentRetention = 24 * time.Hour spentCleanup = 10 * time.Minute - // The table is named with its schema, so that every instance uses the - // same one whatever its role's search path is. - spentSchema = `CREATE TABLE IF NOT EXISTS public.hypeman_auth_spent_assertions ( - id TEXT PRIMARY KEY, - expires_at TIMESTAMPTZ NOT NULL -)` - spentIndex = `CREATE INDEX IF NOT EXISTS hypeman_auth_spent_assertions_expires_at ON public.hypeman_auth_spent_assertions (expires_at)` + // Tables are named with their schema, here and in the migrations, so + // that every instance uses the same ones whatever its role's search path is. spentInsert = `INSERT INTO public.hypeman_auth_spent_assertions (id, expires_at) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING` // The database's clock decides, so the instances agree on what is old. spentDelete = `DELETE FROM public.hypeman_auth_spent_assertions WHERE expires_at < now() - make_interval(secs => $1)` - // spentSchemaLock serializes instances that start together: CREATE ... - // IF NOT EXISTS alone can fail when two sessions create the table at once. - spentSchemaLock = `SELECT pg_advisory_xact_lock(4801270353920264117)` + + // migrationLock serializes instances that start together. It lasts for + // the transaction, so it works through a transaction pooler. + migrationLock = `SELECT pg_advisory_xact_lock(4801270353920264117)` + migrationTable = `CREATE TABLE IF NOT EXISTS public.hypeman_auth_schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() +)` + migrationApplied = `SELECT EXISTS (SELECT 1 FROM public.hypeman_auth_schema_migrations WHERE version = $1)` + migrationRecord = `INSERT INTO public.hypeman_auth_schema_migrations (version) VALUES ($1)` ) // PostgresStore keeps spent identity tokens in a PostgreSQL table. The insert @@ -48,7 +52,7 @@ type PostgresStore struct { db *sql.DB } -// OpenPostgresStore connects to url and creates the table if it is missing. +// OpenPostgresStore connects to url and brings the schema up to date. func OpenPostgresStore(ctx context.Context, url string) (*PostgresStore, error) { config, err := pgx.ParseConfig(url) if err != nil { @@ -60,24 +64,58 @@ func OpenPostgresStore(ctx context.Context, url string) (*PostgresStore, error) db := stdlib.OpenDB(*config) db.SetMaxOpenConns(10) db.SetConnMaxIdleTime(5 * time.Minute) - if err := createSpentTable(ctx, db); err != nil { + if err := migrate(ctx, db, migrations); err != nil { db.Close() return nil, fmt.Errorf("prepare the replay store: %w", err) } return &PostgresStore{db: db}, nil } -func createSpentTable(ctx context.Context, db *sql.DB) error { +// migrations holds the schema: one file for each change, applied in the +// order of the names and never edited afterwards. An older instance may still +// be running while a new file is applied, so a change must leave the schema +// usable by the release before it. +// +//go:embed migrations/*.sql +var migrations embed.FS + +// migrate applies the files the database has no record of and records them, +// in one transaction: a start that fails leaves the schema as it was. +func migrate(ctx context.Context, db *sql.DB, files fs.FS) error { + entries, err := fs.ReadDir(files, "migrations") + if err != nil { + return err + } tx, err := db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() - for _, statement := range []string{spentSchemaLock, spentSchema, spentIndex} { + for _, statement := range []string{migrationLock, migrationTable} { if _, err := tx.ExecContext(ctx, statement); err != nil { return err } } + for _, entry := range entries { + version := entry.Name() + var applied bool + if err := tx.QueryRowContext(ctx, migrationApplied, version).Scan(&applied); err != nil { + return err + } + if applied { + continue + } + statements, err := fs.ReadFile(files, "migrations/"+version) + if err != nil { + return err + } + if _, err := tx.ExecContext(ctx, string(statements)); err != nil { + return fmt.Errorf("migration %s: %w", version, err) + } + if _, err := tx.ExecContext(ctx, migrationRecord, version); err != nil { + return err + } + } return tx.Commit() } diff --git a/lib/authserver/store_test.go b/lib/authserver/store_test.go index 746075bba..415171453 100644 --- a/lib/authserver/store_test.go +++ b/lib/authserver/store_test.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "testing" + "testing/fstest" "time" "github.com/stretchr/testify/assert" @@ -53,7 +54,7 @@ func TestPostgresStore(t *testing.T) { query.Del("database") location.Path, location.RawQuery = "/"+database, query.Encode() - // Instances that start together on a database without the table all come up. + // Instances that start together on an empty database all come up. stores := make(chan *PostgresStore, 8) for range cap(stores) { go func() { @@ -119,6 +120,41 @@ func TestPostgresStore(t *testing.T) { require.NoError(t, err) require.False(t, spent) + // A later release adds a file: it is applied once, on top of what is there. + // A file that fails changes nothing, the statements before the failure included. + schema, err := migrations.ReadFile("migrations/0001_spent_assertions.sql") + require.NoError(t, err) + later := fstest.MapFS{ + "migrations/0001_spent_assertions.sql": {Data: schema}, + "migrations/0002_later.sql": {Data: []byte(`ALTER TABLE public.hypeman_auth_spent_assertions ADD COLUMN later TEXT`)}, + "migrations/0003_broken.sql": {Data: []byte(`CREATE TABLE public.hypeman_auth_half_done (id TEXT); SELECT no_such_function()`)}, + } + require.ErrorContains(t, migrate(ctx, first.db, later), "0003_broken.sql") + applied := func() (versions []string) { + rows, err := first.db.QueryContext(ctx, `SELECT version FROM public.hypeman_auth_schema_migrations ORDER BY version`) + require.NoError(t, err) + defer rows.Close() + for rows.Next() { + var version string + require.NoError(t, rows.Scan(&version)) + versions = append(versions, version) + } + require.NoError(t, rows.Err()) + return versions + } + require.Equal(t, []string{"0001_spent_assertions.sql"}, applied()) + delete(later, "migrations/0003_broken.sql") + require.NoError(t, migrate(ctx, first.db, later)) + require.NoError(t, migrate(ctx, second.db, later), "nothing is left to apply") + require.Equal(t, []string{"0001_spent_assertions.sql", "0002_later.sql"}, applied()) + _, err = first.db.ExecContext(ctx, `CREATE TABLE public.hypeman_auth_half_done (id TEXT)`) + require.NoError(t, err, "the broken file left no table behind") + // A release from before the later file still starts and still works. + require.NoError(t, migrate(ctx, first.db, migrations)) + spent, err = first.Spend(ctx, newID(), time.Now().Add(5*time.Minute)) + require.NoError(t, err) + require.True(t, spent) + _, err = OpenPostgresStore(ctx, "postgres://user:secret-password@%zz") require.Error(t, err) require.NotContains(t, err.Error(), "secret-password")