Files
certctl/internal/mcp/tools_auth.go
T
shankar0123 ddad647ee7 fix(auth/rbac): scope-aware ActorRole revoke (A-4)
HIGH-10's UNIQUE (actor, role, scope_type, scope_id, tenant) uniqueness
extension lets an operator grant the same role to the same actor at
multiple scopes (e.g. r-operator on profile=p-acme AND profile=p-globex).
But ActorRoleRepository.Revoke's WHERE clause omitted (scope_type,
scope_id) — a single call deleted every variant. Selective revoke was
unrepresentable; operators had to drop all and re-grant N-1, opening
a race window where the actor's access was briefly different.

Closure across all layers (handler → service → repo → MCP → GUI client),
preserving the legacy "revoke all variants" contract for unmodified
callers:

  internal/repository/auth.go
    - New ActorRoleRevokeOptions struct. Zero value = legacy semantic;
      non-empty ScopeType narrows to one variant.
    - New ErrActorRoleNotFound sentinel for scoped no-match (HTTP 404).

  internal/repository/postgres/auth.go
    - Revoke signature extended with opts. Empty opts.ScopeType uses
      the legacy SQL (no scope WHERE), zero-row delete = no error.
    - Non-empty narrows with `scope_type = $5 AND scope_id IS NOT
      DISTINCT FROM $6` — the IS-NOT-DISTINCT-FROM is load-bearing,
      vanilla `=` would silently miss the (global, NULL) case because
      NULL ≠ NULL in standard SQL.
    - Selective revoke with zero matching rows returns
      ErrActorRoleNotFound; operators get feedback on typos.

  internal/service/auth/actor_role_service.go
    - Revoke takes opts. Audit row's details map records the scope so
      SIEMs can distinguish wide-vs-selective revokes:
      `scope: "all_variants"` for the legacy path, or
      `scope_type` + `scope_id` for selective. Privilege check
      (auth.role.assign) and reserved-actor guard unchanged.

  internal/api/handler/auth.go
    - RevokeRoleFromKey parses optional `?scope_type=` / `?scope_id=`
      query params via new parseRevokeScope helper.
    - Validation mirrors AssignRoleToKey: scope_id forbidden with
      scope_type=global, required with profile/issuer, invalid
      scope_type → 400. scope_id without scope_type also → 400.
    - writeAuthError maps ErrActorRoleNotFound to 404.

  internal/mcp/tools_auth.go + types.go
    - AuthRevokeKeyRoleInput gains optional ScopeType + ScopeID with
      jsonschema descriptions explaining the dual-mode contract.
    - Tool call site appends URL-encoded query params when ScopeType
      is set; legacy callers (no scope_type) emit the bare DELETE
      path unchanged.

  web/src/api/client.ts
    - authRevokeKeyRole signature: optional 3rd argument
      `{ scope_type?, scope_id? }`. Pre-A-4 call sites (no opts arg)
      keep firing the bare DELETE — fully backward compatible. The
      GUI KeysPage's per-row revoke button (still one row per role,
      pre-Fix-12) continues to use the legacy shape; future GUI work
      can pass scope params for per-variant rows.

  docs/operator/rbac.md
    - New "Revoke: legacy 'all variants' vs scope-selective" subsection
      under "From the HTTP API" with curl examples for both modes plus
      the audit-row payload shape that lets SOC/SIEM tell them apart.

Regression coverage:

  Repository (testcontainers, skipped under -short — 6 tests in
  internal/repository/postgres/auth_revoke_scope_test.go):
    TestRevokeActorRole_NoOpts_RemovesAllVariants
    TestRevokeActorRole_WithScope_RemovesOnlyMatching
    TestRevokeActorRole_WithGlobalScope_RemovesOnlyGlobal — pins the
      IS-NOT-DISTINCT-FROM branch (global, NULL)
    TestRevokeActorRole_NoMatch_ReturnsNotFound — pins the new sentinel
    TestRevokeActorRole_NoOpts_NoMatch_IsNoOp — pins the legacy
      idempotence contract
    TestRevokeActorRole_IssuerScope_RemovesOnlyMatching — pin the
      issuer-scope half (profile + issuer are symmetric scope types)

  Handler (7 new tests in auth_test.go):
    TestAuthHandler_RevokeRoleFromKey — extended to assert no scope
      filter is forwarded when query string is empty (legacy behaviour)
    TestAuthHandler_RevokeRoleFromKey_A4_ScopedProfile
    TestAuthHandler_RevokeRoleFromKey_A4_ScopedGlobal
    TestAuthHandler_RevokeRoleFromKey_A4_RejectsScopeIDWithGlobal
    TestAuthHandler_RevokeRoleFromKey_A4_RejectsMissingScopeID
    TestAuthHandler_RevokeRoleFromKey_A4_RejectsScopeIDWithoutScopeType
    TestAuthHandler_RevokeRoleFromKey_A4_RejectsInvalidScopeType
    TestAuthHandler_RevokeRoleFromKey_A4_ScopedNotFoundReturns404

  MCP (2 new table rows in tools_per_tool_test.go):
    Scoped revoke with scope_type=profile + scope_id=p-acme →
      `?scope_type=profile&scope_id=p-acme`
    Scoped revoke with scope_type=global (no scope_id) →
      `?scope_type=global`

