Files
pangolin/server/internal/admin/auth_test.go
T
wangjia 6e99e32285 feat(admin): 管理端最小后台(独立监听 + 白名单 + 2FA)tsk_SCMtcGF4F434
实现「一个二进制三个监听」中的管理端:

- 独立监听 ADMIN_LISTEN(默认 127.0.0.1:9443,FromEnv 拒绝 0.0.0.0/:: 等公网绑定)
- 中间件链:mw_ipallow(CIDR 白名单,仅信任 RemoteAddr,默认内网段)→
  mw_session(HttpOnly+Secure+SameSite=Strict cookie,Redis 30min 滑动 TTL)
- 登录双因素:argon2id 密码 + RFC6238 TOTP;失败限流与临时锁定;
  TOTP 密钥 AES-GCM 加密入库;migration 000008 增补 admins 表;
  首个管理员由 cmd/adminctl create 创建(终端输出 otpauth URI/Secret)
- 功能三块(html/template + embed 静态资源,原生 JS 二次确认):
  1. 码批次:表单生成→明文仅在本次 CSV 下载出现(不落盘/不入日志);
     批次列表 + 整批作废(复用 #3 codes,新增 Store.ListBatches/VoidBatch)
  2. 节点操作:列表 + 近期 node_events;replace 经 #14 ProvisionService、
     draining/up 经 #5 Lifecycle(二者未就绪→注入 stub,UI 置灰);二次确认 + CSRF
  3. audit_log 查看:actor/action/target/时间范围过滤分页;同页查 node_events
- 所有写操作写 audit_log(actor=用户名,meta 不含明文);管理端仅记安全事件
  (登录失败/锁定/白名单拦截),不记常规访问日志
- internal/totp 复用包(与 doc/05 用户中心 2FA 同算法,纯标准库)

测试:totp RFC6238 向量、argon2/AES 往返、白名单放行/拦截、会话滑动过期、
登录成功/密码错/TOTP 错/未知用户/锁定、批次 CSV 含明文且 audit 不泄露、
作废/节点操作的二次确认与 CSRF 缺失被拒、mock 断言 service 调用参数、审计过滤。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 14:49:32 +08:00

117 lines
3.4 KiB
Go

package admin
import (
"context"
"crypto/rand"
"testing"
"time"
"github.com/wangjia/pangolin/server/internal/totp"
)
// newTestAdmin seeds an active admin and returns its TOTP secret.
func newTestAdmin(t *testing.T, store *fakeStore, key []byte, username, password string) string {
t.Helper()
hash, err := HashPassword(password)
if err != nil {
t.Fatal(err)
}
secret, err := totp.GenerateSecret()
if err != nil {
t.Fatal(err)
}
enc, err := EncryptSecret(key, secret)
if err != nil {
t.Fatal(err)
}
store.admins[username] = &Admin{ID: 1, Username: username, PwHash: hash, TOTPSecretEnc: enc, Status: "active"}
return secret
}
func newTestAuth(t *testing.T) (*Authenticator, *fakeStore, []byte) {
t.Helper()
rdb, _ := newTestRedis(t)
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
store := newFakeStore()
cfg := &Config{SecretKey: key, LoginFailMax: 3, LoginLockDuration: time.Minute, SessionTTL: 30 * time.Minute}
sessions := NewSessionStore(rdb, cfg.SessionTTL)
sec := NewSecurityLog(store, nil)
return NewAuthenticator(store, sessions, rdb, cfg, sec), store, key
}
func TestLogin_Success(t *testing.T) {
auth, store, key := newTestAuth(t)
secret := newTestAdmin(t, store, key, "alice", "s3cret-pass")
code, _ := totp.Code(secret, time.Now().UTC())
sid, sess, err := auth.Login(context.Background(), "alice", "s3cret-pass", code, "127.0.0.1")
if err != nil {
t.Fatalf("login failed: %v", err)
}
if sid == "" || sess == nil {
t.Fatal("no session returned")
}
if _, ok := store.lastLogin[1]; !ok {
t.Error("last login not recorded")
}
if len(store.auditFor("admin_login_ok")) != 1 {
t.Error("successful login not audited")
}
}
func TestLogin_WrongPassword(t *testing.T) {
auth, store, key := newTestAuth(t)
secret := newTestAdmin(t, store, key, "alice", "s3cret-pass")
code, _ := totp.Code(secret, time.Now().UTC())
_, _, err := auth.Login(context.Background(), "alice", "WRONG", code, "127.0.0.1")
if err != ErrInvalidCredentials {
t.Fatalf("err = %v; want ErrInvalidCredentials", err)
}
if len(store.auditFor("admin_login_fail")) != 1 {
t.Error("failed login not audited")
}
}
func TestLogin_WrongTOTP(t *testing.T) {
auth, store, key := newTestAuth(t)
_ = newTestAdmin(t, store, key, "alice", "s3cret-pass")
_, _, err := auth.Login(context.Background(), "alice", "s3cret-pass", "000000", "127.0.0.1")
if err != ErrInvalidCredentials {
t.Fatalf("err = %v; want ErrInvalidCredentials", err)
}
}
func TestLogin_UnknownUser(t *testing.T) {
auth, _, _ := newTestAuth(t)
_, _, err := auth.Login(context.Background(), "ghost", "x", "000000", "127.0.0.1")
if err != ErrInvalidCredentials {
t.Fatalf("err = %v; want ErrInvalidCredentials", err)
}
}
func TestLogin_LockoutAfterFailures(t *testing.T) {
auth, store, key := newTestAuth(t)
secret := newTestAdmin(t, store, key, "alice", "s3cret-pass")
ctx := context.Background()
// 3 failures hit the cap.
for i := 0; i < 3; i++ {
if _, _, err := auth.Login(ctx, "alice", "WRONG", "000000", "127.0.0.1"); err != ErrInvalidCredentials {
t.Fatalf("attempt %d err = %v", i, err)
}
}
// Now even a correct credential is locked out.
code, _ := totp.Code(secret, time.Now().UTC())
if _, _, err := auth.Login(ctx, "alice", "s3cret-pass", code, "127.0.0.1"); err != ErrLockedOut {
t.Fatalf("err = %v; want ErrLockedOut", err)
}
if len(store.auditFor("admin_login_locked")) == 0 {
t.Error("lockout not audited")
}
}