mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-13 13:38:01 +02:00
## 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>
313 lines
11 KiB
TypeScript
313 lines
11 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { flushSync } from "react-dom";
|
|
import { createRoot } from "react-dom/client";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import { AuthPage } from "./Auth";
|
|
|
|
const getSessionMock = vi.hoisted(() => vi.fn());
|
|
const signInEmailMock = vi.hoisted(() => vi.fn());
|
|
const signUpEmailMock = vi.hoisted(() => vi.fn());
|
|
const healthMock = vi.hoisted(() => vi.fn());
|
|
const beginCloudSignInMock = vi.hoisted(() => vi.fn());
|
|
|
|
vi.mock("../api/health", () => ({ healthApi: { get: () => healthMock() } }));
|
|
vi.mock("@/lib/cloud-sign-in", () => ({
|
|
beginCloudSignIn: (url: string) => beginCloudSignInMock(url),
|
|
clearCloudSignInAttempt: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../api/auth", () => ({
|
|
authApi: {
|
|
getSession: () => getSessionMock(),
|
|
signInEmail: (input: unknown) => signInEmailMock(input),
|
|
signUpEmail: (input: unknown) => signUpEmailMock(input),
|
|
},
|
|
}));
|
|
|
|
// The ASCII art animation drives a canvas/requestAnimationFrame loop that adds
|
|
// nothing to these assertions, so stub it out.
|
|
vi.mock("@/components/AsciiArtAnimation", () => ({
|
|
AsciiArtAnimation: () => null,
|
|
}));
|
|
|
|
// The auth page renders a ThemeToggle, which reads ThemeContext. The provider
|
|
// lives in main.tsx (above the router), so mock the hook here the same way
|
|
// SidebarAccountMenu.test.tsx does.
|
|
vi.mock("../context/ThemeContext", () => ({
|
|
useTheme: () => ({
|
|
theme: "dark",
|
|
setTheme: vi.fn(),
|
|
toggleTheme: vi.fn(),
|
|
}),
|
|
}));
|
|
|
|
// The router's navigate wrapper reads the active company prefix from context.
|
|
vi.mock("@/context/CompanyContext", () => ({
|
|
useCompany: () => ({
|
|
selectedCompany: null,
|
|
selectedCompanyId: null,
|
|
companies: [],
|
|
selectionSource: "manual",
|
|
loading: false,
|
|
error: null,
|
|
setSelectedCompanyId: vi.fn(),
|
|
reloadCompanies: vi.fn(),
|
|
createCompany: vi.fn(),
|
|
}),
|
|
}));
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
async function act(callback: () => void | Promise<void>) {
|
|
let result: void | Promise<void> = undefined;
|
|
flushSync(() => {
|
|
result = callback();
|
|
});
|
|
await result;
|
|
}
|
|
|
|
async function flushReact() {
|
|
await act(async () => {
|
|
await Promise.resolve();
|
|
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
|
});
|
|
flushSync(() => {});
|
|
}
|
|
|
|
function renderAuthPage(container: HTMLElement) {
|
|
const root = createRoot(container);
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: false } },
|
|
});
|
|
return { root, queryClient };
|
|
}
|
|
|
|
describe("AuthPage", () => {
|
|
let container: HTMLDivElement;
|
|
|
|
beforeEach(() => {
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
getSessionMock.mockResolvedValue(null);
|
|
healthMock.mockResolvedValue({ status: "ok", deploymentMode: "authenticated" });
|
|
beginCloudSignInMock.mockReturnValue(true);
|
|
signInEmailMock.mockResolvedValue(undefined);
|
|
signUpEmailMock.mockResolvedValue(undefined);
|
|
});
|
|
|
|
afterEach(() => {
|
|
container.remove();
|
|
document.body.innerHTML = "";
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
async function mount(path = "/auth") {
|
|
const { root, queryClient } = renderAuthPage(container);
|
|
await act(async () => {
|
|
root.render(
|
|
<MemoryRouter initialEntries={[path]}>
|
|
<QueryClientProvider client={queryClient}>
|
|
<Routes>
|
|
<Route path="/auth" element={<AuthPage />} />
|
|
</Routes>
|
|
</QueryClientProvider>
|
|
</MemoryRouter>,
|
|
);
|
|
});
|
|
await flushReact();
|
|
await flushReact();
|
|
return { root, queryClient };
|
|
}
|
|
|
|
it.each(["https://my.paperclip.app", "https://my-staging.paperclip.app"])("recovers Cloud auth through %s without rendering an instance form", async (origin) => {
|
|
healthMock.mockResolvedValue({ cloud: { managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: origin, stackSlug: "team" } });
|
|
const { root } = await mount("/auth?next=%2FTEST%2Fissues%2FTEST-1%3Ftab%3Dactivity%23comment");
|
|
await vi.waitFor(() => expect(beginCloudSignInMock).toHaveBeenCalledTimes(1));
|
|
const target = new URL(beginCloudSignInMock.mock.calls[0][0]);
|
|
expect(target.origin).toBe(origin);
|
|
expect(target.pathname).toBe("/v1/stacks/team/entry-redirect");
|
|
expect(target.searchParams.get("returnTo")).toBe("/TEST/issues/TEST-1?tab=activity#comment");
|
|
expect(container.querySelector("form")).toBeNull();
|
|
await act(() => root.unmount());
|
|
});
|
|
|
|
it("never flashes a form while deployment metadata is loading", async () => {
|
|
healthMock.mockReturnValue(new Promise(() => {}));
|
|
const { root } = await mount();
|
|
expect(container.querySelector("form")).toBeNull();
|
|
expect(container.textContent).toContain("Loading");
|
|
await act(() => root.unmount());
|
|
});
|
|
|
|
it("fails closed when deployment metadata cannot be loaded", async () => {
|
|
healthMock.mockRejectedValue(new Error("offline"));
|
|
const { root } = await mount();
|
|
await vi.waitFor(() => expect(container.textContent).toContain("Unable to check sign-in"));
|
|
expect(container.querySelector("form")).toBeNull();
|
|
await act(() => root.unmount());
|
|
});
|
|
|
|
it("offers a manual Cloud retry after the automatic recovery limit", async () => {
|
|
healthMock.mockResolvedValue({ cloud: { managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: "https://my.paperclip.app", stackSlug: "team" } });
|
|
beginCloudSignInMock.mockReturnValue(false);
|
|
const { root } = await mount();
|
|
await vi.waitFor(() => expect(container.textContent).toContain("Continue to Paperclip Cloud"));
|
|
expect(container.querySelector("form")).toBeNull();
|
|
await act(() => root.unmount());
|
|
});
|
|
|
|
it("keeps incomplete Cloud configuration out of the instance form", async () => {
|
|
healthMock.mockResolvedValue({ cloud: { managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: null, stackSlug: null } });
|
|
const { root } = await mount();
|
|
await vi.waitFor(() => expect(container.textContent).toContain("Cloud sign-in is unavailable"));
|
|
expect(container.querySelector("form")).toBeNull();
|
|
expect(beginCloudSignInMock).not.toHaveBeenCalled();
|
|
await act(() => root.unmount());
|
|
});
|
|
|
|
it("exposes password-manager metadata and a11y attributes on the sign-in form", async () => {
|
|
const { root } = await mount();
|
|
|
|
const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement;
|
|
const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement;
|
|
|
|
expect(emailInput).not.toBeNull();
|
|
expect(passwordInput).not.toBeNull();
|
|
|
|
// 1Password / password-manager recognition: identifier field is "username".
|
|
expect(emailInput.getAttribute("autocomplete")).toBe("username");
|
|
expect(emailInput.getAttribute("type")).toBe("email");
|
|
expect(passwordInput.getAttribute("autocomplete")).toBe("current-password");
|
|
|
|
// Stable ids/names for both inputs.
|
|
expect(emailInput.id).toBe("email");
|
|
expect(passwordInput.id).toBe("password");
|
|
|
|
// Required + programmatic required state.
|
|
expect(emailInput.required).toBe(true);
|
|
expect(emailInput.getAttribute("aria-required")).toBe("true");
|
|
expect(passwordInput.required).toBe(true);
|
|
expect(passwordInput.getAttribute("aria-required")).toBe("true");
|
|
|
|
// Programmatic labels.
|
|
expect(container.querySelector('label[for="email"]')).not.toBeNull();
|
|
expect(container.querySelector('label[for="password"]')).not.toBeNull();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("uses new-password autocomplete in sign-up mode", async () => {
|
|
const { root } = await mount();
|
|
|
|
const createOne = Array.from(container.querySelectorAll("button")).find(
|
|
(button) => button.textContent === "Create one",
|
|
);
|
|
expect(createOne).not.toBeNull();
|
|
|
|
await act(async () => {
|
|
createOne?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await flushReact();
|
|
|
|
const nameInput = container.querySelector('input[name="name"]') as HTMLInputElement;
|
|
const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement;
|
|
expect(nameInput).not.toBeNull();
|
|
expect(nameInput.getAttribute("autocomplete")).toBe("name");
|
|
expect(nameInput.required).toBe(true);
|
|
expect(passwordInput.getAttribute("autocomplete")).toBe("new-password");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("renders auth errors in an assertive alert region referenced by the inputs", async () => {
|
|
const { root } = await mount();
|
|
|
|
const inputValueSetter = Object.getOwnPropertyDescriptor(
|
|
HTMLInputElement.prototype,
|
|
"value",
|
|
)?.set;
|
|
const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement;
|
|
const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement;
|
|
|
|
await act(async () => {
|
|
inputValueSetter!.call(emailInput, "jane@example.com");
|
|
emailInput.dispatchEvent(new Event("input", { bubbles: true }));
|
|
inputValueSetter!.call(passwordInput, "wrongpass");
|
|
passwordInput.dispatchEvent(new Event("input", { bubbles: true }));
|
|
});
|
|
|
|
signInEmailMock.mockRejectedValueOnce(new Error("Invalid email or password"));
|
|
|
|
const form = container.querySelector("form") as HTMLFormElement;
|
|
await act(async () => {
|
|
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
|
});
|
|
await flushReact();
|
|
await flushReact();
|
|
|
|
const alert = container.querySelector('[role="alert"]') as HTMLElement;
|
|
expect(alert).not.toBeNull();
|
|
expect(alert.hasAttribute("aria-live")).toBe(false);
|
|
expect(alert.textContent).toContain("Invalid email or password");
|
|
|
|
const errorId = alert.id;
|
|
expect(errorId.length).toBeGreaterThan(0);
|
|
expect(emailInput.getAttribute("aria-describedby")).toBe(errorId);
|
|
expect(emailInput.getAttribute("aria-invalid")).toBe("true");
|
|
expect(passwordInput.getAttribute("aria-describedby")).toBe(errorId);
|
|
expect(passwordInput.getAttribute("aria-invalid")).toBe("true");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("invalidates anonymous health metadata after sign-in", async () => {
|
|
const { root, queryClient } = await mount();
|
|
queryClient.setQueryData(queryKeys.health, {
|
|
status: "ok",
|
|
deploymentMode: "authenticated",
|
|
});
|
|
|
|
const inputValueSetter = Object.getOwnPropertyDescriptor(
|
|
HTMLInputElement.prototype,
|
|
"value",
|
|
)?.set;
|
|
const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement;
|
|
const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement;
|
|
|
|
await act(async () => {
|
|
inputValueSetter!.call(emailInput, "jane@example.com");
|
|
emailInput.dispatchEvent(new Event("input", { bubbles: true }));
|
|
inputValueSetter!.call(passwordInput, "supersecret");
|
|
passwordInput.dispatchEvent(new Event("input", { bubbles: true }));
|
|
});
|
|
|
|
const form = container.querySelector("form") as HTMLFormElement;
|
|
await act(async () => {
|
|
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
|
});
|
|
await flushReact();
|
|
await flushReact();
|
|
|
|
expect(signInEmailMock).toHaveBeenCalledWith({
|
|
email: "jane@example.com",
|
|
password: "supersecret",
|
|
});
|
|
expect(healthMock).toHaveBeenCalledTimes(2);
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
});
|