547d4d9822
The proxy adds the shared token to every upstream request and drops any client copy. The peer relay accepts only tailnet, LAN, ts.net and discovered hosts, resolves each name once and pins the checked address, and flags ws:// endpoints with insecure_transport.
605 lines
18 KiB
JavaScript
605 lines
18 KiB
JavaScript
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { createServer, request } from "node:http";
|
|
import { createHash, randomBytes } from "node:crypto";
|
|
import { once } from "node:events";
|
|
import { mkdtemp, writeFile, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { PeerRegistry } from "../src/peerRegistry.js";
|
|
import { spawn } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
async function fixture(t) {
|
|
const observations = [];
|
|
const gates = {};
|
|
const hold = (name) => {
|
|
let release, enter;
|
|
const promise = new Promise((done) => {
|
|
release = done;
|
|
});
|
|
const entered = new Promise((done) => {
|
|
enter = done;
|
|
});
|
|
gates[name] = { promise, enter };
|
|
t.after(release);
|
|
return { entered, release };
|
|
};
|
|
const remotes = [];
|
|
for (const name of ["one", "two"]) {
|
|
const server = createServer(async (req, res) => {
|
|
observations.push({
|
|
name,
|
|
path: req.url,
|
|
cookie: req.headers.cookie,
|
|
upload: req.headers["x-pipelines-upload-name"],
|
|
});
|
|
if (req.url === "/login" && req.method === "GET" && gates[name]) {
|
|
gates[name].enter();
|
|
await gates[name].promise;
|
|
}
|
|
if (req.url === "/discovery") {
|
|
res.setHeader("Content-Type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
discovered_servers: [
|
|
{
|
|
name: "Linux desktop",
|
|
endpoint: "ws://192.168.1.2:8083/connect",
|
|
auth: "password",
|
|
version: "test",
|
|
},
|
|
],
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
if (req.url === "/login" && req.method === "POST") {
|
|
let body = "";
|
|
for await (const chunk of req) body += chunk;
|
|
if (new URLSearchParams(body).get("password") !== `password-${name}`) {
|
|
res.writeHead(401).end();
|
|
return;
|
|
}
|
|
res
|
|
.writeHead(303, {
|
|
"Set-Cookie": `pipelines_session=remote-${name}; HttpOnly`,
|
|
Location: "/",
|
|
})
|
|
.end();
|
|
return;
|
|
}
|
|
if (req.url === "/login") {
|
|
if (req.headers.cookie === `pipelines_session=remote-${name}`)
|
|
res.writeHead(302, { Location: "/" }).end();
|
|
else res.end('<input name="password">');
|
|
return;
|
|
}
|
|
res.setHeader("Set-Cookie", "do-not-forward=private");
|
|
if (req.method === "POST") {
|
|
let body = "";
|
|
for await (const chunk of req) body += chunk;
|
|
res.end(
|
|
JSON.stringify({
|
|
name,
|
|
method: req.method,
|
|
url: req.url,
|
|
cookie: req.headers.cookie,
|
|
upload: req.headers["x-pipelines-upload-name"],
|
|
type: req.headers["content-type"],
|
|
body,
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
if (
|
|
req.url.startsWith("/artifacts/") ||
|
|
req.url.includes("untrusted.svg")
|
|
) {
|
|
res.setHeader(
|
|
"Content-Type",
|
|
req.url.startsWith("/artifacts/") ? "text/html" : "image/svg+xml",
|
|
);
|
|
if (req.url.startsWith("/artifacts/")) {
|
|
res.setHeader(
|
|
"Content-Security-Policy",
|
|
"sandbox; default-src 'none'; img-src 'none'",
|
|
);
|
|
}
|
|
res.end(
|
|
'<script>fetch("/api/peers/private")</script><svg onload="alert(document.cookie)"></svg>',
|
|
);
|
|
return;
|
|
}
|
|
res.end(
|
|
JSON.stringify({ name, url: req.url, cookie: req.headers.cookie }),
|
|
);
|
|
});
|
|
server.on("upgrade", (req, socket) => {
|
|
observations.push({
|
|
name,
|
|
path: req.url,
|
|
cookie: req.headers.cookie,
|
|
origin: req.headers.origin,
|
|
});
|
|
if (req.headers.cookie !== `pipelines_session=remote-${name}`) {
|
|
socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n");
|
|
return;
|
|
}
|
|
const accept = createHash("sha1")
|
|
.update(
|
|
req.headers["sec-websocket-key"] +
|
|
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
)
|
|
.digest("base64");
|
|
socket.write(
|
|
`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`,
|
|
);
|
|
const message = Buffer.from(JSON.stringify({ name }));
|
|
socket.write(
|
|
Buffer.concat([Buffer.from([0x81, message.length]), message]),
|
|
);
|
|
socket.on("error", () => {});
|
|
});
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
t.after(() => {
|
|
server.closeAllConnections();
|
|
server.close();
|
|
});
|
|
remotes.push(`ws://127.0.0.1:${server.address().port}/connect`);
|
|
}
|
|
const dir = await mkdtemp(join(tmpdir(), "peer-relay-"));
|
|
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
const auth = join(dir, "auth.json");
|
|
await writeFile(
|
|
auth,
|
|
JSON.stringify({ password: "local-password", secret: "s".repeat(40) }),
|
|
);
|
|
const reserve = createServer().listen(0, "127.0.0.1");
|
|
await once(reserve, "listening");
|
|
const port = reserve.address().port;
|
|
await new Promise((done) => reserve.close(done));
|
|
const child = spawn(
|
|
process.execPath,
|
|
[
|
|
"serve.mjs",
|
|
"--port",
|
|
String(port),
|
|
"--pipelines",
|
|
new URL(remotes[0]).host,
|
|
],
|
|
{
|
|
cwd: fileURLToPath(new URL("..", import.meta.url)),
|
|
env: {
|
|
...process.env,
|
|
PIPELINES_WEB_AUTH: "",
|
|
PIPELINES_WEB_AUTH_FILE: auth,
|
|
// The fixture machines listen on loopback, which the relay refuses by default.
|
|
PIPELINES_PEER_ALLOW: "loopback",
|
|
},
|
|
stdio: ["ignore", "pipe", "inherit"],
|
|
},
|
|
);
|
|
t.after(async () => {
|
|
const exited = once(child, "exit");
|
|
child.kill();
|
|
await exited;
|
|
});
|
|
await once(child.stdout, "data");
|
|
const base = `http://127.0.0.1:${port}`;
|
|
const login = async () => {
|
|
const reply = await fetch(base + "/login", {
|
|
method: "POST",
|
|
body: new URLSearchParams({ password: "local-password" }),
|
|
redirect: "manual",
|
|
});
|
|
return reply.headers.get("set-cookie").split(";")[0];
|
|
};
|
|
const cookie = await login();
|
|
const register = (id, data, who = cookie, origin = base) =>
|
|
fetch(base + "/api/peers/" + id, {
|
|
method: "POST",
|
|
headers: {
|
|
Cookie: who,
|
|
Origin: origin,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
return { base, cookie, remotes, observations, register, login, hold };
|
|
}
|
|
|
|
test("browser can authenticate both machines, relay files and keep local credentials isolated", async (t) => {
|
|
const f = await fixture(t);
|
|
assert.equal(
|
|
(await f.register("one", { endpoints: [f.remotes[0]] }, "")).status,
|
|
401,
|
|
);
|
|
const needing = await f.register("one", { endpoints: [f.remotes[0]] });
|
|
assert.equal((await needing.json()).needs_password, true);
|
|
assert.equal(
|
|
(
|
|
await (
|
|
await f.register("one", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
})
|
|
).json()
|
|
).connected,
|
|
true,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await (
|
|
await f.register("two", {
|
|
endpoints: [f.remotes[1]],
|
|
password: "password-two",
|
|
})
|
|
).json()
|
|
).connected,
|
|
true,
|
|
);
|
|
for (const [id, name] of [
|
|
["one", "one"],
|
|
["two", "two"],
|
|
]) {
|
|
const reply = await fetch(
|
|
f.base + `/peers/${id}/files?path=%2Fhome%2Freport`,
|
|
{ headers: { Cookie: f.cookie } },
|
|
);
|
|
assert.equal(reply.status, 200);
|
|
assert.equal(reply.headers.get("set-cookie"), null);
|
|
assert.deepEqual(await reply.json(), {
|
|
name,
|
|
url: "/files?path=%2Fhome%2Freport",
|
|
cookie: `pipelines_session=remote-${name}`,
|
|
});
|
|
}
|
|
const otherCookie = await f.login();
|
|
assert.notEqual(otherCookie, f.cookie);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.base + "/peers/one/files", {
|
|
headers: { Cookie: otherCookie },
|
|
})
|
|
).status,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await f.register(
|
|
"one",
|
|
{ endpoints: [f.remotes[0]], password: "password-one" },
|
|
f.cookie,
|
|
"http://evil.test",
|
|
)
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await f.register("bad", {
|
|
endpoints: ["ws://user:secret@localhost/connect"],
|
|
})
|
|
).status,
|
|
400,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.base + "/peers/one//evil.test/files", {
|
|
headers: { Cookie: f.cookie },
|
|
})
|
|
).status,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.base + "/peers/one/other", {
|
|
headers: { Cookie: f.cookie },
|
|
})
|
|
).status,
|
|
404,
|
|
);
|
|
assert.equal(
|
|
f.observations.some((x) => x.cookie === f.cookie),
|
|
false,
|
|
);
|
|
});
|
|
|
|
test("file uploads relay to the chosen machine's home folder and other POSTs are refused", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("one", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
});
|
|
const upload = (path, headers = {}) =>
|
|
fetch(f.base + `/peers/one${path}`, {
|
|
method: "POST",
|
|
headers: {
|
|
Cookie: f.cookie,
|
|
"Content-Type": "text/plain",
|
|
"X-Pipelines-Upload-Name": "notes%20two.txt",
|
|
...headers,
|
|
},
|
|
body: "hello upload",
|
|
});
|
|
const reply = await upload("/files?path=%2Fhome%2Fproject");
|
|
assert.equal(reply.status, 200);
|
|
assert.equal(reply.headers.get("set-cookie"), null);
|
|
assert.deepEqual(await reply.json(), {
|
|
name: "one",
|
|
method: "POST",
|
|
url: "/files?path=%2Fhome%2Fproject",
|
|
cookie: "pipelines_session=remote-one",
|
|
upload: "notes%20two.txt",
|
|
type: "text/plain",
|
|
body: "hello upload",
|
|
});
|
|
// The remote never sees a POST the relay does not allow.
|
|
const before = f.observations.length;
|
|
assert.equal((await upload("/artifacts/1/2/report.txt")).status, 404);
|
|
assert.equal((await upload("/discovery")).status, 404);
|
|
assert.equal(f.observations.length, before);
|
|
assert.equal(
|
|
(await upload("/files?path=%2Fhome", { Cookie: await f.login() })).status,
|
|
401,
|
|
);
|
|
});
|
|
|
|
test("websocket relay authenticates the chosen machine without forwarding browser Origin", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("two", {
|
|
endpoints: [f.remotes[1]],
|
|
password: "password-two",
|
|
});
|
|
const result = await new Promise((resolve, reject) => {
|
|
const req = request(
|
|
f.base +
|
|
"/peers/two/connect?endpoint=" +
|
|
encodeURIComponent(f.remotes[1]),
|
|
{
|
|
headers: {
|
|
Cookie: f.cookie,
|
|
Origin: f.base,
|
|
Connection: "Upgrade",
|
|
Upgrade: "websocket",
|
|
"Sec-WebSocket-Key": randomBytes(16).toString("base64"),
|
|
"Sec-WebSocket-Version": "13",
|
|
},
|
|
},
|
|
);
|
|
req.on("upgrade", (res, socket, head) => {
|
|
const receive = (chunk) => {
|
|
socket.destroy();
|
|
resolve({ status: res.statusCode, text: chunk.subarray(2).toString() });
|
|
};
|
|
if (head.length) receive(head);
|
|
else socket.once("data", receive);
|
|
});
|
|
req.on("response", (res) => reject(new Error(String(res.statusCode))));
|
|
req.on("error", reject);
|
|
req.end();
|
|
});
|
|
assert.equal(result.status, 101);
|
|
assert.deepEqual(JSON.parse(result.text), { name: "two" });
|
|
const observed = f.observations.find(
|
|
(x) => x.name === "two" && x.path === "/connect",
|
|
);
|
|
assert.equal(observed.cookie, "pipelines_session=remote-two");
|
|
assert.equal(observed.origin, undefined);
|
|
});
|
|
|
|
test("removing or changing a profile revokes its previous remote route", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("server", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
});
|
|
await f.register("server", {
|
|
endpoints: [f.remotes[1]],
|
|
password: "password-two",
|
|
});
|
|
assert.equal(
|
|
(
|
|
await fetch(
|
|
f.base +
|
|
"/peers/server/files?endpoint=" +
|
|
encodeURIComponent(f.remotes[0]),
|
|
{ headers: { Cookie: f.cookie } },
|
|
)
|
|
).status,
|
|
401,
|
|
);
|
|
const removed = await fetch(f.base + "/api/peers/server", {
|
|
method: "DELETE",
|
|
headers: { Cookie: f.cookie, Origin: f.base },
|
|
});
|
|
assert.equal(removed.status, 200);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.base + "/peers/server/files", {
|
|
headers: { Cookie: f.cookie },
|
|
})
|
|
).status,
|
|
401,
|
|
);
|
|
});
|
|
|
|
test("browser discovery is authenticated and served from the hosting machine", async (t) => {
|
|
const f = await fixture(t);
|
|
assert.equal((await fetch(f.base + "/api/discovery")).status, 401);
|
|
const result = await fetch(f.base + "/api/discovery", {
|
|
headers: { Cookie: f.cookie },
|
|
});
|
|
assert.equal(result.status, 200);
|
|
assert.equal(
|
|
(await result.json()).discovered_servers[0].name,
|
|
"Linux desktop",
|
|
);
|
|
assert.equal(f.observations.filter((x) => x.path === "/discovery").length, 1);
|
|
});
|
|
|
|
test("failed password retry keeps the previous authenticated route and socket", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("one", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
});
|
|
const live = await new Promise((resolve, reject) => {
|
|
const req = request(f.base + "/peers/one/connect", {
|
|
headers: {
|
|
Cookie: f.cookie,
|
|
Origin: f.base,
|
|
Connection: "Upgrade",
|
|
Upgrade: "websocket",
|
|
"Sec-WebSocket-Key": randomBytes(16).toString("base64"),
|
|
"Sec-WebSocket-Version": "13",
|
|
},
|
|
});
|
|
req.on("upgrade", (res, socket) => resolve(socket));
|
|
req.on("response", (res) => reject(new Error(String(res.statusCode))));
|
|
req.on("error", reject);
|
|
req.end();
|
|
});
|
|
t.after(() => live.destroy());
|
|
const failed = await f.register("one", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "wrong-password",
|
|
});
|
|
const status = await failed.json();
|
|
assert.equal(status.previous_connection_kept, true);
|
|
assert.equal(status.needs_password, true);
|
|
const file = await fetch(f.base + "/peers/one/files", {
|
|
headers: { Cookie: f.cookie },
|
|
});
|
|
assert.equal(file.status, 200);
|
|
assert.equal((await file.json()).cookie, "pipelines_session=remote-one");
|
|
assert.equal(live.destroyed, false);
|
|
});
|
|
|
|
test("changed aliases revoke immediately and late sign-in cannot resurrect a deleted profile", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("server", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
});
|
|
const gate = f.hold("two");
|
|
const changing = f.register("server", {
|
|
endpoints: [f.remotes[1]],
|
|
password: "password-two",
|
|
});
|
|
await gate.entered;
|
|
assert.equal(
|
|
(
|
|
await fetch(
|
|
f.base +
|
|
"/peers/server/files?endpoint=" +
|
|
encodeURIComponent(f.remotes[0]),
|
|
{ headers: { Cookie: f.cookie } },
|
|
)
|
|
).status,
|
|
401,
|
|
);
|
|
await fetch(f.base + "/api/peers/server", {
|
|
method: "DELETE",
|
|
headers: { Cookie: f.cookie, Origin: f.base },
|
|
});
|
|
gate.release();
|
|
assert.equal((await changing).status, 409);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.base + "/peers/server/files", {
|
|
headers: { Cookie: f.cookie },
|
|
})
|
|
).status,
|
|
401,
|
|
);
|
|
});
|
|
|
|
test("expired registry owners are closed and pruned before the capacity check", () => {
|
|
const registry = new PeerRegistry((req) => req.token);
|
|
let closed = 0;
|
|
for (let i = 0; i < 256; i++)
|
|
registry.sessions.set(String(i), {
|
|
used: 0,
|
|
versions: new Map(),
|
|
peers: new Map([
|
|
[
|
|
"x",
|
|
{
|
|
sockets: new Set([
|
|
{
|
|
destroy() {
|
|
closed++;
|
|
},
|
|
},
|
|
]),
|
|
},
|
|
],
|
|
]),
|
|
});
|
|
registry.owner({ token: "new-session" });
|
|
assert.equal(closed, 256);
|
|
assert.equal(registry.sessions.size, 1);
|
|
const before = registry.sessions.size;
|
|
registry.forget({ token: "unknown-invalid-session" });
|
|
assert.equal(registry.sessions.size, before);
|
|
});
|
|
|
|
test("raw peer HTML and legacy SVG files retain a local sandbox and no cookie authority", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("one", {
|
|
endpoints: [f.remotes[0]],
|
|
password: "password-one",
|
|
});
|
|
for (const path of [
|
|
"/artifacts/7/2/raw.html",
|
|
"/files?path=%2Fhome%2Funtrusted.svg",
|
|
]) {
|
|
const response = await fetch(f.base + "/peers/one" + path, {
|
|
headers: { Cookie: f.cookie },
|
|
});
|
|
assert.equal(response.status, 200);
|
|
const policy = response.headers.get("content-security-policy");
|
|
for (const directive of [
|
|
"sandbox;",
|
|
"default-src 'none'",
|
|
"script-src 'none'",
|
|
"connect-src 'none'",
|
|
"base-uri 'none'",
|
|
"form-action 'none'",
|
|
"frame-ancestors 'self'",
|
|
]) {
|
|
assert.ok(policy.includes(directive), directive);
|
|
}
|
|
assert.equal(policy.includes("allow-same-origin"), false);
|
|
assert.equal(policy.includes("allow-scripts"), false);
|
|
assert.equal(response.headers.get("x-content-type-options"), "nosniff");
|
|
assert.equal(response.headers.get("cache-control"), "private, no-store");
|
|
assert.equal(response.headers.get("set-cookie"), null);
|
|
if (path.startsWith("/artifacts/"))
|
|
assert.ok(
|
|
policy.includes("img-src 'none'"),
|
|
"stricter remote policy preserved",
|
|
);
|
|
// The response boundary, not text rewriting, isolates generated documents.
|
|
assert.match(await response.text(), /<script>/);
|
|
}
|
|
});
|
|
|
|
test("the relay never forwards a machine's loopback MCP chat-tools endpoint", async (t) => {
|
|
const f = await fixture(t);
|
|
await f.register("one", { endpoints: [f.remotes[0]], password: "password-one" });
|
|
const before = f.observations.length;
|
|
for (const method of ["GET", "POST"]) {
|
|
const reply = await fetch(f.base + "/peers/one/mcp/chat/" + "a".repeat(64), {
|
|
method,
|
|
headers: { Cookie: f.cookie, "Content-Type": "application/json" },
|
|
body: method === "POST" ? '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' : undefined,
|
|
});
|
|
assert.equal(reply.status, 404);
|
|
}
|
|
assert.equal(f.observations.length, before);
|
|
});
|