Service-layer test plumbing (service_test.go) updated for new opts
arg: 4 existing call sites pass repository.ActorRoleRevokeOptions{}
to keep their pre-A-4 semantics; the fakeActorRoleRepo.Revoke
implementation now mirrors the postgres scope-aware behaviour
(legacy zero-value vs scoped narrowing + ErrActorRoleNotFound on
no-match).

Verify gate green: gofmt clean, go vet clean, go test -short across
repository/postgres, service/auth, api/handler, and mcp. The
pre-existing KeysPage.test.tsx failure observed on the baseline
commit (reproduced via `git stash` earlier in Fix 03) is unrelated;
my client.ts change adds an optional third argument and is fully
backward-compatible.

Spec at cowork/auth-bundles-fixes-2026-05-11/04-high-actor-role-revoke-scope.md.
Audit doc updated: new row A-4 (2026-05-11) CLOSED appended to the
status table at the bottom of cowork/auth-bundles-audit-2026-05-10.md.
Operator-visible advisory in CHANGELOG.md v2.1.0 release notes under
Security (non-BREAKING — legacy callers are unchanged).

Depends on Fix 01 (the scope-aware EffectivePermissions read path on
branch fix/audit-2026-05-11/crit-actor-role-scope-reads). This fix
makes the inverse op selectively reversible; without Fix 01 the read
side would mis-evaluate scoped grants anyway, making selective revoke
moot at runtime.
2026-05-11 10:50:34 +00:00

214 lines
10 KiB
Go

