add
build / build-push (push) Successful in 30s

This commit is contained in:
mats committed 2026-09-27 22:32:03 +02:00
1 parent d53552f855
commit 2348d2e4b4
15 files changed
+412 -36

No files matched your search

+9 -1
View File
@@ -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
View File
@@ -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})
}
+24
View File
@@ -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.
+116
View File
@@ -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)
}
+22 -3
View File
@@ -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
}
+1 -1
View File
@@ -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>