1 parent
d53552f855
commit
2348d2e4b4
15 files changed
+412
-36
No files matched your search
@@ -316,9 +316,11 @@ file.
|
||||
| `api.allow_blocklist_write` | bool | `true` | **unused** |
|
||||
| `api.trusted_proxies` | list of CIDR | empty | the only peers whose `X-Forwarded-For` / `X-Real-IP` is believed |
|
||||
| `api.cors_origins` | list | empty | `"*"` is allowed but discouraged; the origin is echoed per request so credentials keep working |
|
||||
| `api.auth.mode` | `none` \| `apikey` \| `basic` | `apikey` | see [Admin API](#admin-api) |
|
||||
| `api.auth.mode` | `none` \| `apikey` \| `basic` \| `oidc` | `apikey` | see [Admin API](#admin-api) |
|
||||
| `api.auth.api_keys` | list | empty | full-access keys (`X-API-Key` header, or basic auth with any user) |
|
||||
| `api.auth.read_only_api_keys` | list | empty | GET-only keys; mutations answer 403 |
|
||||
| `api.auth.oidc_issuer` / `oidc_audience` / `oidc_client_id` | strings | empty | OIDC issuer, accepted access-token audience, and public browser client id; required in `oidc` mode |
|
||||
| `api.auth.oidc_write_roles` | list | `[admin]` | OIDC roles allowed to make changes; other authenticated users are read-only |
|
||||
| `api.auth.username` / `password` | string | — | for `mode: basic`; the password may be plaintext or a bcrypt hash (it is hashed either way and compared in constant time) |
|
||||
| `api.auth.session_ttl` | duration | `12h` | lifetime of a `POST /api/auth/login` bearer token |
|
||||
| `api.auth.trust_loopback` | bool | `true` | requests from `127.0.0.0/8` and `::1` authenticate as a local principal without a key |
|
||||
@@ -520,6 +522,18 @@ hash in constant time. `basic`: HTTP basic against `auth.username` /
|
||||
mutation are open to anyone who can reach the port; the settings validator
|
||||
emits a warning for exactly this.
|
||||
|
||||
`oidc` mode signs the console in through a public PKCE client. Configure
|
||||
`oidc_issuer` (for go-auth, `https://users.k6n.net`), `oidc_client_id`, and
|
||||
`oidc_audience` (the resource audience included in the client's access tokens).
|
||||
Register `https://<fancy-dns-host>/auth/oidc/callback` as a redirect URI, and
|
||||
include the configured audience in the client's `audience` list. The API
|
||||
validates RS256 signatures and issuer, audience and expiry using OIDC discovery
|
||||
and JWKS. Users carrying a role listed in `oidc_write_roles` (default `admin`)
|
||||
can make changes; other valid users have read-only access. Discovery metadata
|
||||
is fetched lazily on the first bearer-token request. Set `trust_loopback: false`
|
||||
on networked deployments if local requests should also require an OIDC token;
|
||||
the loopback bypass is independent of the selected auth mode.
|
||||
|
||||
JSON request bodies are capped at 4 MiB and unknown fields are rejected, so a
|
||||
typo is a 400 rather than a silent no-op. A panic in a handler becomes a 500
|
||||
and is logged.
|
||||
|
||||
@@ -198,12 +198,18 @@ api:
|
||||
trusted_proxies: []
|
||||
cors_origins: []
|
||||
auth:
|
||||
# none | apikey | basic
|
||||
# none | apikey | basic | oidc
|
||||
mode: apikey
|
||||
api_keys: ["CHANGE-ME-long-random-string"]
|
||||
read_only_api_keys: []
|
||||
trust_loopback: true
|
||||
session_ttl: 12h
|
||||
# For mode: oidc, configure a registered public PKCE client and the API
|
||||
# audience included in its access tokens. Users need the admin role to write.
|
||||
oidc_issuer: https://users.k6n.net
|
||||
oidc_audience: https://fancy-dns.example.net
|
||||
oidc_client_id: fancy-dns
|
||||
oidc_write_roles: [admin]
|
||||
rate_limit:
|
||||
per_minute: 600
|
||||
failures: 10
|
||||
|
||||
@@ -113,8 +113,12 @@ data:
|
||||
# is unset, so a missing secret is a crash loop rather than an
|
||||
# unauthenticated console.
|
||||
auth:
|
||||
mode: apikey
|
||||
mode: oidc
|
||||
api_keys: ["${FANCYDNS_API_KEY}"]
|
||||
oidc_issuer: https://users.k6n.net
|
||||
oidc_audience: https://dns.k6n.net
|
||||
oidc_client_id: fancy-dns
|
||||
oidc_write_roles: [admin]
|
||||
trust_loopback: false
|
||||
|
||||
metrics:
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
# kubectl -n dns create secret generic fancy-dns-apikey \
|
||||
# --from-literal=api-key="$(openssl rand -hex 32)"
|
||||
#
|
||||
# With auth.mode: apikey and api_keys: ["${FANCYDNS_API_KEY}"] in the config,
|
||||
# a missing FANCYDNS_API_KEY is a startup error rather than an empty key, so a
|
||||
# forgotten secret shows up as a CrashLoopBackOff and not as an unauthenticated
|
||||
# console on the network.
|
||||
# With api_keys: ["${FANCYDNS_API_KEY}"] in the config, a missing
|
||||
# FANCYDNS_API_KEY is a startup error rather than an empty key. These keys
|
||||
# remain available for machine clients when the console uses OIDC.
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
|
||||
@@ -4,6 +4,7 @@ go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/alicebob/miniredis/v2 v2.39.0
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/miekg/dns v1.1.73
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/redis/go-redis/v9 v9.22.0
|
||||
@@ -15,12 +16,14 @@ require (
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
|
||||
@@ -8,8 +8,12 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
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/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
@@ -50,6 +54,8 @@ go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
|
||||
+9
-1
@@ -27,7 +27,7 @@ import (
|
||||
|
||||
// Principal is the authenticated identity behind a request.
|
||||
type Principal struct {
|
||||
// Mode is "apikey", "basic" or "anonymous".
|
||||
// Mode is "apikey", "basic", "oidc" or "anonymous".
|
||||
Mode string
|
||||
// Name is a human label for the key or user.
|
||||
Name string
|
||||
@@ -246,6 +246,7 @@ func (s *Server) routes(cfg *config.Config) *http.ServeMux {
|
||||
})))
|
||||
}
|
||||
mux.Handle("POST "+base+"auth/login", s.limited(s.handleLogin))
|
||||
mux.Handle("GET "+base+"auth/config", s.public(s.handleAuthConfig))
|
||||
mux.Handle("POST "+base+"auth/logout", s.authed(s.handleLogout, false))
|
||||
|
||||
// Everything below requires a principal.
|
||||
@@ -391,6 +392,13 @@ func (s *Server) principal(r *http.Request) (Principal, error) {
|
||||
}
|
||||
switch strings.ToLower(scheme) {
|
||||
case "bearer":
|
||||
// Local sessions minted by /auth/login are 64-character hex
|
||||
// strings. OIDC access tokens are compact JWTs (three segments).
|
||||
// Keep key-based login sessions usable alongside OIDC for scripted
|
||||
// clients, while sending JWT-shaped credentials to the verifier.
|
||||
if s.auth.mode == "oidc" && strings.Count(value, ".") == 2 {
|
||||
return s.auth.oidcPrincipal(value)
|
||||
}
|
||||
return s.auth.session(value)
|
||||
case "basic":
|
||||
user, pass, ok := r.BasicAuth()
|
||||
|
||||
+94
-8
@@ -1,16 +1,19 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
)
|
||||
|
||||
// authenticator checks API keys, basic credentials and issued session tokens.
|
||||
@@ -38,18 +41,34 @@ type authenticator struct {
|
||||
// sessionTTL is how long an issued token stays valid.
|
||||
sessionTTL time.Duration
|
||||
// trustLoopback is informational; the caller checks it.
|
||||
mu sync.RWMutex
|
||||
sessions map[string]session
|
||||
mu sync.RWMutex
|
||||
sessions map[string]session
|
||||
oidcIssuer string
|
||||
oidcAudience string
|
||||
oidcClientID string
|
||||
oidcWriteRoles map[string]bool
|
||||
oidcInitMu sync.Mutex
|
||||
oidcVerifier *oidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
func newAuthenticator(cfg config.Auth) *authenticator {
|
||||
a := &authenticator{
|
||||
mode: cfg.Mode,
|
||||
readOnly: make(map[string]string, len(cfg.ReadOnlyAPIKeys)),
|
||||
readWrite: make(map[string]string, len(cfg.APIKeys)),
|
||||
username: cfg.Username,
|
||||
sessionTTL: cfg.SessionTTL.D(),
|
||||
sessions: make(map[string]session),
|
||||
mode: cfg.Mode,
|
||||
readOnly: make(map[string]string, len(cfg.ReadOnlyAPIKeys)),
|
||||
readWrite: make(map[string]string, len(cfg.APIKeys)),
|
||||
username: cfg.Username,
|
||||
sessionTTL: cfg.SessionTTL.D(),
|
||||
sessions: make(map[string]session),
|
||||
oidcIssuer: cfg.OIDCIssuer,
|
||||
oidcAudience: cfg.OIDCAudience,
|
||||
oidcClientID: cfg.OIDCClientID,
|
||||
oidcWriteRoles: make(map[string]bool),
|
||||
}
|
||||
for _, role := range cfg.OIDCWriteRoles {
|
||||
a.oidcWriteRoles[role] = true
|
||||
}
|
||||
if len(a.oidcWriteRoles) == 0 {
|
||||
a.oidcWriteRoles["admin"] = true
|
||||
}
|
||||
for i, k := range cfg.ReadOnlyAPIKeys {
|
||||
if k == "" {
|
||||
@@ -74,6 +93,68 @@ func newAuthenticator(cfg config.Auth) *authenticator {
|
||||
return a
|
||||
}
|
||||
|
||||
// oidcPrincipal verifies an RS256 access token against issuer discovery/JWKS.
|
||||
// Provider metadata and keys are fetched lazily, then cached by go-oidc.
|
||||
func (a *authenticator) oidcPrincipal(raw string) (Principal, error) {
|
||||
if a == nil || a.oidcIssuer == "" || a.oidcAudience == "" {
|
||||
return Principal{}, errors.New("oidc: not configured")
|
||||
}
|
||||
a.oidcInitMu.Lock()
|
||||
if a.oidcVerifier == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
provider, err := oidc.NewProvider(ctx, a.oidcIssuer)
|
||||
cancel()
|
||||
if err != nil {
|
||||
a.oidcInitMu.Unlock()
|
||||
return Principal{}, fmt.Errorf("oidc discovery: %w", err)
|
||||
}
|
||||
a.oidcVerifier = provider.Verifier(&oidc.Config{ClientID: a.oidcAudience, SupportedSigningAlgs: []string{"RS256"}})
|
||||
}
|
||||
verifier := a.oidcVerifier
|
||||
a.oidcInitMu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
tok, err := verifier.Verify(ctx, raw)
|
||||
if err != nil {
|
||||
return Principal{}, fmt.Errorf("oidc token: %w", err)
|
||||
}
|
||||
var claims struct {
|
||||
Subject string `json:"sub"`
|
||||
TokenUse string `json:"token_use"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Roles []string `json:"roles"`
|
||||
}
|
||||
if err := tok.Claims(&claims); err != nil {
|
||||
return Principal{}, err
|
||||
}
|
||||
if claims.Subject == "" || claims.TokenUse != "access" {
|
||||
return Principal{}, errors.New("oidc: token is not an access token")
|
||||
}
|
||||
name := claims.Name
|
||||
if name == "" {
|
||||
name = claims.Email
|
||||
}
|
||||
if name == "" {
|
||||
name = claims.Subject
|
||||
}
|
||||
readOnly := true
|
||||
for _, role := range claims.Roles {
|
||||
if a.oidcWriteRoles[role] {
|
||||
readOnly = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return Principal{Mode: "oidc", Name: name, ReadOnly: readOnly}, nil
|
||||
}
|
||||
|
||||
func (a *authenticator) OIDCConfig() (issuer, clientID string) {
|
||||
if a == nil || a.mode != "oidc" {
|
||||
return "", ""
|
||||
}
|
||||
return a.oidcIssuer, a.oidcClientID
|
||||
}
|
||||
|
||||
func keyLabel(kind string, i int) string {
|
||||
return kind + "-" + itoa(i+1)
|
||||
}
|
||||
@@ -290,3 +371,8 @@ func (s *Server) handleWhoami(w http.ResponseWriter, r *http.Request) {
|
||||
"base_path": s.base,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAuthConfig(w http.ResponseWriter, r *http.Request) {
|
||||
issuer, clientID := s.auth.OIDCConfig()
|
||||
writeJSON(w, http.StatusOK, map[string]string{"mode": s.AuthMode(), "issuer": issuer, "client_id": clientID})
|
||||
}
|
||||
@@ -34,6 +34,30 @@ func modeBasic(c *config.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
func modeOIDCWithAPIKey(c *config.Config) {
|
||||
c.API.Auth = config.Auth{
|
||||
Mode: "oidc", APIKeys: []string{"machine-key"},
|
||||
OIDCIssuer: "https://users.example.test", OIDCAudience: "https://dns.example.test", OIDCClientID: "fancy-dns",
|
||||
TrustLoopback: false, SessionTTL: config.Duration(time.Hour),
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCModeKeepsAPIKeyLoginSessionsUsable(t *testing.T) {
|
||||
h := newHarness(t, modeOIDCWithAPIKey)
|
||||
res := h.do(http.MethodPost, "/api/auth/login", `{"api_key":"machine-key"}`)
|
||||
if res.status != http.StatusOK {
|
||||
t.Fatalf("API key login = %d: %s", res.status, res.body)
|
||||
}
|
||||
token, _ := res.json(t)["token"].(string)
|
||||
if token == "" {
|
||||
t.Fatal("login returned an empty bearer token")
|
||||
}
|
||||
res = h.do(http.MethodGet, "/api/whoami", "", "Authorization: Bearer "+token)
|
||||
if res.status != http.StatusOK {
|
||||
t.Fatalf("session bearer in OIDC mode = %d: %s", res.status, res.body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthModeAPIKey covers every way a request can present a key in apikey
|
||||
// mode, and the invariant that matters: the right key always works and every
|
||||
// other credential never does.
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
|
||||
)
|
||||
|
||||
func TestOIDCAccessTokenVerificationAndRoleGate(t *testing.T) {
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var issuer string
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"issuer": issuer, "jwks_uri": issuer + "/keys"})
|
||||
})
|
||||
mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
|
||||
e := big.NewInt(int64(key.PublicKey.E)).Bytes()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]string{
|
||||
"kty": "RSA", "use": "sig", "alg": "RS256", "kid": "test-key",
|
||||
"n": base64.RawURLEncoding.EncodeToString(key.PublicKey.N.Bytes()),
|
||||
"e": base64.RawURLEncoding.EncodeToString(e),
|
||||
}}})
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
issuer = server.URL
|
||||
a := newAuthenticator(config.Auth{Mode: "oidc", OIDCIssuer: issuer, OIDCAudience: "fancy-dns-api"})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
roles []string
|
||||
wantReadOnly bool
|
||||
bad bool
|
||||
badSignature bool
|
||||
badIssuer bool
|
||||
}{
|
||||
{name: "admin can write", roles: []string{"admin"}, wantReadOnly: false},
|
||||
{name: "ordinary account is read only", roles: []string{"staff"}, wantReadOnly: true},
|
||||
{name: "wrong audience refused", roles: []string{"admin"}, bad: true},
|
||||
{name: "wrong issuer refused", roles: []string{"admin"}, bad: true, badIssuer: true},
|
||||
{name: "expired token refused", roles: []string{"admin"}, bad: true},
|
||||
{name: "id token refused", roles: []string{"admin"}, bad: true},
|
||||
{name: "bad signature refused", roles: []string{"admin"}, bad: true, badSignature: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
aud := "fancy-dns-api"
|
||||
use := "access"
|
||||
exp := time.Now().Add(time.Hour).Unix()
|
||||
if strings.Contains(tc.name, "wrong audience") {
|
||||
aud = "another-api"
|
||||
}
|
||||
if strings.Contains(tc.name, "expired") {
|
||||
exp = time.Now().Add(-time.Hour).Unix()
|
||||
}
|
||||
if strings.Contains(tc.name, "id token") {
|
||||
use = "id"
|
||||
}
|
||||
tokenIssuer := issuer
|
||||
if tc.badIssuer {
|
||||
tokenIssuer += "/wrong"
|
||||
}
|
||||
token := signedOIDCToken(t, key, map[string]any{"iss": tokenIssuer, "sub": "user-1", "aud": aud, "exp": exp, "iat": time.Now().Unix(), "token_use": use, "name": "Test User", "roles": tc.roles})
|
||||
if tc.badSignature {
|
||||
parts := strings.Split(token, ".")
|
||||
parts[2] = strings.Repeat("A", len(parts[2]))
|
||||
token = strings.Join(parts, ".")
|
||||
}
|
||||
p, err := a.oidcPrincipal(token)
|
||||
if tc.bad {
|
||||
if err == nil {
|
||||
t.Fatalf("accepted invalid token as %+v", p)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Mode != "oidc" || p.Name != "Test User" || p.ReadOnly != tc.wantReadOnly {
|
||||
t.Fatalf("principal = %+v", p)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func signedOIDCToken(t *testing.T, key *rsa.PrivateKey, claims map[string]any) string {
|
||||
t.Helper()
|
||||
enc := base64.RawURLEncoding.EncodeToString
|
||||
header, err := json.Marshal(map[string]string{"alg": "RS256", "kid": "test-key", "typ": "JWT"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, err := json.Marshal(claims)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message := enc(header) + "." + enc(payload)
|
||||
digest := sha256.Sum256([]byte(message))
|
||||
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message + "." + enc(signature)
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"math"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -477,8 +478,13 @@ type API struct {
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
// Mode is "none", "apikey" or "basic".
|
||||
// Mode is "none", "apikey", "basic" or "oidc".
|
||||
Mode string `yaml:"mode"`
|
||||
// OIDC settings validate access tokens issued by an external provider.
|
||||
OIDCIssuer string `yaml:"oidc_issuer"`
|
||||
OIDCAudience string `yaml:"oidc_audience"`
|
||||
OIDCClientID string `yaml:"oidc_client_id"`
|
||||
OIDCWriteRoles []string `yaml:"oidc_write_roles"`
|
||||
// APIKeys grant full access.
|
||||
APIKeys []string `yaml:"api_keys"`
|
||||
// ReadOnlyAPIKeys may only call GET endpoints.
|
||||
@@ -1152,9 +1158,9 @@ func (c *Config) Validate() error {
|
||||
}
|
||||
}
|
||||
switch c.API.Auth.Mode {
|
||||
case "none", "apikey", "basic":
|
||||
case "none", "apikey", "basic", "oidc":
|
||||
default:
|
||||
add("api.auth.mode must be none, apikey or basic (got %q)", c.API.Auth.Mode)
|
||||
add("api.auth.mode must be none, apikey, basic or oidc (got %q)", c.API.Auth.Mode)
|
||||
}
|
||||
if c.API.Auth.Mode == "apikey" && len(c.API.Auth.APIKeys) == 0 && !c.API.Auth.TrustLoopback {
|
||||
add("api.auth.mode is apikey but api.auth.api_keys is empty and trust_loopback is false: the API would be unauthenticated")
|
||||
@@ -1162,6 +1168,17 @@ func (c *Config) Validate() error {
|
||||
if c.API.Auth.Mode == "basic" && c.API.Auth.Username == "" {
|
||||
add("api.auth.mode is basic but api.auth.username is empty")
|
||||
}
|
||||
if c.API.Auth.Mode == "oidc" {
|
||||
if c.API.Auth.OIDCIssuer == "" || c.API.Auth.OIDCAudience == "" || c.API.Auth.OIDCClientID == "" {
|
||||
add("api.auth.mode is oidc and requires oidc_issuer, oidc_audience and oidc_client_id")
|
||||
}
|
||||
if c.API.Auth.OIDCIssuer != "" {
|
||||
u, err := url.Parse(c.API.Auth.OIDCIssuer)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
add("api.auth.oidc_issuer must be an HTTPS issuer URL")
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.API.Auth.SessionTTL <= 0 {
|
||||
add("api.auth.session_ttl must be > 0")
|
||||
}
|
||||
@@ -1290,6 +1307,8 @@ func (c *Config) HasAPIAuth() bool {
|
||||
return len(c.API.Auth.APIKeys) > 0 || len(c.API.Auth.ReadOnlyAPIKeys) > 0 || !c.API.Auth.TrustLoopback
|
||||
case "basic":
|
||||
return true
|
||||
case "oidc":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -5,7 +5,7 @@
|
||||
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>web</title>
|
||||
<script type="module" crossorigin src="./assets/index-DHEE03zK.js"></script>
|
||||
<script type="module" crossorigin src="./assets/index-Dh5C0Ucn.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-CZ8p4VMZ.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -69,6 +69,7 @@ export default function App() {
|
||||
<Routes>
|
||||
{/* Bare: no shell, no header, no nav. */}
|
||||
<Route path="/auth/login" element={<Login />} />
|
||||
<Route path="/auth/oidc/callback" element={<Login />} />
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
|
||||
+2
-2
@@ -154,7 +154,7 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
||||
}
|
||||
|
||||
const token = getToken()
|
||||
if (token && !headers.has('X-API-Key')) headers.set('X-API-Key', token)
|
||||
if (token && !headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`)
|
||||
|
||||
let res: Response
|
||||
try {
|
||||
@@ -369,7 +369,7 @@ export function streamLogs(handlers: LogStreamHandlers): () => void {
|
||||
if (stopped) return
|
||||
const token = getToken()
|
||||
const headers = new Headers({ Accept: 'text/event-stream' })
|
||||
if (token) headers.set('X-API-Key', token)
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`)
|
||||
|
||||
try {
|
||||
const res = await fetch(STREAM_PATH, {
|
||||
|
||||
+104
-14
@@ -7,13 +7,12 @@
|
||||
* shown as an error.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { Globe, KeyRound, LogIn, ShieldCheck, Terminal } from 'lucide-react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
|
||||
import { ApiError, login, whoami } from '../lib/api'
|
||||
import type { Whoami } from '../lib/types'
|
||||
import { ApiError, login, setToken } from '../lib/api'
|
||||
import { Button, Card, CardBody, Input } from '../components/ui'
|
||||
import { Spinner } from '../components/ui'
|
||||
|
||||
@@ -22,11 +21,17 @@ function wantsPassword(mode: string): boolean {
|
||||
return mode === 'basic'
|
||||
}
|
||||
|
||||
function safeNext(value: string): string {
|
||||
return value.startsWith('/') && !value.startsWith('//') && !value.includes('\\') ? value : '/'
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const [params] = useSearchParams()
|
||||
const next = params.get('next') ?? '/'
|
||||
const callbackStarted = useRef(false)
|
||||
|
||||
const [mode, setMode] = useState<string | null>(null)
|
||||
const [oidc, setOIDC] = useState<{ issuer: string; client_id: string } | null>(null)
|
||||
const [apiKey, setApiKey] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
@@ -35,33 +40,118 @@ export default function Login() {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
whoami()
|
||||
.then((who: Whoami) => {
|
||||
if (live) setMode(who.auth_mode ?? 'apikey')
|
||||
fetch('/api/auth/config', { headers: { Accept: 'application/json' } })
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error('could not load authentication settings')
|
||||
return (await res.json()) as { mode?: string; issuer?: string; client_id?: string }
|
||||
})
|
||||
.catch(() => {
|
||||
// Unauthenticated probes and older daemons both land here: show the
|
||||
// form rather than an error, the submit will say what is wrong.
|
||||
if (live) setMode('apikey')
|
||||
.then((cfg) => {
|
||||
if (!live) return
|
||||
setMode(cfg.mode ?? 'apikey')
|
||||
if (cfg.issuer && cfg.client_id) setOIDC({ issuer: cfg.issuer, client_id: cfg.client_id })
|
||||
})
|
||||
.catch(() => { if (live) setMode('apikey') })
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const providerError = params.get('error')
|
||||
if (providerError) {
|
||||
setError(params.get('error_description') ?? `identity provider sign in failed: ${providerError}`)
|
||||
return
|
||||
}
|
||||
const code = params.get('code')
|
||||
if (!code || !oidc || mode !== 'oidc') return
|
||||
if (callbackStarted.current) return
|
||||
callbackStarted.current = true
|
||||
let pendingLogin: { state: string; verifier: string; next: string } | null
|
||||
try {
|
||||
pendingLogin = JSON.parse(sessionStorage.getItem('fancydns.oidc.pending') ?? 'null')
|
||||
} catch { pendingLogin = null }
|
||||
if (!pendingLogin?.state || pendingLogin.state !== params.get('state') || !pendingLogin.verifier) {
|
||||
setError('OIDC login state check failed. Start sign in again.')
|
||||
return
|
||||
}
|
||||
sessionStorage.removeItem('fancydns.oidc.pending')
|
||||
setPending(true)
|
||||
void (async () => {
|
||||
try {
|
||||
const discoveryRes = await fetch(`${oidc.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`)
|
||||
if (!discoveryRes.ok) throw new Error('could not discover the identity provider')
|
||||
const discovery = (await discoveryRes.json()) as { token_endpoint?: string }
|
||||
if (!discovery.token_endpoint) throw new Error('identity provider has no token endpoint')
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: oidc.client_id,
|
||||
code,
|
||||
redirect_uri: `${window.location.origin}/auth/oidc/callback`,
|
||||
code_verifier: pendingLogin.verifier,
|
||||
})
|
||||
const tokenRes = await fetch(discovery.token_endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
})
|
||||
const tokenBody = (await tokenRes.json()) as { access_token?: string; error_description?: string }
|
||||
if (!tokenRes.ok || !tokenBody.access_token) throw new Error(tokenBody.error_description ?? 'code exchange failed')
|
||||
setToken(tokenBody.access_token)
|
||||
window.location.assign(safeNext(pendingLogin.next))
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'OIDC sign in failed')
|
||||
} finally { setPending(false) }
|
||||
})()
|
||||
}, [mode, oidc, params])
|
||||
|
||||
const startOIDC = async (): Promise<void> => {
|
||||
if (!oidc) return
|
||||
setPending(true)
|
||||
setError(null)
|
||||
try {
|
||||
const discoveryRes = await fetch(`${oidc.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`)
|
||||
if (!discoveryRes.ok) throw new Error('could not discover the identity provider')
|
||||
const discovery = (await discoveryRes.json()) as { authorization_endpoint?: string }
|
||||
if (!discovery.authorization_endpoint) throw new Error('identity provider has no authorization endpoint')
|
||||
const random = (bytes: number): string => {
|
||||
const data = crypto.getRandomValues(new Uint8Array(bytes))
|
||||
return btoa(String.fromCharCode(...data)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
const verifier = random(32)
|
||||
const challenge = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
|
||||
const codeChallenge = btoa(String.fromCharCode(...new Uint8Array(challenge))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
const state = random(24)
|
||||
const redirectURI = `${window.location.origin}/auth/oidc/callback`
|
||||
sessionStorage.setItem('fancydns.oidc.pending', JSON.stringify({ state, verifier, next }))
|
||||
const authorize = new URL(discovery.authorization_endpoint)
|
||||
authorize.search = new URLSearchParams({
|
||||
response_type: 'code', client_id: oidc.client_id, redirect_uri: redirectURI,
|
||||
scope: 'openid profile email', state, code_challenge: codeChallenge, code_challenge_method: 'S256',
|
||||
}).toString()
|
||||
window.location.assign(authorize.toString())
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'could not start OIDC sign in')
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = async (event: FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
event.preventDefault()
|
||||
if (pending) return
|
||||
setError(null)
|
||||
setPending(true)
|
||||
try {
|
||||
if (mode === 'oidc') {
|
||||
await startOIDC()
|
||||
return
|
||||
}
|
||||
if (wantsPassword(mode ?? 'apikey')) {
|
||||
await login({ username, password })
|
||||
} else {
|
||||
await login({ api_key: apiKey })
|
||||
}
|
||||
// A full navigation: the shell reads whoami and the token on boot.
|
||||
window.location.assign(next.startsWith('/') ? next : '/')
|
||||
window.location.assign(safeNext(next))
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
@@ -94,12 +184,12 @@ export default function Login() {
|
||||
? 'Checking the authentication mode…'
|
||||
: passwordMode
|
||||
? 'This node uses username and password.'
|
||||
: 'This node uses an API key.'
|
||||
: mode === 'oidc' ? 'Sign in with your identity provider.' : 'This node uses an API key.'
|
||||
}
|
||||
>
|
||||
<CardBody>
|
||||
<form className="space-y-3" onSubmit={(event) => void onSubmit(event)}>
|
||||
{passwordMode ? (
|
||||
{mode === 'oidc' ? null : passwordMode ? (
|
||||
<>
|
||||
<Input
|
||||
label="Username"
|
||||
@@ -152,7 +242,7 @@ export default function Login() {
|
||||
loading={pending}
|
||||
className="w-full justify-center"
|
||||
>
|
||||
{pending ? 'Signing in…' : 'Sign in'}
|
||||
{pending ? 'Signing in…' : mode === 'oidc' ? 'Continue with OIDC' : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardBody>
|
||||
|
||||
Reference in new issue
Block a user