From d1dd640bcab3f58af003e99c4f012a1555394da7 Mon Sep 17 00:00:00 2001 From: "Jon Radoff (Metavert)" Date: Mon, 9 Nov 2026 21:11:19 -0500 Subject: [PATCH 1/2] OAuth connections act as the person who signed in OAuth tokens used to be swapped for a single stored admin key, so every connection had admin rights whoever approved it. A connection is now a grant that names the person; each request loads their current role, and the shared key is gone (removed from the database at startup). - /mcp calls the REST API in-process as the caller. No credential is held by a session or crosses a socket, and each MCP session is bound to the credential that opened it. - Tokens are bound to this server's /mcp resource. OAuth tokens are no longer accepted at /api/v1, and /mcp no longer accepts a cookie. - Authorization codes and refresh tokens are atomically single-use. A replayed refresh token ends the connection. /oauth/revoke works. - Client registration is rate limited and limited in size; redirects must be https or loopback. The consent page says who the app will act as and where the browser goes next. - An API key is refused if its owner is disabled or can't be loaded. Only a key with no owner on record is adopted, and it keeps its limits. - Requests that set `published` now need content.publish. - Agent work is recorded as agent work with a server-generated session, and the audit log names the key or connection. - Asset uploads no longer read paths on the server's disk. The /api/v1 route table moves to internal/handlers so tests can walk it. Co-Authored-By: Claude Opus 5.5 --- cmd/mcp/main.go | 9 +- cmd/server/main.go | 305 +-------------- internal/apiclient/client.go | 26 +- internal/apiclient/types.go | 1 - internal/auth/auth.go | 5 + internal/auth/credentials.go | 117 ++++++ internal/auth/credentials_test.go | 282 ++++++++++++++ internal/auth/permissions.go | 5 + internal/handlers/api.go | 3 +- internal/handlers/api_assets.go | 26 +- internal/handlers/api_content.go | 45 ++- internal/handlers/api_forks.go | 3 + internal/handlers/api_identity_test.go | 509 +++++++++++++++++++++++++ internal/handlers/api_imports.go | 21 + internal/handlers/api_routes.go | 236 ++++++++++++ internal/handlers/fixes_743_test.go | 6 +- internal/handlers/testhelper_test.go | 2 +- internal/mcp/asset_tools.go | 9 +- internal/mcp/http_handler.go | 161 +++++++- internal/mcp/http_handler_test.go | 331 ++++++++++++++++ internal/mcp/resources.go | 12 +- internal/mcp/resources_test.go | 26 -- internal/mcp/server.go | 9 + internal/middleware/apiauth.go | 137 +++++-- internal/middleware/apiauth_test.go | 135 ++++++- internal/middleware/apirate.go | 56 ++- internal/models/oauth.go | 20 + internal/models/user.go | 7 +- internal/oauth/handler.go | 246 +++++++++++- internal/oauth/handler_test.go | 105 +++-- internal/oauth/identity_test.go | 386 +++++++++++++++++++ internal/oauth/templates.go | 6 +- internal/services/apikey.go | 11 + internal/services/oauth.go | 283 ++++++++++++-- internal/services/oauth_grant_test.go | 475 +++++++++++++++++++++++ internal/services/oauth_test.go | 93 ++--- internal/services/system_key.go | 62 ++- internal/services/system_key_test.go | 88 ----- internal/testutil/testutil.go | 2 +- 39 files changed, 3518 insertions(+), 743 deletions(-) create mode 100644 internal/auth/credentials.go create mode 100644 internal/auth/credentials_test.go create mode 100644 internal/handlers/api_identity_test.go create mode 100644 internal/handlers/api_routes.go create mode 100644 internal/mcp/http_handler_test.go create mode 100644 internal/oauth/identity_test.go create mode 100644 internal/services/oauth_grant_test.go delete mode 100644 internal/services/system_key_test.go diff --git a/cmd/mcp/main.go b/cmd/mcp/main.go index f2818de..698347f 100644 --- a/cmd/mcp/main.go +++ b/cmd/mcp/main.go @@ -3,13 +3,10 @@ package main import ( "context" - "crypto/rand" - "encoding/hex" "fmt" "log" "os" "strings" - "time" "github.com/metavert-io/lightcms/v7/internal/apiclient" "github.com/metavert-io/lightcms/v7/internal/mcp" @@ -37,14 +34,12 @@ func main() { // Every MCP session gets a unique agent-session ID. The server groups // this session's changes in the audit log so humans can review or roll // them back as a unit. - sessionBytes := make([]byte, 8) - if _, err := rand.Read(sessionBytes); err == nil { - client.SetAgentSession("agent-" + time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(sessionBytes)) - } + client.SetAgentSession(apiclient.NewAgentSessionID()) // Create and run MCP server ctx := context.Background() server := mcp.NewServer(client) + server.AllowLocalFiles() if err := server.Run(ctx); err != nil { log.Printf("MCP server error: %v", err) os.Exit(1) diff --git a/cmd/server/main.go b/cmd/server/main.go index 5ab4c4b..c773c13 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -26,8 +26,6 @@ import ( "github.com/gorilla/mux" "github.com/gorilla/sessions" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" ) func main() { @@ -282,80 +280,23 @@ func main() { apiHandler.SetSEOService(seoService) apiHandler.SetAnalyticsService(analyticsService) apiHandler.SetBaseURL(cfg.BaseURL) - apiAuthMiddleware := middleware.NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { - apiKey, err := apiKeyService.ValidateAPIKey(ctx, rawKey) - if err != nil { - return nil, err - } - // Resolve the user who owns this API key - if apiKey.UserID != nil { - user, err := userService.GetByID(ctx, *apiKey.UserID) - if err == nil && user != nil { - go analyticsService.RecordActivity(context.Background(), user.ID.Hex()) - return &auth.SessionUser{ - ID: user.ID.Hex(), - Email: user.Email, - Role: user.Role, - ViaAPIKey: true, - Scopes: apiKey.Scopes, - SandboxOnly: apiKey.SandboxOnly, - }, nil - } - } - // Legacy key without user association — auto-migrate by associating with the first admin user. - log.Printf("[security] API key %s... has no user — attempting auto-migration to admin user", rawKey[:min(10, len(rawKey))]) - if adminUsers, err := userService.ListUsers(ctx); err == nil { - for _, u := range adminUsers { - if u.Role == models.RoleAdmin && !u.Disabled { - uid := u.ID - db.UpdateOne(ctx, "api_keys", bson.M{"_id": apiKey.ID}, bson.M{"$set": bson.M{"user_id": uid}}) - log.Printf("[security] Auto-migrated legacy API key to admin user %s", u.Email) - go analyticsService.RecordActivity(context.Background(), u.ID.Hex()) - return &auth.SessionUser{ - ID: u.ID.Hex(), - Email: u.Email, - Role: u.Role, - ViaAPIKey: true, - }, nil - } - } - } - // No admin user found — reject the key - return nil, fmt.Errorf("legacy key has no user and no admin user available for migration") - }) - - // OAuth 2.1 setup for MCP Cowork connector support + // OAuth 2.1 setup for MCP connector support. API keys and OAuth tokens both + // resolve to the person they act for, on every request. oauthService := services.NewOAuthService(db) - // Find an admin user to associate with the system API key so OAuth-authenticated - // MCP sessions resolve to admin-level permissions (not nil → permission bypass). - var systemKeyAdminID *primitive.ObjectID - if adminUsers, err := userService.ListUsers(context.Background()); err == nil { - for _, u := range adminUsers { - if u.Role == models.RoleAdmin && !u.Disabled { - id := u.ID - systemKeyAdminID = &id - break - } - } - } - systemAPIKey, err := services.EnsureSystemAPIKey(context.Background(), db, apiKeyService, systemKeyAdminID) - if err != nil { - log.Fatalf("Failed to create system API key: %v", err) - } + credentials := auth.NewCredentialResolver(userService, apiKeyService, oauthService, + services.MCPResourceURL(cfg.BaseURL), + func(userID string) { go analyticsService.RecordActivity(context.Background(), userID) }) + apiAuthMiddleware := middleware.NewAPIAuth(credentials.ResolveAPIKey) resourceMetadataURL := cfg.BaseURL + "/.well-known/oauth-protected-resource" - apiAuthMiddleware.SetOAuth( - func(ctx context.Context, rawToken string) (interface{}, error) { - _, err := oauthService.ValidateAccessToken(ctx, rawToken) - if err != nil { - return nil, err - } - // OAuth tokens go through the system API key path — no specific user context - // (the system key will be resolved on the subsequent internal request) - return nil, nil - }, - systemAPIKey, - resourceMetadataURL, - ) + apiAuthMiddleware.SetOAuth(credentials.ResolveOAuthToken, resourceMetadataURL) + + // OAuth sessions used to share one stored admin key; remove it if it is still here. + if removed, err := services.RemoveLegacySystemKey(context.Background(), db); err != nil { + log.Printf("Warning: failed to remove the legacy system API key: %v", err) + } else if removed { + log.Printf("Removed the legacy system API key") + } + oauthHandler := oauth.NewHandler(oauthService, authManager, cfg.BaseURL, cfg.SessionSecret) // Allow browser-based admin UI calls to /api/v1/ using session cookies (no Bearer token required). @@ -372,215 +313,7 @@ func main() { return user }, middleware.CSRFProtectAPI(csrfKey, cfg.SecureCookies)) - apiv1 := r.PathPrefix("/api/v1").Subrouter() - apiv1.Use(apiAuthMiddleware.Middleware) - apiv1.Use(middleware.APIBurstRateLimit) // per-token burst limit (20 req/s) - apiv1.Use(middleware.APIRateLimit) // per-token sliding-window rate limit (300 req/min) - apiv1.Use(middleware.APIBodySizeLimit) // cap request body at 10 MiB to prevent memory exhaustion - // Stamp change provenance (and version attribution) on every API request: - // agent sessions are identified by the X-Agent-Session header. - apiv1.Use(func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - prov := services.Provenance{Actor: "human", Via: "api"} - if sess := r.Header.Get("X-Agent-Session"); sess != "" { - prov.Actor = "agent" - prov.AgentSession = sess - } - ctx = services.WithProvenance(ctx, prov) - if u, ok := auth.UserFromAPIContext(ctx); ok && u != nil { - ctx = services.WithEditorEmail(ctx, u.Email) - } - next.ServeHTTP(w, r.WithContext(ctx)) - }) - }) - - // Content - apiv1.HandleFunc("/content", apiHandler.APIListContent).Methods("GET") - apiv1.HandleFunc("/content", apiHandler.APICreateContent).Methods("POST") - apiv1.HandleFunc("/content/by-path", apiHandler.APIGetContentByPath).Methods("GET") - apiv1.HandleFunc("/content/by-path", apiHandler.APIUpdateContentByPath).Methods("PUT") - apiv1.HandleFunc("/content/backlinks", apiHandler.APIGetBacklinks).Methods("GET") - apiv1.HandleFunc("/content/batch-publish", apiHandler.APIBatchPublishContent).Methods("POST") - apiv1.Handle("/content/bulk-create", middleware.BulkUpdateLimiter()(http.HandlerFunc(apiHandler.APIBulkCreateContent))).Methods("POST") - apiv1.Handle("/content/bulk-update", middleware.BulkUpdateLimiter()(http.HandlerFunc(apiHandler.APIBulkUpdateContent))).Methods("POST") - apiv1.Handle("/content/bulk-field-op", middleware.BulkUpdateLimiter()(http.HandlerFunc(apiHandler.APIBulkFieldOperation))).Methods("POST") - apiv1.Handle("/content/export", middleware.ExportLimiter()(http.HandlerFunc(apiHandler.APIExportContent))).Methods("POST") - apiv1.HandleFunc("/content/{id}", apiHandler.APIGetContent).Methods("GET") - apiv1.HandleFunc("/content/{id}", apiHandler.APIUpdateContent).Methods("PUT") - apiv1.HandleFunc("/content/{id}", apiHandler.APIDeleteContent).Methods("DELETE") - apiv1.HandleFunc("/content/{id}/restore", apiHandler.APIRestoreContent).Methods("POST") - apiv1.HandleFunc("/content/{id}/publish", apiHandler.APIPublishContent).Methods("POST") - apiv1.HandleFunc("/content/{id}/unpublish", apiHandler.APIUnpublishContent).Methods("POST") - apiv1.HandleFunc("/content/{id}/preview", apiHandler.APIPreviewContent).Methods("GET", "POST") - apiv1.HandleFunc("/content/{id}/versions", apiHandler.APIListContentVersions).Methods("GET") - apiv1.HandleFunc("/content/{id}/versions/{version}", apiHandler.APIGetContentVersion).Methods("GET") - apiv1.HandleFunc("/content/{id}/versions/{version}/revert", apiHandler.APIRevertContentVersion).Methods("POST") - - // Templates - apiv1.HandleFunc("/templates", apiHandler.APIListTemplates).Methods("GET") - apiv1.HandleFunc("/templates", apiHandler.APICreateTemplate).Methods("POST") - apiv1.HandleFunc("/templates/{id}", apiHandler.APIGetTemplate).Methods("GET") - apiv1.HandleFunc("/templates/{id}", apiHandler.APIUpdateTemplate).Methods("PUT") - apiv1.HandleFunc("/templates/{id}", apiHandler.APIDeleteTemplate).Methods("DELETE") - - // Assets - apiv1.HandleFunc("/assets", apiHandler.APIListAssets).Methods("GET") - apiv1.HandleFunc("/assets", apiHandler.APIUploadAsset).Methods("POST") - apiv1.Handle("/assets/from-url", middleware.AssetFromURLLimiter()(http.HandlerFunc(apiHandler.APIUploadAssetFromURL))).Methods("POST") - apiv1.HandleFunc("/assets/folders", apiHandler.APIListAssetFolders).Methods("GET") - apiv1.HandleFunc("/assets/by-path", apiHandler.APIGetAssetByPath).Methods("GET") - apiv1.HandleFunc("/assets/{id}", apiHandler.APIGetAsset).Methods("GET") - apiv1.HandleFunc("/assets/{id}", apiHandler.APIDeleteAsset).Methods("DELETE") - - // Theme - apiv1.HandleFunc("/theme", apiHandler.APIGetTheme).Methods("GET") - apiv1.HandleFunc("/theme", apiHandler.APIUpdateTheme).Methods("PUT") - apiv1.HandleFunc("/theme/versions", apiHandler.APIListThemeVersions).Methods("GET") - apiv1.HandleFunc("/theme/versions/{version}", apiHandler.APIGetThemeVersion).Methods("GET") - apiv1.HandleFunc("/theme/versions/{version}/revert", apiHandler.APIRevertThemeVersion).Methods("POST") - apiv1.HandleFunc("/theme/versions/{version}/pin", apiHandler.APIPinThemeVersion).Methods("POST") - apiv1.HandleFunc("/theme/versions/{version}/unpin", apiHandler.APIPinThemeVersion).Methods("POST") - - // Site Config - apiv1.HandleFunc("/config", apiHandler.APIGetSiteConfig).Methods("GET") - apiv1.HandleFunc("/config", apiHandler.APIUpdateSiteConfig).Methods("PUT") - - // Redirects - apiv1.HandleFunc("/redirects", apiHandler.APIListRedirects).Methods("GET") - apiv1.HandleFunc("/redirects", apiHandler.APICreateRedirect).Methods("POST") - apiv1.HandleFunc("/redirects/{id}", apiHandler.APIGetRedirect).Methods("GET") - apiv1.HandleFunc("/redirects/{id}", apiHandler.APIUpdateRedirect).Methods("PUT") - apiv1.HandleFunc("/redirects/{id}", apiHandler.APIDeleteRedirect).Methods("DELETE") - - // Folders - apiv1.HandleFunc("/folders", apiHandler.APIListFolders).Methods("GET") - apiv1.HandleFunc("/folders", apiHandler.APICreateFolder).Methods("POST") - apiv1.HandleFunc("/folders/{id}", apiHandler.APIGetFolder).Methods("GET") - apiv1.HandleFunc("/folders/{id}", apiHandler.APIDeleteFolder).Methods("DELETE") - - // Collections - apiv1.HandleFunc("/collections", apiHandler.APIListCollections).Methods("GET") - apiv1.HandleFunc("/collections", apiHandler.APICreateCollection).Methods("POST") - apiv1.HandleFunc("/collections/{id}", apiHandler.APIGetCollection).Methods("GET") - apiv1.HandleFunc("/collections/{id}", apiHandler.APIUpdateCollection).Methods("PUT") - apiv1.HandleFunc("/collections/{id}", apiHandler.APIDeleteCollection).Methods("DELETE") - - // Search - apiv1.HandleFunc("/search", apiHandler.APISearchContent).Methods("GET") - apiv1.HandleFunc("/search-replace/preview", apiHandler.APISearchReplacePreview).Methods("POST") - apiv1.Handle("/search-replace/execute", middleware.SearchReplaceExecuteLimiter()(http.HandlerFunc(apiHandler.APISearchReplaceExecute))).Methods("POST") - apiv1.HandleFunc("/search-replace/scoped/preview", apiHandler.APIScopedSearchReplacePreview).Methods("POST") - apiv1.Handle("/search-replace/scoped/execute", middleware.SearchReplaceExecuteLimiter()(http.HandlerFunc(apiHandler.APIScopedSearchReplaceExecute))).Methods("POST") - - // End-user search (authenticated API) - apiv1.HandleFunc("/end-user-search", apiHandler.APIEndUserSearch).Methods("GET") - apiv1.HandleFunc("/end-user-search/suggest", apiHandler.APIEndUserSearchSuggest).Methods("GET") - apiv1.Handle("/reindex-embeddings", middleware.ReindexLimiter()(http.HandlerFunc(apiHandler.APIReindexEmbeddings))).Methods("POST") - - // API Keys - apiv1.HandleFunc("/api-keys", apiHandler.APIListAPIKeys).Methods("GET") - apiv1.HandleFunc("/api-keys", apiHandler.APICreateAPIKey).Methods("POST") - apiv1.HandleFunc("/api-keys/{id}", apiHandler.APIDeleteAPIKey).Methods("DELETE") - - // Snippets - apiv1.HandleFunc("/snippets", apiHandler.APIListSnippets).Methods("GET") - apiv1.HandleFunc("/snippets", apiHandler.APICreateSnippet).Methods("POST") - apiv1.HandleFunc("/snippets/{id}", apiHandler.APIGetSnippet).Methods("GET") - apiv1.HandleFunc("/snippets/{id}", apiHandler.APIUpdateSnippet).Methods("PUT") - apiv1.HandleFunc("/snippets/{id}", apiHandler.APIDeleteSnippet).Methods("DELETE") - - // Forks - apiv1.HandleFunc("/forks", apiHandler.APIListForks).Methods("GET") - apiv1.HandleFunc("/forks", apiHandler.APICreateFork).Methods("POST") - apiv1.HandleFunc("/forks/{id}", apiHandler.APIGetFork).Methods("GET") - apiv1.HandleFunc("/forks/{id}", apiHandler.APIDeleteFork).Methods("DELETE") - apiv1.HandleFunc("/forks/{id}/fork-page", apiHandler.APIForkPage).Methods("POST") - apiv1.HandleFunc("/forks/{id}/pages", apiHandler.APIListForkPages).Methods("GET") - apiv1.HandleFunc("/forks/{id}/pages/{pageID}", apiHandler.APIRemoveForkPage).Methods("DELETE") - apiv1.HandleFunc("/forks/{id}/diff", apiHandler.APIForkDiff).Methods("GET") - - // Agent session ledger & rollback - apiv1.HandleFunc("/agent-sessions/{id}/changes", apiHandler.APIAgentSessionChanges).Methods("GET") - apiv1.HandleFunc("/agent-sessions/{id}/rollback", apiHandler.APIAgentSessionRollback).Methods("POST") - - // Maintenance scans (self-maintaining site routines) - apiv1.HandleFunc("/maintenance/report", apiHandler.APIMaintenanceReport).Methods("GET") - apiv1.HandleFunc("/indexnow", apiHandler.APIIndexNowStatus).Methods("GET") - apiv1.HandleFunc("/seo", apiHandler.APIGetSEO).Methods("GET") - apiv1.HandleFunc("/seo", apiHandler.APIUpdateSEO).Methods("PUT") - apiv1.HandleFunc("/analytics/ai", apiHandler.APIAITraffic).Methods("GET") - apiv1.HandleFunc("/indexnow", apiHandler.APIIndexNowUpdate).Methods("PUT") - apiv1.HandleFunc("/indexnow/submit", apiHandler.APIIndexNowSubmit).Methods("POST") - apiv1.HandleFunc("/maintenance/scan", apiHandler.APIMaintenanceScan).Methods("POST") - apiv1.HandleFunc("/maintenance/backfill-published-dates", apiHandler.APIBackfillPublishedDates).Methods("POST") - apiv1.HandleFunc("/maintenance/repair-fork-damage", apiHandler.APIRepairForkDamage).Methods("POST") - apiv1.HandleFunc("/forks/{id}/merge", apiHandler.APIMergeFork).Methods("POST") - apiv1.HandleFunc("/forks/{id}/archive", apiHandler.APIArchiveFork).Methods("POST") - apiv1.HandleFunc("/forks/{id}/purge-copies", apiHandler.APIPurgeForkCopies).Methods("POST") - - // Regenerate (rate-limited: 2/min — full rebuild is expensive) - apiv1.Handle("/regenerate", middleware.RegenerateLimiter()(http.HandlerFunc(apiHandler.APIRegenerateAllContent))).Methods("POST") - - // Webhooks API - apiv1.HandleFunc("/webhooks", apiHandler.APIListWebhooks).Methods("GET") - apiv1.HandleFunc("/webhooks", apiHandler.APICreateWebhook).Methods("POST") - apiv1.HandleFunc("/webhooks/{id}", apiHandler.APIUpdateWebhook).Methods("PUT") - apiv1.HandleFunc("/webhooks/{id}", apiHandler.APIDeleteWebhook).Methods("DELETE") - apiv1.HandleFunc("/webhooks/{id}/regenerate-secret", apiHandler.APIRegenerateWebhookSecret).Methods("POST") - apiv1.HandleFunc("/webhooks/{id}/deliveries", apiHandler.APIListWebhookDeliveries).Methods("GET") - - // Content locks API - apiv1.HandleFunc("/content/{id}/lock", apiHandler.APIGetContentLock).Methods("GET") - apiv1.HandleFunc("/content/{id}/lock", apiHandler.APIAcquireContentLock).Methods("POST") - apiv1.HandleFunc("/content/{id}/lock", apiHandler.APIReleaseContentLock).Methods("DELETE") - apiv1.HandleFunc("/content/{id}/lock/force", apiHandler.APIForceUnlockContent).Methods("POST") - - // Scheduled publish API - apiv1.HandleFunc("/content/scheduled", apiHandler.APIListScheduledContent).Methods("GET") - apiv1.HandleFunc("/content/{id}/schedule", apiHandler.APIScheduleContentPublish).Methods("POST") - - // Audit log API - apiv1.HandleFunc("/audit", apiHandler.APIListAuditLogs).Methods("GET") - - // Link check API - apiv1.HandleFunc("/link-check", apiHandler.APIStartLinkCheck).Methods("POST") - apiv1.HandleFunc("/link-check/{id}", apiHandler.APIGetLinkCheckJob).Methods("GET") - - // Import pipeline - apiv1.HandleFunc("/imports/sources", apiHandler.APIListImportSources).Methods("GET") - apiv1.HandleFunc("/imports/sources", apiHandler.APICreateImportSource).Methods("POST") - apiv1.HandleFunc("/imports/sources/{id}", apiHandler.APIUpdateImportSource).Methods("PUT") - apiv1.HandleFunc("/imports/sources/{id}", apiHandler.APIDeleteImportSource).Methods("DELETE") - apiv1.HandleFunc("/imports/sources/{id}/trigger", apiHandler.APITriggerImportSource).Methods("POST") - apiv1.HandleFunc("/imports/markdown", apiHandler.APIImportMarkdown).Methods("POST") - apiv1.HandleFunc("/imports/csv", apiHandler.APIImportCSV).Methods("POST") - apiv1.HandleFunc("/imports/jobs", apiHandler.APIListImportJobs).Methods("GET") - apiv1.HandleFunc("/imports/jobs/{id}", apiHandler.APIGetImportJob).Methods("GET") - apiv1.HandleFunc("/imports/jobs/{id}/cancel", apiHandler.APICancelImportJob).Methods("POST") - - // Comments API - apiv1.HandleFunc("/content/{id}/comments", apiHandler.APIListComments).Methods("GET") - apiv1.Handle("/content/{id}/comments", middleware.CommentCreateLimiter()(http.HandlerFunc(apiHandler.APICreateComment))).Methods("POST") - apiv1.HandleFunc("/content/{id}/comments/{cid}", apiHandler.APIDeleteComment).Methods("DELETE") - apiv1.HandleFunc("/content/{id}/submit-approval", apiHandler.APISubmitForApproval).Methods("POST") - - // Users list (for @mention and approver search in UI) - apiv1.HandleFunc("/users", apiHandler.APIListUsers).Methods("GET") - - // Approval workflows API - apiv1.HandleFunc("/approval-workflows", apiHandler.APIListApprovalWorkflows).Methods("GET") - apiv1.HandleFunc("/approval-workflows", apiHandler.APICreateApprovalWorkflow).Methods("POST") - apiv1.HandleFunc("/approval-workflows/{id}", apiHandler.APIGetApprovalWorkflow).Methods("GET") - apiv1.HandleFunc("/approval-workflows/{id}", apiHandler.APIUpdateApprovalWorkflow).Methods("PUT") - apiv1.HandleFunc("/approval-workflows/{id}", apiHandler.APIDeleteApprovalWorkflow).Methods("DELETE") - - // Approval requests API - apiv1.HandleFunc("/approval-requests", apiHandler.APIListApprovalRequests).Methods("GET") - apiv1.HandleFunc("/approval-requests/{id}", apiHandler.APIGetApprovalRequest).Methods("GET") - apiv1.HandleFunc("/approval-requests/{id}/approve", apiHandler.APIApproveRequest).Methods("POST") - apiv1.HandleFunc("/approval-requests/{id}/reject", apiHandler.APIRejectRequest).Methods("POST") - apiv1.HandleFunc("/approval-requests/{id}/cancel", apiHandler.APICancelRequest).Methods("POST") + apiv1 := apiHandler.MountAPI(r, apiAuthMiddleware) // API routes for AJAX (admin panel internal use) // Note: Most API routes require authentication (checked in handlers) @@ -602,16 +335,16 @@ func main() { api.HandleFunc("/chat/config", h.ChatWidgetConfigPublic).Methods("GET") // Public chat widget config (for JS widget) // OAuth 2.1 endpoints (no auth middleware — these implement their own auth) - r.HandleFunc("/oauth/register", oauthHandler.Register).Methods("POST") + r.Handle("/oauth/register", middleware.OAuthRegisterLimiter(proxyConfig)(http.HandlerFunc(oauthHandler.Register))).Methods("POST") r.HandleFunc("/oauth/authorize", oauthHandler.Authorize).Methods("GET") r.HandleFunc("/oauth/authorize", oauthHandler.AuthorizeSubmit).Methods("POST") r.HandleFunc("/oauth/token", oauthHandler.Token).Methods("POST") r.HandleFunc("/oauth/revoke", oauthHandler.TokenRevocation).Methods("POST") // MCP Streamable HTTP endpoint (API key + OAuth authenticated) - mcpHandler := lightmcp.NewHTTPHandler(cfg.Port) + mcpHandler := lightmcp.NewHTTPHandler(apiv1, resourceMetadataURL) mcpSubrouter := r.PathPrefix("/mcp").Subrouter() - mcpSubrouter.Use(apiAuthMiddleware.Middleware) + mcpSubrouter.Use(apiAuthMiddleware.MCPMiddleware) mcpSubrouter.Handle("", mcpHandler) // Public read-only MCP endpoint — no auth; lets visitors' agents search diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index d755b87..41fb48e 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -3,6 +3,8 @@ package apiclient import ( "bytes" "context" + "crypto/rand" + "encoding/hex" "encoding/json" "fmt" "io" @@ -28,6 +30,14 @@ func (c *Client) SetAgentSession(id string) { c.agentSession = id } // AgentSession returns the session ID configured via SetAgentSession. func (c *Client) AgentSession() string { return c.agentSession } +// NewAgentSessionID returns a new ID for an agent session. The server groups a +// session's changes under it so they can be reviewed or rolled back as a unit. +func NewAgentSessionID() string { + b := make([]byte, 8) + _, _ = rand.Read(b) // never fails: crypto/rand aborts the process instead + return "agent-" + time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(b) +} + // New creates a new API client func New(baseURL, apiKey string) *Client { return &Client{ @@ -39,6 +49,18 @@ func New(baseURL, apiKey string) *Client { } } +// NewWithTransport creates a client that carries no key and sends its requests +// through transport, which is responsible for saying who the caller is. +func NewWithTransport(baseURL string, transport http.RoundTripper) *Client { + return &Client{ + baseURL: baseURL, + httpClient: &http.Client{ + Timeout: 60 * time.Second, + Transport: transport, + }, + } +} + // do executes an HTTP request with auth and JSON handling func (c *Client) do(ctx context.Context, method, path string, body interface{}, result interface{}) error { var bodyReader io.Reader @@ -55,7 +77,9 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, return fmt.Errorf("failed to create request: %w", err) } - req.Header.Set("Authorization", "Bearer "+c.apiKey) + if c.apiKey != "" { + req.Header.Set("Authorization", "Bearer "+c.apiKey) + } if c.agentSession != "" { req.Header.Set("X-Agent-Session", c.agentSession) } diff --git a/internal/apiclient/types.go b/internal/apiclient/types.go index 32f3460..35fe489 100644 --- a/internal/apiclient/types.go +++ b/internal/apiclient/types.go @@ -192,7 +192,6 @@ type UploadAssetRequest struct { Filename string `json:"filename"` ServePath string `json:"serve_path"` DataBase64 string `json:"data_base64,omitempty"` - FilePath string `json:"file_path,omitempty"` Description string `json:"description,omitempty"` } diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 9334a1a..9cac05d 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -100,6 +100,11 @@ func (m *Manager) ValidateCredentials(ctx context.Context, email, password strin return m.userService.ValidateCredentials(ctx, email, password) } +// GetUserByID returns a user account, or nil if there is none. +func (m *Manager) GetUserByID(ctx context.Context, id primitive.ObjectID) (*models.User, error) { + return m.userService.GetByID(ctx, id) +} + // ChangePassword updates a user's password via the user service func (m *Manager) ChangePassword(ctx context.Context, userID primitive.ObjectID, currentPassword, newPassword string) error { if err := ValidatePasswordStrength(newPassword); err != nil { diff --git a/internal/auth/credentials.go b/internal/auth/credentials.go new file mode 100644 index 0000000..d06987c --- /dev/null +++ b/internal/auth/credentials.go @@ -0,0 +1,117 @@ +package auth + +import ( + "context" + "fmt" + "log" + + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" +) + +// CredentialResolver turns an API key or OAuth access token into the person it +// acts for. It runs on every request, so a change of role, a disabled account +// or a revoked connection takes effect at once, and any doubt about who is +// behind a credential refuses the request. +type CredentialResolver struct { + users *services.UserService + apiKeys *services.APIKeyService + oauth *services.OAuthService + resource string + onActivity func(userID string) +} + +// NewCredentialResolver creates a resolver. resource is the identifier OAuth +// tokens must have been issued for. onActivity, if set, is called with each +// authenticated user's ID. +func NewCredentialResolver(users *services.UserService, apiKeys *services.APIKeyService, oauth *services.OAuthService, resource string, onActivity func(userID string)) *CredentialResolver { + return &CredentialResolver{users: users, apiKeys: apiKeys, oauth: oauth, resource: resource, onActivity: onActivity} +} + +// ResolveAPIKey implements middleware.APIKeyValidateFunc. +func (c *CredentialResolver) ResolveAPIKey(ctx context.Context, rawKey string) (interface{}, error) { + key, err := c.apiKeys.ValidateAPIKey(ctx, rawKey) + if err != nil { + return nil, err + } + owner, err := c.keyOwner(ctx, key) + if err != nil { + return nil, err + } + c.recordActivity(owner) + return &SessionUser{ + ID: owner.ID.Hex(), + Email: owner.Email, + Role: owner.Role, + ViaAPIKey: true, + Credential: "apikey:" + key.ID.Hex(), + Scopes: key.Scopes, + SandboxOnly: key.SandboxOnly, + }, nil +} + +// ResolveOAuthToken implements middleware.OAuthValidateFunc. +func (c *CredentialResolver) ResolveOAuthToken(ctx context.Context, rawToken string) (interface{}, error) { + grant, err := c.oauth.ValidateAccessToken(ctx, rawToken, c.resource) + if err != nil { + return nil, err + } + user, err := c.users.GetByID(ctx, grant.UserID) + if err != nil { + return nil, fmt.Errorf("loading connection owner: %w", err) + } + if user == nil || user.Disabled { + return nil, fmt.Errorf("connection owner is missing or disabled") + } + c.recordActivity(user) + return &SessionUser{ + ID: user.ID.Hex(), + Email: user.Email, + Role: user.Role, + ViaOAuth: true, + Credential: "oauth:" + grant.ID.Hex(), + }, nil +} + +// keyOwner returns the active user an API key belongs to. A key with no owner +// on record predates ownership and is given to the first active admin, once; +// it keeps its restrictions. A key whose owner cannot be loaded is refused, +// whatever the reason: a passing database error must not change who it acts as. +func (c *CredentialResolver) keyOwner(ctx context.Context, key *models.APIKey) (*models.User, error) { + if key.UserID == nil { + return c.adoptOwnerlessKey(ctx, key) + } + owner, err := c.users.GetByID(ctx, *key.UserID) + if err != nil { + return nil, fmt.Errorf("loading API key owner: %w", err) + } + if owner == nil || owner.Disabled { + return nil, fmt.Errorf("API key owner is missing or disabled") + } + return owner, nil +} + +func (c *CredentialResolver) adoptOwnerlessKey(ctx context.Context, key *models.APIKey) (*models.User, error) { + users, err := c.users.ListUsers(ctx) + if err != nil { + return nil, fmt.Errorf("listing users for an unowned API key: %w", err) + } + for i := range users { + admin := &users[i] + if admin.Role != models.RoleAdmin || admin.Disabled { + continue + } + if err := c.apiKeys.AssignOwner(ctx, key.ID, admin.ID); err != nil { + return nil, err + } + log.Printf("[security] API key %q had no owner; assigned to admin %s", key.Name, admin.Email) + return admin, nil + } + return nil, fmt.Errorf("API key has no owner and no admin is available to take it") +} + +func (c *CredentialResolver) recordActivity(user *models.User) { + if c.onActivity != nil { + c.onActivity(user.ID.Hex()) + } +} diff --git a/internal/auth/credentials_test.go b/internal/auth/credentials_test.go new file mode 100644 index 0000000..8499cc7 --- /dev/null +++ b/internal/auth/credentials_test.go @@ -0,0 +1,282 @@ +package auth + +import ( + "context" + "testing" + + "github.com/metavert-io/lightcms/v7/internal/database" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" + "github.com/metavert-io/lightcms/v7/internal/testutil" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +const credentialTestResource = "https://example.com/mcp" + +type credentialFixture struct { + db *database.DB + users *services.UserService + keys *services.APIKeyService + oauth *services.OAuthService + resolver *CredentialResolver +} + +func newCredentialFixture(t *testing.T) *credentialFixture { + t.Helper() + db, cleanup := testutil.MustConnectTestDB(t) + t.Cleanup(cleanup) + f := &credentialFixture{ + db: db, + users: services.NewUserService(db), + keys: services.NewAPIKeyService(db), + oauth: services.NewOAuthService(db), + } + f.resolver = NewCredentialResolver(f.users, f.keys, f.oauth, credentialTestResource, nil) + return f +} + +func (f *credentialFixture) user(t *testing.T, email, role string) *models.User { + t.Helper() + user, err := f.users.CreateUserWithHash(context.Background(), email, email, role, "unused", false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + return user +} + +// accessToken connects a client on behalf of user and returns the access token. +func (f *credentialFixture) accessToken(t *testing.T, user *models.User) (string, *models.OAuthGrant) { + t.Helper() + ctx := context.Background() + client, _, err := f.oauth.RegisterClient(ctx, "Test App", []string{"http://localhost/cb"}) + if err != nil { + t.Fatalf("RegisterClient: %v", err) + } + grant, err := f.oauth.SaveGrant(ctx, client, user.ID, credentialTestResource) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + // The challenge is the S256 of this verifier (RFC 7636 appendix B). + verifier := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + code, err := f.oauth.CreateAuthCode(ctx, grant, "http://localhost/cb", "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "S256") + if err != nil { + t.Fatalf("CreateAuthCode: %v", err) + } + access, _, _, err := f.oauth.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) + if err != nil { + t.Fatalf("ExchangeAuthCode: %v", err) + } + return access, grant +} + +func caller(t *testing.T, v interface{}, err error) *SessionUser { + t.Helper() + if err != nil { + t.Fatalf("resolving credential: %v", err) + } + return v.(*SessionUser) +} + +func TestResolveAPIKey_ActsAsItsOwnerWithItsRestrictions(t *testing.T) { + f := newCredentialFixture(t) + owner := f.user(t, "owner@example.com", models.RoleEditor) + raw, key, err := f.keys.CreateScopedAPIKey(context.Background(), "Agent", "", &owner.ID, []string{PermContentView}, true) + if err != nil { + t.Fatalf("CreateScopedAPIKey: %v", err) + } + + v, err := f.resolver.ResolveAPIKey(context.Background(), raw) + got := caller(t, v, err) + if got.ID != owner.ID.Hex() || got.Role != models.RoleEditor || !got.ViaAPIKey || got.ViaOAuth { + t.Errorf("unexpected caller: %+v", got) + } + if !got.SandboxOnly || len(got.Scopes) != 1 { + t.Errorf("key restrictions were dropped: %+v", got) + } + if got.CredentialKey() != "apikey:"+key.ID.Hex() { + t.Errorf("credential = %q", got.CredentialKey()) + } +} + +func TestResolveAPIKey_RefusesWhenOwnerIsDisabled(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + owner := f.user(t, "owner@example.com", models.RoleAdmin) + raw, _, _ := f.keys.CreateAPIKeyForUser(ctx, "Key", "", &owner.ID) + if err := f.users.DisableUser(ctx, owner.ID, true); err != nil { + t.Fatalf("DisableUser: %v", err) + } + if _, err := f.resolver.ResolveAPIKey(ctx, raw); err == nil { + t.Error("a disabled owner's key must not work") + } +} + +func TestResolveAPIKey_RefusesWhenOwnerIsGoneAndDoesNotPromote(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + f.user(t, "admin@example.com", models.RoleAdmin) + missing := primitive.NewObjectID() + raw, key, _ := f.keys.CreateAPIKeyForUser(ctx, "Key", "", &missing) + + if _, err := f.resolver.ResolveAPIKey(ctx, raw); err == nil { + t.Fatal("a key whose owner is missing must not work") + } + var stored models.APIKey + if err := f.db.FindOne(ctx, "api_keys", bson.M{"_id": key.ID}, &stored); err != nil { + t.Fatalf("FindOne: %v", err) + } + if stored.UserID == nil || *stored.UserID != missing { + t.Errorf("the key was reassigned to %v", stored.UserID) + } +} + +func TestResolveAPIKey_RefusesWhenOwnerCannotBeLoaded(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + admin := f.user(t, "admin@example.com", models.RoleAdmin) + raw, _, _ := f.keys.CreateAPIKeyForUser(ctx, "Key", "", &admin.ID) + + // Keys come from a working database, users from a dead one. + broken := services.NewUserService(testutil.MustConnectBrokenDB(t)) + resolver := NewCredentialResolver(broken, f.keys, f.oauth, credentialTestResource, nil) + if _, err := resolver.ResolveAPIKey(ctx, raw); err == nil { + t.Error("a database error must refuse the key") + } +} + +func TestResolveAPIKey_OwnerlessKeyIsAdoptedAndKeepsRestrictions(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + f.user(t, "viewer@example.com", models.RoleViewer) + disabled := f.user(t, "former@example.com", models.RoleAdmin) + if err := f.users.DisableUser(ctx, disabled.ID, true); err != nil { + t.Fatalf("DisableUser: %v", err) + } + admin := f.user(t, "admin@example.com", models.RoleAdmin) + raw, key, err := f.keys.CreateScopedAPIKey(ctx, "Old", "", nil, []string{PermContentView}, true) + if err != nil { + t.Fatalf("CreateScopedAPIKey: %v", err) + } + + v, err := f.resolver.ResolveAPIKey(ctx, raw) + got := caller(t, v, err) + if got.ID != admin.ID.Hex() { + t.Errorf("adopted by %s, want the active admin", got.Email) + } + if !got.SandboxOnly || len(got.Scopes) != 1 { + t.Errorf("restrictions were dropped: %+v", got) + } + var stored models.APIKey + if err := f.db.FindOne(ctx, "api_keys", bson.M{"_id": key.ID}, &stored); err != nil { + t.Fatalf("FindOne: %v", err) + } + if stored.UserID == nil || *stored.UserID != admin.ID { + t.Errorf("owner on record = %v", stored.UserID) + } +} + +func TestResolveAPIKey_OwnerlessKeyRefusedWithNoAdmin(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + f.user(t, "viewer@example.com", models.RoleViewer) + raw, _, _ := f.keys.CreateAPIKey(ctx, "Old", "") + if _, err := f.resolver.ResolveAPIKey(ctx, raw); err == nil { + t.Error("expected refusal") + } +} + +func TestResolveOAuthToken_ActsAsThePersonWhoConnected(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + f.user(t, "admin@example.com", models.RoleAdmin) + viewer := f.user(t, "viewer@example.com", models.RoleViewer) + token, grant := f.accessToken(t, viewer) + + v, err := f.resolver.ResolveOAuthToken(ctx, token) + got := caller(t, v, err) + if got.ID != viewer.ID.Hex() || got.Role != models.RoleViewer { + t.Fatalf("token acts as %s (%s), want the viewer", got.Email, got.Role) + } + if !got.ViaOAuth || got.ViaAPIKey { + t.Errorf("unexpected credential type: %+v", got) + } + if got.CredentialKey() != "oauth:"+grant.ID.Hex() { + t.Errorf("credential = %q", got.CredentialKey()) + } + if UserHasPermission(got, PermContentEdit) { + t.Error("a viewer's token must not be able to edit") + } +} + +func TestResolveOAuthToken_FollowsRoleChangesAtOnce(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + user := f.user(t, "person@example.com", models.RoleAdmin) + token, _ := f.accessToken(t, user) + + if err := f.users.UpdateUser(ctx, user.ID, "person", models.RoleViewer); err != nil { + t.Fatalf("UpdateUser: %v", err) + } + v, err := f.resolver.ResolveOAuthToken(ctx, token) + if got := caller(t, v, err); got.Role != models.RoleViewer { + t.Errorf("role = %s, want viewer", got.Role) + } +} + +func TestResolveOAuthToken_RefusesDisabledMissingOrRevoked(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + + disabled := f.user(t, "leaver@example.com", models.RoleAdmin) + token, _ := f.accessToken(t, disabled) + if err := f.users.DisableUser(ctx, disabled.ID, true); err != nil { + t.Fatalf("DisableUser: %v", err) + } + if _, err := f.resolver.ResolveOAuthToken(ctx, token); err == nil { + t.Error("a disabled person's token must not work") + } + + revoked := f.user(t, "revoked@example.com", models.RoleAdmin) + token, grant := f.accessToken(t, revoked) + if err := f.oauth.RevokeGrant(ctx, grant.ID); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + if _, err := f.resolver.ResolveOAuthToken(ctx, token); err == nil { + t.Error("a revoked connection's token must not work") + } + + gone := &models.User{ID: primitive.NewObjectID()} + token, _ = f.accessToken(t, gone) + if _, err := f.resolver.ResolveOAuthToken(ctx, token); err == nil { + t.Error("a token for a missing person must not work") + } +} + +func TestResolveOAuthToken_RefusesTokenForAnotherResource(t *testing.T) { + f := newCredentialFixture(t) + user := f.user(t, "person@example.com", models.RoleAdmin) + token, _ := f.accessToken(t, user) + + elsewhere := NewCredentialResolver(f.users, f.keys, f.oauth, "https://other.example/mcp", nil) + if _, err := elsewhere.ResolveOAuthToken(context.Background(), token); err == nil { + t.Error("expected refusal") + } +} + +func TestCredentialResolver_ReportsActivity(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + user := f.user(t, "person@example.com", models.RoleEditor) + raw, _, _ := f.keys.CreateAPIKeyForUser(ctx, "Key", "", &user.ID) + + var seen string + resolver := NewCredentialResolver(f.users, f.keys, f.oauth, credentialTestResource, func(id string) { seen = id }) + if _, err := resolver.ResolveAPIKey(ctx, raw); err != nil { + t.Fatalf("ResolveAPIKey: %v", err) + } + if seen != user.ID.Hex() { + t.Errorf("activity recorded for %q", seen) + } +} diff --git a/internal/auth/permissions.go b/internal/auth/permissions.go index e387bf5..6d16a22 100644 --- a/internal/auth/permissions.go +++ b/internal/auth/permissions.go @@ -132,10 +132,15 @@ type SessionUser struct { Email string `json:"email"` Role string `json:"role"` ViaAPIKey bool `json:"via_api_key,omitempty"` // true when authenticated via API key (not session) + ViaOAuth bool `json:"via_oauth,omitempty"` // true when authenticated via an OAuth connection (not session) + Credential string `json:"credential,omitempty"` // the API key or OAuth connection in use: "apikey:" or "oauth:" Scopes []string `json:"scopes,omitempty"` // API-key permission allowlist; empty = full role permissions SandboxOnly bool `json:"sandbox_only,omitempty"` // API key restricted to fork-sandboxed content writes } +// CredentialKey implements middleware.CredentialBound. +func (u *SessionUser) CredentialKey() string { return u.Credential } + // sandboxAllowedPerms is the permission set available to sandbox-only API // keys: reading, creating/editing content (fork-scoped, enforced by the // content handlers), uploading assets, and working with forks. Everything diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 68b7365..472d0a7 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -116,7 +116,8 @@ func (a *APIHandler) auditLog(r *http.Request, action, resource, resourceID stri entry.UserID = oid } entry.UserEmail = user.Email - entry.ViaAPI = user.ViaAPIKey + entry.ViaAPI = user.ViaAPIKey || user.ViaOAuth + entry.Credential = user.Credential } a.auditService.LogAsync(entry) } diff --git a/internal/handlers/api_assets.go b/internal/handlers/api_assets.go index 8def9b9..cb1a605 100644 --- a/internal/handlers/api_assets.go +++ b/internal/handlers/api_assets.go @@ -6,7 +6,6 @@ import ( "io" "net" "net/http" - "os" "path/filepath" "strings" "time" @@ -157,7 +156,6 @@ func (a *APIHandler) APIUploadAsset(w http.ResponseWriter, r *http.Request) { Filename string `json:"filename"` ServePath string `json:"serve_path"` DataBase64 string `json:"data_base64"` - FilePath string `json:"file_path"` Description string `json:"description"` } if err := a.decodeJSON(r, &req); err != nil { @@ -168,8 +166,8 @@ func (a *APIHandler) APIUploadAsset(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "filename and serve_path are required") return } - if req.DataBase64 == "" && req.FilePath == "" { - a.jsonError(w, http.StatusBadRequest, "either data_base64 or file_path is required") + if req.DataBase64 == "" { + a.jsonError(w, http.StatusBadRequest, "data_base64 is required") return } if !isValidAssetServePath(req.ServePath) { @@ -177,22 +175,10 @@ func (a *APIHandler) APIUploadAsset(w http.ResponseWriter, r *http.Request) { return } - var data []byte - if req.FilePath != "" { - // Read file directly from local filesystem (avoids base64 size limits in MCP transport) - var err error - data, err = os.ReadFile(req.FilePath) - if err != nil { - a.jsonError(w, http.StatusBadRequest, fmt.Sprintf("failed to read file_path: %v", err)) - return - } - } else { - var err error - data, err = base64.StdEncoding.DecodeString(req.DataBase64) - if err != nil { - a.jsonError(w, http.StatusBadRequest, "invalid base64 data") - return - } + data, err := base64.StdEncoding.DecodeString(req.DataBase64) + if err != nil { + a.jsonError(w, http.StatusBadRequest, "invalid base64 data") + return } asset, err := a.assetService.UploadAsset(r.Context(), data, req.Filename, req.ServePath, req.Description) diff --git a/internal/handlers/api_content.go b/internal/handlers/api_content.go index 5520e48..7fecdf6 100644 --- a/internal/handlers/api_content.go +++ b/internal/handlers/api_content.go @@ -295,6 +295,27 @@ func (a *APIHandler) APIGetBacklinks(w http.ResponseWriter, r *http.Request) { a.jsonResponse(w, http.StatusOK, backlinks) } +// applyPublishedField applies a "published" value from a partial update. A +// request that changes whether a live page is published needs content.publish, +// like the publish and unpublish endpoints. A fork copy is never published, so +// the value is ignored there. It reports false after writing a refusal. +func (a *APIHandler) applyPublishedField(w http.ResponseWriter, r *http.Request, content *models.Content, raw map[string]json.RawMessage) bool { + v, ok := raw["published"] + if !ok || content.ForkID != nil { + return true + } + var published bool + if err := json.Unmarshal(v, &published); err != nil { + a.jsonError(w, http.StatusBadRequest, "published must be true or false") + return false + } + if published != content.Published && !a.requirePermission(w, r, auth.PermContentPublish) { + return false + } + content.Published = published + return true +} + func (a *APIHandler) APICreateContent(w http.ResponseWriter, r *http.Request) { if !a.requirePermission(w, r, auth.PermContentCreate) { return @@ -333,6 +354,12 @@ func (a *APIHandler) APICreateContent(w http.ResponseWriter, r *http.Request) { return } + // Creating a published page is publishing it. (A page created in a fork + // goes live only through a merge.) + if req.Published && req.ForkID == "" && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } + templateID, err := primitive.ObjectIDFromHex(req.TemplateID) if err != nil { a.jsonError(w, http.StatusBadRequest, "invalid template_id") @@ -406,7 +433,7 @@ func (a *APIHandler) APICreateContent(w http.ResponseWriter, r *http.Request) { AuthorName: req.AuthorName, AuthorURL: req.AuthorURL, Data: req.Data, - Published: req.Published, + Published: req.Published && forkID == nil, // a fork copy is never published UseHeader: req.UseHeader, UseFooter: req.UseFooter, UseTheme: req.UseTheme, @@ -553,8 +580,8 @@ func (a *APIHandler) APIUpdateContent(w http.ResponseWriter, r *http.Request) { } } } - if v, ok := raw["published"]; ok { - json.Unmarshal(v, &content.Published) + if !a.applyPublishedField(w, r, content, raw) { + return } if v, ok := raw["use_header"]; ok { json.Unmarshal(v, &content.UseHeader) @@ -1481,8 +1508,8 @@ func (a *APIHandler) APIUpdateContentByPath(w http.ResponseWriter, r *http.Reque if v, ok := raw["author_url"]; ok { json.Unmarshal(v, &content.AuthorURL) } - if v, ok := raw["published"]; ok { - json.Unmarshal(v, &content.Published) + if !a.applyPublishedField(w, r, content, raw) { + return } if v, ok := raw["use_header"]; ok { json.Unmarshal(v, &content.UseHeader) @@ -1927,6 +1954,14 @@ func (a *APIHandler) APIBulkCreateContent(w http.ResponseWriter, r *http.Request a.jsonError(w, http.StatusBadRequest, "maximum 100 items per batch") return } + for _, item := range req.Items { + if item.Published { + if !a.requirePermission(w, r, auth.PermContentPublish) { + return + } + break + } + } // Resolve templates and folders once templateCache := make(map[string]*models.Template) diff --git a/internal/handlers/api_forks.go b/internal/handlers/api_forks.go index 8588f42..c634f7d 100644 --- a/internal/handlers/api_forks.go +++ b/internal/handlers/api_forks.go @@ -319,6 +319,9 @@ func (a *APIHandler) APIMergeFork(w http.ResponseWriter, r *http.Request) { return } } + if body.PublishNew && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } user := a.getAPIUser(r) var userID primitive.ObjectID var userEmail string diff --git a/internal/handlers/api_identity_test.go b/internal/handlers/api_identity_test.go new file mode 100644 index 0000000..b25acd3 --- /dev/null +++ b/internal/handlers/api_identity_test.go @@ -0,0 +1,509 @@ +package handlers + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/database" + lightmcp "github.com/metavert-io/lightcms/v7/internal/mcp" + "github.com/metavert-io/lightcms/v7/internal/middleware" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" + + "github.com/gorilla/mux" + mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// apiRouterWithKeys mounts the real /api/v1 routes and middleware, with API +// keys that resolve to the given callers. +func apiRouterWithKeys(a *APIHandler, callers map[string]*auth.SessionUser) http.Handler { + apiAuth := middleware.NewAPIAuth(func(ctx context.Context, key string) (interface{}, error) { + if u, ok := callers[key]; ok { + return u, nil + } + return nil, fmt.Errorf("unknown key") + }) + r := mux.NewRouter() + a.MountAPI(r, apiAuth) + return r +} + +func sendJSON(router http.Handler, key, method, target, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, target, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("Content-Type", "application/json") + rr := httptest.NewRecorder() + router.ServeHTTP(rr, req) + return rr +} + +func keyCaller(name, role string, scopes ...string) *auth.SessionUser { + return &auth.SessionUser{ + ID: primitive.NewObjectID().Hex(), + Email: name + "@example.com", + Role: role, + ViaAPIKey: true, + Credential: "apikey:" + name, + Scopes: scopes, + } +} + +// publishCallers: a contributor, a key scoped to writing but not publishing, +// and an editor. +func publishCallers() map[string]*auth.SessionUser { + return map[string]*auth.SessionUser{ + "lc_contributor": keyCaller("contributor", models.RoleContributor), + "lc_writer": keyCaller("writer", models.RoleEditor, auth.PermContentView, auth.PermContentCreate, auth.PermContentEdit), + "lc_editor": keyCaller("editor", models.RoleEditor), + } +} + +func pagePublished(t *testing.T, db *database.DB, slug string) (found, published bool) { + t.Helper() + var c models.Content + if err := db.FindOne(context.Background(), "content", bson.M{"slug": slug}, &c); err != nil { + return false, false + } + return true, c.Published +} + +func TestPublishPermission_CreateRequiresIt(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + tmpl := seedTemplate(t, db, "Page", "page").Hex() + + body := func(slug string, published bool) string { + return fmt.Sprintf(`{"template_id":%q,"title":"T","slug":%q,"data":{},"published":%t}`, tmpl, slug, published) + } + + for _, key := range []string{"lc_contributor", "lc_writer"} { + if rr := sendJSON(router, key, "POST", "/api/v1/content", body("live-"+key, true)); rr.Code != http.StatusForbidden { + t.Errorf("%s publishing on create: %d %s", key, rr.Code, rr.Body.String()) + } + if found, _ := pagePublished(t, db, "live-"+key); found { + t.Errorf("%s: the refused page was created", key) + } + if rr := sendJSON(router, key, "POST", "/api/v1/content", body("draft-"+key, false)); rr.Code != http.StatusCreated { + t.Errorf("%s creating a draft: %d %s", key, rr.Code, rr.Body.String()) + } + } + + if rr := sendJSON(router, "lc_editor", "POST", "/api/v1/content", body("by-editor", true)); rr.Code != http.StatusCreated { + t.Fatalf("editor: %d %s", rr.Code, rr.Body.String()) + } + if _, published := pagePublished(t, db, "by-editor"); !published { + t.Error("the editor's page should be published") + } +} + +func TestPublishPermission_BulkCreateRequiresIt(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + tmpl := seedTemplate(t, db, "Page", "page").Hex() + + body := fmt.Sprintf(`{"items":[ + {"template_id":%q,"title":"Draft","slug":"bulk-draft","data":{}}, + {"template_id":%q,"title":"Live","slug":"bulk-live","data":{},"published":true} + ]}`, tmpl, tmpl) + if rr := sendJSON(router, "lc_contributor", "POST", "/api/v1/content/bulk-create", body); rr.Code != http.StatusForbidden { + t.Errorf("bulk create with a published item: %d %s", rr.Code, rr.Body.String()) + } + if found, _ := pagePublished(t, db, "bulk-live"); found { + t.Error("nothing in a refused batch should be created") + } +} + +func TestPublishPermission_UpdateRequiresItOnlyToChangeState(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + tmpl := seedTemplate(t, db, "Page", "page") + id := seedContent(t, db, tmpl, "Draft", "update-draft", "/update-draft").Hex() + + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/content/"+id, `{"published":true}`); rr.Code != http.StatusForbidden { + t.Errorf("publishing by update: %d %s", rr.Code, rr.Body.String()) + } + if _, published := pagePublished(t, db, "update-draft"); published { + t.Fatal("the page went live") + } + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/content/by-path?path=/update-draft", `{"published":true}`); rr.Code != http.StatusForbidden { + t.Errorf("publishing by path: %d %s", rr.Code, rr.Body.String()) + } + + // Sending the page's current state is not publishing. + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/content/"+id, `{"title":"New title","published":false}`); rr.Code != http.StatusOK { + t.Errorf("same state: %d %s", rr.Code, rr.Body.String()) + } + + if rr := sendJSON(router, "lc_editor", "PUT", "/api/v1/content/"+id, `{"published":true}`); rr.Code != http.StatusOK { + t.Errorf("editor: %d %s", rr.Code, rr.Body.String()) + } + if _, published := pagePublished(t, db, "update-draft"); !published { + t.Error("the editor should have published the page") + } + + // Taking it down is also a change of state. + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/content/"+id, `{"published":false}`); rr.Code != http.StatusForbidden { + t.Errorf("unpublishing by update: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestPublishedField_IgnoredOnForkCopies(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + tmpl := seedTemplate(t, db, "Page", "page").Hex() + fork := createTestFork(t, db, "copies").Hex() + + body := fmt.Sprintf(`{"template_id":%q,"title":"Copy","slug":"fork-copy","data":{},"published":true,"fork_id":%q}`, tmpl, fork) + rr := sendJSON(router, "lc_writer", "POST", "/api/v1/content", body) + if rr.Code != http.StatusCreated { + t.Fatalf("create in fork: %d %s", rr.Code, rr.Body.String()) + } + var created models.Content + json.Unmarshal(rr.Body.Bytes(), &created) + if created.Published { + t.Error("a fork copy was created published") + } + + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/content/"+created.ID.Hex(), `{"published":true}`); rr.Code != http.StatusOK { + t.Fatalf("update copy: %d %s", rr.Code, rr.Body.String()) + } + if _, published := pagePublished(t, db, "fork-copy"); published { + t.Error("a fork copy was flagged published") + } +} + +func TestPublishPermission_ImportsRequireIt(t *testing.T) { + a, _, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + + cases := map[string]string{ + "/api/v1/imports/markdown": `{"pages":[{"filename":"a.md","content":"# A"}],"auto_publish":true}`, + "/api/v1/imports/csv": `{"csv_data":"title\nA\n","title_column":"title","auto_publish":true}`, + "/api/v1/imports/sources": `{"name":"Feed","url":"https://example.org/feed","auto_publish":true}`, + } + for target, body := range cases { + if rr := sendJSON(router, "lc_writer", "POST", target, body); rr.Code != http.StatusForbidden { + t.Errorf("%s: %d %s", target, rr.Code, rr.Body.String()) + } + } + + ctx := context.Background() + draftSource := &models.ImportSource{Name: "Drafts", URL: "https://example.org/a", Schedule: "daily", Active: true} + if err := a.importService.CreateSource(ctx, draftSource); err != nil { + t.Fatalf("CreateSource: %v", err) + } + if rr := sendJSON(router, "lc_writer", "PUT", "/api/v1/imports/sources/"+draftSource.ID.Hex(), `{"auto_publish":true}`); rr.Code != http.StatusForbidden { + t.Errorf("turning on auto-publish: %d %s", rr.Code, rr.Body.String()) + } + + publishing := &models.ImportSource{Name: "Live", URL: "https://example.org/b", Schedule: "daily", Active: true, AutoPublish: true} + if err := a.importService.CreateSource(ctx, publishing); err != nil { + t.Fatalf("CreateSource: %v", err) + } + if rr := sendJSON(router, "lc_writer", "POST", "/api/v1/imports/sources/"+publishing.ID.Hex()+"/trigger", ``); rr.Code != http.StatusForbidden { + t.Errorf("triggering an auto-publishing source: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestMergePublishNew_RequiresPublish(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, map[string]*auth.SessionUser{ + "lc_merger": keyCaller("merger", models.RoleAdmin, auth.PermForkMerge), + }) + fork := createTestFork(t, db, "publish-new").Hex() + + if rr := sendJSON(router, "lc_merger", "POST", "/api/v1/forks/"+fork+"/merge", `{"publish_new":true}`); rr.Code != http.StatusForbidden { + t.Errorf("publish_new without content.publish: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestUploadAsset_NeverReadsTheServersDisk(t *testing.T) { + a, _, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + secret := filepath.Join(t.TempDir(), "secrets.txt") + if err := os.WriteFile(secret, []byte("do not leak"), 0o600); err != nil { + t.Fatalf("WriteFile: %v", err) + } + + body := fmt.Sprintf(`{"filename":"x.txt","serve_path":"/assets/x.txt","file_path":%q}`, secret) + if rr := sendJSON(router, "lc_editor", "POST", "/api/v1/assets", body); rr.Code != http.StatusBadRequest { + t.Errorf("file_path upload: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestStampProvenance(t *testing.T) { + run := func(user *auth.SessionUser, session string) (services.Provenance, string) { + var prov services.Provenance + var email string + handler := StampProvenance(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + prov, _ = services.ProvenanceFromContext(r.Context()) + email = services.EditorEmailFromContext(r.Context()) + })) + req := httptest.NewRequest("POST", "/api/v1/content", nil) + if session != "" { + req.Header.Set("X-Agent-Session", session) + } + if user != nil { + req = req.WithContext(middleware.InjectAPIUser(req.Context(), user)) + } + handler.ServeHTTP(httptest.NewRecorder(), req) + return prov, email + } + + if prov, _ := run(&auth.SessionUser{Email: "a@x", ViaAPIKey: true}, ""); prov.Actor != "human" { + t.Errorf("plain API key: actor %q", prov.Actor) + } + if prov, email := run(&auth.SessionUser{Email: "a@x", ViaAPIKey: true}, "agent-1"); prov.Actor != "agent" || prov.AgentSession != "agent-1" || email != "a@x" { + t.Errorf("session header: %+v, %q", prov, email) + } + if prov, _ := run(&auth.SessionUser{Email: "a@x", ViaOAuth: true}, ""); prov.Actor != "agent" { + t.Errorf("OAuth connection: actor %q", prov.Actor) + } +} + +// --- end to end: a real OAuth connection through /mcp to the real REST API --- + +type mcpEnvironment struct { + url string + db *database.DB + users *services.UserService + oauth *services.OAuthService +} + +const mcpTestBaseURL = "https://cms.example.com" + +func newMCPEnvironment(t *testing.T) *mcpEnvironment { + t.Helper() + a, db, cleanup := newTestAPIHandler(t) + t.Cleanup(cleanup) + + users := services.NewUserService(db) + oauth := services.NewOAuthService(db) + resolver := auth.NewCredentialResolver(users, services.NewAPIKeyService(db), oauth, services.MCPResourceURL(mcpTestBaseURL), nil) + apiAuth := middleware.NewAPIAuth(resolver.ResolveAPIKey) + apiAuth.SetOAuth(resolver.ResolveOAuthToken, mcpTestBaseURL+"/.well-known/oauth-protected-resource") + + r := mux.NewRouter() + apiv1 := a.MountAPI(r, apiAuth) + mcpRoute := r.PathPrefix("/mcp").Subrouter() + mcpRoute.Use(apiAuth.MCPMiddleware) + mcpRoute.Handle("", lightmcp.NewHTTPHandler(apiv1, "")) + + srv := httptest.NewServer(r) + t.Cleanup(srv.Close) + return &mcpEnvironment{url: srv.URL, db: db, users: users, oauth: oauth} +} + +// connect signs person in through the OAuth service and returns the access +// token and grant. +func (e *mcpEnvironment) connect(t *testing.T, person *models.User) (string, *models.OAuthGrant) { + t.Helper() + ctx := context.Background() + client, _, err := e.oauth.RegisterClient(ctx, "Test App", []string{"http://localhost/cb"}) + if err != nil { + t.Fatalf("RegisterClient: %v", err) + } + grant, err := e.oauth.SaveGrant(ctx, client, person.ID, services.MCPResourceURL(mcpTestBaseURL)) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + const ( + verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" // S256 of verifier (RFC 7636 appendix B) + ) + code, err := e.oauth.CreateAuthCode(ctx, grant, "http://localhost/cb", challenge, "S256") + if err != nil { + t.Fatalf("CreateAuthCode: %v", err) + } + access, _, _, err := e.oauth.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) + if err != nil { + t.Fatalf("ExchangeAuthCode: %v", err) + } + return access, grant +} + +func (e *mcpEnvironment) person(t *testing.T, email, role string) *models.User { + t.Helper() + user, err := e.users.CreateUserWithHash(context.Background(), email, email, role, "unused", false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + return user +} + +type tokenTransport struct{ token string } + +func (b tokenTransport) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.Header.Set("Authorization", "Bearer "+b.token) + return http.DefaultTransport.RoundTrip(r) +} + +func (e *mcpEnvironment) session(t *testing.T, token string) *mcpsdk.ClientSession { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "test", Version: "1"}, nil) + session, err := client.Connect(ctx, &mcpsdk.StreamableClientTransport{ + Endpoint: e.url + "/mcp", + HTTPClient: &http.Client{Transport: tokenTransport{token: token}}, + MaxRetries: -1, + }, nil) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { session.Close() }) + return session +} + +func callTool(t *testing.T, session *mcpsdk.ClientSession, name string, args map[string]interface{}) *mcpsdk.CallToolResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + result, err := session.CallTool(ctx, &mcpsdk.CallToolParams{Name: name, Arguments: args}) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + return result +} + +func toolText(result *mcpsdk.CallToolResult) string { + var b strings.Builder + for _, c := range result.Content { + if text, ok := c.(*mcpsdk.TextContent); ok { + b.WriteString(text.Text) + } + } + return b.String() +} + +func TestEndToEnd_OAuthConnectionHasThePersonsRole(t *testing.T) { + env := newMCPEnvironment(t) + env.person(t, "admin@example.com", models.RoleAdmin) // an admin exists, but nobody here signs in as one + tmpl := seedTemplate(t, env.db, "Page", "page").Hex() + + createArgs := func(slug string) map[string]interface{} { + return map[string]interface{}{"template_id": tmpl, "title": "T", "slug": slug, "data": map[string]interface{}{}} + } + + viewerToken, _ := env.connect(t, env.person(t, "viewer@example.com", models.RoleViewer)) + viewer := env.session(t, viewerToken) + + if result := callTool(t, viewer, "list_templates", map[string]interface{}{}); result.IsError { + t.Fatalf("a viewer should be able to read: %s", toolText(result)) + } + result := callTool(t, viewer, "create_content", createArgs("by-viewer")) + if !result.IsError || !strings.Contains(toolText(result), "insufficient permissions") { + t.Fatalf("a viewer wrote through OAuth: %s", toolText(result)) + } + if found, _ := pagePublished(t, env.db, "by-viewer"); found { + t.Fatal("the viewer's page exists") + } + + editorToken, _ := env.connect(t, env.person(t, "editor@example.com", models.RoleEditor)) + editor := env.session(t, editorToken) + if result := callTool(t, editor, "create_content", createArgs("by-editor")); result.IsError { + t.Fatalf("an editor should be able to create: %s", toolText(result)) + } + result = callTool(t, editor, "update_site_config", map[string]interface{}{"title_template": "Taken over"}) + if !result.IsError || !strings.Contains(toolText(result), "insufficient permissions") { + t.Fatalf("an editor changed site configuration: %s", toolText(result)) + } +} + +func TestEndToEnd_ChangesAreRecordedAsTheAgentAndTheConnection(t *testing.T) { + env := newMCPEnvironment(t) + token, grant := env.connect(t, env.person(t, "editor@example.com", models.RoleEditor)) + tmpl := seedTemplate(t, env.db, "Page", "page").Hex() + session := env.session(t, token) + + result := callTool(t, session, "create_content", map[string]interface{}{ + "template_id": tmpl, "title": "T", "slug": "agent-made", "data": map[string]interface{}{}, + }) + if result.IsError { + t.Fatalf("create_content: %s", toolText(result)) + } + + ctx := context.Background() + var version models.ContentVersion + var content models.Content + if err := env.db.FindOne(ctx, "content", bson.M{"slug": "agent-made"}, &content); err != nil { + t.Fatalf("finding page: %v", err) + } + if err := env.db.FindOne(ctx, "content_versions", bson.M{"content_id": content.ID}, &version); err != nil { + t.Fatalf("finding version: %v", err) + } + if version.Actor != "agent" || !strings.HasPrefix(version.AgentSession, "agent-") { + t.Errorf("version recorded actor %q, session %q", version.Actor, version.AgentSession) + } + + // The audit entry is written asynchronously. + deadline := time.Now().Add(5 * time.Second) + for { + var entry models.AuditLog + err := env.db.FindOne(ctx, "audit_logs", bson.M{"action": "content.create", "resource_id": content.ID.Hex()}, &entry) + if err == nil { + if entry.Credential != "oauth:"+grant.ID.Hex() || entry.UserEmail != "editor@example.com" || entry.AgentSession == "" { + t.Errorf("audit entry: %+v", entry) + } + return + } + if time.Now().After(deadline) { + t.Fatalf("no audit entry: %v", err) + } + time.Sleep(50 * time.Millisecond) + } +} + +func TestEndToEnd_RevokingAConnectionStopsItAtOnce(t *testing.T) { + env := newMCPEnvironment(t) + token, grant := env.connect(t, env.person(t, "editor@example.com", models.RoleEditor)) + session := env.session(t, token) + if result := callTool(t, session, "list_templates", map[string]interface{}{}); result.IsError { + t.Fatalf("list_templates: %s", toolText(result)) + } + + if err := env.oauth.RevokeGrant(context.Background(), grant.ID); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if _, err := session.CallTool(ctx, &mcpsdk.CallToolParams{Name: "list_templates", Arguments: map[string]interface{}{}}); err == nil { + t.Error("a revoked connection's open session still works") + } +} + +func TestEndToEnd_OAuthTokenRefusedAtTheRESTAPI(t *testing.T) { + env := newMCPEnvironment(t) + token, _ := env.connect(t, env.person(t, "admin@example.com", models.RoleAdmin)) + + req, _ := http.NewRequest("GET", env.url+"/api/v1/content", nil) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("GET: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("got %d, want 401", resp.StatusCode) + } +} diff --git a/internal/handlers/api_imports.go b/internal/handlers/api_imports.go index ddbb8c2..cfb7b77 100644 --- a/internal/handlers/api_imports.go +++ b/internal/handlers/api_imports.go @@ -77,6 +77,9 @@ func (a *APIHandler) APICreateImportSource(w http.ResponseWriter, r *http.Reques a.jsonError(w, http.StatusBadRequest, "url is required") return } + if body.AutoPublish && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } schedule := body.Schedule if schedule == "" { @@ -186,6 +189,9 @@ func (a *APIHandler) APIUpdateImportSource(w http.ResponseWriter, r *http.Reques updates["folder_path"] = *body.FolderPath } if body.AutoPublish != nil { + if *body.AutoPublish && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } updates["auto_publish"] = *body.AutoPublish } if body.Schedule != nil { @@ -263,6 +269,15 @@ func (a *APIHandler) APITriggerImportSource(w http.ResponseWriter, r *http.Reque return } + src, err := a.importService.GetSource(r.Context(), id) + if err != nil { + a.jsonError(w, http.StatusNotFound, "import source not found") + return + } + if src.AutoPublish && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } + triggeredBy := "api" if user := a.getAPIUser(r); user != nil { triggeredBy = user.Email @@ -310,6 +325,9 @@ func (a *APIHandler) APIImportMarkdown(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "pages is required and must be non-empty") return } + if body.AutoPublish && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } defaultFolder := body.DefaultFolder if defaultFolder == "" { @@ -379,6 +397,9 @@ func (a *APIHandler) APIImportCSV(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "title_column is required") return } + if body.AutoPublish && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } _, records, err := importer.ParseCSV(strings.NewReader(body.CSVData)) if err != nil { diff --git a/internal/handlers/api_routes.go b/internal/handlers/api_routes.go new file mode 100644 index 0000000..7c61876 --- /dev/null +++ b/internal/handlers/api_routes.go @@ -0,0 +1,236 @@ +package handlers + +import ( + "net/http" + + "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/middleware" + "github.com/metavert-io/lightcms/v7/internal/services" + + "github.com/gorilla/mux" +) + +// StampProvenance records who is behind each API change on the request context +// (change provenance and version attribution). An agent is identified by an +// OAuth connection, or by the X-Agent-Session header, which the MCP endpoint +// sets itself and the stdio MCP client sends; from any other caller that header +// is only a label. +func StampProvenance(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, _ := auth.UserFromAPIContext(ctx) + prov := services.Provenance{Actor: "human", Via: "api"} + if sess := r.Header.Get("X-Agent-Session"); sess != "" { + prov.Actor = "agent" + prov.AgentSession = sess + } + if user != nil && user.ViaOAuth { + prov.Actor = "agent" + } + ctx = services.WithProvenance(ctx, prov) + if user != nil { + ctx = services.WithEditorEmail(ctx, user.Email) + } + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// MountAPI creates the /api/v1 subrouter on r with its middleware and every +// REST route, and returns it. +func (a *APIHandler) MountAPI(r *mux.Router, apiAuth *middleware.APIAuth) *mux.Router { + apiv1 := r.PathPrefix("/api/v1").Subrouter() + apiv1.Use(apiAuth.Middleware) + apiv1.Use(middleware.APIBurstRateLimit) // per-credential burst limit (20 req/s) + apiv1.Use(middleware.APIRateLimit) // per-credential sliding-window rate limit (300 req/min) + apiv1.Use(middleware.APIBodySizeLimit) // cap request body at 10 MiB to prevent memory exhaustion + apiv1.Use(StampProvenance) + + // Content + apiv1.HandleFunc("/content", a.APIListContent).Methods("GET") + apiv1.HandleFunc("/content", a.APICreateContent).Methods("POST") + apiv1.HandleFunc("/content/by-path", a.APIGetContentByPath).Methods("GET") + apiv1.HandleFunc("/content/by-path", a.APIUpdateContentByPath).Methods("PUT") + apiv1.HandleFunc("/content/backlinks", a.APIGetBacklinks).Methods("GET") + apiv1.HandleFunc("/content/batch-publish", a.APIBatchPublishContent).Methods("POST") + apiv1.Handle("/content/bulk-create", middleware.BulkUpdateLimiter()(http.HandlerFunc(a.APIBulkCreateContent))).Methods("POST") + apiv1.Handle("/content/bulk-update", middleware.BulkUpdateLimiter()(http.HandlerFunc(a.APIBulkUpdateContent))).Methods("POST") + apiv1.Handle("/content/bulk-field-op", middleware.BulkUpdateLimiter()(http.HandlerFunc(a.APIBulkFieldOperation))).Methods("POST") + apiv1.Handle("/content/export", middleware.ExportLimiter()(http.HandlerFunc(a.APIExportContent))).Methods("POST") + apiv1.HandleFunc("/content/{id}", a.APIGetContent).Methods("GET") + apiv1.HandleFunc("/content/{id}", a.APIUpdateContent).Methods("PUT") + apiv1.HandleFunc("/content/{id}", a.APIDeleteContent).Methods("DELETE") + apiv1.HandleFunc("/content/{id}/restore", a.APIRestoreContent).Methods("POST") + apiv1.HandleFunc("/content/{id}/publish", a.APIPublishContent).Methods("POST") + apiv1.HandleFunc("/content/{id}/unpublish", a.APIUnpublishContent).Methods("POST") + apiv1.HandleFunc("/content/{id}/preview", a.APIPreviewContent).Methods("GET", "POST") + apiv1.HandleFunc("/content/{id}/versions", a.APIListContentVersions).Methods("GET") + apiv1.HandleFunc("/content/{id}/versions/{version}", a.APIGetContentVersion).Methods("GET") + apiv1.HandleFunc("/content/{id}/versions/{version}/revert", a.APIRevertContentVersion).Methods("POST") + + // Templates + apiv1.HandleFunc("/templates", a.APIListTemplates).Methods("GET") + apiv1.HandleFunc("/templates", a.APICreateTemplate).Methods("POST") + apiv1.HandleFunc("/templates/{id}", a.APIGetTemplate).Methods("GET") + apiv1.HandleFunc("/templates/{id}", a.APIUpdateTemplate).Methods("PUT") + apiv1.HandleFunc("/templates/{id}", a.APIDeleteTemplate).Methods("DELETE") + + // Assets + apiv1.HandleFunc("/assets", a.APIListAssets).Methods("GET") + apiv1.HandleFunc("/assets", a.APIUploadAsset).Methods("POST") + apiv1.Handle("/assets/from-url", middleware.AssetFromURLLimiter()(http.HandlerFunc(a.APIUploadAssetFromURL))).Methods("POST") + apiv1.HandleFunc("/assets/folders", a.APIListAssetFolders).Methods("GET") + apiv1.HandleFunc("/assets/by-path", a.APIGetAssetByPath).Methods("GET") + apiv1.HandleFunc("/assets/{id}", a.APIGetAsset).Methods("GET") + apiv1.HandleFunc("/assets/{id}", a.APIDeleteAsset).Methods("DELETE") + + // Theme + apiv1.HandleFunc("/theme", a.APIGetTheme).Methods("GET") + apiv1.HandleFunc("/theme", a.APIUpdateTheme).Methods("PUT") + apiv1.HandleFunc("/theme/versions", a.APIListThemeVersions).Methods("GET") + apiv1.HandleFunc("/theme/versions/{version}", a.APIGetThemeVersion).Methods("GET") + apiv1.HandleFunc("/theme/versions/{version}/revert", a.APIRevertThemeVersion).Methods("POST") + apiv1.HandleFunc("/theme/versions/{version}/pin", a.APIPinThemeVersion).Methods("POST") + apiv1.HandleFunc("/theme/versions/{version}/unpin", a.APIPinThemeVersion).Methods("POST") + + // Site Config + apiv1.HandleFunc("/config", a.APIGetSiteConfig).Methods("GET") + apiv1.HandleFunc("/config", a.APIUpdateSiteConfig).Methods("PUT") + + // Redirects + apiv1.HandleFunc("/redirects", a.APIListRedirects).Methods("GET") + apiv1.HandleFunc("/redirects", a.APICreateRedirect).Methods("POST") + apiv1.HandleFunc("/redirects/{id}", a.APIGetRedirect).Methods("GET") + apiv1.HandleFunc("/redirects/{id}", a.APIUpdateRedirect).Methods("PUT") + apiv1.HandleFunc("/redirects/{id}", a.APIDeleteRedirect).Methods("DELETE") + + // Folders + apiv1.HandleFunc("/folders", a.APIListFolders).Methods("GET") + apiv1.HandleFunc("/folders", a.APICreateFolder).Methods("POST") + apiv1.HandleFunc("/folders/{id}", a.APIGetFolder).Methods("GET") + apiv1.HandleFunc("/folders/{id}", a.APIDeleteFolder).Methods("DELETE") + + // Collections + apiv1.HandleFunc("/collections", a.APIListCollections).Methods("GET") + apiv1.HandleFunc("/collections", a.APICreateCollection).Methods("POST") + apiv1.HandleFunc("/collections/{id}", a.APIGetCollection).Methods("GET") + apiv1.HandleFunc("/collections/{id}", a.APIUpdateCollection).Methods("PUT") + apiv1.HandleFunc("/collections/{id}", a.APIDeleteCollection).Methods("DELETE") + + // Search + apiv1.HandleFunc("/search", a.APISearchContent).Methods("GET") + apiv1.HandleFunc("/search-replace/preview", a.APISearchReplacePreview).Methods("POST") + apiv1.Handle("/search-replace/execute", middleware.SearchReplaceExecuteLimiter()(http.HandlerFunc(a.APISearchReplaceExecute))).Methods("POST") + apiv1.HandleFunc("/search-replace/scoped/preview", a.APIScopedSearchReplacePreview).Methods("POST") + apiv1.Handle("/search-replace/scoped/execute", middleware.SearchReplaceExecuteLimiter()(http.HandlerFunc(a.APIScopedSearchReplaceExecute))).Methods("POST") + + // End-user search (authenticated API) + apiv1.HandleFunc("/end-user-search", a.APIEndUserSearch).Methods("GET") + apiv1.HandleFunc("/end-user-search/suggest", a.APIEndUserSearchSuggest).Methods("GET") + apiv1.Handle("/reindex-embeddings", middleware.ReindexLimiter()(http.HandlerFunc(a.APIReindexEmbeddings))).Methods("POST") + + // API Keys + apiv1.HandleFunc("/api-keys", a.APIListAPIKeys).Methods("GET") + apiv1.HandleFunc("/api-keys", a.APICreateAPIKey).Methods("POST") + apiv1.HandleFunc("/api-keys/{id}", a.APIDeleteAPIKey).Methods("DELETE") + + // Snippets + apiv1.HandleFunc("/snippets", a.APIListSnippets).Methods("GET") + apiv1.HandleFunc("/snippets", a.APICreateSnippet).Methods("POST") + apiv1.HandleFunc("/snippets/{id}", a.APIGetSnippet).Methods("GET") + apiv1.HandleFunc("/snippets/{id}", a.APIUpdateSnippet).Methods("PUT") + apiv1.HandleFunc("/snippets/{id}", a.APIDeleteSnippet).Methods("DELETE") + + // Forks + apiv1.HandleFunc("/forks", a.APIListForks).Methods("GET") + apiv1.HandleFunc("/forks", a.APICreateFork).Methods("POST") + apiv1.HandleFunc("/forks/{id}", a.APIGetFork).Methods("GET") + apiv1.HandleFunc("/forks/{id}", a.APIDeleteFork).Methods("DELETE") + apiv1.HandleFunc("/forks/{id}/fork-page", a.APIForkPage).Methods("POST") + apiv1.HandleFunc("/forks/{id}/pages", a.APIListForkPages).Methods("GET") + apiv1.HandleFunc("/forks/{id}/pages/{pageID}", a.APIRemoveForkPage).Methods("DELETE") + apiv1.HandleFunc("/forks/{id}/diff", a.APIForkDiff).Methods("GET") + + // Agent session ledger & rollback + apiv1.HandleFunc("/agent-sessions/{id}/changes", a.APIAgentSessionChanges).Methods("GET") + apiv1.HandleFunc("/agent-sessions/{id}/rollback", a.APIAgentSessionRollback).Methods("POST") + + // Maintenance scans (self-maintaining site routines) + apiv1.HandleFunc("/maintenance/report", a.APIMaintenanceReport).Methods("GET") + apiv1.HandleFunc("/indexnow", a.APIIndexNowStatus).Methods("GET") + apiv1.HandleFunc("/seo", a.APIGetSEO).Methods("GET") + apiv1.HandleFunc("/seo", a.APIUpdateSEO).Methods("PUT") + apiv1.HandleFunc("/analytics/ai", a.APIAITraffic).Methods("GET") + apiv1.HandleFunc("/indexnow", a.APIIndexNowUpdate).Methods("PUT") + apiv1.HandleFunc("/indexnow/submit", a.APIIndexNowSubmit).Methods("POST") + apiv1.HandleFunc("/maintenance/scan", a.APIMaintenanceScan).Methods("POST") + apiv1.HandleFunc("/maintenance/backfill-published-dates", a.APIBackfillPublishedDates).Methods("POST") + apiv1.HandleFunc("/maintenance/repair-fork-damage", a.APIRepairForkDamage).Methods("POST") + apiv1.HandleFunc("/forks/{id}/merge", a.APIMergeFork).Methods("POST") + apiv1.HandleFunc("/forks/{id}/archive", a.APIArchiveFork).Methods("POST") + apiv1.HandleFunc("/forks/{id}/purge-copies", a.APIPurgeForkCopies).Methods("POST") + + // Regenerate (rate-limited: 2/min — full rebuild is expensive) + apiv1.Handle("/regenerate", middleware.RegenerateLimiter()(http.HandlerFunc(a.APIRegenerateAllContent))).Methods("POST") + + // Webhooks API + apiv1.HandleFunc("/webhooks", a.APIListWebhooks).Methods("GET") + apiv1.HandleFunc("/webhooks", a.APICreateWebhook).Methods("POST") + apiv1.HandleFunc("/webhooks/{id}", a.APIUpdateWebhook).Methods("PUT") + apiv1.HandleFunc("/webhooks/{id}", a.APIDeleteWebhook).Methods("DELETE") + apiv1.HandleFunc("/webhooks/{id}/regenerate-secret", a.APIRegenerateWebhookSecret).Methods("POST") + apiv1.HandleFunc("/webhooks/{id}/deliveries", a.APIListWebhookDeliveries).Methods("GET") + + // Content locks API + apiv1.HandleFunc("/content/{id}/lock", a.APIGetContentLock).Methods("GET") + apiv1.HandleFunc("/content/{id}/lock", a.APIAcquireContentLock).Methods("POST") + apiv1.HandleFunc("/content/{id}/lock", a.APIReleaseContentLock).Methods("DELETE") + apiv1.HandleFunc("/content/{id}/lock/force", a.APIForceUnlockContent).Methods("POST") + + // Scheduled publish API + apiv1.HandleFunc("/content/scheduled", a.APIListScheduledContent).Methods("GET") + apiv1.HandleFunc("/content/{id}/schedule", a.APIScheduleContentPublish).Methods("POST") + + // Audit log API + apiv1.HandleFunc("/audit", a.APIListAuditLogs).Methods("GET") + + // Link check API + apiv1.HandleFunc("/link-check", a.APIStartLinkCheck).Methods("POST") + apiv1.HandleFunc("/link-check/{id}", a.APIGetLinkCheckJob).Methods("GET") + + // Import pipeline + apiv1.HandleFunc("/imports/sources", a.APIListImportSources).Methods("GET") + apiv1.HandleFunc("/imports/sources", a.APICreateImportSource).Methods("POST") + apiv1.HandleFunc("/imports/sources/{id}", a.APIUpdateImportSource).Methods("PUT") + apiv1.HandleFunc("/imports/sources/{id}", a.APIDeleteImportSource).Methods("DELETE") + apiv1.HandleFunc("/imports/sources/{id}/trigger", a.APITriggerImportSource).Methods("POST") + apiv1.HandleFunc("/imports/markdown", a.APIImportMarkdown).Methods("POST") + apiv1.HandleFunc("/imports/csv", a.APIImportCSV).Methods("POST") + apiv1.HandleFunc("/imports/jobs", a.APIListImportJobs).Methods("GET") + apiv1.HandleFunc("/imports/jobs/{id}", a.APIGetImportJob).Methods("GET") + apiv1.HandleFunc("/imports/jobs/{id}/cancel", a.APICancelImportJob).Methods("POST") + + // Comments API + apiv1.HandleFunc("/content/{id}/comments", a.APIListComments).Methods("GET") + apiv1.Handle("/content/{id}/comments", middleware.CommentCreateLimiter()(http.HandlerFunc(a.APICreateComment))).Methods("POST") + apiv1.HandleFunc("/content/{id}/comments/{cid}", a.APIDeleteComment).Methods("DELETE") + apiv1.HandleFunc("/content/{id}/submit-approval", a.APISubmitForApproval).Methods("POST") + + // Users list (for @mention and approver search in UI) + apiv1.HandleFunc("/users", a.APIListUsers).Methods("GET") + + // Approval workflows API + apiv1.HandleFunc("/approval-workflows", a.APIListApprovalWorkflows).Methods("GET") + apiv1.HandleFunc("/approval-workflows", a.APICreateApprovalWorkflow).Methods("POST") + apiv1.HandleFunc("/approval-workflows/{id}", a.APIGetApprovalWorkflow).Methods("GET") + apiv1.HandleFunc("/approval-workflows/{id}", a.APIUpdateApprovalWorkflow).Methods("PUT") + apiv1.HandleFunc("/approval-workflows/{id}", a.APIDeleteApprovalWorkflow).Methods("DELETE") + + // Approval requests API + apiv1.HandleFunc("/approval-requests", a.APIListApprovalRequests).Methods("GET") + apiv1.HandleFunc("/approval-requests/{id}", a.APIGetApprovalRequest).Methods("GET") + apiv1.HandleFunc("/approval-requests/{id}/approve", a.APIApproveRequest).Methods("POST") + apiv1.HandleFunc("/approval-requests/{id}/reject", a.APIRejectRequest).Methods("POST") + apiv1.HandleFunc("/approval-requests/{id}/cancel", a.APICancelRequest).Methods("POST") + + return apiv1 +} diff --git a/internal/handlers/fixes_743_test.go b/internal/handlers/fixes_743_test.go index c093405..b8f8877 100644 --- a/internal/handlers/fixes_743_test.go +++ b/internal/handlers/fixes_743_test.go @@ -654,13 +654,13 @@ func TestRemovedAdminRoutes(t *testing.T) { t.Errorf("POST %s: %d, want 404/405 (the route was removed)", target, rr.Code) } } - src, err := os.ReadFile("../../cmd/server/main.go") + src, err := os.ReadFile("api_routes.go") if err != nil { - t.Fatalf("read main.go: %v", err) + t.Fatalf("read api_routes.go: %v", err) } for _, route := range []string{`"/content/{id}/lock"`, `"/content/{id}/lock/force"`} { if !strings.Contains(string(src), route) { - t.Errorf("main.go no longer registers the lock API route %s", route) + t.Errorf("api_routes.go no longer registers the lock API route %s", route) } } } diff --git a/internal/handlers/testhelper_test.go b/internal/handlers/testhelper_test.go index 1ce3504..c897aef 100644 --- a/internal/handlers/testhelper_test.go +++ b/internal/handlers/testhelper_test.go @@ -156,7 +156,7 @@ func cleanupCollections(t *testing.T, db *database.DB) { "content", "content_versions", "templates", "folders", "collections", "settings", "theme_versions", "assets", "api_keys", "redirects", "snippets", "users", "audit_logs", "contact_messages", "login_attempts", - "oauth_clients", "user_activity", + "oauth_clients", "oauth_grants", "user_activity", // Forks carry a preview token and webhooks fire on content events: // leftovers from an earlier test (or run) change what a later one sees. "content_forks", "webhooks", "webhook_deliveries", "content_comments", diff --git a/internal/mcp/asset_tools.go b/internal/mcp/asset_tools.go index 93de266..d58d036 100644 --- a/internal/mcp/asset_tools.go +++ b/internal/mcp/asset_tools.go @@ -26,7 +26,7 @@ type UploadAssetInput struct { Filename string `json:"filename" jsonschema:"Original filename with extension,required"` ServePath string `json:"serve_path" jsonschema:"URL path where file will be served (e.g., /images/logo.png),required"` Description string `json:"description,omitempty" jsonschema:"Optional description of the asset"` - FilePath string `json:"file_path,omitempty" jsonschema:"Absolute local filesystem path to read the file from. Preferred over data_base64 for large files — avoids MCP transport size limits."` + FilePath string `json:"file_path,omitempty" jsonschema:"Absolute local filesystem path to read the file from (only when this MCP server runs on your own machine). Preferred over data_base64 for large files — avoids MCP transport size limits."` DataBase64 string `json:"data_base64,omitempty" jsonschema:"Base64-encoded file content. Use for small files (<100KB). For larger files, prefer file_path."` } @@ -111,8 +111,8 @@ func (s *Server) registerAssetTools() { Description: `Upload or replace an asset in the asset library. Re-uploading to the same serve_path replaces the existing file in place — no need to delete first. Provide file content via one of: -- file_path: Absolute local path to the file (preferred for files >100KB — avoids MCP transport size limits) -- data_base64: Base64-encoded file content (fine for small files) +- file_path: Absolute local path to the file (preferred for files >100KB — avoids MCP transport size limits). Only available when this MCP server runs on your own machine (the stdio binary), not over a hosted /mcp connection. +- data_base64: Base64-encoded file content (fine for small files; required over a hosted /mcp connection) Validates file type and MIME type for security.`, Annotations: &mcp.ToolAnnotations{ @@ -134,6 +134,9 @@ Validates file type and MIME type for security.`, } if args.FilePath != "" { + if !s.localFiles { + return errorResult(fmt.Errorf("file_path is only available when the MCP server runs on your own machine; send the file as data_base64")), nil, nil + } // Read file locally and base64-encode it — avoids MCP transport size limits fileData, err := os.ReadFile(args.FilePath) if err != nil { diff --git a/internal/mcp/http_handler.go b/internal/mcp/http_handler.go index 37b36f2..c1a22b0 100644 --- a/internal/mcp/http_handler.go +++ b/internal/mcp/http_handler.go @@ -1,35 +1,160 @@ package mcp import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log" "net/http" - "strings" + "runtime/debug" + "time" "github.com/metavert-io/lightcms/v7/internal/apiclient" + "github.com/metavert-io/lightcms/v7/internal/middleware" + sdkauth "github.com/modelcontextprotocol/go-sdk/auth" "github.com/modelcontextprotocol/go-sdk/mcp" ) -// NewHTTPHandler creates an HTTP handler for the MCP Streamable HTTP transport. -// Each session gets its own MCP server backed by an API client using the -// caller's API key (extracted from the Authorization header, already validated -// by the API auth middleware). -func NewHTTPHandler(serverPort string) http.Handler { - return mcp.NewStreamableHTTPHandler( - func(r *http.Request) *mcp.Server { - apiKey := extractBearerToken(r) - client := apiclient.New("http://localhost:"+serverPort, apiKey) - server := NewServer(client) - return server.MCPServer() +const ( + // inProcessBaseURL is never dialled: requests go straight to the router. + inProcessBaseURL = "http://lightcms.internal" + // callerExtraKey is where a request's caller travels inside TokenInfo. + callerExtraKey = "lightcms.caller" + // callerInfoLifetime satisfies the SDK, which refuses a TokenInfo without an + // expiry. The credential was checked moments ago, and is again on every + // request; API keys have no expiry of their own to report. + callerInfoLifetime = time.Minute +) + +// callerContextKey carries the MCP request's caller to the in-process transport. +type callerContextKey struct{} + +// NewHTTPHandler creates the handler for the MCP Streamable HTTP endpoint. It +// must run behind APIAuth.MCPMiddleware, which authenticates every request. +// +// Each MCP session gets its own server. Its tools call api, the REST router, in +// this process, as whoever sent the current MCP request, so no credential is +// held by the session or sent over a socket. The session is bound to the +// credential that opened it: the SDK refuses a request from any other. +func NewHTTPHandler(api http.Handler, resourceMetadataURL string) http.Handler { + transport := &inProcessTransport{api: api} + streamable := mcp.NewStreamableHTTPHandler( + func(*http.Request) *mcp.Server { + client := apiclient.NewWithTransport(inProcessBaseURL, transport) + client.SetAgentSession(apiclient.NewAgentSessionID()) + server := NewServer(client).MCPServer() + server.AddReceivingMiddleware(carryCaller) + return server }, nil, ) + return sdkauth.RequireBearerToken(callerTokenInfo, &sdkauth.RequireBearerTokenOptions{ + ResourceMetadataURL: resourceMetadataURL, + })(streamable) +} + +// callerTokenInfo is the SDK's token verifier. The credential has already been +// validated by APIAuth.MCPMiddleware, so this only reports the result: UserID +// turns on the SDK's session binding and Extra takes the caller to the tools. +func callerTokenInfo(ctx context.Context, _ string, _ *http.Request) (*sdkauth.TokenInfo, error) { + caller, _ := middleware.APIUserFromContext(ctx) + key := middleware.CredentialKeyFromContext(ctx) + if caller == nil || key == "" { + return nil, fmt.Errorf("%w: no authenticated caller", sdkauth.ErrInvalidToken) + } + return &sdkauth.TokenInfo{ + UserID: key, + Expiration: time.Now().Add(callerInfoLifetime), + Extra: map[string]any{callerExtraKey: caller}, + }, nil +} + +// carryCaller moves the caller from the SDK's per-request data into the context +// that tool and resource handlers pass to the API client. +func carryCaller(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { + if extra := req.GetExtra(); extra != nil && extra.TokenInfo != nil { + if caller := extra.TokenInfo.Extra[callerExtraKey]; caller != nil { + ctx = context.WithValue(ctx, callerContextKey{}, caller) + } + } + return next(ctx, method, req) + } +} + +// inProcessTransport serves API client requests by calling the REST router +// directly, as the caller of the MCP request they belong to. +type inProcessTransport struct { + api http.Handler +} + +// RoundTrip implements http.RoundTripper. +func (t *inProcessTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { + caller := req.Context().Value(callerContextKey{}) + if caller == nil { + return nil, errors.New("no authenticated caller for this MCP request") + } + + // A panic in a handler would otherwise reach the SDK's goroutine and take + // the whole server down; net/http only recovers its own. + defer func() { + if p := recover(); p != nil { + log.Printf("[MCP] panic serving %s %s: %v\n%s", req.Method, req.URL.Path, p, debug.Stack()) + resp, err = nil, errors.New("internal server error") + } + }() + + inner := req.Clone(middleware.WithInternalCaller(req.Context(), caller)) + inner.RequestURI = req.URL.RequestURI() + inner.RemoteAddr = "127.0.0.1:0" + if inner.Body == nil { + inner.Body = http.NoBody + } + + rec := &bufferedResponse{header: http.Header{}} + t.api.ServeHTTP(rec, inner) + return rec.response(req), nil +} + +// bufferedResponse is the http.ResponseWriter for an in-process call. +type bufferedResponse struct { + header http.Header + status int + body bytes.Buffer +} + +func (b *bufferedResponse) Header() http.Header { return b.header } + +func (b *bufferedResponse) WriteHeader(status int) { + if b.status == 0 { + b.status = status + } } -func extractBearerToken(r *http.Request) string { - auth := r.Header.Get("Authorization") - parts := strings.SplitN(auth, " ", 2) - if len(parts) == 2 && strings.EqualFold(parts[0], "Bearer") { - return parts[1] +func (b *bufferedResponse) Write(p []byte) (int, error) { + if b.status == 0 { + b.status = http.StatusOK + } + return b.body.Write(p) +} + +func (b *bufferedResponse) response(req *http.Request) *http.Response { + status := b.status + if status == 0 { + status = http.StatusOK + } + return &http.Response{ + Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), + StatusCode: status, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: b.header, + Body: io.NopCloser(&b.body), + ContentLength: int64(b.body.Len()), + Request: req, } - return "" } diff --git a/internal/mcp/http_handler_test.go b/internal/mcp/http_handler_test.go new file mode 100644 index 0000000..9b4f91b --- /dev/null +++ b/internal/mcp/http_handler_test.go @@ -0,0 +1,331 @@ +package mcp + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/metavert-io/lightcms/v7/internal/middleware" + + mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// testCaller is an authenticated caller, as the auth middleware produces. +type testCaller struct { + name string + credential string +} + +func (c *testCaller) CredentialKey() string { return c.credential } + +// fakeAPI is a REST API that records who each call ran as. +type fakeAPI struct { + mu sync.Mutex + callers []string + sessions []string + headers []http.Header + panics bool +} + +func (f *fakeAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + panics := f.panics + caller, _ := middleware.APIUserFromContext(r.Context()) + if c, ok := caller.(*testCaller); ok { + f.callers = append(f.callers, c.name) + } else { + f.callers = append(f.callers, "") + } + f.sessions = append(f.sessions, r.Header.Get("X-Agent-Session")) + f.headers = append(f.headers, r.Header.Clone()) + f.mu.Unlock() + if panics { + panic("handler blew up") + } + json.NewEncoder(w).Encode([]map[string]interface{}{}) +} + +func (f *fakeAPI) lastCaller() string { + f.mu.Lock() + defer f.mu.Unlock() + if len(f.callers) == 0 { + return "" + } + return f.callers[len(f.callers)-1] +} + +// newMCPTestServer builds the /mcp endpoint with real authentication in front +// and fake's REST API behind. Tokens: alice-token and bob-token are OAuth, +// lc_carol is an API key. +func newMCPTestServer(t *testing.T, fake *fakeAPI) *httptest.Server { + t.Helper() + apiAuth := middleware.NewAPIAuth(func(ctx context.Context, key string) (interface{}, error) { + if key == "lc_carol" { + return &testCaller{name: "carol", credential: "apikey:carol"}, nil + } + return nil, fmt.Errorf("invalid key") + }) + apiAuth.SetOAuth(func(ctx context.Context, token string) (interface{}, error) { + switch token { + case "alice-token": + return &testCaller{name: "alice", credential: "oauth:alice"}, nil + case "bob-token": + return &testCaller{name: "bob", credential: "oauth:bob"}, nil + } + return nil, fmt.Errorf("invalid token") + }, "https://example.com/.well-known/oauth-protected-resource") + + // The REST side authenticates in-process calls as the real server does. + rest := apiAuth.Middleware(fake) + srv := httptest.NewServer(apiAuth.MCPMiddleware(NewHTTPHandler(rest, "https://example.com/.well-known/oauth-protected-resource"))) + t.Cleanup(srv.Close) + return srv +} + +type bearerTransport struct { + token string + base http.RoundTripper +} + +func (b *bearerTransport) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.Header.Set("Authorization", "Bearer "+b.token) + return b.base.RoundTrip(r) +} + +func connectAs(t *testing.T, url, token string) *mcpsdk.ClientSession { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + t.Cleanup(cancel) + client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "test", Version: "1"}, nil) + session, err := client.Connect(ctx, &mcpsdk.StreamableClientTransport{ + Endpoint: url, + HTTPClient: &http.Client{Transport: &bearerTransport{token: token, base: http.DefaultTransport}}, + MaxRetries: -1, + }, nil) + if err != nil { + t.Fatalf("connect as %s: %v", token, err) + } + t.Cleanup(func() { session.Close() }) + return session +} + +func callListTemplates(t *testing.T, session *mcpsdk.ClientSession) *mcpsdk.CallToolResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + result, err := session.CallTool(ctx, &mcpsdk.CallToolParams{Name: "list_templates", Arguments: map[string]interface{}{}}) + if err != nil { + t.Fatalf("CallTool: %v", err) + } + return result +} + +func TestHTTPHandler_ToolCallsRunAsTheCaller(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + + callListTemplates(t, connectAs(t, srv.URL, "alice-token")) + if got := fake.lastCaller(); got != "alice" { + t.Errorf("OAuth call ran as %q, want alice", got) + } + + callListTemplates(t, connectAs(t, srv.URL, "bob-token")) + if got := fake.lastCaller(); got != "bob" { + t.Errorf("OAuth call ran as %q, want bob", got) + } + + callListTemplates(t, connectAs(t, srv.URL, "lc_carol")) + if got := fake.lastCaller(); got != "carol" { + t.Errorf("API key call ran as %q, want carol", got) + } +} + +func TestHTTPHandler_NoCredentialCrossesTheInternalCall(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + + callListTemplates(t, connectAs(t, srv.URL, "alice-token")) + fake.mu.Lock() + defer fake.mu.Unlock() + for _, h := range fake.headers { + if got := h.Get("Authorization"); got != "" { + t.Errorf("internal call carried Authorization %q", got) + } + } +} + +func TestHTTPHandler_EachSessionHasItsOwnAgentSession(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + + first := connectAs(t, srv.URL, "alice-token") + callListTemplates(t, first) + callListTemplates(t, first) + callListTemplates(t, connectAs(t, srv.URL, "alice-token")) + + fake.mu.Lock() + defer fake.mu.Unlock() + if len(fake.sessions) != 3 { + t.Fatalf("expected 3 calls, got %d", len(fake.sessions)) + } + if fake.sessions[0] == "" || !strings.HasPrefix(fake.sessions[0], "agent-") { + t.Errorf("session ID = %q", fake.sessions[0]) + } + if fake.sessions[0] != fake.sessions[1] { + t.Error("calls in one session should share its ID") + } + if fake.sessions[0] == fake.sessions[2] { + t.Error("separate sessions should have separate IDs") + } +} + +func TestHTTPHandler_SessionIsBoundToTheCredentialThatOpenedIt(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + session := connectAs(t, srv.URL, "alice-token") + + body := `{"jsonrpc":"2.0","id":99,"method":"tools/call","params":{"name":"list_templates","arguments":{}}}` + send := func(token string) *http.Response { + req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("Mcp-Session-Id", session.ID()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("POST: %v", err) + } + resp.Body.Close() + return resp + } + + if resp := send("bob-token"); resp.StatusCode != http.StatusForbidden { + t.Errorf("another credential got %d, want 403", resp.StatusCode) + } + if got := fake.lastCaller(); got != "" { + t.Errorf("a tool ran as %q on someone else's session", got) + } +} + +func TestHTTPHandler_RefusesRequestsWithoutACredential(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + + req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(`{}`)) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("POST: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("got %d, want 401", resp.StatusCode) + } + if !strings.Contains(resp.Header.Get("WWW-Authenticate"), "resource_metadata") { + t.Errorf("WWW-Authenticate = %q", resp.Header.Get("WWW-Authenticate")) + } +} + +func TestHTTPHandler_APanicInAHandlerBecomesAToolError(t *testing.T) { + fake := &fakeAPI{panics: true} + srv := newMCPTestServer(t, fake) + session := connectAs(t, srv.URL, "alice-token") + + result := callListTemplates(t, session) + if !result.IsError { + t.Fatalf("expected a tool error, got %+v", result) + } + + // The server survived and the session still works. + fake.mu.Lock() + fake.panics = false + fake.mu.Unlock() + if result := callListTemplates(t, session); result.IsError { + t.Errorf("session did not recover: %+v", result) + } +} + +func TestResourcesRunAsTheCaller(t *testing.T) { + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + session := connectAs(t, srv.URL, "alice-token") + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if _, err := session.ReadResource(ctx, &mcpsdk.ReadResourceParams{URI: "lightcms://content/recent"}); err != nil { + t.Fatalf("ReadResource: %v", err) + } + if got := fake.lastCaller(); got != "alice" { + t.Errorf("resource read ran as %q, want alice", got) + } +} + +func TestInProcessTransport_FailsClosedWithoutACaller(t *testing.T) { + called := false + transport := &inProcessTransport{api: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true })} + + req, _ := http.NewRequest(http.MethodGet, inProcessBaseURL+"/api/v1/templates", nil) + if _, err := transport.RoundTrip(req); err == nil { + t.Error("expected an error") + } + if called { + t.Error("the API was called with no caller") + } +} + +func TestBufferedResponse_DefaultsAndFirstStatusWins(t *testing.T) { + req, _ := http.NewRequest(http.MethodGet, inProcessBaseURL, nil) + + empty := &bufferedResponse{header: http.Header{}} + if resp := empty.response(req); resp.StatusCode != http.StatusOK { + t.Errorf("no writes: status %d", resp.StatusCode) + } + + b := &bufferedResponse{header: http.Header{}} + b.WriteHeader(http.StatusForbidden) + b.WriteHeader(http.StatusOK) + b.Write([]byte("no")) + resp := b.response(req) + if resp.StatusCode != http.StatusForbidden || resp.ContentLength != 2 { + t.Errorf("status %d, length %d", resp.StatusCode, resp.ContentLength) + } +} + +func TestCallerTokenInfo_RefusesAnUnauthenticatedContext(t *testing.T) { + if _, err := callerTokenInfo(context.Background(), "token", nil); err == nil { + t.Error("expected an error") + } +} + +func TestHostedEndpoint_UploadCannotReadTheServersDisk(t *testing.T) { + secret := filepath.Join(t.TempDir(), "secrets.txt") + if err := os.WriteFile(secret, []byte("do not leak"), 0o600); err != nil { + t.Fatalf("WriteFile: %v", err) + } + fake := &fakeAPI{} + srv := newMCPTestServer(t, fake) + session := connectAs(t, srv.URL, "alice-token") + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + result, err := session.CallTool(ctx, &mcpsdk.CallToolParams{Name: "upload_asset", Arguments: map[string]interface{}{ + "filename": "x.txt", "serve_path": "/assets/x.txt", "file_path": secret, + }}) + if err != nil { + t.Fatalf("CallTool: %v", err) + } + if !result.IsError { + t.Fatalf("expected a refusal, got %+v", result) + } + if got := fake.lastCaller(); got != "" { + t.Errorf("the upload reached the API as %q", got) + } +} diff --git a/internal/mcp/resources.go b/internal/mcp/resources.go index b727a02..fcbc2ec 100644 --- a/internal/mcp/resources.go +++ b/internal/mcp/resources.go @@ -40,9 +40,7 @@ func (s *Server) registerResources() { ) } -func (s *Server) handleSiteStructure(_ context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { - ctx := context.Background() - +func (s *Server) handleSiteStructure(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { folders, err := s.client.ListFolders(ctx) if err != nil { return nil, err @@ -75,9 +73,7 @@ func (s *Server) handleSiteStructure(_ context.Context, req *mcp.ReadResourceReq }, nil } -func (s *Server) handleRecentContent(_ context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { - ctx := context.Background() - +func (s *Server) handleRecentContent(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { content, err := s.client.ListContent(ctx, false, "", "") if err != nil { return nil, err @@ -106,9 +102,7 @@ func (s *Server) handleRecentContent(_ context.Context, req *mcp.ReadResourceReq }, nil } -func (s *Server) handleThemeConfig(_ context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { - ctx := context.Background() - +func (s *Server) handleThemeConfig(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { theme, err := s.client.GetTheme(ctx) if err != nil { return nil, err diff --git a/internal/mcp/resources_test.go b/internal/mcp/resources_test.go index 49b3c79..4d34d49 100644 --- a/internal/mcp/resources_test.go +++ b/internal/mcp/resources_test.go @@ -2,37 +2,11 @@ package mcp import ( "context" - "net/http" "testing" mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp" ) -func TestExtractBearerToken(t *testing.T) { - cases := map[string]string{ - "Bearer abc123": "abc123", - "bearer xyz": "xyz", - "Basic foo": "", - "": "", - "Bearer": "", - } - for header, want := range cases { - r, _ := http.NewRequest("GET", "/", nil) - if header != "" { - r.Header.Set("Authorization", header) - } - if got := extractBearerToken(r); got != want { - t.Errorf("extractBearerToken(%q) = %q, want %q", header, got, want) - } - } -} - -func TestNewHTTPHandler(t *testing.T) { - if NewHTTPHandler("8082") == nil { - t.Error("NewHTTPHandler returned nil") - } -} - func TestServerCard(t *testing.T) { b, err := ServerCard("http://localhost:8082") if err != nil { diff --git a/internal/mcp/server.go b/internal/mcp/server.go index e3978ef..6a16d0a 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -16,6 +16,15 @@ type Server struct { mcpServer *mcp.Server client *apiclient.Client sandbox sandboxState + // localFiles lets upload_asset read file_path from this machine's disk. + localFiles bool +} + +// AllowLocalFiles lets upload_asset read a file_path from the local disk. Only +// the stdio server calls it: it runs on the user's own machine, on the user's +// behalf. On the hosted endpoint the local disk is the server's. +func (s *Server) AllowLocalFiles() { + s.localFiles = true } // NewServer creates a new MCP server with all tools registered diff --git a/internal/middleware/apiauth.go b/internal/middleware/apiauth.go index 04b46a1..ce031b4 100644 --- a/internal/middleware/apiauth.go +++ b/internal/middleware/apiauth.go @@ -13,8 +13,34 @@ type contextKey int const ( // apiUserContextKey stores the authenticated API user in context apiUserContextKey contextKey = iota + // internalCallerContextKey marks a same-process call to the REST API. + internalCallerContextKey ) +// CredentialBound is implemented by a caller that signed in with an API key or +// OAuth connection. CredentialKey identifies that credential, stably and +// without revealing it, for rate limiting and MCP session binding. +type CredentialBound interface { + CredentialKey() string +} + +// CredentialKeyFromContext returns the credential behind the authenticated +// caller in ctx, or "" for a browser session or no caller. +func CredentialKeyFromContext(ctx context.Context) string { + if bound, ok := ctx.Value(apiUserContextKey).(CredentialBound); ok { + return bound.CredentialKey() + } + return "" +} + +// WithInternalCaller returns a context for calling the REST API from inside +// this process on behalf of caller, who has already been authenticated. +// Context values cannot arrive over the network, so a remote client cannot +// claim this; only the MCP endpoint sets it. +func WithInternalCaller(ctx context.Context, caller interface{}) context.Context { + return context.WithValue(ctx, internalCallerContextKey, caller) +} + // APIKeyValidateFunc validates an API key and returns the authenticated user (as interface{}). // The returned value will be stored in the request context and can be retrieved with APIUserFromContext. type APIKeyValidateFunc func(ctx context.Context, rawKey string) (interface{}, error) @@ -45,7 +71,6 @@ type APIAuth struct { validateOAuth OAuthValidateFunc validateSession SessionValidateFunc sessionCSRF func(http.Handler) http.Handler // CSRF check for unsafe session-authenticated requests - systemAPIKey string // internal API key substituted for OAuth-authenticated requests resourceMetadataURL string // for WWW-Authenticate header (OAuth discovery) } @@ -78,18 +103,23 @@ func isSafeMethod(method string) bool { return false } -// SetOAuth enables OAuth token validation alongside API key validation. -// systemAPIKey is injected into the Authorization header for OAuth-authenticated -// requests so the downstream MCP handler can use it for internal REST API calls. -func (m *APIAuth) SetOAuth(validateOAuth OAuthValidateFunc, systemAPIKey, resourceMetadataURL string) { +// SetOAuth enables OAuth tokens on MCPMiddleware. The validator returns the +// signed-in person the token acts for. +func (m *APIAuth) SetOAuth(validateOAuth OAuthValidateFunc, resourceMetadataURL string) { m.validateOAuth = validateOAuth - m.systemAPIKey = systemAPIKey m.resourceMetadataURL = resourceMetadataURL } -// Middleware returns a gorilla/mux compatible middleware function +// Middleware authenticates a REST API request: an API key, a browser session, +// or a call from the MCP endpoint in this process. OAuth tokens are issued for +// the MCP endpoint alone and are refused here. func (m *APIAuth) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if caller := r.Context().Value(internalCallerContextKey); caller != nil { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), apiUserContextKey, caller))) + return + } + authHeader := r.Header.Get("Authorization") if authHeader == "" { // No Authorization header — try session cookie fallback for browser-based admin UI calls @@ -113,52 +143,75 @@ func (m *APIAuth) Middleware(next http.Handler) http.Handler { return } - // Expect "Bearer " - parts := strings.SplitN(authHeader, " ", 2) - if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + token, ok := m.bearerToken(w, authHeader) + if !ok { + return + } + + if !strings.HasPrefix(token, "lc_") { m.setWWWAuthenticate(w) - apiJsonError(w, http.StatusUnauthorized, "Invalid Authorization header format (expected: Bearer )") + apiJsonError(w, http.StatusUnauthorized, "Invalid API key (OAuth access tokens are accepted only at the MCP endpoint)") return } + m.authenticate(w, r, next, m.validate, token, "Invalid API key") + }) +} - token := parts[1] +// MCPMiddleware authenticates a request to the MCP endpoint: an API key or an +// OAuth token. A browser session is not accepted, because a page must not be +// able to drive an agent session with a visitor's cookie. +func (m *APIAuth) MCPMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + m.setWWWAuthenticate(w) + apiJsonError(w, http.StatusUnauthorized, "Missing Authorization header") + return + } + token, ok := m.bearerToken(w, authHeader) + if !ok { + return + } - // Route based on token prefix: lc_ = API key, anything else = OAuth token - if strings.HasPrefix(token, "lc_") { - user, err := m.validate(r.Context(), token) - if err != nil { - m.setWWWAuthenticate(w) - apiJsonError(w, http.StatusUnauthorized, "Invalid API key") - return - } - // Inject user into request context - if user != nil { - r = r.WithContext(context.WithValue(r.Context(), apiUserContextKey, user)) - } - next.ServeHTTP(w, r) - } else if m.validateOAuth != nil { - user, err := m.validateOAuth(r.Context(), token) - if err != nil { - m.setWWWAuthenticate(w) - apiJsonError(w, http.StatusUnauthorized, "Invalid access token") - return - } - // Inject user into request context - if user != nil { - r = r.WithContext(context.WithValue(r.Context(), apiUserContextKey, user)) - } - // Replace Authorization header with system API key so downstream - // handlers (MCP http_handler, REST API) work correctly - r.Header.Set("Authorization", "Bearer "+m.systemAPIKey) - next.ServeHTTP(w, r) - } else { + switch { + case strings.HasPrefix(token, "lc_"): + m.authenticate(w, r, next, m.validate, token, "Invalid API key") + case m.validateOAuth != nil: + m.authenticate(w, r, next, APIKeyValidateFunc(m.validateOAuth), token, "Invalid access token") + default: m.setWWWAuthenticate(w) apiJsonError(w, http.StatusUnauthorized, "Invalid API key") - return } }) } +// bearerToken extracts the token from "Bearer ", writing the 401 itself +// when the header has another form. +func (m *APIAuth) bearerToken(w http.ResponseWriter, authHeader string) (string, bool) { + parts := strings.SplitN(authHeader, " ", 2) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + m.setWWWAuthenticate(w) + apiJsonError(w, http.StatusUnauthorized, "Invalid Authorization header format (expected: Bearer )") + return "", false + } + return parts[1], true +} + +// authenticate runs validate and, when it succeeds, calls next with the caller +// in the request context. +func (m *APIAuth) authenticate(w http.ResponseWriter, r *http.Request, next http.Handler, validate APIKeyValidateFunc, token, invalidMessage string) { + user, err := validate(r.Context(), token) + if err != nil { + m.setWWWAuthenticate(w) + apiJsonError(w, http.StatusUnauthorized, invalidMessage) + return + } + if user != nil { + r = r.WithContext(context.WithValue(r.Context(), apiUserContextKey, user)) + } + next.ServeHTTP(w, r) +} + // setWWWAuthenticate adds the WWW-Authenticate header for OAuth discovery func (m *APIAuth) setWWWAuthenticate(w http.ResponseWriter) { if m.resourceMetadataURL != "" { diff --git a/internal/middleware/apiauth_test.go b/internal/middleware/apiauth_test.go index 0aa7566..cde16e7 100644 --- a/internal/middleware/apiauth_test.go +++ b/internal/middleware/apiauth_test.go @@ -109,8 +109,9 @@ func TestAPIAuth_InvalidAPIKey(t *testing.T) { } } -func TestAPIAuth_ValidOAuthToken(t *testing.T) { - systemKey := "lc_system_key_12345678901234567890" +func TestAPIAuth_OAuthTokenAcceptedAtMCPWithCallerAndHeaderUntouched(t *testing.T) { + type person struct{ Email string } + caller := &person{Email: "viewer@example.com"} m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { return nil, fmt.Errorf("not an API key") }) @@ -118,44 +119,73 @@ func TestAPIAuth_ValidOAuthToken(t *testing.T) { if rawToken != "oauth_access_token_123" { return nil, fmt.Errorf("invalid token") } - return nil, nil - }, systemKey, "https://example.com/.well-known/oauth-protected-resource") + return caller, nil + }, "https://example.com/.well-known/oauth-protected-resource") var capturedAuth string - handler := m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var capturedUser interface{} + handler := m.MCPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { capturedAuth = r.Header.Get("Authorization") + capturedUser, _ = APIUserFromContext(r.Context()) w.WriteHeader(http.StatusOK) })) - req := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil) + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) req.Header.Set("Authorization", "Bearer oauth_access_token_123") rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) if rr.Code != http.StatusOK { - t.Errorf("expected 200, got %d", rr.Code) + t.Fatalf("expected 200, got %d", rr.Code) } - - // Verify system API key was substituted - expected := "Bearer " + systemKey - if capturedAuth != expected { - t.Errorf("expected Authorization header %q, got %q", expected, capturedAuth) + if capturedUser != caller { + t.Errorf("expected the signed-in person in context, got %+v", capturedUser) + } + if capturedAuth != "Bearer oauth_access_token_123" { + t.Errorf("Authorization header was rewritten to %q", capturedAuth) } } -func TestAPIAuth_InvalidOAuthToken(t *testing.T) { +func TestAPIAuth_OAuthTokenRefusedAtREST(t *testing.T) { m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { return nil, fmt.Errorf("not an API key") }) + validated := false m.SetOAuth(func(ctx context.Context, rawToken string) (interface{}, error) { - return nil, fmt.Errorf("invalid token") - }, "lc_system", "https://example.com/.well-known/oauth-protected-resource") + validated = true + return "someone", nil + }, "https://example.com/.well-known/oauth-protected-resource") handler := m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) + t.Error("handler must not run for an OAuth token at /api/v1") })) req := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil) + req.Header.Set("Authorization", "Bearer oauth_access_token_123") + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", rr.Code) + } + if validated { + t.Error("the OAuth validator must not run at /api/v1") + } +} + +func TestAPIAuth_InvalidOAuthTokenAtMCP(t *testing.T) { + m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { + return nil, fmt.Errorf("not an API key") + }) + m.SetOAuth(func(ctx context.Context, rawToken string) (interface{}, error) { + return nil, fmt.Errorf("invalid token") + }, "https://example.com/.well-known/oauth-protected-resource") + + handler := m.MCPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("handler must not run for an invalid token") + })) + + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) req.Header.Set("Authorization", "Bearer bad_oauth_token") rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) @@ -165,6 +195,77 @@ func TestAPIAuth_InvalidOAuthToken(t *testing.T) { } } +func TestAPIAuth_MCPRefusesBrowserSession(t *testing.T) { + m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { + return nil, fmt.Errorf("invalid") + }) + m.SetSessionAuth(func(r *http.Request) interface{} { return "cookie user" }, nil) + + handler := m.MCPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("handler must not run for a browser session at /mcp") + })) + + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", rr.Code) + } +} + +func TestAPIAuth_InternalCallerIsOnlyReachableThroughContext(t *testing.T) { + type person struct{ Email string } + caller := &person{Email: "agent@example.com"} + m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { + return nil, fmt.Errorf("invalid") + }) + + var seen interface{} + handler := m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen, _ = APIUserFromContext(r.Context()) + w.WriteHeader(http.StatusOK) + })) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil).WithContext(WithInternalCaller(context.Background(), caller)) + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + if rr.Code != http.StatusOK || seen != caller { + t.Fatalf("in-process call: code %d, caller %+v", rr.Code, seen) + } + + // The same request without the context value has no caller at all. + rr = httptest.NewRecorder() + handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/v1/test", nil)) + if rr.Code != http.StatusUnauthorized { + t.Errorf("request from the network: expected 401, got %d", rr.Code) + } +} + +type credentialCaller struct{ key string } + +func (c credentialCaller) CredentialKey() string { return c.key } + +func TestRateLimitKey_CountsAgainstTheCredential(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil) + req.Header.Set("Authorization", "Bearer lc_raw") + if got := rateLimitKey(req); got != "lc_raw" { + t.Errorf("without a caller: got %q", got) + } + + withCaller := req.WithContext(context.WithValue(req.Context(), apiUserContextKey, credentialCaller{key: "oauth:abc"})) + if got := rateLimitKey(withCaller); got != "oauth:abc" { + t.Errorf("with a caller: got %q", got) + } + + // An in-process call has no Authorization header but is still counted. + internal := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil) + internal = internal.WithContext(context.WithValue(internal.Context(), apiUserContextKey, credentialCaller{key: "oauth:abc"})) + if got := rateLimitKey(internal); got != "oauth:abc" { + t.Errorf("in-process: got %q", got) + } +} + func TestAPIAuth_OAuthNotConfigured_NonLCToken(t *testing.T) { m := NewAPIAuth(func(ctx context.Context, rawKey string) (interface{}, error) { return nil, fmt.Errorf("invalid key") @@ -192,7 +293,7 @@ func TestAPIAuth_WWWAuthenticateHeader(t *testing.T) { }) m.SetOAuth(func(ctx context.Context, rawToken string) (interface{}, error) { return nil, fmt.Errorf("invalid") - }, "lc_system", resourceURL) + }, resourceURL) handler := m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) diff --git a/internal/middleware/apirate.go b/internal/middleware/apirate.go index a40b05a..6230ed2 100644 --- a/internal/middleware/apirate.go +++ b/internal/middleware/apirate.go @@ -65,17 +65,25 @@ var apiKeyRateLimiter = struct { tokens: make(map[string][]time.Time), } -// APIRateLimit is middleware that enforces a per-bearer-token sliding-window rate limit -// on the /api/v1/ subrouter. It runs after authentication so the token is already +// rateLimitKey returns what a request is counted against: the credential the +// caller signed in with, or failing that the raw bearer token. A browser session +// has neither and is not limited here. +func rateLimitKey(r *http.Request) string { + if key := CredentialKeyFromContext(r.Context()); key != "" { + return key + } + if auth := r.Header.Get("Authorization"); len(auth) > 7 { + return auth[7:] // strip "Bearer " + } + return "" +} + +// APIRateLimit is middleware that enforces a per-credential sliding-window rate limit +// on the /api/v1/ subrouter. It runs after authentication so the credential is already // validated; unauthenticated requests are rejected by the auth middleware first. func APIRateLimit(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Extract the raw bearer token to use as the rate-limit key. - // We use the token directly (already validated by auth middleware). - token := "" - if auth := r.Header.Get("Authorization"); len(auth) > 7 { - token = auth[7:] // strip "Bearer " - } + token := rateLimitKey(r) if token == "" { // No token — auth middleware would have blocked this, but be safe. next.ServeHTTP(w, r) @@ -156,10 +164,7 @@ func init() { // APIBurstRateLimit is middleware that enforces 20 requests/second per bearer token. func APIBurstRateLimit(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token := "" - if auth := r.Header.Get("Authorization"); len(auth) > 7 { - token = auth[7:] - } + token := rateLimitKey(r) if token == "" { next.ServeHTTP(w, r) return @@ -263,6 +268,7 @@ var ( exportLimiter = newEndpointRateLimiter(5) // 5 exports per minute reindexLimiter = newEndpointRateLimiter(1) // 1 full reindex per minute commentCreateLimiter = newEndpointRateLimiter(20) // 20 comments per minute per token + oauthRegisterLimiter = newEndpointRateLimiter(10) // 10 client registrations per minute per address ) // EndpointRateLimit returns middleware that enforces a per-token limit for a specific @@ -270,10 +276,7 @@ var ( func EndpointRateLimit(limiter *endpointRateLimiter, description string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token := "" - if auth := r.Header.Get("Authorization"); len(auth) > 7 { - token = auth[7:] - } + token := rateLimitKey(r) if token != "" && limiter.check(token) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Retry-After", "60") @@ -318,6 +321,27 @@ func ReindexLimiter() func(http.Handler) http.Handler { return EndpointRateLimit(reindexLimiter, "reindex-embeddings (1/min)") } +// OAuthRegisterLimiter returns middleware limiting OAuth client registration to +// 10/min per client address. Registration is open to anyone, so it has no +// credential to count against. +func OAuthRegisterLimiter(proxy *TrustedProxyConfig) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if oauthRegisterLimiter.check(GetClientIP(r, proxy)) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "60") + w.WriteHeader(http.StatusTooManyRequests) + json.NewEncoder(w).Encode(map[string]string{ + "error": "too_many_requests", + "error_description": "Too many client registrations. Try again in a minute.", + }) + return + } + next.ServeHTTP(w, r) + }) + } +} + // CommentCreateLimiter returns middleware limiting comment creation to 20/min per token. func CommentCreateLimiter() func(http.Handler) http.Handler { return EndpointRateLimit(commentCreateLimiter, "comment creation (20/min)") diff --git a/internal/models/oauth.go b/internal/models/oauth.go index 6adaec7..90fd6f4 100644 --- a/internal/models/oauth.go +++ b/internal/models/oauth.go @@ -17,11 +17,28 @@ type OAuthClient struct { CreatedAt time.Time `bson:"created_at" json:"created_at"` } +// OAuthGrant is one person's consent for one client: the "connection". Every +// authorization code and token belongs to a grant, and the person it names is +// who the connection acts as. Revoking the grant ends the connection and +// every token issued under it. +type OAuthGrant struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` + ClientID string `bson:"client_id" json:"client_id"` + ClientName string `bson:"client_name" json:"client_name"` // as registered, for display; chosen by the client + UserID primitive.ObjectID `bson:"user_id" json:"user_id"` + Resource string `bson:"resource" json:"resource"` + CreatedAt time.Time `bson:"created_at" json:"created_at"` + UpdatedAt time.Time `bson:"updated_at" json:"updated_at"` + LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"` + RevokedAt *time.Time `bson:"revoked_at,omitempty" json:"revoked_at,omitempty"` +} + // OAuthAuthCode represents a pending authorization code type OAuthAuthCode struct { ID primitive.ObjectID `bson:"_id,omitempty"` CodeHash string `bson:"code" json:"-"` ClientID string `bson:"client_id"` + GrantID primitive.ObjectID `bson:"grant_id,omitempty"` RedirectURI string `bson:"redirect_uri"` CodeChallenge string `bson:"code_challenge"` CodeChallengeMethod string `bson:"code_challenge_method"` @@ -36,6 +53,7 @@ type OAuthAccessToken struct { ID primitive.ObjectID `bson:"_id,omitempty"` TokenHash string `bson:"token_hash"` ClientID string `bson:"client_id"` + GrantID primitive.ObjectID `bson:"grant_id,omitempty"` Resource string `bson:"resource"` ExpiresAt time.Time `bson:"expires_at"` CreatedAt time.Time `bson:"created_at"` @@ -46,8 +64,10 @@ type OAuthRefreshToken struct { ID primitive.ObjectID `bson:"_id,omitempty"` TokenHash string `bson:"token_hash"` ClientID string `bson:"client_id"` + GrantID primitive.ObjectID `bson:"grant_id,omitempty"` Resource string `bson:"resource"` ExpiresAt time.Time `bson:"expires_at"` Revoked bool `bson:"revoked"` + RotatedAt *time.Time `bson:"rotated_at,omitempty"` // when this token was exchanged for a new one CreatedAt time.Time `bson:"created_at"` } diff --git a/internal/models/user.go b/internal/models/user.go index 7bb968d..922c0d8 100644 --- a/internal/models/user.go +++ b/internal/models/user.go @@ -35,8 +35,11 @@ type AuditLog struct { // AgentSession groups all changes made by one AI-agent session (from the // X-Agent-Session request header) so they can be reviewed and rolled // back as a unit. - AgentSession string `bson:"agent_session,omitempty" json:"agent_session,omitempty"` - CreatedAt time.Time `bson:"created_at" json:"created_at"` + AgentSession string `bson:"agent_session,omitempty" json:"agent_session,omitempty"` + // Credential names the API key ("apikey:") or OAuth connection + // ("oauth:") a change was made with. + Credential string `bson:"credential,omitempty" json:"credential,omitempty"` + CreatedAt time.Time `bson:"created_at" json:"created_at"` } // Role constants diff --git a/internal/oauth/handler.go b/internal/oauth/handler.go index 775d575..8c9c9fb 100644 --- a/internal/oauth/handler.go +++ b/internal/oauth/handler.go @@ -11,19 +11,32 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" + "unicode" "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/models" "github.com/metavert-io/lightcms/v7/internal/services" + + "go.mongodb.org/mongo-driver/bson/primitive" ) -const loginProofMaxAge = 5 * time.Minute +const ( + loginProofMaxAge = 5 * time.Minute + + // Limits on what an unauthenticated client may register. + maxRegistrationBody = 16 << 10 + maxClientNameLength = 100 + maxRedirectURIs = 10 +) // Handler implements OAuth 2.1 endpoints for MCP authorization type Handler struct { oauthService *services.OAuthService authManager *auth.Manager baseURL string + resource string // the one resource tokens are issued for: this server's MCP endpoint sessionSecret string tmpl *template.Template } @@ -34,6 +47,7 @@ func NewHandler(oauthService *services.OAuthService, authManager *auth.Manager, oauthService: oauthService, authManager: authManager, baseURL: baseURL, + resource: services.MCPResourceURL(baseURL), sessionSecret: sessionSecret, } h.tmpl = template.Must(template.New("authorize").Parse(oauthTemplates["authorize"])) @@ -43,6 +57,7 @@ func NewHandler(oauthService *services.OAuthService, authManager *auth.Manager, // Register handles Dynamic Client Registration (RFC 7591) // POST /oauth/register func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, maxRegistrationBody) var req struct { ClientName string `json:"client_name"` RedirectURIs []string `json:"redirect_uris"` @@ -54,6 +69,7 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { return } + req.ClientName = cleanClientName(req.ClientName) if req.ClientName == "" { req.ClientName = "Unknown Client" } @@ -61,6 +77,16 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { jsonError(w, http.StatusBadRequest, "invalid_request", "redirect_uris is required") return } + if len(req.RedirectURIs) > maxRedirectURIs { + jsonError(w, http.StatusBadRequest, "invalid_redirect_uri", "Too many redirect_uris") + return + } + for _, uri := range req.RedirectURIs { + if err := services.ValidateRedirectURI(uri); err != nil { + jsonError(w, http.StatusBadRequest, "invalid_redirect_uri", err.Error()) + return + } + } client, rawSecret, err := h.oauthService.RegisterClient(r.Context(), req.ClientName, req.RedirectURIs) if err != nil { @@ -115,6 +141,12 @@ func (h *Handler) Authorize(w http.ResponseWriter, r *http.Request) { return } + resource, ok := h.resolveResource(resource) + if !ok { + redirectWithError(w, r, redirectURI, state, "invalid_target", "This server only issues tokens for "+h.resource) + return + } + // Render login page h.renderAuthorize(w, map[string]interface{}{ "ShowLogin": true, @@ -155,6 +187,18 @@ func (h *Handler) AuthorizeSubmit(w http.ResponseWriter, r *http.Request) { return } + if action == "login" || action == "approve" { + if responseType != "code" || codeChallenge == "" || codeChallengeMethod != "S256" { + jsonError(w, http.StatusBadRequest, "invalid_request", "response_type=code and PKCE with S256 are required") + return + } + var ok bool + if resource, ok = h.resolveResource(resource); !ok { + redirectWithError(w, r, redirectURI, state, "invalid_target", "This server only issues tokens for "+h.resource) + return + } + } + templateData := map[string]interface{}{ "ClientID": clientID, "RedirectURI": redirectURI, @@ -190,29 +234,58 @@ func (h *Handler) AuthorizeSubmit(w http.ResponseWriter, r *http.Request) { h.authManager.ClearRateLimit(r.Context(), r) + if user.IsDefaultPassword { + templateData["ShowLogin"] = true + templateData["Error"] = "Set a new password in the admin dashboard before connecting an app." + h.renderAuthorize(w, templateData) + return + } + // Password valid — show consent page with login proof ts := strconv.FormatInt(time.Now().Unix(), 10) - proof := h.computeLoginProof(clientID, redirectURI, codeChallenge, ts) + userID := user.ID.Hex() templateData["ShowLogin"] = false templateData["ClientName"] = client.ClientName - templateData["LoginProof"] = proof + templateData["RedirectHost"] = redirectHost(redirectURI) + templateData["UserEmail"] = user.Email + templateData["UserRole"] = user.Role + templateData["RoleSummary"] = roleSummary(user.Role) + templateData["LoginUser"] = userID + templateData["LoginProof"] = h.computeLoginProof(userID, clientID, redirectURI, codeChallenge, resource, ts) templateData["LoginTS"] = ts h.renderAuthorize(w, templateData) case "approve": + loginUser := r.FormValue("login_user") loginProof := r.FormValue("login_proof") loginTS := r.FormValue("login_ts") - if !h.verifyLoginProof(clientID, redirectURI, codeChallenge, loginTS, loginProof) { + if !h.verifyLoginProof(loginUser, clientID, redirectURI, codeChallenge, resource, loginTS, loginProof) { templateData["ShowLogin"] = true templateData["Error"] = "Session expired. Please sign in again." h.renderAuthorize(w, templateData) return } + // The account may have changed since the password was checked. + user := h.approvingUser(r, loginUser) + if user == nil { + templateData["ShowLogin"] = true + templateData["Error"] = "This account can't connect apps. Please sign in again." + h.renderAuthorize(w, templateData) + return + } + + grant, err := h.oauthService.SaveGrant(r.Context(), client, user.ID, resource) + if err != nil { + log.Printf("[OAuth] Failed to save grant: %v", err) + redirectWithError(w, r, redirectURI, state, "server_error", "Failed to record the connection") + return + } + // Generate auth code - code, err := h.oauthService.CreateAuthCode(r.Context(), clientID, redirectURI, codeChallenge, codeChallengeMethod, resource) + code, err := h.oauthService.CreateAuthCode(r.Context(), grant, redirectURI, codeChallenge, codeChallengeMethod) if err != nil { log.Printf("[OAuth] Failed to create auth code: %v", err) redirectWithError(w, r, redirectURI, state, "server_error", "Failed to generate authorization code") @@ -262,6 +335,17 @@ func (h *Handler) Token(w http.ResponseWriter, r *http.Request) { return } + if resource := r.FormValue("resource"); resource != "" { + if _, ok := h.resolveResource(resource); !ok { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{ + "error": "invalid_target", + "error_description": "This server only issues tokens for " + h.resource, + }) + return + } + } + switch grantType { case "authorization_code": code := r.FormValue("code") @@ -316,23 +400,115 @@ func (h *Handler) Token(w http.ResponseWriter, r *http.Request) { } } -// computeLoginProof creates an HMAC proving the admin authenticated -func (h *Handler) computeLoginProof(clientID, redirectURI, codeChallenge, timestamp string) string { +// computeLoginProof creates an HMAC proving that this person gave the right +// password for this authorization request. Each field is written with its +// length, so one set of values can't be read as another. +func (h *Handler) computeLoginProof(userID, clientID, redirectURI, codeChallenge, resource, timestamp string) string { mac := hmac.New(sha256.New, []byte(h.sessionSecret)) - mac.Write([]byte(clientID + "|" + redirectURI + "|" + codeChallenge + "|" + timestamp)) + for _, field := range []string{"lightcms-oauth-consent", userID, clientID, redirectURI, codeChallenge, resource, timestamp} { + fmt.Fprintf(mac, "%d:%s", len(field), field) + } return hex.EncodeToString(mac.Sum(nil)) } // verifyLoginProof checks the HMAC and ensures it's not expired -func (h *Handler) verifyLoginProof(clientID, redirectURI, codeChallenge, timestamp, proof string) bool { +func (h *Handler) verifyLoginProof(userID, clientID, redirectURI, codeChallenge, resource, timestamp, proof string) bool { ts, err := strconv.ParseInt(timestamp, 10, 64) if err != nil || time.Since(time.Unix(ts, 0)) > loginProofMaxAge { return false } - expected := h.computeLoginProof(clientID, redirectURI, codeChallenge, timestamp) + expected := h.computeLoginProof(userID, clientID, redirectURI, codeChallenge, resource, timestamp) return hmac.Equal([]byte(expected), []byte(proof)) } +// approvingUser returns the account behind a verified login proof, or nil if +// it can no longer connect an app. +func (h *Handler) approvingUser(r *http.Request, userID string) *models.User { + id, err := primitive.ObjectIDFromHex(userID) + if err != nil { + return nil + } + user, err := h.authManager.GetUserByID(r.Context(), id) + if err != nil { + log.Printf("[OAuth] Failed to load approving user: %v", err) + return nil + } + if user == nil || user.Disabled || user.IsDefaultPassword { + return nil + } + return user +} + +// resolveResource returns the resource an authorization request is for. A +// client that names none gets this server's MCP endpoint; naming anything else +// is refused (RFC 8707). +func (h *Handler) resolveResource(requested string) (string, bool) { + if requested == "" || sameResource(requested, h.resource) { + return h.resource, true + } + return "", false +} + +// sameResource compares two resource URLs, ignoring the differences that don't +// change what they point at: letter case in the scheme and host, a default +// port and a trailing slash. +func sameResource(a, b string) bool { + na, okA := normalizeResource(a) + nb, okB := normalizeResource(b) + return okA && okB && na == nb +} + +func normalizeResource(raw string) (string, bool) { + u, err := url.Parse(raw) + if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" { + return "", false + } + scheme := strings.ToLower(u.Scheme) + host := strings.ToLower(u.Hostname()) + if port := u.Port(); port != "" && !(scheme == "https" && port == "443") && !(scheme == "http" && port == "80") { + host += ":" + port + } + return scheme + "://" + host + strings.TrimSuffix(u.Path, "/"), true +} + +// cleanClientName removes characters that could disguise a client's name on +// the consent page (control, zero-width and text-direction characters) and +// shortens it. +func cleanClientName(name string) string { + name = strings.TrimSpace(strings.Map(func(r rune) rune { + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, name)) + if runes := []rune(name); len(runes) > maxClientNameLength { + name = string(runes[:maxClientNameLength]) + } + return name +} + +// redirectHost returns the host the browser is sent back to after consent. +func redirectHost(redirectURI string) string { + if u, err := url.Parse(redirectURI); err == nil && u.Host != "" { + return u.Host + } + return redirectURI +} + +// roleSummary says in plain words what a role can do through a connection. +func roleSummary(role string) string { + switch role { + case models.RoleAdmin: + return "everything an admin can do, including changing site settings, templates and API keys, and publishing" + case models.RoleEditor: + return "create, edit, delete and publish content, upload assets, and manage forks and approvals" + case models.RoleContributor: + return "create drafts, upload assets for review, and comment" + default: + return "read content, templates, assets and settings" + } +} + func (h *Handler) renderAuthorize(w http.ResponseWriter, data map[string]interface{}) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := h.tmpl.Execute(w, data); err != nil { @@ -389,15 +565,17 @@ func ProtectedResourceMetadataHandler(baseURL string) http.HandlerFunc { // AuthorizationServerMetadataHandler returns the RFC 8414 metadata handler func AuthorizationServerMetadataHandler(baseURL string) http.HandlerFunc { metadata, _ := json.Marshal(map[string]interface{}{ - "issuer": baseURL, - "authorization_endpoint": baseURL + "/oauth/authorize", - "token_endpoint": baseURL + "/oauth/token", - "registration_endpoint": baseURL + "/oauth/register", - "response_types_supported": []string{"code"}, - "grant_types_supported": []string{"authorization_code", "refresh_token"}, - "token_endpoint_auth_methods_supported": []string{"client_secret_post"}, - "code_challenge_methods_supported": []string{"S256"}, - "scopes_supported": []string{}, + "issuer": baseURL, + "authorization_endpoint": baseURL + "/oauth/authorize", + "token_endpoint": baseURL + "/oauth/token", + "registration_endpoint": baseURL + "/oauth/register", + "revocation_endpoint": baseURL + "/oauth/revoke", + "response_types_supported": []string{"code"}, + "grant_types_supported": []string{"authorization_code", "refresh_token"}, + "token_endpoint_auth_methods_supported": []string{"client_secret_post"}, + "revocation_endpoint_auth_methods_supported": []string{"client_secret_post"}, + "code_challenge_methods_supported": []string{"S256"}, + "scopes_supported": []string{}, }) return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -421,10 +599,36 @@ func JWKSHandler() http.HandlerFunc { } } -// TokenRevocationHandler handles token revocation (RFC 7009) +// TokenRevocation handles token revocation (RFC 7009) // POST /oauth/revoke +// +// A client can revoke only its own tokens. Revoking a refresh token ends the +// whole connection. An unknown token still gets a 200, as the RFC requires. func (h *Handler) TokenRevocation(w http.ResponseWriter, r *http.Request) { - // Per RFC 7009, always return 200 even if token is invalid + if err := r.ParseForm(); err != nil { + jsonError(w, http.StatusBadRequest, "invalid_request", "Invalid form data") + return + } + + clientID := r.FormValue("client_id") + if _, err := h.oauthService.ValidateClientCredentials(r.Context(), clientID, r.FormValue("client_secret")); err != nil { + jsonError(w, http.StatusUnauthorized, "invalid_client", "Invalid client credentials") + return + } + + token := r.FormValue("token") + if token == "" { + jsonError(w, http.StatusBadRequest, "invalid_request", "token is required") + return + } + + if err := h.oauthService.RevokeToken(r.Context(), clientID, token); err != nil { + log.Printf("[OAuth] Token revocation failed: %v", err) + jsonError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "Could not revoke the token. Try again.") + return + } + + w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) fmt.Fprint(w, "{}") } diff --git a/internal/oauth/handler_test.go b/internal/oauth/handler_test.go index 58cf6ba..1c1e4d7 100644 --- a/internal/oauth/handler_test.go +++ b/internal/oauth/handler_test.go @@ -14,13 +14,22 @@ import ( "time" "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/models" "github.com/metavert-io/lightcms/v7/internal/services" "github.com/metavert-io/lightcms/v7/internal/testutil" "github.com/gorilla/sessions" + "go.mongodb.org/mongo-driver/bson/primitive" + "golang.org/x/crypto/bcrypt" ) func newTestHandler(t *testing.T) (*Handler, *services.OAuthService, func()) { + t.Helper() + handler, oauthService, _, cleanup := newTestHandlerWithUsers(t) + return handler, oauthService, cleanup +} + +func newTestHandlerWithUsers(t *testing.T) (*Handler, *services.OAuthService, *services.UserService, func()) { t.Helper() db, cleanup := testutil.MustConnectTestDB(t) @@ -31,7 +40,35 @@ func newTestHandler(t *testing.T) (*Handler, *services.OAuthService, func()) { authManager.MigrateToMultiUser(context.Background()) handler := NewHandler(oauthService, authManager, "https://example.com", "test-session-secret") - return handler, oauthService, cleanup + return handler, oauthService, userService, cleanup +} + +const testPassword = "correct horse battery staple" + +// testAccount creates an account that has already chosen its own password. +func testAccount(t *testing.T, users *services.UserService, email, role string) *models.User { + t.Helper() + hash, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.MinCost) + if err != nil { + t.Fatalf("hashing password: %v", err) + } + user, err := users.CreateUserWithHash(context.Background(), email, email, role, string(hash), false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + return user +} + +const testResourceURL = "https://example.com/mcp" + +// testGrant records that a new person approved the client. +func testGrant(t *testing.T, oauthSvc *services.OAuthService, client *models.OAuthClient) *models.OAuthGrant { + t.Helper() + grant, err := oauthSvc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResourceURL) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + return grant } func TestRegister_Success(t *testing.T) { @@ -360,47 +397,41 @@ func TestJWKSHandler(t *testing.T) { } } -func TestTokenRevocation(t *testing.T) { - handler, _, cleanup := newTestHandler(t) - defer cleanup() - - req := httptest.NewRequest(http.MethodPost, "/oauth/revoke", nil) - rr := httptest.NewRecorder() - handler.TokenRevocation(rr, req) - - if rr.Code != http.StatusOK { - t.Errorf("expected 200, got %d", rr.Code) - } -} - func TestComputeVerifyLoginProof(t *testing.T) { handler, _, cleanup := newTestHandler(t) defer cleanup() + userID := "user-1" clientID := "test-client" redirectURI := "http://localhost/cb" codeChallenge := "challenge123" + resource := testResourceURL ts := strconv.FormatInt(time.Now().Unix(), 10) - proof := handler.computeLoginProof(clientID, redirectURI, codeChallenge, ts) + proof := handler.computeLoginProof(userID, clientID, redirectURI, codeChallenge, resource, ts) if proof == "" { t.Error("expected non-empty proof") } // Verify should pass - if !handler.verifyLoginProof(clientID, redirectURI, codeChallenge, ts, proof) { + if !handler.verifyLoginProof(userID, clientID, redirectURI, codeChallenge, resource, ts, proof) { t.Error("expected proof to be valid") } // Wrong proof should fail - if handler.verifyLoginProof(clientID, redirectURI, codeChallenge, ts, "wrong-proof") { + if handler.verifyLoginProof(userID, clientID, redirectURI, codeChallenge, resource, ts, "wrong-proof") { t.Error("expected wrong proof to fail") } - // Different params should produce different proof - proof2 := handler.computeLoginProof("other-client", redirectURI, codeChallenge, ts) - if proof == proof2 { - t.Error("different params should produce different proof") + // A proof is good only for the person, client and resource it was made for + if handler.verifyLoginProof("user-2", clientID, redirectURI, codeChallenge, resource, ts, proof) { + t.Error("expected proof to be bound to the user") + } + if handler.verifyLoginProof(userID, "other-client", redirectURI, codeChallenge, resource, ts, proof) { + t.Error("expected proof to be bound to the client") + } + if handler.verifyLoginProof(userID, clientID, redirectURI, codeChallenge, "https://other.example/mcp", ts, proof) { + t.Error("expected proof to be bound to the resource") } } @@ -410,9 +441,9 @@ func TestVerifyLoginProof_Expired(t *testing.T) { // Use a timestamp from 10 minutes ago (proof max age is 5 minutes) oldTs := strconv.FormatInt(time.Now().Add(-10*time.Minute).Unix(), 10) - proof := handler.computeLoginProof("client", "uri", "challenge", oldTs) + proof := handler.computeLoginProof("user", "client", "uri", "challenge", testResourceURL, oldTs) - if handler.verifyLoginProof("client", "uri", "challenge", oldTs, proof) { + if handler.verifyLoginProof("user", "client", "uri", "challenge", testResourceURL, oldTs, proof) { t.Error("expected expired proof to fail") } } @@ -421,7 +452,7 @@ func TestVerifyLoginProof_InvalidTimestamp(t *testing.T) { handler, _, cleanup := newTestHandler(t) defer cleanup() - if handler.verifyLoginProof("client", "uri", "challenge", "not-a-number", "proof") { + if handler.verifyLoginProof("user", "client", "uri", "challenge", testResourceURL, "not-a-number", "proof") { t.Error("expected invalid timestamp to fail") } } @@ -448,8 +479,9 @@ func TestJsonError(t *testing.T) { // AuthorizeSubmit tests func TestAuthorizeSubmit_LoginSuccess(t *testing.T) { - handler, oauthSvc, cleanup := newTestHandler(t) + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) defer cleanup() + testAccount(t, users, "author@example.com", models.RoleEditor) client, _, err := oauthSvc.RegisterClient(context.Background(), "Test App", []string{"http://localhost/cb"}) if err != nil { @@ -464,8 +496,8 @@ func TestAuthorizeSubmit_LoginSuccess(t *testing.T) { "code_challenge": {"challenge123"}, "code_challenge_method": {"S256"}, "action": {"login"}, - "email": {"admin@localhost"}, - "password": {"admin123"}, + "email": {"author@example.com"}, + "password": {testPassword}, } req := httptest.NewRequest(http.MethodPost, "/oauth/authorize", strings.NewReader(form.Encode())) @@ -522,8 +554,9 @@ func TestAuthorizeSubmit_LoginWrongPassword(t *testing.T) { } func TestAuthorizeSubmit_Approve(t *testing.T) { - handler, oauthSvc, cleanup := newTestHandler(t) + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) defer cleanup() + user := testAccount(t, users, "author@example.com", models.RoleEditor) client, _, err := oauthSvc.RegisterClient(context.Background(), "Test App", []string{"http://localhost/cb"}) if err != nil { @@ -532,7 +565,7 @@ func TestAuthorizeSubmit_Approve(t *testing.T) { // Generate a valid login proof ts := strconv.FormatInt(time.Now().Unix(), 10) - proof := handler.computeLoginProof(client.ClientID, "http://localhost/cb", "challenge", ts) + proof := handler.computeLoginProof(user.ID.Hex(), client.ClientID, "http://localhost/cb", "challenge", testResourceURL, ts) form := url.Values{ "client_id": {client.ClientID}, @@ -542,6 +575,7 @@ func TestAuthorizeSubmit_Approve(t *testing.T) { "code_challenge": {"challenge"}, "code_challenge_method": {"S256"}, "action": {"approve"}, + "login_user": {user.ID.Hex()}, "login_proof": {proof}, "login_ts": {ts}, } @@ -582,7 +616,7 @@ func TestAuthorizeSubmit_ApproveExpiredProof(t *testing.T) { // Expired timestamp ts := strconv.FormatInt(time.Now().Add(-10*time.Minute).Unix(), 10) - proof := handler.computeLoginProof(client.ClientID, "http://localhost/cb", "challenge", ts) + proof := handler.computeLoginProof("user", client.ClientID, "http://localhost/cb", "challenge", testResourceURL, ts) form := url.Values{ "client_id": {client.ClientID}, @@ -591,6 +625,7 @@ func TestAuthorizeSubmit_ApproveExpiredProof(t *testing.T) { "code_challenge": {"challenge"}, "code_challenge_method": {"S256"}, "action": {"approve"}, + "login_user": {"user"}, "login_proof": {proof}, "login_ts": {ts}, } @@ -712,7 +747,7 @@ func TestToken_AuthorizationCodeGrant(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) // Create auth code - code, _ := oauthSvc.CreateAuthCode(context.Background(), client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := oauthSvc.CreateAuthCode(context.Background(), testGrant(t, oauthSvc, client), "http://localhost/cb", challenge, "S256") form := url.Values{ "grant_type": {"authorization_code"}, @@ -761,7 +796,7 @@ func TestToken_RefreshTokenGrant(t *testing.T) { h := sha256.Sum256([]byte(verifier)) challenge := base64.RawURLEncoding.EncodeToString(h[:]) - code, _ := oauthSvc.CreateAuthCode(context.Background(), client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := oauthSvc.CreateAuthCode(context.Background(), testGrant(t, oauthSvc, client), "http://localhost/cb", challenge, "S256") _, refreshToken, _, _ := oauthSvc.ExchangeAuthCode(context.Background(), code, client.ClientID, "http://localhost/cb", verifier) form := url.Values{ @@ -899,12 +934,13 @@ func TestRedirectWithError_InvalidURI(t *testing.T) { } func TestAuthorizeSubmit_ApproveNoState(t *testing.T) { - handler, oauthSvc, cleanup := newTestHandler(t) + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) defer cleanup() + user := testAccount(t, users, "author@example.com", models.RoleEditor) client, _, _ := oauthSvc.RegisterClient(context.Background(), "Test", []string{"http://localhost/cb"}) ts := strconv.FormatInt(time.Now().Unix(), 10) - proof := handler.computeLoginProof(client.ClientID, "http://localhost/cb", "challenge", ts) + proof := handler.computeLoginProof(user.ID.Hex(), client.ClientID, "http://localhost/cb", "challenge", testResourceURL, ts) form := url.Values{ "client_id": {client.ClientID}, @@ -914,6 +950,7 @@ func TestAuthorizeSubmit_ApproveNoState(t *testing.T) { "code_challenge": {"challenge"}, "code_challenge_method": {"S256"}, "action": {"approve"}, + "login_user": {user.ID.Hex()}, "login_proof": {proof}, "login_ts": {ts}, } diff --git a/internal/oauth/identity_test.go b/internal/oauth/identity_test.go new file mode 100644 index 0000000..fb9f56b --- /dev/null +++ b/internal/oauth/identity_test.go @@ -0,0 +1,386 @@ +package oauth + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" +) + +func postForm(handler http.HandlerFunc, path string, form url.Values) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + handler(rr, req) + return rr +} + +func pkcePair(verifier string) string { + sum := sha256.Sum256([]byte(verifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func authorizeForm(client *models.OAuthClient, challenge, action string) url.Values { + return url.Values{ + "client_id": {client.ClientID}, + "redirect_uri": {"http://localhost/cb"}, + "response_type": {"code"}, + "code_challenge": {challenge}, + "code_challenge_method": {"S256"}, + "action": {action}, + } +} + +// signIn runs the login step and returns the consent page. +func signIn(t *testing.T, handler *Handler, client *models.OAuthClient, challenge, email string) string { + t.Helper() + form := authorizeForm(client, challenge, "login") + form.Set("email", email) + form.Set("password", testPassword) + rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) + if rr.Code != http.StatusOK { + t.Fatalf("login: %d %s", rr.Code, rr.Body.String()) + } + return rr.Body.String() +} + +func hiddenField(t *testing.T, page, name string) string { + t.Helper() + marker := `name="` + name + `" value="` + i := strings.Index(page, marker) + if i < 0 { + t.Fatalf("field %s not on page:\n%s", name, page) + } + rest := page[i+len(marker):] + return rest[:strings.Index(rest, `"`)] +} + +// approveFromPage submits the consent page's own hidden fields. +func approveFromPage(handler *Handler, client *models.OAuthClient, challenge, page string, t *testing.T) *httptest.ResponseRecorder { + t.Helper() + form := authorizeForm(client, challenge, "approve") + form.Set("resource", hiddenField(t, page, "resource")) + form.Set("login_user", hiddenField(t, page, "login_user")) + form.Set("login_proof", hiddenField(t, page, "login_proof")) + form.Set("login_ts", hiddenField(t, page, "login_ts")) + return postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) +} + +func TestConsent_ConnectionActsAsThePersonWhoSignedIn(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + ctx := context.Background() + + // An admin exists, but the person connecting is a viewer. + testAccount(t, users, "boss@example.com", models.RoleAdmin) + viewer := testAccount(t, users, "viewer@example.com", models.RoleViewer) + + client, secret, err := oauthSvc.RegisterClient(ctx, "Some App", []string{"http://localhost/cb"}) + if err != nil { + t.Fatalf("RegisterClient: %v", err) + } + verifier := "viewer-connection-verifier" + + page := signIn(t, handler, client, pkcePair(verifier), "viewer@example.com") + rr := approveFromPage(handler, client, pkcePair(verifier), page, t) + if rr.Code != http.StatusFound { + t.Fatalf("approve: %d %s", rr.Code, rr.Body.String()) + } + location, _ := url.Parse(rr.Header().Get("Location")) + + rr = postForm(handler.Token, "/oauth/token", url.Values{ + "grant_type": {"authorization_code"}, + "client_id": {client.ClientID}, + "client_secret": {secret}, + "code": {location.Query().Get("code")}, + "redirect_uri": {"http://localhost/cb"}, + "code_verifier": {verifier}, + }) + if rr.Code != http.StatusOK { + t.Fatalf("token: %d %s", rr.Code, rr.Body.String()) + } + var tokens map[string]interface{} + json.Unmarshal(rr.Body.Bytes(), &tokens) + + grant, err := oauthSvc.ValidateAccessToken(ctx, tokens["access_token"].(string), testResourceURL) + if err != nil { + t.Fatalf("ValidateAccessToken: %v", err) + } + if grant.UserID != viewer.ID { + t.Errorf("connection belongs to %s, want the viewer %s", grant.UserID.Hex(), viewer.ID.Hex()) + } +} + +func TestConsent_ProofCannotBeMovedToAnotherAccount(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + + admin := testAccount(t, users, "boss@example.com", models.RoleAdmin) + testAccount(t, users, "viewer@example.com", models.RoleViewer) + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + challenge := pkcePair("verifier") + + page := signIn(t, handler, client, challenge, "viewer@example.com") + form := authorizeForm(client, challenge, "approve") + form.Set("login_user", admin.ID.Hex()) // the viewer claims to be the admin + form.Set("login_proof", hiddenField(t, page, "login_proof")) + form.Set("login_ts", hiddenField(t, page, "login_ts")) + + rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) + if rr.Code == http.StatusFound { + t.Fatalf("approved with a proof made for another account; redirected to %s", rr.Header().Get("Location")) + } + if !strings.Contains(rr.Body.String(), "Session expired") { + t.Errorf("expected a sign-in prompt, got: %s", rr.Body.String()) + } +} + +func TestConsent_PageSaysWhoAndWhereAndClaimsNothingElse(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + testAccount(t, users, "viewer@example.com", models.RoleViewer) + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"https://app.example.org/callback"}) + + form := authorizeForm(client, pkcePair("v"), "login") + form.Set("redirect_uri", "https://app.example.org/callback") + form.Set("email", "viewer@example.com") + form.Set("password", testPassword) + rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) + page := rr.Body.String() + + for _, want := range []string{"viewer@example.com", "app.example.org", "viewer role"} { + if !strings.Contains(page, want) { + t.Errorf("consent page does not mention %q", want) + } + } + if strings.Contains(page, "full access") { + t.Error("consent page still claims full access") + } +} + +func TestLogin_TemporaryPasswordCannotConnectApps(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + // The migrated default admin still has its default password. + form := authorizeForm(client, pkcePair("v"), "login") + form.Set("email", "admin@localhost") + form.Set("password", "admin123") + rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) + + if strings.Contains(rr.Body.String(), "login_proof") { + t.Error("an account on a temporary password reached the consent page") + } + if !strings.Contains(rr.Body.String(), "Set a new password") { + t.Errorf("expected a prompt to change the password, got: %s", rr.Body.String()) + } +} + +func TestApprove_RefusesAccountDisabledSinceLogin(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + ctx := context.Background() + user := testAccount(t, users, "leaver@example.com", models.RoleEditor) + client, _, _ := oauthSvc.RegisterClient(ctx, "Some App", []string{"http://localhost/cb"}) + challenge := pkcePair("v") + + page := signIn(t, handler, client, challenge, "leaver@example.com") + if err := users.DisableUser(ctx, user.ID, true); err != nil { + t.Fatalf("DisableUser: %v", err) + } + + rr := approveFromPage(handler, client, challenge, page, t) + if rr.Code == http.StatusFound { + t.Fatal("a disabled account completed the connection") + } +} + +func TestAuthorize_RefusesAnotherResource(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + params := url.Values{ + "response_type": {"code"}, + "client_id": {client.ClientID}, + "redirect_uri": {"http://localhost/cb"}, + "code_challenge": {"c"}, + "code_challenge_method": {"S256"}, + "resource": {"https://elsewhere.example/mcp"}, + } + rr := httptest.NewRecorder() + handler.Authorize(rr, httptest.NewRequest(http.MethodGet, "/oauth/authorize?"+params.Encode(), nil)) + + if rr.Code != http.StatusFound { + t.Fatalf("expected a redirect with an error, got %d", rr.Code) + } + location, _ := url.Parse(rr.Header().Get("Location")) + if location.Query().Get("error") != "invalid_target" { + t.Errorf("expected invalid_target, got %q", location.Query().Get("error")) + } +} + +func TestToken_RefusesAnotherResource(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + client, secret, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + rr := postForm(handler.Token, "/oauth/token", url.Values{ + "grant_type": {"refresh_token"}, + "client_id": {client.ClientID}, + "client_secret": {secret}, + "refresh_token": {"whatever"}, + "resource": {"https://elsewhere.example/mcp"}, + }) + if rr.Code != http.StatusBadRequest || !strings.Contains(rr.Body.String(), "invalid_target") { + t.Errorf("expected invalid_target, got %d %s", rr.Code, rr.Body.String()) + } +} + +func TestSameResource(t *testing.T) { + const canonical = "https://example.com/mcp" + same := []string{canonical, "https://example.com/mcp/", "HTTPS://EXAMPLE.com/mcp", "https://example.com:443/mcp"} + for _, r := range same { + if !sameResource(r, canonical) { + t.Errorf("%q should match", r) + } + } + different := []string{"https://example.com", "https://example.com/api/v1", "http://example.com/mcp", "https://example.com/mcp?x=1", "https://example.com:8443/mcp", "not a url"} + for _, r := range different { + if sameResource(r, canonical) { + t.Errorf("%q should not match", r) + } + } +} + +func TestRegister_Limits(t *testing.T) { + handler, _, cleanup := newTestHandler(t) + defer cleanup() + + register := func(body string) *httptest.ResponseRecorder { + rr := httptest.NewRecorder() + handler.Register(rr, httptest.NewRequest(http.MethodPost, "/oauth/register", strings.NewReader(body))) + return rr + } + + if rr := register(`{"client_name":"X","redirect_uris":["http://evil.example/cb"]}`); rr.Code != http.StatusBadRequest { + t.Errorf("plain http to a remote host: %d", rr.Code) + } + if rr := register(`{"client_name":"X","redirect_uris":["javascript:alert(1)"]}`); rr.Code != http.StatusBadRequest { + t.Errorf("javascript scheme: %d", rr.Code) + } + if rr := register(`{"client_name":"X","redirect_uris":["https://a.example/cb#frag"]}`); rr.Code != http.StatusBadRequest { + t.Errorf("fragment: %d", rr.Code) + } + many := `"https://a.example/cb"` + strings.Repeat(`,"https://a.example/cb"`, maxRedirectURIs) + if rr := register(`{"client_name":"X","redirect_uris":[` + many + `]}`); rr.Code != http.StatusBadRequest { + t.Errorf("too many redirect URIs: %d", rr.Code) + } + huge := `{"client_name":"` + strings.Repeat("x", maxRegistrationBody) + `","redirect_uris":["https://a.example/cb"]}` + if rr := register(huge); rr.Code != http.StatusBadRequest { + t.Errorf("oversized body: %d", rr.Code) + } + if rr := register(`{"client_name":"X","redirect_uris":["https://a.example/cb","http://127.0.0.1:3334/cb","http://[::1]:3334/cb"]}`); rr.Code != http.StatusCreated { + t.Errorf("https and loopback should register: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestCleanClientName(t *testing.T) { + cases := map[string]string{ + " Claude ": "Claude", + "Trusted‮evil": "Trustedevil", + "Zero​Width": "ZeroWidth", + "Line\nBreak": "LineBreak", + strings.Repeat("é", 150): strings.Repeat("é", maxClientNameLength), + } + for in, want := range cases { + if got := cleanClientName(in); got != want { + t.Errorf("cleanClientName(%q) = %q, want %q", in, got, want) + } + } +} + +func TestTokenRevocation_ClientMustAuthenticate(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + rr := postForm(handler.TokenRevocation, "/oauth/revoke", url.Values{ + "client_id": {client.ClientID}, + "client_secret": {"wrong"}, + "token": {"anything"}, + }) + if rr.Code != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", rr.Code) + } +} + +func TestTokenRevocation_RevokesTheToken(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + ctx := context.Background() + client, secret, _ := oauthSvc.RegisterClient(ctx, "Some App", []string{"http://localhost/cb"}) + verifier := "revocation-verifier" + code, _ := oauthSvc.CreateAuthCode(ctx, testGrant(t, oauthSvc, client), "http://localhost/cb", pkcePair(verifier), "S256") + access, refresh, _, err := oauthSvc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) + if err != nil { + t.Fatalf("ExchangeAuthCode: %v", err) + } + + rr := postForm(handler.TokenRevocation, "/oauth/revoke", url.Values{ + "client_id": {client.ClientID}, + "client_secret": {secret}, + "token": {refresh}, + }) + if rr.Code != http.StatusOK { + t.Fatalf("revoke: %d %s", rr.Code, rr.Body.String()) + } + if _, err := oauthSvc.ValidateAccessToken(ctx, access, testResourceURL); err == nil { + t.Error("access token still works after its connection was revoked") + } +} + +func TestTokenRevocation_UnknownTokenStillSucceeds(t *testing.T) { + handler, oauthSvc, cleanup := newTestHandler(t) + defer cleanup() + client, secret, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + rr := postForm(handler.TokenRevocation, "/oauth/revoke", url.Values{ + "client_id": {client.ClientID}, + "client_secret": {secret}, + "token": {"never-issued"}, + }) + if rr.Code != http.StatusOK { + t.Errorf("expected 200, got %d", rr.Code) + } +} + +func TestConsent_ExpiredProofRefused(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + user := testAccount(t, users, "author@example.com", models.RoleEditor) + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + challenge := pkcePair("v") + + ts := strconv.FormatInt(time.Now().Add(-loginProofMaxAge-time.Minute).Unix(), 10) + form := authorizeForm(client, challenge, "approve") + form.Set("login_user", user.ID.Hex()) + form.Set("login_ts", ts) + form.Set("login_proof", handler.computeLoginProof(user.ID.Hex(), client.ClientID, "http://localhost/cb", challenge, services.MCPResourceURL("https://example.com"), ts)) + + rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form) + if rr.Code == http.StatusFound { + t.Fatal("approved with an expired proof") + } +} diff --git a/internal/oauth/templates.go b/internal/oauth/templates.go index 8a559b5..e9da545 100644 --- a/internal/oauth/templates.go +++ b/internal/oauth/templates.go @@ -177,8 +177,9 @@ var oauthTemplates = map[string]string{ {{else}}

Authorize application access

@@ -189,6 +190,7 @@ var oauthTemplates = map[string]string{ + diff --git a/internal/services/apikey.go b/internal/services/apikey.go index b8956f3..cb7b864 100644 --- a/internal/services/apikey.go +++ b/internal/services/apikey.go @@ -143,6 +143,17 @@ func (s *APIKeyService) deleteKey(ctx context.Context, filter bson.M) error { return nil } +// AssignOwner gives a key with no owner on record to a user. It never changes +// the owner of a key that already has one. +func (s *APIKeyService) AssignOwner(ctx context.Context, id, ownerID primitive.ObjectID) error { + if err := s.db.UpdateOne(ctx, "api_keys", + bson.M{"_id": id, "user_id": nil}, + bson.M{"$set": bson.M{"user_id": ownerID}}); err != nil { + return fmt.Errorf("failed to assign API key owner: %w", err) + } + return nil +} + // ValidateAPIKey checks a raw API key, returns the key record if valid, and updates last_used_at func (s *APIKeyService) ValidateAPIKey(ctx context.Context, rawKey string) (*models.APIKey, error) { if len(rawKey) < 4 || rawKey[:3] != "lc_" { diff --git a/internal/services/oauth.go b/internal/services/oauth.go index 5e836ab..813df3e 100644 --- a/internal/services/oauth.go +++ b/internal/services/oauth.go @@ -6,7 +6,12 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" "fmt" + "log" + "net" + "net/url" + "strings" "time" "github.com/metavert-io/lightcms/v7/internal/database" @@ -14,14 +19,75 @@ import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" ) const ( AccessTokenTTL = 1 * time.Hour RefreshTokenTTL = 30 * 24 * time.Hour AuthCodeTTL = 10 * time.Minute + + // RefreshReuseLeeway is how long after a refresh token is rotated a second + // use is refused without ending the connection. Two requests from one + // client racing to refresh are not an attack; a used token that comes back + // later is. + RefreshReuseLeeway = 30 * time.Second + + // grantTouchInterval limits how often a grant's last-used time is written. + grantTouchInterval = time.Minute + + maxRedirectURILength = 2048 ) +// ErrRefreshTokenReplayed reports that an already-used refresh token was +// presented, and the connection it belonged to has been revoked. +var ErrRefreshTokenReplayed = errors.New("refresh token already used; the connection has been revoked") + +// MCPResourceURL returns this server's canonical OAuth resource identifier +// (RFC 8707): the one URL its access tokens are good for. +func MCPResourceURL(baseURL string) string { + return strings.TrimRight(baseURL, "/") + "/mcp" +} + +// ValidateRedirectURI enforces the redirect rules for OAuth clients: https, or +// http only to a loopback address, where a native app listens on a local port +// (RFC 8252 section 7.3). No fragments and no embedded credentials. +func ValidateRedirectURI(raw string) error { + if raw == "" || len(raw) > maxRedirectURILength { + return fmt.Errorf("redirect_uri must be between 1 and %d characters", maxRedirectURILength) + } + u, err := url.Parse(raw) + if err != nil || u.Host == "" { + return fmt.Errorf("redirect_uri must be an absolute URL") + } + if u.Fragment != "" || strings.Contains(raw, "#") { + return fmt.Errorf("redirect_uri must not contain a fragment") + } + if u.User != nil { + return fmt.Errorf("redirect_uri must not contain credentials") + } + switch strings.ToLower(u.Scheme) { + case "https": + return nil + case "http": + if isLoopbackHost(u.Hostname()) { + return nil + } + return fmt.Errorf("redirect_uri must use https unless it points at this device (localhost)") + default: + return fmt.Errorf("redirect_uri must use https, or http to localhost") + } +} + +func isLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + // OAuthService handles OAuth 2.1 authorization type OAuthService struct { db *database.DB @@ -40,6 +106,11 @@ func (s *OAuthService) RegisterClient(ctx context.Context, clientName string, re if len(redirectURIs) == 0 { return nil, "", fmt.Errorf("redirect_uris is required") } + for _, uri := range redirectURIs { + if err := ValidateRedirectURI(uri); err != nil { + return nil, "", err + } + } clientID, err := generateToken(16) if err != nil { @@ -93,6 +164,10 @@ func (s *OAuthService) ValidateClient(ctx context.Context, clientID, redirectURI if !found { return nil, fmt.Errorf("redirect_uri not registered") } + // Clients registered before these rules existed are held to them too. + if err := ValidateRedirectURI(redirectURI); err != nil { + return nil, err + } return &client, nil } @@ -112,8 +187,98 @@ func (s *OAuthService) ValidateClientCredentials(ctx context.Context, clientID, return &client, nil } -// CreateAuthCode generates an authorization code for the given client -func (s *OAuthService) CreateAuthCode(ctx context.Context, clientID, redirectURI, codeChallenge, codeChallengeMethod, resource string) (string, error) { +// SaveGrant records that a person approved a client, and returns the grant. +// One person has one active grant per client: approving again reuses it. +func (s *OAuthService) SaveGrant(ctx context.Context, client *models.OAuthClient, userID primitive.ObjectID, resource string) (*models.OAuthGrant, error) { + now := time.Now() + var grant models.OAuthGrant + err := s.db.Collection("oauth_grants").FindOneAndUpdate(ctx, + bson.M{"client_id": client.ClientID, "user_id": userID, "revoked_at": nil}, + bson.M{ + "$set": bson.M{"client_name": client.ClientName, "resource": resource, "updated_at": now}, + "$setOnInsert": bson.M{"created_at": now}, + }, + options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After), + ).Decode(&grant) + if err != nil { + return nil, fmt.Errorf("failed to save grant: %w", err) + } + return &grant, nil +} + +// GetGrant returns a grant by ID, revoked or not. +func (s *OAuthService) GetGrant(ctx context.Context, id primitive.ObjectID) (*models.OAuthGrant, error) { + var grant models.OAuthGrant + if err := s.db.FindOne(ctx, "oauth_grants", bson.M{"_id": id}, &grant); err != nil { + return nil, fmt.Errorf("grant not found: %w", err) + } + return &grant, nil +} + +// activeGrant returns a grant that has not been revoked. +func (s *OAuthService) activeGrant(ctx context.Context, id primitive.ObjectID) (*models.OAuthGrant, error) { + if id.IsZero() { + return nil, fmt.Errorf("issued before connections were tied to a person; reconnect the app") + } + grant, err := s.GetGrant(ctx, id) + if err != nil { + return nil, err + } + if grant.RevokedAt != nil { + return nil, fmt.Errorf("connection revoked") + } + return grant, nil +} + +// RevokeGrant ends a connection: the grant is marked revoked, which alone +// invalidates everything issued under it, and its tokens are then removed. +func (s *OAuthService) RevokeGrant(ctx context.Context, id primitive.ObjectID) error { + now := time.Now() + if err := s.db.UpdateOne(ctx, "oauth_grants", + bson.M{"_id": id, "revoked_at": nil}, + bson.M{"$set": bson.M{"revoked_at": now, "updated_at": now}}); err != nil { + return fmt.Errorf("failed to revoke grant: %w", err) + } + if _, err := s.db.Collection("oauth_refresh_tokens").UpdateMany(ctx, + bson.M{"grant_id": id}, bson.M{"$set": bson.M{"revoked": true}}); err != nil { + log.Printf("[OAuth] grant %s revoked; marking refresh tokens failed: %v", id.Hex(), err) + } + if _, err := s.db.DeleteMany(ctx, "oauth_access_tokens", bson.M{"grant_id": id}); err != nil { + log.Printf("[OAuth] grant %s revoked; removing access tokens failed: %v", id.Hex(), err) + } + return nil +} + +// RevokeToken implements RFC 7009 for one client. Revoking a refresh token ends +// its connection; revoking an access token ends that token alone. A token that +// is unknown or belongs to another client is ignored, as the RFC requires. +func (s *OAuthService) RevokeToken(ctx context.Context, clientID, rawToken string) error { + tokenHash := hashToken(rawToken) + + var refresh models.OAuthRefreshToken + err := s.db.FindOne(ctx, "oauth_refresh_tokens", bson.M{"token_hash": tokenHash}, &refresh) + switch { + case err == nil: + if refresh.ClientID != clientID { + return nil + } + if refresh.GrantID.IsZero() { + return s.db.UpdateOne(ctx, "oauth_refresh_tokens", bson.M{"_id": refresh.ID}, bson.M{"$set": bson.M{"revoked": true}}) + } + return s.RevokeGrant(ctx, refresh.GrantID) + case !errors.Is(err, mongo.ErrNoDocuments): + return fmt.Errorf("looking up refresh token: %w", err) + } + + _, err = s.db.DeleteMany(ctx, "oauth_access_tokens", bson.M{"token_hash": tokenHash, "client_id": clientID}) + if err != nil { + return fmt.Errorf("revoking access token: %w", err) + } + return nil +} + +// CreateAuthCode generates an authorization code under the given grant. +func (s *OAuthService) CreateAuthCode(ctx context.Context, grant *models.OAuthGrant, redirectURI, codeChallenge, codeChallengeMethod string) (string, error) { rawCode, err := generateToken(32) if err != nil { return "", fmt.Errorf("failed to generate auth code: %w", err) @@ -122,11 +287,12 @@ func (s *OAuthService) CreateAuthCode(ctx context.Context, clientID, redirectURI now := time.Now() authCode := &models.OAuthAuthCode{ CodeHash: hashToken(rawCode), - ClientID: clientID, + ClientID: grant.ClientID, + GrantID: grant.ID, RedirectURI: redirectURI, CodeChallenge: codeChallenge, CodeChallengeMethod: codeChallengeMethod, - Resource: resource, + Resource: grant.Resource, ExpiresAt: now.Add(AuthCodeTTL), Used: false, CreatedAt: now, @@ -139,7 +305,20 @@ func (s *OAuthService) CreateAuthCode(ctx context.Context, clientID, redirectURI return rawCode, nil } -// ExchangeAuthCode validates an auth code and returns access + refresh tokens +// claim atomically applies update to the one document filter matches, and +// reports whether this call was the one that changed it. +func (s *OAuthService) claim(ctx context.Context, collection string, filter, update bson.M) (bool, error) { + result, err := s.db.Collection(collection).UpdateOne(ctx, filter, update) + if err != nil { + return false, err + } + return result.ModifiedCount == 1, nil +} + +// ExchangeAuthCode validates an auth code and returns access + refresh tokens. +// The code is consumed atomically, after every check has passed: of two +// concurrent exchanges exactly one gets tokens, and a failed attempt does not +// burn the code. func (s *OAuthService) ExchangeAuthCode(ctx context.Context, rawCode, clientID, redirectURI, codeVerifier string) (accessToken, refreshToken string, expiresIn int, err error) { codeHash := hashToken(rawCode) @@ -167,19 +346,28 @@ func (s *OAuthService) ExchangeAuthCode(ctx context.Context, rawCode, clientID, return "", "", 0, fmt.Errorf("PKCE verification failed") } - // Mark code as used - _ = s.db.UpdateOne(ctx, "oauth_auth_codes", bson.M{"_id": authCode.ID}, bson.M{"$set": bson.M{"used": true}}) + grant, err := s.activeGrant(ctx, authCode.GrantID) + if err != nil { + return "", "", 0, fmt.Errorf("authorization code: %w", err) + } - // Generate tokens - accessToken, refreshToken, expiresIn, err = s.generateTokenPair(ctx, clientID, authCode.Resource) + claimed, err := s.claim(ctx, "oauth_auth_codes", + bson.M{"_id": authCode.ID, "used": false}, + bson.M{"$set": bson.M{"used": true}}) if err != nil { - return "", "", 0, err + return "", "", 0, fmt.Errorf("failed to consume authorization code: %w", err) + } + if !claimed { + return "", "", 0, fmt.Errorf("authorization code already used") } - return accessToken, refreshToken, expiresIn, nil + return s.generateTokenPair(ctx, grant) } -// RefreshAccessToken validates a refresh token and issues new tokens (with rotation) +// RefreshAccessToken rotates a refresh token and issues new tokens. Rotation is +// atomic, so one token yields one new pair however many requests race for it. +// A used token that comes back after RefreshReuseLeeway means two parties hold +// it, so the connection is revoked and ErrRefreshTokenReplayed returned. func (s *OAuthService) RefreshAccessToken(ctx context.Context, rawRefreshToken, clientID string) (newAccessToken, newRefreshToken string, expiresIn int, err error) { tokenHash := hashToken(rawRefreshToken) @@ -188,27 +376,46 @@ func (s *OAuthService) RefreshAccessToken(ctx context.Context, rawRefreshToken, return "", "", 0, fmt.Errorf("invalid refresh token") } + if refreshToken.ClientID != clientID { + return "", "", 0, fmt.Errorf("client_id mismatch") + } if refreshToken.Revoked { + if refreshToken.RotatedAt != nil && time.Since(*refreshToken.RotatedAt) > RefreshReuseLeeway && !refreshToken.GrantID.IsZero() { + log.Printf("[OAuth] used refresh token replayed; revoking grant %s", refreshToken.GrantID.Hex()) + if err := s.RevokeGrant(ctx, refreshToken.GrantID); err != nil { + log.Printf("[OAuth] revoking grant %s after replay failed: %v", refreshToken.GrantID.Hex(), err) + } + return "", "", 0, ErrRefreshTokenReplayed + } return "", "", 0, fmt.Errorf("refresh token revoked") } if time.Now().After(refreshToken.ExpiresAt) { return "", "", 0, fmt.Errorf("refresh token expired") } - if refreshToken.ClientID != clientID { - return "", "", 0, fmt.Errorf("client_id mismatch") + + grant, err := s.activeGrant(ctx, refreshToken.GrantID) + if err != nil { + return "", "", 0, fmt.Errorf("refresh token: %w", err) } - // Revoke old refresh token (rotation) - _ = s.db.UpdateOne(ctx, "oauth_refresh_tokens", - bson.M{"_id": refreshToken.ID}, - bson.M{"$set": bson.M{"revoked": true}}) + now := time.Now() + claimed, err := s.claim(ctx, "oauth_refresh_tokens", + bson.M{"_id": refreshToken.ID, "revoked": false}, + bson.M{"$set": bson.M{"revoked": true, "rotated_at": now}}) + if err != nil { + return "", "", 0, fmt.Errorf("failed to rotate refresh token: %w", err) + } + if !claimed { + return "", "", 0, fmt.Errorf("refresh token revoked") + } - // Generate new token pair - return s.generateTokenPair(ctx, clientID, refreshToken.Resource) + return s.generateTokenPair(ctx, grant) } -// ValidateAccessToken checks a raw access token and returns the token record -func (s *OAuthService) ValidateAccessToken(ctx context.Context, rawToken string) (*models.OAuthAccessToken, error) { +// ValidateAccessToken checks a raw access token, for use at the given resource, +// and returns the live grant it belongs to. A token issued before connections +// were tied to a person has no grant and is refused. +func (s *OAuthService) ValidateAccessToken(ctx context.Context, rawToken, resource string) (*models.OAuthGrant, error) { tokenHash := hashToken(rawToken) var token models.OAuthAccessToken @@ -219,12 +426,28 @@ func (s *OAuthService) ValidateAccessToken(ctx context.Context, rawToken string) if time.Now().After(token.ExpiresAt) { return nil, fmt.Errorf("access token expired") } + if token.Resource != resource { + return nil, fmt.Errorf("access token was not issued for this resource") + } + + grant, err := s.activeGrant(ctx, token.GrantID) + if err != nil { + return nil, fmt.Errorf("access token: %w", err) + } + + if grant.LastUsedAt == nil || time.Since(*grant.LastUsedAt) > grantTouchInterval { + now := time.Now() + if err := s.db.UpdateOne(ctx, "oauth_grants", bson.M{"_id": grant.ID}, bson.M{"$set": bson.M{"last_used_at": now}}); err != nil { + log.Printf("[OAuth] recording last use of grant %s failed: %v", grant.ID.Hex(), err) + } + grant.LastUsedAt = &now + } - return &token, nil + return grant, nil } // generateTokenPair creates and stores a new access token + refresh token -func (s *OAuthService) generateTokenPair(ctx context.Context, clientID, resource string) (string, string, int, error) { +func (s *OAuthService) generateTokenPair(ctx context.Context, grant *models.OAuthGrant) (string, string, int, error) { rawAccess, err := generateToken(48) if err != nil { return "", "", 0, fmt.Errorf("failed to generate access token: %w", err) @@ -239,16 +462,18 @@ func (s *OAuthService) generateTokenPair(ctx context.Context, clientID, resource accessToken := &models.OAuthAccessToken{ TokenHash: hashToken(rawAccess), - ClientID: clientID, - Resource: resource, + ClientID: grant.ClientID, + GrantID: grant.ID, + Resource: grant.Resource, ExpiresAt: now.Add(AccessTokenTTL), CreatedAt: now, } refreshToken := &models.OAuthRefreshToken{ TokenHash: hashToken(rawRefresh), - ClientID: clientID, - Resource: resource, + ClientID: grant.ClientID, + GrantID: grant.ID, + Resource: grant.Resource, ExpiresAt: now.Add(RefreshTokenTTL), Revoked: false, CreatedAt: now, @@ -260,7 +485,7 @@ func (s *OAuthService) generateTokenPair(ctx context.Context, clientID, resource if _, err := s.db.InsertOne(ctx, "oauth_refresh_tokens", refreshToken); err != nil { // Clean up the access token we just created - _ = s.db.DeleteOne(ctx, "oauth_access_tokens", bson.M{"_id": accessToken.ID}) + _, _ = s.db.DeleteMany(ctx, "oauth_access_tokens", bson.M{"token_hash": accessToken.TokenHash}) return "", "", 0, fmt.Errorf("failed to store refresh token: %w", err) } diff --git a/internal/services/oauth_grant_test.go b/internal/services/oauth_grant_test.go new file mode 100644 index 0000000..a901915 --- /dev/null +++ b/internal/services/oauth_grant_test.go @@ -0,0 +1,475 @@ +package services + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/metavert-io/lightcms/v7/internal/database" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/testutil" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +const testVerifier = "grant-test-verifier" + +func testChallenge() string { + sum := sha256.Sum256([]byte(testVerifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +type oauthFixture struct { + db *database.DB + svc *OAuthService + client *models.OAuthClient + grant *models.OAuthGrant +} + +func newOAuthFixture(t *testing.T) *oauthFixture { + t.Helper() + db, cleanup := testutil.MustConnectTestDB(t) + t.Cleanup(cleanup) + svc := NewOAuthService(db) + client, _, err := svc.RegisterClient(context.Background(), "Test", []string{"http://localhost/cb"}) + if err != nil { + t.Fatalf("RegisterClient: %v", err) + } + return &oauthFixture{db: db, svc: svc, client: client, grant: testGrant(t, svc, client)} +} + +func (f *oauthFixture) code(t *testing.T) string { + t.Helper() + code, err := f.svc.CreateAuthCode(context.Background(), f.grant, "http://localhost/cb", testChallenge(), "S256") + if err != nil { + t.Fatalf("CreateAuthCode: %v", err) + } + return code +} + +// tokens returns a fresh access + refresh token under the fixture's grant. +func (f *oauthFixture) tokens(t *testing.T) (string, string) { + t.Helper() + access, refresh, _, err := f.svc.ExchangeAuthCode(context.Background(), f.code(t), f.client.ClientID, "http://localhost/cb", testVerifier) + if err != nil { + t.Fatalf("ExchangeAuthCode: %v", err) + } + return access, refresh +} + +func TestSaveGrant_OneActiveGrantPerPersonAndClient(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + user := primitive.NewObjectID() + + first, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + again, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + if err != nil { + t.Fatalf("SaveGrant again: %v", err) + } + if first.ID != again.ID { + t.Error("approving the same client again should reuse the grant") + } + + other, err := f.svc.SaveGrant(ctx, f.client, primitive.NewObjectID(), testResource) + if err != nil { + t.Fatalf("SaveGrant other: %v", err) + } + if other.ID == first.ID { + t.Error("another person must get their own grant") + } + + if err := f.svc.RevokeGrant(ctx, first.ID); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + after, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + if err != nil { + t.Fatalf("SaveGrant after revoke: %v", err) + } + if after.ID == first.ID { + t.Error("a revoked grant must not come back to life") + } +} + +func TestValidateAccessToken(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + access, _ := f.tokens(t) + + grant, err := f.svc.ValidateAccessToken(ctx, access, testResource) + if err != nil { + t.Fatalf("ValidateAccessToken: %v", err) + } + if grant.ID != f.grant.ID || grant.UserID != f.grant.UserID { + t.Errorf("got grant %+v, want %+v", grant, f.grant) + } + if grant.LastUsedAt == nil { + t.Error("expected last use to be recorded") + } + + if _, err := f.svc.ValidateAccessToken(ctx, "nonexistent", testResource); err == nil { + t.Error("expected error for an unknown token") + } + if _, err := f.svc.ValidateAccessToken(ctx, access, "https://other.example/mcp"); err == nil { + t.Error("expected error for a token used at another resource") + } +} + +func TestValidateAccessToken_Expired(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, err := f.db.InsertOne(ctx, "oauth_access_tokens", bson.M{ + "token_hash": hashToken("expired"), + "client_id": f.client.ClientID, + "grant_id": f.grant.ID, + "resource": testResource, + "expires_at": time.Now().Add(-time.Hour), + "created_at": time.Now().Add(-2 * time.Hour), + }) + if err != nil { + t.Fatalf("insert: %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, "expired", testResource); err == nil { + t.Error("expected error for an expired token") + } +} + +func TestValidateAccessToken_RefusesTokenFromBeforeGrants(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, err := f.db.InsertOne(ctx, "oauth_access_tokens", bson.M{ + "token_hash": hashToken("old"), + "client_id": f.client.ClientID, + "resource": testResource, + "expires_at": time.Now().Add(time.Hour), + "created_at": time.Now(), + }) + if err != nil { + t.Fatalf("insert: %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, "old", testResource); err == nil { + t.Error("a token with no grant must be refused") + } +} + +func TestExchangeAuthCode_ConcurrentExchangesGetOnePair(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + code := f.code(t) + + var wg sync.WaitGroup + var mu sync.Mutex + succeeded := 0 + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, _, _, err := f.svc.ExchangeAuthCode(ctx, code, f.client.ClientID, "http://localhost/cb", testVerifier); err == nil { + mu.Lock() + succeeded++ + mu.Unlock() + } + }() + } + wg.Wait() + if succeeded != 1 { + t.Errorf("%d exchanges succeeded, want exactly 1", succeeded) + } +} + +func TestExchangeAuthCode_FailedAttemptDoesNotBurnTheCode(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + code := f.code(t) + + if _, _, _, err := f.svc.ExchangeAuthCode(ctx, code, f.client.ClientID, "http://localhost/cb", "wrong"); err == nil { + t.Fatal("expected wrong verifier to fail") + } + if _, _, _, err := f.svc.ExchangeAuthCode(ctx, code, f.client.ClientID, "http://localhost/cb", testVerifier); err != nil { + t.Errorf("the right verifier should still work: %v", err) + } +} + +func TestExchangeAuthCode_RefusedAfterGrantRevoked(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + code := f.code(t) + if err := f.svc.RevokeGrant(ctx, f.grant.ID); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + if _, _, _, err := f.svc.ExchangeAuthCode(ctx, code, f.client.ClientID, "http://localhost/cb", testVerifier); err == nil { + t.Error("a code under a revoked grant must not yield tokens") + } +} + +func TestRefreshAccessToken_ConcurrentRefreshesGetOnePair(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, refresh := f.tokens(t) + + var wg sync.WaitGroup + var mu sync.Mutex + succeeded := 0 + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, _, _, err := f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID); err == nil { + mu.Lock() + succeeded++ + mu.Unlock() + } + }() + } + wg.Wait() + if succeeded != 1 { + t.Errorf("%d refreshes succeeded, want exactly 1", succeeded) + } + if grant, _ := f.svc.GetGrant(ctx, f.grant.ID); grant.RevokedAt != nil { + t.Error("racing refreshes from one client must not end the connection") + } +} + +func TestRefreshAccessToken_ReuseWithinLeewayKeepsConnection(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, refresh := f.tokens(t) + + _, newRefresh, _, err := f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID) + if err != nil { + t.Fatalf("first refresh: %v", err) + } + _, _, _, err = f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID) + if err == nil { + t.Fatal("expected the used token to be refused") + } + if errors.Is(err, ErrRefreshTokenReplayed) { + t.Error("a retry within the leeway should not count as a replay") + } + if _, _, _, err := f.svc.RefreshAccessToken(ctx, newRefresh, f.client.ClientID); err != nil { + t.Errorf("the connection should still work: %v", err) + } +} + +func TestRefreshAccessToken_ReplayAfterLeewayEndsConnection(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, refresh := f.tokens(t) + + newAccess, newRefresh, _, err := f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID) + if err != nil { + t.Fatalf("first refresh: %v", err) + } + longAgo := time.Now().Add(-RefreshReuseLeeway - time.Minute) + if err := f.db.UpdateOne(ctx, "oauth_refresh_tokens", bson.M{"token_hash": hashToken(refresh)}, bson.M{"$set": bson.M{"rotated_at": longAgo}}); err != nil { + t.Fatalf("backdating: %v", err) + } + + _, _, _, err = f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID) + if !errors.Is(err, ErrRefreshTokenReplayed) { + t.Fatalf("expected ErrRefreshTokenReplayed, got %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, newAccess, testResource); err == nil { + t.Error("the newest access token should be dead after a replay") + } + if _, _, _, err := f.svc.RefreshAccessToken(ctx, newRefresh, f.client.ClientID); err == nil { + t.Error("the newest refresh token should be dead after a replay") + } +} + +func TestRefreshAccessToken_RefusesTokenFromBeforeGrants(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + _, err := f.db.InsertOne(ctx, "oauth_refresh_tokens", bson.M{ + "token_hash": hashToken("old"), + "client_id": f.client.ClientID, + "resource": testResource, + "expires_at": time.Now().Add(time.Hour), + "revoked": false, + "created_at": time.Now(), + }) + if err != nil { + t.Fatalf("insert: %v", err) + } + if _, _, _, err := f.svc.RefreshAccessToken(ctx, "old", f.client.ClientID); err == nil { + t.Error("a refresh token with no grant must be refused") + } +} + +func TestRevokeToken(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + + t.Run("another client's token is ignored", func(t *testing.T) { + access, refresh := f.tokens(t) + if err := f.svc.RevokeToken(ctx, "someone-else", refresh); err != nil { + t.Fatalf("RevokeToken: %v", err) + } + if err := f.svc.RevokeToken(ctx, "someone-else", access); err != nil { + t.Fatalf("RevokeToken: %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, access, testResource); err != nil { + t.Errorf("token should be untouched: %v", err) + } + }) + + t.Run("an access token ends alone", func(t *testing.T) { + access, refresh := f.tokens(t) + if err := f.svc.RevokeToken(ctx, f.client.ClientID, access); err != nil { + t.Fatalf("RevokeToken: %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, access, testResource); err == nil { + t.Error("revoked access token still works") + } + if _, _, _, err := f.svc.RefreshAccessToken(ctx, refresh, f.client.ClientID); err != nil { + t.Errorf("the connection should survive: %v", err) + } + }) + + t.Run("a refresh token ends the connection", func(t *testing.T) { + access, refresh := f.tokens(t) + if err := f.svc.RevokeToken(ctx, f.client.ClientID, refresh); err != nil { + t.Fatalf("RevokeToken: %v", err) + } + if _, err := f.svc.ValidateAccessToken(ctx, access, testResource); err == nil { + t.Error("access token survived its connection") + } + grant, err := f.svc.GetGrant(ctx, f.grant.ID) + if err != nil || grant.RevokedAt == nil { + t.Errorf("grant not revoked: %+v, %v", grant, err) + } + }) +} + +func TestValidateRedirectURI(t *testing.T) { + allowed := []string{ + "https://claude.ai/api/mcp/auth_callback", + "http://localhost:3334/callback", + "http://127.0.0.1:53682/cb", + "http://[::1]:53682/cb", + "HTTPS://app.example/cb", + } + for _, uri := range allowed { + if err := ValidateRedirectURI(uri); err != nil { + t.Errorf("%q should be allowed: %v", uri, err) + } + } + refused := []string{ + "", + "http://example.com/cb", + "http://localhost.example.com/cb", + "javascript:alert(1)", + "data:text/html,x", + "cursor://callback", + "/relative", + "https://app.example/cb#fragment", + "https://user:pass@app.example/cb", + "https://app.example/" + strings.Repeat("a", maxRedirectURILength), + } + for _, uri := range refused { + if err := ValidateRedirectURI(uri); err == nil { + t.Errorf("%q should be refused", uri) + } + } +} + +func TestRegisterClient_RefusesBadRedirect(t *testing.T) { + f := newOAuthFixture(t) + if _, _, err := f.svc.RegisterClient(context.Background(), "X", []string{"http://evil.example/cb"}); err == nil { + t.Error("expected refusal") + } +} + +func TestValidateClient_HoldsExistingClientsToTheRules(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + if _, err := f.db.InsertOne(ctx, "oauth_clients", &models.OAuthClient{ + ClientID: "old-client", + ClientName: "Registered before the rules", + RedirectURIs: []string{"http://evil.example/cb"}, + }); err != nil { + t.Fatalf("insert: %v", err) + } + if _, err := f.svc.ValidateClient(ctx, "old-client", "http://evil.example/cb"); err == nil { + t.Error("expected refusal") + } +} + +func TestRemoveLegacySystemKey(t *testing.T) { + db, cleanup := testutil.MustConnectTestDB(t) + defer cleanup() + ctx := context.Background() + keys := NewAPIKeyService(db) + + // Nothing to remove + if removed, err := RemoveLegacySystemKey(ctx, db); err != nil || removed { + t.Fatalf("empty database: removed=%v err=%v", removed, err) + } + + rawKey, _, err := keys.CreateAPIKeyForUser(ctx, "Renamed by someone", "Internal key", nil) + if err != nil { + t.Fatalf("CreateAPIKeyForUser: %v", err) + } + if _, err := db.Settings().InsertOne(ctx, bson.M{"type": "system_api_key", "raw_key": rawKey}); err != nil { + t.Fatalf("insert setting: %v", err) + } + _, keep, err := keys.CreateAPIKeyForUser(ctx, "A key of mine", "", nil) + if err != nil { + t.Fatalf("CreateAPIKeyForUser: %v", err) + } + if _, _, err := keys.CreateAPIKeyForUser(ctx, "System (OAuth)", "Internal key for OAuth-authenticated MCP sessions", nil); err != nil { + t.Fatalf("CreateAPIKeyForUser: %v", err) + } + + removed, err := RemoveLegacySystemKey(ctx, db) + if err != nil || !removed { + t.Fatalf("removed=%v err=%v", removed, err) + } + if _, err := keys.ValidateAPIKey(ctx, rawKey); err == nil { + t.Error("the system key still works") + } + if n, _ := db.Count(ctx, "settings", bson.M{"type": "system_api_key"}); n != 0 { + t.Error("the stored raw key is still there") + } + remaining, err := keys.ListAPIKeys(ctx) + if err != nil { + t.Fatalf("ListAPIKeys: %v", err) + } + if len(remaining) != 1 || remaining[0].ID != keep.ID { + t.Errorf("unrelated keys must survive, got %+v", remaining) + } + + // Safe to run on every boot + if removed, err := RemoveLegacySystemKey(ctx, db); err != nil || removed { + t.Errorf("second run: removed=%v err=%v", removed, err) + } +} + +func TestAssignOwner_NeverChangesAnExistingOwner(t *testing.T) { + db, cleanup := testutil.MustConnectTestDB(t) + defer cleanup() + ctx := context.Background() + keys := NewAPIKeyService(db) + + owner := primitive.NewObjectID() + _, key, err := keys.CreateAPIKeyForUser(ctx, "Mine", "", &owner) + if err != nil { + t.Fatalf("CreateAPIKeyForUser: %v", err) + } + if err := keys.AssignOwner(ctx, key.ID, primitive.NewObjectID()); err != nil { + t.Fatalf("AssignOwner: %v", err) + } + list, _ := keys.ListAPIKeysForUser(ctx, owner) + if len(list) != 1 { + t.Error("the key's owner changed") + } +} diff --git a/internal/services/oauth_test.go b/internal/services/oauth_test.go index 7ad9814..c8e737a 100644 --- a/internal/services/oauth_test.go +++ b/internal/services/oauth_test.go @@ -6,13 +6,26 @@ import ( "encoding/base64" "encoding/hex" "testing" - "time" + "github.com/metavert-io/lightcms/v7/internal/models" "github.com/metavert-io/lightcms/v7/internal/testutil" "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" ) +const testResource = "https://example.com/mcp" + +// testGrant records that a new person approved the client. +func testGrant(t *testing.T, svc *OAuthService, client *models.OAuthClient) *models.OAuthGrant { + t.Helper() + grant, err := svc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResource) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + return grant +} + func TestHashToken(t *testing.T) { token := "test-token-123" h1 := hashToken(token) @@ -216,7 +229,8 @@ func TestCreateAuthCode(t *testing.T) { svc := NewOAuthService(db) ctx := context.Background() - code, err := svc.CreateAuthCode(ctx, "client123", "http://localhost/cb", "challenge", "S256", "https://example.com/mcp") + client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) + code, err := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", "challenge", "S256") if err != nil { t.Fatalf("CreateAuthCode failed: %v", err) } @@ -252,7 +266,7 @@ func TestExchangeAuthCode_FullFlow(t *testing.T) { t.Fatalf("RegisterClient failed: %v", err) } - code, err := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, err := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") if err != nil { t.Fatalf("CreateAuthCode failed: %v", err) } @@ -285,7 +299,7 @@ func TestExchangeAuthCode_SingleUse(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") // First exchange should succeed _, _, _, err := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) @@ -312,7 +326,7 @@ func TestExchangeAuthCode_WrongPKCE(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") _, _, _, err := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", "wrong-verifier") if err == nil { @@ -332,7 +346,7 @@ func TestExchangeAuthCode_ClientMismatch(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") _, _, _, err := svc.ExchangeAuthCode(ctx, code, "wrong-client-id", "http://localhost/cb", verifier) if err == nil { @@ -352,7 +366,7 @@ func TestExchangeAuthCode_RedirectMismatch(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") _, _, _, err := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://evil.com/steal", verifier) if err == nil { @@ -385,7 +399,7 @@ func TestRefreshAccessToken(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") _, refreshToken, _, _ := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) @@ -429,7 +443,7 @@ func TestRefreshAccessToken_ClientMismatch(t *testing.T) { challenge := base64.RawURLEncoding.EncodeToString(h[:]) client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "") + code, _ := svc.CreateAuthCode(ctx, testGrant(t, svc, client), "http://localhost/cb", challenge, "S256") _, refreshToken, _, _ := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) _, _, _, err := svc.RefreshAccessToken(ctx, refreshToken, "wrong-client") @@ -449,67 +463,6 @@ func TestRefreshAccessToken_InvalidToken(t *testing.T) { } } -func TestValidateAccessToken(t *testing.T) { - db, cleanup := testutil.MustConnectTestDB(t) - defer cleanup() - - svc := NewOAuthService(db) - ctx := context.Background() - - verifier := "verifier-for-validate-test" - h := sha256.Sum256([]byte(verifier)) - challenge := base64.RawURLEncoding.EncodeToString(h[:]) - - client, _, _ := svc.RegisterClient(ctx, "Test", []string{"http://localhost/cb"}) - code, _ := svc.CreateAuthCode(ctx, client.ClientID, "http://localhost/cb", challenge, "S256", "https://example.com/mcp") - accessToken, _, _, _ := svc.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) - - // Valid token - token, err := svc.ValidateAccessToken(ctx, accessToken) - if err != nil { - t.Fatalf("ValidateAccessToken failed: %v", err) - } - if token.ClientID != client.ClientID { - t.Errorf("expected client ID %q, got %q", client.ClientID, token.ClientID) - } - if token.Resource != "https://example.com/mcp" { - t.Errorf("expected resource, got %q", token.Resource) - } - - // Invalid token - _, err = svc.ValidateAccessToken(ctx, "nonexistent") - if err == nil { - t.Error("expected error for invalid access token") - } -} - -func TestValidateAccessToken_Expired(t *testing.T) { - db, cleanup := testutil.MustConnectTestDB(t) - defer cleanup() - - svc := NewOAuthService(db) - ctx := context.Background() - - // Manually insert an expired token - rawToken := "expired-test-token" - tokenHash := hashToken(rawToken) - _, err := db.InsertOne(ctx, "oauth_access_tokens", bson.M{ - "token_hash": tokenHash, - "client_id": "test-client", - "resource": "", - "expires_at": time.Now().Add(-1 * time.Hour), - "created_at": time.Now().Add(-2 * time.Hour), - }) - if err != nil { - t.Fatalf("failed to insert expired token: %v", err) - } - - _, err = svc.ValidateAccessToken(ctx, rawToken) - if err == nil { - t.Error("expected error for expired access token") - } -} - func TestDeleteClientByID(t *testing.T) { db, cleanup := testutil.MustConnectTestDB(t) defer cleanup() diff --git a/internal/services/system_key.go b/internal/services/system_key.go index dc77294..2ee88c2 100644 --- a/internal/services/system_key.go +++ b/internal/services/system_key.go @@ -2,58 +2,40 @@ package services import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" - "log" "github.com/metavert-io/lightcms/v7/internal/database" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo/options" ) -// EnsureSystemAPIKey creates or retrieves the system-internal API key used for -// OAuth-authenticated MCP sessions. The key is associated with the given admin -// user so that OAuth-authenticated requests are authorized with admin-level -// permissions (rather than bypassing permission checks via a nil user). -// The raw key is stored in the settings collection so it persists across restarts. -func EnsureSystemAPIKey(ctx context.Context, db *database.DB, apiKeyService *APIKeyService, adminUserID *primitive.ObjectID) (string, error) { - // Check if system key already exists +// RemoveLegacySystemKey deletes what is left of the shared admin key that +// OAuth sessions used to run on before 7.5.0: the "System (OAuth)" API key and +// the stored copy of its raw value. The key goes first, so a failure part way +// leaves the stored value for the next startup to find. It reports whether it +// removed anything. +func RemoveLegacySystemKey(ctx context.Context, db *database.DB) (bool, error) { var setting struct { RawKey string `bson:"raw_key"` } - err := db.FindOne(ctx, "settings", bson.M{"type": "system_api_key"}, &setting) - if err == nil && setting.RawKey != "" { - // Verify the key is still valid in the api_keys collection - if existingKey, err := apiKeyService.ValidateAPIKey(ctx, setting.RawKey); err == nil { - // If the key exists but has no user, update it to use the admin user. - if existingKey.UserID == nil && adminUserID != nil { - db.UpdateOne(ctx, "api_keys", bson.M{"_id": existingKey.ID}, //nolint:errcheck - bson.M{"$set": bson.M{"user_id": adminUserID}}) - log.Printf("Updated system API key to associate with admin user") - } - return setting.RawKey, nil - } - // Key was deleted or invalid, fall through to create a new one - log.Printf("System API key invalid, creating new one") - } + haveSetting := db.FindOne(ctx, "settings", bson.M{"type": "system_api_key"}, &setting) == nil - // Create new system API key associated with the admin user - rawKey, _, err := apiKeyService.CreateAPIKeyForUser(ctx, "System (OAuth)", "Internal key for OAuth-authenticated MCP sessions", adminUserID) + filters := bson.A{bson.M{"name": "System (OAuth)", "description": "Internal key for OAuth-authenticated MCP sessions"}} + if setting.RawKey != "" { + sum := sha256.Sum256([]byte(setting.RawKey)) + filters = append(filters, bson.M{"key_hash": hex.EncodeToString(sum[:])}) + } + removed, err := db.DeleteMany(ctx, "api_keys", bson.M{"$or": filters}) if err != nil { - return "", fmt.Errorf("failed to create system API key: %w", err) + return false, fmt.Errorf("deleting the system API key: %w", err) } - - // Store raw key in settings for persistence - _, upsertErr := db.Settings().UpdateOne(ctx, - bson.M{"type": "system_api_key"}, - bson.M{"$set": bson.M{"type": "system_api_key", "raw_key": rawKey}}, - options.Update().SetUpsert(true), - ) - if upsertErr != nil { - return "", fmt.Errorf("failed to store system API key: %w", upsertErr) + if !haveSetting { + return removed > 0, nil } - - log.Printf("Created system API key for OAuth MCP sessions (associated with admin user)") - return rawKey, nil + if err := db.DeleteOne(ctx, "settings", bson.M{"type": "system_api_key"}); err != nil { + return removed > 0, fmt.Errorf("deleting the stored system API key: %w", err) + } + return true, nil } diff --git a/internal/services/system_key_test.go b/internal/services/system_key_test.go deleted file mode 100644 index 0376667..0000000 --- a/internal/services/system_key_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package services - -import ( - "context" - "testing" - - "github.com/metavert-io/lightcms/v7/internal/testutil" -) - -func TestEnsureSystemAPIKey_CreatesNewKey(t *testing.T) { - db, cleanup := testutil.MustConnectTestDB(t) - defer cleanup() - - apiKeySvc := NewAPIKeyService(db) - ctx := context.Background() - - rawKey, err := EnsureSystemAPIKey(ctx, db, apiKeySvc, nil) - if err != nil { - t.Fatalf("EnsureSystemAPIKey failed: %v", err) - } - - if rawKey == "" { - t.Error("expected non-empty raw key") - } - - // Key should be valid - _, err = apiKeySvc.ValidateAPIKey(ctx, rawKey) - if err != nil { - t.Fatalf("system key should be valid: %v", err) - } -} - -func TestEnsureSystemAPIKey_ReturnsCachedKey(t *testing.T) { - db, cleanup := testutil.MustConnectTestDB(t) - defer cleanup() - - apiKeySvc := NewAPIKeyService(db) - ctx := context.Background() - - // First call creates - key1, err := EnsureSystemAPIKey(ctx, db, apiKeySvc, nil) - if err != nil { - t.Fatalf("first EnsureSystemAPIKey failed: %v", err) - } - - // Second call returns same key - key2, err := EnsureSystemAPIKey(ctx, db, apiKeySvc, nil) - if err != nil { - t.Fatalf("second EnsureSystemAPIKey failed: %v", err) - } - - if key1 != key2 { - t.Error("expected same key on second call") - } -} - -func TestEnsureSystemAPIKey_RecreatesDeletedKey(t *testing.T) { - db, cleanup := testutil.MustConnectTestDB(t) - defer cleanup() - - apiKeySvc := NewAPIKeyService(db) - ctx := context.Background() - - // Create system key - key1, _ := EnsureSystemAPIKey(ctx, db, apiKeySvc, nil) - - // Delete all API keys (simulating key deletion) - keys, _ := apiKeySvc.ListAPIKeys(ctx) - for _, k := range keys { - apiKeySvc.DeleteAPIKey(ctx, k.ID) - } - - // Should create a new key since the old one is invalid - key2, err := EnsureSystemAPIKey(ctx, db, apiKeySvc, nil) - if err != nil { - t.Fatalf("EnsureSystemAPIKey after deletion failed: %v", err) - } - - if key1 == key2 { - t.Error("expected different key after deletion") - } - - // New key should be valid - _, err = apiKeySvc.ValidateAPIKey(ctx, key2) - if err != nil { - t.Fatal("new system key should be valid") - } -} diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 9fabd30..f5de2b8 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -221,7 +221,7 @@ func CleanupCollections(t *testing.T, db *database.DB) { "custom_pages", "settings", "theme_versions", "contact_messages", "login_attempts", "assets", "api_keys", "redirects", "snippets", "users", "audit_logs", "user_activity", - "oauth_clients", "oauth_auth_codes", "oauth_access_tokens", "oauth_refresh_tokens", + "oauth_clients", "oauth_grants", "oauth_auth_codes", "oauth_access_tokens", "oauth_refresh_tokens", "content_comments", "content_locks", "webhooks", "webhook_deliveries", "content_forks", "approval_workflows", "approval_requests", "import_sources", "import_jobs", "link_check_jobs", "regen_jobs", From 65fe5c3ad8ea484c6946f0dc397950f1825d415f Mon Sep 17 00:00:00 2001 From: "Jon Radoff (Metavert)" Date: Mon, 9 Nov 2026 21:21:18 -0500 Subject: [PATCH 2/2] Close the review's findings on OAuth identity - Reverting to a version, or restoring a deleted page, that changes whether a live page is published now needs content.publish. - One active grant per person and client is enforced by a unique partial index; a racing second approval reuses the first grant. - A used refresh token is excused only within 10 seconds of rotation. - Access tokens never begin with "lc_", which marks an API key. - The consent page no longer points at a page that doesn't exist yet. - Session binding is tested for GET and DELETE as well as POST. Co-Authored-By: Claude Opus 5.5 --- internal/database/mongo.go | 18 ++++++++ internal/handlers/api_content.go | 26 ++++++++++++ internal/handlers/api_identity_test.go | 44 +++++++++++++++++++ internal/mcp/http_handler_test.go | 16 +++++++ internal/oauth/templates.go | 2 +- internal/services/oauth.go | 29 +++++++++---- internal/services/oauth_grant_test.go | 59 ++++++++++++++++++++++++++ 7 files changed, 184 insertions(+), 10 deletions(-) diff --git a/internal/database/mongo.go b/internal/database/mongo.go index b22cb31..82c5091 100644 --- a/internal/database/mongo.go +++ b/internal/database/mongo.go @@ -64,6 +64,17 @@ func Connect(ctx context.Context, uri, dbName string, extraOpts ...*options.Clie return db, nil } +// OAuthGrantIndex is the unique index that allows one active OAuth grant per +// person and client. SaveGrant inserts grants with revoked_at: null. +func OAuthGrantIndex() mongo.IndexModel { + return mongo.IndexModel{ + Keys: bson.D{{Key: "client_id", Value: 1}, {Key: "user_id", Value: 1}}, + Options: options.Index().SetUnique(true). + SetPartialFilterExpression(bson.M{"revoked_at": bson.M{"$type": "null"}}). + SetName("one_active_grant_per_person_and_client"), + } +} + func (db *DB) createIndexes(ctx context.Context) error { // Content full_path index (unique for live content only). // Fork copies share the same full_path as their live counterpart, so the @@ -298,6 +309,13 @@ func (db *DB) createIndexes(ctx context.Context) error { return err } + // OAuth grants: one active grant per person and client. Revoking a grant + // sets revoked_at, which takes it out of the index. + _, err = db.database.Collection("oauth_grants").Indexes().CreateOne(ctx, OAuthGrantIndex()) + if err != nil { + return err + } + // Users: unique email _, err = db.database.Collection("users").Indexes().CreateOne(ctx, mongo.IndexModel{ Keys: bson.D{{Key: "email", Value: 1}}, diff --git a/internal/handlers/api_content.go b/internal/handlers/api_content.go index 7fecdf6..a20ed6b 100644 --- a/internal/handlers/api_content.go +++ b/internal/handlers/api_content.go @@ -645,6 +645,16 @@ func (a *APIHandler) APIRestoreContent(w http.ResponseWriter, r *http.Request) { return } + // Restoring a page that was live before it was deleted publishes it again. + deleted, err := a.contentService.GetContent(r.Context(), id) + if err != nil { + a.jsonError(w, http.StatusNotFound, "content not found") + return + } + if deleted.PublishedBeforeDelete && deleted.ForkID == nil && !deleted.Hold && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } + if err := a.contentService.RestoreContent(r.Context(), id); err != nil { a.jsonError(w, http.StatusInternalServerError, err.Error()) return @@ -765,6 +775,22 @@ func (a *APIHandler) APIRevertContentVersion(w http.ResponseWriter, r *http.Requ comment = fmt.Sprintf("Reverted to version %d", version) } + // A revert restores the version's published state too: changing what + // is live needs content.publish, as publishing does. + current, err := a.contentService.GetContent(r.Context(), id) + if err != nil { + a.jsonError(w, http.StatusNotFound, "content not found") + return + } + target, err := a.contentService.GetVersion(r.Context(), id, version) + if err != nil { + a.jsonError(w, http.StatusNotFound, "version not found") + return + } + if target.Published != current.Published && current.ForkID == nil && !a.requirePermission(w, r, auth.PermContentPublish) { + return + } + if err := a.contentService.RevertToVersion(r.Context(), id, version, comment); err != nil { a.jsonError(w, http.StatusInternalServerError, err.Error()) return diff --git a/internal/handlers/api_identity_test.go b/internal/handlers/api_identity_test.go index b25acd3..3ba5470 100644 --- a/internal/handlers/api_identity_test.go +++ b/internal/handlers/api_identity_test.go @@ -161,6 +161,50 @@ func TestPublishPermission_UpdateRequiresItOnlyToChangeState(t *testing.T) { } } +func TestPublishPermission_RevertAndRestoreRequireItToChangeWhatIsLive(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + router := apiRouterWithKeys(a, publishCallers()) + tmpl := seedTemplate(t, db, "Page", "page").Hex() + + // Version 1 is a published page; version 2 takes it down. + rr := sendJSON(router, "lc_editor", "POST", "/api/v1/content", fmt.Sprintf(`{"template_id":%q,"title":"T","slug":"revert-me","data":{},"published":true}`, tmpl)) + if rr.Code != http.StatusCreated { + t.Fatalf("create: %d %s", rr.Code, rr.Body.String()) + } + var page models.Content + json.Unmarshal(rr.Body.Bytes(), &page) + id := page.ID.Hex() + if rr := sendJSON(router, "lc_editor", "PUT", "/api/v1/content/"+id, `{"published":false}`); rr.Code != http.StatusOK { + t.Fatalf("unpublish: %d %s", rr.Code, rr.Body.String()) + } + + if rr := sendJSON(router, "lc_writer", "POST", "/api/v1/content/"+id+"/versions/1/revert", `{}`); rr.Code != http.StatusForbidden { + t.Errorf("reverting to a published version: %d %s", rr.Code, rr.Body.String()) + } + if _, published := pagePublished(t, db, "revert-me"); published { + t.Fatal("the revert published the page") + } + // Reverting to a version in the same state is an ordinary edit. + if rr := sendJSON(router, "lc_writer", "POST", "/api/v1/content/"+id+"/versions/2/revert", `{}`); rr.Code != http.StatusOK { + t.Errorf("reverting within the same state: %d %s", rr.Code, rr.Body.String()) + } + + // A page that was live when it was deleted comes back live on restore. + if rr := sendJSON(router, "lc_editor", "PUT", "/api/v1/content/"+id, `{"published":true}`); rr.Code != http.StatusOK { + t.Fatalf("republish: %d %s", rr.Code, rr.Body.String()) + } + if err := a.contentService.DeleteContent(context.Background(), page.ID); err != nil { + t.Fatalf("DeleteContent: %v", err) + } + if rr := sendJSON(router, "lc_writer", "POST", "/api/v1/content/"+id+"/restore", ``); rr.Code != http.StatusForbidden { + t.Errorf("restoring a page that was live: %d %s", rr.Code, rr.Body.String()) + } + if rr := sendJSON(router, "lc_editor", "POST", "/api/v1/content/"+id+"/restore", ``); rr.Code != http.StatusOK { + t.Errorf("editor restoring: %d %s", rr.Code, rr.Body.String()) + } +} + func TestPublishedField_IgnoredOnForkCopies(t *testing.T) { a, db, cleanup := newTestAPIHandler(t) defer cleanup() diff --git a/internal/mcp/http_handler_test.go b/internal/mcp/http_handler_test.go index 9b4f91b..e4d56a2 100644 --- a/internal/mcp/http_handler_test.go +++ b/internal/mcp/http_handler_test.go @@ -211,6 +211,22 @@ func TestHTTPHandler_SessionIsBoundToTheCredentialThatOpenedIt(t *testing.T) { if resp := send("bob-token"); resp.StatusCode != http.StatusForbidden { t.Errorf("another credential got %d, want 403", resp.StatusCode) } + + // The event stream and session deletion are bound the same way. + for _, method := range []string{http.MethodGet, http.MethodDelete} { + req, _ := http.NewRequest(method, srv.URL, nil) + req.Header.Set("Authorization", "Bearer bob-token") + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Mcp-Session-Id", session.ID()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("%s: %v", method, err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Errorf("%s with another credential: %d, want 403", method, resp.StatusCode) + } + } if got := fake.lastCaller(); got != "" { t.Errorf("a tool ran as %q on someone else's session", got) } diff --git a/internal/oauth/templates.go b/internal/oauth/templates.go index e9da545..b8fd0c3 100644 --- a/internal/oauth/templates.go +++ b/internal/oauth/templates.go @@ -179,7 +179,7 @@ var oauthTemplates = map[string]string{ diff --git a/internal/services/oauth.go b/internal/services/oauth.go index 813df3e..3927e84 100644 --- a/internal/services/oauth.go +++ b/internal/services/oauth.go @@ -32,7 +32,7 @@ const ( // use is refused without ending the connection. Two requests from one // client racing to refresh are not an attack; a used token that comes back // later is. - RefreshReuseLeeway = 30 * time.Second + RefreshReuseLeeway = 10 * time.Second // grantTouchInterval limits how often a grant's last-used time is written. grantTouchInterval = time.Minute @@ -192,14 +192,21 @@ func (s *OAuthService) ValidateClientCredentials(ctx context.Context, clientID, func (s *OAuthService) SaveGrant(ctx context.Context, client *models.OAuthClient, userID primitive.ObjectID, resource string) (*models.OAuthGrant, error) { now := time.Now() var grant models.OAuthGrant - err := s.db.Collection("oauth_grants").FindOneAndUpdate(ctx, - bson.M{"client_id": client.ClientID, "user_id": userID, "revoked_at": nil}, - bson.M{ - "$set": bson.M{"client_name": client.ClientName, "resource": resource, "updated_at": now}, - "$setOnInsert": bson.M{"created_at": now}, - }, - options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After), - ).Decode(&grant) + save := func() error { + return s.db.Collection("oauth_grants").FindOneAndUpdate(ctx, + bson.M{"client_id": client.ClientID, "user_id": userID, "revoked_at": nil}, + bson.M{ + "$set": bson.M{"client_name": client.ClientName, "resource": resource, "updated_at": now}, + "$setOnInsert": bson.M{"created_at": now}, + }, + options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After), + ).Decode(&grant) + } + err := save() + if mongo.IsDuplicateKeyError(err) { + // Another approval inserted the grant first; update that one. + err = save() + } if err != nil { return nil, fmt.Errorf("failed to save grant: %w", err) } @@ -449,6 +456,10 @@ func (s *OAuthService) ValidateAccessToken(ctx context.Context, rawToken, resour // generateTokenPair creates and stores a new access token + refresh token func (s *OAuthService) generateTokenPair(ctx context.Context, grant *models.OAuthGrant) (string, string, int, error) { rawAccess, err := generateToken(48) + // Bearer tokens that start with "lc_" are taken to be API keys. + for err == nil && strings.HasPrefix(rawAccess, "lc_") { + rawAccess, err = generateToken(48) + } if err != nil { return "", "", 0, fmt.Errorf("failed to generate access token: %w", err) } diff --git a/internal/services/oauth_grant_test.go b/internal/services/oauth_grant_test.go index a901915..be5060d 100644 --- a/internal/services/oauth_grant_test.go +++ b/internal/services/oauth_grant_test.go @@ -100,6 +100,65 @@ func TestSaveGrant_OneActiveGrantPerPersonAndClient(t *testing.T) { } } +func TestSaveGrant_ConcurrentApprovalsMakeOneGrant(t *testing.T) { + f := newOAuthFixture(t) + ctx := context.Background() + if _, err := f.db.Collection("oauth_grants").Indexes().CreateOne(ctx, database.OAuthGrantIndex()); err != nil { + t.Fatalf("creating index: %v", err) + } + user := primitive.NewObjectID() + + var wg sync.WaitGroup + ids := make(chan primitive.ObjectID, 8) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + grant, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + if err != nil { + t.Errorf("SaveGrant: %v", err) + return + } + ids <- grant.ID + }() + } + wg.Wait() + close(ids) + seen := map[primitive.ObjectID]bool{} + for id := range ids { + seen[id] = true + } + if len(seen) != 1 { + t.Errorf("%d grants for one person and client, want 1", len(seen)) + } + if n, _ := f.db.Count(ctx, "oauth_grants", bson.M{"user_id": user, "revoked_at": nil}); n != 1 { + t.Errorf("%d active grants stored, want 1", n) + } + + // A revoked grant leaves the index, so the person can connect again. + for id := range seen { + if err := f.svc.RevokeGrant(ctx, id); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + } + if _, err := f.svc.SaveGrant(ctx, f.client, user, testResource); err != nil { + t.Errorf("reconnecting after a revoke: %v", err) + } +} + +func TestGenerateTokenPair_AccessTokenNeverLooksLikeAnAPIKey(t *testing.T) { + f := newOAuthFixture(t) + for i := 0; i < 50; i++ { + access, _, _, err := f.svc.generateTokenPair(context.Background(), f.grant) + if err != nil { + t.Fatalf("generateTokenPair: %v", err) + } + if strings.HasPrefix(access, "lc_") { + t.Fatalf("access token %q starts like an API key", access) + } + } +} + func TestValidateAccessToken(t *testing.T) { f := newOAuthFixture(t) ctx := context.Background()