authn

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package authn 是访问令牌的验签机制件:解析 Bearer 访问令牌与 X-Step-Up step-up 证明,验签后注入 appkit.Actor。判定(Require/Check)在框架根包, 本包只负责「凭证 → Actor」这一段——验签只写一次,模块经 ctx 只读。

claims 布局是框架与鉴权提供方之间的契约(提供方按此签发,换提供方即换 一个按此布局签发的实现,模块与框架零改动):

访问令牌(Bearer):iss(须是已配置的签发方)、sub=用户、exp 必填、
                   tid=业务租户(可选)、perms=精确权限码快照。
step-up(X-Step-Up):iss(须与访问令牌同一签发方)、sub(须与访问令牌
                   一致)、exp 必填、purpose="step-up"、iat=新鲜度判定依据。

提供方验「挑战动作」(MFA/TOTP 等)并签发 step-up 令牌;本包验「挑战 证明」(签名、iss、sub 一致、purpose、exp)。

挂载是组合根的部署面决策,通常一行:

appkit.Middleware(authn.Middleware(pub, "rbac-demo"))

多分区同进程(每个 rbac 分区一个 iss、可各配一把密钥)用 MultiIssuer, 并顺手把签发方所属的分区键焊进 callctx:

appkit.Middleware(authn.MultiIssuer(map[string]authn.Issuer{
    "rbac-a": {Key: pubA, Partition: "a"},
    "rbac-b": {Key: pubB, Partition: "b"},
}))

Index

Constants

View Source
const HeaderServiceAuthorization = "X-Service-Authorization"

HeaderServiceAuthorization carries a Bearer service JWT, independently of the user's Authorization header. It must never contain a forwarded user token.

View Source
const HeaderStepUp = "X-Step-Up"

HeaderStepUp 携带 step-up 证明(另一枚 JWT)。凭证不跨边界传播——每个 服务用自己的 Authn 重新验证——因此不进 callctx 白名单。

Variables

This section is empty.

Functions

func Middleware

func Middleware(pub ed25519.PublicKey, issuer string) func(http.Handler) http.Handler

Middleware 验签并注入 appkit.Actor。语义:

  • 无 Authorization 头的请求原样放行(不注入 Actor)——判公开与否是 Require 的职责,公开端点(探针等)不因本中间件存在而关死;
  • 除内建 /healthz、/readyz 探针外,有头但验签失败(坏签名、错算法、 错 iss、过期、缺 exp、sub 为空)→ 401:凭证无效必须响亮,不能 静默降级为匿名;探针始终隐式 Public;
  • X-Step-Up 同样原则:有头才验,验不过 401(含 sub 与访问令牌不一致、 purpose 不是 step-up);验过则 Actor.StepUpAt = 证明的 iat。

租户身份在此焊进 callctx:认证请求以令牌 tid 为准。严格安全模式会在 更外层先清掉所有 unsigned 身份头与预置 principal,本中间件只从已验签 token 重建用户与租户身份。 域代码与存储层(RLS)统一从 callctx.From(ctx).TenantID 取租户。

单签发方形态;多签发方(多分区同进程)见 MultiIssuer。

func MultiIssuer added in v0.9.0

func MultiIssuer(issuers map[string]Issuer) func(http.Handler) http.Handler

MultiIssuer 是 Middleware 的多签发方形态:按令牌 iss 选验签公钥,iss 不在 表里即 401;step-up 证明必须与访问令牌出自同一签发方。签发方带 Partition 时验签后把分区键焊进 callctx.Meta.Partition。严格 HTTP 边界先剥离所有 unsigned 分区/租户头;本中间件只从已验签令牌及组合根配置重建身份。

表为空、iss 为空、公钥缺失都是装配错误,直接 panic。

Types

type Issuer added in v0.9.0

type Issuer struct {
	// Key 是该签发方的 EdDSA 验签公钥。
	Key ed25519.PublicKey
	// Partition 是该签发方所属的分区键(rbac 分区 "a" 的签发方 iss=rbac-a
	// 对应 "a")。非空时验签后焊进 callctx.Meta.Partition——认证请求的分区
	// 以令牌为准,入站 X-Partition 头带来的值被覆盖;空则不动 callctx 里的
	// 分区(单分区部署或不用分区的系统)。严格 HTTP 边界已清除 unsigned
	// 分区;如果另有可信服务验证器先重建了分区,空配置也不会覆盖它。
	Partition string
}

