仰望星辰工作室

miaopanel

miaopanel/ internal/security/security_test.go 2.2 KB · 95 行 原始文件
1package security
2
3import (
4 "strings"
5 "testing"
6 "time"
7)
8
9func TestPasswordRoundTrip(t *testing.T) {
10 hash, err := HashPassword("Sup3r-Secret!")
11 if err != nil {
12 t.Fatalf("hash: %v", err)
13 }
14 if !strings.HasPrefix(hash, "$argon2id$") {
15 t.Fatalf("unexpected format: %s", hash)
16 }
17 if !VerifyPassword(hash, "Sup3r-Secret!") {
18 t.Fatal("valid password rejected")
19 }
20 if VerifyPassword(hash, "wrong-password") {
21 t.Fatal("invalid password accepted")
22 }
23 if VerifyPassword("garbage", "x") {
24 t.Fatal("malformed hash accepted")
25 }
26 if _, err := HashPassword("short"); err == nil {
27 t.Fatal("short password accepted")
28 }
29}
30
31func TestTOTPKnownVector(t *testing.T) {
32 // RFC 6238 test vector: SHA1 secret, T=59s, 8 digits = 94287082.
33 secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
34 code, err := TOTPCode(secret, 1)
35 if err != nil {
36 t.Fatalf("code: %v", err)
37 }
38 if code != "287082" {
39 t.Fatalf("got %s, want 287082", code)
40 }
41 now := time.Unix(59, 0)
42 if !VerifyTOTP(secret, "287082", now) {
43 t.Fatal("valid code rejected")
44 }
45 if VerifyTOTP(secret, "287083", now) {
46 t.Fatal("invalid code accepted")
47 }
48 // One step of drift must still be accepted.
49 if !VerifyTOTP(secret, "287082", now.Add(30*time.Second)) {
50 t.Fatal("drift window not applied")
51 }
52 if VerifyTOTP(secret, "287082", now.Add(5*time.Minute)) {
53 t.Fatal("stale code accepted")
54 }
55}
56
57func TestTokenHashing(t *testing.T) {
58 plain, hashed, err := Token(32)
59 if err != nil {
60 t.Fatal(err)
61 }
62 if len(plain) < 40 || hashed == plain {
63 t.Fatalf("bad token pair: %q %q", plain, hashed)
64 }
65 if HashToken(plain) != hashed {
66 t.Fatal("hash mismatch")
67 }
68 if HashToken(plain+"x") == hashed {
69 t.Fatal("hash collision")
70 }
71}
72
73func TestRecoveryCodes(t *testing.T) {
74 codes := RecoveryCodes(8)
75 if len(codes) != 8 {
76 t.Fatalf("want 8 codes, got %d", len(codes))
77 }
78 seen := map[string]bool{}
79 for _, c := range codes {
80 if len(c) != 11 || !strings.Contains(c, "-") {
81 t.Fatalf("malformed code %q", c)
82 }
83 if seen[c] {
84 t.Fatalf("duplicate code %q", c)
85 }
86 seen[c] = true
87 }
88}
89
90func TestOTPAuthURL(t *testing.T) {
91 u := OTPAuthURL("MiaoPanel", "admin", "ABC123")
92 if !strings.HasPrefix(u, "otpauth://totp/MiaoPanel:admin?secret=ABC123") {
93 t.Fatalf("unexpected url: %s", u)
94 }
95}