feat: API Key 前缀改为 sk-ot
- apikey 包 prefix 常量 sk- → sk-ot(生成/校验/展示前缀统一驱动) - 鉴权错误提示同步更新为 sk-ot 格式 - 测试断言改用常量,避免硬编码长度 - 前端 curl 示例与 README/PLANNING 文档同步
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// Package apikey 生成与管理 API Key:sk- + 48 位 base62 随机串。
|
||||
// Package apikey 生成与管理 API Key:sk-ot + 48 位 base62 随机串。
|
||||
// 库中仅存 SHA-256 哈希与展示前缀(PLANNING §4.3.3)。
|
||||
package apikey
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
const (
|
||||
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
keyLen = 48
|
||||
prefix = "sk-"
|
||||
prefix = "sk-ot"
|
||||
)
|
||||
|
||||
// Generate 生成明文 key(仅创建时展示一次)与哈希、前缀。
|
||||
@@ -34,7 +34,7 @@ func Hash(key string) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Prefix 展示前缀:sk-aB3cD5…(前 12 字符)
|
||||
// Prefix 展示前缀:sk-ot…(前 12 字符)
|
||||
func Prefix(key string) string {
|
||||
if len(key) <= 12 {
|
||||
return key
|
||||
|
||||
@@ -3,32 +3,35 @@ package apikey
|
||||
import "testing"
|
||||
|
||||
func TestGenerateValid(t *testing.T) {
|
||||
plain, hash, prefix, err := Generate()
|
||||
plain, hash, keyPrefix, err := Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if !Valid(plain) {
|
||||
t.Fatalf("generated key invalid: %q", plain)
|
||||
}
|
||||
if len(plain) != len("sk-")+48 {
|
||||
if len(plain) != len(prefix)+keyLen {
|
||||
t.Fatalf("unexpected key length: %d", len(plain))
|
||||
}
|
||||
if keyPrefix != plain[:12] {
|
||||
t.Fatalf("prefix mismatch: %s vs %s", keyPrefix, plain[:12])
|
||||
}
|
||||
if Hash(plain) != hash {
|
||||
t.Fatal("hash mismatch")
|
||||
}
|
||||
if prefix != plain[:12] {
|
||||
t.Fatalf("prefix mismatch: %s vs %s", prefix, plain[:12])
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashStable(t *testing.T) {
|
||||
if Hash("sk-test") != Hash("sk-test") {
|
||||
if Hash("sk-ot-test") != Hash("sk-ot-test") {
|
||||
t.Fatal("hash not stable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidRejects(t *testing.T) {
|
||||
cases := []string{"", "sk-abc", "abc-123456789012345678901234567890123456789012345678", "sk-1234567890123456789012345678901234567890123456789"}
|
||||
tooShort := prefix + "abc"
|
||||
tooLong := prefix + "1234567890123456789012345678901234567890123456789"
|
||||
wrongPrefix := "abc-ot123456789012345678901234567890123456789012345678"
|
||||
cases := []string{"", tooShort, wrongPrefix, tooLong}
|
||||
for _, c := range cases {
|
||||
if Valid(c) {
|
||||
t.Fatalf("expected invalid: %q", c)
|
||||
|
||||
Reference in New Issue
Block a user