Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion cmd/api/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"time"

"github.com/c2h5oh/datasize"
"github.com/go-viper/mapstructure/v2"
"github.com/kernel/hypeman/lib/oidcfederation"
"github.com/kernel/hypeman/lib/snapshot"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
Expand Down Expand Up @@ -297,6 +299,10 @@ type Config struct {
// even though they are signed with JwtSecret and not yet expired.
RevokedTokenHashes []string `koanf:"revoked_token_hashes"`

// OIDC configures the external issuers and federation rules whose identity
// tokens can be exchanged for short-lived API tokens.
OIDC oidcfederation.Config `koanf:"oidc"`

Network NetworkConfig `koanf:"network"`
Caddy CaddyConfig `koanf:"caddy"`
ACME ACMEConfig `koanf:"acme"`
Expand Down Expand Up @@ -564,8 +570,14 @@ func Load(configPath string) (*Config, error) {
return nil, fmt.Errorf("JWT_VERIFICATION_SECRETS must be a JSON array of strings")
}
}
var oidc map[string]interface{}
if value := os.Getenv("OIDC"); value != "" {
if err := json.Unmarshal([]byte(value), &oidc); err != nil || oidc == nil {
return nil, fmt.Errorf("OIDC must be a JSON object")
}
}
envProvider := env.ProviderWithValue("", "__", func(key string, value string) (string, interface{}) {
if value == "" {
if value == "" || key == "OIDC" {
return "", nil
}
if key == "JWT_VERIFICATION_SECRETS" {
Expand All @@ -574,12 +586,31 @@ func Load(configPath string) (*Config, error) {
return strings.ToLower(key), value
})
_ = k.Load(envProvider, nil)
// OIDC replaces the YAML block as a whole: merging would leave rules from
// the file trusting issuers the environment redefined.
if oidc != nil {
k.Delete("oidc")
if err := k.Set("oidc", oidc); err != nil {
return nil, fmt.Errorf("failed to load OIDC: %w", err)
}
}

// 4. Unmarshal to Config struct
var cfg Config
if err := k.Unmarshal("", &cfg); err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
// Decode the oidc block again, rejecting unknown keys: a misspelled
// restriction would otherwise be dropped and leave its rule wider than written.
cfg.OIDC = oidcfederation.Config{}
if err := k.UnmarshalWithConf("oidc", &cfg.OIDC, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{
TagName: "koanf",
WeaklyTypedInput: true,
ErrorUnused: true,
Result: &cfg.OIDC,
}}); err != nil {
return nil, fmt.Errorf("invalid oidc config: %w", err)
}
cfg.expandPathFields()

return &cfg, nil
Expand Down Expand Up @@ -615,6 +646,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("jwt_verification_secrets entry %d must not be empty", i)
}
}
if _, err := oidcfederation.Compile(c.OIDC); err != nil {
return err
}
if c.MacOSOnly && (runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" || c.Hypervisor.Default != "vz") {
return fmt.Errorf("macos_only requires vz on Apple silicon")
}
Expand Down
139 changes: 139 additions & 0 deletions cmd/api/config/oidc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package config

import (
"os"
"path/filepath"
"testing"

"github.com/kernel/hypeman/lib/oidcfederation"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const oidcYAML = `
oidc:
issuers:
- name: github-actions
preset_type: github_actions
- name: cluster
preset_type: kubernetes
issuer_url: https://cluster.example.test
token_validation:
max_lifetime_seconds: 600
federation_rules:
- name: ci
issuer: github-actions
expected_audience: https://hypeman.example.test
match:
type: github_actions
repository_id: 12
repository_owner_id: "34"
workflow: .github/workflows/test.yml
ref: refs/heads/main
event_names: [schedule]
claims:
/runner_environment: github-hosted
authorization:
permissions: [instance:read, instance:write]
- name: pods
issuer: cluster
expected_audience: https://hypeman.example.test
match:
type: kubernetes
namespace: ci
service_account: runner
claims:
/kubernetes.io/namespace: ci
authorization:
permissions: [image:read]
max_token_ttl_seconds: 120
`

func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0600))
return path
}

func TestLoadOIDC(t *testing.T) {
t.Setenv("OIDC", "")
cfg, err := Load(writeConfig(t, oidcYAML))
require.NoError(t, err)
require.NoError(t, cfg.Validate())
registry, err := oidcfederation.Compile(cfg.OIDC)
require.NoError(t, err)

ci, ok := registry.Rule("ci")
require.True(t, ok)
assert.Equal(t, oidcfederation.GitHubIssuer, ci.IssuerSpec.IssuerURL)
assert.Equal(t, "12", ci.Match.RepositoryID, "an unquoted numeric ID is read as text")
assert.Equal(t, []string{"schedule"}, ci.Match.EventNames)
assert.Equal(t, "github-hosted", ci.Match.Claims["/runner_environment"])
assert.Equal(t, []string{"instance:read", "instance:write"}, ci.Authorization.Permissions)

pods, ok := registry.Rule("pods")
require.True(t, ok)
assert.Equal(t, "ci", pods.Match.Claims["/kubernetes.io/namespace"], "a dotted claim pointer is one key")
assert.Equal(t, 600, *pods.IssuerSpec.TokenValidation.MaxLifetimeSeconds)
assert.Equal(t, 120, *pods.Authorization.MaxTokenTTLSeconds)
}

