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
6 changes: 6 additions & 0 deletions pm-stack/console/edge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts
There is no shared secret, here or in the repository. A report is
refused unless the signature verifies, its time is within two minutes
of the edge's clock, and it is later than the last one accepted.
The path is open to anyone, since the laptop cannot sign in, and a
report may be megabytes: one that says it is too large, or is not
shaped like a report, is refused without being read, and an address
with twenty refused reports in a minute is refused unread until the
minute is out. A report the laptop signed that is merely wrong (an
old clock, a replay) is not held against its address.
- **A phone** is whoever holds a token the edge issued after the owner
approved it. The edge keeps only the token's hash.
- **The laptop trusts the edge** for one thing: the held actions in the
Expand Down
56 changes: 46 additions & 10 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { actions, type Action, ownActions } from "../../src/actions.ts";
import { AuthError, type Identity, identify } from "../../src/auth.ts";
import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from "./direct.ts";
import { Devices, Limiter } from "../../src/devices.ts";
import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts";
import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts";
import {
type EdgeConfig,
Expand Down Expand Up @@ -80,6 +80,11 @@ const WATCHED = ["board", "asks", "census", "sessions", "questionCount", "servic
/** One stored value holds at most this many characters of a section. */
const CHUNK = 600_000;
const SYNC_LIMIT = 8 * 1024 * 1024;
/** A report's signature: 64 bytes, as unpadded base64url. */
const SIGNATURE = /^[A-Za-z0-9_-]{86}$/;
/** Reports from one address that may fail their checks in a minute
* before that address is refused unread. The host's own never fail. */
const SYNC_REFUSALS = 20;
const ACT_LIMIT = 256 * 1024;
const HELD_MAX = 100;
const ACTS_KEPT = 30;
Expand Down Expand Up @@ -165,6 +170,8 @@ export class Edge {
private confirmed: Record<string, { hash: string; at: number; error: string | null }> = {};
private sure = 0;
private unsure = 0;
private hostVersion: string | null = null;
private syncRefused: KeyedLimiter;
readonly docs: Docs;
readonly push: Push;
readonly phones: Phones;
Expand All @@ -177,6 +184,7 @@ export class Edge {
this.fetchImpl = options.fetchImpl ?? fetch;
this.direct = options.direct;
this.setAlarm = options.setAlarm ?? (async () => {});
this.syncRefused = new KeyedLimiter(SYNC_REFUSALS, 60_000, this.now);
this.docs = new Docs(
Object.fromEntries(
Object.entries(SECTIONS).map(([name, ttlMs]) => [
Expand Down Expand Up @@ -317,11 +325,17 @@ export class Edge {
if (this.ownActs === null) await this.showActs();
if (this.hostSeen === null) {
const host = (await this.kv.get("host")) as
| { seen: number; seq: number; confirmed?: Record<string, { hash: string; at: number; error: string | null }> }
| {
seen: number;
seq: number;
confirmed?: Record<string, { hash: string; at: number; error: string | null }>;
version?: string | null;
}
| undefined;
this.hostSeen = host?.seen ?? 0;
this.hostSeq = host?.seq ?? 0;
this.confirmed = host?.confirmed ?? {};
this.hostVersion = host?.version ?? null;
}
}

Expand Down Expand Up @@ -506,24 +520,43 @@ export class Edge {
}

private async sync(req: Request): Promise<Response> {
if (Number(req.headers.get("content-length") ?? "0") > SYNC_LIMIT) return json({ error: "too large" }, 413);
const body = new Uint8Array(await req.arrayBuffer());
if (body.byteLength > SYNC_LIMIT) return json({ error: "too large" }, 413);
// The laptop cannot sign in, so this path is open to anyone, and a
// report may be megabytes. Every report that fails a check below
// counts against the address it came from, and an address with too
// many is refused here, before its body is read.
const from = req.headers.get("cf-connecting-ip") ?? "unknown";
if (this.syncRefused.blocked(from)) {
return json({ error: "too many reports from this address were not the host's; try again in a minute" }, 429);
}
const refuse = (body: unknown, status: number) => {
this.syncRefused.count(from);
return json(body, status);
};
// Too large by its own account, or not shaped like a report: refused unread.
if (Number(req.headers.get("content-length") ?? "0") > SYNC_LIMIT) return refuse({ error: "too large" }, 413);
const kid = req.headers.get("x-pm-key") ?? "";
const signature = req.headers.get("x-pm-signature") ?? "";
if (kid === "" || !SIGNATURE.test(signature)) {
return refuse({ error: "this is not signed with the host's key" }, 401);
}
const key = (await this.kv.get("key")) as { kid: string; jwk: PublicKey } | undefined;
const now = this.now();
if (!key || key.kid !== kid) {
// A key this side has not seen: ask the host for its key, but not
// on every stranger's request.
// on every stranger's request. Nothing has been read yet.
if (req.headers.get("x-pm-key-fetched") === "1" || now - this.lastKeyFetch < KEY_FETCH_EVERY_MS) {
return json({ error: "this is not signed with the host's key" }, 401);
return refuse({ error: "this is not signed with the host's key" }, 401);
}
this.lastKeyFetch = now;
return next("key", {});
}
if (!(await verify(key.jwk, body, req.headers.get("x-pm-signature") ?? ""))) {
return json({ error: "this is not signed with the host's key" }, 401);
const body = new Uint8Array(await req.arrayBuffer());
if (body.byteLength > SYNC_LIMIT) return refuse({ error: "too large" }, 413);
if (!(await verify(key.jwk, body, signature))) {
return refuse({ error: "this is not signed with the host's key" }, 401);
}
// Signed by the host from here on: what is wrong with it is the
// host's to hear about, and is not held against the address.
let msg: SyncRequest;
try {
msg = JSON.parse(new TextDecoder().decode(body)) as SyncRequest;
Expand Down Expand Up @@ -613,7 +646,8 @@ export class Edge {
// current it says each section is.
this.hostSeen = now;
this.hostSeq = msg.at;
await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed });
this.hostVersion = typeof msg.version === "string" && /^[0-9a-f]{7,40}$/.test(msg.version) ? msg.version : null;
await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed, version: this.hostVersion });
if (wasSilent) {
try {
const delivery = await this.push.send("trouble", {
Expand Down Expand Up @@ -705,6 +739,8 @@ export class Edge {
directReady: this.directCapable() && this.directConfigReady(cfg),
selfCheck: this.selfCheckResult,
hostSeen: this.hostSeen || null,
// The commit the host's console is running, as it last said.
hostVersion: this.hostVersion,
// Since this object last started: requests it answered as the
// owner's, and requests it left to the host to judge.
answered: this.sure,
Expand Down
39 changes: 39 additions & 0 deletions pm-stack/console/src/devices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,45 @@ export class Limiter {
}
}

/** A limit counted apart for each sender: at most `max` in each window
* for one key. Senders not heard from lately are forgotten, so the table
* stays small whatever arrives. */
export class KeyedLimiter {
private seen = new Map<string, { start: number; used: number }>();

constructor(
private max: number,
private windowMs: number,
private now: () => number = Date.now,
private keys = 2000,
) {}

/** Count one against this key. */
count(key: string): void {
const t = this.now();
const entry = this.seen.get(key);
if (entry && t - entry.start < this.windowMs) {
entry.used++;
return;
}
if (this.seen.size >= this.keys) {
// Make room: first whatever has run out, then the oldest.
for (const [k, v] of this.seen) if (t - v.start >= this.windowMs) this.seen.delete(k);
for (const k of this.seen.keys()) {
if (this.seen.size < this.keys) break;
this.seen.delete(k);
}
}
this.seen.set(key, { start: t, used: 1 });
}

/** True once this key has used up its allowance for the window it is in. */
blocked(key: string): boolean {
const entry = this.seen.get(key);
return entry !== undefined && this.now() - entry.start < this.windowMs && entry.used >= this.max;
}
}

export class Devices {
private store: Store | null = null;

Expand Down
4 changes: 4 additions & 0 deletions pm-stack/console/src/edge-proto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export interface SyncRequest {
v: 1;
/** Milliseconds, later than every sync before it. */
at: number;
/** The commit the host's console is running. The edge says it in its
* health answer, so whether a merge has reached the host can be seen
* from anywhere, without reaching the host. */
version?: string;
config: EdgeConfig;
/** Sections that changed since the edge last had them. */
sections: SyncSection[];
Expand Down
17 changes: 17 additions & 0 deletions pm-stack/console/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,22 @@ export function marked(res: Response): Response {
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
}

/** The commit this console was started from, or nothing if it cannot
* be told (not a checkout, no git). The service is restarted when a
* merge is put into service, so this is the code that is running. */
async function runningCommit(): Promise<string | undefined> {
try {
const git = Bun.spawn(["git", "-C", import.meta.dir, "rev-parse", "--short=12", "HEAD"], {
stdout: "pipe",
stderr: "ignore",
});
const said = (await new Response(git.stdout).text()).trim();
return (await git.exited) === 0 && /^[0-9a-f]{12}$/.test(said) ? said : undefined;
} catch {
return undefined;
}
}

if (import.meta.main) {
// `--check` builds everything this service needs and stops before
// listening: what a redeploy runs to learn that new code starts.
Expand Down Expand Up @@ -571,6 +587,7 @@ if (import.meta.main) {
const link = cfg.edgeUrl
? new EdgeLink({
url: cfg.edgeUrl,
version: await runningCommit(),
keys: fileStore(cfg.edgeKeyFile),
done: fileStore(cfg.edgeDoneFile),
docs,
Expand Down
3 changes: 3 additions & 0 deletions pm-stack/console/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export interface LinkOptions {
config: () => Promise<EdgeConfig>;
/** Run one held action; throws if it could not be done. */
run: (held: Held) => Promise<void>;
/** The commit this console is running, if it could be found. */
version?: string;
fetchImpl?: typeof fetch;
now?: () => number;
log?: (line: string) => void;
Expand Down Expand Up @@ -186,6 +188,7 @@ export class EdgeLink {
const message: SyncRequest & { acts: unknown } = {
v: 1,
at,
...(this.o.version ? { version: this.o.version } : {}),
config: await this.o.config(),
sections,
have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])),
Expand Down
36 changes: 35 additions & 1 deletion pm-stack/console/test/devices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { join } from "node:path";
import { actions, perform } from "../src/actions.ts";
import { AuthError } from "../src/auth.ts";
import { readConfig } from "../src/config.ts";
import { challengeOf, Devices, Limiter, summary } from "../src/devices.ts";
import { challengeOf, Devices, KeyedLimiter, Limiter, summary } from "../src/devices.ts";
import { Docs } from "../src/docs.ts";
import { fileStore } from "../src/file-store.ts";
import { OpError, Ops } from "../src/ops.ts";
Expand Down Expand Up @@ -588,3 +588,37 @@ describe("over HTTP, without the sign-in", () => {
}
});
});

test("a limit kept apart for each sender forgets old senders and never grows past its table", () => {
const now = { t: 1_000_000 };
const limit = new KeyedLimiter(3, 60_000, () => now.t, 4);
// Under the allowance: not blocked. At it: blocked, for that key only.
limit.count("a");
limit.count("a");
expect(limit.blocked("a")).toBe(false);
limit.count("a");
expect(limit.blocked("a")).toBe(true);
expect(limit.blocked("b")).toBe(false);
// The window is the key's own, from its first count.
now.t += 59_999;
expect(limit.blocked("a")).toBe(true);
now.t += 1;
expect(limit.blocked("a")).toBe(false);
limit.count("a");
expect(limit.blocked("a")).toBe(false);
// A full table makes room: what has run out goes first, then the oldest.
for (const key of ["b", "c", "d"]) {
limit.count(key);
limit.count(key);
limit.count(key);
}
expect(["a", "b", "c", "d"].map((key) => limit.blocked(key))).toEqual([false, true, true, true]);
limit.count("e");
limit.count("f");
// "a" and "b" were the oldest: forgotten, so no longer blocked; the newest are counted.
expect(limit.blocked("b")).toBe(false);
expect(limit.blocked("d")).toBe(true);
limit.count("f");
limit.count("f");
expect(limit.blocked("f")).toBe(true);
});
Loading