auth

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

internal/auth

Overview

JWT auth contract for the HTTP API and the git surface. It defines claim types, scope and algorithm constants, a Verifier that checks compact JWS tokens against per-org PEM public keys, helpers to generate keys and mint tokens, and ref-policy parsing and matching used on the git receive path. The package does no I/O of its own: key lookup goes through an injected KeySource.

Interface

  • SubjectLiteral, RepoClaimOrg, ScopeGitRead, ScopeGitWrite, ScopeRepoWrite, ScopeOrgRead — fixed sub value, org sentinel repo value, and scope strings [auth.go:SubjectLiteral]
  • AllowedAlgorithms — JWS allow-list: ES256, RS256, EdDSA, PS256, ES384, ES512 [auth.go:AllowedAlgorithms]
  • Claims, Claims.HasScope — verified claim set (iss, sub, repo, scopes, iat, exp, refs, ops, sync_claim) and exact scope match [auth.go:Claims]
  • Verifier — interface Verify(ctx, token) (*Claims, error) [auth.go:Verifier]
  • WithClaims, ClaimsFromContext — store and read verified claims on a context [auth.go:WithClaims]
  • ParsePublicKeysPEM — parses PKIX PUBLIC KEY blocks into ECDSA, RSA (>= 2048 bit), or Ed25519 keys [auth.go:ParsePublicKeysPEM]
  • GenerateKey, DefaultAlgorithm, MintToken — create a signer, map a key to its alg, sign claims into a compact JWT [mint.go:MintToken]
  • MarshalPrivateKeyPEM, MarshalPublicKeyPEM, ParsePrivateKeyPEM — PKCS#8 and PKIX PEM encode/decode; SEC1 also accepted on parse [mint.go:ParsePrivateKeyPEM]
  • RefPolicy (MarshalJSON/UnmarshalJSON as a [pattern, ops] tuple), OpNoPush, OpNoForcePush, OpVerifySig [policy.go:RefPolicy]
  • EphemeralNamespacePrefix (refs/namespaces/ephemeral/), NormalizeRefName, EphemeralRefName [policy.go:EphemeralNamespacePrefix]
  • ParseRefPolicies, MatchPolicy, FoldOps — parse the refs claim, first-match lookup over exact, *, or trailing /* patterns, fold the deprecated ops claim into refs [policy.go:MatchPolicy]
  • KeySource, OrgKeyVerifier, NewVerifier, UnionKeySource — Verifier backed by per-org keys, and an overlay of in-memory PEM keys for one org [verifier.go:OrgKeyVerifier]

Invariants

  • WithClaims panics on nil claims [auth.go:WithClaims]
  • ParsePublicKeysPEM rejects non-PUBLIC KEY blocks, RSA under 2048 bits, unsupported key types, and an empty key set [auth.go:ParsePublicKeysPEM]
  • MintToken rejects an alg outside the signature map or one that does not fit the key; GenerateKey rejects unknown algs [mint.go:MintToken]
  • RefPolicy.UnmarshalJSON requires exactly a 2-element tuple [policy.go:UnmarshalJSON]
  • MatchPolicy returns no match for an empty ref [policy.go:MatchPolicy]
  • Verify rejects tokens without exactly two dots, non-canonical base64url segments, and JSON-serialized JWS with other than one signature [verifier.go:Verify]
  • Verify accepts only algs in signatureAlgorithms and checks the key family matches the alg [verifier.go:keySupportsAlg]
  • validateClaims requires exp > now and sub == SubjectLiteral; iat is not checked [verifier.go:validateClaims]
  • init panics if signatureAlgorithms and AllowedAlgorithms disagree [verifier.go:init]
  • UnionKeySource panics on a nil inner source, empty org, no PEMs, or unparseable PEM [verifier.go:UnionKeySource]
  • Verify fails closed for an issuer with no keys [verifier.go:Verify]

Side Effects

  • GenerateKey reads crypto/rand.Reader [mint.go:GenerateKey]
  • OrgKeyVerifier.Verify calls the injected KeySource.PublicKeysForOrg with the unverified iss claim [verifier.go:Verify]
  • FoldOps and UnionKeySource.PublicKeysForOrg do not mutate their inputs. FoldOps returns the caller's refs slice itself when ops is empty and a fresh slice otherwise [policy.go:FoldOps]
  • UnionKeySource.PublicKeysForOrg copies only for the union org. For every other org it returns the inner source's slice unchanged [verifier.go:PublicKeysForOrg]
  • No database, network, filesystem, subprocess, or logging use [auth.go:Claims]

Verification

  • Run: go test ./internal/auth/... -tags=openstorage_viewcheck -count=1 -race -timeout=30m
  • Nightly fuzz lane (.github/workflows/fuzz-nightly.yml), one target per run, for FuzzVerify and FuzzParseRefPolicies. Local form from docs/reference/testing.md: go test ./internal/auth -run '^$' -fuzz '^FuzzVerify$' -fuzztime 60s -parallel 8

Documentation

Overview

Package auth declares the JWT authentication contract for the HTTP API (docs/reference/authentication.md): customer-signed tokens verified against per-org public keys.

FROZEN CONTRACT: parallel phase-1 slices implement Verifier (jwx v3, keys resolved via the meta store) and build middleware/handlers on these exact signatures. Do not change them without coordinating across slices.

Index

Constants

View Source
const (
	ScopeGitRead   = "git:read"
	ScopeGitWrite  = "git:write"
	ScopeRepoWrite = "repo:write"
	ScopeOrgRead   = "org:read"
)

Scopes (docs/reference/authentication.md scope table). Matching is exact: no scope implies another.

View Source
const (
	OpNoPush      = "no-push"
	OpNoForcePush = "no-force-push"
	OpVerifySig   = "verify-sig"
)

Policy ops (docs/reference/authentication.md + branch-protection.md). Unknown ops fail closed in the hook.

View Source
const EphemeralNamespacePrefix = "refs/namespaces/ephemeral/"

EphemeralNamespacePrefix is the storage-side ref prefix for writes that go through the `+ephemeral` namespace (branch-protection.md "Ephemeral namespace quirk"): `refs/heads/main` is stored as `refs/namespaces/ephemeral/refs/heads/main`.

View Source
const RepoClaimOrg = "org"

RepoClaimOrg is the sentinel `repo` claim value for org-level operations (GET /repos).

View Source
const SubjectLiteral = "@pierre/storage"

SubjectLiteral is the fixed `sub` claim used by all vendor SDKs (docs/reference/authentication.md).

Variables

View Source
var AllowedAlgorithms = []string{"ES256", "RS256", "EdDSA", "PS256", "ES384", "ES512"}

AllowedAlgorithms is the JWS signature algorithm allow-list (docs/reference/authentication.md). `none` and HS* are always rejected.

Functions

func DefaultAlgorithm

func DefaultAlgorithm(key crypto.Signer) (string, error)

DefaultAlgorithm infers the natural signing algorithm from the key type, matching vendor SDK auto-detection: EC by curve, RSA → RS256 (PS256 must be requested explicitly), Ed25519 → EdDSA.

func EphemeralRefName

func EphemeralRefName(ref string) string

EphemeralRefName rewrites ref to its ephemeral-namespace storage name, normalizing shorthand first (`main` → `refs/heads/main` → `refs/namespaces/ephemeral/refs/heads/main`). Policies for a push targeting a `+ephemeral` repo are matched against this rewritten name, so persistent-branch rules don't police ephemeral pushes unless the token uses `*` or an explicit namespaced pattern.

An empty ref (malformed external input) yields "", which never names a real ref and never matches a policy pattern (MatchPolicy treats "" as no-match) — callers validate emptiness where it matters.

func GenerateKey

func GenerateKey(alg string) (crypto.Signer, error)

GenerateKey creates a fresh private key for the named algorithm: the curve-matched ECDSA key for ES256/ES384/ES512, RSA-2048 for RS256/PS256, Ed25519 for EdDSA.

func MarshalPrivateKeyPEM

func MarshalPrivateKeyPEM(key crypto.Signer) ([]byte, error)

MarshalPrivateKeyPEM encodes key as one PKCS#8 "PRIVATE KEY" PEM block. Never commit the result.

func MarshalPublicKeyPEM

func MarshalPublicKeyPEM(pub crypto.PublicKey) ([]byte, error)

MarshalPublicKeyPEM encodes pub as one PKIX "PUBLIC KEY" PEM block (the format ParsePublicKeysPEM and the org registry accept).

func MintToken

func MintToken(key crypto.Signer, alg string, c Claims) (string, error)

MintToken signs c into a compact JWT with header {"alg": alg, "typ": "JWT"}. Claims are marshaled exactly as given so tests can mint invalid tokens (expired, wrong sub, ...); typical callers set Sub: SubjectLiteral, Iat: now, Exp: now+ttl. Errors when alg is not allowed or does not fit the key.

func NormalizeRefName

func NormalizeRefName(s string) string

NormalizeRefName applies the docs/reference/authentication.md shorthand rule: anything not starting with `refs/` (and not exactly `*` or `HEAD`) becomes `refs/heads/<value>`.

func ParsePrivateKeyPEM

func ParsePrivateKeyPEM(data []byte) (crypto.Signer, error)

ParsePrivateKeyPEM parses the first PEM block as a PKCS#8 (EC, RSA, or Ed25519) or SEC1 EC private key — the client-side formats named in docs/reference/authentication.md.

func ParsePublicKeysPEM

func ParsePublicKeysPEM(data []byte) ([]crypto.PublicKey, error)

ParsePublicKeysPEM parses one or more PEM "PUBLIC KEY" (PKIX) blocks and returns the contained keys. Accepted key types: ECDSA (P-256/384/521), RSA (at least 2048 bits), and Ed25519 — the families backing AllowedAlgorithms. Errors on zero blocks or any unsupported/undecodable block.

func WithClaims

func WithClaims(ctx context.Context, c *Claims) context.Context

WithClaims returns a context carrying the verified claims (set by the auth middleware after Verify succeeds).

Types

type Claims

type Claims struct {
	Iss    string          `json:"iss"`
	Sub    string          `json:"sub"`
	Repo   string          `json:"repo"` // target repo url, or RepoClaimOrg
	Scopes []string        `json:"scopes"`
	Iat    int64           `json:"iat"`            // unix seconds
	Exp    int64           `json:"exp"`            // unix seconds
	Refs   json.RawMessage `json:"refs,omitempty"` // ordered [pattern, ops] tuples
	Ops    []string        `json:"ops,omitempty"`  // deprecated repo-wide policy ops
	// SyncClaim carries an upstream-sync run's claim-holder token on the
	// internally minted loopback push JWT (issue #86): the update hook
	// refuses ref updates when the repo's sync claim is no longer held by
	// this holder, fencing a stale run's force push out of the ref store
	// even after its request authenticated. Never set on external tokens.
	SyncClaim string `json:"sync_claim,omitempty"`
}

Claims is the verified JWT claim set (docs/reference/authentication.md). Refs/Ops are passed through raw for the git path, which owns ref-policy parsing.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) (*Claims, bool)

ClaimsFromContext returns the verified claims injected by WithClaims, or ok=false when the request was not authenticated.

func (*Claims) HasScope

func (c *Claims) HasScope(scope string) bool

HasScope reports whether claims grant exactly the given scope.

type KeySource

type KeySource interface {
	PublicKeysForOrg(ctx context.Context, name string) ([]string, error)
}

KeySource resolves an org's registered PEM public key blocks by org name (the JWT `iss` claim). meta.Store satisfies this. Implementations return an error for unknown orgs.

func UnionKeySource

func UnionKeySource(inner KeySource, org string, pems ...string) KeySource

UnionKeySource returns a KeySource that appends pems to inner's result for exactly org; every other org resolves through inner unchanged.

type OrgKeyVerifier

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

OrgKeyVerifier implements Verifier: it resolves the issuing org's public keys through a KeySource and verifies the token signature against them, restricted to AllowedAlgorithms.

func NewVerifier

func NewVerifier(keys KeySource) *OrgKeyVerifier

NewVerifier returns an OrgKeyVerifier backed by keys.

func (*OrgKeyVerifier) Verify

func (v *OrgKeyVerifier) Verify(ctx context.Context, token string) (*Claims, error)

Verify authenticates a compact JWT per the Verifier contract: allowed algorithm, valid signature for one of the issuer's registered keys, `exp` in the future, `sub` == SubjectLiteral. Any failure maps to 401.

type RefPolicy

type RefPolicy struct {
	Pattern string
	Ops     []string
}

RefPolicy is one `[pattern, ops]` tuple from the `refs` claim. Policies are ordered; matching is first-match-wins.

func FoldOps

func FoldOps(refs []RefPolicy, ops []string) []RefPolicy

FoldOps merges the deprecated repo-wide `ops` claim into refs as a fallback (docs/reference/authentication.md): with no ops it returns refs unchanged; when refs contains a `*` pattern entry, ops are merged into that entry's op list (deduplicated, existing ops first); otherwise a trailing `["*", ops]` rule is appended. `refs` and `ops` are not additive — callers apply this exactly once at parse time.

The input slices are never mutated; a fresh slice is returned whenever ops is non-empty. Only the first `*` entry is merged into: with first-match-wins evaluation, later `*` entries are dead rules.

func MatchPolicy

func MatchPolicy(policies []RefPolicy, ref string) (RefPolicy, bool)

MatchPolicy scans normalized policies in order and returns the first whose pattern matches ref (normalized with the same shorthand rule); ok=false when nothing matches (unpoliced ref). Pattern syntax per branch-protection.md: an exact ref name, the standalone `*` (matches everything), or a single trailing `*` after a `/` (prefix match, e.g. `refs/heads/feature/*` matches nested `feature/a/b`). No mid-pattern globs, no segment matching.

func ParseRefPolicies

func ParseRefPolicies(raw string) ([]RefPolicy, error)

ParseRefPolicies parses the `refs` claim JSON (ordered [pattern, ops] tuples) and normalizes each pattern per the docs/reference/authentication.md shorthand rule: anything not starting with `refs/` (and not exactly `*` or `HEAD`) becomes `refs/heads/<value>`. Returns an error for malformed JSON or tuples.

func (RefPolicy) MarshalJSON

func (p RefPolicy) MarshalJSON() ([]byte, error)

MarshalJSON encodes the wire tuple form; nil ops marshal as [].

func (*RefPolicy) UnmarshalJSON

func (p *RefPolicy) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the wire tuple encoding `["<pattern>", ["<op>", ...]]`.

type Verifier

type Verifier interface {
	Verify(ctx context.Context, token string) (*Claims, error)
}

Verifier authenticates a compact JWT. Implementations must verify the signature against the issuing org's registered public keys (per AllowedAlgorithms), require `exp` in the future and `sub` == SubjectLiteral, and resolve the org from the `iss` claim.

Any failure — malformed token, bad signature, disallowed algorithm, expired, unknown issuer — returns a non-nil error and maps to 401. Scope and repo-claim checks are the caller's responsibility (403).

Jump to

Keyboard shortcuts

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