fix(32.2): WR-06 check the consent provider's redirect against the request's redirect URI

cabana loads the pending request on both decisions and refuses (500) a Decide answer whose scheme, user info, host, path or opaque part differ from the registered redirect URI. The admin SPA also refuses blob:, file:, about: and filesystem: and a destination that does not return to the host the consent card showed. Regenerated the admin OpenAPI document and rebuilt modules/boardwalk/dist.
This commit is contained in:
Jakub Zych
2026-11-21 09:32:54 +01:00
parent 60bc6ee68f
commit 0ade662a04
17 changed files with 212 additions and 49 deletions

View File

@@ -5316,7 +5316,7 @@
] ]
}, },
"post": { "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).", "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. Both decisions load the request first; a provider redirect that does not go back to the request's redirect URI (same scheme, host and path) is refused (500). 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": [ "parameters": [
{ {
"description": "Pending request id", "description": "Pending request id",

View File

@@ -1705,7 +1705,7 @@ export interface paths {
put?: never; put?: never;
/** /**
* Allow or deny an MCP consent request * 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). * @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. Both decisions load the request first; a provider redirect that does not go back to the request's redirect URI (same scheme, host and path) is refused (500). 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: { post: {
parameters: { parameters: {

View File

@@ -188,7 +188,41 @@ function scopeDisabled(name: string): boolean {
return starChecked.value && name !== '*' return starChecked.value && name !== '*'
} }
/** The server-issued redirect, refused when its scheme could run script (T-32.2-09). */ /** Schemes a consent redirect never uses: script, inline content and local files. */
const FORBIDDEN_PROTOCOLS = new Set(['javascript:', 'data:', 'vbscript:', 'blob:', 'file:', 'about:', 'filesystem:'])
/**
* Whether url returns to the place the consent screen showed: the
* redirect host (with its port) for a URI with a host, or the URI without
* query and fragment for one without (a custom scheme). Both sides go
* through the URL parser, so case and default ports compare as the browser
* sees them.
*/
function returnsTo(url: URL, host: string): boolean {
if (host === '') {
return false
}
try {
if (url.host !== '') {
return new URL(`${url.protocol}//${host}`).host === url.host
}
const want = new URL(host)
const got = new URL(url.href)
for (const u of [want, got]) {
u.search = ''
u.hash = ''
}
return want.href === got.href
} catch {
return false
}
}
/**
* The server-issued redirect, refused when its scheme could run script or
* open local content, or when it leaves for another place than the one the
* screen named (T-32.2-09).
*/
function safeDestination(uri: string): string | null { function safeDestination(uri: string): string | null {
let url: URL let url: URL
try { try {
@@ -196,7 +230,7 @@ function safeDestination(uri: string): string | null {
} catch { } catch {
return null return null
} }
if (url.protocol === 'javascript:' || url.protocol === 'data:' || url.protocol === 'vbscript:') { if (FORBIDDEN_PROTOCOLS.has(url.protocol) || !returnsTo(url, redirectHost.value)) {
return null return null
} }
return uri return uri

View File

@@ -258,13 +258,22 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
expect(wrapper.find('[data-action="allow"]').exists()).toBe(false) expect(wrapper.find('[data-action="allow"]').exists()).toBe(false)
expect(document.activeElement).toBe(card.find('h1').element) expect(document.activeElement).toBe(card.find('h1').element)
const custom = await open('/connect?request=req1', routes(consentView(), ok({ redirect_uri: 'myagent:/callback?code=1' }))) const customView = consentView({ client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'myagent:/callback', logo_url: '' } })
const custom = await open('/connect?request=req1', routes(customView, ok({ redirect_uri: 'myagent:/callback?code=1' })))
await custom.wrapper.find('[data-connect-state="ready"]').trigger('submit') await custom.wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises() await flushPromises()
expect(assign).toHaveBeenLastCalledWith('myagent:/callback?code=1') expect(assign).toHaveBeenLastCalledWith('myagent:/callback?code=1')
const returning = custom.wrapper.find('[data-connect-state="returning"]') const returning = custom.wrapper.find('[data-connect-state="returning"]')
expect(returning.find('[data-connect-continue]').exists()).toBe(false) expect(returning.find('[data-connect-continue]').exists()).toBe(false)
expect(returning.find('h1').text()).toBe('Returning to agent.example.test') expect(returning.find('h1').text()).toBe('Returning to myagent:/callback')
})
it('leaves for a redirect whose host matches the shown one as the browser compares hosts', async () => {
const view = consentView({ client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'Agent.Example.Test:443', logo_url: '' } })
const { wrapper } = await open('/connect?request=req1', routes(view))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).toHaveBeenCalledWith(REDIRECT)
}) })
it('disables both buttons and the scopes while a decision is in flight', async () => { it('disables both buttons and the scopes while a decision is in flight', async () => {
@@ -290,7 +299,21 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
}) })
describe('submit failures', () => { describe('submit failures', () => {
it.each(['javascript:alert(1)', 'data:text/html,<script>x</script>', 'vbscript:msgbox(1)', 'JavaScript:alert(1)', 'not a uri'])( it.each([
'javascript:alert(1)',
'data:text/html,<script>x</script>',
'vbscript:msgbox(1)',
'JavaScript:alert(1)',
'not a uri',
'blob:https://agent.example.test/0b7c',
'file:///etc/passwd',
'about:blank',
'filesystem:https://agent.example.test/temporary/x',
'https://evil.example.test/callback?code=abc123',
'https://agent.example.test.evil.example/callback?code=abc123',
'https://agent.example.test:8443/callback?code=abc123',
'myagent:/callback?code=1',
])(
'treats the redirect %j as a submit failure', 'treats the redirect %j as a submit failure',
async (uri) => { async (uri) => {
const { wrapper, push, replace } = await open('/connect?request=req1', routes(consentView(), ok({ redirect_uri: uri }))) const { wrapper, push, replace } = await open('/connect?request=req1', routes(consentView(), ok({ redirect_uri: uri })))

View File

@@ -49,7 +49,7 @@ When the server offers more than one admin language (`meta.locales` of `GET .../
The route is standalone, without the navigation shell, and needs a session: an anonymous visitor goes to the login screen with the connect path as its redirect, signs in (with any second step the login asks for) and comes back to the same request. The login screen then says why the administrator is signing in. The route is standalone, without the navigation shell, and needs a session: an anonymous visitor goes to the login screen with the connect path as its redirect, signs in (with any second step the login asks for) and comes back to the same request. The login screen then says why the administrator is signing in.
The card names the client, the signed-in administrator (with a "Use another account" button that signs out of this browser and goes through login again) and the host the browser returns to, which is always shown in full. Below are the scopes the server offered, in catalog order: every one starts ticked except `*`, which starts ticked only when it is the only scope, and ticking `*` clears and disables the others, as on API token creation. A "Stay connected" box, ticked by default, appears only when the client asked for offline access. Nothing is sent until the administrator clicks Allow or Deny, even for a client allowed before, and neither button has initial focus or a shortcut. The answer's `redirect_uri` is opened with `window.location.assign`, never through the router or the login redirect check, and a `javascript:`, `data:` or `vbscript:` URI is refused as a failed answer. An unknown, expired or used request shows an expired card with a link to the admin; when the administrator holds none of the requested scopes only Deny is offered. The card names the client, the signed-in administrator (with a "Use another account" button that signs out of this browser and goes through login again) and the host the browser returns to, which is always shown in full. Below are the scopes the server offered, in catalog order: every one starts ticked except `*`, which starts ticked only when it is the only scope, and ticking `*` clears and disables the others, as on API token creation. A "Stay connected" box, ticked by default, appears only when the client asked for offline access. Nothing is sent until the administrator clicks Allow or Deny, even for a client allowed before, and neither button has initial focus or a shortcut. The answer's `redirect_uri` is opened with `window.location.assign`, never through the router or the login redirect check, and a `javascript:`, `data:`, `vbscript:`, `blob:`, `file:`, `about:` or `filesystem:` URI, or one that does not return to the host the card showed, is refused as a failed answer (the server already refuses a redirect that does not go back to the request's redirect URI). An unknown, expired or used request shows an expired card with a link to the admin; when the administrator holds none of the requested scopes only Deny is offered.
## Plugins screen ## Plugins screen

View File

@@ -118,7 +118,7 @@ The authorization endpoint sends the browser to `<issuer>/connect?request=<id>`,
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)). 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`). 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). cabana also loads the request before a deny, and refuses with 500 a redirect from Decide that does not go back to the request's `pact.MCPAdminConsentRequest.RedirectURI` (same scheme, host and path; only the query and fragment may differ). 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 ## Clients created outside registration

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,2 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./editor-uDgt9VKj.js","./index-Vcq4gwWv.js"])))=>i.map(i=>d[i]); const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./editor-uDgt9VKj.js","./index-Vcq4gwWv.js"])))=>i.map(i=>d[i]);
import{_ as r}from"./index-CHYC7L7j.js";function t(){return r(()=>import("./editor-uDgt9VKj.js"),__vite__mapDeps([0,1]),import.meta.url)}export{t as importCodeEditor}; import{_ as r}from"./index-BbjrikzN.js";function t(){return r(()=>import("./editor-uDgt9VKj.js"),__vite__mapDeps([0,1]),import.meta.url)}export{t as importCodeEditor};

View File

@@ -8,7 +8,7 @@
<meta name="summer-admin-build" content="__SUMMER_ADMIN_BUILD__" /> <meta name="summer-admin-build" content="__SUMMER_ADMIN_BUILD__" />
<link rel="icon" href="./favicon.ico" sizes="48x48" /> <link rel="icon" href="./favicon.ico" sizes="48x48" />
<title>SummerCMS</title> <title>SummerCMS</title>
<script type="module" crossorigin src="./assets/index-CHYC7L7j.js"></script> <script type="module" crossorigin src="./assets/index-BbjrikzN.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DEB8-xeq.css"> <link rel="stylesheet" crossorigin href="./assets/index-DEB8-xeq.css">
</head> </head>
<body> <body>

View File

@@ -94,7 +94,7 @@ Guarded routes run surf's `locale.from-principal` after the backend guard: an in
| GET `/account/tokens/scopes` | Scopes the caller may assign (`cabana.AdminAPITokenScope`), including `*`, `admin:read` and overlapping plugin scopes. 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 `/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. | | 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 `/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`). Both decisions load the request first, and a redirect the provider answers that does not go back to the request's redirect URI (same scheme, host and path) is refused with 500. cabana opens no transaction: the provider owns it. Interactive session only, AJAX header required. |
| POST `/account/contribution-items/{name}/{item}/actions/{action}` | Run one item action of a contributed section on one row: 404 for an unknown section or item action, 403 without its permissions, 404 when the section's `Items` does not list `{item}` for the signed-in administrator (so another administrator's row is never reachable) or when `Run` answers `pact.ErrAccountItemNotFound`; `Run` gets the administrator and item ids inside a transaction and answers `cabana.AccountActionResultView`. The path is not under `/account/contributions/` because a nine-segment POST there would overlap the controller routes. Interactive session only, AJAX header required. | | POST `/account/contribution-items/{name}/{item}/actions/{action}` | Run one item action of a contributed section on one row: 404 for an unknown section or item action, 403 without its permissions, 404 when the section's `Items` does not list `{item}` for the signed-in administrator (so another administrator's row is never reachable) or when `Run` answers `pact.ErrAccountItemNotFound`; `Run` gets the administrator and item ids inside a transaction and answers `cabana.AccountActionResultView`. The path is not under `/account/contributions/` because a nine-segment POST there would overlap the controller routes. 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. | | 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 `/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. |

View File

@@ -483,7 +483,7 @@ func AdminMCPConsentShow() {}
// AdminMCPConsentDecide documents POST /mcp/consent/{request}. // AdminMCPConsentDecide documents POST /mcp/consent/{request}.
// //
// @Summary Allow or deny an 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). // @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. Both decisions load the request first; a provider redirect that does not go back to the request's redirect URI (same scheme, host and path) is refused (500). 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 // @Tags admin
// @Accept json // @Accept json
// @Produce json // @Produce json

View File

@@ -35,6 +35,8 @@ type recordingAdminConsent struct {
required bool required bool
showErr error showErr error
decideErr error decideErr error
// redirect replaces Decide's redirect URI while set.
redirect string
shows []consentCall shows []consentCall
calls []consentCall calls []consentCall
} }
@@ -71,6 +73,9 @@ func (f *recordingAdminConsent) MCPAdminConsentDecide(_ context.Context, adminID
if requestID != "req1" { if requestID != "req1" {
return "", pact.ErrMCPConsentNotFound return "", pact.ErrMCPConsentNotFound
} }
if f.redirect != "" {
return f.redirect, nil
}
if !decision.Allow { if !decision.Allow {
return "myagent:/callback?error=access_denied", nil return "myagent:/callback?error=access_denied", nil
} }
@@ -405,8 +410,9 @@ func TestMCPAdminConsent(t *testing.T) {
if rec := decide("nope", `{"decision":"deny"}`, readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { if rec := decide("nope", `{"decision":"deny"}`, readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" {
t.Fatalf("deny of an unknown request = %d %s", rec.Code, rec.Body.String()) t.Fatalf("deny of an unknown request = %d %s", rec.Code, rec.Body.String())
} }
if got := provider.lastCall(t); got.request != "nope" || got.decision.Allow { // Both decisions load the request first: neither reaches Decide.
t.Fatalf("deny of an unknown request reached Decide with %+v", got) if got := provider.lastCall(t); got.request == "nope" {
t.Fatalf("a decision of an unknown request reached Decide with %+v", got)
} }
provider.set(func(f *recordingAdminConsent) { f.decideErr = pact.ErrMCPConsentNotFound }) provider.set(func(f *recordingAdminConsent) { f.decideErr = pact.ErrMCPConsentNotFound })
rec := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP) rec := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP)
@@ -421,6 +427,34 @@ func TestMCPAdminConsent(t *testing.T) {
} }
}) })
t.Run("a provider redirect away from the request's redirect URI is refused", func(t *testing.T) {
for _, foreign := range []string{
"https://evil.example/callback?code=c1",
"evilagent:/callback?code=c1",
"myagent:/elsewhere?code=c1",
"myagent://host/callback?code=c1",
"javascript:alert(1)",
"/callback?code=c1",
} {
provider.set(func(f *recordingAdminConsent) { f.redirect = foreign })
allow := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP)
deny := decide("req1", `{"decision":"deny"}`, readerP)
provider.set(func(f *recordingAdminConsent) { f.redirect = "" })
for name, rec := range map[string]*httptest.ResponseRecorder{"allow": allow, "deny": deny} {
if rec.Code != http.StatusInternalServerError || strings.Contains(rec.Body.String(), foreign) {
t.Fatalf("%s answering %q = %d %s, want 500 without the URI", name, foreign, rec.Code, rec.Body.String())
}
}
}
// The registered redirect with its own query and a fragment kept.
provider.set(func(f *recordingAdminConsent) { f.redirect = "myagent:/callback?state=1&code=c9#frag" })
rec := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP)
provider.set(func(f *recordingAdminConsent) { f.redirect = "" })
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "code=c9") {
t.Fatalf("the registered redirect = %d %s", rec.Code, rec.Body.String())
}
})
t.Run("malformed bodies and the body cap", func(t *testing.T) { t.Run("malformed bodies and the body cap", func(t *testing.T) {
before := provider.callCount() before := provider.callCount()
for _, body := range []string{ for _, body := range []string{
@@ -456,3 +490,39 @@ func TestMCPAdminConsent(t *testing.T) {
} }
}) })
} }
// TestMCPConsentSameRedirect locks the redirect check of the consent
// decision (32.2 WR-06): the provider's redirect must keep the registered
// URI's scheme, user info, host with port, path and opaque part; only the
// query and fragment may differ. Runs under -short.
func TestMCPConsentSameRedirect(t *testing.T) {
const want = "https://agent.example.test:8443/oauth/cb?x=1"
for got, ok := range map[string]bool{
"https://agent.example.test:8443/oauth/cb?x=1&code=a&state=s": true,
"https://agent.example.test:8443/oauth/cb?error=access_denied": true,
"https://agent.example.test:8443/oauth/cb#frag": true,
"http://agent.example.test:8443/oauth/cb?code=a": false,
"https://agent.example.test/oauth/cb?code=a": false,
"https://evil.example:8443/oauth/cb?code=a": false,
"https://user@agent.example.test:8443/oauth/cb?code=a": false,
"https://agent.example.test:8443/oauth/cb/../x?code=a": false,
"https://agent.example.test:8443/oauth/cb2?code=a": false,
"//agent.example.test:8443/oauth/cb?code=a": false,
"javascript:alert(1)": false,
"": false,
"%zz": false,
} {
if mcpConsentSameRedirect(want, got) != ok {
t.Fatalf("mcpConsentSameRedirect(%q, %q) = %v, want %v", want, got, !ok, ok)
}
}
if !mcpConsentSameRedirect("urn:ietf:wg:oauth:2.0:oob", "urn:ietf:wg:oauth:2.0:oob?code=a") {
t.Fatal("an opaque redirect with a query added does not match")
}
if mcpConsentSameRedirect("urn:ietf:wg:oauth:2.0:oob", "urn:ietf:wg:oauth:2.0:other?code=a") {
t.Fatal("a different opaque redirect matches")
}
if mcpConsentSameRedirect("", "https://agent.example.test/cb") {
t.Fatal("an empty registered redirect matches")
}
}

