Files
summercms/modules/cabana/mcp_consent.go
Jakub Zych 97d7ee0586 feat(32.2-01): admin consent endpoint for administrator-only MCP grants
- pact: MCPAdminConsent provider interface, MCPAdminConsentRequest,
  MCPAdminConsentDecision, ErrMCPConsentNotFound, ErrMCPConsentNoScopes
- cabana: GET/POST {api}/mcp/consent/{request}, interactive-only, scope
  policy of personal tokens (requested, catalog, owned; * collapses)
- cabana: TokenScopeNames and TokenScopeLabels export the token-scope catalog
- swag views and annotations; admin.json and schema.d.ts regenerated so the
  contract and conformance inventories stay green
- phrasebook keys mcp_connect.request_not_found and no_grantable_scopes
2026-11-21 00:14:43 +01:00

234 lines
8.1 KiB
Go

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)
}