passport

package
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package passport is the platform's bearer-authentication contract: who a caller is, how that is proven, and how it is carried between services.

Identity. Principal and Claims describe an authenticated caller (user id, role, teams, whether it is a service). A Principal travels in a context (WithPrincipal, FromContext) and in audit fields (AuditSource, AuditIdentityLabel, RequestIP).

Proof. A Signer (platform-api only) issues short-lived ES256 JWTs and a Verifier checks them. The algorithm is pinned, the issuer is fixed, and a token carries exactly one audience (platform-api, runtime-api or analytics-api), so a token minted for one service is rejected by another. Backend services receive only public keys (VerifierFromEnv), so a compromised backend can verify tokens but cannot mint them. Keys rotate by overlapping public keys, selected by the token's kid header.

Enforcement. An Authenticator is built for one audience (NewAudienceAuthenticator) and wraps handlers with authentication and role checks. API keys resolve to a Principal through a PrincipalResolver; HTTPUserKeyResolver is the network-backed implementation. It caches only unsuccessful key lookups, for 45 seconds by default, with at most 1,024 entries per resolver. Successful authentication always revalidates the key.

Exchange. ExchangeHandler is the Traefik forward-auth endpoint that trades a platform user bearer for a one-minute JWT scoped to the runtime or analytics audience. Internal service secrets never reach the gateway or the UI.

Wire. AuthResolve* and PrincipalResolve* are the request and response types of the platform-api principal endpoints the resolvers call.

Failure modes are explicit: missing or invalid credentials map to 401, insufficient role to 403, and an unavailable resolver or secret to 503, all through apikit's error envelope.

Index

Constants

View Source
const (
	AudiencePlatform  = "platform-api"
	AudienceRuntime   = "runtime-api"
	AudienceAnalytics = "analytics-api"
)
View Source
const (
	RoleAdmin = "admin"
	RoleUser  = "user"
)
View Source
const (
	// EnvSigningKey names the PEM-encoded ES256 private key. Only platform-api
	// receives it.
	EnvSigningKey = "JWT_SIGNING_KEY"
	// EnvVerifyKeys names one or more PEM-encoded ES256 public keys. Services
	// that only verify tokens receive just these. During rotation it holds the
	// outgoing and incoming keys together.
	EnvVerifyKeys = "JWT_VERIFY_KEY"
)
View Source
const ExchangeTTL = time.Minute
View Source
const Issuer = "github.com/mcp-runtime/mcp-runtime"
View Source
const UnknownRequestIP = "unknown"

Variables

View Source
var ErrExchangeUnauthorized = errors.New("token exchange unauthorized")

Functions

func AuditIdentityLabel

func AuditIdentityLabel(p Principal) string

func AuditSource

func AuditSource(r *http.Request, p Principal) string

func EnsureKeyPair

func EnsureKeyPair(existingSigningPEM, existingVerifyPEM []byte) (signingPEM, verifyPEM []byte, err error)

EnsureKeyPair returns the signing key and verification key set a deployment should publish. An existing signing key is kept; a blank one is generated. The verification set keeps every existing public key and gains the signing key's public key when it is absent. A signing key or verification set that cannot be parsed is an error, so a credential that cannot be read is never overwritten.

func EnsureVerifyKey

func EnsureVerifyKey(signingPEM, existingVerifyPEM []byte) ([]byte, error)

EnsureVerifyKey returns the verification key set a deployment should publish for a signing key: the existing set, plus the signing key's public key when the set does not hold it yet. Old keys stay until an operator removes them, so tokens signed before a rotation keep verifying. An existing set that is not valid, or that holds a private key, is an error and is never overwritten.

func ExchangeBearer

func ExchangeBearer(ctx context.Context, client *http.Client, platform *url.URL, authorization, target string) (string, error)

ExchangeBearer is used by the server-side UI proxy, which reaches the split APIs directly. The browser keeps its ordinary opaque session cookie.

func ExchangePath

func ExchangePath(target string) string

ExchangePath fixes the audience in server configuration rather than deriving it from client-supplied URLs or forwarded headers.

func GenerateES256KeyPair

func GenerateES256KeyPair() (privatePEM, publicPEM []byte, err error)

GenerateES256KeyPair creates a P-256 key pair as PKCS#8 and PKIX PEM.

func PlatformKeysFromEnv

func PlatformKeysFromEnv() (Signer, Verifier, error)

PlatformKeysFromEnv builds what platform-api needs: the signer from JWT_SIGNING_KEY, and a verifier trusting its own public key plus any extra public keys in JWT_VERIFY_KEY, which lets old tokens survive a rotation.

func RequestIP

