diff --git a/bun.lock b/bun.lock index c2cc0fb3..84df5eb3 100644 --- a/bun.lock +++ b/bun.lock @@ -104,7 +104,7 @@ "typegpu@0.12.10": "patches/typegpu@0.12.10.patch", }, "overrides": { - "zod": "4.6.5", + "zod": "4.6.6", }, "packages": { "@apm-js-collab/code-transformer": ["@apm-js-collab/code-transformer@0.18.0", "", { "dependencies": { "@types/estree": "^1.0.8", "astring": "^1.9.0", "esquery": "^1.7.0", "meriyah": "^6.1.4", "semifies": "^1.0.0", "source-map": "^0.6.0" }, "bin": { "code-transformer": "cli.js" } }, "sha512-aN3Oq8r1J3gPJtCwErP664gM0+HhM1I1lujPr9TMTCcEl/joQQbpGpeMdts9B1+W2wHMsvioDMv5F4PvMWE6gw=="], @@ -1853,7 +1853,7 @@ "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], - "zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + "zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], diff --git a/migrations/0058_clicks_live_dedupe_ts_index.sql b/migrations/0058_clicks_live_dedupe_ts_index.sql new file mode 100644 index 00000000..b2c07f85 --- /dev/null +++ b/migrations/0058_clicks_live_dedupe_ts_index.sql @@ -0,0 +1,7 @@ +-- #489: the daily dedupe sweep (sweepDedupeIds in src/worker/clicks.ts) asks +-- for clicks that still carry a dedupe id and are older than a day. Through +-- idx_clicks_ts that walks every click older than the cutoff, up to 400 days +-- of history, on each loop. Only about a day of rows ever carries a dedupe id, +-- so an index over just those rows keeps the sweep proportional to what it +-- clears. +CREATE INDEX idx_clicks_live_dedupe_ts ON clicks(ts) WHERE dedupe_id IS NOT NULL; diff --git a/package.json b/package.json index f0b632a6..bb92ff95 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "posthog:upload": "POSTHOG_CLI_PROJECT_ID=${POSTHOG_CLI_PROJECT_ID:-240147} posthog-cli --host ${POSTHOG_CLI_HOST:-https://eu.posthog.com} sourcemap process --directory dist/client/assets --release-name rdyrct --delete-after", "deploy": "bun scripts/deploy.ts", "setup": "bun scripts/setup.ts", + "db:migrate:local": "wrangler d1 migrations apply DB --local", "db:reset:local": "rm -rf .wrangler/state/v3/d1 .wrangler/state/v3/kv && wrangler d1 migrations apply DB --local", "db:seed:local": "NODE_EXTRA_CA_CERTS=\"$HOME/.portless/ca.pem\" bun scripts/seed-local.ts", "check:contrast": "bun scripts/check-contrast.ts", @@ -127,7 +128,7 @@ "wrangler": "^4.156.0" }, "overrides": { - "zod": "4.6.5" + "zod": "4.6.6" }, "packageManager": "bun@1.4.4", "cloudflare": { diff --git a/src/worker/better-auth.ts b/src/worker/better-auth.ts index 29829a99..e779fafa 100644 --- a/src/worker/better-auth.ts +++ b/src/worker/better-auth.ts @@ -276,6 +276,7 @@ function pendingSignUpResponse(email: string, name: string) { polarSubscriptionCancelAtPeriodEnd: false, polarSubscriptionCurrentPeriodEnd: null, polarSubscriptionInterval: null, + lastSeenAt: null, // Never the existing row's id: this account is not the caller's to // learn anything about. Same alphabet and length as better-auth's. id: uid(32), @@ -575,6 +576,10 @@ function buildAuth(env: Env) { input: false, }, polarSubscriptionInterval: { type: "string", required: false, input: false }, + // Read with the session, so withSession can tell an hour-old mark + // from a fresh one without a query of its own (#489). Written only + // by markSeen in session.ts. + lastSeenAt: { type: "number", required: false, input: false }, }, // Self-service account deletion. Authored links/invites keep working // (ON DELETE SET NULL) and memberships cascade. Owned organizations are diff --git a/src/worker/clicks.ts b/src/worker/clicks.ts index 5081ccc3..8296c9a7 100644 --- a/src/worker/clicks.ts +++ b/src/worker/clicks.ts @@ -280,6 +280,16 @@ const DEDUPE_WINDOW_MS = 24 * 60 * 60 * 1000; // this table can exceed D1's statement limits once it is large. const DEDUPE_SWEEP_CHUNK = 1000; +/** + * One chunk of the sweep. `idx_clicks_live_dedupe_ts` (migration 0058) covers + * exactly the rows the inner select asks for, about a day of clicks, so each + * loop reads what it clears and the last, empty loop reads nothing. Through + * `idx_clicks_ts` it walked every click older than the cutoff (#489). + */ +export const DEDUPE_SWEEP_SQL = `update clicks set dedupe_id = null where id in ( + select id from clicks where dedupe_id is not null and ts < ? limit ? +)`; + /** * Clear dedupe ids old enough that no flush retry can still reference them. * @@ -292,11 +302,7 @@ const DEDUPE_SWEEP_CHUNK = 1000; */ export async function sweepDedupeIds(env: Env): Promise { const cutoff = Date.now() - DEDUPE_WINDOW_MS; - const stmt = env.DB.prepare( - `update clicks set dedupe_id = null where id in ( - select id from clicks where dedupe_id is not null and ts < ? limit ? - )`, - ); + const stmt = env.DB.prepare(DEDUPE_SWEEP_SQL); let cleared = 0; let changes = 0; do { diff --git a/src/worker/risk.ts b/src/worker/risk.ts index e8de5086..d83d871d 100644 --- a/src/worker/risk.ts +++ b/src/worker/risk.ts @@ -463,6 +463,51 @@ export async function scoreAndRecord( */ const HOST_VERDICT_TTL_SECONDS = 24 * 60 * 60; +/** + * Links this isolate has already run the per-click update for, keyed by link + * and destination, to the time that run stops counting (#489). + * + * Without it every click on an org link sent D1 an `update` that, for a link + * scored in the last day, changed nothing. The skip has to cost nothing on + * the click path: a D1 read would replace the write it saves, and carrying + * the check time in the link's KV value would mean a KV write per link per + * day. Memory is per isolate, so a link served by many isolates is written by + * each at most once per window, which is what makes a busy link cheap: the + * clicks that cost the most are the ones that land on a warm isolate. + * + * Keyed by link id, with a hash of the destination in the value, so an edit + * (which starts its own scan anyway) never inherits the old destination's + * skip, and an entry costs the same whatever the destination's length. + */ +const recentlyStamped = new Map(); + +/** FNV-1a, 32 bits: only tells one destination from the next for one link, + * so a collision costs at most one skipped stamp until the next window. */ +function destinationHash(url: string): number { + let hash = 0x811c9dc5; + for (let i = 0; i < url.length; i++) { + hash ^= url.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + return hash >>> 0; +} + +/** How long a click that found the row already scored skips the next update. */ +const STAMP_RECHECK_MS = 60 * 60 * 1000; + +/** Bounds the memo: an isolate serving a long tail of links forgets the + * oldest entries rather than growing without limit. */ +const STAMP_MEMO_MAX = 10_000; + +function rememberStamp(linkId: string, destination: number, until: number) { + recentlyStamped.delete(linkId); + recentlyStamped.set(linkId, { until, destination }); + if (recentlyStamped.size > STAMP_MEMO_MAX) { + const oldest = recentlyStamped.keys().next(); + if (!oldest.done) recentlyStamped.delete(oldest.value); + } +} + /** * Re-checks a destination when somebody clicks it, if the answer is stale. * @@ -515,24 +560,40 @@ export async function revalidateOnRedirect( // cold and left every other link pointing at it unscored: the admin // table sorts by that score, so the rest hid in plain sight. // - // The two conditions are what keep this off the hot path in practice: a - // link already carrying this verdict is not written again, and a link - // whose destination has moved on is not relabelled by a KV entry that - // predates the edit. - await env.DB.prepare( + // A link this isolate already stamped with this cached verdict is skipped + // without a statement (#489). A fresh lookup always writes: it is a new + // verdict, and it only happens once a day per host. + const destination = destinationHash(hit.url); + const now = Date.now(); + const stamped = recentlyStamped.get(hit.linkId); + if (cached && stamped && stamped.destination === destination && stamped.until > now) return; + + // The two conditions keep the statement itself cheap: a link already + // carrying this verdict is not written again, and a link whose + // destination has moved on is not relabelled by a KV entry that predates + // the edit. + const result = await env.DB.prepare( `update links set risk_score = ?, risk_reasons = ?, risk_checked_at = ?, risk_provider = ? where id = ? and destination = ? and (risk_checked_at is null or risk_checked_at < ?)`, ) .bind( verdict.score, JSON.stringify(verdict.reasons), - Date.now(), + now, verdict.provider, hit.linkId, stripUtmParams(hit.url), - Date.now() - HOST_VERDICT_TTL_SECONDS * 1000, + now - HOST_VERDICT_TTL_SECONDS * 1000, ) .run(); + // A row this wrote is fresh for the whole TTL, so every click until then + // would be a no-op. One it left alone was scored at some time we did not + // read, inside the last day, so it is only safe to skip for a while. + rememberStamp( + hit.linkId, + destination, + now + (result.meta.changes > 0 ? HOST_VERDICT_TTL_SECONDS * 1000 : STAMP_RECHECK_MS), + ); } catch (error) { logFailure("risk_revalidate_failed", error, { linkId: hit.linkId }); } diff --git a/src/worker/session.ts b/src/worker/session.ts index 4ccb766a..e43fd4e7 100644 --- a/src/worker/session.ts +++ b/src/worker/session.ts @@ -47,18 +47,30 @@ function sessionUserOfRow(row: typeof schema.user.$inferSelect): SessionUser { }; } +/** Who a request is from, and when they were last marked here, so the caller + * can tell whether this request needs to mark them again. */ +interface Caller { + user: SessionUser; + lastSeenAt: number | null; +} + /** A bearer key's owner, resolved to the same shape a session cookie - * produces, plus the key row's id so the caller can bump its last-used mark. */ + * produces, plus the key row's id and last-used mark so the caller can bump + * it. */ async function userFromApiKey( db: DB, authorization: string | undefined, -): Promise<{ keyId: string; user: SessionUser } | null> { +): Promise<(Caller & { keyId: string; keyLastUsedAt: number | null }) | null> { const raw = authorization?.startsWith("Bearer ") ? authorization.slice(7) : null; if (!raw || !raw.startsWith(API_KEY_PREFIX)) return null; const hash = await hashApiKey(raw); const rows = await db - .select({ keyId: schema.apiKeys.id, user: schema.user }) + .select({ + keyId: schema.apiKeys.id, + keyLastUsedAt: schema.apiKeys.lastUsedAt, + user: schema.user, + }) .from(schema.apiKeys) .innerJoin(schema.user, eq(schema.apiKeys.userId, schema.user.id)) .where(and(eq(schema.apiKeys.keyHash, hash), isNull(schema.apiKeys.revokedAt))); @@ -68,7 +80,12 @@ async function userFromApiKey( // entirely, so the same refusal has to happen here. if (!row || row.user.banned) return null; - return { keyId: row.keyId, user: sessionUserOfRow(row.user) }; + return { + keyId: row.keyId, + keyLastUsedAt: row.keyLastUsedAt, + user: sessionUserOfRow(row.user), + lastSeenAt: row.user.lastSeenAt, + }; } /** @@ -92,7 +109,7 @@ async function userFromOAuthToken( env: Env, db: DB, authorization: string | undefined, -): Promise { +): Promise { const raw = authorization?.startsWith("Bearer ") ? authorization.slice(7) : null; if (!raw || raw.startsWith(API_KEY_PREFIX)) return null; @@ -109,7 +126,7 @@ async function userFromOAuthToken( const rows = await db.select().from(schema.user).where(eq(schema.user.id, payload.sub)); const row = rows[0]; if (!row || row.banned) return null; - return sessionUserOfRow(row); + return { user: sessionUserOfRow(row), lastSeenAt: row.lastSeenAt }; } catch { // Not a JWT, an expired one, a bad signature, or the wrong audience: all // the same "not authenticated this way" to the caller. @@ -140,10 +157,29 @@ function sessionUserOf(user: AuthSession["user"]): SessionUser { const SEEN_EVERY_MS = 60 * 60 * 1000; -/** Records that the account was here, at most once an hour: the condition - * makes every other request a read that changes nothing. */ -function markSeen(db: DB, userId: string) { +/** + * How stale an API key's last-used mark may get before a request rewrites it. + * The keys page shows it as a relative date ("2 minutes ago"), so five minutes + * is the most it can lag, for one write per five minutes instead of one per + * call (#489). A key never used before is written at once. + */ +const KEY_USED_EVERY_MS = 5 * 60 * 1000; + +/** Whether a mark last written at `at` is old enough to write again. */ +const due = (at: number | null | undefined, every: number, now: number) => + at == null || at < now - every; + +/** + * Records that the account was here, at most once an hour. + * + * Skipped outright when the mark already loaded with the session is under an + * hour old, so most signed-in requests send D1 nothing at all (#489). The + * condition stays for the requests that do write: two arriving together both + * see an old mark, and only the first changes the row. + */ +function markSeen(db: DB, userId: string, lastSeenAt: number | null | undefined) { const now = Date.now(); + if (!due(lastSeenAt, SEEN_EVERY_MS, now)) return null; return db .update(schema.user) .set({ lastSeenAt: now }) @@ -185,28 +221,34 @@ export function withSession(opts: { oauthTokenPath?: string } = {}) { const session = await getAuth(c.env).api.getSession({ headers: c.req.raw.headers, }); + let caller: Caller | null = null; if (session) { - c.set("user", sessionUserOf(session.user)); + caller = { user: sessionUserOf(session.user), lastSeenAt: session.user.lastSeenAt ?? null }; } else { const authorization = c.req.header("authorization"); const viaKey = await userFromApiKey(db, authorization); if (viaKey) { - c.set("user", viaKey.user); - c.executionCtx.waitUntil( - db - .update(schema.apiKeys) - .set({ lastUsedAt: Date.now() }) - .where(eq(schema.apiKeys.id, viaKey.keyId)), - ); + caller = viaKey; + const now = Date.now(); + if (due(viaKey.keyLastUsedAt, KEY_USED_EVERY_MS, now)) + c.executionCtx.waitUntil( + db + .update(schema.apiKeys) + .set({ lastUsedAt: now }) + .where(eq(schema.apiKeys.id, viaKey.keyId)), + ); } else if (!opts.oauthTokenPath || c.req.path === opts.oauthTokenPath) { - const viaOAuth = await userFromOAuthToken(c.env, db, authorization); - if (viaOAuth) c.set("user", viaOAuth); + caller = await userFromOAuthToken(c.env, db, authorization); } } - // Who made the request, on every API event: ids only, never the email. - const user = c.var.user; - if (user) c.executionCtx.waitUntil(markSeen(db, user.id)); - if (user) c.get("log")?.set({ user: { id: user.id, plan: user.plan, admin: user.isAdmin } }); + if (caller) { + const { user } = caller; + c.set("user", user); + const seen = markSeen(db, user.id, caller.lastSeenAt); + if (seen) c.executionCtx.waitUntil(seen); + // Who made the request, on every API event: ids only, never the email. + c.get("log")?.set({ user: { id: user.id, plan: user.plan, admin: user.isAdmin } }); + } await next(); }); } diff --git a/tests/worker/clicks.worker.ts b/tests/worker/clicks.worker.ts index 82045ee0..6e4e204f 100644 --- a/tests/worker/clicks.worker.ts +++ b/tests/worker/clicks.worker.ts @@ -6,6 +6,7 @@ import { insertClicks, isDeletedLink, sweepDedupeIds, + DEDUPE_SWEEP_SQL, type ClickMessage, } from "../../src/worker/clicks"; import { @@ -231,6 +232,18 @@ describe("sweepDedupeIds (#70)", () => { expect(index?.sql.toLowerCase()).toContain("where dedupe_id is not null"); }); + it("finds what to clear through the live-id index, not the whole click history", async () => { + // Through idx_clicks_ts every loop walked each click older than a day, up + // to 400 days of them, including the last loop that clears nothing (#489). + const plan = await env.DB.prepare(`explain query plan ${DEDUPE_SWEEP_SQL}`) + .bind(Date.now() - DAY_MS, 1000) + .all<{ detail: string }>(); + const details = plan.results.map((row) => row.detail).join("\n"); + + expect(details).toContain("idx_clicks_live_dedupe_ts"); + expect(details).not.toContain("idx_clicks_ts "); + }); + it("clears ids past the retry window and keeps the recent ones", async () => { await seedLink(); await seedClick(1, 30, "dedupe-old"); diff --git a/tests/worker/link-risk.worker.ts b/tests/worker/link-risk.worker.ts index 8e15482f..cec9f5d7 100644 --- a/tests/worker/link-risk.worker.ts +++ b/tests/worker/link-risk.worker.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { env } from "cloudflare:workers"; import { createExecutionContext, reset, waitOnExecutionContext } from "cloudflare:test"; import worker from "../../src/worker"; -import { applyTestMigrations, authEnv, freeOwnerCookie, jsonBody } from "./support"; +import { applyTestMigrations, authEnv, freeOwnerCookie, jsonBody, recordingEnv } from "./support"; import { revalidateOnRedirect, scoreAndRecord } from "../../src/worker/risk"; import type { JsonValue } from "../../src/shared/types"; @@ -203,13 +203,18 @@ describe("re-checking on a click", () => { const clickOn = (linkId: string, url: string) => revalidateOnRedirect(authEnv(), { linkId, orgId: "org-1", url }); - it("records the verdict for the link that was clicked", async () => { + /** A link on BLOCKED that has never been scored. */ + async function unscoredLink() { stubResolver(); - const cookie = await freeOwnerCookie(); - const linkId = await createLink(cookie, BLOCKED); + const linkId = await createLink(await freeOwnerCookie(), BLOCKED); await env.DB.prepare("update links set risk_checked_at = null, risk_score = null where id = ?") .bind(linkId) .run(); + return linkId; + } + + it("records the verdict for the link that was clicked", async () => { + const linkId = await unscoredLink(); await clickOn(linkId, BLOCKED); @@ -246,6 +251,38 @@ describe("re-checking on a click", () => { expect((await riskRow(second))?.risk_score).toBe(100); }); + it("sends D1 nothing for a second click on a link already stamped (#489)", async () => { + // The update's own condition made this a no-op, but it was still one D1 + // statement per click on every org link. + const linkId = await unscoredLink(); + await clickOn(linkId, BLOCKED); + expect((await riskRow(linkId))?.risk_score).toBe(100); + + const recording = recordingEnv(); + await revalidateOnRedirect(recording.env, { linkId, orgId: "org-1", url: BLOCKED }); + + expect(recording.sql).toEqual([]); + }); + + it("still stamps a link whose destination changed after its last click", async () => { + // The skip is keyed by destination too: an edit must not inherit it. + stubResolver(); + const cookie = await freeOwnerCookie(); + const firstUrl = "https://malware.example/before"; + const secondUrl = "https://malware.example/after"; + const linkId = await createLink(cookie, firstUrl); + await clickOn(linkId, firstUrl); + await env.DB.prepare( + "update links set destination = ?, risk_checked_at = null, risk_score = null where id = ?", + ) + .bind(secondUrl, linkId) + .run(); + + await clickOn(linkId, secondUrl); + + expect((await riskRow(linkId))?.risk_score).toBe(100); + }); + it("leaves a link alone when its destination has moved on", async () => { // KV can hold a redirect that predates an edit, and a click on it must // not label the new destination with the old one's verdict. diff --git a/tests/worker/request-writes.worker.ts b/tests/worker/request-writes.worker.ts new file mode 100644 index 00000000..126fd27a --- /dev/null +++ b/tests/worker/request-writes.worker.ts @@ -0,0 +1,154 @@ +import { env } from "cloudflare:workers"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { reset } from "cloudflare:test"; +import { + applyTestMigrations, + fetchWorker, + freeOwnerCookie, + jsonBody, + recordingEnv, +} from "./support"; +import type { ApiKeyDTO } from "../../src/shared/types"; + +/** + * What a signed-in request writes to D1 on its way through withSession + * (#489). Every request used to queue an update of the account's last-seen + * mark, and every API-key request an update of the key's last-used mark, + * whether or not either had anything to change. The marks are read with the + * caller, so a fresh one now means no statement at all. + */ + +const HOUR_MS = 60 * 60 * 1000; + +const seenWrites = (sql: string[]) => + sql.filter((q) => q.startsWith('update "user"') && q.includes('"last_seen_at"')); +const keyWrites = (sql: string[]) => sql.filter((q) => q.startsWith('update "api_keys"')); + +async function setLastSeen(at: number | null) { + await env.DB.prepare("update user set last_seen_at = ? where id = 'free-1'").bind(at).run(); +} + +async function lastSeen() { + const row = await env.DB.prepare("select last_seen_at from user where id = 'free-1'").first<{ + last_seen_at: number | null; + }>(); + return row?.last_seen_at ?? null; +} + +describe("withSession's last-seen and last-used marks (#489)", () => { + beforeEach(applyTestMigrations); + afterEach(reset); + + describe("a session cookie", () => { + async function getUser(cookie: string) { + const recording = recordingEnv(); + const res = await fetchWorker( + new Request("http://localhost/api/user", { headers: { cookie } }), + recording.env, + ); + expect(res.status).toBe(200); + return recording.sql; + } + + it("marks an account never seen before", async () => { + const cookie = await freeOwnerCookie(); + await setLastSeen(null); + + expect(seenWrites(await getUser(cookie))).toHaveLength(1); + expect(await lastSeen()).toBeGreaterThan(Date.now() - HOUR_MS); + }); + + it("sends no write when the mark is under an hour old", async () => { + const cookie = await freeOwnerCookie(); + const recent = Date.now() - HOUR_MS / 2; + await setLastSeen(recent); + + expect(seenWrites(await getUser(cookie))).toHaveLength(0); + expect(await lastSeen()).toBe(recent); + }); + + it("writes again once the mark is over an hour old", async () => { + const cookie = await freeOwnerCookie(); + const stale = Date.now() - 2 * HOUR_MS; + await setLastSeen(stale); + + expect(seenWrites(await getUser(cookie))).toHaveLength(1); + expect(await lastSeen()).toBeGreaterThan(stale); + }); + }); + + describe("an API key", () => { + async function mintKey() { + const cookie = await freeOwnerCookie(); + const minted = await fetchWorker( + new Request("http://localhost/api/orgs/org-1/api-keys", { + method: "POST", + headers: { cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "connector" }), + }), + ); + expect(minted.status).toBe(201); + return jsonBody(minted); + } + + async function useKey(key: ApiKeyDTO) { + const recording = recordingEnv(); + const res = await fetchWorker( + new Request("http://localhost/api/orgs/org-1/links", { + headers: { authorization: `Bearer ${key.key}` }, + }), + recording.env, + ); + expect(res.status).toBe(200); + return recording.sql; + } + + async function setLastUsed(id: string, at: number | null) { + await env.DB.prepare("update api_keys set last_used_at = ? where id = ?").bind(at, id).run(); + } + + async function lastUsed(id: string) { + const row = await env.DB.prepare("select last_used_at from api_keys where id = ?") + .bind(id) + .first<{ last_used_at: number | null }>(); + return row?.last_used_at ?? null; + } + + it("records a key's first use at once", async () => { + const key = await mintKey(); + + expect(keyWrites(await useKey(key))).toHaveLength(1); + expect(await lastUsed(key.id)).toBeGreaterThan(Date.now() - HOUR_MS); + }); + + it("sends no write for a key used in the last five minutes", async () => { + const key = await mintKey(); + const recent = Date.now() - 60 * 1000; + await setLastUsed(key.id, recent); + await setLastSeen(Date.now()); + + const sql = await useKey(key); + + expect(keyWrites(sql)).toHaveLength(0); + // The account was seen a moment ago too, so the request writes nothing. + expect(seenWrites(sql)).toHaveLength(0); + expect(await lastUsed(key.id)).toBe(recent); + }); + + it("writes again once the mark is over five minutes old", async () => { + const key = await mintKey(); + const stale = Date.now() - 10 * 60 * 1000; + await setLastUsed(key.id, stale); + + expect(keyWrites(await useKey(key))).toHaveLength(1); + expect(await lastUsed(key.id)).toBeGreaterThan(stale); + }); + + it("marks the key's account as seen, through the row the key was read with", async () => { + const key = await mintKey(); + await setLastSeen(Date.now() - 2 * HOUR_MS); + + expect(seenWrites(await useKey(key))).toHaveLength(1); + }); + }); +}); diff --git a/tests/worker/support.ts b/tests/worker/support.ts index bb19a6d6..a8763c89 100644 --- a/tests/worker/support.ts +++ b/tests/worker/support.ts @@ -213,6 +213,21 @@ export function overriding(target: T, overrides: Partial): }); } +/** + * authEnv() with every SQL string the Worker prepares recorded, lowercased, + * in `sql`: how a test proves a path sent D1 nothing (#489). + */ +export function recordingEnv() { + const sql: string[] = []; + const db = overriding(env.DB, { + prepare(query: string) { + sql.push(query.toLowerCase()); + return env.DB.prepare(query); + }, + }); + return { env: overrideEnv({ ...authEnv(), DB: db }), sql }; +} + /** The single ClickBuffer instance the redirect path writes to (#225). Its * add/alarm/buffered/reset methods are callable straight off the stub as RPC. */ export function clicksStub(): DurableObjectStub {