Files
PaperClipAI/server/src/__tests__/better-auth.test.ts
T
DottaandPaperclip cfa5e0704e feat(mcp) [split 3/8]: add tool access policy core (#9558)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Governed MCP access spans contracts, runtime enforcement, adapters,
UI surfaces, and operator verification
> - The parity reference PR #9534 is too large for effective automated
or human review
> - The feature therefore needs a linear stack whose individual diffs
stay below the 100-file review limit
> - This pull request is split 3/8 and focuses on tool-access policy and
authorization core
> - The benefit is a standalone, testable review boundary while
preserving byte-for-byte parity at the top of the stack

## Linked Issues or Issue Description

- Related parity reference: #9534
- Problem: Authorization, OAuth binding, secret projection, content
guards, and policy evaluation need a security-reviewable server
boundary.
- Proposed solution: Adds tool-access services/routes/tests plus the
runtime service dependencies directly imported by the core, without
registering the routes in the application.
- Alternatives considered: keeping #9534 as one 403-file review, or
rewriting the feature to manufacture seams; both were rejected in favor
of path extraction plus compile-driven boundary moves.
- Roadmap alignment: this advances the existing governed MCP/tool-access
work already represented by #9534; it does not introduce a separate
roadmap initiative.
- Stack position: base branch is `pap10341-split/02-schema-shared`.
- Merge policy: merge bottom-up, in order, only after the complete
eight-PR stack has been reviewed and the top-of-stack parity gate
remains empty.
- Requested review: SecurityEngineer for authz, OAuth, secrets, and
content guards; Greptile on every PR.

## What Changed

- Adds tool-access services/routes/tests plus the runtime service
dependencies directly imported by the core, without registering the
routes in the application.
- Keeps this PR below 100 changed files and independently typecheckable.
- Preserves the final tree from #9534 when combined with the other seven
stack levels.

## Verification

- `pnpm typecheck`
- Focused server Vitest run — 4 files, 143 tests passed

## Risks

- Authorization bugs could permit cross-company or over-broad tool
access; the PR remains inert until PR 4 wiring and requires dedicated
security review.
- Stack risk: merging out of order can expose incomplete layers;
mitigate by following the documented bottom-up merge policy.
- Parity risk: later edits to an intermediate branch can drift from
#9534; mitigate by re-running the empty top-of-stack diff before merge.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, exact model ID `gpt-5.4`; runtime-managed context
window; medium reasoning with repository, shell, Git, GitHub CLI, and
code-execution tools enabled.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] Internal references are omitted except the execution-plan link
explicitly required for this coordinated split stack
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge


## Stack Coordination

