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
1 change: 1 addition & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ Common settings:
| `data_dir` | Data directory for VM images, volumes, etc. | `/var/lib/hypeman` |
| `jwt_secret` | Secret key for JWT authentication (required) | _(empty)_ |
| `revoked_token_hashes` | Hex SHA-256 digests of API tokens to reject before they expire (`printf '%s' "$TOKEN" \| sha256sum`) | _(empty)_ |
| `oidc` | OIDC issuers and federation rules whose identity tokens can be exchanged for short-lived API tokens; see [docs/oidc-federation.md](docs/oidc-federation.md). `OIDC` in the environment is one JSON document that replaces the block | _(empty)_ |
| `env` | Deployment environment (filters telemetry) | `unset` |
| `network.bridge_name` | Network bridge for VM networking | `vmbr0` |
| `network.subnet_cidr` | CIDR for the VM network subnet | `10.100.0.0/16` |
Expand Down
24 changes: 24 additions & 0 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
mw "github.com/kernel/hypeman/lib/middleware"
"github.com/kernel/hypeman/lib/oapi"
"github.com/kernel/hypeman/lib/ocicachegc"
"github.com/kernel/hypeman/lib/oidcfederation"
"github.com/kernel/hypeman/lib/otel"
"github.com/kernel/hypeman/lib/paths"
"github.com/kernel/hypeman/lib/registry"
Expand Down Expand Up @@ -286,6 +287,19 @@ func run() error {
if err != nil {
return fmt.Errorf("initialize JWT verifier: %w", err)
}
oidcRegistry, err := oidcfederation.Compile(app.Config.OIDC)
if err != nil {
return fmt.Errorf("initialize OIDC federation: %w", err)
}
tokenExchanger, err := oidcfederation.NewExchanger(oidcRegistry, app.Config.JwtSecret, paths.New(app.Config.DataDir).OIDCSpentAssertions(), otelProvider.Meter)
if err != nil {
return fmt.Errorf("initialize OIDC federation: %w", err)
}
if tokenExchanger.Enabled() && !tokenExchanger.SpentRecordComplete() {
logger.Warn("no complete record of spent OIDC identity tokens was found; single-use identity tokens issued before the floor are refused", "floor", tokenExchanger.SpentRecordFloor())
}
// Tokens issued for a federation rule stay valid only while that rule is configured unchanged.
jwtVerifier = jwtVerifier.WithFederation(tokenExchanger)
revokedTokens, err := tokenrevocation.New(app.Config.RevokedTokenHashes)
if err != nil {
return fmt.Errorf("invalid revoked_token_hashes: %w", err)
Expand Down Expand Up @@ -441,6 +455,16 @@ func run() error {
mw.ResolveResource(app.ApiService.NewResolvers(), api.ResolverErrorResponder),
).Get("/instances/{id}/cp", app.ApiService.CpHandler)

// OIDC assertion exchange (outside OpenAPI spec: form-encoded, and the
// assertion is the only credential)
r.With(
middleware.RequestID,
middleware.RealIP,
middleware.Recoverer,
mw.InjectLogger(logger),
mw.AccessLogger(accessLogger),
).Post("/oauth/token", tokenExchanger.ServeHTTP)

// Create builder VM resolver for secure token authentication
// This validates that token requests from builder VMs are for their authorized repos only
// Create token handler for Docker Registry Token Authentication
Expand Down
129 changes: 129 additions & 0 deletions cmd/api/oidc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package main

import (
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"math/big"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"time"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/go-chi/chi/v5"
"github.com/golang-jwt/jwt/v5"
"github.com/kernel/hypeman/lib/jwtauth"
mw "github.com/kernel/hypeman/lib/middleware"
"github.com/kernel/hypeman/lib/oapi"
"github.com/kernel/hypeman/lib/oidcfederation"
"github.com/kernel/hypeman/lib/scopes"
nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/metric/noop"
)

// oidcTestServer wires the token endpoint and an authenticated API route the
// way run() does, for an issuer whose public key is configured inline.
func oidcTestServer(t *testing.T, key *rsa.PublicKey, permissions []string) http.Handler {
t.Helper()
registry, err := oidcfederation.Compile(oidcfederation.Config{
Issuers: []oidcfederation.IssuerSpec{{
Name: "idp",
IssuerURL: "https://idp.example.test",
// On its first start a server has no record of spent assertions and
// refuses single-use ones for a while.
TokenValidation: oidcfederation.TokenValidation{ReplayProtection: oidcfederation.ReplayAllowReuse},
JWKS: oidcfederation.KeySource{Type: "inline", Keys: []map[string]any{{
"kty": "RSA", "kid": "key-a", "alg": "RS256", "use": "sig",
"n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()),
"e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.E)).Bytes()),
}}},
}},
FederationRules: []oidcfederation.RuleSpec{{
Name: "deploy", Issuer: "idp", ExpectedAudience: "https://hypeman.example.test",
Match: oidcfederation.Match{Type: "custom_oidc", Subject: "deployer"},
Authorization: oidcfederation.RuleAuthorization{Permissions: permissions},
}},
})
require.NoError(t, err)
meter := noop.NewMeterProvider().Meter("test")
exchanger, err := oidcfederation.NewExchanger(registry, testJWTSecret, filepath.Join(t.TempDir(), "spent"), meter)
require.NoError(t, err)
verifier, err := jwtauth.NewVerifier(testJWTSecret, nil, meter)
require.NoError(t, err)
verifier = verifier.WithFederation(exchanger)
spec, err := oapi.GetSwagger()
require.NoError(t, err)
spec.Servers = nil

r := chi.NewRouter()
r.Post("/oauth/token", exchanger.ServeHTTP)
r.Group(func(r chi.Router) {
r.Use(nethttpmiddleware.OapiRequestValidatorWithOptions(spec, &nethttpmiddleware.Options{
Options: openapi3filter.Options{AuthenticationFunc: mw.OapiAuthenticationFunc(verifier, nil)},
ErrorHandler: mw.OapiErrorHandler,
}))
r.Use(scopes.Middleware())
r.Get("/images", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`[]`)) })
r.Post("/images", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) })
})
return r
}