Issuer 是一个签发方的验签规格。

type ServiceDelegation added in v0.9.1

type ServiceDelegation struct {
	TenantID   string
	MerchantID string
	Partition  string
}

ServiceDelegation is the explicitly authorized data scope of one service call. Empty fields do not mean all tenants/merchants/partitions. MerchantID stays in ServicePrincipal; it is deliberately not added to callctx's propagation list.

type ServiceDelegationPolicy added in v0.9.1

type ServiceDelegationPolicy func(context.Context, appkit.ServicePrincipal, ServiceDelegation) error

ServiceDelegationPolicy authorizes the complete requested scope after signature verification (or before signing). A nil policy denies any nonempty delegation. The callback must be concurrency-safe and honor ctx cancellation. It receives a detached principal snapshot; changing it cannot change the verified identity.

type ServiceIssuer added in v0.9.1

type ServiceIssuer struct {
	Keys     map[string]ed25519.PublicKey
	Subjects []string
}

ServiceIssuer is a static trust entry. Keys are selected by the exact iss+kid pair; Subjects is a nonempty allowlist. Neither token-provided URLs nor dynamic key lookup are supported. Keep old and new kids during a deliberate rotation.

type ServiceSigner added in v0.9.1

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

ServiceSigner signs only explicitly supplied audience and delegation. It does not infer authorization from an Actor, incoming credential, header or callctx.

func NewServiceSigner added in v0.9.1

func NewServiceSigner(o ServiceSignerOptions) (*ServiceSigner, error)

NewServiceSigner validates the fixed identity, lifetime and key without panicking. Callers retain ownership of their private-key buffer.

func (*ServiceSigner) Sign added in v0.9.1

func (s *ServiceSigner) Sign(ctx context.Context, audience string, scope ServiceDelegation) (string, error)

Sign returns a compact service JWT. Use SignWithExpiry when a transport must check freshness without interpreting the token or caching past its expiry.

func (*ServiceSigner) SignWithExpiry added in v0.9.1

func (s *ServiceSigner) SignWithExpiry(ctx context.Context, audience string, scope ServiceDelegation) (string, time.Time, error)

SignWithExpiry returns the exact signed expiry, not a separately sampled clock.

type ServiceSignerOptions added in v0.9.1

type ServiceSignerOptions struct {
	Issuer              string
	Subject             string
	KeyID               string
	Key                 ed25519.PrivateKey
	TTL                 time.Duration
	AuthorizeDelegation ServiceDelegationPolicy
}

ServiceSignerOptions describes a fixed service identity. The constructor copies Key. TTL defaults to one minute and must be an integral second in 1s..5m.

type ServiceVerifier added in v0.9.1

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

ServiceVerifier is immutable after construction; its zero value is invalid.

func NewServiceVerifier added in v0.9.1

func NewServiceVerifier(o ServiceVerifierOptions) (*ServiceVerifier, error)

NewServiceVerifier validates configuration without panicking and snapshots all maps, slices, and key bytes. Subsequent caller changes do not rotate live keys.

func (*ServiceVerifier) Middleware added in v0.9.1

func (v *ServiceVerifier) Middleware(next http.Handler) http.Handler

Middleware verifies a present service credential, then injects ServicePrincipal and callctx.Caller from signed sub. Missing credentials remain anonymous; route guards decide whether authentication is required. Invalid credentials fail even on public application routes, except the built-in health/readiness probes. In mixed mode install user authentication first. Both credentials must agree on the exact tenant and partition, including empty scope. No user Actor is created.

func (*ServiceVerifier) Validate added in v0.9.1

func (v *ServiceVerifier) Validate() error

Validate permits composition roots to fail before migrations, Setup or listen.

type ServiceVerifierOptions added in v0.9.1

type ServiceVerifierOptions struct {
	Audience            string
	Issuers             map[string]ServiceIssuer
	MaxTTL              time.Duration
	ClockSkew           time.Duration
	AuthorizeDelegation ServiceDelegationPolicy
}

ServiceVerifierOptions configures one recipient. Audience must be explicit. MaxTTL defaults to five minutes and may only reduce that limit. ClockSkew is optional, capped at 30 seconds, and never increases the allowed exp-iat span.

Jump to

Keyboard shortcuts

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