func RequestIP(r *http.Request) string

RequestIP uses the socket peer by default. Forwarded hops are considered only for explicitly trusted proxy CIDRs, walking from the socket toward the first untrusted hop. Untrusted client-supplied prefixes never become rate-limit or audit identities. Invalid trust/header configuration falls back to the peer.

func RequestSource

func RequestSource(r *http.Request) string

func Sign

func Sign(signer Signer, p Principal, ttl time.Duration, audiences []string) (string, error)

Sign mints a token that expires ttl from now. Only a holder of a Signer, which is platform-api alone, can call it.

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

Types

type AudienceConfig

type AudienceConfig struct {
	Audience       string
	Verifier       Verifier
	PlatformAPIURL string
	InternalToken  string
	ServiceAPIKeys map[string]struct{}
	AdminAPIKeys   map[string]struct{}
}

AudienceConfig configures a backend service that platform-api fronts.

type AuthResolveRequest

type AuthResolveRequest struct {
	APIKey string `json:"api_key"`
}

AuthResolveRequest is POST /internal/auth/resolve.

type AuthResolveResponse

type AuthResolveResponse struct {
	OK        bool      `json:"ok"`
	Principal Principal `json:"principal,omitempty"`
}

AuthResolveResponse is POST /internal/auth/resolve.

type Authenticator

type Authenticator struct {
	// Verifier accepts platform JWTs. Services other than platform-api set only
	// this, so they cannot mint tokens. A nil Verifier disables JWT auth.
	Verifier Verifier
	// Signer mints exchange tokens. Only platform-api sets it.
	Signer          Signer
	Audience        string
	ServiceAPIKeys  map[string]struct{}
	AdminAPIKeys    map[string]struct{}
	UserKeyResolver UserKeyResolver
	OIDC            OIDCVerifier
	Principals      PrincipalResolver
}

func NewAudienceAuthenticator

func NewAudienceAuthenticator(cfg AudienceConfig) Authenticator

NewAudienceAuthenticator builds the Authenticator for a service other than platform-api. Platform-api's ExchangeHandler re-reads the account for every request and mints a token that lives at most ExchangeTTL for exactly one audience, so the service verifies that token locally and does not call platform-api again. User API keys are still resolved remotely on every call, because a revoked key must fail immediately.

func (Authenticator) AuthenticateRequest

func (a Authenticator) AuthenticateRequest(r *http.Request) (Principal, bool, error)

func (Authenticator) Middleware

func (a Authenticator) Middleware(next http.Handler) http.Handler

func (Authenticator) RequireRole

func (a Authenticator) RequireRole(role string, next http.Handler) http.Handler

type Claims

type Claims struct {
	jwt.RegisteredClaims
	Email             string      `json:"email,omitempty"`
	Role              string      `json:"role,omitempty"`
	Namespace         string      `json:"namespace,omitempty"`
	Teams             []TeamClaim `json:"teams,omitempty"`
	AllowedNamespaces []string    `json:"allowed_namespaces,omitempty"`
	APIKeyID          string      `json:"api_key_id,omitempty"`
	AuthType          string      `json:"auth_type,omitempty"`
	IsService         bool        `json:"is_service,omitempty"`
}

func ClaimsFromPrincipal

func ClaimsFromPrincipal(p Principal) Claims

type ES256Signer

type ES256Signer struct {
	// contains filtered or unexported fields
}

ES256Signer signs platform tokens with a P-256 private key.

func NewES256Signer

func NewES256Signer(privatePEM []byte) (*ES256Signer, error)

NewES256Signer parses a PKCS#8 or SEC1 PEM private key. Only P-256 keys are valid for ES256.

func (*ES256Signer) PublicKeyPEM

func (s *ES256Signer) PublicKeyPEM() ([]byte, error)

PublicKeyPEM returns the matching verification key.

func (*ES256Signer) Sign

func (s *ES256Signer) Sign(p Principal, now, expires time.Time, audiences []string) (string, error)

func (*ES256Signer) Verifier

func (s *ES256Signer) Verifier() *ES256Verifier

Verifier returns a verifier that trusts only this signer's own public key.

type ES256Verifier

type ES256Verifier struct {
	// contains filtered or unexported fields
}

ES256Verifier verifies platform tokens against a set of public keys chosen by the token's kid header. It holds no private key and cannot sign.

func NewES256Verifier

func NewES256Verifier(publicPEMs ...[]byte) (*ES256Verifier, error)

NewES256Verifier parses every PUBLIC KEY block in the given PEM inputs. A private key or any other block type is an error, so a key that should have stayed secret is never silently accepted as a verification key.

