56 lines
1.6 KiB
Go
56 lines
1.6 KiB
Go
// Copyright (c) 2026 Petr Balvín <opensource@petrbalvin.org> (https://petrbalvin.org)
|
|||
|
|
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||
|
|
|
||
|
|
package preview
|
||
|
|
|
||
|
|
import (
|
||
|
|
"strings"
|
||
|
|
"testing"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestTokenRoundTrip(t *testing.T) {
|
||
|
|
now := time.Now()
|
||
|
|
secret := strings.Repeat("k", 64)
|
||
|
|
token := Token("hello", secret, now)
|
||
|
|
if token == "" {
|
||
|
|
t.Fatal("Token returned nothing for a configured key")
|
||
|
|
}
|
||
|
|
if !Valid(token, "hello", secret, now) {
|
||
|
|
t.Fatal("a fresh token was rejected")
|
||
|
|
}
|
||
|
|
if Valid(token, "hello", secret, now.Add(TTL+time.Minute)) {
|
||
|
|
t.Fatal("an expired token was accepted")
|
||
|
|
}
|
||
|
|
// The link carries no start time: a reviewer whose clock sits a little
|
||
|
|
// behind the server's must still be able to open it.
|
||
|
|
if !Valid(token, "hello", secret, now.Add(-time.Hour)) {
|
||
|
|
t.Fatal("a token was rejected shortly before its mint time")
|
||
|
|
}
|
||
|
|
if Valid(token, "other", secret, now) {
|
||
|
|
t.Fatal("a token for another slug was accepted")
|
||
|
|
}
|
||
|
|
if Valid(token, "hello", strings.Repeat("j", 64), now) {
|
||
|
|
t.Fatal("a token was accepted under another key")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTokenRequiresAKeyAndSlug(t *testing.T) {
|
||
|
|
now := time.Now()
|
||
|
|
if Token("", "secret", now) != "" {
|
||
|
|
t.Fatal("a token was minted for an empty slug")
|
||
|
|
}
|
||
|
|
if Token("hello", "", now) != "" {
|
||
|
|
t.Fatal("a token was minted without a session key")
|
||
|
|
}
|
||
|
|
if Valid("", "hello", "secret", now) {
|
||
|
|
t.Fatal("an empty token was accepted")
|
||
|
|
}
|
||
|
|
if Valid("garbage", "hello", "secret", now) {
|
||
|
|
t.Fatal("a malformed token was accepted")
|
||
|
|
}
|
||
|
|
if Valid("x-notanumber", "hello", "secret", now) {
|
||
|
|
t.Fatal("a token with an unparsable stamp was accepted")
|
||
|
|
}
|
||
|
|
}
|