View File

@@ -81,6 +81,29 @@ func mcpConsentRedirectHost(raw string) string {
return u.String() return u.String()
} }
// mcpConsentSameRedirect reports whether got, the redirect a provider
// answered for a decision, goes back to want, the pending request's
// registered redirect URI: the same scheme, user info, host (with its
// port), path and opaque part, whatever query and fragment it adds (the
// code, state, iss or error parameters). An unparsable or empty URI never
// matches, so the consent screen never sends the browser anywhere the
// request did not name.
func mcpConsentSameRedirect(want, got string) bool {
if want == "" || got == "" {
return false
}
w, err := url.Parse(want)
if err != nil {
return false
}
g, err := url.Parse(got)
if err != nil {
return false
}
return g.Scheme != "" && g.Scheme == w.Scheme && g.User.String() == w.User.String() &&
g.Host == w.Host && g.Opaque == w.Opaque && g.EscapedPath() == w.EscapedPath()
}
// mcpConsentShow serves GET /mcp/consent/{request}: the pending MCP // mcpConsentShow serves GET /mcp/consent/{request}: the pending MCP
// authorization request of an administrator-only grant, as the published // authorization request of an administrator-only grant, as the published
// pact.MCPAdminConsent resolves it for the signed-in administrator, with // pact.MCPAdminConsent resolves it for the signed-in administrator, with
@@ -152,8 +175,11 @@ func (s *service) mcpConsentShow(w http.ResponseWriter, r *http.Request) {
// and that the administrator can grant (others are dropped, not refused), // and that the administrator can grant (others are dropped, not refused),
// normalises them as personal-token creation does (* collapses to ["*"]) // normalises them as personal-token creation does (* collapses to ["*"])
// and answers 422 no_grantable_scopes when nothing is left; offline access // 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 // is granted only when it was requested and the body asks for it. Both
// provider owns the transaction and the lock of the pending request. // decisions load the request first (404 when it is gone), and the
// provider's redirect must go back to the request's redirect URI
// (mcpConsentSameRedirect), else 500. The provider owns the transaction
// and the lock of the pending request.
func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) { func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r) principal := accountPrincipal(w, r)
if principal == nil { if principal == nil {
@@ -171,12 +197,14 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request") WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request")
return return
} }
if body.Decision != "allow" && body.Decision != "deny" {
WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request")
return
}
ctx := r.Context() ctx := r.Context()
requestID := r.PathValue("request") requestID := r.PathValue("request")
var decision pact.MCPAdminConsentDecision // Both decisions load the request: an allow filters against its scopes,
switch body.Decision { // and either answer's redirect is checked against its redirect URI.
case "deny":
case "allow":
req, err := provider.MCPAdminConsentShow(ctx, principal.ID, requestID) req, err := provider.MCPAdminConsentShow(ctx, principal.ID, requestID)
if errors.Is(err, pact.ErrMCPConsentNotFound) { if errors.Is(err, pact.ErrMCPConsentNotFound) {
s.writeMCPConsentNotFound(w, r) s.writeMCPConsentNotFound(w, r)
@@ -187,6 +215,8 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusInternalServerError, "error", msgServerError) WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return return
} }
var decision pact.MCPAdminConsentDecision
if body.Decision == "allow" {
grantable := map[string]bool{} grantable := map[string]bool{}
for _, scope := range s.grantableConsentScopes(principal, req.Scopes) { for _, scope := range s.grantableConsentScopes(principal, req.Scopes) {
grantable[scope.Name] = true grantable[scope.Name] = true
@@ -211,9 +241,6 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
Scopes: scopes, Scopes: scopes,
OfflineAccess: req.OfflineAccess && body.OfflineAccess, OfflineAccess: req.OfflineAccess && body.OfflineAccess,
} }
default:
WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request")
return
} }
redirect, err := provider.MCPAdminConsentDecide(ctx, principal.ID, requestID, decision) redirect, err := provider.MCPAdminConsentDecide(ctx, principal.ID, requestID, decision)
switch { switch {
@@ -228,6 +255,11 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusInternalServerError, "error", msgServerError) WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return return
} }
if !mcpConsentSameRedirect(req.RedirectURI, redirect) {
moduleLog.ErrorContext(ctx, "cabana: mcp consent provider answered a foreign redirect", "admin_id", principal.ID, "allow", decision.Allow, "client_id", req.ClientID)
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return
}
moduleLog.InfoContext(ctx, "cabana: mcp consent decided", "admin_id", principal.ID, "allow", decision.Allow, "scopes", decision.Scopes) 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) WriteData(w, http.StatusOK, MCPConsentDecisionView{RedirectURI: redirect}, nil)
} }

