45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"git.warky.dev/wdevs/amcs/internal/config"
|
|
"git.warky.dev/wdevs/amcs/internal/tenancy"
|
|
)
|
|
|
|
func TestMiddlewareAddsTenantKeyToContext(t *testing.T) {
|
|
keyring, err := NewKeyring([]config.APIKey{{ID: "user-a", Value: "secret-a"}})
|
|
if err != nil {
|
|
t.Fatalf("NewKeyring error = %v", err)
|
|
}
|
|
|
|
var gotKeyID, gotTenant string
|
|
handler := Middleware(config.AuthConfig{}, keyring, nil, nil, nil, slog.Default())(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var ok bool
|
|
gotKeyID, ok = KeyIDFromContext(r.Context())
|
|
if !ok {
|
|
t.Fatal("KeyIDFromContext ok = false")
|
|
}
|
|
gotTenant, ok = tenancy.KeyFromContext(r.Context())
|
|
if !ok {
|
|
t.Fatal("tenancy.KeyFromContext ok = false")
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}))
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
|
|
req.Header.Set("x-brain-key", "secret-a")
|
|
rr := httptest.NewRecorder()
|
|
handler.ServeHTTP(rr, req)
|
|
|
|
if rr.Code != http.StatusNoContent {
|
|
t.Fatalf("status = %d, want %d", rr.Code, http.StatusNoContent)
|
|
}
|
|
if gotKeyID != "user-a" || gotTenant != "user-a" {
|
|
t.Fatalf("keyID=%q tenant=%q, want user-a/user-a", gotKeyID, gotTenant)
|
|
}
|
|
}
|