forgejo-runner-optimiser/internal/receiver/token_test.go
Martin McCaffery aa3e8cddf9
All checks were successful
ci / build (push) Successful in 28s
Add token-based authentication for receiver
2026-02-11 13:58:42 +01:00

78 lines
2.3 KiB
Go

package receiver
import (
"encoding/hex"
"testing"
)
func TestGenerateScopedToken_Deterministic(t *testing.T) {
token1 := GenerateScopedToken("key", "org", "repo", "wf", "job")
token2 := GenerateScopedToken("key", "org", "repo", "wf", "job")
if token1 != token2 {
t.Errorf("tokens differ: %q vs %q", token1, token2)
}
}
func TestGenerateScopedToken_ScopePinning(t *testing.T) {
base := GenerateScopedToken("key", "org", "repo", "wf", "job")
variants := []struct {
name string
org string
repo string
wf string
job string
}{
{"different org", "other-org", "repo", "wf", "job"},
{"different repo", "org", "other-repo", "wf", "job"},
{"different workflow", "org", "repo", "other-wf", "job"},
{"different job", "org", "repo", "wf", "other-job"},
}
for _, v := range variants {
t.Run(v.name, func(t *testing.T) {
token := GenerateScopedToken("key", v.org, v.repo, v.wf, v.job)
if token == base {
t.Errorf("token for %s should differ from base", v.name)
}
})
}
}
func TestGenerateScopedToken_DifferentKeys(t *testing.T) {
token1 := GenerateScopedToken("key-a", "org", "repo", "wf", "job")
token2 := GenerateScopedToken("key-b", "org", "repo", "wf", "job")
if token1 == token2 {
t.Error("different keys should produce different tokens")
}
}
func TestGenerateScopedToken_ValidHex(t *testing.T) {
token := GenerateScopedToken("key", "org", "repo", "wf", "job")
if len(token) != 64 {
t.Errorf("token length = %d, want 64", len(token))
}
if _, err := hex.DecodeString(token); err != nil {
t.Errorf("token is not valid hex: %v", err)
}
}
func TestValidateScopedToken_Correct(t *testing.T) {
token := GenerateScopedToken("key", "org", "repo", "wf", "job")
if !ValidateScopedToken("key", token, "org", "repo", "wf", "job") {
t.Error("ValidateScopedToken should accept correct token")
}
}
func TestValidateScopedToken_WrongToken(t *testing.T) {
if ValidateScopedToken("key", "deadbeef", "org", "repo", "wf", "job") {
t.Error("ValidateScopedToken should reject wrong token")
}
}
func TestValidateScopedToken_WrongScope(t *testing.T) {
token := GenerateScopedToken("key", "org", "repo", "wf", "job")
if ValidateScopedToken("key", token, "org", "repo", "wf", "other-job") {
t.Error("ValidateScopedToken should reject token for different scope")
}
}