auth

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 23 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.

README

独立 Auth

公开包 github.com/lfhy/compactfs/fs/cluster/auth 将身份数据库、账号目录和 STS 签发放在独立进程中。Meta 继续决定文件访问、版本租约和 RF3 布局,然后通过已认证的服务连接提交精确 grant;Data/compute 继续在本机验证票据与持久门禁。Auth 不拥有文件元数据。

API 职责
NewServer(Config{Identity: authConfig, StatePath: path}) 校验 Auth 角色并独占身份库;仅首次从配置初始化
Server.ServeHTTP 在 /v1/auth/control 提供 WebSocket 控制 RPC
Server.Close(ctx) 取消并等待 RPC,随后释放状态文件;超时可重试
Server.Drain(ctx) 关闭并等待 RPC,保留 DB,允许组装方先停止共识后台 Apply
NewClient(ClientConfig{Endpoint, RPC, Epoch, Incarnation, Timeout}) 接受 Auth/Gateway base URL 或完整控制 URL,使用 Meta 服务身份
Client.Lookup(ak, securityToken) 仅查询未过期长期身份,拒绝非空 token
Client.Issue(ctx, originAK, grant) 以原始客户端 AK 请求签发已批准 grant,不自动重放
Client.Close() 取消并等待调用和握手,关闭共享连接
Catalog/CreateNamespace/UpdateNamespace/DisableNamespace 无密钥账号目录和资源策略;名称可改,opaque ID 不变
CreateKey/ListKeys/DisableKey/DeleteKey/RotateKey 多AK、client/reader及默认控制scope的admin、过期和撤销;列表无 SK,创建/轮换只返回一次新 SK
Revocations(ctx, since) 每页最多 1024 条,接最后 Sequence 拉取直到空页
SetCommitter/Apply/AppliedSequence 挂接有序共识提交;Apply 只在持久成功后发布内存快照
ReplicationSeed(ctx) 首条共识日志的完整 typed seed,包含退休记录/撤销 feed;至多32MiB
Snapshot/SnapshotFile/Restore 全库一致备份、离线备份和新目标灾备恢复
ReadRecoveryInfo(ctx, path) 读取无密钥的来源序号与用户AK退休数量审计
InspectCheckpoint(ctx, path, identity) 只读校验停止的DB与精确signing generation,返回native sequence及逻辑digest

RPC 节点身份固定为 auth;客户端会覆盖普通 Meta 角色文件中的 RPC NodeID。identity.lookup 和 token.issue 仅允许 meta 角色,普通文件客户端无法直接查询身份密钥或提交任意 STS 请求。服务身份和 Gateway 路由均不能替代最终 Data 的授权检查。

Lookup 返回身份登记的 NamespaceID/Revision,Issue 再核对原始 AK 的归属、有效期和 client/reader 权限。多组 AK 可共享同一 Principal/NamespaceID,但不能用可重名的 Principal 替代 AK 请求签票;只有旧默认模式的唯一 Principal 与后台唯一 Meta 服务身份保留兼容调用。Meta 服务可为已登记空间提交明确 scope,普通身份不能跨空间。用户票使用 version 3,把原始 AK/revision 与 namespace 一并签名;旧 Data 拒绝该版本。后台 Meta 票不绑定某个用户,Meta 仍负责其权限与对象来源。Auth 不决定 grant 的对象或卷是否对应已提交文件。

状态文件沿用现有 bbolt 依赖,schema 2 分表保存版本化 header、namespace、credential 和撤销 feed,不以整张 JSON 身份表充当数据库。现有单代数库会原子迁移,其他数据库不会被改写。首次启动的 JSON 是 bootstrap;以后以 DB 为准,旧 JSON 不会覆盖策略或复活撤销身份。最多 64 个空间、8192 个 AK(含删除墓碑)。事务持久成功后才发布不可变内存快照,Lookup/Issue 走内存;管理提交失败不会改变可见身份。每次控制请求重验当前调用方,撤销后的旧连接也不能继续签新票。

管理 RPC 仅允许 admin;Catalog/撤销 feed 允许 meta 或 admin,查询长期 SK 仍仅允许 meta。禁用/删除/轮换和空间开关会同事务提高相应 AK revision 并写撤销记录。让旧 STS 立即失效仍需运行层把撤销 feed 同步至 Data/compute 的持久 gate,并等待 ACK;只改 Auth DB 不能宣称所有旧票即时失效。配置 Gate 可在 authority 租约失效时关闭普通请求,Other 只接收已认证 meta 的 authority.* 复制调用。提交器可接入统一复制域,包本身不自动选主。

