Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions app/src/server/course-consent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@ export function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
}

export function connectorPage(title: string, body: string, headers = new Headers(), status = 200): Response {
export function connectorPage(title: string, body: string, headers = new Headers(), status = 200, redirectUri?: string): Response {
const callback = redirectUri ? new URL(redirectUri) : undefined;
// Chromium applies form-action to the OAuth redirect too. Include only the
// registered callback's HTTP(S) origin, never raw client text in the policy.
const callbackSource = callback && /^https?:$/.test(callback.protocol) && /^[a-z\d.:[\]-]+$/i.test(callback.host) ? ` ${callback.origin}` : "";
headers.set("content-type", "text/html; charset=utf-8");
headers.set("cache-control", "no-store");
headers.set("referrer-policy", "no-referrer");
// Keep Origin on same-origin form POSTs for CSRF checks, without sending
// consent URLs as referrers to the external assistant.
headers.set("referrer-policy", "same-origin");
headers.set("x-frame-options", "DENY");
headers.set("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
headers.set("content-security-policy", `default-src 'none'; style-src 'unsafe-inline'; form-action 'self'${callbackSource}; frame-ancestors 'none'; base-uri 'none'`);
return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)} · PI</title>
<style>body{margin:0;background:#f6f3ed;color:#242521;font:16px/1.55 system-ui,sans-serif}main{max-width:620px;margin:6vh auto;padding:32px}h1{font:600 34px/1.15 Georgia,serif}h2{font-size:20px;margin-top:32px}a{color:#305a4b}label{display:block;padding:18px 0;border-top:1px solid #ccc}input{margin-right:8px;accent-color:#305a4b}button{padding:12px 20px;font:inherit;border:1px solid #305a4b;border-radius:8px;background:#305a4b;color:white;cursor:pointer}button.secondary{background:transparent;color:#305a4b}small{display:block;color:#595b54}code{overflow-wrap:anywhere}.actions{display:flex;gap:12px;flex-wrap:wrap;margin-top:24px}.grant{padding:18px 0;border-top:1px solid #ccc}.eyebrow{font-weight:600;color:#305a4b}p,li{overflow-wrap:anywhere}</style></head><body><main><a href="/apps">PI / My apps</a><p class="eyebrow">Princeton Courses by TigerApps</p><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`, { headers, status });
}
Expand All @@ -27,7 +33,7 @@ export function consentPage(details: ConsentDescription, handle: string, netid:
<label><input type="checkbox" name="scope" value="${PLAN_WRITE}">Allow changes to my saved plans<small>Optional. Create, rename, add, or remove courses in TigerJunction and TigerPath when you ask. This does not register you for courses.</small></label>
<p>Your conversation stays in your assistant. This connection does not import memories, PI chats, Canvas, or calendars.</p>
<small>Access can renew for up to 30 days. Disconnect any time at PI / My apps / Course connector.</small>
<div class="actions"><button name="decision" value="approve">Connect</button><button class="secondary" name="decision" value="deny">Cancel</button></div></form>`, headers);
<div class="actions"><button name="decision" value="approve">Connect</button><button class="secondary" name="decision" value="deny">Cancel</button></div></form>`, headers, 200, details.redirectUri);
}

export function connectionsPage(origin: string, netid: string, grants: GrantSummary[], cursor?: string): Response {
Expand Down
12 changes: 11 additions & 1 deletion app/tests/course-mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { COURSE_READ, PLAN_WRITE, createCourseServer, handleCourseMcp, type CourseUpstream } from "../src/server/course-mcp.ts";
import { consentPage } from "../src/server/course-consent.ts";
import { connectorPage, consentPage } from "../src/server/course-consent.ts";

const tool = (name: string) => ({ name, inputSchema: { type: "object" as const, properties: {} } });
function fakeEngine() {
Expand Down Expand Up @@ -111,3 +111,13 @@ test("consent escapes client-controlled text and makes plan editing opt-in", asy
assert.match(response.headers.get("content-security-policy")!, /frame-ancestors 'none'/);
assert.equal(response.headers.get("cache-control"), "no-store");
});

test("consent CSP permits only the callback origin and cannot inject directives", () => {
const policy = (uri: string) => connectorPage("Test", "", undefined, 200, uri).headers.get("content-security-policy")!;
assert.match(policy("https://assistant.test/callback?state=private"), /form-action 'self' https:\/\/assistant\.test;/);
assert.doesNotMatch(policy("https://assistant.test/callback?state=private"), /callback|private/);
assert.match(policy("http://127.0.0.1:4321/callback"), /form-action 'self' http:\/\/127\.0\.0\.1:4321;/);
for (const uri of ["https://evil.test;script-src/callback", "https://*.evil.test/callback", "javascript:alert(1)"]) {
assert.equal(policy(uri), "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
}
});
7 changes: 7 additions & 0 deletions app/tests/course-oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ async function flow(netid = "student1") {
authorize.search = new URLSearchParams({ client_id: client.client_id, redirect_uri: redirectUri, response_type: "code", scope: "courses:read plans:write offline_access", state: "client-state", resource: `${origin}/mcp`, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256" }).toString();
const page = await request(authorize.href, { headers: { cookie: session(netid) } });
assert.equal(page.status, 200);
assert.equal(page.headers.get("referrer-policy"), "same-origin", "consent forms must preserve the browser's Origin header");
assert.match(page.headers.get("content-security-policy")!, /form-action 'self' https:\/\/assistant\.test;/);
const html = await page.text();
const handle = html.match(/name="handle" value="([^"]+)"/)![1];
const subject = html.match(/name="subject" value="([^"]+)"/)![1];
Expand Down Expand Up @@ -118,6 +120,8 @@ test("unsigned browsers return through CAS before connector consent", async () =
test("consent rejects CSRF, another browser, and switching accounts", async () => {
const f = await flow();
assert.equal((await approve(f, false, { requestOrigin: "https://evil.test" })).status, 403);
assert.equal((await approve(f, false, { requestOrigin: "null" })).status, 403);
assert.equal((await request("/connect/authorize", { method: "POST", headers: { cookie: f.cookie }, body: new URLSearchParams({ handle: f.handle, subject: f.subject, decision: "approve" }) })).status, 403);
assert.equal((await approve(f, false, { cookie: session() })).status, 400);
const swapped = f.cookie.replace(/^pi_session=[^;]+/, session("student2"));
assert.equal((await approve(f, false, { cookie: swapped })).status, 400);
Expand Down Expand Up @@ -167,13 +171,16 @@ test("optional editing works and per-student grants can be revoked only by their
assert.ok(grants.keys.length > 0);
// The user-facing management page identifies the grant without exposing tokens.
const page = await request("/connect", { headers: { cookie: session() } });
assert.equal(page.headers.get("referrer-policy"), "same-origin", "disconnect forms must preserve the browser's Origin header");
assert.match(page.headers.get("content-security-policy")!, /form-action 'self';/);
const html = await page.text();
assert.doesNotMatch(html, new RegExp(token.access_token));
const grantRecords = await Promise.all(grants.keys.map(k => kv.get(k.name, "json") as Promise<any>));
const grant = grantRecords.find(g => g.clientId === f.client.client_id);
assert.ok(grant);
const revoke = (netid: string, requestOrigin = origin) => request("/connect/revoke", { method: "POST", headers: { origin: requestOrigin, cookie: session(netid) }, body: new URLSearchParams({ grant: grant.id }) });
assert.equal((await revoke("student1", "https://evil.test")).status, 403);
assert.equal((await revoke("student1", "null")).status, 403);
await revoke("student2");
assert.equal((await rpc(token.access_token, "ping")).status, 200);
assert.equal((await revoke("student1")).status, 303);
Expand Down
Loading