package security import ( "strings" "testing" "time" ) func TestPasswordRoundTrip(t *testing.T) { hash, err := HashPassword("Sup3r-Secret!") if err != nil { t.Fatalf("hash: %v", err) } if !strings.HasPrefix(hash, "$argon2id$") { t.Fatalf("unexpected format: %s", hash) } if !VerifyPassword(hash, "Sup3r-Secret!") { t.Fatal("valid password rejected") } if VerifyPassword(hash, "wrong-password") { t.Fatal("invalid password accepted") } if VerifyPassword("garbage", "x") { t.Fatal("malformed hash accepted") } if _, err := HashPassword("short"); err == nil { t.Fatal("short password accepted") } } func TestTOTPKnownVector(t *testing.T) { // RFC 6238 test vector: SHA1 secret, T=59s, 8 digits = 94287082. secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" code, err := TOTPCode(secret, 1) if err != nil { t.Fatalf("code: %v", err) } if code != "287082" { t.Fatalf("got %s, want 287082", code) } now := time.Unix(59, 0) if !VerifyTOTP(secret, "287082", now) { t.Fatal("valid code rejected") } if VerifyTOTP(secret, "287083", now) { t.Fatal("invalid code accepted") } // One step of drift must still be accepted. if !VerifyTOTP(secret, "287082", now.Add(30*time.Second)) { t.Fatal("drift window not applied") } if VerifyTOTP(secret, "287082", now.Add(5*time.Minute)) { t.Fatal("stale code accepted") } } func TestTokenHashing(t *testing.T) { plain, hashed, err := Token(32) if err != nil { t.Fatal(err) } if len(plain) < 40 || hashed == plain { t.Fatalf("bad token pair: %q %q", plain, hashed) } if HashToken(plain) != hashed { t.Fatal("hash mismatch") } if HashToken(plain+"x") == hashed { t.Fatal("hash collision") } } func TestRecoveryCodes(t *testing.T) { codes := RecoveryCodes(8) if len(codes) != 8 { t.Fatalf("want 8 codes, got %d", len(codes)) } seen := map[string]bool{} for _, c := range codes { if len(c) != 11 || !strings.Contains(c, "-") { t.Fatalf("malformed code %q", c) } if seen[c] { t.Fatalf("duplicate code %q", c) } seen[c] = true } } func TestOTPAuthURL(t *testing.T) { u := OTPAuthURL("MiaoPanel", "admin", "ABC123") if !strings.HasPrefix(u, "otpauth://totp/MiaoPanel:admin?secret=ABC123") { t.Fatalf("unexpected url: %s", u) } }