Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

test(view): follow cookie redirects in printed links [N39,N26]

Corey Olson3b16052b6e0c
diff --git a/test/e2e-helpers.js b/test/e2e-helpers.js
index 7f17cd03..d9f50b02 100644
--- a/test/e2e-helpers.js
+++ b/test/e2e-helpers.js
@@ -12,6 +12,7 @@ import { join, resolve } from 'node:path';
import * as store from '../src/board.js';
import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
import { fetchFresh } from './http-fixture.js';
+import { fetchPrintedViewLink } from './view-link-fixture.js';
/** Create isolated real-repository helpers for one parallel end-to-end test file. */
export function createE2eHelpers() {
@@ -194,35 +195,8 @@ async function startView(box, cwd) {
const key = link.searchParams.get('k');
const base = `http://127.0.0.1:${link.port}`;
const headers = { 'x-pullboard-key': key };
- /**
- * Fetch the page through either the accepted printed-key response or the cookie exchange.
- * Keeping these paths in one fixture lets the API assertions stay independent of page auth.
- */
- const page = async () => {
- const response = await fetchFresh(link, { redirect: 'manual' });
- if (response.status === 200) return response;
- assert.equal(response.status, 303, 'the printed link either serves the legacy page or exchanges its key');
-
- const rawLocation = response.headers.get('location');
- assert.ok(rawLocation, 'the cookie exchange has a redirect target');
- const location = new URL(rawLocation, base);
- assert.equal(location.origin, new URL(base).origin, 'the cookie exchange stays on this view origin');
- assert.equal(location.pathname, '/', 'the cookie exchange returns to the clean page path');
- assert.equal(location.search, '', 'the redirect does not keep credentials in the address');
- assert.equal(location.hash, '', 'the redirect has no credential-bearing fragment');
-
- const cookies = response.headers.getSetCookie?.() ?? [response.headers.get('set-cookie')].filter(Boolean);
- assert.equal(cookies.length, 1, 'the exchange sets one session cookie');
- const [pair, ...attributes] = cookies[0].split(';').map((part) => part.trim());
- assert.match(pair, /^[A-Za-z0-9_-]+=[A-Za-z0-9._~-]+$/u, 'the session cookie has a valid nonempty name and value');
- assert.ok(attributes.some((attribute) => /^httponly$/iu.test(attribute)), 'the session cookie is HttpOnly');
- assert.ok(attributes.some((attribute) => /^samesite=strict$/iu.test(attribute)), 'the session cookie is SameSite=Strict');
- assert.ok(attributes.some((attribute) => /^path=\/$/iu.test(attribute)), 'the session cookie is scoped to the view');
-
- const pageResponse = await fetchFresh(location, { headers: { cookie: pair }, redirect: 'manual' });
- assert.equal(pageResponse.status, 200, 'the cookie jar fetches the page after the exchange');
- return pageResponse;
- };
+ /** Read the page through either the legacy link or the cookie exchange. */
+ const page = () => fetchPrintedViewLink(link);
/** Read the public listing through the view's real authenticated API. */
const boards = async () => {
const response = await fetchFresh(`${base}/api/v1/boards`, { headers });
diff --git a/test/e2e-view.test.js b/test/e2e-view.test.js
index d239d0cc..ccc54214 100644
--- a/test/e2e-view.test.js
+++ b/test/e2e-view.test.js
@@ -17,7 +17,7 @@ import {
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
-import { request } from 'node:http';
+import { createServer, request } from 'node:http';
import { connect } from 'node:net';
import { join, resolve } from 'node:path';
import { after, test } from 'node:test';
@@ -27,6 +27,7 @@ import * as store from '../src/board.js';
import { createE2eHelpers } from './e2e-helpers.js';
import { fetchFresh } from './http-fixture.js';
+import { fetchPrintedViewLink } from './view-link-fixture.js';
const e2e = createE2eHelpers();
after(e2e.cleanup);
const {
@@ -46,7 +47,7 @@ async function waitForViewStopped(url) {
const deadline = Date.now() + 5_000; // budget: hang ceiling for observing graceful SIGTERM cleanup.
while (Date.now() < deadline) {
try {
- const response = await fetchFresh(url, { signal: AbortSignal.timeout(500) });
+ const response = await fetchPrintedViewLink(url, { signal: AbortSignal.timeout(500) });
if (!response.ok) throw new Error('the view listener remained open after its owner stopped');
} catch (error) {
if (error.cause?.code === 'ECONNREFUSED') return;
@@ -77,7 +78,7 @@ test("an agent's pullboard view prints its link and returns [N26,N32]", async ()
assert.equal((statSync(stateFile).mode & 0o077) === 0, true, 'the persisted session secret is private to this user');
assert.equal(state.pid === first.pid && state.boundAt === first.boundAt, true, 'the runtime record matches the successful bind receipt');
assert.equal(state.secret === firstUrl.searchParams.get('k'), true, 'the private record authenticates the returned link');
- const page = await fetchFresh(firstUrl);
+ const page = await fetchPrintedViewLink(firstUrl);
assert.equal(page.status, 200, 'the returned link fetches the live view page');
const receiptFile = join(box.repo, '.git', 'pullboard', 'view-bind.json');
assert.equal(existsSync(receiptFile), true, 'a fresh bind writes the setup receipt');
@@ -102,7 +103,7 @@ test("an agent's pullboard view prints its link and returns [N26,N32]", async ()
const agent = JSON.parse(agentStarted);
owned.push({ pid: agent.pid, port: agent.port, url: agent.url });
assert.equal(agent.reused, false, 'an explicit agent start also creates and returns its owned view');
- assert.equal((await fetchFresh(agent.url)).status, 200, 'the explicit agent link fetches its live page');
+ assert.equal((await fetchPrintedViewLink(agent.url)).status, 200, 'the explicit agent link fetches its live page');
assert.equal(existsSync(receiptFile), true, 'a new port-0 bind writes a new setup receipt');
const agentReceipt = JSON.parse(readFileSync(receiptFile, 'utf8'));
assert.equal(agentReceipt.boundAt, agent.boundAt, 'a new port-0 bind records its actual setup receipt');
@@ -131,6 +132,65 @@ test("an agent's pullboard view prints its link and returns [N26,N32]", async ()
}
});
+test('a printed view link opens through its cookie redirect [N39,N26]', async (t) => {
+ const requests = [];
+ const server = createServer((req, res) => {
+ requests.push({ url: req.url, cookie: req.headers.cookie ?? '' });
+ if (req.url === '/?k=legacy-key') {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end('legacy view page');
+ } else if (req.url === '/?k=fixture-key') {
+ res.writeHead(303, {
+ location: '/',
+ 'set-cookie': 'pb_view=fixture-cookie; Path=/; HttpOnly; SameSite=Strict',
+ }).end();
+ } else if (req.url === '/?k=invalid-userinfo') {
+ const target = new URL('/', origin);
+ target.username = 'user';
+ target.password = 'pass';
+ res.writeHead(303, {
+ location: target.href,
+ 'set-cookie': 'pb_view=fixture-cookie; Path=/; HttpOnly; SameSite=Strict',
+ }).end();
+ } else if (req.url === '/?k=foreign-domain') {
+ res.writeHead(303, {
+ location: '/',
+ 'set-cookie': 'pb_view=foreign-cookie; Path=/; HttpOnly; SameSite=Strict; Domain=foreign.invalid',
+ }).end();
+ } else if (req.url === '/' && req.headers.cookie === 'pb_view=fixture-cookie') {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end('browser opened the view');
+ } else {
+ res.writeHead(403).end('the clean address requires the cookie');
+ }
+ });
+ await new Promise((ready, fail) => {
+ server.once('error', fail);
+ server.listen(0, '127.0.0.1', ready);
+ });
+ t.after(() => new Promise((done) => server.close(done)));
+
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ const legacy = await fetchPrintedViewLink(`${origin}/?k=legacy-key`);
+ assert.equal(legacy.status, 200);
+ assert.equal(await legacy.text(), 'legacy view page');
+ assert.deepEqual(requests.splice(0), [{ url: '/?k=legacy-key', cookie: '' }]);
+
+ const page = await fetchPrintedViewLink(`${origin}/?k=fixture-key`);
+ assert.equal(page.status, 200);
+ assert.equal(await page.text(), 'browser opened the view');
+ assert.deepEqual(requests, [
+ { url: '/?k=fixture-key', cookie: '' },
+ { url: '/', cookie: 'pb_view=fixture-cookie' },
+ ]);
+
+ requests.length = 0;
+ await assert.rejects(fetchPrintedViewLink(`${origin}/?k=invalid-userinfo`), { name: 'AssertionError' });
+ assert.deepEqual(requests, [{ url: '/?k=invalid-userinfo', cookie: '' }]);
+
+ requests.length = 0;
+ await assert.rejects(fetchPrintedViewLink(`${origin}/?k=foreign-domain`), { name: 'AssertionError' });
+ assert.deepEqual(requests, [{ url: '/?k=foreign-domain', cookie: '' }]);
+});
+
test('a person running view with JSON in a terminal keeps the server in that terminal [N26,N32]', () => {
let box = sandbox();
box.env.PULLBOARD_MODEL ??= 'Fixture Model';
diff --git a/test/fixtures/view-person-pty.py b/test/fixtures/view-person-pty.py
index daff2b05..cd8ea351 100644
--- a/test/fixtures/view-person-pty.py
+++ b/test/fixtures/view-person-pty.py
@@ -1,4 +1,5 @@
"""Run one person-mode pullboard view command with real terminal file descriptors."""
+import http.cookiejar
import json
import os
import pty
@@ -70,7 +71,8 @@ def main():
break
assert document is not None, "person PTY command did not print its JSON view link"
server_pid = document.get("pid")
- with urllib.request.urlopen(document["url"], timeout=5) as response:
+ opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
+ with opener.open(document["url"], timeout=5) as response:
page_status = response.status
assert page_status == 200, "the PTY view link did not fetch the page"
stayed_foreground = child.poll() is None
diff --git a/test/relay.test.js b/test/relay.test.js
index 1c2e5594..0074cb59 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -14,6 +14,7 @@ import { githubFixture } from './relay-fixture.js';
import { relayClientFixture } from './relay-client-fixture.js';
import { serveView } from '../src/serve.js';
import { fetchFresh } from './http-fixture.js';
+import { fetchPrintedViewLink } from './view-link-fixture.js';
/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */
async function fixture(t, options = {}) {
@@ -511,7 +512,7 @@ test('offline linked reads use the local board, moves refuse, and the same relay
let view;
try {
view = await serveView({ port: 0 });
- const page = await fetchFresh(view.url);
+ const page = await fetchPrintedViewLink(view.url);
assert.equal(page.status, 200, 'the real local view page remains available');
assert.match(page.headers.get('content-type') ?? '', /text\/html/);
diff --git a/test/view-link-fixture.js b/test/view-link-fixture.js
new file mode 100644
index 00000000..d4e7f544
--- /dev/null
+++ b/test/view-link-fixture.js
@@ -0,0 +1,42 @@
+/** Open a printed view link like a browser when it exchanges its key for a cookie [N39,N26]. */
+import assert from 'node:assert/strict';
+import { fetchFresh } from './http-fixture.js';
+
+/** Follow the view's same-origin cookie redirect and validate the final page response.
+ *
+ * @param {string | URL} url
+ * @param {RequestInit} [init]
+ * @returns {Promise<Response>}
+ */
+export async function fetchPrintedViewLink(url, init = {}) {
+ const response = await fetchFresh(url, { ...init, redirect: 'manual' });
+ if (response.status === 200) return response;
+ assert.equal(response.status, 303, 'the printed link either serves the legacy page or exchanges its key');
+ await response.body?.cancel();
+
+ const location = response.headers.get('location');
+ assert.ok(location, 'the cookie exchange has a redirect target');
+ const target = new URL(location, url);
+ const source = new URL(url);
+ assert.equal(target.username, '', 'the cookie exchange target has no username');
+ assert.equal(target.password, '', 'the cookie exchange target has no password');
+ assert.equal(target.origin, source.origin, 'the cookie exchange stays on this view origin');
+ assert.equal(target.pathname, '/', 'the cookie exchange returns to the clean page path');
+ assert.equal(target.search, '', 'the redirect does not keep credentials in the address');
+ assert.equal(target.hash, '', 'the redirect has no credential-bearing fragment');
+
+ const setCookies = response.headers.getSetCookie?.() ?? [response.headers.get('set-cookie')].filter(Boolean);
+ assert.equal(setCookies.length, 1, 'the exchange sets one session cookie');
+ const [pair, ...attributes] = setCookies[0].split(';').map((part) => part.trim());
+ assert.match(pair, /^[A-Za-z0-9_-]+=[A-Za-z0-9._~-]+$/u, 'the session cookie has a valid nonempty name and value');
+ assert.ok(attributes.some((attribute) => /^httponly$/iu.test(attribute)), 'the session cookie is HttpOnly');
+ assert.ok(attributes.some((attribute) => /^samesite=strict$/iu.test(attribute)), 'the session cookie is SameSite=Strict');
+ assert.ok(attributes.some((attribute) => /^path=\/$/iu.test(attribute)), 'the session cookie is scoped to the view');
+ assert.ok(!attributes.some((attribute) => /^domain=/iu.test(attribute)), 'the session cookie is host-only');
+
+ const headers = new Headers(init.headers);
+ headers.set('cookie', pair);
+ const page = await fetchFresh(target, { ...init, headers, redirect: 'manual' });
+ assert.equal(page.status, 200, 'the cookie fetches the page after the exchange');
+ return page;
+}
diff --git a/test/view-port.test.js b/test/view-port.test.js
index 98b0baaa..d48829d0 100644
--- a/test/view-port.test.js
+++ b/test/view-port.test.js
@@ -10,6 +10,7 @@ import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
import { takeDefaultViewPort } from './view-port-fixture.js';
import { fetchFresh } from './http-fixture.js';
+import { fetchPrintedViewLink } from './view-link-fixture.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
@@ -263,7 +264,7 @@ test('pullboard view uses its fixed default port and reuses its authenticated li
assert.equal(first.reused, false, 'the first invocation owns the new listener');
const sessionFile = join(env.PULLBOARD_HOME, 'view-4890.json');
assert.equal((statSync(sessionFile).mode & 0o077) === 0, true, 'the session secret stays private under umask 022');
- const page = await fetchFresh(first.url);
+ const page = await fetchPrintedViewLink(first.url);
assert.equal(page.status, 200, 'the printed secret link reaches the view');
await page.body?.cancel();