Repository navigation
feat(plugins): expose authenticated caller to route handlers as ctx.user - #1947
Conversation
🦋 Changeset detectedLatest commit: 306504b The changes in this PR will be included in the next version bump. This PR includes changesets to release 17 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
|
This PR has been inactive for 14 days. It will be closed automatically in 7 days if there is no further activity. If you're still working on this, please push an update or leave a comment. |
The plugin API catch-all resolves and authorizes the caller, then drops it before dispatch, leaving plugins no safe way to know who is calling a private route. Thread the validated user through handlePluginApiRoute into RouteContext (native format) and routeCtx.user (standard format, in-process and worker sandboxes alike) as the read-only UserInfo shape. Public routes and machine tokens with no bound user receive undefined; the catch-all only forwards the caller after private-route auth, so an ambient admin session is never bound to a public route. Fixes emdash-cms#812
872b71e to
6d56403
Compare
There was a problem hiding this comment.
This is the right change for #812. Threading a sanitized UserInfo through both native and sandboxed route contexts, stripping host-only fields, and only binding the caller on private routes matches the issue's security requirements and EmDash's architecture. The tests cover the catch-all forwarding rules, the in-process adapter split, and the UserInfo mapping.
I traced the three dispatch paths: the plugin API catch-all, the in-process sandbox adapter, and both generated sandbox wrapper templates. The serialization is JSON/structured-clone safe, and public-route / unbound-token semantics are handled correctly.
Two issues keep this from a clean sign-off:
-
MCP tool invocations don't forward the caller.
handlePluginMcpToolcallshandlePluginApiRoutewithout passing a caller, so plugin route handlers invoked via MCP tools seectx.user === undefinedeven though those are private routes running with authenticated admin auth. This contradicts the PR's stated semantics that private routes always receive the caller. -
AGENTS.md comment violations. New comments reference issue
#812("they're stale narrative" per AGENTS.md) and use justification language like "intentionally". This pattern appears in source files and the generated wrapper templates.
Both should be addressed before merge.
Findings
-
[needs fixing]
packages/core/src/emdash-runtime.ts:3912This call invokes a private plugin route through
handlePluginApiRoutebut omits the authenticated caller. Because MCP tools are exposed only for private plugin routes and run with authenticated admin auth, the route handler will seectx.user === undefined, which contradicts the PR's stated semantics that private routes receive the caller.The
api/mcp.tsroute haslocals.useravailable; pass it throughauthInfo.extra, thread it intohandlePluginMcpTool, and forward it here.actorIdalone is not enough becausetoRouteCallerInfoneeds email, name, role, and createdAt.const result = await this.handlePluginApiRoute( pluginId, "POST", route, internalRequest, caller, );The plumbing also needs updates in
packages/core/src/astro/routes/api/mcp.ts(includeuserinauthInfo.extra),packages/core/src/mcp/server.ts(passpayload.usertohandlePluginMcpTool), and this method's signature (addcaller?: RouteCallerInput | null). -
[needs fixing]
packages/core/src/astro/routes/api/plugins/[pluginId]/[...path].ts:79AGENTS.md forbids referencing issues, PRs, or review threads in comments because they become stale narrative once merged. This PR adds
#812references in several source comments and in the generated sandbox wrapper templates.Examples found:
packages/core/src/emdash-runtime.ts:3748packages/core/src/astro/types.ts:414packages/core/src/plugins/sandbox/types.ts:145packages/cloudflare/src/sandbox/wrapper.ts:262packages/workerd/src/sandbox/wrapper.ts:465
Please drop the issue references and keep only the behavioral explanation.
// Forward the caller only for private routes: it was validated by the // requirePerm/requireScope checks above, so plugins can trust ctx.user. // Public routes skip auth, so no caller is bound even when an ambient // session happens to exist.
There was a problem hiding this comment.
This is the right change for #812. Threading a sanitized UserInfo through the native route context, the in-process sandbox adapter, both generated sandbox wrappers, and the MCP tool path matches the issue's security semantics and EmDash's architecture.
I re-read the full diff and the changed source files, then traced the four dispatch paths (plugin API catch-all, in-process sandbox adapter, Cloudflare Worker Loader wrapper, and workerd wrapper) and the MCP plumbing.
The two prior review findings are addressed:
-
MCP tools now forward the authenticated caller.
packages/core/src/astro/routes/api/mcp.tsputslocals.userintoauthInfo.extra,packages/core/src/mcp/server.tsthreadspayload.userthrough tohandlePluginMcpTool, andpackages/core/src/emdash-runtime.tsaccepts and forwards that caller intohandlePluginApiRoute. The tests inpackages/core/tests/unit/mcp/authorization.test.tsandpackages/core/tests/integration/runtime/plugin-media-route.test.tsassert the caller is passed. -
AGENTS.md comment violations are gone. I searched the changed source files and generated wrapper templates for
#812, issue/PR references, and justification language like "intentionally" in the newly added comments; none remain. Existing issue references such as#1853,#2146, and#1293are in comments from earlier PRs, not introduced here.
Coverage is solid: the catch-all tests verify caller forwarding for private routes and omission for public routes with an ambient session; adapt-sandbox-entry.test.ts verifies routeCtx.user placement and pluginCtx exclusion; routes.test.ts verifies toRouteCallerInfo strips extra host-side fields and converts Date to ISO; MCP tests verify the caller reaches the runtime. The changeset covers the published packages that changed.
No new logic bugs, security gaps, or AGENTS.md violations were found. Approvable as-is.
What does this PR do?
The plugin API catch-all resolves the authenticated user, uses it to enforce
plugins:manage+ scope + CSRF — and then drops it before invoking the plugin's handler. Plugins had no first-class way to know who is calling a private route, forcing bad workarounds (reading a user id from the request body is trivially spoofable).This threads the validated caller through
handlePluginApiRouteinto the route context, exactly as proposed in #812:ctx.useronRouteContext.routeCtx.user— wired through the in-process adapter, the Cloudflare Worker Loader wrapper, and both workerd runners (SerializedRequest.useris structured-clone/JSON-safe).UserInfo({ id, email, name, role, createdAt }) — the same shapectx.usersreturns, with sensitive host-side fields (avatarUrl,data, …) stripped bytoRouteCallerInfo().Semantics (per the issue):
ctx.useris the authenticated caller, validated by the existingrequirePerm/requireScopechecks one frame up.ctx.userisundefined— the catch-all only forwards the caller after private-route auth, so an ambient admin session browsing the site is never bound to a public route.undefined.Purely additive — no change for plugins that don't read
ctx.user, no migration, no flag. Caller identity is intentionally not gated by theusers:readcapability (it's the caller's own identity, not a directory lookup).Tests: route handler exposes/omits
ctx.user(unit), catch-all forwards the caller only for private routes (unit, including the ambient-session case), sandbox adapter putsuseronrouteCtxand strips it frompluginCtx,toRouteCallerInfomapping (Date→ISO, field stripping). Docs updated in the API-routes guide (new "The authenticated caller" section + route context reference) and the native-plugin guide.Closes #812
Discussion: #1757
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain. — n/a, no admin UI stringsAI-generated code disclosure
Screenshots / test output