package notify import ( "strings" "testing" ) func TestUnsubscribeTokenRoundtrip(t *testing.T) { t.Setenv("AUTH_SECRET", "unsubscribe-test-secret") tok := UnsubscribeToken("0123456789abcdef0123456789abcdef") id, ok := ParseUnsubscribeToken(tok) if !ok || id != "0123456789abcdef0123456789abcdef" { t.Fatalf("roundtrip = %q, %v", id, ok) } // Stable: every mail to the same user carries the same link. if UnsubscribeToken("0123456789abcdef0123456789abcdef") != tok { t.Fatal("token must be stable across issuances") } } func TestUnsubscribeTokenRejectsTampering(t *testing.T) { t.Setenv("AUTH_SECRET", "unsubscribe-test-secret") const id = "0123456789abcdef0123456789abcdef" tok := UnsubscribeToken(id) _, mac, _ := strings.Cut(tok, ".") // A token minted under a different secret must not verify here. t.Setenv("AUTH_SECRET", "a-different-secret") foreign := UnsubscribeToken(id) t.Setenv("AUTH_SECRET", "unsubscribe-test-secret") cases := []struct{ name, token string }{ {"swapped id", "ffffffffffffffffffffffffffffffff." + mac}, {"flipped mac", id + "." + strings.Repeat("0", 63) + "1"}, {"truncated mac", tok[:len(tok)-1]}, {"no separator", strings.ReplaceAll(tok, ".", "")}, {"empty id", "." + mac}, {"empty mac", id + "."}, {"empty token", ""}, {"foreign secret", foreign}, } for _, c := range cases { if _, ok := ParseUnsubscribeToken(c.token); ok { t.Errorf("%s accepted", c.name) } } }