Files
gitea-mcp-forward-auth/internal/auth/auth_test.go
T
torben 1acdbb5519
Build and Test / verify (push) Failing after 1m22s
Update build configuration and improve token handling
- Change CI container image to debian:trixie-slim and set GOPROXY.
- Update Go version to 1.26 in Dockerfile and go.mod.
- Refactor token validation to use SHA-256 hashes instead of plain tokens.
- Add network policy to restrict access to the service.
- Enhance README with new configuration details and usage examples.
- Add tests for new token hash validation logic.
2026-07-11 22:08:56 +02:00

105 lines
2.5 KiB
Go

package auth
import (
"crypto/sha256"
"fmt"
"testing"
)
func hashHex(token string) string {
sum := sha256.Sum256([]byte(token))
return fmt.Sprintf("%x", sum[:])
}
func TestValidator_IsValid(t *testing.T) {
t.Parallel()
validator, err := NewValidator([]string{hashHex("token-one"), hashHex("token-two"), hashHex("token-three")})
if err != nil {
t.Fatalf("NewValidator() error = %v", err)
}
tests := []struct {
name string
token string
want bool
}{
{name: "valid token one", token: "token-one", want: true},
{name: "valid token two", token: "token-two", want: true},
{name: "unknown token", token: "wrong-token", want: false},
{name: "empty token", token: "", want: false},
{name: "whitespace token", token: " ", want: false},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := validator.IsValid(tc.token); got != tc.want {
t.Fatalf("IsValid() = %v, want %v", got, tc.want)
}
})
}
}
func TestNewValidator_EmptyTokenSet(t *testing.T) {
t.Parallel()
if _, err := NewValidator(nil); err == nil {
t.Fatal("NewValidator(nil) expected error, got nil")
}
if _, err := NewValidator([]string{"", " "}); err == nil {
t.Fatal("NewValidator(empty tokens) expected error, got nil")
}
}
func TestNewValidator_InvalidHash(t *testing.T) {
t.Parallel()
if _, err := NewValidator([]string{"not-a-hash"}); err == nil {
t.Fatal("NewValidator(invalid hash) expected error, got nil")
}
}
func TestParseBearerToken(t *testing.T) {
t.Parallel()
tests := []struct {
name string
header string
want string
wantErr bool
}{
{name: "valid bearer", header: "Bearer abc123", want: "abc123"},
{name: "valid lowercase prefix", header: "bearer abc123", want: "abc123"},
{name: "valid uppercase prefix", header: "BEARER abc123", want: "abc123"},
{name: "missing header", header: "", wantErr: true},
{name: "wrong scheme", header: "Basic abc123", wantErr: true},
{name: "missing token", header: "Bearer", wantErr: true},
{name: "too many parts", header: "Bearer one two", wantErr: true},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, err := ParseBearerToken(tc.header)
if tc.wantErr {
if err == nil {
t.Fatal("ParseBearerToken() expected error, got nil")
}
return
}
if err != nil {
t.Fatalf("ParseBearerToken() error = %v", err)
}
if got != tc.want {
t.Fatalf("ParseBearerToken() = %q, want %q", got, tc.want)
}
})
}
}