feat(identity): verify provider tokens and attribute task actions to their actor
Two halves of one boundary: a credential resolves to an identity, and an action records which identity acted and whose authority it used. resource server. internal/infrastructure/oidc verifies a provider-issued bearer token against the provider's published keys, using an OSS OIDC library: archie compares no signature, validates no claim and rotates no key itself, holds no client secret and issues no session, so a compromised archie cannot mint an identity. Audience is required rather than optional -- a token minted for another service must not authenticate here -- and discovery happens at construction, so an unreachable provider is a startup failure rather than a request-time surprise. identity.Authenticate is the single place a credential becomes an identity, and it refuses in four distinguishable ways: no credential presented, a credential that did not verify (wrong key, expired, wrong issuer, wrong audience, malformed), a verified subject with no identity bound to it, and an identity that may not act. The order is deliberate: verification happens before any field of the token is used, so nothing an unverified token carries can select an identity. A suspended identity is refused even though its credential verified, because suspension is archie's decision and must not depend on the provider withdrawing a token. The binding is the second bridge beside the legacy-name alias: identity_subjects keys (issuer, subject) so the same subject string from another issuer is a different caller, and rebinding moves a subject so two identities can never claim one provider subject. The contract Authenticate needs is SubjectResolver, narrower than Repository, so a consumer that only authenticates does not take the whole identity CRUD surface -- and staterpc.Client, which asserts Repository, does not need a new RPC to satisfy it. attribution. taskactions now records two identities per action: the acting identity and the authorising principal, both on the event row as new columns added through the existing migration table. The rule that the bug turned on is enforced by the event kind describing the actor: a person's approval is human_approved, an agent's is agent_approved, and an action with no verified actor is task_approved, a task-level event that credits nobody. An agent acting under a person's standing approval records itself as the actor and that person as the principal, so "approved by came from me" is answerable from the record rather than asserted. Scope and actor are separated: scope decides which task a caller may touch and is never promoted into an actor, because the dashboard's credential is a shared token and possession of it is not evidence that a person was at the keyboard. That last point is a deliberate fidelity trade, and the reason the transport is not wired: the dashboard action path passes no actor yet, so dashboard approvals are now recorded as task_approved rather than claimed as a human's. Recording nothing false is the requirement; naming the human verifiably needs the dashboard to authenticate a token and resolve it, which needs two new state-store RPCs (ResolveIdentitySubject, BindIdentitySubject) -- the next piece, not a rewrite: the verifier is a one-method interface, so introspection would be a second implementation of it. Verified: task check exit 0; focused runs recorded in the handoff. Opaque authelia_at_ tokens were inspected rather than assumed and cannot be verified against public keys; infra is configuring access_token_signed_response_alg RS256 on the archie client, with audience https://archie.catlow.cloud and issuer https://auth.catlow.cloud.
This commit is contained in:
19 files changed
+1146
-88
No files matched your search
@@ -0,0 +1,72 @@
|
||||
// Package oidc verifies identity-provider tokens. It is a resource server: it
|
||||
// validates a token the provider issued and never issues one, holds no client
|
||||
// secret, and mints no session.
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
gooidc "github.com/coreos/go-oidc/v3/oidc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// Config identifies the provider and the audience archie accepts tokens for.
|
||||
// Audience is required rather than optional: without it a token the provider
|
||||
// minted for a different service would authenticate here, which is the
|
||||
// confused-deputy failure this boundary exists to prevent.
|
||||
type Config struct {
|
||||
Issuer string
|
||||
Audience string
|
||||
}
|
||||
|
||||
// Verifier validates tokens against the provider's published signing keys.
|
||||
type Verifier struct {
|
||||
verifier *gooidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
// New discovers the provider and builds a verifier from its published keys.
|
||||
// Discovery happens once, at construction: an unreachable provider is a
|
||||
// startup failure the operator sees, not a request-time surprise.
|
||||
func New(ctx context.Context, cfg Config) (*Verifier, error) {
|
||||
issuer := strings.TrimSpace(cfg.Issuer)
|
||||
audience := strings.TrimSpace(cfg.Audience)
|
||||
if issuer == "" {
|
||||
return nil, fmt.Errorf("oidc: issuer is required")
|
||||
}
|
||||
if audience == "" {
|
||||
return nil, fmt.Errorf("oidc: audience is required")
|
||||
}
|
||||
provider, err := gooidc.NewProvider(ctx, issuer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc: discover %q: %w", issuer, err)
|
||||
}
|
||||
return &Verifier{verifier: provider.Verifier(&gooidc.Config{ClientID: audience})}, nil
|
||||
}
|
||||
|
||||
// Verify checks the token's signature, issuer, audience and expiry against the
|
||||
// provider's keys, and returns what it proved. Every check is the library's:
|
||||
// signature comparison, claim validation and key rotation are not archie's code.
|
||||
func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Credential, error) {
|
||||
if v == nil || v.verifier == nil {
|
||||
return identity.Credential{}, fmt.Errorf("oidc: no verifier is configured")
|
||||
}
|
||||
token, err := v.verifier.Verify(ctx, strings.TrimSpace(rawToken))
|
||||
if err != nil {
|
||||
return identity.Credential{}, fmt.Errorf("oidc: verify: %w", err)
|
||||
}
|
||||
var claims struct {
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
// Claims are read after verification and are advisory: the identity comes
|
||||
// from the verified subject and issuer, never from a claim a caller could
|
||||
// have written into an unverified token.
|
||||
_ = token.Claims(&claims)
|
||||
return identity.Credential{
|
||||
Subject: identity.Subject{Issuer: token.Issuer, Subject: token.Subject},
|
||||
Scopes: strings.Fields(claims.Scope),
|
||||
Expires: token.Expiry,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-jose/go-jose/v4"
|
||||
"github.com/go-jose/go-jose/v4/jwt"
|
||||
)
|
||||
|
||||
const testAudience = "archie-dashboard"
|
||||
|
||||
// provider is a minimal identity provider: a discovery document and a JWKS.
|
||||
// It signs with a real RSA key so every refusal below is the library's own
|
||||
// signature and claim checking, not a stub's behaviour.
|
||||
type provider struct {
|
||||
server *httptest.Server
|
||||
key *rsa.PrivateKey
|
||||
keyID string
|
||||
// other is a second, unrelated key used to sign a token the provider
|
||||
// never published, which is what a forged or foreign token looks like.
|
||||
other *rsa.PrivateKey
|
||||
}
|
||||
|
||||
func newProvider(t *testing.T) *provider {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate key: %v", err)
|
||||
}
|
||||
other, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate second key: %v", err)
|
||||
}
|
||||
p := &provider{key: key, other: other, keyID: "test-key"}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": p.server.URL,
|
||||
"jwks_uri": p.server.URL + "/keys",
|
||||
"authorization_endpoint": p.server.URL + "/authorize",
|
||||
"token_endpoint": p.server.URL + "/token",
|
||||
"response_types_supported": []string{"code"},
|
||||
"subject_types_supported": []string{"public"},
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{
|
||||
Key: key.Public(), KeyID: p.keyID, Algorithm: "RS256", Use: "sig",
|
||||
}}})
|
||||
})
|
||||
p.server = httptest.NewServer(mux)
|
||||
t.Cleanup(p.server.Close)
|
||||
return p
|
||||
}
|
||||
|
||||
// token signs a token with the given key for the given claims.
|
||||
func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*jwt.Claims)) string {
|
||||
t.Helper()
|
||||
claims := jwt.Claims{
|
||||
Issuer: p.server.URL,
|
||||
Subject: "sam",
|
||||
Audience: jwt.Audience{testAudience},
|
||||
Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&claims)
|
||||
}
|
||||
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: signer},
|
||||
(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", p.keyID))
|
||||
if err != nil {
|
||||
t.Fatalf("new signer: %v", err)
|
||||
}
|
||||
raw, err := jwt.Signed(sig).Claims(claims).Serialize()
|
||||
if err != nil {
|
||||
t.Fatalf("serialize token: %v", err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func (p *provider) verifier(t *testing.T) *Verifier {
|
||||
t.Helper()
|
||||
v, err := New(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience})
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestVerifyAcceptsAProviderIssuedToken(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
credential, err := p.verifier(t).Verify(context.Background(), p.token(t, p.key, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("Verify() error = %v", err)
|
||||
}
|
||||
if credential.Subject.Subject != "sam" {
|
||||
t.Fatalf("subject = %q, want %q", credential.Subject.Subject, "sam")
|
||||
}
|
||||
if credential.Subject.Issuer != p.server.URL {
|
||||
t.Fatalf("issuer = %q, want %q", credential.Subject.Issuer, p.server.URL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
verifier := p.verifier(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
token string
|
||||
}{
|
||||
{
|
||||
name: "no token",
|
||||
token: "",
|
||||
},
|
||||
{
|
||||
name: "expired",
|
||||
token: p.token(t, p.key, func(c *jwt.Claims) { c.Expiry = jwt.NewNumericDate(time.Now().Add(-time.Hour)) }),
|
||||
},
|
||||
{
|
||||
name: "signed by a key the provider never published",
|
||||
token: p.token(t, p.other, nil),
|
||||
},
|
||||
{
|
||||
name: "issued for another audience",
|
||||
token: p.token(t, p.key, func(c *jwt.Claims) { c.Audience = jwt.Audience{"another-service"} }),
|
||||
},
|
||||
{
|
||||
name: "issued by another provider",
|
||||
token: p.token(t, p.key, func(c *jwt.Claims) { c.Issuer = "https://someone-else.example" }),
|
||||
},
|
||||
{
|
||||
name: "not a token at all",
|
||||
token: "not-a-jwt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := verifier.Verify(context.Background(), tc.token); err == nil {
|
||||
t.Fatal("Verify() accepted a token it must refuse")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRefusesAnIncompleteConfiguration(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg Config
|
||||
}{
|
||||
{"no issuer", Config{Audience: testAudience}},
|
||||
{"no audience", Config{Issuer: p.server.URL}},
|
||||
{"unreachable issuer", Config{Issuer: "http://127.0.0.1:1", Audience: testAudience}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := New(context.Background(), tc.cfg); err == nil {
|
||||
t.Fatal("New() accepted a configuration it must refuse")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user