1 parent
d53552f855
commit
2348d2e4b4
15 files changed
+412
-36
No files matched your search
+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)
|
||||
}
|
||||
Reference in new issue
Block a user