默认 CLI 的 cmd/auth.AuthServer 在独立 Auth Raft 组装上使用 Gate 执行多数派读屏障,并在屏障后的已应用快照重新检查调用方。少数派不能查询账号、管理凭据或签新票。Auth 的选举 term 独立于 STS generation,普通选主不改变已有票据的有效期。配置 ReplicaKeys 的固定物理成员只能调用复制运输,不能用这组 AK 查询用户密钥或签票;用户目录撤销不会阻断副本间恢复。

共识首条 auth 日志保存 ReplicationSeed,采用确定顺序的 typed 记录,完整包含秘密、配额、永久退休记录和撤销 feed。新盘从完整日志重建,JSON 只提供共识运输与首次 seed 材料。初始记录与 applied marker 在同一个 bbolt 事务提交,失败不发布内存快照;不能将已有非零 native 历史直接换序号导入空日志,也不能由旧 seed 清除退休 AK。详细启动和投票材料说明见Auth Raft 部署。

运行中的服务只接受精确 epoch/incarnation;请求者无法提升它。手动推进需显式更新 Auth 配置并重启,持久代数防旧配置回退和同 epoch 换 incarnation。Snapshot 流式导出包含秘密、墓碑、节点票据密钥及 applied sequence 的一致图像,调用者负责加以保护;SnapshotFile 需要先停止 Auth。普通 Restore 只创建新目标,要求更高 epoch 和新 incarnation,拒绝损坏图像、既有目标和符号链接;恢复保留备份内 NodeKeys。

灾备恢复默认永久退休备份内全部 client/reader 用户 AK:记录显示 retired=true、disabled=true,所存 SK 清空,账号、空间、配额及原 AK 审计仍保留。不能通过轮换旧 AK、重新启用空间或重放修改复活它,必须 CreateKey 发放全新 AK。这样即使某用户在备份之后才被撤销,也不会因恢复旧备份而重新获得访问。仅提升 epoch 只能阻止旧 STS,不能替代这一步。

恢复保留 admin/服务身份以重新建立控制面;这些身份在备份之后的撤销仍需要最新可信配置或撤销日志逐项核对并补齐,恢复后应轮换管理密钥。CLI 的 admin 轮换先创建新 AK、0600保存新配置,成功后才禁用旧 AK,输出失败保留旧入口。可用 cpfs auth key rotate -gw GATEWAY --cluster-config ./admin.json --ak OLD_ADMIN_AK --out ./admin-new.json --wait;--wait 使用保存后的新 admin 身份。Meta/Data/compute 服务 AK 仍需按各角色配置维护。

严格恢复的 native applied marker 为0,RecoverySourceSequence 保留原序号。重建 Auth Raft 时,各副本使用同一备份和同一新 signing generation 恢复得到一致 seed;cpfs auth raft-init 另行生成全新 GroupID、递增的发现 generation 和一次性投票材料,再使用全新 authority 目录,不能接回旧 WAL。首条共识 seed 保存退休墓碑和完整撤销 feed,后续空盘追赶无需依赖旧 JSON 恢复这些记录。旧 Auth 必须全部 fencing,Meta/Data 也必须完成新代数门禁 ACK 后才恢复客户端流量。命令顺序见Auth Raft 部署。

已有 paired Auth 的 ReplicaRestoreExactGeneration 只用于同代数且被 fencing 的新 standby 初始同步,保留用户状态和精确 marker,不能用于灾备激活。该模式提升会导出当前完整DB与完整WAL到同一检查点,并整目录原子发布替换standby材料;复制检查点保留当前native marker,不重新退休用户或归0。任何恢复都不替代 fencing 和门禁 ACK。旧JSON无法描述灾备seed中的退休记录,不能单独用它加新WAL替换已恢复的副本。

客户端使用一个有界的懒连接并发复用 RPC,断线后由下一次显式调用重新连接。Lookup 也受缺省五秒超时和 Close 取消控制。配置中的 Timeout 可以覆盖为一分钟以内的正值。HTTP server、listener 由组装方拥有;Auth 服务拥有升级连接与状态库,结束时先停止入口再关闭服务。

明文身份查询响应包含长期身份密钥,仅适用于既定可信内部网络,不应记录响应内容。独立 Gateway 只转发这些消息,无需持有密钥;公网 TLS 可由入口代理终止。

