sky/internal/platform/auth/password_test.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

110 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package auth
import (
"strings"
"testing"
)
func TestHashAndVerify(t *testing.T) {
pw := "CorrectHorseBatteryStaple!2026"
h, err := HashPassword(pw)
if err != nil {
t.Fatalf("哈希失败: %v", err)
}
if !strings.HasPrefix(h, "scrypt$") {
t.Fatalf("哈希格式不符: %s", h[:20])
}
if err := VerifyPassword(h, pw); err != nil {
t.Fatalf("正确密码校验失败: %v", err)
}
}
func TestWrongPasswordRejected(t *testing.T) {
h, _ := HashPassword("real-password-1")
for _, wrong := range []string{
"real-password-2",
"",
"Real-Password-1", // 大小写敏感
"real-password-1 ", // 尾部空格
} {
if err := VerifyPassword(h, wrong); err == nil {
t.Errorf("错误密码 %q 不应通过", wrong)
}
}
}
// 同一密码多次哈希必须产出不同结果(盐随机)。
// 若相同,说明盐没起作用,彩虹表可直接命中。
func TestSaltIsRandom(t *testing.T) {
pw := "same-password"
h1, _ := HashPassword(pw)
h2, _ := HashPassword(pw)
if h1 == h2 {
t.Fatal("两次哈希结果相同,盐未生效")
}
// 但两者都应校验通过
if err := VerifyPassword(h1, pw); err != nil {
t.Fatal("h1 校验失败")
}
if err := VerifyPassword(h2, pw); err != nil {
t.Fatal("h2 校验失败")
}
}
func TestMalformedHashRejected(t *testing.T) {
cases := []string{
"",
"plaintext",
"scrypt$onlytwo",
"bcrypt$abc$def",
"scrypt$nothex$alsonothex",
}
for _, c := range cases {
if err := VerifyPassword(c, "x"); err == nil {
t.Errorf("畸形哈希 %q 不应通过", c)
}
}
}
func TestTokenHashStable(t *testing.T) {
tok := "abcdefghijklmnop"
a := TokenHash(tok)
b := TokenHash(tok)
if a != b {
t.Fatal("同一令牌哈希应稳定")
}
if a == tok {
t.Fatal("哈希不应等于原文")
}
if TokenHash("other") == a {
t.Fatal("不同令牌哈希应不同")
}
}
func TestRandomTokenUnique(t *testing.T) {
seen := map[string]bool{}
for i := 0; i < 200; i++ {
tok, err := RandomToken(32)
if err != nil {
t.Fatalf("生成失败: %v", err)
}
if len(tok) < 40 {
t.Fatalf("令牌过短: %d", len(tok))
}
if seen[tok] {
t.Fatal("出现重复令牌")
}
seen[tok] = true
}
}
// BurnTime 必须真的消耗时间,否则「账号不存在」与「密码错误」
// 的响应时间可区分,账号枚举防护形同虚设。
func TestBurnTimeTakesTime(t *testing.T) {
if dummyHash == "" {
t.Fatal("dummyHash 未初始化")
}
// 只验证它能正常执行不 panic;精确计时在 CI 上不稳定
BurnTime("any-password")
}