Files
PaperClipAI/ui/src/App.test.tsx
T
DottaandPaperclip d9d2147171 fix(auth): keep Cloud tenants on the Cloud sign-in flow (#14407)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Cloud owns human identity and passes a verified identity to each
tenant.
> - The tenant can report no session while the Cloud session is still
valid.
> - The access gate and direct `/auth` route then show the instance
password form.
> - This pull request sends those users through the configured Cloud
entry endpoint.
> - Cloud can renew the tenant session or show its login page, then
return to the original task.

## Linked Issues or Issue Description

**What happened?**

A Cloud tenant can display the self-hosted email/password form after an
instance session check returns no session. This gives Cloud users the
wrong login method.

**Expected behavior**

An active Cloud session renews tenant access automatically. A signed-out
user signs in through Cloud. Staging and production use their own
configured Cloud origins. Self-hosted instances keep their instance
login form.

**Steps to reproduce**

1. Open a Cloud tenant task or an `/auth?next=...` link.
2. Keep the Cloud session active but make the instance session check
return 401.
3. Observe the instance password form instead of Cloud session recovery.

**Deployment mode**

Cloud-managed authenticated instances. No database or server API
changes.

Searched related authentication PRs. Native self-hosted OIDC support in
#10411 is a separate feature; this change uses the existing Cloud entry
contract.

## What Changed

- Wait for deployment metadata before showing an instance login form.
- Use the health response's Cloud origin and stack slug for session
recovery.
- Preserve the tenant path, query, and fragment. Reject external and
recursive login return targets.
- Limit automatic recovery per tab. Show a manual Cloud retry after
failed recovery. Show service failures as errors.
- Keep self-hosted login and local trusted access. Add focused tests,
browser regressions, deployment documentation, and an unavailable-state
design example.

## Verification

- `pnpm -r typecheck` and `pnpm build` passed.
- UI typecheck and `pnpm check:token-gates` passed after the final UI
edits.
- All UI tests passed: 639 files, 6,777 tests.
- 63 focused Vitest tests passed across Auth, CloudAccessGate, Cloud
links, and recovery coordination.
- `pnpm exec playwright test --config tests/e2e/playwright.config.ts
tests/e2e/cloud-auth.spec.ts`: 5 passed. The tests use the real tenant
UI and database with a simulated Cloud HTTP endpoint. They cover both
Cloud origins, direct auth/task links, no password-form flash, preserved
URLs, reload, and self-hosted login.
- Hands-on browser test used the real Cloud gateway and a fresh tenant
build with disposable local data. Active Cloud session plus a forced
missing instance session returned to the task. An expired tenant cookie
also renewed automatically and returned to the task. Removing both
sessions reached the real Cloud email/social login UI. Persistent
failure stopped at the retry screen; retry succeeded after removing the
injected fault. The fixture used a loopback transport adapter and a
simulated signed-out OIDC issuer. No production session or deployment
was changed.
- The default local browser startup hit the host's embedded PostgreSQL
resource limit. The passing run used a separate disposable database on
the test PostgreSQL process.
- The full local `pnpm test:run` sweep was stopped after about 31
minutes once CI completed the full suite. It had reported 33 failures in
the unchanged runner API unit/integration files; both files pass in
isolation (1,749 + 28 tests). The local sweep did not reach the later
workspace/serialized groups. CI completed all of those groups
successfully.
- Greptile reviewed commit `d603fd4e39455de44da9dae81b72197096c0e1e8` at
5/5 with its only thread resolved. All CI gates are green on this
commit, including all general/serialized server groups, workspace tests,
Runner checks, typecheck, build, and all eight browser shards
([run](https://github.com/paperclipai/paperclip/actions/runs/36446230697)).

## Risks

- Recovery depends on valid Cloud origin and stack metadata. Incomplete
metadata shows an unavailable message instead of a password form.
- Browsers with session storage disabled use the manual Cloud link,
since automatic retries cannot be bounded across documents.
- The external identity provider's email/social login was not completed
in this local test. Existing Cloud authentication owns that flow.
- No migration, credential format, membership rule, or production
deployment changes.

## Model Used

OpenAI GPT-6 through Codex. The exact served variant and context-window
limit are not exposed in this session. Used reasoning, repository tools,
code execution, and browser testing.

## 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
#` OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-28 13:45:27 -05:00

363 lines
15 KiB
TypeScript

// @vitest-environment jsdom
import type { ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CloudAccessGate } from "./components/CloudAccessGate";
import { queryKeys } from "./lib/queryKeys";
import appSource from "./App.tsx?raw";
const mockHealthApi = vi.hoisted(() => ({
get: vi.fn(),
}));
const mockAuthApi = vi.hoisted(() => ({
getSession: vi.fn(),
}));
const mockAccessApi = vi.hoisted(() => ({
getCurrentBoardAccess: vi.fn(),
claimBootstrapAdmin: vi.fn(),
}));
const beginCloudSignInMock = vi.hoisted(() => vi.fn());
vi.mock("@/lib/cloud-sign-in", () => ({
beginCloudSignIn: (url: string) => beginCloudSignInMock(url),
clearCloudSignInAttempt: vi.fn(),
}));
vi.mock("./api/health", () => ({
healthApi: mockHealthApi,
}));
vi.mock("./api/auth", () => ({
authApi: mockAuthApi,
}));
vi.mock("./api/access", () => ({
accessApi: mockAccessApi,
}));
vi.mock("@/lib/router", () => ({
Link: ({ to, children }: { to: string; children?: ReactNode }) => <a href={to}>{children}</a>,
Navigate: ({ to }: { to: string }) => <div>Navigate:{to}</div>,
Outlet: () => <div>Outlet content</div>,
Route: ({ children }: { children?: ReactNode }) => <>{children}</>,
Routes: ({ children }: { children?: ReactNode }) => <>{children}</>,
useLocation: () => ({ pathname: "/instance/settings/general", search: "", hash: "" }),
useParams: () => ({}),
}));
/**
* Waits on the condition, not on a fixed number of turns. A hand-rolled retry
* loop is ample on an idle machine and not when the suite runs many workers in
* parallel: it gives up after N turns and reports a failure on behaviour that
* works. `vi.waitFor` retries against a time budget, so a loaded worker gets
* more turns instead.
*
* Same replacement as #11499 and #11521, which fixed the shorter-budget
* instances of this in the routing tests.
*/
async function waitForText(container: HTMLElement, text: string) {
await vi.waitFor(() => expect(container.textContent).toContain(text));
}
function renderGate(container: HTMLElement, allowMembershipRequest = false, client?: QueryClient) {
const root = createRoot(container);
const queryClient = client ?? new QueryClient({
defaultOptions: { queries: { retry: false } },
});
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
<CloudAccessGate allowMembershipRequest={allowMembershipRequest} />
</QueryClientProvider>,
);
});
return root;
}
function unmountRoot(root: ReturnType<typeof createRoot>) {
flushSync(() => {
root.unmount();
});
}
describe("CloudAccessGate", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
bootstrapStatus: "ready",
});
});
afterEach(() => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("renews a missing Cloud instance session without opening local auth", async () => {
mockHealthApi.get.mockResolvedValue({ deploymentMode: "authenticated", cloud: { managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: "https://my-staging.paperclip.app", stackSlug: "team" } });
mockAuthApi.getSession.mockResolvedValue(null);
beginCloudSignInMock.mockReturnValue(true);
const root = renderGate(container);
await vi.waitFor(() => expect(beginCloudSignInMock).toHaveBeenCalledTimes(1));
expect(beginCloudSignInMock).toHaveBeenCalledWith("https://my-staging.paperclip.app/v1/stacks/team/entry-redirect?returnTo=%2Finstance%2Fsettings%2Fgeneral");
expect(container.textContent).not.toContain("Navigate:/auth");
expect(container.textContent).not.toContain("Outlet content");
unmountRoot(root);
});
it("does not mistake a session service failure for a signed-out user", async () => {
mockAuthApi.getSession.mockRejectedValue(new Error("Session service unavailable"));
const root = renderGate(container);
await waitForText(container, "Session service unavailable");
expect(container.textContent).not.toContain("Navigate:/auth");
expect(beginCloudSignInMock).not.toHaveBeenCalled();
unmountRoot(root);
});
it.each([undefined, { managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: "https://my.paperclip.app", stackSlug: "team" }])(
"does not require a session in local trusted mode, including with Cloud metadata %j", async (cloud) => {
mockHealthApi.get.mockResolvedValue({ deploymentMode: "local_trusted", cloud });
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await client.fetchQuery({
queryKey: queryKeys.auth.session,
queryFn: () => Promise.reject(new Error("Session service unavailable")),
}).catch(() => {});
const root = renderGate(container, false, client);
await waitForText(container, "Outlet content");
expect(beginCloudSignInMock).not.toHaveBeenCalled();
unmountRoot(root);
});
it("shows a no-access message for signed-in users without org access", async () => {
mockAuthApi.getSession.mockResolvedValue({
session: { id: "session-1", userId: "user-1" },
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
});
mockAccessApi.getCurrentBoardAccess.mockResolvedValue({
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
userId: "user-1",
isInstanceAdmin: false,
companyIds: [],
source: "session",
keyId: null,
});
const root = renderGate(container);
await waitForText(container, "No organization access");
expect(container.textContent).toContain("No organization access");
expect(container.textContent).not.toContain("Outlet content");
unmountRoot(root);
});
it("admits signed-in nonmembers only for the private invitation landing page", async () => {
mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
mockAccessApi.getCurrentBoardAccess.mockResolvedValue({ isInstanceAdmin: false, companyIds: [] });
const root = renderGate(container, true);
await waitForText(container, "Outlet content");
unmountRoot(root);
});
it("still requires sign-in for the invitation landing page", async () => {
mockAuthApi.getSession.mockResolvedValue(null);
const root = renderGate(container, true);
await waitForText(container, "Navigate:/auth?next=");
expect(container.textContent).not.toContain("Outlet content");
unmountRoot(root);
});
it("still blocks invitation pages while cloud bootstrap is pending", async () => {
mockHealthApi.get.mockResolvedValue({ deploymentMode: "authenticated", deploymentExposure: "public", bootstrapStatus: "bootstrap_pending" });
mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
const root = renderGate(container, true);
await waitForText(container, "This Paperclip is waiting on its first admin");
expect(container.textContent).not.toContain("Outlet content");
unmountRoot(root);
});
it("keeps invitation pages closed when cloud access checks fail", async () => {
mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
mockAccessApi.getCurrentBoardAccess.mockRejectedValueOnce(new Error("Access check unavailable"));
const root = renderGate(container, true);
await waitForText(container, "Access check unavailable");
expect(container.textContent).not.toContain("Outlet content");
unmountRoot(root);
});
it("allows authenticated users with company access through to the board", async () => {
mockAuthApi.getSession.mockResolvedValue({
session: { id: "session-1", userId: "user-1" },
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
});
mockAccessApi.getCurrentBoardAccess.mockResolvedValue({
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
userId: "user-1",
isInstanceAdmin: false,
companyIds: ["company-1"],
source: "session",
keyId: null,
});
const root = renderGate(container);
await waitForText(container, "Outlet content");
expect(container.textContent).toContain("Outlet content");
expect(container.textContent).not.toContain("No organization access");
unmountRoot(root);
});
it("shows browser sign-in setup for signed-out private bootstrap-pending instances", async () => {
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
bootstrapStatus: "bootstrap_pending",
bootstrapInviteActive: false,
});
mockAuthApi.getSession.mockResolvedValue(null);
const root = renderGate(container);
await waitForText(container, "Finish setting up this Paperclip");
expect(container.textContent).toContain("Finish setting up this Paperclip");
expect(container.textContent).toContain("Sign in / Create account");
expect(container.textContent).toContain("npx paperclipai auth bootstrap-ceo");
expect(mockAccessApi.getCurrentBoardAccess).not.toHaveBeenCalled();
unmountRoot(root);
});
it("shows the claim action for signed-in private bootstrap-pending instances", async () => {
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
bootstrapStatus: "bootstrap_pending",
bootstrapInviteActive: false,
});
mockAuthApi.getSession.mockResolvedValue({
session: { id: "session-1", userId: "user-1" },
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
});
mockAccessApi.claimBootstrapAdmin.mockResolvedValue({ claimed: true, userId: "user-1" });
const root = renderGate(container);
await waitForText(container, "Claim this instance");
expect(container.textContent).toContain("Claim this instance");
expect(container.textContent).toContain("Signed in as user@example.com");
expect(mockAccessApi.getCurrentBoardAccess).not.toHaveBeenCalled();
const button = Array.from(container.querySelectorAll("button")).find((candidate) =>
candidate.textContent?.includes("Claim this instance"),
);
expect(button).toBeTruthy();
flushSync(() => {
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await waitForText(container, "You're the instance admin");
expect(mockAccessApi.claimBootstrapAdmin).toHaveBeenCalledTimes(1);
expect(container.textContent).toContain("You're the instance admin");
expect(container.textContent).toContain("Continue to dashboard");
unmountRoot(root);
});
it("keeps public bootstrap-pending instances invite-only", async () => {
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
bootstrapStatus: "bootstrap_pending",
bootstrapInviteActive: true,
});
mockAuthApi.getSession.mockResolvedValue({
session: { id: "session-1", userId: "user-1" },
user: { id: "user-1", email: "user@example.com", name: "User", image: null },
});
const root = renderGate(container);
await waitForText(container, "This Paperclip is waiting on its first admin");
expect(container.textContent).toContain("This Paperclip is waiting on its first admin");
expect(container.textContent).toContain("invite-only mode");
expect(container.textContent).not.toContain("Claim this instance");
expect(container.textContent).not.toContain("Sign in / Create account");
expect(mockAccessApi.claimBootstrapAdmin).not.toHaveBeenCalled();
unmountRoot(root);
});
});
describe("Skill Studio routes", () => {
it("registers create mode before the skillId route in prefixed and unprefixed routing", () => {
const createRoute = 'path="skills/studio/new"';
const detailRoute = 'path="skills/studio/:skillId"';
const createIndexes = [...appSource.matchAll(new RegExp(createRoute, "g"))].map((match) => match.index ?? -1);
const detailIndexes = [...appSource.matchAll(new RegExp(detailRoute, "g"))].map((match) => match.index ?? -1);
expect(createIndexes).toHaveLength(2);
expect(detailIndexes).toHaveLength(2);
expect(createIndexes[0]).toBeLessThan(detailIndexes[0]!);
expect(createIndexes[1]).toBeLessThan(detailIndexes[1]!);
});
});
describe("Apps routes", () => {
it("uses one connector landing page and redirects retired browse, connections, and audit URLs", () => {
expect(appSource).toContain('<Route path="apps" element={<Browse />} />');
expect(appSource).toContain('<Route path="apps/browse" element={<Navigate to="/apps" replace />} />');
expect(appSource).toContain('<Route path="apps/connections" element={<Navigate to="/apps" replace />} />');
expect(appSource).toContain('<Route path="apps/advanced/audit" element={<Navigate to="/apps" replace />} />');
expect(appSource).toContain('<Route path="apps/advanced/run-your-own" element={<Navigate to="/apps" replace />} />');
expect(appSource).not.toContain('import { Connections }');
expect(appSource).toContain('<Route path="apps/byo" element={<AppsConnect byoOnly />} />');
expect(appSource).toContain('path="apps/vercel-connect"');
expect(appSource).toContain('<AppsConnectEntryRoute credentialSource="vercel_connect" />');
expect(appSource).toContain('<AppsConnect credentialSource={credentialSource} />');
expect(appSource).toContain('<Route path="apps/connect/:appKey" element={<Navigate to="/apps" replace />} />');
expect(appSource).toContain('<Route path="apps/connect/:appKey/:stage" element={<Navigate to="/apps" replace />} />');
expect(appSource).toContain('<Route path="apps/advanced/gateways" element={<GatewaysList />} />');
});
it("redirects legacy Rules and Health links to the remaining developer surfaces", () => {
expect(appSource).toContain('if (tab === "runtime" || tab === "audit") return "/apps";');
expect(appSource).toContain('if (tab === "policies") return "/apps/advanced/profiles";');
});
});
describe("Retired settings routes", () => {
it("redirects the removed heartbeats page to the settings root instead of dropping the route", () => {
expect(appSource).toContain(
'<Route path="company/settings/instance/heartbeats" element={<Navigate to="/company/settings" replace />} />',
);
expect(appSource).not.toContain("<InstanceSettings");
expect(appSource).not.toContain('"./pages/InstanceSettings"');
});
});
describe("Decisions routes", () => {
it("does not register decision-training views", () => {
expect(appSource).not.toContain('path="decisions/training"');
expect(appSource).not.toContain('path="decisions/training/:id"');
expect(appSource).not.toContain('path="training"');
expect(appSource).not.toContain('path="training/:id"');
});
});