auth

package
v0.17.0 Latest Latest
Warning

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

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

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