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
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
233
modules/cabana/mcp_consent.go
Normal file
233
modules/cabana/mcp_consent.go
Normal file
@@ -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)
|
||||
}
|
||||
302
modules/cabana/mcp_consent_smoke_test.go
Normal file
302
modules/cabana/mcp_consent_smoke_test.go
Normal file
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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" }
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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,
|
||||
|
||||
63
modules/cabana/token_scopes_export.go
Normal file
63
modules/cabana/token_scopes_export.go
Normal file
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user