func TestLoadWithoutOIDC(t *testing.T) {
t.Setenv("OIDC", "")
cfg, err := Load(writeConfig(t, "{}\n"))
require.NoError(t, err)
require.NoError(t, cfg.Validate())
registry, err := oidcfederation.Compile(cfg.OIDC)
require.NoError(t, err)
assert.False(t, registry.Enabled())
}

// The environment replaces the file's block; it is not merged into it.
func TestLoadOIDCFromEnvironment(t *testing.T) {
t.Setenv("OIDC", `{"issuers":[{"name":"idp","issuer_url":"https://idp.example.test"}],"federation_rules":[{"name":"deploy","issuer":"idp","expected_audience":"https://hypeman.example.test","match":{"type":"custom_oidc","subject":"deployer"},"authorization":{"permissions":["image:write"],"max_token_ttl_seconds":60}}]}`)
cfg, err := Load(writeConfig(t, oidcYAML))
require.NoError(t, err)
require.NoError(t, cfg.Validate())
registry, err := oidcfederation.Compile(cfg.OIDC)
require.NoError(t, err)
_, ok := registry.Rule("ci")
assert.False(t, ok, "rules from the file do not survive the override")
deploy, ok := registry.Rule("deploy")
require.True(t, ok)
assert.Equal(t, 60, *deploy.Authorization.MaxTokenTTLSeconds)

t.Setenv("OIDC", `{}`)
cfg, err = Load(writeConfig(t, oidcYAML))
require.NoError(t, err)
assert.Empty(t, cfg.OIDC.FederationRules, "an empty object turns federation off")
}

