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

@@ -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/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 `/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/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. |

View File

@@ -483,7 +483,7 @@ 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).
// @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
// @Accept json
// @Produce json

View File

@@ -35,8 +35,10 @@ type recordingAdminConsent struct {
required bool
showErr error
decideErr error
shows []consentCall
calls []consentCall
// redirect replaces Decide's redirect URI while set.
redirect string
shows []consentCall
calls []consentCall
}
func (f *recordingAdminConsent) set(fn func(*recordingAdminConsent)) {
@@ -71,6 +73,9 @@ func (f *recordingAdminConsent) MCPAdminConsentDecide(_ context.Context, adminID
if requestID != "req1" {
return "", pact.ErrMCPConsentNotFound
}
if f.redirect != "" {
return f.redirect, nil
}
if !decision.Allow {
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" {
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 {
t.Fatalf("deny of an unknown request reached Decide with %+v", got)
// Both decisions load the request first: neither reaches Decide.
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 })
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) {
before := provider.callCount()
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()
}
// 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
// authorization request of an administrator-only grant, as the published
// 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),
// 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.
// is granted only when it was requested and the body asks for it. Both
// 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) {
principal := accountPrincipal(w, r)
if principal == nil {
@@ -171,22 +197,26 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request")
return
}
if body.Decision != "allow" && body.Decision != "deny" {
WriteError(w, http.StatusBadRequest, "invalid_request", "Invalid request")
return
}
ctx := r.Context()
requestID := r.PathValue("request")
// Both decisions load the request: an allow filters against its scopes,
// and either answer's redirect is checked against its redirect URI.
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
}
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
}
if body.Decision == "allow" {
grantable := map[string]bool{}
for _, scope := range s.grantableConsentScopes(principal, req.Scopes) {
grantable[scope.Name] = true
@@ -211,9 +241,6 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
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 {
@@ -228,6 +255,11 @@ func (s *service) mcpConsentDecide(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
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)
WriteData(w, http.StatusOK, MCPConsentDecisionView{RedirectURI: redirect}, nil)
}