- Internal execution plan:
[PAP-13874](/PAP/issues/PAP-13874#document-plan)
- Parity reference: #9534
- Stack: #9556 → #9557 → #9558 → #9559 → #9560 → #9561 → #9562 → #9563
- Merge bottom-up only after full-stack review and an empty parity diff
at #9563.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-07-14 14:22:39 -05:00

216 lines
7.8 KiB
TypeScript

import { afterEach, describe, expect, it } from "vitest";
import type { BetterAuthOptions } from "better-auth";
import { getCookies } from "better-auth/cookies";
import {
buildBetterAuthAdvancedOptions,
buildBetterAuthRateLimitOptions,
deriveAuthCookiePrefix,
deriveAuthTrustedOrigins,
shouldDisableSecureAuthCookies,
} from "../auth/better-auth.js";
const ORIGINAL_INSTANCE_ID = process.env.PAPERCLIP_INSTANCE_ID;
const ORIGINAL_PUBLIC_URL = process.env.PAPERCLIP_PUBLIC_URL;
afterEach(() => {
if (ORIGINAL_INSTANCE_ID === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
else process.env.PAPERCLIP_INSTANCE_ID = ORIGINAL_INSTANCE_ID;
if (ORIGINAL_PUBLIC_URL === undefined) delete process.env.PAPERCLIP_PUBLIC_URL;
else process.env.PAPERCLIP_PUBLIC_URL = ORIGINAL_PUBLIC_URL;
});
describe("Better Auth cookie scoping", () => {
it("derives an instance-scoped cookie prefix", () => {
expect(deriveAuthCookiePrefix("default")).toBe("paperclip-default");
expect(deriveAuthCookiePrefix("PAP-1601-worktree")).toBe("paperclip-PAP-1601-worktree");
});
it("uses PAPERCLIP_INSTANCE_ID for the Better Auth cookie prefix", () => {
process.env.PAPERCLIP_INSTANCE_ID = "sat-worktree";
const advanced = buildBetterAuthAdvancedOptions({ disableSecureCookies: false });
expect(advanced).toEqual({
cookiePrefix: "paperclip-sat-worktree",
});
expect(getCookies({ advanced } as BetterAuthOptions).sessionToken.name).toMatch(
/paperclip-sat-worktree\.session_token$/,
);
});
it("keeps local http auth cookies non-secure while preserving the scoped prefix", () => {
process.env.PAPERCLIP_INSTANCE_ID = "pap-worktree";
expect(buildBetterAuthAdvancedOptions({ disableSecureCookies: true })).toEqual({
cookiePrefix: "paperclip-pap-worktree",
useSecureCookies: false,
});
expect(getCookies({
advanced: buildBetterAuthAdvancedOptions({ disableSecureCookies: true }),
} as BetterAuthOptions).sessionToken.name).toBe("paperclip-pap-worktree.session_token");
});
it("enables Better Auth rate limiting for authenticated private instances by default", () => {
expect(buildBetterAuthRateLimitOptions({
deploymentMode: "authenticated",
deploymentExposure: "private",
})).toEqual({ enabled: true });
});
it("keeps Better Auth rate limiting enabled for authenticated public instances", () => {
expect(buildBetterAuthRateLimitOptions({
deploymentMode: "authenticated",
deploymentExposure: "public",
})).toEqual({ enabled: true });
});
it("allows an explicit Better Auth rate-limit override", () => {
expect(buildBetterAuthRateLimitOptions({
deploymentMode: "authenticated",
deploymentExposure: "private",
override: "true",
})).toEqual({ enabled: true });
expect(buildBetterAuthRateLimitOptions({
deploymentMode: "authenticated",
deploymentExposure: "public",
override: "false",
})).toEqual({ enabled: false });
});
it("disables secure cookies for authenticated private auto-origin dev servers", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: undefined,
})).toBe(true);
});
it("keeps secure cookies for authenticated public auto-origin servers", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "public",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: undefined,
})).toBe(false);
});
it("uses an explicit public URL when deciding whether secure cookies are required", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: "https://paperclip.example.test",
})).toBe(false);
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "public",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "http://paperclip.local.test:3100",
publicUrl: undefined,
})).toBe(true);
});
it("disables secure cookies when no canonical public auth URL is configured", () => {
delete process.env.PAPERCLIP_PUBLIC_URL;
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(true);
});
it("derives secure cookie behavior from the configured public auth URL", () => {
delete process.env.PAPERCLIP_PUBLIC_URL;
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "http://paperclip-dev:46259",
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(true);
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "https://paperclip.example.test",
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(false);
});
it("uses the caller-resolved public URL for cookie security", () => {
process.env.PAPERCLIP_PUBLIC_URL = "https://ignored.example.test";
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "https://paperclip.example.test",
publicUrl: "http://paperclip-dev:46259",
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(true);
});
it("disables secure cookies for private authenticated auto mode without a public URL", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
})).toBe(true);
});
it("disables secure cookies for explicit HTTP public URLs", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "http://board.example.test:3101",
})).toBe(true);
});
it("keeps secure cookies for explicit HTTPS public URLs", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "public",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "https://board.example.test",
})).toBe(false);
});
it("adds hostname port variants for authenticated mode on non-default ports", () => {
const trustedOrigins = deriveAuthTrustedOrigins({
deploymentMode: "authenticated",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
allowedHostnames: ["Board.Example.Test"],
port: 3101,
} as Parameters<typeof deriveAuthTrustedOrigins>[0]);
expect(trustedOrigins).toEqual(expect.arrayContaining([
"https://board.example.test",
"http://board.example.test",
"https://board.example.test:3101",
"http://board.example.test:3101",
]));
});
it("prefers an explicit resolved listen port over the configured port", () => {
const trustedOrigins = deriveAuthTrustedOrigins({
deploymentMode: "authenticated",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
allowedHostnames: ["board.example.test"],
port: 3100,
} as Parameters<typeof deriveAuthTrustedOrigins>[0], { listenPort: 3101 });
expect(trustedOrigins).toEqual(expect.arrayContaining([
"https://board.example.test:3101",
"http://board.example.test:3101",
]));
expect(trustedOrigins).not.toContain("https://board.example.test:3100");
expect(trustedOrigins).not.toContain("http://board.example.test:3100");
});
});