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>
This commit is contained in:
wangjia
2026-06-13 14:49:32 +08:00
parent 787151245e
commit 6e99e32285
36 changed files with 3695 additions and 2 deletions
+132
View File
@@ -0,0 +1,132 @@
// Package totp implements RFC 6238 time-based one-time passwords (TOTP) on
// top of RFC 4226 HOTP, using HMAC-SHA1, 6 digits, and a 30-second step.
//
// It is deliberately dependency-free (standard library only) so it can be
// shared between the admin backend two-factor login and the user-center 2FA
// (doc/05) without pulling in a third-party OTP package.
package totp
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"encoding/base32"
"encoding/binary"
"fmt"
"net/url"
"strings"
"time"
)
const (
// Digits is the number of decimal digits in a generated code.
Digits = 6
// Period is the time step length.
Period = 30 * time.Second
// secretBytes is the length of a freshly generated shared secret. 20 bytes
// (160 bits) matches the RFC 4226 recommendation and the SHA-1 block size.
secretBytes = 20
)
// b32 is the no-padding, upper-case Base32 encoding used for OTP secrets
// (the alphabet authenticator apps expect).
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
// GenerateSecret returns a new cryptographically random Base32-encoded secret.
func GenerateSecret() (string, error) {
buf := make([]byte, secretBytes)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("totp.GenerateSecret: %w", err)
}
return b32.EncodeToString(buf), nil
}
// Code returns the TOTP code for the given Base32 secret at time t.
func Code(secret string, t time.Time) (string, error) {
key, err := decodeSecret(secret)
if err != nil {
return "", err
}
counter := uint64(t.UTC().Unix()) / uint64(Period.Seconds())
return hotp(key, counter), nil
}
// Validate reports whether code is a valid TOTP for secret at time t, allowing
// ±skew steps of clock drift (skew=1 accepts the previous, current, and next
// 30-second windows). Comparison is constant-time.
func Validate(secret, code string, t time.Time, skew int) bool {
key, err := decodeSecret(secret)
if err != nil {
return false
}
code = strings.TrimSpace(code)
if len(code) != Digits {
return false
}
if skew < 0 {
skew = 0
}
base := int64(uint64(t.UTC().Unix()) / uint64(Period.Seconds()))
for d := -skew; d <= skew; d++ {
c := base + int64(d)
if c < 0 {
continue
}
want := hotp(key, uint64(c))
if subtle.ConstantTimeCompare([]byte(want), []byte(code)) == 1 {
return true
}
}
return false
}
// ProvisioningURI builds an otpauth:// URI suitable for rendering as a QR code
// or pasting into an authenticator app.
func ProvisioningURI(secret, account, issuer string) string {
label := url.PathEscape(issuer + ":" + account)
q := url.Values{}
q.Set("secret", secret)
q.Set("issuer", issuer)
q.Set("algorithm", "SHA1")
q.Set("digits", fmt.Sprintf("%d", Digits))
q.Set("period", fmt.Sprintf("%d", int(Period.Seconds())))
return "otpauth://totp/" + label + "?" + q.Encode()
}
// decodeSecret accepts a Base32 secret with or without padding/whitespace.
func decodeSecret(secret string) ([]byte, error) {
s := strings.ToUpper(strings.TrimSpace(secret))
s = strings.ReplaceAll(s, " ", "")
s = strings.TrimRight(s, "=")
key, err := b32.DecodeString(s)
if err != nil {
return nil, fmt.Errorf("totp: invalid secret: %w", err)
}
if len(key) == 0 {
return nil, fmt.Errorf("totp: empty secret")
}
return key, nil
}
// hotp implements RFC 4226 HOTP with dynamic truncation.
func hotp(key []byte, counter uint64) string {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], counter)
mac := hmac.New(sha1.New, key)
mac.Write(buf[:])
sum := mac.Sum(nil)
offset := sum[len(sum)-1] & 0x0f
value := (uint32(sum[offset]&0x7f) << 24) |
(uint32(sum[offset+1]) << 16) |
(uint32(sum[offset+2]) << 8) |
uint32(sum[offset+3])
mod := uint32(1)
for i := 0; i < Digits; i++ {
mod *= 10
}
return fmt.Sprintf("%0*d", Digits, value%mod)
}
+94
View File
@@ -0,0 +1,94 @@
package totp
import (
"testing"
"time"
)
// rfc6238Secret is the Base32 encoding of the ASCII seed "12345678901234567890"
// from RFC 6238 Appendix B (the SHA-1 test vector).
const rfc6238Secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
func TestCode_RFC6238Vectors(t *testing.T) {
// 8-digit reference values from RFC 6238 truncated to our 6 digits.
cases := []struct {
unix int64
want string
}{
{59, "287082"},
{1111111109, "081804"},
{1111111111, "050471"},
{1234567890, "005924"},
{2000000000, "279037"},
{20000000000, "353130"},
}
for _, c := range cases {
got, err := Code(rfc6238Secret, time.Unix(c.unix, 0).UTC())
if err != nil {
t.Fatalf("Code(%d): %v", c.unix, err)
}
if got != c.want {
t.Errorf("Code(%d) = %s; want %s", c.unix, got, c.want)
}
}
}
func TestValidate_SkewWindow(t *testing.T) {
secret, err := GenerateSecret()
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
code, err := Code(secret, now)
if err != nil {
t.Fatal(err)
}
if !Validate(secret, code, now, 1) {
t.Error("current code rejected")
}
// Previous window must be accepted with skew=1.
if !Validate(secret, code, now.Add(Period), 1) {
t.Error("code from previous step rejected with skew=1")
}
// Two steps away must be rejected.
if Validate(secret, code, now.Add(2*Period+time.Second), 1) {
t.Error("stale code accepted outside skew window")
}
// Wrong code rejected.
if Validate(secret, "000000", now, 1) && code != "000000" {
t.Error("validate accepted obviously wrong code")
}
}
func TestValidate_BadInput(t *testing.T) {
secret, _ := GenerateSecret()
now := time.Now().UTC()
if Validate(secret, "12345", now, 1) { // too short
t.Error("accepted 5-digit code")
}
if Validate("not-base32!!", "123456", now, 1) {
t.Error("accepted invalid secret")
}
}
func TestProvisioningURI(t *testing.T) {
uri := ProvisioningURI(rfc6238Secret, "admin", "Pangolin")
if uri == "" {
t.Fatal("empty URI")
}
for _, sub := range []string{"otpauth://totp/", "secret=" + rfc6238Secret, "issuer=Pangolin"} {
if !contains(uri, sub) {
t.Errorf("URI %q missing %q", uri, sub)
}
}
}
func contains(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}