func (*ES256Verifier) Verify

func (v *ES256Verifier) Verify(token, expectedAudience string) (Claims, error)

Verify accepts only ES256 tokens whose kid names a known key. The algorithm is pinned: the token header is attacker controlled, so none and every HMAC variant are rejected before any key is looked up.

type ExchangeHandler

type ExchangeHandler struct {
	Auth   Authenticator
	Target string
}

ExchangeHandler is a Traefik forward-auth endpoint, never a public API route. A platform user bearer is the exchange credential. Internal service secrets are deliberately not distributed to the gateway or UI. API keys and anonymous requests pass through unchanged for the destination's own authentication and public-catalog policy; they never acquire a JWT or a human identity here.

func (ExchangeHandler) ServeHTTP

func (h ExchangeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HTTPUserKeyResolver

type HTTPUserKeyResolver struct {
	BaseURL  string
	Token    string
	Client   *http.Client
	CacheTTL time.Duration
	// contains filtered or unexported fields
}

func (*HTTPUserKeyResolver) PrincipalForUserID

func (r *HTTPUserKeyResolver) PrincipalForUserID(ctx context.Context, userID string) (Principal, error)

PrincipalForUserID deliberately does not cache positive account state.

func (*HTTPUserKeyResolver) ResolveAPIKey

func (r *HTTPUserKeyResolver) ResolveAPIKey(ctx context.Context, rawKey string) (Principal, bool, error)

type OIDCVerifier

type OIDCVerifier interface {
	Verify(context.Context, string) (Principal, bool, error)
}

type Principal

type Principal struct {
	Role              string          `json:"role"`
	Subject           string          `json:"subject,omitempty"`
	Email             string          `json:"email,omitempty"`
	Namespace         string          `json:"namespace,omitempty"`
	AllowedNamespaces []string        `json:"allowed_namespaces,omitempty"`
	Teams             []PrincipalTeam `json:"teams,omitempty"`
	AuthType          string          `json:"auth_type,omitempty"`
	APIKeyID          string          `json:"api_key_id,omitempty"`
	IsService         bool            `json:"is_service,omitempty"`
}

func FromContext

func FromContext(ctx context.Context) (Principal, bool)

func ToPrincipal

func ToPrincipal(claims Claims) Principal

func (Principal) HasNamespace

func (p Principal) HasNamespace(namespace string) bool

func (Principal) TeamForNamespace

func (p Principal) TeamForNamespace(namespace string) (PrincipalTeam, bool)

func (Principal) TeamRole

func (p Principal) TeamRole(slug string) string

func (Principal) UserID

func (p Principal) UserID() string

type PrincipalResolveRequest

type PrincipalResolveRequest struct {
	UserID string `json:"user_id"`
}

PrincipalResolveRequest is POST /internal/identity/principal.

type PrincipalResolveResponse

type PrincipalResolveResponse struct {
	Principal Principal `json:"principal"`
}

PrincipalResolveResponse is POST /internal/identity/principal.

type PrincipalResolver

type PrincipalResolver interface {
	PrincipalForUserID(context.Context, string) (Principal, error)
}

PrincipalResolver refreshes current account and membership state after token verification. A signed token cannot keep a deactivated account authorized. Only platform-api sets it: its exchange handler refreshes the account before minting the short-lived token that other services then verify locally (see NewAudienceAuthenticator).

type PrincipalTeam

type PrincipalTeam = TeamClaim

type Signer

type Signer interface {
	Sign(p Principal, now, expires time.Time, audiences []string) (string, error)
}

Signer mints compact JWTs for a principal. Only platform-api holds one.

type TeamClaim

type TeamClaim struct {
	ID        string `json:"id"`
	Slug      string `json:"slug"`
	Name      string `json:"name"`
	Namespace string `json:"namespace"`
	Role      string `json:"role"`
}

type UserKeyResolver

type UserKeyResolver interface {
	ResolveAPIKey(context.Context, string) (Principal, bool, error)
}

type Verifier

type Verifier interface {
	Verify(token, expectedAudience string) (Claims, error)
}

Verifier validates a compact JWT for exactly one expected audience. A service that only verifies tokens must not be able to mint them, so verification and signing are separate interfaces.

func VerifierFromEnv

func VerifierFromEnv() (Verifier, error)

VerifierFromEnv builds the verifier a backend service uses. It reads only public keys, so a compromised backend cannot mint platform tokens.

Directories

Path Synopsis
Package passporttest gives tests across the repository ES256 keys and tokens without each one re-deriving how platform tokens are signed.
Package passporttest gives tests across the repository ES256 keys and tokens without each one re-deriving how platform tokens are signed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL