Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6581: expose globally versioned Plugin Public API (#7446)

Jiayuan Zhanga4e1ea7140c4
diff --git a/.env.example b/.env.example
index b6ecf96422..c438890aec 100644
--- a/.env.example
+++ b/.env.example
@@ -551,8 +551,14 @@ MULTICA_VCS_SECRET_KEY=
# instead of zipping and uploading after every edit. It still produces an
# ordinary immutable version, so there is no second way for plugin code to
# reach a browser. Leave empty to accept uploads only.
+# 4. MULTICA_PLUGIN_API_URL — the complete, versioned Public API base URL
+# sent to hook servers (for example https://plugin-api.example.com/v1).
+# Route this hostname's /v1/* traffic to the backend. Leave empty to use
+# MULTICA_PUBLIC_URL + /v1, which is convenient for local and self-hosted
+# deployments that serve the Public API on the ordinary API origin.
MULTICA_PLUGIN_SECRET_KEY=
MULTICA_PLUGIN_SURFACE_ORIGIN=
+MULTICA_PLUGIN_API_URL=
MULTICA_PLUGIN_DIR=
# Lark / Feishu bot integration (Settings → Integrations "Bind to Lark")
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 29fbc2199f..42a6e879ec 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -522,10 +522,10 @@ COOKIE_DOMAIN= # empty: cookies are host-only on app.examp
# Frontend
NEXT_PUBLIC_API_URL= # empty: the client uses relative /api paths on the page origin
NEXT_PUBLIC_WS_URL= # empty
-REMOTE_API_URL=http://backend:8080 # target the Next.js rewrites proxy /api, /auth and /uploads to
+REMOTE_API_URL=http://backend:8080 # target the Next.js rewrites proxy /v1, /api, /auth and /uploads to
```
-Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because Next.js rewrites forward `/api`, `/auth` and `/uploads` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a `/ws` block to the frontend vhost that reaches the backend directly:
+Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because Next.js rewrites forward `/v1`, `/api`, `/auth` and `/uploads` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a `/ws` block to the frontend vhost that reaches the backend directly:
```nginx
# Add to the app.example.com server block above
@@ -561,7 +561,7 @@ docker compose -f docker-compose.selfhost.yml up -d
### WebSocket for LAN / Non-localhost Access
-HTTP requests (issues, comments, uploads) work on LAN out of the box — Next.js rewrites proxy `/api`, `/auth`, and `/uploads` to the backend. **WebSockets do not**: Next.js rewrites only forward HTTP requests, not the `Upgrade` handshake a WebSocket needs. If you open the app on `http://<lan-ip>:3000`, real-time features (chat streaming, live issue updates, notifications) will fail to connect until you do one of the following:
+HTTP requests (Plugin API, issues, comments, uploads) work on LAN out of the box — Next.js rewrites proxy `/v1`, `/api`, `/auth`, and `/uploads` to the backend. **WebSockets do not**: Next.js rewrites only forward HTTP requests, not the `Upgrade` handshake a WebSocket needs. If you open the app on `http://<lan-ip>:3000`, real-time features (chat streaming, live issue updates, notifications) will fail to connect until you do one of the following:
1. **Put a reverse proxy in front of the stack (recommended).** Nginx or Caddy terminates the WebSocket upgrade and forwards it to the backend on port 8080. See the [Reverse Proxy](#reverse-proxy) section above — the Nginx example already includes a `location /ws { ... }` block with the correct `Upgrade` / `Connection` headers. Once a proxy is in place the browser connects directly through it, so no frontend rebuild is needed.
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index eb3e3a1175..8dbf140417 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -178,6 +178,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| セルフホスト Git | `MULTICA_VCS_SECRET_KEY` | base64 エンコードされた 32 バイトの暗号化キー(`openssl rand -base64 32`)。未設定の場合、この機能全体が利用できません |
| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | 保存済み secret と surface 起動 URL を暗号化する base64 形式の 32 バイト鍵 |
| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | バックエンドへルーティングする Cookie なしの専用 origin。app/API origin と分離し、`Host` を保持すること |
+| Plugins | `MULTICA_PLUGIN_API_URL` | バージョンを含む Plugin Public API の完全な Base URL(例: `https://plugin-api.example.com/v1`)。未設定時は `MULTICA_PUBLIC_URL` + `/v1` |
| Plugins | `MULTICA_PLUGIN_DIR` | 開発時にローカル plugin bundle を公開するための任意の絶対ディレクトリ |
`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージによる done への遷移は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 8804b427ec..48d6873107 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -178,6 +178,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| 자체 호스팅 Git | `MULTICA_VCS_SECRET_KEY` | base64로 인코딩한 32바이트 암호화 키(`openssl rand -base64 32`). 없으면 전체 기능을 사용할 수 없음 |
| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | 저장된 secret과 surface 실행 URL을 암호화하는 base64 인코딩 32바이트 키 |
| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 백엔드로 라우팅되는 쿠키 없는 전용 origin. app/API origin과 달라야 하며 `Host`를 보존해야 함 |
+| Plugins | `MULTICA_PLUGIN_API_URL` | 버전을 포함한 Plugin Public API의 전체 Base URL(예: `https://plugin-api.example.com/v1`). 설정하지 않으면 `MULTICA_PUBLIC_URL` + `/v1` 사용 |
| Plugins | `MULTICA_PLUGIN_DIR` | 개발 중 로컬 plugin bundle을 게시하는 선택적 절대 디렉터리 |
`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 done 전환은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 3671a7c1d2..7f474b6b4f 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -178,6 +178,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
| Self-hosted Git | `MULTICA_VCS_SECRET_KEY` | Base64-encoded 32-byte encryption key (`openssl rand -base64 32`); the feature is entirely unavailable without it |
| Plugins | `MULTICA_PLUGIN_SECRET_KEY` | Base64-encoded 32-byte key for stored secrets and encrypted surface launch URLs |
| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | Dedicated cookie-free browser origin routed to this backend; must differ from app/API origins and preserve `Host` |
+| Plugins | `MULTICA_PLUGIN_API_URL` | Complete versioned Plugin Public API base URL, such as `https://plugin-api.example.com/v1`; falls back to `MULTICA_PUBLIC_URL` + `/v1` |
| Plugins | `MULTICA_PLUGIN_DIR` | Optional absolute directory used to publish local plugin bundles during development |
Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and trigger merge-to-done normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 7ece129bea..54efc2e866 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -178,6 +178,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| 自托管 Git | `MULTICA_VCS_SECRET_KEY` | base64 编码的 32 字节加密密钥(`openssl rand -base64 32`);未配置时该功能整体不可用 |
| 插件 | `MULTICA_PLUGIN_SECRET_KEY` | base64 编码的 32 字节密钥,用于加密已存 secret 和 surface 启动 URL |
| 插件 | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 路由到后端的独立无 Cookie 浏览器 origin;必须不同于 app/API origin,并保留 `Host` |
+| 插件 | `MULTICA_PLUGIN_API_URL` | 带版本的插件 Public API 完整 Base URL,例如 `https://plugin-api.example.com/v1`;未设置时使用 `MULTICA_PUBLIC_URL` + `/v1` |
| 插件 | `MULTICA_PLUGIN_DIR` | 开发时用于发布本地插件包的可选绝对目录 |
不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像和触发合并转 done,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。
diff --git a/apps/web/config/runtime-urls.test.ts b/apps/web/config/runtime-urls.test.ts
index b3f01b10c1..c23e70b0cb 100644
--- a/apps/web/config/runtime-urls.test.ts
+++ b/apps/web/config/runtime-urls.test.ts
@@ -213,6 +213,7 @@ describe("browser runtime URLs", () => {
describe("runtimeRewriteDestination", () => {
it("keeps same-origin fallback when no runtime upstreams are configured", () => {
expect(runtimeRewriteDestination("/api/config", {})).toBeUndefined();
+ expect(runtimeRewriteDestination("/v1/context", {})).toBeUndefined();
expect(runtimeRewriteDestination("/auth/send-code", {})).toBeUndefined();
expect(
runtimeRewriteDestination("/uploads/workspaces/a.png", {}),
@@ -243,6 +244,11 @@ describe("runtimeRewriteDestination", () => {
REMOTE_API_URL: "http://backend:8080",
}),
).toBe("http://backend:8080/api/config");
+ expect(
+ runtimeRewriteDestination("/v1/issues/MUL-6581", {
+ REMOTE_API_URL: "http://backend:8080",
+ }),
+ ).toBe("http://backend:8080/v1/issues/MUL-6581");
expect(
runtimeRewriteDestination("/auth/send-code", {
REMOTE_API_URL: "http://backend:8080",
diff --git a/apps/web/config/runtime-urls.ts b/apps/web/config/runtime-urls.ts
index ba37c0b62b..01cd624962 100644
--- a/apps/web/config/runtime-urls.ts
+++ b/apps/web/config/runtime-urls.ts
@@ -122,6 +122,9 @@ export function runtimeRewriteDestination(
const remoteApiUrl = resolveRemoteApiUrl(env);
if (!remoteApiUrl) return undefined;
+ if (pathname === "/v1" || pathname.startsWith("/v1/")) {
+ return appendPath(remoteApiUrl, pathname);
+ }
if (pathname === "/api" || pathname.startsWith("/api/")) {
return appendPath(remoteApiUrl, pathname);
}
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index 4348027a53..680b90e370 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -66,6 +66,10 @@ const nextConfig: NextConfig = {
: [],
afterFiles: remoteApiUrl
? [
+ {
+ source: "/v1/:path*",
+ destination: `${remoteApiUrl}/v1/:path*`,
+ },
{
source: "/api/:path*",
destination: `${remoteApiUrl}/api/:path*`,
diff --git a/apps/web/proxy.test.ts b/apps/web/proxy.test.ts
index 52383335e0..20623421f8 100644
--- a/apps/web/proxy.test.ts
+++ b/apps/web/proxy.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { NextRequest } from "next/server";
import { MULTICA_LOCALE_HEADER } from "./lib/locale-routing";
-import { proxy } from "./proxy";
+import { config, proxy } from "./proxy";
function makeRequest(
path: string,
@@ -134,6 +134,10 @@ describe("proxy legacy workspace route redirects", () => {
});
describe("proxy runtime upstream rewrites", () => {
+ it("matches globally versioned Plugin API requests", () => {
+ expect(config.matcher).toContain("/v1/:path*");
+ });
+
it("does not rewrite API requests when no runtime API origin is configured", () => {
withoutRuntimeUpstreams(() => {
const res = proxy(makeRequest("/api/config?x=1"));
@@ -146,6 +150,15 @@ describe("proxy runtime upstream rewrites", () => {
});
});
+ it("does not rewrite Plugin API requests when no runtime API origin is configured", () => {
+ withoutRuntimeUpstreams(() => {
+ const res = proxy(makeRequest("/v1/context?x=1"));
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("x-middleware-rewrite")).toBeNull();
+ });
+ });
+
it("does not rewrite docs requests when no runtime docs origin is configured", () => {
withoutRuntimeUpstreams(() => {
const res = proxy(makeRequest("/docs/zh"));
@@ -173,6 +186,21 @@ describe("proxy runtime upstream rewrites", () => {
}
});
+ it("rewrites Plugin API requests to the runtime API origin", () => {
+ const previous = process.env.REMOTE_API_URL;
+ process.env.REMOTE_API_URL = "http://backend:8080";
+ try {
+ const res = proxy(makeRequest("/v1/issues/MUL-6581?x=1"));
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("x-middleware-rewrite")).toBe(
+ "http://backend:8080/v1/issues/MUL-6581?x=1",
+ );
+ } finally {
+ restoreEnv("REMOTE_API_URL", previous);
+ }
+ });
+
it("rewrites docs requests to the runtime docs origin", () => {
const previous = process.env.DOCS_URL;
process.env.DOCS_URL = "http://docs:4000";
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index 7469c04eab..2ebf037c3d 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -117,11 +117,12 @@ export const config = {
// proxy routes whose upstream origins are resolved from process.env at
// request time instead of being baked into next.config.js at build time.
matcher: [
+ "/v1/:path*",
"/api/:path*",
"/auth/:path*",
"/uploads/:path*",
"/docs/:path*",
"/ws",
- "/((?!api|_next/static|_next/image|favicon.ico|.*\\.).*)",
+ "/((?!api|v1|_next/static|_next/image|favicon.ico|.*\\.).*)",
],
};
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index 27aad60b26..b29753bb5c 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -177,7 +177,7 @@ backend:
frontend:
replicas: 1
config:
- # Backend origin used by the frontend runtime proxy for /api, /auth,
+ # Backend origin used by the frontend runtime proxy for /v1, /api, /auth,
# /uploads, and /ws. Empty defaults to this release's backend Service.
remoteApiUrl: ""
# Optional docs origin used by the frontend runtime proxy for /docs.
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 8bdb9dc7c1..cdb90ac848 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -139,6 +139,7 @@ services:
# either empty disables plugin surfaces rather than weakening isolation.
MULTICA_PLUGIN_SECRET_KEY: ${MULTICA_PLUGIN_SECRET_KEY:-}
MULTICA_PLUGIN_SURFACE_ORIGIN: ${MULTICA_PLUGIN_SURFACE_ORIGIN:-}
+ MULTICA_PLUGIN_API_URL: ${MULTICA_PLUGIN_API_URL:-}
MULTICA_PLUGIN_DIR: ${MULTICA_PLUGIN_DIR:-}
# Comma-separated CIDRs whose source IP is allowed to set
# X-Forwarded-For / X-Real-IP for the webhook per-IP rate limiter.
diff --git a/examples/plugins/deploy-sentinel/server/handler.mjs b/examples/plugins/deploy-sentinel/server/handler.mjs
index fec78dde25..908c03440b 100644
--- a/examples/plugins/deploy-sentinel/server/handler.mjs
+++ b/examples/plugins/deploy-sentinel/server/handler.mjs
@@ -75,13 +75,13 @@ function verifySignature(rawBody, signature, timestamp) {
// The callback token is scoped to THIS invocation and is revoked the moment the
// hook returns, so anything the handler wants to write has to be written before
// it replies. That constraint is the reason this is awaited, not fired off.
-async function commentOnIssue(callback, issueId, body) {
- if (!callback?.token || !callback?.base_url || !issueId) return;
+async function commentOnIssue(callbackUrl, callbackToken, issueId, content) {
+ if (!callbackToken || !callbackUrl || !issueId) return;
try {
- const response = await fetch(`${callback.base_url}/api/v1/plugin/issues/${issueId}/comments`, {
+ const response = await fetch(`${callbackUrl}/issues/${encodeURIComponent(issueId)}/comments`, {
method: "POST",
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${callback.token}` },
- body: JSON.stringify({ body }),
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${callbackToken}` },
+ body: JSON.stringify({ content }),
});
if (!response.ok) {
console.warn(`callback comment failed: ${response.status} ${await response.text()}`);
@@ -178,7 +178,15 @@ const server = createServer(tlsOptions(), async (req, res) => {
return reply(400, { error: "body is not valid JSON" });
}
- const { hook_key: hookKey, trigger, input = {}, config = {}, callback, issue_id: issueId } = payload;
+ const {
+ hook_key: hookKey,
+ trigger,
+ input = {},
+ config = {},
+ callback_url: callbackUrl,
+ callback_token: callbackToken,
+ issue_id: issueId,
+ } = payload;
console.log(`${hookKey} via ${trigger}`);
switch (hookKey) {
@@ -188,7 +196,7 @@ const server = createServer(tlsOptions(), async (req, res) => {
// their colleagues will see it. An agent call already returns to the
// agent, which will write its own account of what it found.
if (trigger === "ui" || trigger === "manual") {
- await commentOnIssue(callback, issueId, `**Deploy Sentinel** — ${result.summary}`);
+ await commentOnIssue(callbackUrl, callbackToken, issueId, `**Deploy Sentinel** — ${result.summary}`);
}
return reply(200, result);
}
@@ -197,7 +205,8 @@ const server = createServer(tlsOptions(), async (req, res) => {
const result = requestRollback(input, config);
if (result.status === "filed") {
await commentOnIssue(
- callback,
+ callbackUrl,
+ callbackToken,
issueId,
`**Deploy Sentinel** filed rollback ${result.change_id} for deploy ${result.deploy_id}.\n\n> ${input.reason}\n\nAwaiting human approval — nothing has been rolled back.`,
);
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 19a8328dbf..9c35606a92 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -192,6 +192,53 @@ describe("ApiClient Plugin preview response schema", () => {
});
});
+describe("ApiClient Plugin surface bridge routes", () => {
+ it("relays Action API calls through the session-only bridge prefix", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response("{}", { status: 200, headers: { "Content-Type": "application/json" } }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").callPluginAction(
+ "installation-1",
+ { method: "GET", path: "/context", issueId: "MUL-42" },
+ );
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://api.example.test/api/plugin-bridge/v1/context?issue_id=MUL-42",
+ );
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "GET",
+ headers: expect.objectContaining({
+ "X-Multica-Plugin-Installation": "installation-1",
+ }),
+ });
+ });
+
+ it("invokes UI hooks through the session-only bridge prefix", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({
+ status: "ok",
+ hook_key: "summarize",
+ trigger: "ui",
+ latency_ms: 1,
+ attempts: 1,
+ }), { status: 200, headers: { "Content-Type": "application/json" } }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").invokePluginHook(
+ "installation-1",
+ "summarize",
+ { trigger: "ui", issueId: "issue-1" },
+ );
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://api.example.test/api/plugin-bridge/v1/hooks/summarize",
+ );
+ });
+});
+
describe("ApiClient server Table query", () => {
it("posts the canonical query to the group and branch endpoints", async () => {
const fetchMock = vi
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 867a29d1b0..6f9c2e01d3 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2672,7 +2672,7 @@ export class ApiClient {
const query = request.path === "/context" && request.issueId
? `?issue_id=${encodeURIComponent(request.issueId)}`
: "";
- return this.fetch<unknown>(`/api/v1/plugin${request.path}${query}`, {
+ return this.fetch<unknown>(`/api/plugin-bridge/v1${request.path}${query}`, {
method: request.method,
headers: { "X-Multica-Plugin-Installation": installationId },
body: request.body === undefined ? undefined : JSON.stringify(request.body),
@@ -2693,7 +2693,7 @@ export class ApiClient {
hookKey: string,
request: { trigger: "ui" | "manual"; issueId?: string; input?: unknown },
): Promise<PluginHookResult> {
- const raw = await this.fetch<unknown>(`/api/v1/plugin/hooks/${encodeURIComponent(hookKey)}`, {
+ const raw = await this.fetch<unknown>(`/api/plugin-bridge/v1/hooks/${encodeURIComponent(hookKey)}`, {
method: "POST",
headers: { "X-Multica-Plugin-Installation": installationId },
body: JSON.stringify({ trigger: request.trigger, issue_id: request.issueId, input: request.input }),
@@ -2704,7 +2704,7 @@ export class ApiClient {
trigger: request.trigger,
latency_ms: 0,
attempts: 1,
- }, { endpoint: "POST /api/v1/plugin/hooks/{key}" });
+ }, { endpoint: "POST /api/plugin-bridge/v1/hooks/{key}" });
}
async listPluginInvocations(workspaceId: string, installationId: string): Promise<PluginInvocation[]> {
diff --git a/server/cmd/server/plugin_action_routes_test.go b/server/cmd/server/plugin_action_routes_test.go
new file mode 100644
index 0000000000..0336cdf775
--- /dev/null
+++ b/server/cmd/server/plugin_action_routes_test.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+ "io"
+ "net/http"
+ "testing"
+)
+
+func TestPluginActionRouteTrustBoundaries(t *testing.T) {
+ tests := []struct {
+ name string
+ path string
+ authorization string
+ wantStatus int
+ wantHandler bool
+ }{
+ {
+ name: "public API rejects a missing token before the handler",
+ path: "/v1/context",
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "public API rejects a browser session token",
+ path: "/v1/context",
+ authorization: "Bearer " + testToken,
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "public API passes plugin tokens to the Action handler",
+ path: "/v1/context",
+ authorization: "Bearer mpi_invalid",
+ wantHandler: true,
+ },
+ {
+ name: "surface bridge accepts a browser session",
+ path: "/api/plugin-bridge/v1/context",
+ authorization: "Bearer " + testToken,
+ wantHandler: true,
+ },
+ {
+ name: "removed legacy prefix is not routed",
+ path: "/api/v1/plugin/context",
+ wantStatus: http.StatusNotFound,
+ },
+ {
+ name: "public API does not expose person-triggered hooks",
+ path: "/v1/hooks/summarize",
+ authorization: "Bearer mpi_invalid",
+ wantStatus: http.StatusNotFound,
+ },
+ {
+ name: "surface bridge retains person-triggered hooks",
+ path: "/api/plugin-bridge/v1/hooks/summarize",
+ authorization: "Bearer " + testToken,
+ wantStatus: http.StatusMethodNotAllowed,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req, err := http.NewRequest(http.MethodGet, testServer.URL+tt.path, nil)
+ if err != nil {
+ t.Fatalf("build request: %v", err)
+ }
+ if tt.authorization != "" {
+ req.Header.Set("Authorization", tt.authorization)
+ }
+ response, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("request failed: %v", err)
+ }
+ defer response.Body.Close()
+ _, _ = io.Copy(io.Discard, response.Body)
+
+ if tt.wantHandler {
+ if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusNotFound {
+ t.Fatalf("status = %d, request did not reach the Action handler", response.StatusCode)
+ }
+ return
+ }
+ if response.StatusCode != tt.wantStatus {
+ t.Fatalf("status = %d, want %d", response.StatusCode, tt.wantStatus)
+ }
+ })
+ }
+}
+
+func TestPluginActionBaseURLPrefersDedicatedVersionedBase(t *testing.T) {
+ t.Setenv("MULTICA_PLUGIN_API_URL", " https://plugin-api.example.com/v1/ ")
+
+ if got := pluginActionBaseURL("https://api.example.com/"); got != "https://plugin-api.example.com/v1" {
+ t.Fatalf("pluginActionBaseURL() = %q", got)
+ }
+}
+
+func TestPluginActionBaseURLFallsBackToPublicURL(t *testing.T) {
+ t.Setenv("MULTICA_PLUGIN_API_URL", "")
+
+ if got := pluginActionBaseURL(" https://api.example.com/ "); got != "https://api.example.com/v1" {
+ t.Fatalf("pluginActionBaseURL() = %q", got)
+ }
+}
+
+func TestPluginActionBaseURLOmittedWithoutPublicOrigin(t *testing.T) {
+ t.Setenv("MULTICA_PLUGIN_API_URL", "")
+
+ if got := pluginActionBaseURL(""); got != "" {
+ t.Fatalf("pluginActionBaseURL() = %q, want empty", got)
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 8486c8e835..7eaaee87c4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -53,6 +53,11 @@ var defaultOrigins = []string{
"http://localhost:5174", // electron-vite dev (fallback port)
}
+const (
+ pluginActionPublicPrefix = "/v1"
+ pluginBridgePrefix = "/api/plugin-bridge/v1"
+)
+
// corsAllowedHeaders must list every header the browser clients send. A header
// missing here fails the preflight, so the request never reaches the handler at
// all — the failure looks nothing like "the server ignored my header".
@@ -91,6 +96,18 @@ var corsExposedHeaders = []string{
handler.HeaderTimelineTruncated,
}
+func registerPluginActionRoutes(r chi.Router, h *handler.Handler) {
+ r.Get("/context", h.GetPluginContext)
+ r.Get("/issues/{id}", h.GetPluginIssue)
+ r.Patch("/issues/{id}", h.PatchPluginIssue)
+ r.Get("/issues/{id}/comments", h.ListPluginComments)
+ r.Post("/issues/{id}/comments", h.CreatePluginComment)
+ r.Get("/storage/{scope}", h.ListPluginStorage)
+ r.Get("/storage/{scope}/{key}", h.GetPluginStorage)
+ r.Put("/storage/{scope}/{key}", h.PutPluginStorage)
+ r.Delete("/storage/{scope}/{key}", h.DeletePluginStorage)
+}
+
func allowedOrigins() []string {
raw := strings.TrimSpace(os.Getenv("CORS_ALLOWED_ORIGINS"))
if raw == "" {
@@ -125,6 +142,21 @@ func appURLFromEnv() string {
return strings.TrimRight(strings.TrimSpace(os.Getenv("FRONTEND_ORIGIN")), "/")
}
+// pluginActionBaseURL resolves the versioned public base a hook handler calls
+// back into. Managed deployments give the Plugin API its own hostname through
+// MULTICA_PLUGIN_API_URL; self-hosted and local deployments can leave it empty
+// and serve the same /v1 contract on MULTICA_PUBLIC_URL.
+func pluginActionBaseURL(publicURL string) string {
+ if value := strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_API_URL")), "/"); value != "" {
+ return value
+ }
+ publicURL = strings.TrimRight(strings.TrimSpace(publicURL), "/")
+ if publicURL == "" {
+ return ""
+ }
+ return publicURL + pluginActionPublicPrefix
+}
+
// parseTrustedProxies parses a comma-separated list of CIDR prefixes from the
// MULTICA_TRUSTED_PROXIES env var. Invalid entries are dropped with a single
// warn-line per entry rather than crashing the server — a typo in one CIDR
@@ -1101,13 +1133,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// put an outside server on the critical path of creating an issue.
if h.PluginService != nil {
h.PluginService.Callbacks = service.NewCallbackTokens()
- // Omitted rather than sent relative: a handler receiving
- // "/api/v1/plugin" cannot call anything with it, and a broken absolute
- // URL is harder to diagnose than an absent one.
- if publicURL := strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")); publicURL != "" {
- h.PluginService.CallbackBaseURL = strings.TrimSuffix(publicURL, "/") + "/api/v1/plugin"
+ // Omitted rather than sent relative: a third-party hook server cannot
+ // call a path-only URL, and a broken absolute URL is harder to diagnose
+ // than an absent one.
+ if baseURL := pluginActionBaseURL(signupConfig.PublicURL); baseURL != "" {
+ h.PluginService.CallbackBaseURL = baseURL
} else {
- slog.Warn("plugins: MULTICA_PUBLIC_URL is not set; hook callbacks will carry no callback_url")
+ slog.Warn("plugins: MULTICA_PLUGIN_API_URL and MULTICA_PUBLIC_URL are not set; hook callbacks will carry no callback_url")
}
// The flag reaches the event path only through the service: a worker has
// no request to read it from.
@@ -1365,35 +1397,27 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/tasks/{taskId}/session", h.PinTaskSession)
})
- // Protected API routes
- // Plugin Action API. Two kinds of caller reach these, and the difference is
- // only in WHO the call acts as.
- //
- // A SURFACE has no credential: the iframe asks the host page over the
- // postMessage bridge, and the host re-issues the call on the signed-in
- // user's own session, naming the installation in a header the iframe cannot
- // set for itself. That path goes through the ordinary Auth chain.
- //
- // A HOOK HANDLER — the plugin author's own server — has no session and
- // never will, so it presents a plugin bearer token instead. PluginAuth
- // routes that request past the session chain to the handler, which resolves
- // the token itself; a request with neither credential is refused there.
- //
- // The workspace always comes from the installation, never from the client.
+ // Public Plugin Action API. This is the stable, globally versioned contract
+ // exposed on the Plugin API origin. It accepts only mpi_/mpc_ bearer tokens;
+ // browser sessions use the bridge group below and cannot cross this trust
+ // boundary even when both hostnames route to the same Go service.
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.PluginBearerOnly)
+ r.Route(pluginActionPublicPrefix, func(r chi.Router) {
+ registerPluginActionRoutes(r, h)
+ })
+ })
+
+ // Browser-session relay for sandboxed plugin surfaces. The iframe talks to
+ // the host over MessagePort; the host calls this internal route with the
+ // signed-in user's session and the installation header. Keeping it outside
+ // /v1 prevents the Public API from accepting session cookies.
r.Group(func(r chi.Router) {
- r.Use(middleware.PluginAuth(middleware.Auth(queries, patCache, cloudPATVerifier)))
- r.Route("/api/v1/plugin", func(r chi.Router) {
- r.Get("/context", h.GetPluginContext)
- r.Get("/issues/{id}", h.GetPluginIssue)
- r.Patch("/issues/{id}", h.PatchPluginIssue)
- r.Get("/issues/{id}/comments", h.ListPluginComments)
- r.Post("/issues/{id}/comments", h.CreatePluginComment)
- r.Get("/storage/{scope}", h.ListPluginStorage)
- r.Get("/storage/{scope}/{key}", h.GetPluginStorage)
- r.Put("/storage/{scope}/{key}", h.PutPluginStorage)
- r.Delete("/storage/{scope}/{key}", h.DeletePluginStorage)
+ r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))
+ r.Route(pluginBridgePrefix, func(r chi.Router) {
+ registerPluginActionRoutes(r, h)
// ui / manual only. `event` is dispatched by the host off the event
- // bus and never requested; `agent` arrives over MCP in PR 4.
+ // bus; `agent` arrives over MCP rather than this HTTP endpoint.
r.Post("/hooks/{key}", h.InvokePluginHook)
})
})
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 919cc0ed46..119b35d370 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -227,7 +227,7 @@ func (h *Handler) resolvePluginIssue(r *http.Request, caller service.PluginActio
return issue, true
}
-// GetPluginContext — GET /api/v1/plugin/context
+// GetPluginContext — GET /v1/context
func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {
// No scope: this is the page the user is already looking at.
caller, actor, ok := h.pluginCaller(w, r, "")
@@ -263,7 +263,7 @@ func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, h.PluginService.BuildPluginContext(caller, workspace, user, issue))
}
-// GetPluginIssue — GET /api/v1/plugin/issues/{id}
+// GetPluginIssue — GET /v1/issues/{id}
func (h *Handler) GetPluginIssue(w http.ResponseWriter, r *http.Request) {
caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesRead)
if !ok {
@@ -281,7 +281,7 @@ type patchPluginIssueRequest struct {
Description *string `json:"description,omitempty"`
}
-// PatchPluginIssue — PATCH /api/v1/plugin/issues/{id}
+// PatchPluginIssue — PATCH /v1/issues/{id}
//
// Title and description only. Status, priority, assignee, parent, project and
// stage each carry dispatch, catalog or hierarchy semantics — a status change
@@ -352,7 +352,7 @@ func (h *Handler) pluginIssuePayload(r *http.Request, caller service.PluginActio
return issueToResponse(issue, prefix)
}
-// ListPluginComments — GET /api/v1/plugin/issues/{id}/comments
+// ListPluginComments — GET /v1/issues/{id}/comments
func (h *Handler) ListPluginComments(w http.ResponseWriter, r *http.Request) {
caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsRead)
if !ok {
@@ -401,7 +401,7 @@ type createPluginCommentRequest struct {
ParentID *string `json:"parent_id,omitempty"`
}
-// CreatePluginComment — POST /api/v1/plugin/issues/{id}/comments
+// CreatePluginComment — POST /v1/issues/{id}/comments
//
// The comment is authored BY THE USER and marked with the plugin that produced
// it, so the timeline can render "Jiayuan (via Hello Panel)".
@@ -551,7 +551,7 @@ func hasGrantedScope(scopes []string, want string) bool {
return false
}
-// ListPluginStorage — GET /api/v1/plugin/storage/{scope}
+// ListPluginStorage — GET /v1/storage/{scope}
func (h *Handler) ListPluginStorage(w http.ResponseWriter, r *http.Request) {
caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
@@ -569,7 +569,7 @@ func (h *Handler) ListPluginStorage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"keys": keys})
}
-// GetPluginStorage — GET /api/v1/plugin/storage/{scope}/{key}
+// GetPluginStorage — GET /v1/storage/{scope}/{key}
func (h *Handler) GetPluginStorage(w http.ResponseWriter, r *http.Request) {
caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
@@ -591,7 +591,7 @@ type putPluginStorageRequest struct {
Value string `json:"value"`
}
-// PutPluginStorage — PUT /api/v1/plugin/storage/{scope}/{key}
+// PutPluginStorage — PUT /v1/storage/{scope}/{key}
func (h *Handler) PutPluginStorage(w http.ResponseWriter, r *http.Request) {
caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
@@ -613,7 +613,7 @@ func (h *Handler) PutPluginStorage(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// DeletePluginStorage — DELETE /api/v1/plugin/storage/{scope}/{key}
+// DeletePluginStorage — DELETE /v1/storage/{scope}/{key}
func (h *Handler) DeletePluginStorage(w http.ResponseWriter, r *http.Request) {
caller, actor, ok := h.pluginCaller(w, r, "")
if !ok {
diff --git a/server/internal/handler/plugin_callback_test.go b/server/internal/handler/plugin_callback_test.go
index 6961f9fb70..4e82a2200c 100644
--- a/server/internal/handler/plugin_callback_test.go
+++ b/server/internal/handler/plugin_callback_test.go
@@ -77,7 +77,7 @@ func TestCallbackFromAUserTriggeredHookWritesAsTheUser(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
recorder := httptest.NewRecorder()
testHandler.CreatePluginComment(recorder, callbackRequest(token, http.MethodPost,
- "/api/v1/plugin/issues/"+issueID+"/comments",
+ "/v1/issues/"+issueID+"/comments",
map[string]any{"content": "posted by a manual hook"},
map[string]string{"id": issueID}))
if recorder.Code != http.StatusCreated {
@@ -108,7 +108,7 @@ func TestCallbackFromAnEventHookWritesAsThePlugin(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
recorder := httptest.NewRecorder()
testHandler.CreatePluginComment(recorder, callbackRequest(token, http.MethodPost,
- "/api/v1/plugin/issues/"+issueID+"/comments",
+ "/v1/issues/"+issueID+"/comments",
map[string]any{"content": "posted by an event hook"},
map[string]string{"id": issueID}))
if recorder.Code != http.StatusCreated {
@@ -137,7 +137,7 @@ func TestCallbackTokenServesTheWholeInvocation(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
first := httptest.NewRecorder()
testHandler.GetPluginIssue(first, callbackRequest(token, http.MethodGet,
- "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ "/v1/issues/"+issueID, nil, map[string]string{"id": issueID}))
if first.Code != http.StatusOK {
t.Fatalf("first use: status=%d body=%s", first.Code, first.Body.String())
}
@@ -145,7 +145,7 @@ func TestCallbackTokenServesTheWholeInvocation(t *testing.T) {
// The read-then-write shape every non-trivial handler has.
second := httptest.NewRecorder()
testHandler.CreatePluginComment(second, callbackRequest(token, http.MethodPost,
- "/api/v1/plugin/issues/"+issueID+"/comments",
+ "/v1/issues/"+issueID+"/comments",
map[string]any{"content": "and now a comment about what I read"},
map[string]string{"id": issueID}))
if second.Code != http.StatusCreated {
@@ -156,7 +156,7 @@ func TestCallbackTokenServesTheWholeInvocation(t *testing.T) {
testHandler.PluginService.Callbacks.Revoke(token)
third := httptest.NewRecorder()
testHandler.GetPluginIssue(third, callbackRequest(token, http.MethodGet,
- "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ "/v1/issues/"+issueID, nil, map[string]string{"id": issueID}))
if third.Code != http.StatusForbidden {
t.Fatalf("a revoked grant must be refused: status=%d body=%s", third.Code, third.Body.String())
}
@@ -174,7 +174,7 @@ func TestPluginActorCannotReachUserStorage(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
recorder := httptest.NewRecorder()
testHandler.PutPluginStorage(recorder, callbackRequest(token, http.MethodPut,
- "/api/v1/plugin/storage/user/pref",
+ "/v1/storage/user/pref",
map[string]any{"value": "x"},
map[string]string{"scope": "user", "key": "pref"}))
if recorder.Code != http.StatusForbidden {
@@ -193,7 +193,7 @@ func TestPluginContextOmitsTheUserForAPluginActor(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "plugin", ID: parseUUID(installationID)})
recorder := httptest.NewRecorder()
- testHandler.GetPluginContext(recorder, callbackRequest(token, http.MethodGet, "/api/v1/plugin/context", nil, nil))
+ testHandler.GetPluginContext(recorder, callbackRequest(token, http.MethodGet, "/v1/context", nil, nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
@@ -259,7 +259,7 @@ func TestCallbackTokenCannotReachAnotherIssue(t *testing.T) {
// The issue it was issued for: allowed.
ok := httptest.NewRecorder()
testHandler.GetPluginIssue(ok, callbackRequest(token, http.MethodGet,
- "/api/v1/plugin/issues/"+granted, nil, map[string]string{"id": granted}))
+ "/v1/issues/"+granted, nil, map[string]string{"id": granted}))
if ok.Code != http.StatusOK {
t.Fatalf("the granted issue must be reachable: status=%d body=%s", ok.Code, ok.Body.String())
}
@@ -267,14 +267,14 @@ func TestCallbackTokenCannotReachAnotherIssue(t *testing.T) {
// Any other issue in the same workspace: refused, on both read and write.
refusedRead := httptest.NewRecorder()
testHandler.GetPluginIssue(refusedRead, callbackRequest(token, http.MethodGet,
- "/api/v1/plugin/issues/"+other, nil, map[string]string{"id": other}))
+ "/v1/issues/"+other, nil, map[string]string{"id": other}))
if refusedRead.Code != http.StatusNotFound {
t.Fatalf("reading another issue must be refused: status=%d body=%s", refusedRead.Code, refusedRead.Body.String())
}
refusedWrite := httptest.NewRecorder()
testHandler.CreatePluginComment(refusedWrite, callbackRequest(token, http.MethodPost,
- "/api/v1/plugin/issues/"+other+"/comments",
+ "/v1/issues/"+other+"/comments",
map[string]any{"content": "should never land"},
map[string]string{"id": other}))
if refusedWrite.Code != http.StatusNotFound {
@@ -295,7 +295,7 @@ func TestCallbackTokenWithoutAnIssueIsNotNarrowed(t *testing.T) {
token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(testUserID)})
recorder := httptest.NewRecorder()
testHandler.GetPluginIssue(recorder, callbackRequest(token, http.MethodGet,
- "/api/v1/plugin/issues/"+issueID, nil, map[string]string{"id": issueID}))
+ "/v1/issues/"+issueID, nil, map[string]string{"id": issueID}))
if recorder.Code != http.StatusOK {
t.Fatalf("an unscoped grant must still reach the workspace: status=%d body=%s", recorder.Code, recorder.Body.String())
}
diff --git a/server/internal/handler/plugin_example_test.go b/server/internal/handler/plugin_example_test.go
index 377f6a8d0b..cccb7ae2b1 100644
--- a/server/internal/handler/plugin_example_test.go
+++ b/server/internal/handler/plugin_example_test.go
@@ -169,7 +169,7 @@ func installExamplePlugin(t *testing.T, servers exampleServers) string {
// without a deployment key the engine refuses to call out at all.
plugins.DeploymentKey = bytes.Repeat([]byte{3}, 32)
plugins.Callbacks = service.NewCallbackTokens()
- plugins.CallbackBaseURL = "https://multica.test/api/v1/plugin"
+ plugins.CallbackBaseURL = "https://plugin-api.multica.test/v1"
t.Cleanup(func() { *plugins = previous })
// Publishing is what validates the whole artifact: the manifest, the surface
diff --git a/server/internal/handler/plugin_hook.go b/server/internal/handler/plugin_hook.go
index 05e27668f1..0db1fbc19e 100644
--- a/server/internal/handler/plugin_hook.go
+++ b/server/internal/handler/plugin_hook.go
@@ -28,7 +28,7 @@ type invokePluginHookRequest struct {
Input json.RawMessage `json:"input,omitempty"`
}
-// InvokePluginHook — POST /api/v1/plugin/hooks/{key}
+// InvokePluginHook — POST /api/plugin-bridge/v1/hooks/{key}
func (h *Handler) InvokePluginHook(w http.ResponseWriter, r *http.Request) {
// No scope of its own: a hook is the plugin's own capability, and what it
// may do on the way back is bounded by the installation's scopes when the
diff --git a/server/internal/handler/plugin_hook_test.go b/server/internal/handler/plugin_hook_test.go
index 930e9f7730..2a78100c7e 100644
--- a/server/internal/handler/plugin_hook_test.go
+++ b/server/internal/handler/plugin_hook_test.go
@@ -68,7 +68,7 @@ func installHookPlugin(t *testing.T) string {
func invokeHookRequest(installationID, hookKey string, payload map[string]any) *http.Request {
body, _ := json.Marshal(payload)
- request := httptest.NewRequest(http.MethodPost, "/api/v1/plugin/hooks/"+hookKey, bytes.NewReader(body))
+ request := httptest.NewRequest(http.MethodPost, "/api/plugin-bridge/v1/hooks/"+hookKey, bytes.NewReader(body))
request.Header.Set("X-User-ID", testUserID)
request.Header.Set("Content-Type", "application/json")
request.Header.Set(pluginInstallationHeader, installationID)
diff --git a/server/internal/middleware/plugin_auth.go b/server/internal/middleware/plugin_auth.go
index 54f570acb5..9062d26306 100644
--- a/server/internal/middleware/plugin_auth.go
+++ b/server/internal/middleware/plugin_auth.go
@@ -5,33 +5,20 @@ import (
"strings"
)
-// PluginAuth lets the Action API be reached two ways without weakening either.
+// PluginBearerOnly keeps the public Action API on a machine-credential trust
+// boundary. Browser sessions use the separate, session-authenticated bridge
+// route; the public /v1 contract accepts only installation and callback tokens.
//
-// The original way is the only one a SURFACE has: no credential at all. The
-// iframe posts a message to the host page, the host re-issues the call on the
-// signed-in user's session, and this middleware sends it through the ordinary
-// Auth chain like any other request.
-//
-// Hooks add a second way. A plugin's own server has no session and never will,
-// so when it presents a plugin bearer token this middleware steps aside and
-// lets the handler resolve the token itself — which it must, because only the
-// handler knows which installation and which scopes that token stands for.
-//
-// Stepping aside is not the same as skipping authentication: every Action API
-// handler starts by resolving a caller, and a request that arrives with neither
-// a session nor a valid token fails there. What this avoids is the session
-// chain rejecting a token-bearing request before the handler can look at it.
-func PluginAuth(sessionAuth func(http.Handler) http.Handler) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- sessionProtected := sessionAuth(next)
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if IsPluginBearerToken(BearerToken(r)) {
- next.ServeHTTP(w, r)
- return
- }
- sessionProtected.ServeHTTP(w, r)
- })
- }
+// Prefix matching is only routing. The Action handler still resolves the token
+// against its store and rejects an invalid or expired credential.
+func PluginBearerOnly(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !IsPluginBearerToken(BearerToken(r)) {
+ writeError(w, http.StatusUnauthorized, "plugin bearer token required")
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
}
// BearerToken pulls the raw credential out of an Authorization header.
diff --git a/server/internal/middleware/plugin_auth_test.go b/server/internal/middleware/plugin_auth_test.go
new file mode 100644
index 0000000000..306389eeb2
--- /dev/null
+++ b/server/internal/middleware/plugin_auth_test.go
@@ -0,0 +1,66 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestPluginBearerOnlyRejectsNonPluginCredentials(t *testing.T) {
+ tests := []struct {
+ name string
+ authorization string
+ }{
+ {name: "missing"},
+ {name: "session jwt", authorization: "Bearer eyJhbGciOiJIUzI1NiJ9.payload.signature"},
+ {name: "personal access token", authorization: "Bearer mul_personal"},
+ {name: "wrong scheme", authorization: "Basic mpi_installation"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ called := false
+ next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ called = true
+ })
+ req := httptest.NewRequest(http.MethodGet, "/v1/context", nil)
+ if tt.authorization != "" {
+ req.Header.Set("Authorization", tt.authorization)
+ }
+ response := httptest.NewRecorder()
+
+ PluginBearerOnly(next).ServeHTTP(response, req)
+
+ if response.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", response.Code, http.StatusUnauthorized)
+ }
+ if called {
+ t.Fatal("non-plugin credential reached the Action API handler")
+ }
+ })
+ }
+}
+
+func TestPluginBearerOnlyPassesPluginTokenKindsToTheHandler(t *testing.T) {
+ for _, token := range []string{"mpi_installation", "mpc_callback"} {
+ t.Run(token[:3], func(t *testing.T) {
+ called := false
+ next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusNoContent)
+ })
+ req := httptest.NewRequest(http.MethodGet, "/v1/context", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ response := httptest.NewRecorder()
+
+ PluginBearerOnly(next).ServeHTTP(response, req)
+
+ if response.Code != http.StatusNoContent {
+ t.Fatalf("status = %d, want %d", response.Code, http.StatusNoContent)
+ }
+ if !called {
+ t.Fatal("plugin credential did not reach the Action API handler")
+ }
+ })
+ }
+}
diff --git a/server/internal/service/plugin_hook_transport_test.go b/server/internal/service/plugin_hook_transport_test.go
index 9fe050e7c1..4342677ba5 100644
--- a/server/internal/service/plugin_hook_transport_test.go
+++ b/server/internal/service/plugin_hook_transport_test.go
@@ -65,7 +65,7 @@ func hookTestService(t *testing.T, harness *hookTestServer) *PluginService {
service.DevOrigins = []string{harness.server.URL}
service.HookClient = harness.server.Client()
service.Callbacks = NewCallbackTokens()
- service.CallbackBaseURL = "https://multica.test/api/v1/plugin"
+ service.CallbackBaseURL = "https://plugin-api.multica.test/v1"
return service
}
@@ -244,7 +244,7 @@ func TestHookCarriesAnInvocationScopedCallbackToken(t *testing.T) {
if body.CallbackToken == "" {
t.Fatal("the handler needs a callback token to answer with")
}
- if body.CallbackURL != "https://multica.test/api/v1/plugin" {
+ if body.CallbackURL != "https://plugin-api.multica.test/v1" {
t.Fatalf("unexpected callback url %q", body.CallbackURL)
}
if body.Actor.Type != "member" {