Skip to content
Merged
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
20 changes: 20 additions & 0 deletions 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/accesstoken"
"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"`

// OAuth names the authorization servers whose access tokens are accepted
// as API tokens, and the audiences those tokens must be issued for.
OAuth accesstoken.Config `koanf:"oauth"`

Network NetworkConfig `koanf:"network"`
Caddy CaddyConfig `koanf:"caddy"`
ACME ACMEConfig `koanf:"acme"`
Expand Down Expand Up @@ -580,6 +586,17 @@ func Load(configPath string) (*Config, error) {
if err := k.Unmarshal("", &cfg); err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
// Decode the oauth block again, rejecting unknown keys: a misspelled key
// would otherwise be dropped and leave the block meaning something else.
cfg.OAuth = accesstoken.Config{}
if err := k.UnmarshalWithConf("oauth", &cfg.OAuth, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{
TagName: "koanf",
WeaklyTypedInput: true,
ErrorUnused: true,
Result: &cfg.OAuth,
}}); err != nil {
return nil, fmt.Errorf("invalid oauth config: %w", err)
}
cfg.expandPathFields()

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

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

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

func loadYAML(t *testing.T, body string) (*Config, error) {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return Load(path)
}

func TestLoadOAuth(t *testing.T) {
cfg, err := loadYAML(t, `
oauth:
audiences: [prod, https://host-1.example.test]
authorization_servers:
- issuer: https://auth.example.test
- issuer: https://other.example.test
jwks:
type: explicit_url
url: https://other.example.test/keys.json
`)
require.NoError(t, err)
require.NoError(t, cfg.Validate())
require.Equal(t, []string{"prod", "https://host-1.example.test"}, cfg.OAuth.Audiences)
require.Len(t, cfg.OAuth.AuthorizationServers, 2)
require.Equal(t, "https://auth.example.test", cfg.OAuth.AuthorizationServers[0].Issuer)
require.Equal(t, "https://other.example.test/keys.json", cfg.OAuth.AuthorizationServers[1].JWKS.URL)

// Without the block nothing is configured.
cfg, err = loadYAML(t, "port: 4973\n")
require.NoError(t, err)
require.NoError(t, cfg.Validate())
require.Empty(t, cfg.OAuth.AuthorizationServers)
}

func TestOAuthRejectsUnknownKeysAndInvalidSettings(t *testing.T) {
for _, body := range []string{
"oauth:\n audience: [prod]\n",
"oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n jwks_url: https://auth.example.test/keys\n",
"oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n jwks:\n kind: discovery\n",
} {
_, err := loadYAML(t, body)
require.ErrorContains(t, err, "invalid oauth config", body)
}
for _, body := range []string{
"oauth:\n authorization_servers:\n - issuer: https://auth.example.test\n",
"oauth:\n audiences: [prod]\n",
"oauth:\n audiences: [prod]\n authorization_servers:\n - issuer: http://auth.example.test\n",
} {
cfg, err := loadYAML(t, body)
require.NoError(t, err, body)
require.ErrorIs(t, cfg.Validate(), accesstoken.ErrInvalidConfig, body)
}
}
9 changes: 9 additions & 0 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/kernel/hypeman"
"github.com/kernel/hypeman/cmd/api/api"
"github.com/kernel/hypeman/cmd/api/config"
"github.com/kernel/hypeman/lib/accesstoken"
"github.com/kernel/hypeman/lib/devices"
"github.com/kernel/hypeman/lib/guest"
"github.com/kernel/hypeman/lib/hypervisor/qemu"
Expand Down Expand Up @@ -286,6 +287,14 @@ func run() error {
if err != nil {
return fmt.Errorf("initialize JWT verifier: %w", err)
}
accessTokens, err := accesstoken.New(app.Config.OAuth, accesstoken.NewFileKeyStore(paths.New(app.Config.DataDir).OAuthKeysDir(), logger), logger)
if err != nil {
return fmt.Errorf("initialize OAuth access tokens: %w", err)
}
if accessTokens.Enabled() {
logger.Info("accepting access tokens from authorization servers", "authorization_servers", len(app.Config.OAuth.AuthorizationServers), "audiences", app.Config.OAuth.Audiences)
jwtVerifier = jwtVerifier.WithAccessTokens(accessTokens)
}
revokedTokens, err := tokenrevocation.New(app.Config.RevokedTokenHashes)
if err != nil {
return fmt.Errorf("invalid revoked_token_hashes: %w", err)
Expand Down
9 changes: 9 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ jwt_secret: ""
# revoked_token_hashes:
# - 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

# Optional - also accept access tokens issued by an OAuth authorization server.
# The server only verifies them, with the authorization server's public keys.
# See docs/oauth-access-tokens.md.
# oauth:
# audiences:
# - https://hypeman.example.com
# authorization_servers:
# - issuer: https://auth.example.com

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

Expand Down
94 changes: 94 additions & 0 deletions docs/oauth-access-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# OAuth access tokens

Hypeman can accept access tokens issued by an OAuth authorization server, beside the tokens signed
with `jwt_secret`. For these tokens the server is a resource server: it holds the authorization
server's public keys, so it can verify the tokens and cannot issue them.

## Configure

```yaml
oauth:
audiences:
- https://hypeman.example.com
authorization_servers:
- issuer: https://auth.example.com
```

| Key | Meaning |
|---|---|
| `audiences` | The names this server answers to. A token is accepted only if its `aud` holds at least one of them. Servers that share an audience accept the same tokens. |
| `authorization_servers[].issuer` | The authorization server's issuer URL. It must equal a token's `iss` exactly. |
| `authorization_servers[].jwks` | Where the server's public keys come from; see [Keys](#keys). Optional. |

Restart after a change. A block that is not valid stops the server from starting, and so does a
key it does not know. `jwt_secret` is still required, and tokens signed with it work as before.

## What a token needs

Access tokens follow the JWT format of [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068).

| Part | Requirement |
|---|---|
| `typ` header | `at+jwt`. A token without it is never checked against an authorization server's keys, and a token with it is never checked against `jwt_secret`. |
| `alg` header | An asymmetric algorithm: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512 or EdDSA. The key must be of that algorithm's kind, and for ES256, ES384 and ES512 on its curve. |
| `kid` header | Names the signing key. It may be left out only when the server publishes a single key. |
| `iss` | A configured `issuer`. |
| `aud` | A string or a list holding at least one configured audience. |
| `sub` | Who the token is for. It is the user in logs. |
| `client_id` | The client the token was issued to. Required. |
| `iat`, `exp` | Required. `nbf` is honoured if present. Clocks may differ by 30 seconds. |
| `scope` | Optional. Space-separated permissions such as `instance:read image:read`, or `*` for all of them. |
| `jti` | The token's ID. Required. |

A token is at most 16 KB. Its lifetime is the authorization server's to choose.

A token without a `scope` has no permissions. This differs from a token signed with `jwt_secret`,
where a missing `permissions` claim means full access. As for every API token, the registry under
`/v2` does not check permissions.

`revoked_token_hashes` applies to access tokens as it does to the others. Revoking a token signed
with ES256, ES384 or ES512 also revokes the second token string that carries the same signature.

## Keys

`jwks.type` selects the source:

| Type | Source |
|---|---|
| `discovery` (default) | The key set named by `jwks_uri` in the server's [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) metadata, at `/.well-known/oauth-authorization-server`. |
| `explicit_url` | The key set at `jwks.url`. |
| `inline` | The public JWKs listed in `jwks.keys`. Nothing is fetched. |

`jwks.ca_cert_pem` replaces the system roots for the fetch.

Fetched keys are handled so that requests do not wait on the authorization server:

- Keys are fetched over HTTPS from public addresses only, without redirects or a proxy, and kept
for five minutes. After that they are refreshed in the background while requests are still
verified with the last key set.
- A token signed with a key the last set lacks triggers a refresh, at most one a minute. This is
how a new signing key is picked up without a restart.
- The last key set is also saved under `<data_dir>/oauth/keys/`, with the time it was fetched. A
server that restarts continues from that copy as if it had kept running: a copy fetched less
than five minutes ago is used until those five minutes are over, and an older one is used while
the key set is fetched again. Only a server with no saved copy, such as one that has just been
configured, makes its first requests wait for a fetch.
- If a fetched key set cannot be saved, the older copy is removed, so that a restart cannot bring
back keys the authorization server has withdrawn since. The restart then waits for a fetch.

A key removed from the authorization server stops being trusted at the next successful fetch, at
most five minutes later while the authorization server is reachable, whether or not the server
restarted in between. A key set that is empty, or holds only valid public keys for other purposes
such as encryption, is such a fetch too, and withdraws every key. While the authorization server
is unreachable or answers with anything else, the last key set stays trusted, for as long as that
lasts. To drop it at once, delete the saved copy and restart: until a fetch succeeds, no access
token is then accepted.

## Monitor

`hypeman_jwt_validations_total{key_role="authorization_server"}` counts verified access tokens.

A key fetch that fails is logged as a warning, with whether the last key set is still in use, at
most every ten seconds for each authorization server. A copy that could not be saved is logged as a
warning as well, or as an error if the older copy could not be removed either. A start from the
saved copy is logged at info level, with the copy's fetch time.
15 changes: 15 additions & 0 deletions lib/accesstoken/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# accesstoken

Verifies the access tokens an OAuth authorization server issues for this server, in the JWT format
of RFC 9068. Operator documentation is in
[docs/oauth-access-tokens.md](../../docs/oauth-access-tokens.md).

`New` validates the `oauth` block of the server configuration. `Verifier.Verify` selects the
authorization server a token names in `iss`, has `lib/oidcfederation` check the signature, type
and time claims against that server's keys, and then requires a subject, a client ID, a token ID
and one of this server's audiences. The token's `scope` becomes `Claims.Permissions`, which is never nil.

`lib/jwtauth` calls it for tokens whose `typ` header is `at+jwt` (`Typed`), and only for those.

`FileKeyStore` keeps each authorization server's last fetched key set in a file, with the time it
was fetched, so that a restarted server continues with the key cache it had.
Loading
Loading