Repository navigation
Add hypeman-auth, the OAuth authorization server #618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rgarcia
wants to merge
3
commits into
main
Choose a base branch
from
hypeship/auth-server
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,099
−7
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # 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 | ||
| USER nonroot:nonroot | ||
| EXPOSE 8080 | ||
| ENTRYPOINT ["/hypeman-auth"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| // 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) | ||
| } | ||
| } | ||
| // 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 { | ||
| 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, 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) | ||
| // 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) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.