回归测试使用真实 HTTP/WebSocket 和 bbolt,覆盖管理门禁、同空间多 AK、reader、撤销和轮换、旧 JSON 重启、迁移、失败提交、幂等重放、备份恢复与并发 lookup/update,并保留取消、关闭和重连验证。

管理命令使用独立的 admin 角色配置;新客户端密钥只保存到指定文件:

cpfs auth namespace create -gw http://127.0.0.1:7420 --cluster-config ./admin.json --name team-c --quota-bytes 107374182400
cpfs auth key create -gw http://127.0.0.1:7420 --cluster-config ./admin.json --namespace team-c --principal alice --out ./alice.json
cpfs auth key rotate -gw http://127.0.0.1:7420 --cluster-config ./admin.json --ak OLD_AK --out ./alice-new.json --wait
cpfs auth namespace update -gw http://127.0.0.1:7420 --cluster-config ./admin.json --namespace team-c --disabled=false

namespace list 和 key list --namespace team-c 输出无 SK 的 JSON。namespace update 省略的资源项保持原值,--name 修改展示名,ID 与已有客户端归属保持不变。--wait 经 --meta-server 或 -gw 等待撤销门禁;如 ACK 未齐,命令明确报告 Auth 已提交,不能据此继续信任旧票。轮换前应确认新输出文件路径可用,CLI支持client/reader/admin,服务AK按角色维护。

停止对应 Auth 后可运行 cpfs auth backup create --state ./auth.db --out ./auth.image。恢复使用 cpfs auth backup restore --in ./auth.image --state ./new/auth.db --cluster-config ./auth-new-generation.json;该配置必须属于同一集群,明确指定更高 epoch 和不同 incarnation。输出包含 users_retired=true、退休数量、来源序号和新HA目录要求。恢复后先核对并轮换管理/服务身份,再为用户创建新AK并分发新私有配置;备份和恢复不会自动启动服务、fence旧主或更新Data门禁。

Documentation

Overview

Package auth hosts offline identities and signs metadata-approved object grants without owning namespace, placement or a metadata write lease.

Index

Constants

View Source
const (
	NodeID      = "auth"
	ControlPath = "/v1/auth/control"
)
View Source
const RevocationPageSize = 1024

Variables

This section is empty.

Functions

func ReplicaRestoreExactGeneration

func ReplicaRestoreExactGeneration(ctx context.Context, r io.Reader, path string, identity cluster.Config) error

ReplicaRestoreExactGeneration bootstraps a fresh, fenced standby at exactly the snapshot generation. It must not be used as disaster promotion: the caller must keep the new replica fenced until normal authority replay/registration.

func Restore

func Restore(ctx context.Context, r io.Reader, path string, identity cluster.Config) error

Restore creates a new database without replacing any existing target. Disaster recovery must use a strictly newer epoch and a different incarnation; the generation in an old backup can never be activated directly by this API. Every restored client/reader AK is permanently retired: a backup cannot know which users were revoked after its capture. Administrators must create new user AKs. Service/admin credentials are retained for control-plane recovery and require a separate trusted revocation audit and subsequent rotation.

func SnapshotFile

func SnapshotFile(ctx context.Context, path string, w io.Writer) error

SnapshotFile exclusively opens an offline identity database. It neither seeds JSON identities nor changes authority generation. A running Auth owns the exclusive lock, so an operator must stop it before using this helper.

Types

type CheckpointInfo

type CheckpointInfo struct {
	Sequence uint64
	Digest   string
}

CheckpointInfo describes secret-bearing offline replica material without exposing stored SKs. Digest is only for authenticated replica comparisons.

func InspectCheckpoint

func InspectCheckpoint(ctx context.Context, path string, identity cluster.Config) (CheckpointInfo, error)

InspectCheckpoint validates a stopped database without creating, seeding or changing it. It requires the exact signing generation; ordinary NewServer intentionally permits explicit generation advancement and is not an inspector.

type Client

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

Client owns one lazily established RPC connection. Calls share that connection concurrently; failures never replay a token issue automatically.

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context) ([]NamespacePolicy, error)

func (*Client) Close

func (c *Client) Close() error

Close cancels pending calls and dialing, closes the shared connection and waits until all callers have relinquished it. It is safe to call concurrently.

func (*Client) CreateKey

func (c *Client) CreateKey(ctx context.Context, q KeyRequest) (CreatedCredential, error)

func (*Client) CreateNamespace

