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
- func Middleware(pub ed25519.PublicKey, issuer string) func(http.Handler) http.Handlerdeprecated
- func MultiIssuer(issuers map[string]Issuer) func(http.Handler) http.Handlerdeprecated
- type Issuerdeprecated
- type OIDCRealm
- type OIDCVerifier
- func (v *OIDCVerifier) Middleware(next http.Handler) http.Handler
- func (v *OIDCVerifier) PartitionForIssuer(issuer string) (string, bool)
- func (v *OIDCVerifier) Realms() int
- func (v *OIDCVerifier) Validate() error
- func (v *OIDCVerifier) Verify(ctx context.Context, raw string) (appkit.Actor, string, error)
- type OIDCVerifierOptions
- type ServiceDelegation
- type ServiceDelegationPolicy
- type ServiceIssuer
- type ServiceSigner
- type ServiceSignerOptions
- type ServiceVerifier
- type ServiceVerifierOptions
Constants ¶
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.
const HeaderStepUp = "X-Step-Up"
HeaderStepUp 携带 step-up 证明(另一枚 JWT)。凭证不跨边界传播——每个 服务用自己的 Authn 重新验证——因此不进 callctx 白名单。
Deprecated: 请优先使用 OIDCVerifier。
Variables ¶
This section is empty.
Functions ¶
func Middleware
deprecated
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。
Deprecated: 请优先使用 OIDCVerifier。
func MultiIssuer
deprecated
added in
v0.9.0
MultiIssuer 是 Middleware 的多签发方形态:按令牌 iss 选验签公钥,iss 不在 表里即 401;step-up 证明必须与访问令牌出自同一签发方。签发方带 Partition 时验签后把分区键焊进 callctx.Meta.Partition。严格 HTTP 边界先剥离所有 unsigned 分区/租户头;本中间件只从已验签令牌及组合根配置重建身份。
表为空、iss 为空、公钥缺失都是装配错误,直接 panic。
Deprecated: 请优先使用 OIDCVerifier。
Types ¶
type Issuer
deprecated
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 是一个签发方的验签规格。
Deprecated: 请优先使用 OIDCRealm 与 OIDCVerifier。
type OIDCRealm ¶ added in v0.11.0
type OIDCRealm struct {
// Issuer 是该 Realm 签发令牌的精确 iss(例如 "https://demo.sso.example.com/")。
Issuer string
// Audience 是目标 Resource Server(API)的精确 aud 标识。
Audience string
// Partition 是该 Realm 绑定的可信数据分区键;非空时验签后焊进 callctx.Meta.Partition。
Partition string
// JWKSURL 是该 Realm 的 JWKS 公钥集合地址。StaticKeys 为空且未指定时默认取
// strings.TrimRight(Issuer, "/") + "/.well-known/jwks.json"。
JWKSURL string
// StaticKeys 允许不经网络直接按 kid 查公钥(单测、离线验收或钉死公钥场景)。
// 支持 *rsa.PublicKey(>=2048 位)、*ecdsa.PublicKey(P-256)与 ed25519.PublicKey。
StaticKeys map[string]crypto.PublicKey
// RequireOrg 为 true 时要求令牌携带非空 org_id(映射为 Actor.TenantID 与 callctx.TenantID)。
RequireOrg bool
}
OIDCRealm 描述一个受信任的 SSO Realm(如 forgeplex/sso 的单个身份域)。 每个 Realm 拥有独立的 Issuer、Audience 与 JWKS(或静态测试公钥),并可映射 到组合根内的一个数据分区(Partition)。
type OIDCVerifier ¶ added in v0.11.0
type OIDCVerifier struct {
// contains filtered or unexported fields
}
OIDCVerifier 是不可变的多 Realm 用户访问令牌验签器;零值无效。
func NewOIDCVerifier ¶ added in v0.11.0
func NewOIDCVerifier(o OIDCVerifierOptions) (*OIDCVerifier, error)
NewOIDCVerifier 校验并构造多 Realm 用户令牌验签器。所有配置切片与公钥映射 在构造期快照,避免运行期外部修改。
func (*OIDCVerifier) Middleware ¶ added in v0.11.0
func (v *OIDCVerifier) Middleware(next http.Handler) http.Handler
Middleware 验签 Bearer 访问令牌并注入 appkit.Actor 与 callctx.Meta:
- /healthz、/readyz 探针直接放行;
- 无 Authorization 头(或非 Bearer)匿名放行,由路由守卫决定是否 401;
- 有 Bearer 头但验签失败(非法签名、未知 iss/kid、错 aud、过期、机器令牌、 缺 sub、缺必需 org_id、与服务委托冲突)一律返回 401,不降级匿名。
func (*OIDCVerifier) PartitionForIssuer ¶ added in v0.11.0
func (v *OIDCVerifier) PartitionForIssuer(issuer string) (string, bool)
PartitionForIssuer 返回已配置 issuer 绑定的可信分区键。
func (*OIDCVerifier) Realms ¶ added in v0.11.0
func (v *OIDCVerifier) Realms() int
Realms 返回已配置 Realm 的数量(供组合根启动测试检查)。
func (*OIDCVerifier) Validate ¶ added in v0.11.0
func (v *OIDCVerifier) Validate() error
Validate 供组合根与 bootstrap 在打开基础设施前校验验签器有效性。
type OIDCVerifierOptions ¶ added in v0.11.0
type OIDCVerifierOptions struct {
Realms []OIDCRealm
HTTPClient *http.Client
CacheTTL time.Duration
MinRefresh time.Duration
ClockSkew time.Duration
// StepUpACRs 列举可视为已通过 MFA step-up 的 acr 取值(除 amr 含 "mfa" 外)。
StepUpACRs []string
// contains filtered or unexported fields
}
OIDCVerifierOptions 配置多 Realm 用户令牌验签器。
type ServiceDelegation ¶ added in v0.9.1
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
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.