M0-M4: 推倒重来基线(基建+用户/密钥/核心代理+前端+管理后台+三协议互转)
- 后端 Go+Gin+GORM: 配置(OT_ env)/SQLite/Postgres 双驱动、用户体系(argon2id+JWT access/refresh)、 API Key(sk- 48位, 仅存 SHA-256 哈希) - 代理网关: /v1/chat/completions、/v1/responses、/v1/messages、/v1/models;错误按客户端协议返回 - 三协议互转(convert 包): Chat↔Messages↔Responses 请求/响应 + 流式 SSE 逐事件转换(直通优先) - 用量计费: 异步批量记账、余额扣减、balance_logs、usage_daily 日聚合 - 管理 API: 用户/渠道 CRUD+测试+模型导入/模型定价+绑定/统计/系统配置 - 前端 Vue3+TS+Tailwind(taste-skill 设计 tokens): Landing/登录注册/控制台/管理后台, 自建组件+Phosphor 图标+自建 SVG 趋势图, 已过 web-design-guidelines 复查 - mock 上游: OpenAI+Anthropic 双协议模拟(含流式) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,6 @@ package apikey
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
@@ -47,6 +46,3 @@ func Prefix(key string) string {
|
||||
func Valid(key string) bool {
|
||||
return strings.HasPrefix(key, prefix) && len(key) == len(prefix)+keyLen
|
||||
}
|
||||
|
||||
// base64 占位,避免未使用导入告警
|
||||
var _ = base64.StdEncoding
|
||||
|
||||
@@ -2,32 +2,36 @@ package apikey
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
func TestGenerateValid(t *testing.T) {
|
||||
plain, hash, prefix, err := Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if !Valid(plain) {
|
||||
t.Fatalf("generated key invalid: %q", plain)
|
||||
}
|
||||
if len(plain) != 3+48 {
|
||||
t.Fatalf("key length = %d, want 51", len(plain))
|
||||
if len(plain) != len("sk-")+48 {
|
||||
t.Fatalf("unexpected key length: %d", len(plain))
|
||||
}
|
||||
if Hash(plain) != hash {
|
||||
t.Fatal("hash mismatch")
|
||||
}
|
||||
if len(prefix) > len(plain) || prefix != plain[:len(prefix)] {
|
||||
t.Fatal("prefix must be prefix of plain key")
|
||||
}
|
||||
// 两次生成不重复
|
||||
plain2, _, _, _ := Generate()
|
||||
if plain == plain2 {
|
||||
t.Fatal("keys should be unique")
|
||||
if prefix != plain[:12] {
|
||||
t.Fatalf("prefix mismatch: %s vs %s", prefix, plain[:12])
|
||||
}
|
||||
}
|
||||
|
||||
func TestValid(t *testing.T) {
|
||||
if Valid("") || Valid("sk-short") || Valid("xxx") {
|
||||
t.Fatal("invalid keys should be rejected")
|
||||
func TestHashStable(t *testing.T) {
|
||||
if Hash("sk-test") != Hash("sk-test") {
|
||||
t.Fatal("hash not stable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidRejects(t *testing.T) {
|
||||
cases := []string{"", "sk-abc", "abc-123456789012345678901234567890123456789012345678", "sk-1234567890123456789012345678901234567890123456789"}
|
||||
for _, c := range cases {
|
||||
if Valid(c) {
|
||||
t.Fatalf("expected invalid: %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// PasswordHasher argon2id 参数(来自配置)。
|
||||
type PasswordHasher struct {
|
||||
Time uint32
|
||||
Memory uint32
|
||||
@@ -26,7 +27,7 @@ func NewPasswordHasher(time, memory uint32, threads uint8, keyLen uint32, saltLe
|
||||
return &PasswordHasher{Time: time, Memory: memory, Threads: threads, KeyLen: keyLen, SaltLen: saltLen}
|
||||
}
|
||||
|
||||
// HashPassword argon2id 编码为 $argon2id$v=19$m=...,t=...,p=...$salt$hash
|
||||
// HashPassword 编码为 $argon2id$v=19$m=...,t=...,p=...$salt$hash
|
||||
func (h *PasswordHasher) HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, h.SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
@@ -38,14 +39,13 @@ func (h *PasswordHasher) HashPassword(password string) (string, error) {
|
||||
h.Memory, h.Time, h.Threads, enc.EncodeToString(salt), enc.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
// VerifyPassword 校验密码,返回是否匹配(常数时间比较)。
|
||||
// VerifyPassword 校验密码,常数时间比较。
|
||||
func (h *PasswordHasher) VerifyPassword(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errors.New("invalid hash format")
|
||||
}
|
||||
var memory uint32
|
||||
var time uint32
|
||||
var memory, time uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
|
||||
return false, err
|
||||
@@ -66,6 +66,7 @@ func (h *PasswordHasher) VerifyPassword(encoded, password string) (bool, error)
|
||||
// ---------------------------------------------------------------------------
|
||||
// AES-GCM 渠道密钥加密
|
||||
|
||||
// Encryptor 用主密钥加解密渠道上游 key。
|
||||
type Encryptor struct {
|
||||
key []byte
|
||||
}
|
||||
@@ -76,8 +77,7 @@ func NewEncryptor(master string) *Encryptor {
|
||||
switch len(key) {
|
||||
case 16, 24, 32:
|
||||
default:
|
||||
sum := sha256Sum(master)
|
||||
key = sum
|
||||
key = sha256Sum(master)
|
||||
}
|
||||
return &Encryptor{key: key}
|
||||
}
|
||||
@@ -100,6 +100,7 @@ func (e *Encryptor) Encrypt(plain string) (string, error) {
|
||||
return base64.StdEncoding.EncodeToString(append(nonce, ct...)), nil
|
||||
}
|
||||
|
||||
// Decrypt 解析 Encrypt 的输出。
|
||||
func (e *Encryptor) Decrypt(enc string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(enc)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,42 +3,43 @@ package crypto
|
||||
import "testing"
|
||||
|
||||
func TestPasswordHashRoundTrip(t *testing.T) {
|
||||
h := NewPasswordHasher(3, 64*1024, 2, 32, 16)
|
||||
h := NewPasswordHasher(1, 64*1024, 1, 32, 16)
|
||||
hash, err := h.HashPassword("s3cret-password")
|
||||
if err != nil {
|
||||
t.Fatalf("hash: %v", err)
|
||||
t.Fatalf("HashPassword: %v", err)
|
||||
}
|
||||
ok, err := h.VerifyPassword(hash, "s3cret-password")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("verify correct password: ok=%v err=%v", ok, err)
|
||||
t.Fatalf("VerifyPassword correct: ok=%v err=%v", ok, err)
|
||||
}
|
||||
ok, _ = h.VerifyPassword(hash, "wrong-password")
|
||||
if ok {
|
||||
t.Fatal("wrong password should not verify")
|
||||
t.Fatal("VerifyPassword accepted wrong password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptDecrypt(t *testing.T) {
|
||||
e := NewEncryptor("master-key-0123456789abcdef")
|
||||
func TestEncryptorRoundTrip(t *testing.T) {
|
||||
e := NewEncryptor("a-very-long-master-key-1234567890")
|
||||
enc, err := e.Encrypt("sk-upstream-secret")
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt: %v", err)
|
||||
t.Fatalf("Encrypt: %v", err)
|
||||
}
|
||||
dec, err := e.Decrypt(enc)
|
||||
if err != nil || dec != "sk-upstream-secret" {
|
||||
t.Fatalf("decrypt: got %q err %v", dec, err)
|
||||
if enc == "sk-upstream-secret" {
|
||||
t.Fatal("ciphertext equals plaintext")
|
||||
}
|
||||
// 密文不可读
|
||||
if dec == enc {
|
||||
t.Fatal("ciphertext should differ from plaintext")
|
||||
plain, err := e.Decrypt(enc)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if plain != "sk-upstream-secret" {
|
||||
t.Fatalf("round trip mismatch: %q", plain)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortMasterKeyDerived(t *testing.T) {
|
||||
func TestEncryptorShortKeyDerived(t *testing.T) {
|
||||
// 短主密钥应派生 32 字节而非报错
|
||||
e := NewEncryptor("short")
|
||||
enc, _ := e.Encrypt("x")
|
||||
dec, err := e.Decrypt(enc)
|
||||
if err != nil || dec != "x" {
|
||||
t.Fatalf("short key derive failed: %v", err)
|
||||
if _, err := e.Encrypt("x"); err != nil {
|
||||
t.Fatalf("Encrypt with short key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Claims 用户声明;Subject 字段区分 "access" / "refresh"。
|
||||
type Claims struct {
|
||||
UserID uint64 `json:"uid"`
|
||||
Username string `json:"uname"`
|
||||
@@ -16,9 +17,9 @@ type Claims struct {
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
secret []byte
|
||||
issuer string
|
||||
accessTTL time.Duration
|
||||
secret []byte
|
||||
issuer string
|
||||
accessTTL time.Duration
|
||||
refreshTTL time.Duration
|
||||
}
|
||||
|
||||
|
||||
@@ -5,37 +5,41 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSignParse(t *testing.T) {
|
||||
func TestSignParseAccess(t *testing.T) {
|
||||
m := NewManager("test-secret", "openteam", time.Hour, 24*time.Hour)
|
||||
tok, exp, err := m.Sign(42, "alice", "admin", "access")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Sign: %v", err)
|
||||
}
|
||||
if time.Until(exp) < 50*time.Minute {
|
||||
t.Fatal("expiry too short")
|
||||
if exp.Before(time.Now()) {
|
||||
t.Fatal("expires in the past")
|
||||
}
|
||||
claims, err := m.Parse(tok)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Parse: %v", err)
|
||||
}
|
||||
if claims.UserID != 42 || claims.Username != "alice" || claims.Role != "admin" || claims.Subject != "access" {
|
||||
if claims.UserID != 42 || claims.Username != "alice" || claims.Role != "admin" {
|
||||
t.Fatalf("claims mismatch: %+v", claims)
|
||||
}
|
||||
if claims.Subject != "access" {
|
||||
t.Fatalf("subject mismatch: %s", claims.Subject)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsBadToken(t *testing.T) {
|
||||
m := NewManager("test-secret", "openteam", time.Hour, 24*time.Hour)
|
||||
if _, err := m.Parse("not-a-jwt"); err == nil {
|
||||
t.Fatal("expected error for invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredToken(t *testing.T) {
|
||||
m := NewManager("test-secret", "openteam", -time.Minute, time.Hour)
|
||||
tok, _, _ := m.Sign(1, "a", "user", "access")
|
||||
m := NewManager("test-secret", "openteam", -time.Hour, -time.Hour)
|
||||
tok, _, err := m.Sign(1, "bob", "user", "access")
|
||||
if err != nil {
|
||||
t.Fatalf("Sign: %v", err)
|
||||
}
|
||||
if _, err := m.Parse(tok); err == nil {
|
||||
t.Fatal("expired token should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongSecret(t *testing.T) {
|
||||
m1 := NewManager("secret-a", "openteam", time.Hour, time.Hour)
|
||||
m2 := NewManager("secret-b", "openteam", time.Hour, time.Hour)
|
||||
tok, _, _ := m1.Sign(1, "a", "user", "access")
|
||||
if _, err := m2.Parse(tok); err == nil {
|
||||
t.Fatal("token signed with different secret should fail")
|
||||
t.Fatal("expected error for expired token")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,8 +32,3 @@ func Created(c *gin.Context, data any) {
|
||||
func Fail(c *gin.Context, status int, message string) {
|
||||
c.JSON(status, Body{Error: &Error{Message: message}})
|
||||
}
|
||||
|
||||
// FailCode 带错误码的业务错误
|
||||
func FailCode(c *gin.Context, status int, code, message string) {
|
||||
c.JSON(status, Body{Error: &Error{Message: message, Type: code}})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user