func (c *Client) CreateNamespace(ctx context.Context, p NamespacePolicy) (NamespacePolicy, error)

func (*Client) DeleteKey

func (c *Client) DeleteKey(ctx context.Context, ak string) error

func (*Client) DisableKey

func (c *Client) DisableKey(ctx context.Context, ak string) error

func (*Client) DisableNamespace

func (c *Client) DisableNamespace(ctx context.Context, id string) error

func (*Client) Issue

func (c *Client) Issue(ctx context.Context, principal string, grant cluster.Grant) (cluster.Credentials, error)

func (*Client) ListKeys

func (c *Client) ListKeys(ctx context.Context, id string) ([]CredentialInfo, error)

func (*Client) Lookup

func (c *Client) Lookup(accessKeyID, securityToken string) (cluster.Identity, error)

Lookup is a bounded remote identity lookup for an RPC Authenticator. It accepts long-term identities only and does not treat temporary tokens as keys.

func (*Client) Revocations

func (c *Client) Revocations(ctx context.Context, since uint64) ([]Revocation, error)

func (*Client) RotateKey

func (c *Client) RotateKey(ctx context.Context, ak string) (CreatedCredential, error)

func (*Client) UpdateNamespace

func (c *Client) UpdateNamespace(ctx context.Context, p NamespacePolicy) (NamespacePolicy, error)

type ClientConfig

type ClientConfig struct {
	Endpoint    string
	RPC         cluster.RPCClientConfig
	Epoch       uint64
	Incarnation string
	Timeout     time.Duration
}

type CommitFunc

type CommitFunc func(context.Context, func(context.Context, uint64) ([]byte, error)) error

CommitFunc reserves a global sequence, prepares under that reservation and confirms only after Apply persisted the mutation on every required replica.

type Config

type Config struct {
	Identity  cluster.Config
	StatePath string
	Gate      func(context.Context) error
	Other     cluster.RPCHandler
	// ReplicaKeys authenticate only physical consensus peers. These fixed
	// bootstrap keys cannot call ordinary identity, signing or admin methods.
	ReplicaKeys map[string]cluster.Identity
}

Config requires a role-scoped Auth identity and a persistent state path. StatePath is a bbolt file held exclusively until Server.Close succeeds.

type CreatedCredential

type CreatedCredential struct {
	CredentialInfo
	SecretAccessKey string `json:"secret_access_key"`
}

type CredentialInfo

type CredentialInfo struct {
	AccessKeyID string    `json:"access_key_id"`
	Principal   string    `json:"principal"`
	NamespaceID string    `json:"namespace_id"`
	Roles       []string  `json:"roles"`
	Expires     time.Time `json:"expires,omitempty"`
	Disabled    bool      `json:"disabled"`
	// Retired permanently disables a user AK after disaster recovery. Its
	// audit record survives, while the stored SK is erased and never reissued.
	Retired  bool   `json:"retired,omitempty"`
	Revision uint64 `json:"revision"`
}

CredentialInfo deliberately excludes every stored secret.

type IssueRequest

type IssueRequest struct {
	Principal   string        `json:"principal"`
	Grant       cluster.Grant `json:"grant"`
	Epoch       uint64        `json:"epoch"`
	Incarnation string        `json:"incarnation"`
}

IssueRequest binds every issue call to the exact authority generation with which the requesting Meta was started. It cannot advance the Auth generation.

type KeyRequest

type KeyRequest struct {
	NamespaceID string    `json:"namespace_id"`
	Principal   string    `json:"principal"`
	Roles       []string  `json:"roles"`
	Expires     time.Time `json:"expires,omitempty"`
}

type LookupRequest

type LookupRequest struct {
	AccessKeyID   string `json:"access_key_id"`
	SecurityToken string `json:"security_token,omitempty"`
}

type NamespacePolicy

type NamespacePolicy struct {
	Name           string `json:"name"`
	ID             string `json:"id"`
	QuotaBytes     int64  `json:"quota_bytes"`
	CacheBytes     int64  `json:"cache_bytes"`
	ReadCacheBytes int64  `json:"read_cache_bytes"`
	Workers        int    `json:"workers"`
	Weight         int    `json:"weight"`
	MaxInflight    int    `json:"max_inflight"`
	Disabled       bool   `json:"disabled"`
	Revision       uint64 `json:"revision"`
}

NamespacePolicy is the authoritative account catalog. IDs never change when display names or resource policy change. Zero resource values mean defaults.

