Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/ai/src/mcp/lib/resolve-tenant.oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ describe("an MCP OAuth token, resolved by the AI worker", () => {
}).pipe(Effect.provide(makeLayer(db)))
})

it.effect("treats a request with cookies and no bearer as carrying no credential", () => {
const db = createTestDb(createdDbs)
return Effect.gen(function* () {
const failure = yield* resolveMcpTenantContext(
new Request(resource, { headers: { cookie: "__session=anything" } }),
).pipe(Effect.flip)
expect(failure._tag).toBe("@maple/mcp/errors/McpAuthMissingError")
}).pipe(Effect.provide(makeLayer(db)))
})

it.effect("is refused for a resource it was not bound to", () => {
const db = createTestDb(createdDbs)
return Effect.gen(function* () {
Expand Down
4 changes: 2 additions & 2 deletions apps/ai/src/mcp/lib/resolve-tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ export const describeMalformedBearer = (token: string | undefined): string | und
*/
export const mcpResourceUrl = (apiBaseUrl: string) => `${Str.replace(/\/+$/, "")(apiBaseUrl)}/mcp`

/** A request with neither an `Authorization` header nor a cookie sent nothing a session reads. */
const carriesCredential = (headers: Headers): boolean => headers.has("authorization") || headers.has("cookie")
/** A request without an `Authorization` header sent nothing a session reads. */
const carriesCredential = (headers: Headers): boolean => headers.has("authorization")

/**
* The session resolver's failures as the MCP ones. A provider outage is retryable (503), and a
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/api-proxy-forward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ const forwardOverBinding = (
// Copying the request copies the browser's `Host: app.…`, and a service binding passes it
// through as-is. The API builds OAuth redirect URIs from Host, so it must name the API.
forwarded.headers.set("host", target.host)
// The app authenticates with a bearer. The page's cookies are not the API's to read.
forwarded.headers.delete("cookie")
// @effect-diagnostics-next-line preferEffectRecord:off -- not a record type; Rec.toEntries would need a cast
Arr.forEach(Object.entries(HttpTraceContext.toHeaders(client)), ([name, value]) =>
forwarded.headers.set(name, value),
Expand Down
12 changes: 12 additions & 0 deletions apps/web/src/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ describe("handleRequest API proxy", () => {
expect(await request?.text()).toBe("hello")
})

it("keeps the page's cookies out of the forwarded request", async () => {
const { env, forwarded } = recordingEnv()
await handleRequest(
new Request("https://app.maple.test/_api/v2/traces", {
headers: { authorization: "Bearer t", cookie: "__session=s; theme=dark" },
}),
env,
)
expect(forwarded[0]?.headers.get("cookie")).toBeNull()
expect(forwarded[0]?.headers.get("authorization")).toBe("Bearer t")
})

it("sends the API's host, not the app's, so OAuth callbacks stay on the API", async () => {
const { env, forwarded } = recordingEnv()
await handleRequest(
Expand Down
38 changes: 38 additions & 0 deletions packages/auth/src/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,44 @@ describe("makeResolveTenant", () => {
}),
)

it.effect("signs a request in by its bearer, never by a session cookie", () =>
Effect.gen(function* () {
// Stands in for the provider, which accepts either credential it is shown.
const resolveTenant = makeResolveTenant(
{
...baseEnv,
MAPLE_AUTH_MODE: "clerk",
CLERK_SECRET_KEY: Option.some(Redacted.make("sk_test_123")),
CLERK_JWT_KEY: Option.some(Redacted.make("jwt_test_123")),
},
async (request) => {
const shown = request.headers.has("authorization") || request.headers.has("cookie")
return {
isAuthenticated: shown,
message: shown ? null : "No credential",
toAuth: () => ({
isAuthenticated: true,
tokenType: "session_token",
userId: "user_123",
orgId: "org_123",
orgRole: "org:admin",
}),
}
},
)

assertRejected(
yield* Effect.exit(resolveTenant({ cookie: "__session=test-token" })),
"No credential",
)
const tenant = yield* resolveTenant({
Authorization: "Bearer test-token",
cookie: "__session=other-token",
})
assert.strictEqual(tenant.userId, asUserId("user_123"))
}),
)

it.effect("rejects invalid or expired Clerk tokens", () =>
Effect.gen(function* () {
const resolveTenant = makeResolveTenant(
Expand Down
6 changes: 5 additions & 1 deletion packages/auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,15 @@ const getBearerToken = (headers: HeaderRecord): string | undefined => {
return token
}

/**
* The bearer and nothing else. A cookie the browser attaches on its own is never a credential
* here, so only a caller that can read the session token can act with it.
*/
const toHeaders = (headers: HeaderRecord): Headers => {
const requestHeaders = new Headers()

for (const [name, value] of Rec.toEntries(headers)) {
if (value !== undefined) {
if (value !== undefined && Str.toLowerCase(name) === "authorization") {
Comment thread
Makisuo marked this conversation as resolved.
Resolved
requestHeaders.set(name, value)
}
}
Expand Down
Loading