package mcp
import (
"context"
"net/url"
gomcp "github.com/modelcontextprotocol/go-sdk/mcp"
)
// =============================================================================
// Bundle 1 Phase 11 — RBAC MCP tools.
//
// 12 tools mirroring the Phase-4 + Phase-7 HTTP surface so operators
// driving certctl from Claude / VS Code / any MCP client get the same
// management capability the GUI + CLI already expose. Every tool routes
// through the existing HTTP client (no parallel business logic), so
// permission gates fire server-side: a non-admin caller's MCP tool
// invocation returns whatever 403 the underlying HTTP handler emits.
//
// Coverage map (each tool → HTTP endpoint → permission):
//
// certctl_auth_me GET /v1/auth/me (no perm; own data)
// certctl_auth_list_roles GET /v1/auth/roles auth.role.list
// certctl_auth_get_role GET /v1/auth/roles/{id} auth.role.list
// certctl_auth_create_role POST /v1/auth/roles auth.role.create
// certctl_auth_update_role PUT /v1/auth/roles/{id} auth.role.edit
// certctl_auth_delete_role DELETE /v1/auth/roles/{id} auth.role.delete
// certctl_auth_list_permissions GET /v1/auth/permissions auth.role.list
// certctl_auth_add_permission_to_role POST /v1/auth/roles/{id}/permissions auth.role.edit
// certctl_auth_remove_permission_from_role DELETE /v1/auth/roles/{id}/permissions/{perm} auth.role.edit
// certctl_auth_list_keys GET /v1/auth/keys auth.role.list
// certctl_auth_assign_role_to_key POST /v1/auth/keys/{id}/roles auth.role.assign
// certctl_auth_revoke_role_from_key DELETE /v1/auth/keys/{id}/roles/{role_id} auth.role.assign
//
// CLAUDE.md asks for a re-derive after each MCP-tool addition:
// grep -cE 'mcp\.AddTool\(' internal/mcp/tools*.go
// =============================================================================
func registerAuthTools(s *gomcp.Server, c *Client) {
// ── Identity probe ────────────────────────────────────────────────
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_me",
Description: "Return the current actor's identity, roles, and effective permissions (GET /v1/auth/me). Useful for verifying which API key the MCP server is calling under and what operations it can perform without 403.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, _ struct{}) (*gomcp.CallToolResult, any, error) {
data, err := c.Get("/api/v1/auth/me", nil)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
// ── Roles ─────────────────────────────────────────────────────────
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_list_roles",
Description: "List every role in the active tenant (GET /v1/auth/roles). Permission: auth.role.list.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, _ struct{}) (*gomcp.CallToolResult, any, error) {
data, err := c.Get("/api/v1/auth/roles", nil)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_get_role",
Description: "Get a single role by id, including its current permission grants (GET /v1/auth/roles/{id}). Permission: auth.role.list.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthRoleIDInput) (*gomcp.CallToolResult, any, error) {
data, err := c.Get("/api/v1/auth/roles/"+input.ID, nil)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_create_role",
Description: "Create a new custom role (POST /v1/auth/roles). The 7 default roles (admin / operator / viewer / agent / mcp / cli / auditor) are seeded by migration; this tool is for tenant-specific custom roles. Permission: auth.role.create.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthCreateRoleInput) (*gomcp.CallToolResult, any, error) {
data, err := c.Post("/api/v1/auth/roles", input)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_update_role",
Description: "Update a custom role's name or description (PUT /v1/auth/roles/{id}). Default roles cannot be renamed. Permission: auth.role.edit.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthUpdateRoleInput) (*gomcp.CallToolResult, any, error) {
body := map[string]string{}
if input.Name != "" {
body["name"] = input.Name
}
if input.Description != "" {
body["description"] = input.Description
}
data, err := c.Put("/api/v1/auth/roles/"+input.ID, body)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_delete_role",
Description: "Delete a custom role (DELETE /v1/auth/roles/{id}). Fails with 409 when actors still hold the role; revoke their assignments first via certctl_auth_revoke_role_from_key. Permission: auth.role.delete.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthRoleIDInput) (*gomcp.CallToolResult, any, error) {
data, err := c.Delete("/api/v1/auth/roles/" + input.ID)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
// ── Permissions ───────────────────────────────────────────────────
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_list_permissions",
Description: "List the canonical permission catalogue (GET /v1/auth/permissions). Used by the role editor to populate the grant picker. Permission: auth.role.list.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, _ struct{}) (*gomcp.CallToolResult, any, error) {
data, err := c.Get("/api/v1/auth/permissions", nil)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_add_permission_to_role",
Description: "Grant a permission to a role at a scope (POST /v1/auth/roles/{id}/permissions). Body: permission name (must be in canonical catalogue), scope_type (global|profile|issuer), and scope_id (required for non-global). Permission: auth.role.edit.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthRolePermissionGrantInput) (*gomcp.CallToolResult, any, error) {
body := map[string]any{"permission": input.Permission}
if input.ScopeType != "" {
body["scope_type"] = input.ScopeType
}
if input.ScopeID != "" {
body["scope_id"] = input.ScopeID
}
data, err := c.Post("/api/v1/auth/roles/"+input.RoleID+"/permissions", body)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_remove_permission_from_role",
Description: "Revoke a permission from a role (DELETE /v1/auth/roles/{id}/permissions/{perm}?scope_type=&scope_id=). The scope_type + scope_id query params disambiguate when a permission is granted at multiple scopes. Permission: auth.role.edit.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthRolePermissionRevokeInput) (*gomcp.CallToolResult, any, error) {
path := "/api/v1/auth/roles/" + input.RoleID + "/permissions/" + input.Permission
q := url.Values{}
if input.ScopeType != "" {
q.Set("scope_type", input.ScopeType)
}
if input.ScopeID != "" {
q.Set("scope_id", input.ScopeID)
}
if encoded := q.Encode(); encoded != "" {
path += "?" + encoded
}
data, err := c.Delete(path)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
// ── Keys ──────────────────────────────────────────────────────────
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_list_keys",
Description: "List every actor in the active tenant with at least one role grant (GET /v1/auth/keys). Includes the synthetic actor-demo-anon row when CERTCTL_AUTH_TYPE=none is configured; that row is system-managed and cannot be mutated. Permission: auth.role.list.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, _ struct{}) (*gomcp.CallToolResult, any, error) {
data, err := c.Get("/api/v1/auth/keys", nil)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_assign_role_to_key",
Description: "Assign a role to an API key actor (POST /v1/auth/keys/{id}/roles). Body: role_id. Privilege-escalation guard: the caller must hold auth.role.assign globally (admin role or equivalent). Permission: auth.role.assign.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthAssignKeyRoleInput) (*gomcp.CallToolResult, any, error) {
data, err := c.Post("/api/v1/auth/keys/"+input.KeyID+"/roles",
map[string]string{"role_id": input.RoleID})
if err != nil {
return errorResult(err)
}
return textResult(data)
})
gomcp.AddTool(s, &gomcp.Tool{
Name: "certctl_auth_revoke_role_from_key",
Description: "Revoke a role from an API key actor (DELETE /v1/auth/keys/{id}/roles/{role_id}). Rejects revocations against the reserved actor-demo-anon (HTTP 409). Audit 2026-05-11 A-4: pass scope_type=global / profile / issuer (with scope_id for the latter two) to selectively revoke ONE variant when the actor holds the same role at multiple scopes; omit both for the legacy 'revoke every variant' behaviour. Permission: auth.role.assign.",
}, func(ctx context.Context, req *gomcp.CallToolRequest, input AuthRevokeKeyRoleInput) (*gomcp.CallToolResult, any, error) {
// Audit 2026-05-11 A-4 — append the optional scope filter when
// the caller supplied scope_type. The handler validates the
// pair shape (scope_id required vs forbidden) so we don't
// duplicate that here.
path := "/api/v1/auth/keys/" + input.KeyID + "/roles/" + input.RoleID
if input.ScopeType != "" {
q := "?scope_type=" + url.QueryEscape(input.ScopeType)
if input.ScopeID != "" {
q += "&scope_id=" + url.QueryEscape(input.ScopeID)
}
path += q
}
data, err := c.Delete(path)
if err != nil {
return errorResult(err)
}
return textResult(data)
})
}