View File

@@ -166,7 +166,7 @@ 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; the MCP endpoint refuses any other value. A refused token is `pact.ErrMCPTokenInvalid`. The interface is only `MCPVerifyToken` and `MCPResource`. | | `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; the MCP endpoint refuses any other value. 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.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.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.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, and refuses (500) a redirect URI from Decide that does not go back to the request's `pact.MCPAdminConsentRequest.RedirectURI` (same scheme, host and path); 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.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.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.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. |

View File

@@ -343,6 +343,10 @@ type MCPPersonalTokenResolver interface {
// and owns the scope policy: it shows only requested scopes the // and owns the scope policy: it shows only requested scopes the
// administrator can grant and filters a decision the same way before it // administrator can grant and filters a decision the same way before it
// calls MCPAdminConsentDecide, so the provider only resolves and issues. // calls MCPAdminConsentDecide, so the provider only resolves and issues.
// The framework also loads the request before either decision and refuses
// a redirect URI from MCPAdminConsentDecide that does not go back to its
// RedirectURI (same scheme, user info, host and path; the query and
// fragment may differ).
// //
// MCPAdminConsentShow answers the pending request requestID for the // MCPAdminConsentShow answers the pending request requestID for the
// administrator adminID; a missing, expired, used or foreign request is // administrator adminID; a missing, expired, used or foreign request is