type RecoveryInfo

type RecoveryInfo struct {
	SourceSequence uint64 `json:"source_sequence"`
	RetiredUsers   int    `json:"retired_users"`
}

RecoveryInfo is a nonsecret audit of the most recent disaster restore. The native marker starts at zero in the new generation; SourceSequence retains the input database's native position without permitting old WAL reuse.

func ReadRecoveryInfo

func ReadRecoveryInfo(ctx context.Context, path string) (RecoveryInfo, error)

type Revocation

type Revocation struct {
	Sequence uint64 `json:"sequence"`
	AK       string `json:"ak"`
	Revision uint64 `json:"revision"`
	Disabled bool   `json:"disabled"`
}

type Server

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

Server owns RPC connections and its exclusive authority-generation store. The caller owns the enclosing HTTP server and listener.

func NewServer

func NewServer(cfg Config) (*Server, error)

func (*Server) AppliedSequence

func (s *Server) AppliedSequence(ctx context.Context) (uint64, error)

func (*Server) Apply

func (s *Server) Apply(ctx context.Context, seq uint64, payload []byte) error

Apply is deterministic and idempotent. It never invokes the committer. The published snapshot is constructed within the transaction and stored only after bbolt commits, so persistence failure cannot change authentication.

func (*Server) Catalog

func (s *Server) Catalog(ctx context.Context) ([]NamespacePolicy, error)

func (*Server) Close

func (s *Server) Close(ctx context.Context) error

Close cancels and joins RPC calls before releasing the state file. A timed out RPC close keeps the database owned so callers may retry with a new ctx.

func (*Server) CreateKey

func (s *Server) CreateKey(ctx context.Context, q KeyRequest) (CreatedCredential, error)

func (*Server) CreateNamespace

func (s *Server) CreateNamespace(ctx context.Context, p NamespacePolicy) (NamespacePolicy, error)

func (*Server) DeleteKey

func (s *Server) DeleteKey(ctx context.Context, ak string) error

func (*Server) DisableKey

func (s *Server) DisableKey(ctx context.Context, ak string) error

func (*Server) DisableNamespace

func (s *Server) DisableNamespace(ctx context.Context, id string) error

func (*Server) Drain

func (s *Server) Drain(ctx context.Context) error

Drain cancels and joins the RPC layer while retaining database ownership. Consensus owners stop background Apply after Drain and before Close.

func (*Server) Issue

func (s *Server) Issue(ctx context.Context, origin string, grant cluster.Grant) (cluster.Credentials, error)

func (*Server) ListKeys

func (s *Server) ListKeys(ctx context.Context, namespaceID string) ([]CredentialInfo, error)

func (*Server) Lookup

func (s *Server) Lookup(accessKeyID, securityToken string) (cluster.Identity, error)

func (*Server) ReplicationDigest

func (s *Server) ReplicationDigest(ctx context.Context) (string, error)

ReplicationDigest compares logical state rather than bbolt pages or Gob map byte order. It includes bootstrap secrets, catalog, generation, revocations and native watermarks, so equal empty WALs cannot hide different seeds. The digest must only be exchanged over an authenticated physical peer link.

func (*Server) ReplicationSeed

func (s *Server) ReplicationSeed(ctx context.Context) ([]byte, error)

ReplicationSeed captures complete account state for the first consensus log entry. The coordinator must commit it only to an empty log; existing logs retain their original seed, including strict-recovery retirement tombstones. SourceSequence is checked on Apply: an existing nonzero native history must be migrated explicitly instead of being silently renumbered into a fresh group.

func (*Server) Revocations

func (s *Server) Revocations(ctx context.Context, since uint64) ([]Revocation, error)

Revocations returns one bounded page. Continue from the last Sequence until an empty page; the feed includes tombstones and namespace transitions.

func (*Server) RotateKey

func (s *Server) RotateKey(ctx context.Context, ak string) (CreatedCredential, error)

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetCommitter

func (s *Server) SetCommitter(commit CommitFunc)

func (*Server) Snapshot

func (s *Server) Snapshot(ctx context.Context, w io.Writer) error

Snapshot streams a consistent database image including secrets, tombstones, revocations and the applied sequence. The caller owns and protects the writer. A checksum detects accidental damage; this is not an untrusted import format.

func (*Server) UpdateNamespace

func (s *Server) UpdateNamespace(ctx context.Context, p NamespacePolicy) (NamespacePolicy, error)

Jump to

Keyboard shortcuts

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