Implement inbound caller authentication (ADR 0004); close T03 and T05
TokenReview-based caller identity with audience-scoped tokens and exact resource.system to ServiceAccount bindings, per ops-warden's recommendation. Deletes the unwired tenant-engine live-roles adapter (T03) and adds make verify-posture (T05). Source implements A2; running digest is still A0 until promotion, so tenancy.current.A stays 0. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
6d82ef7f14
commit
1e1e077b27
18 changed files with 768 additions and 357 deletions
125
internal/callerauth/auth.go
Normal file
125
internal/callerauth/auth.go
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// Package callerauth authenticates protected systems before flex-auth evaluates
|
||||
// the authorization request they submit.
|
||||
package callerauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Mode string
|
||||
|
||||
const (
|
||||
ModeDisabled Mode = "disabled"
|
||||
ModeWarn Mode = "warn"
|
||||
ModeEnforce Mode = "enforce"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnauthenticated = errors.New("caller is not authenticated")
|
||||
ErrForbidden = errors.New("caller is not allowed to represent the requested system")
|
||||
ErrUnavailable = errors.New("caller identity service is unavailable")
|
||||
)
|
||||
|
||||
type Identity struct {
|
||||
Username string
|
||||
Audiences []string
|
||||
}
|
||||
|
||||
type TokenReviewer interface {
|
||||
Review(context.Context, string) (Identity, error)
|
||||
}
|
||||
|
||||
type WarningFunc func(string, ...any)
|
||||
|
||||
type Authenticator struct {
|
||||
mode Mode
|
||||
reviewer TokenReviewer
|
||||
audience string
|
||||
bindings map[string]string
|
||||
warnf WarningFunc
|
||||
}
|
||||
|
||||
func New(mode Mode, reviewer TokenReviewer, audience string, bindings map[string]string, warnf WarningFunc) (*Authenticator, error) {
|
||||
switch mode {
|
||||
case ModeDisabled:
|
||||
return &Authenticator{mode: mode}, nil
|
||||
case ModeWarn, ModeEnforce:
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported caller-auth mode %q", mode)
|
||||
}
|
||||
if reviewer == nil {
|
||||
return nil, fmt.Errorf("token reviewer is required in %s mode", mode)
|
||||
}
|
||||
if strings.TrimSpace(audience) == "" {
|
||||
return nil, fmt.Errorf("caller audience is required in %s mode", mode)
|
||||
}
|
||||
if len(bindings) == 0 {
|
||||
return nil, fmt.Errorf("at least one caller binding is required in %s mode", mode)
|
||||
}
|
||||
copyBindings := make(map[string]string, len(bindings))
|
||||
for system, principal := range bindings {
|
||||
if strings.TrimSpace(system) == "" || strings.TrimSpace(principal) == "" {
|
||||
return nil, fmt.Errorf("caller bindings require non-empty system and principal")
|
||||
}
|
||||
copyBindings[system] = principal
|
||||
}
|
||||
return &Authenticator{mode: mode, reviewer: reviewer, audience: audience, bindings: copyBindings, warnf: warnf}, nil
|
||||
}
|
||||
|
||||
func Disabled() *Authenticator {
|
||||
authenticator, _ := New(ModeDisabled, nil, "", nil, nil)
|
||||
return authenticator
|
||||
}
|
||||
|
||||
// Authorize verifies the bearer token and binds every resource.system value to
|
||||
// the authenticated workload principal. Warn mode records the same failures but
|
||||
// permits the request so callers can be migrated before enforcement is enabled.
|
||||
func (a *Authenticator) Authorize(ctx context.Context, authorization string, systems []string) error {
|
||||
if a == nil || a.mode == ModeDisabled {
|
||||
return nil
|
||||
}
|
||||
err := a.authorize(ctx, authorization, systems)
|
||||
if err != nil && a.mode == ModeWarn {
|
||||
if a.warnf != nil {
|
||||
a.warnf("caller authentication warning: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *Authenticator) authorize(ctx context.Context, authorization string, systems []string) error {
|
||||
token, ok := strings.CutPrefix(authorization, "Bearer ")
|
||||
if !ok || strings.TrimSpace(token) == "" || strings.ContainsAny(strings.TrimSpace(token), " \t\r\n") {
|
||||
return ErrUnauthenticated
|
||||
}
|
||||
identity, err := a.reviewer.Review(ctx, strings.TrimSpace(token))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrUnavailable, err)
|
||||
}
|
||||
if strings.TrimSpace(identity.Username) == "" || !contains(identity.Audiences, a.audience) {
|
||||
return ErrUnauthenticated
|
||||
}
|
||||
if len(systems) == 0 {
|
||||
return fmt.Errorf("%w: request has no resources", ErrForbidden)
|
||||
}
|
||||
for _, system := range systems {
|
||||
expected, found := a.bindings[system]
|
||||
if !found || expected != identity.Username {
|
||||
return fmt.Errorf("%w: principal %q cannot represent system %q", ErrForbidden, identity.Username, system)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func contains(values []string, wanted string) bool {
|
||||
for _, value := range values {
|
||||
if value == wanted {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
72
internal/callerauth/auth_test.go
Normal file
72
internal/callerauth/auth_test.go
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
package callerauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeReviewer struct {
|
||||
identity Identity
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeReviewer) Review(context.Context, string) (Identity, error) {
|
||||
return f.identity, f.err
|
||||
}
|
||||
|
||||
func TestAuthenticatorEnforcesAudienceAndSystemBinding(t *testing.T) {
|
||||
authenticator, err := New(ModeEnforce, fakeReviewer{identity: Identity{
|
||||
Username: "system:serviceaccount:tenant-engine:tenant-engine",
|
||||
Audiences: []string{"flex-auth"},
|
||||
}}, "flex-auth", map[string]string{
|
||||
"tenant-engine": "system:serviceaccount:tenant-engine:tenant-engine",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := authenticator.Authorize(context.Background(), "Bearer caller-token", []string{"tenant-engine"}); err != nil {
|
||||
t.Fatalf("Authorize: %v", err)
|
||||
}
|
||||
if err := authenticator.Authorize(context.Background(), "Bearer caller-token", []string{"user-engine"}); !errors.Is(err, ErrForbidden) {
|
||||
t.Fatalf("system mismatch error = %v; want forbidden", err)
|
||||
}
|
||||
|
||||
wrongAudience, _ := New(ModeEnforce, fakeReviewer{identity: Identity{
|
||||
Username: "system:serviceaccount:tenant-engine:tenant-engine",
|
||||
Audiences: []string{"kubernetes"},
|
||||
}}, "flex-auth", map[string]string{"tenant-engine": "system:serviceaccount:tenant-engine:tenant-engine"}, nil)
|
||||
if err := wrongAudience.Authorize(context.Background(), "Bearer caller-token", []string{"tenant-engine"}); !errors.Is(err, ErrUnauthenticated) {
|
||||
t.Fatalf("audience error = %v; want unauthenticated", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatorRejectsMissingTokenAndReviewerFailure(t *testing.T) {
|
||||
bindings := map[string]string{"tenant-engine": "principal"}
|
||||
authenticator, _ := New(ModeEnforce, fakeReviewer{identity: Identity{Username: "principal", Audiences: []string{"flex-auth"}}}, "flex-auth", bindings, nil)
|
||||
if err := authenticator.Authorize(context.Background(), "", []string{"tenant-engine"}); !errors.Is(err, ErrUnauthenticated) {
|
||||
t.Fatalf("missing token error = %v; want unauthenticated", err)
|
||||
}
|
||||
|
||||
unavailable, _ := New(ModeEnforce, fakeReviewer{err: errors.New("apiserver down")}, "flex-auth", bindings, nil)
|
||||
if err := unavailable.Authorize(context.Background(), "Bearer token", []string{"tenant-engine"}); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("reviewer error = %v; want unavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatorWarnModePermitsButRecordsFailure(t *testing.T) {
|
||||
var warning string
|
||||
authenticator, err := New(ModeWarn, fakeReviewer{}, "flex-auth", map[string]string{"tenant-engine": "principal"}, func(format string, _ ...any) {
|
||||
warning = format
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := authenticator.Authorize(context.Background(), "", []string{"tenant-engine"}); err != nil {
|
||||
t.Fatalf("warn mode returned error: %v", err)
|
||||
}
|
||||
if !strings.Contains(warning, "warning") {
|
||||
t.Fatalf("warning = %q", warning)
|
||||
}
|
||||
}
|
||||
110
internal/callerauth/tokenreview.go
Normal file
110
internal/callerauth/tokenreview.go
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
package callerauth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type KubernetesTokenReviewer struct {
|
||||
endpoint string
|
||||
audience string
|
||||
reviewerTokenFile string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewKubernetesTokenReviewer(endpoint, audience, reviewerTokenFile, caFile string) (*KubernetesTokenReviewer, error) {
|
||||
ca, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Kubernetes CA: %w", err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(ca) {
|
||||
return nil, fmt.Errorf("Kubernetes CA file contains no certificates")
|
||||
}
|
||||
return &KubernetesTokenReviewer{
|
||||
endpoint: strings.TrimRight(endpoint, "/") + "/apis/authentication.k8s.io/v1/tokenreviews",
|
||||
audience: audience,
|
||||
reviewerTokenFile: reviewerTokenFile,
|
||||
client: &http.Client{
|
||||
Timeout: 3 * time.Second,
|
||||
Transport: &http.Transport{TLSClientConfig: &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
RootCAs: pool,
|
||||
}},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type tokenReview struct {
|
||||
APIVersion string `json:"apiVersion"`
|
||||
Kind string `json:"kind"`
|
||||
Spec tokenReviewSpec `json:"spec"`
|
||||
Status tokenReviewStatus `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
type tokenReviewSpec struct {
|
||||
Token string `json:"token"`
|
||||
Audiences []string `json:"audiences"`
|
||||
}
|
||||
|
||||
type tokenReviewStatus struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Audiences []string `json:"audiences"`
|
||||
Error string `json:"error"`
|
||||
User struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"user"`
|
||||
}
|
||||
|
||||
func (r *KubernetesTokenReviewer) Review(ctx context.Context, callerToken string) (Identity, error) {
|
||||
reviewerToken, err := os.ReadFile(r.reviewerTokenFile)
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("read reviewer credential: %w", err)
|
||||
}
|
||||
payload, err := json.Marshal(tokenReview{
|
||||
APIVersion: "authentication.k8s.io/v1",
|
||||
Kind: "TokenReview",
|
||||
Spec: tokenReviewSpec{
|
||||
Token: callerToken,
|
||||
Audiences: []string{r.audience},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(reviewerToken)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||
return Identity{}, fmt.Errorf("TokenReview returned %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var review tokenReview
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&review); err != nil {
|
||||
return Identity{}, fmt.Errorf("decode TokenReview: %w", err)
|
||||
}
|
||||
if review.Status.Error != "" {
|
||||
return Identity{}, fmt.Errorf("TokenReview: %s", review.Status.Error)
|
||||
}
|
||||
if !review.Status.Authenticated {
|
||||
return Identity{}, nil
|
||||
}
|
||||
return Identity{Username: review.Status.User.Username, Audiences: review.Status.Audiences}, nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue