diff --git a/admin/openapi/admin.json b/admin/openapi/admin.json index c4226263..4e0bcf57 100644 --- a/admin/openapi/admin.json +++ b/admin/openapi/admin.json @@ -1338,6 +1338,36 @@ ], "type": "object" }, + "cabana.Envelope-cabana_MCPConsentDecisionView": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.MCPConsentDecisionView" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, + "cabana.Envelope-cabana_MCPConsentView": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.MCPConsentView" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, "cabana.Envelope-cabana_PartialView": { "properties": { "data": { @@ -2586,6 +2616,123 @@ ], "type": "object" }, + "cabana.MCPConsentAdminView": { + "properties": { + "email": { + "type": "string" + }, + "login": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "email", + "login", + "name" + ], + "type": "object" + }, + "cabana.MCPConsentClientView": { + "properties": { + "id": { + "type": "string" + }, + "logo_url": { + "type": "string" + }, + "name": { + "type": "string" + }, + "redirect_host": { + "type": "string" + } + }, + "required": [ + "id", + "logo_url", + "name", + "redirect_host" + ], + "type": "object" + }, + "cabana.MCPConsentDecisionRequest": { + "properties": { + "decision": { + "enum": [ + "allow", + "deny" + ], + "type": "string" + }, + "offline_access": { + "type": "boolean" + }, + "scopes": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "decision", + "offline_access", + "scopes" + ], + "type": "object" + }, + "cabana.MCPConsentDecisionView": { + "properties": { + "redirect_uri": { + "type": "string" + } + }, + "required": [ + "redirect_uri" + ], + "type": "object" + }, + "cabana.MCPConsentView": { + "properties": { + "admin": { + "$ref": "#/components/schemas/cabana.MCPConsentAdminView" + }, + "client": { + "$ref": "#/components/schemas/cabana.MCPConsentClientView" + }, + "consent_required": { + "type": "boolean" + }, + "expires_at": { + "type": "string" + }, + "offline_access": { + "type": "boolean" + }, + "request_id": { + "type": "string" + }, + "scopes": { + "items": { + "$ref": "#/components/schemas/cabana.AdminAPITokenScope" + }, + "type": "array" + } + }, + "required": [ + "admin", + "client", + "consent_required", + "expires_at", + "offline_access", + "request_id", + "scopes" + ], + "type": "object" + }, "cabana.MarketplaceMeta": { "properties": { "categories": { @@ -4960,6 +5107,169 @@ ] } }, + "/mcp/consent/{request}": { + "get": { + "description": "Shows a pending MCP authorization request of an administrator-only grant to the signed-in admin, as the plugin that owns the MCP authorization server resolves it. Only requested scopes the admin can grant are listed. 404 request_not_found when the request is missing, expired or used, or no plugin serves admin consent. Personal API tokens are refused (403 interactive_only).", + "parameters": [ + { + "description": "Pending request id", + "in": "path", + "name": "request", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_MCPConsentView" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Show an MCP consent request", + "tags": [ + "admin" + ] + }, + "post": { + "description": "Allows or denies a pending MCP authorization request for the signed-in admin and answers the client redirect URI. Submitted scopes that were not requested or that the admin cannot grant are dropped, * collapses as for personal tokens, and 422 no_grantable_scopes answers when nothing is left. Needs X-Requested-With; the body is capped at 16 KiB and unknown fields are refused (400). Personal API tokens are refused (403 interactive_only).", + "parameters": [ + { + "description": "Pending request id", + "in": "path", + "name": "request", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.MCPConsentDecisionRequest" + } + } + }, + "description": "Decision", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_MCPConsentDecisionView" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Allow or deny an MCP consent request", + "tags": [ + "admin" + ] + } + }, "/navigation": { "get": { "responses": { diff --git a/admin/src/api/schema.d.ts b/admin/src/api/schema.d.ts index 0e22b24c..2620db81 100644 --- a/admin/src/api/schema.d.ts +++ b/admin/src/api/schema.d.ts @@ -1559,6 +1559,151 @@ export interface paths { patch?: never; trace?: never; }; + "/mcp/consent/{request}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Show an MCP consent request + * @description Shows a pending MCP authorization request of an administrator-only grant to the signed-in admin, as the plugin that owns the MCP authorization server resolves it. Only requested scopes the admin can grant are listed. 404 request_not_found when the request is missing, expired or used, or no plugin serves admin consent. Personal API tokens are refused (403 interactive_only). + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Pending request id */ + request: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_MCPConsentView"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + put?: never; + /** + * Allow or deny an MCP consent request + * @description Allows or denies a pending MCP authorization request for the signed-in admin and answers the client redirect URI. Submitted scopes that were not requested or that the admin cannot grant are dropped, * collapses as for personal tokens, and 422 no_grantable_scopes answers when nothing is left. Needs X-Requested-With; the body is capped at 16 KiB and unknown fields are refused (400). Personal API tokens are refused (403 interactive_only). + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Pending request id */ + request: string; + }; + cookie?: never; + }; + /** @description Decision */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.MCPConsentDecisionRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_MCPConsentDecisionView"]; + }; + }; + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/navigation": { parameters: { query?: never; @@ -6429,6 +6574,14 @@ export interface components { data: components["schemas"]["cabana.ListSchema"]; meta: components["schemas"]["cabana.SuccessMeta"]; }; + "cabana.Envelope-cabana_MCPConsentDecisionView": { + data: components["schemas"]["cabana.MCPConsentDecisionView"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; + "cabana.Envelope-cabana_MCPConsentView": { + data: components["schemas"]["cabana.MCPConsentView"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; "cabana.Envelope-cabana_PartialView": { data: components["schemas"]["cabana.PartialView"]; meta: components["schemas"]["cabana.SuccessMeta"]; @@ -6911,6 +7064,35 @@ export interface components { column: string; direction: string; }; + "cabana.MCPConsentAdminView": { + email: string; + login: string; + name: string; + }; + "cabana.MCPConsentClientView": { + id: string; + logo_url: string; + name: string; + redirect_host: string; + }; + "cabana.MCPConsentDecisionRequest": { + /** @enum {string} */ + decision: "allow" | "deny"; + offline_access: boolean; + scopes: string[]; + }; + "cabana.MCPConsentDecisionView": { + redirect_uri: string; + }; + "cabana.MCPConsentView": { + admin: components["schemas"]["cabana.MCPConsentAdminView"]; + client: components["schemas"]["cabana.MCPConsentClientView"]; + consent_required: boolean; + expires_at: string; + offline_access: boolean; + request_id: string; + scopes: components["schemas"]["cabana.AdminAPITokenScope"][]; + }; "cabana.MarketplaceMeta": { categories: string[]; registry: components["schemas"]["cabana.RegistryState"]; diff --git a/docs/services/oauth-server.md b/docs/services/oauth-server.md index 155ce5af..d37ccad2 100644 --- a/docs/services/oauth-server.md +++ b/docs/services/oauth-server.md @@ -118,6 +118,8 @@ The authorization endpoint sends the browser to `/connect?request=`, An OAuth server plugin that signs administrators in instead of frontend users answers its verifier's grants with `pact.MCPGrant.Subject` set to `pact.MCPGrantSubjectBackend`, `UserID` 0 and the administrator in `pact.MCPGrant.BackendUserID`. The MCP endpoint then acts as that administrator only, scope-limited like a `g15_` token with the granted scopes (see [MCP](mcp.md)). +The consent page of such grants is the admin's own: the plugin sets `wristband.Options.ConsentPath` to a page under the admin prefix and publishes a `pact.MCPAdminConsent`. cabana serves `GET` and `POST {admin api}/mcp/consent/{request}` for the signed-in administrator (cookie session only, the POST with `X-Requested-With`) and delegates to that provider: `pact.MCPAdminConsent.MCPAdminConsentShow` describes the pending request as a `pact.MCPAdminConsentRequest`, `pact.MCPAdminConsent.MCPAdminConsentDecide` issues the code or the denial for a `pact.MCPAdminConsentDecision` and answers the redirect URI. cabana owns the scope policy, the same as for `g15_` personal tokens: the scopes are the token-scope catalog (`cabana.TokenScopeNames`, labels through `cabana.TokenScopeLabels`), the screen shows only requested scopes the administrator can grant, and an allow drops anything else before Decide runs (`*` collapses as on token creation). A missing provider or request is 404 `request_not_found` (`pact.ErrMCPConsentNotFound`), and nothing left to grant is 422 `no_grantable_scopes` (`pact.ErrMCPConsentNoScopes`). + ## Clients created outside registration Operator tooling that creates clients directly uses the same rules as registration. `wristband.RejectRedirectURI` accepts `https://` URIs and loopback `http://` URIs only: diff --git a/modules/cabana/README.md b/modules/cabana/README.md index f7c38d7c..e428839f 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -92,6 +92,8 @@ Guarded routes run surf's `locale.from-principal` after the backend guard: an in | DELETE `/account/tokens/{id}` | Soft-revoke one of the caller's own active tokens (`cabana.AdminAPIToken`); 404 otherwise. Interactive session only. | | GET `/account/tokens/scopes` | Scopes the caller may assign (`cabana.AdminAPITokenScope`), including `*`, `admin:read` and overlapping plugin scopes. Interactive session only. | | GET `/account/contributions` | The sections plugins contribute to My account (`cabana.AccountContributionView`): translated label, description and status for the signed-in administrator, and the actions (`cabana.AccountContributionActionView`) they hold the permissions for and whose `Applies` reports true. A section whose status or one of whose actions' `Applies` failed carries `error: true`. An empty list when no plugin contributes. Interactive session only. | +| GET `/mcp/consent/{request}` | A pending MCP authorization request of an administrator-only grant (`cabana.MCPConsentView`), resolved by the published `pact.MCPAdminConsent` for the signed-in administrator: the client (`cabana.MCPConsentClientView`, with the redirect URI's host), the administrator (`cabana.MCPConsentAdminView`: login, name, email), the requested scopes the administrator can grant in catalog order (`cabana.AdminAPITokenScope`; scopes outside the catalog or without an owned permission are hidden, as in the token picker), `offline_access` (requested), `consent_required` and `expires_at`. 404 `request_not_found` when no provider is published or the request is unknown. Interactive session only. | +| POST `/mcp/consent/{request}` | Allow or deny that request (`cabana.MCPConsentDecisionRequest`: `decision` `allow` or `deny`, `scopes`, `offline_access`; at most 16 KiB, unknown fields 400). An allow keeps the submitted scopes that were requested and can be granted (others are dropped), normalises them like token creation (`*` collapses to `["*"]`), answers 422 `no_grantable_scopes` when nothing is left and grants offline access only when it was requested and asked for; the answer is `cabana.MCPConsentDecisionView` (`redirect_uri`). cabana opens no transaction: the provider owns it. Interactive session only, AJAX header required. | | POST `/account/contributions/{name}/actions/{action}` | Run one contributed action for the signed-in administrator: 404 for an unknown section or action, 403 without the action's permissions, 409 when it no longer applies; `Run` gets the administrator's id inside a transaction and answers `cabana.AccountActionResultView` (translated `message`, optional `url`, only an `http`/`https` or same-origin URL). Interactive session only, AJAX header required. | | GET `/navigation`, GET `/settings` | Navigation and settings entries the administrator may open and, for a navigation entry with a `Visible` func, that it answers true for the request; a settings entry's `controller` names the admin controller a link entry opens and is empty for a singleton form, and `path` (only on the admin's own Plugins entry) names the SPA route it opens. | | GET `/plugins` | The Plugins screen (`cabana.PluginsOverview`): the framework version the application was built with, the registry state (`cabana.RegistryState`: `enabled`, `status` ok, disabled or unavailable) and every activated plugin in summer.yaml order (`cabana.InstalledPlugin`) with, for a plugin the registry lists, `latest`, `updateAvailable`, `updateCommand` and `latestFramework`. 403 without `cabana.PermissionViewPlugins`. | @@ -279,6 +281,9 @@ func (p *BlogPlugin) AdminFS() fs.FS { return os.DirFS("testdata/docs") } | `cabana.ErrUnauthenticated` / `cabana.ErrTokenScope` | Sentinel errors from `cabana.ResolveBackend`. | | `cabana.ResolveBackendToken` | Resolves a `g15_` token outside any request (same hash lookup, usability window, admin load and `last_used_at` stamp as the guard) without the request-method scope filter; returns the principal, the token row and the stored scope names. For an in-process dispatcher that opens a session with a personal token. Each attempt is logged as `admin.auth` with the client address the caller put on the context (`towel.ClientIP`). | | `cabana.ScopeLimitFor` | Filters stored scope names by one HTTP method into the `bouncer.ScopeLimit` the guard would set for a request with that method, with the known and method-allowed counts. | +| `cabana.TokenScopeNames` | The personal-token scope catalog names in catalog order (`*`, `admin:read`, then the plugins' `TokenScopes`), compiled from the activated plugins, so it works at plugin Boot before `cabana.Activate`. | +| `cabana.TokenScopeLabels` | The translated label of each catalog scope name, the name itself for an unknown one, in input order. | +| `cabana.MCPConsentView` / `cabana.MCPConsentClientView` / `cabana.MCPConsentAdminView` / `cabana.MCPConsentDecisionRequest` / `cabana.MCPConsentDecisionView` | JSON shapes of the MCP consent routes. `cabana.AdminMCPConsentShow` and `cabana.AdminMCPConsentDecide` carry their swag annotations. | | `cabana.BackendPrincipal` | Loads an admin principal by id through the backend users provider (grants, superuser flag, backend kind set); nil, nil for a missing or deactivated admin. | | `cabana.AdminAPIToken` / `cabana.AdminAPITokenScope` / `cabana.AdminAPITokenCreated` / `cabana.AdminAPITokenRequest` | JSON shapes of the account token API. | | `cabana.AccountContributionView` / `cabana.AccountContributionActionView` / `cabana.AccountActionResultView` | JSON shapes of the My account contribution routes: a contributed section with its status and offered actions, one action, and an action's answer (message and optional URL). | @@ -455,6 +460,8 @@ The Phase 18.1 pieces (the taglist field and the flat reorder) are covered by Do `ClearOnChange` is covered by `clear_on_change_field_test.go` (TestClearOnChangeFieldBoot, Docker-free, and TestClearOnChangeBelongsTo on Postgres: a changed, emptied, kept or co-submitted belongsTo key) and `clear_on_change_test.go` (TestClearOnChangeRelationBoot and, on Postgres, TestClearOnChangeHasMany: link, unlink and a deferred link committed by the parent's first save). +The MCP consent routes are covered by the Postgres test TestMCPAdminConsentSmoke in `mcp_consent_smoke_test.go`, over a fake `pact.MCPAdminConsent`: hidden scopes, a dropped `*` that was not requested, a requested `*` collapsing the grant, offline access, deny, 400 for a bad body, 401 anonymous, 403 `interactive_only` for a `g15_` token and 404 without a provider or for an unknown request. TestTokenScopeNamesAndLabels covers the exported catalog names and labels. + The toolbar and widget action run log is covered by the Postgres test TestAdminActionRunLog in `action_run_log_test.go`: who ran the action, its kind, the field and record id of a widget run, no posted or returned content, and no line for refused, invalid or failed runs. A Detached bulk action (`pact.AdminBulkAction.Detached`) is covered by the Postgres test TestDetachedBulkAction in `bulk_detached_test.go`, on the roster fixture with two test-only actions: Run sees no transaction (`TxFromContext`) and holds no row lock (another connection's `SELECT ... FOR UPDATE NOWAIT` succeeds during Run); the empty, absent and partial-selection rules match the locked path; a `ValidationError` from Run is 422 and the rows written before it stay written; the same action without Detached still runs in the transaction holding the row locks. `scripts/check-phase18.1.sh` requires it in its postgres stage. diff --git a/modules/cabana/admin_openapi.go b/modules/cabana/admin_openapi.go index f28d21e6..53bdced1 100644 --- a/modules/cabana/admin_openapi.go +++ b/modules/cabana/admin_openapi.go @@ -396,6 +396,88 @@ func AdminAccountContributions() {} // @Router /account/contributions/{name}/actions/{action} [post] func AdminAccountContributionAction() {} +// MCPConsentView is a pending MCP authorization request of an +// administrator-only grant, for the signed-in administrator's consent +// screen: the client, the administrator the grant would act as, the +// requested scopes this administrator can grant (catalog order, others +// hidden), whether offline access was requested, whether consent must be +// asked (false when the client was allowed before) and the expiry (RFC 3339). +type MCPConsentView struct { + RequestID string `json:"request_id"` + Client MCPConsentClientView `json:"client"` + Admin MCPConsentAdminView `json:"admin"` + Scopes []AdminAPITokenScope `json:"scopes"` + OfflineAccess bool `json:"offline_access"` + ConsentRequired bool `json:"consent_required"` + ExpiresAt string `json:"expires_at"` +} + +// MCPConsentClientView is the client of a consent request: its id, name, +// logo and redirect host (the host of the redirect URI, or the URI without +// query when it has no host). +type MCPConsentClientView struct { + ID string `json:"id"` + Name string `json:"name"` + RedirectHost string `json:"redirect_host"` + LogoURL string `json:"logo_url"` +} + +// MCPConsentAdminView is the administrator a consent grants access as. +type MCPConsentAdminView struct { + Login string `json:"login"` + Name string `json:"name"` + Email string `json:"email"` +} + +// MCPConsentDecisionRequest is the POST /mcp/consent/{request} body: +// decision allow or deny, the scopes to grant and whether to stay +// connected (offline access). Unknown fields are refused. +type MCPConsentDecisionRequest struct { + Decision string `json:"decision" enums:"allow,deny"` + Scopes []string `json:"scopes"` + OfflineAccess bool `json:"offline_access"` +} + +// MCPConsentDecisionView is the answer to a decision: the client redirect +// URI to send the browser to. +type MCPConsentDecisionView struct { + RedirectURI string `json:"redirect_uri"` +} + +// AdminMCPConsentShow documents GET /mcp/consent/{request}. +// +// @Summary Show an MCP consent request +// @Description Shows a pending MCP authorization request of an administrator-only grant to the signed-in admin, as the plugin that owns the MCP authorization server resolves it. Only requested scopes the admin can grant are listed. 404 request_not_found when the request is missing, expired or used, or no plugin serves admin consent. Personal API tokens are refused (403 interactive_only). +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param request path string true "Pending request id" +// @Success 200 {object} Envelope[MCPConsentView] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Router /mcp/consent/{request} [get] +func AdminMCPConsentShow() {} + +// AdminMCPConsentDecide documents POST /mcp/consent/{request}. +// +// @Summary Allow or deny an MCP consent request +// @Description Allows or denies a pending MCP authorization request for the signed-in admin and answers the client redirect URI. Submitted scopes that were not requested or that the admin cannot grant are dropped, * collapses as for personal tokens, and 422 no_grantable_scopes answers when nothing is left. Needs X-Requested-With; the body is capped at 16 KiB and unknown fields are refused (400). Personal API tokens are refused (403 interactive_only). +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param request path string true "Pending request id" +// @Param body body MCPConsentDecisionRequest true "Decision" +// @Success 200 {object} Envelope[MCPConsentDecisionView] +// @Failure 400 {object} ErrorEnvelope +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /mcp/consent/{request} [post] +func AdminMCPConsentDecide() {} + // AdminAccountTokenScopes documents GET /account/tokens/scopes. // // @Summary List available API token scopes diff --git a/modules/cabana/http.go b/modules/cabana/http.go index e8ad3e97..48d068ba 100644 --- a/modules/cabana/http.go +++ b/modules/cabana/http.go @@ -348,6 +348,10 @@ func (s *service) mount(r pact.Router) { // Sections plugins contribute to My account (pact.HasAccountContributions). g.Get("/account/contributions", interactiveOnly(s.accountContributionsList)) g.Post("/account/contributions/{name}/actions/{action}", interactiveOnly(requireAjax(s.accountContributionAction))) + // Consent of administrator-only MCP grants, served for the + // published pact.MCPAdminConsent (404 when none is published). + g.Get("/mcp/consent/{request}", interactiveOnly(s.mcpConsentShow)) + g.Post("/mcp/consent/{request}", interactiveOnly(requireAjax(s.mcpConsentDecide))) g.Get("/navigation", s.navigation) // Plugin field types (pact.HasFormFieldTypes): the SPA loads their // scripts and styles once after sign-in. diff --git a/modules/cabana/mcp_consent.go b/modules/cabana/mcp_consent.go new file mode 100644 index 00000000..d6ea5f62 --- /dev/null +++ b/modules/cabana/mcp_consent.go @@ -0,0 +1,233 @@ +package cabana + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strings" + "time" + + "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/pact" +) + +// maxMCPConsentBody caps the POST /mcp/consent/{request} body. +const maxMCPConsentBody = 16 << 10 + +// Messages of the consent endpoints (phrase keys under backend::lang). +const ( + mcpConsentNotFoundKey = "mcp_connect.request_not_found" + mcpConsentNotFoundFallback = "This connection request has expired or does not exist." + mcpConsentNoScopesKey = "mcp_connect.no_grantable_scopes" + mcpConsentNoScopesFallback = "Choose at least one scope you can use." +) + +// mcpConsentProvider answers the published pact.MCPAdminConsent, nil when +// no plugin publishes one. +func (s *service) mcpConsentProvider() pact.MCPAdminConsent { + if s == nil || s.app == nil { + return nil + } + provider, ok := s.app.Lookup[pact.MCPAdminConsent]() + if !ok || provider == nil { + return nil + } + return provider +} + +func (s *service) writeMCPConsentNotFound(w http.ResponseWriter, r *http.Request) { + WriteError(w, http.StatusNotFound, "request_not_found", backendMessage(r.Context(), s.translator(), mcpConsentNotFoundKey, mcpConsentNotFoundFallback)) +} + +func (s *service) writeMCPConsentNoScopes(w http.ResponseWriter, r *http.Request) { + WriteError(w, http.StatusUnprocessableEntity, "no_grantable_scopes", backendMessage(r.Context(), s.translator(), mcpConsentNoScopesKey, mcpConsentNoScopesFallback)) +} + +// grantableConsentScopes answers, in catalog order, the requested scope +// names that are in the token-scope catalog and that the administrator can +// grant (scopeOverlaps, the personal-token picker rule). Everything else is +// hidden from the consent screen and dropped from a decision (D-11). +func (s *service) grantableConsentScopes(principal *bouncer.Principal, requested []string) []*compiledTokenScope { + if s.reg == nil || s.reg.tokenScopes == nil || principal == nil { + return nil + } + want := make(map[string]bool, len(requested)) + for _, name := range requested { + want[strings.TrimSpace(name)] = true + } + var out []*compiledTokenScope + for _, scope := range s.reg.tokenScopes.ordered { + if want[scope.Name] && scopeOverlaps(s.reg, principal, scope.Name) { + out = append(out, scope) + } + } + return out +} + +// mcpConsentRedirectHost is what the consent screen shows as the place the +// browser returns to: the redirect URI's host (with its port), or, for a +// URI without a host (a custom scheme), the URI without query and fragment. +func mcpConsentRedirectHost(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + if u.Host != "" { + return u.Host + } + u.RawQuery, u.Fragment, u.RawFragment = "", "", "" + return u.String() +} + +// mcpConsentShow serves GET /mcp/consent/{request}: the pending MCP +// authorization request of an administrator-only grant, as the published +// pact.MCPAdminConsent resolves it for the signed-in administrator, with +// only the requested scopes this administrator can grant. +func (s *service) mcpConsentShow(w http.ResponseWriter, r *http.Request) { + principal := accountPrincipal(w, r) + if principal == nil { + return + } + provider := s.mcpConsentProvider() + if provider == nil { + s.writeMCPConsentNotFound(w, r) + return + } + ctx := r.Context() + req, err := provider.MCPAdminConsentShow(ctx, principal.ID, r.PathValue("request")) + if errors.Is(err, pact.ErrMCPConsentNotFound) { + s.writeMCPConsentNotFound(w, r) + return + } + if err != nil { + moduleLog.ErrorContext(ctx, "cabana: mcp consent show failed", "admin_id", principal.ID, "error", err) + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + db, err := s.db() + if err != nil { + moduleLog.ErrorContext(ctx, "cabana: mcp consent show without a database", "error", err) + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + var admin BackendUser + if err := db.WithContext(ctx).Select("id", "login", "first_name", "last_name", "email").Where("id = ?", principal.ID).Take(&admin).Error; err != nil { + moduleLog.ErrorContext(ctx, "cabana: mcp consent show could not load the administrator", "admin_id", principal.ID, "error", err) + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + tr := s.translator() + scopes := []AdminAPITokenScope{} + for _, scope := range s.grantableConsentScopes(principal, req.Scopes) { + scopes = append(scopes, mapCompiledScope(ctx, tr, scope)) + } + expires := "" + if !req.ExpiresAt.IsZero() { + expires = req.ExpiresAt.UTC().Format(time.RFC3339) + } + WriteData(w, http.StatusOK, MCPConsentView{ + RequestID: req.RequestID, + Client: MCPConsentClientView{ + ID: req.ClientID, + Name: req.ClientName, + RedirectHost: mcpConsentRedirectHost(req.RedirectURI), + LogoURL: req.LogoURL, + }, + Admin: MCPConsentAdminView{ + Login: admin.Login, + Name: strings.TrimSpace(admin.FirstName + " " + admin.LastName), + Email: admin.Email, + }, + Scopes: scopes, + OfflineAccess: req.OfflineAccess, + ConsentRequired: req.ConsentRequired, + ExpiresAt: expires, + }, nil) +} + +// mcpConsentDecide serves POST /mcp/consent/{request}: the administrator's +// allow or deny. An allow keeps the submitted scopes that were requested +// and that the administrator can grant (others are dropped, not refused), +// normalises them as personal-token creation does (* collapses to ["*"]) +// and answers 422 no_grantable_scopes when nothing is left; offline access +// is granted only when it was requested and the body asks for it. The +// provider owns the transaction and the lock of the pending request. +func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) { + principal := accountPrincipal(w, r) + if principal == nil { + return + } + provider := s.mcpConsentProvider() + if provider == nil { + s.writeMCPConsentNotFound(w, r) + return + } + var body MCPConsentDecisionRequest + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxMCPConsentBody)) + dec.DisallowUnknownFields() + if err := dec.Decode(&body); err != nil || dec.Decode(&struct{}{}) != io.EOF { + WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request") + return + } + ctx := r.Context() + requestID := r.PathValue("request") + var decision pact.MCPAdminConsentDecision + switch body.Decision { + case "deny": + case "allow": + req, err := provider.MCPAdminConsentShow(ctx, principal.ID, requestID) + if errors.Is(err, pact.ErrMCPConsentNotFound) { + s.writeMCPConsentNotFound(w, r) + return + } + if err != nil { + moduleLog.ErrorContext(ctx, "cabana: mcp consent decide could not load the request", "admin_id", principal.ID, "error", err) + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + grantable := map[string]bool{} + for _, scope := range s.grantableConsentScopes(principal, req.Scopes) { + grantable[scope.Name] = true + } + kept := make([]string, 0, len(body.Scopes)) + for _, name := range body.Scopes { + if name = strings.TrimSpace(name); grantable[name] { + kept = append(kept, name) + } + } + if len(kept) == 0 { + s.writeMCPConsentNoScopes(w, r) + return + } + scopes, details := validateTokenScopes(s.reg, principal, kept) + if details != nil || len(scopes) == 0 { + s.writeMCPConsentNoScopes(w, r) + return + } + decision = pact.MCPAdminConsentDecision{ + Allow: true, + Scopes: scopes, + OfflineAccess: req.OfflineAccess && body.OfflineAccess, + } + default: + WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request") + return + } + redirect, err := provider.MCPAdminConsentDecide(ctx, principal.ID, requestID, decision) + switch { + case errors.Is(err, pact.ErrMCPConsentNotFound): + s.writeMCPConsentNotFound(w, r) + return + case errors.Is(err, pact.ErrMCPConsentNoScopes): + s.writeMCPConsentNoScopes(w, r) + return + case err != nil: + moduleLog.ErrorContext(ctx, "cabana: mcp consent decide failed", "admin_id", principal.ID, "allow", decision.Allow, "error", err) + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + moduleLog.InfoContext(ctx, "cabana: mcp consent decided", "admin_id", principal.ID, "allow", decision.Allow, "scopes", decision.Scopes) + WriteData(w, http.StatusOK, MCPConsentDecisionView{RedirectURI: redirect}, nil) +} diff --git a/modules/cabana/mcp_consent_smoke_test.go b/modules/cabana/mcp_consent_smoke_test.go new file mode 100644 index 00000000..b501d105 --- /dev/null +++ b/modules/cabana/mcp_consent_smoke_test.go @@ -0,0 +1,302 @@ +package cabana + +import ( + "context" + "database/sql" + "encoding/json" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/lagoon" + "git.golem15.com/golem15/summercms/modules/pact" + "git.golem15.com/golem15/summercms/modules/party" + _ "github.com/jackc/pgx/v5/stdlib" + tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres" + "gorm.io/gorm" +) + +var ( + consentPGOnce sync.Once + consentPGDB *gorm.DB + consentPGErr error +) + +// consentGorm starts one Postgres for the admin smoke tests of this file +// set and migrates the framework tables (backend_users and friends). +func consentGorm(t *testing.T) *gorm.DB { + t.Helper() + if testing.Short() { + t.Skip("requires testcontainers postgres") + } + consentPGOnce.Do(func() { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + ctr, err := tcpostgres.Run(ctx, "postgres:16-alpine", + tcpostgres.WithDatabase("cabana"), + tcpostgres.WithUsername("cabana"), + tcpostgres.WithPassword("cabana"), + tcpostgres.BasicWaitStrategies(), + ) + if err != nil { + consentPGErr = err + return + } + dsn, err := ctr.ConnectionString(ctx, "sslmode=disable") + if err != nil { + consentPGErr = err + return + } + db, err := sql.Open("pgx", dsn) + if err != nil { + consentPGErr = err + return + } + gdb, err := lagoon.Use(ctx, db) + if err != nil { + consentPGErr = err + return + } + if err := lagoon.Migrate(gdb, nil); err != nil { + consentPGErr = err + return + } + consentPGDB = gdb + }) + if consentPGErr != nil { + t.Fatalf("postgres: %v", consentPGErr) + } + return consentPGDB +} + +// consentScopesPlugin declares a read and a write permission and one plugin +// token scope behind the write permission. +type consentScopesPlugin struct{} + +func (consentScopesPlugin) ID() string { return "acme.items" } +func (consentScopesPlugin) Requires() []string { return nil } +func (consentScopesPlugin) Register(*backpack.App) error { return nil } +func (consentScopesPlugin) Boot(*backpack.App) error { return nil } +func (consentScopesPlugin) Permissions() []pact.Permission { + return []pact.Permission{ + {Code: "acme.items.read", Tab: "Items", Label: "Read items"}, + {Code: "acme.items.write", Tab: "Items", Label: "Write items"}, + } +} +func (consentScopesPlugin) TokenScopes() []pact.TokenScope { + return []pact.TokenScope{{Name: "acme:write", Label: "Write items", Description: "Create and change items.", Permissions: []string{"acme.items.write"}, Methods: []string{"GET", "POST"}}} +} + +// fakeAdminConsent is the published pact.MCPAdminConsent of the test: one +// pending request "req1" for any administrator. +type fakeAdminConsent struct { + mu sync.Mutex + requested []string + decided []pact.MCPAdminConsentDecision + admins []uint +} + +func (f *fakeAdminConsent) MCPAdminConsentShow(_ context.Context, adminID uint, requestID string) (pact.MCPAdminConsentRequest, error) { + if requestID != "req1" { + return pact.MCPAdminConsentRequest{}, pact.ErrMCPConsentNotFound + } + f.mu.Lock() + defer f.mu.Unlock() + return pact.MCPAdminConsentRequest{ + RequestID: "req1", ClientID: "oas_client", ClientName: "Agent", LogoURL: "https://agent.example.com/logo.png", + RedirectURI: "https://agent.example.com:8443/callback?x=1", Scopes: append([]string(nil), f.requested...), + OfflineAccess: true, ConsentRequired: true, ExpiresAt: time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC), + }, nil +} + +func (f *fakeAdminConsent) MCPAdminConsentDecide(_ context.Context, adminID uint, requestID string, decision pact.MCPAdminConsentDecision) (string, error) { + if requestID != "req1" { + return "", pact.ErrMCPConsentNotFound + } + f.mu.Lock() + defer f.mu.Unlock() + f.decided = append(f.decided, decision) + f.admins = append(f.admins, adminID) + if !decision.Allow { + return "https://agent.example.com:8443/callback?error=access_denied", nil + } + return "https://agent.example.com:8443/callback?code=c1", nil +} + +// TestMCPAdminConsentSmoke covers the admin consent endpoints over a fake +// provider: Show lists only requested catalog scopes the administrator can +// grant (a write scope they lack and an unknown name are hidden), Allow +// drops submitted scopes outside that set and calls Decide with the rest, +// offline access needs both the request and the body, Deny passes through, +// and the endpoint answers 401 anonymous, 403 interactive_only for a g15_ +// token, 404 without a provider or for an unknown request, 422 when nothing +// grantable is submitted and 400 for an unknown body field. +func TestMCPAdminConsentSmoke(t *testing.T) { + gdb := consentGorm(t) + var admin BackendUser + admin = BackendUser{FirstName: "Ada", LastName: "Reader", Login: "consent-reader", Email: "reader@acme.test", Password: "x", Permissions: `{"acme.items.read":1}`, IsActivated: true} + if err := gdb.Create(&admin).Error; err != nil { + t.Fatal(err) + } + reg, err := compileTokenCatalog([]party.Plugin{consentScopesPlugin{}}) + if err != nil { + t.Fatal(err) + } + app := backpack.New(nil) + if err := app.Publish(gdb); err != nil { + t.Fatal(err) + } + provider := &fakeAdminConsent{requested: []string{"acme:write", "admin:read", "ghost"}} + svc := &service{app: app, reg: reg} + principal := &bouncer.Principal{ID: admin.ID, Backend: true, PermissionGrants: map[string]bool{"acme.items.read": true}} + + request := func(method, id, body string, p *bouncer.Principal) *http.Request { + req := httptest.NewRequest(method, "/mcp/consent/"+id, strings.NewReader(body)) + req.Header.Set("X-Requested-With", "XMLHttpRequest") + req.SetPathValue("request", id) + if p != nil { + req = req.WithContext(bouncer.WithUser(req.Context(), p)) + } + return req + } + show := func(s *service, id string, p *bouncer.Principal) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + interactiveOnly(s.mcpConsentShow)(rec, request(http.MethodGet, id, "", p)) + return rec + } + decide := func(s *service, id, body string, p *bouncer.Principal) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + interactiveOnly(requireAjax(s.mcpConsentDecide))(rec, request(http.MethodPost, id, body, p)) + return rec + } + + // No provider published: 404 request_not_found for both. + if rec := show(svc, "req1", principal); rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), `"request_not_found"`) { + t.Fatalf("show without provider = %d %s", rec.Code, rec.Body.String()) + } + if rec := decide(svc, "req1", `{"decision":"deny"}`, principal); rec.Code != http.StatusNotFound { + t.Fatalf("decide without provider = %d %s", rec.Code, rec.Body.String()) + } + if err := app.Publish[pact.MCPAdminConsent](provider); err != nil { + t.Fatal(err) + } + + rec := show(svc, "req1", principal) + if rec.Code != http.StatusOK { + t.Fatalf("show = %d %s", rec.Code, rec.Body.String()) + } + var shown struct { + Data MCPConsentView `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil { + t.Fatal(err) + } + var names []string + for _, sc := range shown.Data.Scopes { + names = append(names, sc.Name) + } + if !slices.Equal(names, []string{"admin:read"}) { + t.Fatalf("shown scopes = %v, want [admin:read]", names) + } + d := shown.Data + if d.RequestID != "req1" || d.Client.ID != "oas_client" || d.Client.Name != "Agent" || d.Client.RedirectHost != "agent.example.com:8443" || + d.Admin.Login != "consent-reader" || d.Admin.Name != "Ada Reader" || d.Admin.Email != "reader@acme.test" || + !d.OfflineAccess || !d.ConsentRequired || d.ExpiresAt != "2026-11-21T10:00:00Z" || !shown.Data.Scopes[0].ReadOnly { + t.Fatalf("view = %+v", d) + } + if rec := show(svc, "nope", principal); rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), `"request_not_found"`) { + t.Fatalf("unknown request = %d %s", rec.Code, rec.Body.String()) + } + + // Allow: * was not requested and acme:write is not grantable, so both + // are dropped; offline access is requested and asked for. + rec = decide(svc, "req1", `{"decision":"allow","scopes":["*","admin:read","acme:write"],"offline_access":true}`, principal) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"redirect_uri":"https://agent.example.com:8443/callback?code=c1"`) { + t.Fatalf("allow = %d %s", rec.Code, rec.Body.String()) + } + if last := provider.decided[len(provider.decided)-1]; !last.Allow || !slices.Equal(last.Scopes, []string{"admin:read"}) || !last.OfflineAccess || provider.admins[len(provider.admins)-1] != admin.ID { + t.Fatalf("decide called with %+v", last) + } + // Only hidden scopes submitted: 422, Decide not called. + calls := len(provider.decided) + if rec := decide(svc, "req1", `{"decision":"allow","scopes":["acme:write","ghost"]}`, principal); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"no_grantable_scopes"`) || len(provider.decided) != calls { + t.Fatalf("nothing grantable = %d %s", rec.Code, rec.Body.String()) + } + // A requested * is offered, as on personal-token creation, and + // collapses the grant to ["*"]. + provider.mu.Lock() + provider.requested = []string{"*", "admin:read"} + provider.mu.Unlock() + if rec := decide(svc, "req1", `{"decision":"allow","scopes":["admin:read","*"],"offline_access":false}`, principal); rec.Code != http.StatusOK { + t.Fatalf("allow * = %d %s", rec.Code, rec.Body.String()) + } + if last := provider.decided[len(provider.decided)-1]; !slices.Equal(last.Scopes, []string{"*"}) || last.OfflineAccess { + t.Fatalf("decide * called with %+v", last) + } + // Deny passes through without scopes. + if rec := decide(svc, "req1", `{"decision":"deny"}`, principal); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "access_denied") { + t.Fatalf("deny = %d %s", rec.Code, rec.Body.String()) + } + if last := provider.decided[len(provider.decided)-1]; last.Allow || len(last.Scopes) != 0 { + t.Fatalf("deny called with %+v", last) + } + // Malformed bodies: an unknown field and an unknown decision. + for _, body := range []string{`{"decision":"allow","scopes":["admin:read"],"extra":1}`, `{"decision":"maybe"}`, `not json`} { + if rec := decide(svc, "req1", body, principal); rec.Code != http.StatusBadRequest { + t.Fatalf("body %s = %d %s", body, rec.Code, rec.Body.String()) + } + } + if rec := decide(svc, "nope", `{"decision":"allow","scopes":["admin:read"]}`, principal); rec.Code != http.StatusNotFound { + t.Fatalf("decide unknown request = %d %s", rec.Code, rec.Body.String()) + } + + // Anonymous: 401. A g15_ token: 403 interactive_only, for GET and POST. + if rec := show(svc, "req1", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous = %d %s", rec.Code, rec.Body.String()) + } + tokenReq := request(http.MethodGet, "req1", "", principal) + tokenReq = tokenReq.WithContext(bouncer.WithCredential(tokenReq.Context(), &BackendAPIToken{ID: 3})) + rec = httptest.NewRecorder() + interactiveOnly(svc.mcpConsentShow)(rec, tokenReq) + if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "interactive_only") { + t.Fatalf("token credential = %d %s", rec.Code, rec.Body.String()) + } + bearer := request(http.MethodPost, "req1", `{"decision":"deny"}`, principal) + bearer.Header.Set("Authorization", "Bearer "+APITokenPrefix+strings.Repeat("0", 40)) + rec = httptest.NewRecorder() + interactiveOnly(requireAjax(svc.mcpConsentDecide))(rec, bearer) + if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "interactive_only") { + t.Fatalf("raw g15_ bearer = %d %s", rec.Code, rec.Body.String()) + } + // The POST needs X-Requested-With. + plain := request(http.MethodPost, "req1", `{"decision":"deny"}`, principal) + plain.Header.Del("X-Requested-With") + rec = httptest.NewRecorder() + interactiveOnly(requireAjax(svc.mcpConsentDecide))(rec, plain) + if rec.Code != http.StatusForbidden { + t.Fatalf("POST without X-Requested-With = %d", rec.Code) + } +} + +// TestTokenScopeNamesAndLabels: the exported catalog answers names in +// catalog order before activation, and labels fall back to the name. +func TestTokenScopeNamesAndLabels(t *testing.T) { + app := backpack.New(nil) + if err := app.Publish(party.Activated([]party.Plugin{consentScopesPlugin{}})); err != nil { + t.Fatal(err) + } + names, err := TokenScopeNames(app) + if err != nil || !slices.Equal(names, []string{"*", "admin:read", "acme:write"}) { + t.Fatalf("names = %v, %v", names, err) + } + labels := TokenScopeLabels(context.Background(), app, []string{"acme:write", "ghost"}) + if !slices.Equal(labels, []string{"Write items", "ghost"}) { + t.Fatalf("labels = %v", labels) + } +} diff --git a/modules/cabana/openapi_conformance_test.go b/modules/cabana/openapi_conformance_test.go index e98c0069..6660c380 100644 --- a/modules/cabana/openapi_conformance_test.go +++ b/modules/cabana/openapi_conformance_test.go @@ -836,6 +836,12 @@ func conformCases() []conformCase { {"POST /account/contributions/{name}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/account/contributions/conform_link/actions/open", nil, true) }, into[cabana.Envelope[cabana.AccountActionResultView]](), nil}, + {"GET /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodGet, "/mcp/consent/conform-request", nil, true) + }, into[cabana.Envelope[cabana.MCPConsentView]](), nil}, + {"POST /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentDecisionView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodPost, "/mcp/consent/conform-request", map[string]any{"decision": "allow", "scopes": []string{"admin:read"}, "offline_access": true}, true) + }, into[cabana.Envelope[cabana.MCPConsentDecisionView]](), nil}, {"POST /auth/logout", 200, "cabana.Envelope-cabana_AdminLogoutData", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/auth/logout", nil, true) }, into[cabana.Envelope[cabana.AdminLogoutData]](), nil}, @@ -1134,6 +1140,10 @@ func newConformEnv(t *testing.T) *conformEnv { if err := app.Publish[postcard.Mailer](mailer); err != nil { t.Fatal(err) } + // The MCP consent routes serve a fake administrator-only consent provider. + if err := app.Publish[pact.MCPAdminConsent](conformConsent{}); err != nil { + t.Fatal(err) + } // The acme.companions fixture serves the Phase 17 routes (dependent // options) next to the gadgets. plugins := []party.Plugin{conformPlugin{stamp: stamp}, companionsPlugin{app: app}} @@ -1238,6 +1248,30 @@ func (conformSettings) TableName() string { return "cabana_conform_settin func (conformSettings) Fillable() []string { return []string{"enabled", "api_key"} } func (conformSettings) Rules() map[string]string { return map[string]string{} } +// conformConsent is the fake pact.MCPAdminConsent of the conformance +// suite: one pending request asking for admin:read and offline access. +type conformConsent struct{} + +func (conformConsent) MCPAdminConsentShow(_ context.Context, _ uint, requestID string) (pact.MCPAdminConsentRequest, error) { + if requestID != "conform-request" { + return pact.MCPAdminConsentRequest{}, pact.ErrMCPConsentNotFound + } + return pact.MCPAdminConsentRequest{ + RequestID: requestID, ClientID: "oas_conform", ClientName: "Conform agent", RedirectURI: "https://agent.example.test/callback", + Scopes: []string{"admin:read"}, OfflineAccess: true, ConsentRequired: true, ExpiresAt: time.Now().Add(10 * time.Minute), + }, nil +} + +func (conformConsent) MCPAdminConsentDecide(_ context.Context, _ uint, requestID string, decision pact.MCPAdminConsentDecision) (string, error) { + if requestID != "conform-request" { + return "", pact.ErrMCPConsentNotFound + } + if len(decision.Scopes) == 0 && decision.Allow { + return "", pact.ErrMCPConsentNoScopes + } + return "https://agent.example.test/callback?code=conform", nil +} + type conformPlugin struct{ stamp string } func (conformPlugin) ID() string { return "acme.conform" } diff --git a/modules/cabana/phase10_coverage_test.go b/modules/cabana/phase10_coverage_test.go index ada9b83b..c8afc53f 100644 --- a/modules/cabana/phase10_coverage_test.go +++ b/modules/cabana/phase10_coverage_test.go @@ -103,6 +103,7 @@ func TestPhase10Coverage(t *testing.T) { "POST /mail/preview", "POST /mail/test-send", "POST /markdown/preview", + "POST /mcp/consent/{request}", "POST /{vendor}/{plugin}/{controller}", "POST /{vendor}/{plugin}/{controller}/bulk-delete", "POST /{vendor}/{plugin}/{controller}/bulk/{action}", diff --git a/modules/cabana/phase10_csrf_test.go b/modules/cabana/phase10_csrf_test.go index 329104f9..f566e343 100644 --- a/modules/cabana/phase10_csrf_test.go +++ b/modules/cabana/phase10_csrf_test.go @@ -73,9 +73,9 @@ func TestPhase10CSRF(t *testing.T) { // caption, file remove, relation child create, update and delete, pivot // update, child file upload, reorder, caption and remove, plugin field // type upload, tree reorder save, account contribution action, - // mail image upload, mail preview, mail test-send - if unsafe != 38 { - t.Fatalf("walked %d state-changing routes, want 38: %v", unsafe, router.order) + // mail image upload, mail preview, mail test-send, MCP consent decision + if unsafe != 39 { + t.Fatalf("walked %d state-changing routes, want 39: %v", unsafe, router.order) } loginHandler := router.handlers[login] diff --git a/modules/cabana/security_coverage_test.go b/modules/cabana/security_coverage_test.go index e89ca320..48662eef 100644 --- a/modules/cabana/security_coverage_test.go +++ b/modules/cabana/security_coverage_test.go @@ -50,6 +50,8 @@ var phase09Routes = []adminRoute{ {key: "DELETE /account/tokens/{id}"}, {key: "GET /account/contributions"}, {key: "POST /account/contributions/{name}/actions/{action}"}, + {key: "GET /mcp/consent/{request}"}, + {key: "POST /mcp/consent/{request}"}, {key: "GET /navigation"}, {key: "GET /field-types"}, {key: "GET /settings"}, diff --git a/modules/cabana/token_routes_test.go b/modules/cabana/token_routes_test.go index 1310f5cc..e6a68c93 100644 --- a/modules/cabana/token_routes_test.go +++ b/modules/cabana/token_routes_test.go @@ -45,6 +45,8 @@ var tokenRouteClasses = map[string]tokenRouteClass{ "DELETE /account/tokens/{id}": classInteractive, "GET /account/contributions": classInteractive, "POST /account/contributions/{name}/actions/{action}": classInteractive, + "GET /mcp/consent/{request}": classInteractive, + "POST /mcp/consent/{request}": classInteractive, "GET /navigation": classAllowsNav, "GET /field-types": classExplicitGate, diff --git a/modules/cabana/token_scopes_export.go b/modules/cabana/token_scopes_export.go new file mode 100644 index 00000000..09aa00a9 --- /dev/null +++ b/modules/cabana/token_scopes_export.go @@ -0,0 +1,63 @@ +package cabana + +import ( + "context" + "strings" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/phrasebook" +) + +// TokenScopeNames answers the names of the personal API token scope catalog +// in catalog order: *, admin:read, then every plugin's TokenScopes in +// activation order. It compiles the catalog from the activated plugins +// (party.Activated), so it works at plugin Boot, before cabana.Activate. A +// plugin that advertises the same scopes elsewhere (an OAuth server whose +// grants act as administrators, for example) reads them here. The error is +// the catalog's compile error (an invalid or duplicate plugin scope). +func TokenScopeNames(app *backpack.App) ([]string, error) { + reg, err := tokenCatalogForApp(app) + if err != nil { + return nil, err + } + if reg == nil || reg.tokenScopes == nil { + return []string{}, nil + } + out := make([]string, 0, len(reg.tokenScopes.ordered)) + for _, scope := range reg.tokenScopes.ordered { + out = append(out, scope.Name) + } + return out, nil +} + +// TokenScopeLabels answers the translated label of each name, in input +// order: the label the token screens show for a catalog scope, and the name +// itself for a name the catalog does not know (or when the catalog fails to +// compile). The locale is the one ctx carries. +func TokenScopeLabels(ctx context.Context, app *backpack.App, names []string) []string { + if ctx == nil { + ctx = context.Background() + } + var tr *phrasebook.Translator + if app != nil { + tr, _ = app.Lookup[*phrasebook.Translator]() + } + reg, err := tokenCatalogForApp(app) + out := make([]string, 0, len(names)) + for _, name := range names { + label := name + if err == nil && reg != nil && reg.tokenScopes != nil { + if scope, ok := reg.tokenScopes.byName[name]; ok { + label = scope.Label + if strings.Contains(label, "::") { + label = resolveScopePhrase(ctx, tr, label, label) + } + if strings.TrimSpace(label) == "" { + label = name + } + } + } + out = append(out, label) + } + return out +} diff --git a/modules/pact/README.md b/modules/pact/README.md index 7bb76aac..ec2ab7cc 100644 --- a/modules/pact/README.md +++ b/modules/pact/README.md @@ -162,6 +162,10 @@ func (p *BlogPlugin) Schedule() []pact.ScheduledCommand { | `pact.MCPTokenVerifier` | Published by the OAuth server plugin: verifies an access token at the MCP endpoint into a `pact.MCPGrant` (user, client, token, scopes, expiry and, for a `backend` grant, `BackendUserID`, the backend account the consent showed) and names its resource. `pact.MCPGrant.Subject` says what the grant acts as: empty is the frontend user in `UserID` (the meaning every grant had before), `pact.MCPGrantSubjectBackend` is the administrator in `pact.MCPGrant.BackendUserID` alone, with `UserID` 0 and no frontend user. A refused token is `pact.ErrMCPTokenInvalid`. The interface is only `MCPVerifyToken` and `MCPResource`. | | `pact.MCPAdvertisedScopes` | Optional second interface on that verifier. `pact.MCPAdvertisedScopes.MCPScopesSupported` is the MCP scope list pier copies into protected-resource metadata when the slice is non-empty. | | `pact.MCPPersonalTokenResolver` | Published by the one plugin whose personal tokens may open an MCP session (one resolver per application): resolves a raw token into a `pact.MCPSubject` whose `TokenID` identifies the token row (it keys the session binding; a subject without one is refused); false when the prefix is not its own, which the endpoint answers as unauthorized. | +| `pact.MCPAdminConsent` | Published (`app.Publish`) by the plugin that owns the MCP authorization server, one per application: `pact.MCPAdminConsent.MCPAdminConsentShow` answers a pending request for the signed-in administrator as a `pact.MCPAdminConsentRequest`, `pact.MCPAdminConsent.MCPAdminConsentDecide` applies a `pact.MCPAdminConsentDecision` and answers the client redirect URI. The framework serves the consent endpoints of the admin API over it and applies the scope policy before calling Decide; the provider only resolves and issues. | +| `pact.MCPAdminConsentRequest` | A pending request as the administrator's consent screen shows it: request and client ids, client name, logo URL, redirect URI, requested data scopes (`offline_access` excluded), whether `offline_access` was requested, whether consent must be asked and the expiry. | +| `pact.MCPAdminConsentDecision` | The administrator's answer: `Allow`, the scopes to grant (already filtered by the framework) and `OfflineAccess`. | +| `pact.ErrMCPConsentNotFound` / `pact.ErrMCPConsentNoScopes` | What a `pact.MCPAdminConsent` answers for a missing, expired, used or foreign request, and for an allow that leaves nothing to grant. | | `pact.MCPLinkedBackendResolver` | Published by the plugin that owns the frontend-to-backend account link: the `pact.LinkedBackendUser` (id, login, display name) of a frontend user, false when unlinked. | | `pact.MCPSubjectChanged` | Event fired on the festival bus when a subject's permissions, link, grants or existence change (`Kind` is `pact.MCPSubjectPermissions`, `pact.MCPSubjectLink`, `pact.MCPSubjectRevoked` or `pact.MCPSubjectDeleted`), so the MCP endpoint re-lists tools or ends sessions. `TokenID` and `ClientID` narrow a revoked event: a token id ends only the sessions that personal token opened (subject with that `TokenID` and no `ClientID`), a client id only that OAuth client's sessions, neither every session of the subject; other kinds ignore them. | | `pact.FrontendPermission` | One frontend permission code a plugin declares: `Code`, `Label`, `Tab` and `Comment`, offered in the user plugin's permission editors next to the seeded codes. | diff --git a/modules/pact/mcp.go b/modules/pact/mcp.go index c4227cda..4ecaf014 100644 --- a/modules/pact/mcp.go +++ b/modules/pact/mcp.go @@ -334,6 +334,65 @@ type MCPPersonalTokenResolver interface { MCPResolvePersonalToken(ctx context.Context, raw string) (MCPSubject, bool, error) } +// MCPAdminConsent serves the consent screen of administrator-only MCP +// grants (MCPGrantSubjectBackend) to the framework's admin API. One +// provider per application, published through app.Publish by the plugin +// that owns the MCP authorization server. The framework serves the +// cookie-authenticated consent endpoints for the signed-in administrator +// and owns the scope policy: it shows only requested scopes the +// administrator can grant and filters a decision the same way before it +// calls MCPAdminConsentDecide, so the provider only resolves and issues. +// +// MCPAdminConsentShow answers the pending request requestID for the +// administrator adminID; a missing, expired, used or foreign request is +// ErrMCPConsentNotFound. MCPAdminConsentDecide allows or denies it and +// answers the client redirect URI to send the browser to (carrying the +// code, or the access_denied error); ErrMCPConsentNotFound as for Show, +// ErrMCPConsentNoScopes when an allow decision leaves nothing to grant. +type MCPAdminConsent interface { + MCPAdminConsentShow(ctx context.Context, adminID uint, requestID string) (MCPAdminConsentRequest, error) + MCPAdminConsentDecide(ctx context.Context, adminID uint, requestID string, decision MCPAdminConsentDecision) (string, error) +} + +// MCPAdminConsentRequest is one pending MCP authorization request as the +// administrator's consent screen shows it: the request id, the client (id, +// name, logo and the redirect URI the browser returns to), the requested +// data scopes (offline_access excluded), whether offline_access was +// requested, whether consent must be asked (false when this client was +// allowed before) and the request's expiry. +type MCPAdminConsentRequest struct { + RequestID string + ClientID string + ClientName string + LogoURL string + RedirectURI string + Scopes []string + OfflineAccess bool + ConsentRequired bool + ExpiresAt time.Time +} + +// MCPAdminConsentDecision is the administrator's answer to a consent +// request: Allow, the scopes to grant (already filtered by the framework to +// requested scopes the administrator can grant, with * collapsed as for +// personal tokens) and OfflineAccess (a refresh token; only when it was +// requested). A deny carries no scopes. +type MCPAdminConsentDecision struct { + Allow bool + Scopes []string + OfflineAccess bool +} + +// ErrMCPConsentNotFound is what an MCPAdminConsent answers for a consent +// request that does not exist, expired, was used or belongs to someone +// else; the admin API answers 404 request_not_found. +var ErrMCPConsentNotFound = errors.New("pact: mcp consent request not found") + +// ErrMCPConsentNoScopes is what MCPAdminConsentDecide answers when an allow +// decision leaves no scope to grant; the admin API answers 422 +// no_grantable_scopes. +var ErrMCPConsentNoScopes = errors.New("pact: mcp consent has no grantable scopes") + // MCPLinkedBackendResolver answers the verified backend account linked to a // frontend user, published by the plugin that owns the link. The boolean is // false when the user has no link. diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml index 1fb36186..0a7f8792 100644 --- a/modules/phrasebook/backend/lang/en/lang.yaml +++ b/modules/phrasebook/backend/lang/en/lang.yaml @@ -348,6 +348,9 @@ api_tokens: unknown_scope: ':name (unknown)' unknown_scope_hint: This scope is no longer registered and grants nothing. hint: Token ending in :last4 +mcp_connect: + request_not_found: This connection request has expired or does not exist. + no_grantable_scopes: Choose at least one scope you can use. myaccount: menu_label: My account menu_description: Edit your name, email, subtitle and password, and manage your API tokens. diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml index 1f432a91..716d6e1d 100644 --- a/modules/phrasebook/backend/lang/pl/lang.yaml +++ b/modules/phrasebook/backend/lang/pl/lang.yaml @@ -370,6 +370,9 @@ api_tokens: unknown_scope: ':name (nieznany)' unknown_scope_hint: Ten zakres nie jest już zarejestrowany i nic nie przyznaje. hint: Token kończący się na :last4 +mcp_connect: + request_not_found: To żądanie połączenia wygasło albo nie istnieje. + no_grantable_scopes: Wybierz co najmniej jeden zakres, którego możesz użyć. myaccount: menu_label: Moje konto menu_description: Zmień imię, nazwisko, e-mail, podtytuł i hasło oraz zarządzaj tokenami API.