背景:auth.go 注释写着 RoleViewer 是只读监控档,但实现从未接线 —— 管理侧 24 个 GET 全是 owner/admin,viewer 全 403。本批把它接上(手机端「全功能管理」的前置之一)。
- routes.go:新增第四道门 viewerAuth = Authorize(owner, admin, viewer);registerAdminRoutes 传入。**只**把 12 条只读监控 GET 从 writeAuth 换过来:personas / sessions / plugins / plugins-installed / channels / iot / automations / rag / observability{metrics,trace,logs} / notifications;其余 12 条读与 32 条写**一行不动**
- 保持 owner/admin(viewer 403):memories / llm / users / backthink / audit / sessions-export / channels-messages ×2;owner-only(35 条)含凭据获取(login-qr/login-status)、channels view/friends、全部写操作
- 三处「编码旧策略」的既有测试按**新权限矩阵**改写(不是放宽):gateway_test 的 /admin/plugins viewer 403→200 且补一条 memories 403;observability_logs 的 ViewerForbidden→ViewerReadsTail;notifications 的 viewer 403→200
- 新增 rbac_viewer_test.go:5 个顶层 / 185 个子测试(12 条×3 角色 200、9+35 条 viewer 403、admin 在读档非 401/403 且在 owner-only 403、56 条匿名 401、写路由 viewer 403);含 3 次变异验证(含**反向变异**:把 memories 误放开为 viewerAuth 会 FAIL)
- auth.go 的 RoleViewer 注释改为**实际**可见面;Docs/api-client 新增 §2.0 管理侧权限矩阵 + 变更记录 v0.40;顺带修 §0 一处不实陈述(原写「管理端另支持 X-API-Key」→ 标注尚未接线)
- 验收:**隔离 worktree(HEAD + 本片)** go build/vet/test 全绿 + linux/amd64 与 darwin/arm64 交叉编译 + gofmt 干净(主工作树此时被另一代理的在途改动占用,见下条提交)
- 已知遗留(未改前端,按范围只记录):管理面板未按角色隐藏分区 → viewer 打开 memories/users/llm/审计等页会吃 403(应做能力降级)
117 lines
4.3 KiB
Go
117 lines
4.3 KiB
Go
// Package auth provides authentication and authorization primitives for the
|
|
// Cyrene v2 gateway: JWT signing/verification (HS256), an RBAC middleware built
|
|
// on an owner>admin>viewer role hierarchy, in-memory API keys, and salted
|
|
// password hashing. All APIs are self-contained and use only the standard
|
|
// library, so the package compiles without adding dependencies to the module.
|
|
//
|
|
// Identity is carried as strong-typed actor metadata and decided by policy (see
|
|
// DevDocs/design/11): it is never inferred by an LLM. This package supplies the
|
|
// credential layer that such policies rely on.
|
|
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// Role is an authorization role in the owner>admin>viewer hierarchy.
|
|
type Role string
|
|
|
|
const (
|
|
// RoleOwner has full authority, including security/key/system settings.
|
|
RoleOwner Role = "owner"
|
|
// RoleAdmin manages modules but no sensitive security items.
|
|
RoleAdmin Role = "admin"
|
|
// RoleViewer is read-only: the dashboard/logs/monitoring surface. It reads
|
|
// the admin module inventories (personas/sessions/plugins/channels/IoT/
|
|
// automations/knowledge docs), the runtime metrics/traces, the backend log
|
|
// tail and the notification feed, plus the authenticated user reads
|
|
// (GET /sessions, /personas, /meta/enums). Everything else is 403 — notably
|
|
// memories, accounts/API keys, the LLM provider stack, audit records, channel
|
|
// message logs, session export and every write (see
|
|
// gateway/registerAdminRoutes for the wired route table).
|
|
RoleViewer Role = "viewer"
|
|
)
|
|
|
|
// Sentinel errors returned by the auth package.
|
|
var (
|
|
// ErrInvalidSecret reports a JWTSecret shorter than the required minimum.
|
|
ErrInvalidSecret = errors.New("auth: JWTSecret must be at least 32 characters")
|
|
// ErrInvalidRole reports an unknown or unparseable role name.
|
|
ErrInvalidRole = errors.New("auth: invalid role")
|
|
// ErrMalformedToken reports a token that is not well-formed.
|
|
ErrMalformedToken = errors.New("auth: malformed token")
|
|
// ErrInvalidSignature reports a token whose HMAC signature does not verify.
|
|
ErrInvalidSignature = errors.New("auth: invalid signature")
|
|
// ErrTokenExpired reports a token whose exp is in the past.
|
|
ErrTokenExpired = errors.New("auth: token expired")
|
|
// ErrUnsupportedAlg reports a token declaring an algorithm other than HS256.
|
|
ErrUnsupportedAlg = errors.New("auth: unsupported algorithm")
|
|
// ErrUnauthorized reports a missing/invalid/unexpired-failed credential.
|
|
ErrUnauthorized = errors.New("auth: unauthorized")
|
|
// ErrForbidden reports a valid credential with insufficient privilege.
|
|
ErrForbidden = errors.New("auth: forbidden")
|
|
// ErrInvalidGrant reports an unknown, revoked, or expired refresh token.
|
|
ErrInvalidGrant = errors.New("auth: invalid refresh grant")
|
|
// ErrNilDB reports a nil *sql.DB passed to a store constructor.
|
|
ErrNilDB = errors.New("auth: nil database")
|
|
)
|
|
|
|
// Package-wide constants. `source` is the log provenance tag used by every
|
|
// logger.WithSource call in this package (no bare logs are emitted).
|
|
const (
|
|
source = "auth"
|
|
minSecretLen = 32
|
|
keyLength = 32
|
|
passwordScheme = "sha256"
|
|
saltLength = 16
|
|
passwordIterations = 100000
|
|
)
|
|
|
|
// ParseRole converts a string into a Role, erroring on unknown values.
|
|
func ParseRole(s string) (Role, error) {
|
|
r := Role(s)
|
|
if !r.Valid() {
|
|
return "", fmt.Errorf("%w: %q", ErrInvalidRole, s)
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
// Valid reports whether r is one of owner, admin, or viewer.
|
|
func (r Role) Valid() bool {
|
|
return r.rank() > 0
|
|
}
|
|
|
|
// rank returns the privilege rank of r. Invalid roles rank below viewer.
|
|
func (r Role) rank() int {
|
|
switch r {
|
|
case RoleOwner:
|
|
return 3
|
|
case RoleAdmin:
|
|
return 2
|
|
case RoleViewer:
|
|
return 1
|
|
default:
|
|
return 0
|
|
}
|
|
}
|
|
|
|
// HasRole reports whether role holds at least the privilege of required, where
|
|
// owner>admin>viewer. Owner satisfies admin and viewer, admin satisfies viewer,
|
|
// and viewer satisfies only viewer.
|
|
func HasRole(role, required Role) bool {
|
|
return role.rank() >= required.rank()
|
|
}
|
|
|
|
// UserSummary is the read-only shape of an account or API key visible to the
|
|
// admin panel (GET /api/v1/admin/users). CreatedAt is nil when the source does
|
|
// not track a creation time (the configured admin account and in-memory keys
|
|
// both omit it).
|
|
type UserSummary struct {
|
|
ID string
|
|
Username string
|
|
Role Role
|
|
CreatedAt *time.Time
|
|
}
|