Files
Codeman/test/webview-auth-exemption.test.ts
T
Codeman maintainer b34fcaf928 feat(web-tabs): open dashboard URLs as tabs beside agent sessions
Adds a "Web / URL" section to the Run dropdown. A saved URL renders as a tab in
the same strip as Claude/Codex/Gemini sessions, with the same Alt+1..9 numbering,
so Codeman is one mission control instead of Codeman plus a pile of browser tabs.

A webview is NOT a sixth SessionMode: no PTY, no tmux, no respawn, no idle
detection. It is a separate resource sharing only the tab strip and the main
content area, the same call that keeps Docker and remote-SSH as case overlays.

Dashboards are proxied through Codeman's own origin, because a direct iframe
fails three ways at once in the shipped deployment: prod serves HTTPS behind
tailscale serve, so http:// targets are hard-blocked as mixed content (with no
override at all on iOS Safari); Grafana/Portainer-class dashboards send
X-Frame-Options: DENY; and our own default-src 'self' CSP blocks cross-origin
frames. Proxying dissolves all three and leaves the production CSP byte-for-byte
unchanged, since /webview/... is already covered by 'self'. A useful side effect:
the fetch happens server-side, so a tailnet-only dashboard is reachable from a
phone that is not on the tailnet.

The proxy is not an API surface. It authenticates on a 192-bit capability in the
path (memory-only, rolling TTL, bound to the minting user, revoked on edit or
delete) and is correspondingly exempt from the cookie and Origin checks, because
a sandboxed iframe is opaque-origin: it sends no SameSite=lax cookie and its
writes arrive with Origin: null. The Host allowlist is never bypassed. A second
Referer-keyed form of the exemption exists for root-absolute assets and is fenced
to safe methods on non-/api, non-/ws, non-/q paths.

Iframes omit allow-same-origin unless a URL is explicitly marked trusted, since a
proxied page is served from Codeman's own origin and could otherwise read this
document and drive the agent-spawning API. Authorization and codeman_session are
stripped upstream in BOTH modes, so CODEMAN_PASSWORD cannot leak into a dashboard.

Two things only a real browser reveals, both presenting as the dashboard's own
"Failed to fetch" while the page itself renders fine:

- Runtime-built root-absolute URLs (fetch('/api/data')) escape <base href> and
  land on Codeman's root. Widening the Referer fallback into /api would trade
  security for it, so an injected shim patches fetch/XHR/WebSocket/EventSource
  inside the frame instead, removing the class rather than the guard.
- An opaque-origin document CORS-checks every request, including to the host it
  was served from. Script/css/img loads are not CORS-checked, which is why the
  page renders while its API calls die. The proxy now emits CORS headers and
  answers preflights itself. registerSecurityHeaders answered every OPTIONS with
  a bare 204 before routing, carrying no ACAO for Origin: null, so that
  short-circuit now exempts a valid capability.

Neither is reproducible with curl, which does not enforce CORS.

Also fixes a pre-existing bug found on the way: .toolbar has backdrop-filter,
making it a stacking context that trapped .run-mode-menu's z-index:1000, so
.welcome-overlay painted over the whole Run menu. With no session open, every
item in it (Claude Code included) was unclickable.

Verified end to end against a real tailnet dashboard: live data, WebSocket push,
no failed requests, and switching tabs does not reload the frame. 98 new tests
cover the pure rewrite helpers, the CORS helper, the shim's rewrite logic, route
CRUD, and every edge of the auth exemption.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 17:06:36 +02:00

181 lines
7.2 KiB
TypeScript

