managarten/services/mana-sync/internal/auth/jwt_test.go
Till JS 4f70e1ca6c refactor(shared-go): extract shared auth package from 3 Go services
Create packages/shared-go/authutil/ with two JWT validator implementations:
- JWKSValidator: EdDSA JWKS validation with key caching (extracted from mana-sync)
- RemoteValidator: delegates to mana-core-auth /api/v1/auth/validate (from mana-notify/gateway)

Plus shared types (Claims, User), middleware factories (JWTMiddleware, ServiceKeyMiddleware),
context helpers (GetUser, GetUserID, GetUserRole), and token extraction.

Migrated services:
- mana-sync: internal/auth/jwt.go now wraps authutil.JWKSValidator
- mana-notify: internal/auth/auth.go now wraps authutil.RemoteValidator + ServiceKeyMiddleware
- mana-api-gateway: internal/middleware/jwt.go now wraps authutil.RemoteValidator

All 3 services compile and pass tests. Service-level packages re-export types
for backward compatibility so no consumer code changes are needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 13:27:44 +02:00

72 lines
1.7 KiB
Go

package auth
import (
"net/http"
"testing"
)
func TestExtractToken(t *testing.T) {
tests := []struct {
name string
header string
wantToken string
}{
{"valid bearer", "Bearer eyJhbGciOiJFZERTQSJ9.test.sig", "eyJhbGciOiJFZERTQSJ9.test.sig"},
{"missing bearer prefix", "eyJhbGciOiJFZERTQSJ9.test.sig", ""},
{"empty header", "", ""},
{"lowercase bearer", "bearer token123", ""},
{"only bearer", "Bearer ", ""},
{"bearer with space", "Bearer token123", " token123"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, _ := http.NewRequest("GET", "/", nil)
if tt.header != "" {
r.Header.Set("Authorization", tt.header)
}
got := ExtractToken(r)
if got != tt.wantToken {
t.Errorf("ExtractToken() = %q, want %q", got, tt.wantToken)
}
})
}
}
func TestNewValidator(t *testing.T) {
v := NewValidator("http://localhost:3001/api/auth/jwks")
if v == nil {
t.Fatal("NewValidator returned nil")
}
}
func TestValidateTokenNoKeys(t *testing.T) {
v := NewValidator("http://localhost:99999/jwks")
_, err := v.ValidateToken("some.invalid.token")
if err == nil {
t.Error("expected error for token with no keys, got nil")
}
}
func TestUserIDFromRequestNoAuth(t *testing.T) {
v := NewValidator("http://localhost:99999/jwks")
r, _ := http.NewRequest("GET", "/", nil)
_, err := v.UserIDFromRequest(r)
if err == nil {
t.Error("expected error for request without auth header")
}
}
func TestUserIDFromRequestEmptyBearer(t *testing.T) {
v := NewValidator("http://localhost:99999/jwks")
r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer ")
_, err := v.UserIDFromRequest(r)
if err == nil {
t.Error("expected error for empty bearer token")
}
}