func TestLoadOIDCRejectsInvalidConfig(t *testing.T) {
for name, body := range map[string]string{
// A misspelled restriction must not be dropped silently.
"unknown rule key": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s, subject_prefx: t}\n authorization: {permissions: [image:read]}\n",
"unknown block key": "oidc:\n issuer: []\n",
// A repository name is pinned through claims; a field the matcher ignored would look enforced.
"repository name key": "oidc:\n issuers: [{name: gh, preset_type: github_actions}]\n federation_rules:\n - name: r\n issuer: gh\n expected_audience: a\n match: {type: github_actions, repository: owner/name, repository_id: 1, repository_owner_id: 2, workflow: .github/workflows/ci.yml, ref: refs/heads/main}\n authorization: {permissions: [image:read]}\n",
"unknown issuer": "oidc:\n federation_rules:\n - name: r\n issuer: missing\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n authorization: {permissions: [image:read]}\n",
"no permissions": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n",
"wildcard permission": "oidc:\n issuers: [{name: idp, issuer_url: 'https://idp.example.test'}]\n federation_rules:\n - name: r\n issuer: idp\n expected_audience: a\n match: {type: custom_oidc, subject: s}\n authorization: {permissions: ['*']}\n",
} {
t.Run(name, func(t *testing.T) {
t.Setenv("OIDC", "")
cfg, err := Load(writeConfig(t, body))
if err == nil {
err = cfg.Validate()
}
require.Error(t, err)
})
}
for _, value := range []string{`[]`, `null`, `"oidc"`, `{"issuers":`, `{"unknown":true}`} {
t.Run(value, func(t *testing.T) {
t.Setenv("OIDC", value)
_, err := Load(writeConfig(t, "{}\n"))
require.Error(t, err)
})
}
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ require (
github.com/getkin/kin-openapi v0.133.0
github.com/ghodss/yaml v1.0.0
github.com/go-chi/chi/v5 v5.3.0
github.com/go-jose/go-jose/v4 v4.1.5
github.com/go-viper/mapstructure/v2 v2.4.0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/go-containerregistry v0.20.6
github.com/google/uuid v1.6.0
Expand Down Expand Up @@ -97,7 +99,6 @@ require (
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-test/deep v1.1.1 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA=
github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
Expand Down
51 changes: 51 additions & 0 deletions lib/oidcfederation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# oidcfederation

Validates OIDC identity tokens from operator-configured issuers, so a workload can prove who it
is with a token it already holds instead of a stored Hypeman API token.

Trust is two kinds of object, both written in the `oidc` block of the server configuration:

- An **issuer** names who signs: an issuer URL, where its public keys come from (`discovery`,
`explicit_url` or `inline`), the longest assertion lifetime accepted, and whether an assertion
may be presented more than once.
- A **federation rule** names which workload of one issuer is accepted and what it receives: the
audience the assertion must carry, the conditions its claims must meet, a `permissions` scope
list and a token lifetime.

`Compile` validates a configuration and returns a `Registry` of rules. `Verifier.Verify` checks one
assertion against a rule's issuer and audience, and `Match.Matches` evaluates the rule's conditions
on the verified claims.

## Presets

Each issuer has a `preset_type`, and a rule's `match.type` must be the same type. A preset carries
its provider's mandatory identity checks, so a rule cannot trade them for a generic matcher.

| Preset | Recognized by | A rule must name |
|---|---|---|
| `github_actions` | issuer URL | numeric `repository_id` and `repository_owner_id`, one of `workflow`, `workflow_ref` or `job_workflow_ref`, and `ref` or `environment`. `event_names` defaults to `push` and `workflow_dispatch`. |
| `google_cloud` | issuer URL | a numeric `subject` |
| `microsoft_entra` | issuer URL | `subject`, or an `/oid`, `/appid` or `/azp` claim. The tenant is pinned from the issuer URL. Tokens carrying delegated scopes are refused. |
| `kubernetes` | configuration | `namespace` and `service_account` |
| `aws`, `custom_oidc` | configuration | `subject`, `subject_prefix` or at least one claim |

`claims` maps a JSON Pointer to the text a scalar claim must equal. Booleans and numbers compare by
their JSON text; objects and arrays never match.

## Verification

- The token's `iss` must equal the configured issuer URL before any key is fetched. Key locations
come only from configuration, never from the token.
- Keys are fetched over HTTPS from public addresses only, without redirects or an ambient proxy,
and cached for five minutes. An unknown `kid` forces a refresh: after one that succeeds, the
next waits a minute; after a fetch that fails, the next attempt waits ten seconds. Keys
published for another purpose, such as encryption, are ignored.
- Only asymmetric signature algorithms are accepted, and only RS256 for GitHub, Google and Entra.
- An assertion needs `sub`, `iat`, `exp` and exactly one `aud` equal to the rule's
`expected_audience`. Its lifetime must fit the issuer's `max_lifetime_seconds`.
- A single-use issuer's assertion needs a token ID (`jti`, or `uti` for Entra). GitHub and AWS are
always single-use. Google identity tokens carry no ID, so Google always allows reuse. Kubernetes
allows reuse by default, because a pod reads the same projected token until it is rotated.

The verifier reports only that an assertion is invalid or that keys are unavailable. A
`KeyProblem` carries the reason an issuer's keys cannot be used, for the operator's logs.
76 changes: 76 additions & 0 deletions lib/oidcfederation/claims.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package oidcfederation

import (
"encoding/json"
"fmt"
"strconv"
"strings"
)

func pointerParts(pointer string) ([]string, error) {
if pointer == "" || !strings.HasPrefix(pointer, "/") || len(pointer) > 1024 {
return nil, fmt.Errorf("%w: claim selector must be a JSON Pointer", ErrInvalid)
}
parts := strings.Split(pointer[1:], "/")
for i, part := range parts {
var decoded strings.Builder
for j := 0; j < len(part); j++ {
if part[j] != '~' {
decoded.WriteByte(part[j])
continue
}
j++
if j == len(part) || (part[j] != '0' && part[j] != '1') {
return nil, ErrInvalid
}
if part[j] == '0' {
decoded.WriteByte('~')
} else {
decoded.WriteByte('/')
}
}
parts[i] = decoded.String()
}
return parts, nil
}

// ClaimString resolves a JSON Pointer to a scalar claim as text. Providers send
// some claims as booleans or numbers (Google's email_verified is true, not
// "true"), so those compare by their JSON text. Objects and arrays never match.
func ClaimString(claims map[string]any, pointer string) (string, bool) {
parts, err := pointerParts(pointer)
if err != nil {
return "", false
}
var value any = claims
for _, part := range parts {
switch node := value.(type) {
case map[string]any:
var ok bool
value, ok = node[part]
if !ok {
return "", false
}
case []any:
index, err := strconv.Atoi(part)
if err != nil || index < 0 || index >= len(node) || strconv.Itoa(index) != part {
return "", false
}
value = node[index]
default:
return "", false
}
}
switch scalar := value.(type) {
case string:
return scalar, true
case bool:
return strconv.FormatBool(scalar), true
case json.Number:
return scalar.String(), true
case float64:
return strconv.FormatFloat(scalar, 'f', -1, 64), true
default:
return "", false
}
}
Loading
Loading