/**
* The web-tab proxy is exempt from Codeman's cookie auth and its cross-site Origin
* guard, because a sandboxed dashboard iframe is opaque-origin: it sends no session
* cookie and its writes arrive with `Origin: null`. The capability in the path is
* the credential instead.
*
* That exemption is the security-sensitive part of this feature, so these tests pin
* its EDGES: it must apply to a live capability and to nothing else. A regression
* here would be an unauthenticated hole into an agent-spawning API.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { registerAuthMiddleware, registerHostGuard, registerSecurityHeaders } from '../src/web/middleware/auth.js';
import { webviewCapabilities } from '../src/webview-capabilities.js';
import type { HostPolicy } from '../src/web/network-auth-policy.js';
const POLICY: HostPolicy = { allowedHosts: [], allowLan: true };
const PASSWORD = 'test-password';
let app: FastifyInstance;
let capability: string;
let savedPassword: string | undefined;
beforeEach(async () => {
savedPassword = process.env.CODEMAN_PASSWORD;
// The middleware reads this at registration time; auth is inert without it.
process.env.CODEMAN_PASSWORD = PASSWORD;
capability = webviewCapabilities.mint('webview-under-test', undefined);
app = Fastify({ logger: false });
await app.register(fastifyCookie);
// Same order as server.ts (host guard → auth → security headers), so hook
// interactions are exercised for real. The OPTIONS short-circuit lives in
// registerSecurityHeaders and is part of what these tests pin.
registerHostGuard(app, () => POLICY);
registerAuthMiddleware(app, false);
registerSecurityHeaders(app, false);
// Stand-ins for the real surfaces, so a reachable route means auth let it through.
app.all('/webview/:cap/*', async () => ({ proxied: true }));
app.all('/api/sessions', async () => ({ sensitive: true }));
app.get('/', async () => 'app shell');
app.get('/static/app.js', async () => 'asset');
app.get('/webviewfoo/bar', async () => 'lookalike');
await app.ready();
});
afterEach(async () => {
await app.close();
webviewCapabilities.revokeWebview('webview-under-test');
if (savedPassword === undefined) delete process.env.CODEMAN_PASSWORD;
else process.env.CODEMAN_PASSWORD = savedPassword;
});
describe('the exemption applies to a live capability', () => {
it('lets an unauthenticated GET through on the proxy path', async () => {
const res = await app.inject({ method: 'GET', url: `/webview/${capability}/static/app.js` });
expect(res.statusCode).toBe(200);
});
it('lets a write through despite Origin: null, which a sandboxed iframe always sends', async () => {
const res = await app.inject({
method: 'POST',
url: `/webview/${capability}/login`,
headers: { origin: 'null' },
payload: {},
});
expect(res.statusCode).toBe(200);
});
it('lets a CORS preflight reach the proxy instead of the global 204 short-circuit', async () => {
// registerSecurityHeaders answers every OPTIONS with a bare 204, which carries
// no Access-Control-Allow-Origin for the `null` origin a sandboxed frame sends.
// The proxy must get the chance to answer with real CORS headers, or every
// dashboard fetch fails its preflight.
const res = await app.inject({
method: 'OPTIONS',
url: `/webview/${capability}/api/stats`,
headers: { origin: 'null', 'access-control-request-method': 'GET' },
});
expect(res.statusCode).toBe(200); // reached the stand-in route, not the 204 hook
});
it('still short-circuits OPTIONS everywhere else', async () => {
// Authenticated, because the auth hook runs before the security-headers hook
// and would otherwise 401 first. With credentials the 204 short-circuit is
// reached, proving it is intact for every non-webview path.
const res = await app.inject({
method: 'OPTIONS',
url: '/api/sessions',
headers: {
origin: 'null',
'access-control-request-method': 'GET',
authorization: 'Basic ' + Buffer.from(`admin:${PASSWORD}`).toString('base64'),
},
});
expect(res.statusCode).toBe(204);
expect(res.headers['access-control-allow-origin']).toBeUndefined();
});
it('serves a root-absolute asset when the Referer identifies the dashboard', async () => {
const res = await app.inject({
method: 'GET',
url: '/static/app.js',
headers: { referer: `http://localhost/webview/${capability}/panel` },
});
expect(res.statusCode).toBe(200);
});
});
describe('the exemption does NOT widen anywhere else', () => {
it('rejects an unauthenticated request with no capability at all', async () => {
expect((await app.inject({ method: 'GET', url: '/static/app.js' })).statusCode).toBe(401);
expect((await app.inject({ method: 'GET', url: '/' })).statusCode).toBe(401);
});
it('rejects a well-formed but UNKNOWN capability', async () => {
const res = await app.inject({ method: 'GET', url: `/webview/${'Z'.repeat(32)}/x` });
expect(res.statusCode).toBe(401);
});
it('rejects a revoked capability immediately', async () => {
webviewCapabilities.revokeWebview('webview-under-test');
const res = await app.inject({ method: 'GET', url: `/webview/${capability}/x` });
expect(res.statusCode).toBe(401);
});
it('does not match a lookalike prefix', async () => {
expect((await app.inject({ method: 'GET', url: '/webviewfoo/bar' })).statusCode).toBe(401);
});
it('NEVER exempts the Codeman API, even with a valid capability in the Referer', async () => {
// This is the hole the Referer form would open if it were not path-fenced.
const res = await app.inject({
method: 'GET',
url: '/api/sessions',
headers: { referer: `http://localhost/webview/${capability}/panel` },
});
expect(res.statusCode).toBe(401);
});
it('does not let the Referer form carry a WRITE', async () => {
const res = await app.inject({
method: 'POST',
url: '/static/app.js',
headers: { referer: `http://localhost/webview/${capability}/panel`, origin: 'null' },
payload: {},
});
// Blocked as cross-site by the Origin guard, or as unauthenticated. Either is fine;
// what matters is that it is not 200.
expect(res.statusCode).not.toBe(200);
});
it('still blocks a genuinely cross-site write to the API', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/sessions',
headers: { origin: 'https://evil.example' },
payload: {},
});
expect(res.statusCode).toBe(403);
});
});
describe('authenticated access is unaffected', () => {
const basic = 'Basic ' + Buffer.from(`admin:${PASSWORD}`).toString('base64');
it('normal Basic auth still reaches the app', async () => {
const res = await app.inject({ method: 'GET', url: '/', headers: { authorization: basic } });
expect(res.statusCode).toBe(200);
});
it('a wrong password is still rejected', async () => {
const wrong = 'Basic ' + Buffer.from('admin:nope').toString('base64');
expect((await app.inject({ method: 'GET', url: '/', headers: { authorization: wrong } })).statusCode).toBe(401);
});
});