auth

package
v0.2.33 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package auth 提供 Cloudpath 的鉴权原语:argon2id 密码哈希、服务端会话 cookie、 服务令牌校验、登录限流与请求身份(Principal)解析(docs/api.md §1/§2)。

Index

Constants

View Source
const (
	Argon2Time    uint32 = 3
	Argon2Memory  uint32 = 64 * 1024 // KiB
	Argon2Threads uint8  = 2
	Argon2KeyLen  uint32 = 32
)

argon2id 参数(契约要求写成实现常量;Verify 只接受与之一致的哈希, 避免把攻击者可控的 m/t 交给 argon2 造成内存/CPU DoS)。

View Source
const SessionCookieName = "cp_session"

SessionCookieName 是服务端会话 cookie 名(契约 §2.1:cp_session)。

View Source
const TenantTokenPrefix = "cp_"

TenantTokenPrefix 是租户服务令牌的固定前缀(docs/api.md §3.3)。

Variables

This section is empty.

Functions

func BearerToken

func BearerToken(r *http.Request) string

BearerToken 提取 Authorization: Bearer <token>;无则空串。

func ClearSessionCookie

func ClearSessionCookie(w http.ResponseWriter)

ClearSessionCookie 清 cookie(登出/会话失效)。

func ClientIP

func ClientIP(r *http.Request, proxies *TrustedProxies) string

ClientIP 返回客户端 IP:仅当对端命中 trusted proxies 时才解析 X-Real-IP / X-Forwarded-For;否则一律用 socket 对端 IP(防伪造绕过)。

func ConstantTimeEqual

func ConstantTimeEqual(a, b string) bool

ConstantTimeEqual 恒时比较两个秘密字符串:先把双方散列成定长摘要, 再用 subtle 比较,避免长度早退泄露秘密内容。

func DummyVerify

func DummyVerify(password string)

DummyVerify 对未知用户执行一次完整 Argon2id 派生,结果丢弃。 登录路径对不存在的用户名也必须烧掉等量 CPU,避免通过响应时延枚举用户名。

func HasScope

func HasScope(scopes []string, target string) bool

HasScope 判断 scopes 是否包含目标 scope。

func HashPassword

func HashPassword(password string) (string, error)

HashPassword 生成可持久化的 argon2id 哈希(含参数与盐,自描述,永不落明文)。

func HashToken

func HashToken(token string) string

HashToken 返回 token 的 SHA-256 十六进制 hash(数据库只存 hash)。

func IsLoopbackRemote

func IsLoopbackRemote(r *http.Request) bool

IsLoopbackRemote 判断来源是否为回环地址(无凭据写操作的放行条件)。 只看真实 TCP 对端(RemoteAddr),不采信任何转发头。

func IsSecureRequest

func IsSecureRequest(r *http.Request, proxies *TrustedProxies) bool

IsSecureRequest 判断请求是否走 TLS:真实 TLS,或可信反代声明的 X-Forwarded-Proto=https。未命中可信反代时伪造 proto 头一律忽略。

func IsTenantToken

func IsTenantToken(token string) bool

IsTenantToken 判断 token 是否为租户令牌形状(cp_ 前缀)。

func NewSessionID

func NewSessionID() (string, error)

NewSessionID 生成 256-bit 随机会话 ID(base64url,无填充)。

func NewTenantToken

func NewTenantToken() (plain, hash, prefix string, err error)

NewTenantToken 生成 `cp_` + 32 字节随机数据的租户服务令牌。 返回明文(仅在创建响应返回一次)、SHA-256 十六进制 hash 与短 prefix。

func QueryToken

func QueryToken(r *http.Request) string

QueryToken 提取 ?token=(WS 等无法自定义 header 的场景)。

func RoleAllows

func RoleAllows(role, need string) bool

RoleAllows 判断角色是否满足所需角色(admin>operator>viewer 层级)。

func RoleRank

func RoleRank(role string) int

RoleRank 返回角色权限等级:admin=3 > operator=2 > viewer=1 > 未知=0。

func ScopeRole

func ScopeRole(scopes []string) string

ScopeRole 把租户令牌 scopes 映射为等价角色。 read→viewer、write→operator、admin→admin;edge 不授予 REST 角色。 空集合或仅 edge → ""(无 REST 权限)。

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, maxAge int, proxies *TrustedProxies)

SetSessionCookie 写 cp_session cookie:HttpOnly + SameSite=Lax;真实 TLS 或 可信反代声明的 https 下加 Secure。maxAge 为 TTL 秒(每次登录新 ID,防固定)。

func TokenOK

func TokenOK(r *http.Request, token string) bool

TokenOK 校验共享服务令牌:令牌非空且命中 header 或 query,等价 admin。 比较走恒定时间,避免 legacy token 被时序侧信道探测。

func VerifyPassword

func VerifyPassword(encoded, password string) bool

VerifyPassword 常数时间校验明文密码与哈希。格式/参数不合法一律 false。

func WithPrincipal

func WithPrincipal(ctx context.Context, p *Principal) context.Context

WithPrincipal 把解析出的身份挂进请求 context。

Types

type Principal

type Principal struct {
	UserID     int64
	Username   string
	Name       string
	Role       string
	TenantID   int64
	TenantSlug string
	Token      bool     // 服务令牌身份(无会话行)
	Legacy     bool     // legacy -token(等价 default tenant admin)
	Scopes     []string // 租户服务令牌 scopes(会话/legacy 为空)
}

Principal 是解析后的请求身份:会话用户或服务令牌(等价 admin)。

func FromContext

func FromContext(ctx context.Context) *Principal

FromContext 取请求身份;未认证返回 nil。

type RateLimiter

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

RateLimiter 是滑动窗口限流器(登录限流:默认 5 次/分/IP)。 除了每 key 滑窗外,还带 TTL 清理与最大容量驱逐。

func NewRateLimiter

func NewRateLimiter(per int, maxKeys ...int) *RateLimiter

NewRateLimiter 构造限流器;per<=0 归一为 1。可选第二个参数为最大 key 数。

func (*RateLimiter) Allow

func (l *RateLimiter) Allow(key string) (bool, time.Duration)

Allow 记录一次命中并判定是否放行。放行返回 (true, 0);超限返回 (false, retryAfter)。 命中序列单调递增,kept[0] 即窗口内最早命中。

func (*RateLimiter) Len

func (l *RateLimiter) Len() int

Len 返回当前内存中的 key 数(测试用)。

type TrustedProxies

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

TrustedProxies 是显式的反向代理来源 allowlist(CIDR 或单 IP)。 仅当 TCP 对端地址命中该清单时,才采信 X-Forwarded-For / X-Real-IP / X-Forwarded-Proto 等转发头;直连请求伪造这些头一律忽略。

func ParseTrustedProxies

func ParseTrustedProxies(cidrs []string) (*TrustedProxies, error)

ParseTrustedProxies 解析 CIDR/IP 清单;空清单返回 nil(不信任任何反代)。 任一非法条目返回错误:配置错误必须 fail-closed,绝不静默信任。

func (*TrustedProxies) Contains

func (tp *TrustedProxies) Contains(ip net.IP) bool

Contains 报告 ip 是否命中 allowlist。

func (*TrustedProxies) Empty

func (tp *TrustedProxies) Empty() bool

Empty 报告 allowlist 是否为空(nil 视为空)。

func (*TrustedProxies) TrustsRemote

func (tp *TrustedProxies) TrustsRemote(remoteAddr string) bool

TrustsRemote 报告 TCP 对端地址是否为可信反代。

Jump to

Keyboard shortcuts

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