package authapi_test import ( "context" "log/slog" "net/http" "net/http/httptest" "testing" "time" "github.com/itworx/pulse/internal/audit" "github.com/itworx/pulse/internal/auth" "github.com/itworx/pulse/internal/authapi" "github.com/itworx/pulse/internal/config" "github.com/itworx/pulse/internal/correlation" "github.com/jackc/pgx/v5/pgxpool" ) // TestDocumentedWiringCompilesAndRoutes mirrors the registration snippet in the // package documentation so cmd/api/main.go can copy it verbatim. func TestDocumentedWiringCompilesAndRoutes(t *testing.T) { // The issuer points at a closed local server so the test stays offline: both // endpoints then answer with the safe error redirect instead of a session. unreachable := httptest.NewServer(http.NewServeMux()) unreachable.Close() application := config.Config{ Environment: config.Development, AuthMode: "oidc", OIDCIssuer: unreachable.URL, OIDCClientID: "pulse", OIDCRedirectURL: "https://pulse.example/auth/callback", } sessions := auth.NewSessionManager("pulse_session", 8*time.Hour, application.Environment == config.Production) logger := slog.New(slog.DiscardHandler) var pool *pgxpool.Pool oidcAuth, err := authapi.New(authapi.Options{ OIDC: auth.OIDCConfig{ Issuer: application.OIDCIssuer, ClientID: application.OIDCClientID, ClientSecret: application.OIDCClientSecret, RedirectURL: application.OIDCRedirectURL, }, RoleMapping: map[string]auth.Role{ "pulse-viewer": auth.RoleViewer, "pulse-operator": auth.RoleOperator, "pulse-editor": auth.RoleEditor, "pulse-admin": auth.RoleAdministrator, }, Sessions: sessions, Secure: application.Environment == config.Production, Logger: logger, Audit: func(ctx context.Context, actor, result string) error { if pool == nil { return nil } return audit.RecordSecurityAction(ctx, audit.PostgresStore{Pool: pool}, actor, "auth.login", result, correlation.FromContext(ctx)) }, }) if err != nil { t.Fatalf("New: %v", err) } mux := http.NewServeMux() mux.Handle("/auth/login", oidcAuth.LoginHandler()) mux.Handle("/auth/callback", oidcAuth.CallbackHandler()) for _, path := range []string{"/auth/login", "/auth/callback"} { response := httptest.NewRecorder() mux.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) if response.Code != http.StatusFound { t.Fatalf("%s status = %d, want %d", path, response.Code, http.StatusFound) } } }