func TestOIDCExchangedTokenAuthenticatesWithItsRulesScopes(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
server := oidcTestServer(t, &key.PublicKey, []string{"image:read"})

assertion := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iss": "https://idp.example.test", "sub": "deployer", "aud": "https://hypeman.example.test",
"iat": time.Now().Unix(), "exp": time.Now().Add(5 * time.Minute).Unix(),
})
assertion.Header["kid"] = "key-a"
signed, err := assertion.SignedString(key)
require.NoError(t, err)

exchange := func(server http.Handler) *httptest.ResponseRecorder {
form := url.Values{"grant_type": {oidcfederation.GrantTypeJWTBearer}, "assertion": {signed}, "federation_rule_id": {"deploy"}}
request := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
recorder := httptest.NewRecorder()
server.ServeHTTP(recorder, request)
return recorder
}
call := func(server http.Handler, method, token string) int {
body := ""
if method == http.MethodPost {
body = `{"name":"docker.io/library/alpine:latest"}`
}
request := httptest.NewRequest(method, "/images", strings.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
server.ServeHTTP(recorder, request)
return recorder.Code
}

issued := exchange(server)
require.Equal(t, http.StatusOK, issued.Code, issued.Body.String())
var response struct {
AccessToken string `json:"access_token"`
Scope string `json:"scope"`
}
require.NoError(t, json.Unmarshal(issued.Body.Bytes(), &response))
assert.Equal(t, "image:read", response.Scope)

assert.Equal(t, http.StatusOK, call(server, http.MethodGet, response.AccessToken))
assert.Equal(t, http.StatusForbidden, call(server, http.MethodPost, response.AccessToken), "the token holds only its rule's permissions")

// The same rule name with different permissions is a different revision:
// a server restarted with it rejects the token issued before the change.
changed := oidcTestServer(t, &key.PublicKey, []string{"image:read", "image:write"})
assert.Equal(t, http.StatusUnauthorized, call(changed, http.MethodGet, response.AccessToken))
}
22 changes: 22 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,28 @@ jwt_secret: ""
# revoked_token_hashes:
# - 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

# Optional - let workloads trade an OIDC identity token (GitHub Actions, a cloud
# workload identity, a Kubernetes service account, ...) for a short-lived API
# token at POST /oauth/token, instead of storing an API token with them.
# Nothing is trusted until an issuer and a rule are configured. Restart after
# changes; see docs/oidc-federation.md.
# oidc:
# issuers:
# - name: github-actions
# preset_type: github_actions
# federation_rules:
# - name: ci
# issuer: github-actions
# expected_audience: https://hypeman.example.com
# match:
# type: github_actions
# repository_id: "123456789"
# repository_owner_id: "987654321"
# workflow: .github/workflows/deploy.yml
# ref: refs/heads/main
# authorization:
# permissions: [image:read, image:write]

# Data directory (default: /var/lib/hypeman)
data_dir: /var/lib/hypeman

Expand Down
6 changes: 6 additions & 0 deletions docs/jwt-rotation.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ Apply each phase with a restart:
`/v2/token` does not re-sign credentials. Account for infrequent callers and
year-long installer-issued CLI tokens.

Tokens issued by the [OIDC assertion exchange](oidc-federation.md) are signed
with `jwt_secret` and live at most 10 minutes. Their callers hold nothing to
reissue: after signing switches, the next exchange is signed with the new key.
The restarts do not interrupt them: spent single-use identity tokens are
recorded on disk, so exchanges work as soon as the server is up.

## Caveats

- **Environment overrides YAML:** `JWT_SECRET` sets the signing key;
Expand Down
Loading
Loading