fix(logging): keep reviewers unlinkable, look admin users up by explicit id

- Requests carry userId on warn and error records only. The app calls
  /api/user on every page load, so a userId on routine info records sat
  next to the repoId a signed-in reviewer opened, and timestamps linked
  them. Jobs keep it at every level. Logger, collector and the admin
  projection apply the same rule.
- Admin user routes take an _id only as id:<_id>; a 24-hex GitHub login
  can no longer match another account's _id for ban or promote.
- The download-job expectation includes the owner id the PR adds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-29 13:08:19 +00:00
1 parent c281841f91
commit d8a777cd35
8 files changed
+58 -20

No files matched your search

+5 -2
View File
@@ -82,7 +82,8 @@ if includes(["/", "other", "/dashboard", "/anonymize", "/healthcheck", "/api/hea
}
# Public anonymized project IDs, the viewer role and the internal user _id.
# Same double-blind rule as src/core/log-context.ts logIdentity: on
# anonymized-content routes userId is kept only for owner/coauthor/admin.
# anonymized-content routes userId is kept only for owner/coauthor/admin, and
# requests keep it on warn and error records only (jobs at every level).
if includes(["api", "streamer"], service) {
log_route = string(out.route) ?? ""
# Upstream lookups (/api/repo/:owner/:repo) carry an owner name, never a repoId,
@@ -98,7 +99,9 @@ if includes(["api", "streamer"], service) {
privileged = includes(["owner", "coauthor", "admin"], record.viewer)
anonymized_route = service == "streamer" || match(log_route, r'^/(?:api/repo/:(?:repoId|id)(?:/|$)|r/|w/|viewer/|api/pr/|api/gist/)')
account_route = includes(["/dashboard", "/anonymize", "/profile", "/api/repo", "/api/anonymize-preview", "/api/conferences/plans", "/conference/:id", "/github/:action"], log_route) || match(log_route, r'^/api/(?:user|billing|admin)(?:/|$)') || match(log_route, r'^/api/repo/:owner/:repo(?:/|$)')
keep_user = if has_viewer || anonymized_route { privileged } else { account_route || (log_route == "" && out.service == "worker") }
is_job = log_route == "" && out.service == "worker"
keep_user = if has_viewer || anonymized_route { privileged } else { account_route || is_job }
keep_user = keep_user && (is_job || includes(["warn", "error"], record.severity))
if keep_user { out.userId = record.userId }
}
}
+1 -1
View File
@@ -244,7 +244,7 @@
</div>
<div class="aside-block" v-if="row?._userId">
<div class="aside-label">User<span class="aside-sub" v-if="row?._viewer"> · {{ row?._viewer }}</span></div>
<a class="aside-value mono" :href="safeUrl(&quot;/admin/users/&quot; + (row?._userId))">{{ row?._userId }}</a>
<a class="aside-value mono" :href="safeUrl(&quot;/admin/users/id:&quot; + (row?._userId))">{{ row?._userId }}</a>
</div>
<div class="aside-block" v-else-if="row?._viewer">
<div class="aside-label">Viewer</div>
+10 -4
View File
@@ -51,8 +51,14 @@ export function setLogContext(fields: Pick<LogContext, "repoId" | "pullRequestId
* the project's owner, a co-author or an admin. Visitors and anonymous readers
* get a viewer label and no userId. Requests on any other route (assets,
* "other", webhooks) get no userId.
*
* Requests carry userId on warn and error records only. The app calls
* /api/user on every page load, so a userId on routine info records would sit
* milliseconds before the repoId of the anonymized page a signed-in reviewer
* opens, and matching timestamps would tell who reviewed what. Jobs are the
* owner's own work and keep it at every level.
*/
export function logIdentity(context: LogContext, details: Record<string, unknown> = {}) {
export function logIdentity(context: LogContext, details: Record<string, unknown> = {}, level?: string) {
const out: Record<string, string> = {};
const { route, service, viewer, userId } = context;
// Upstream lookups (/api/repo/:owner/:repo) put an owner name where a repoId would sit.
@@ -64,9 +70,9 @@ export function logIdentity(context: LogContext, details: Record<string, unknown
if (validViewer(viewer)) out.viewer = viewer;
if (validUserId(userId)) {
const privileged = validViewer(viewer) && PRIVILEGED_VIEWERS.includes(viewer);
const visible = validViewer(viewer) || anonymizedRoute(route, service) ? privileged
: accountRoute(route) || (route === undefined && service === "worker");
if (visible) out.userId = userId;
const job = route === undefined && service === "worker";
const visible = validViewer(viewer) || anonymizedRoute(route, service) ? privileged : accountRoute(route) || job;
if (visible && (job || level === "warn" || level === "error")) out.userId = userId;
}
return out;
}
+1 -1
View File
@@ -78,7 +78,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
if (context.method && allowed(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "OTHER"], context.method)) record.method = context.method;
Object.assign(record, safeDiagnosticFields(details));
// Validated public project IDs, viewer role and, where allowed, the internal user _id.
Object.assign(record, logIdentity(context, details));
Object.assign(record, logIdentity(context, details, level));
// Anonymous request paths are diagnostic fields, never metric labels.
const requestPath = safeReproductionPath(context.requestPath || details.requestPath, record.method);
if (requestPath) Object.assign(record, requestReproduction(requestPath, record.method));
+6 -3
View File
@@ -1207,9 +1207,12 @@ router.get("/users", async (req, res) => {
res.json({ query: filter, page, total, sort, results, statusCounts });
});
// Log records carry the internal user _id, never the username; accept either.
function adminUserFilter(param: string) {
return /^[a-f0-9]{24}$/.test(param) ? { $or: [{ username: param }, { _id: param }] } : { username: param };
// Log records carry the internal user _id, never the username. An _id is
// asked for explicitly as "id:<_id>": a GitHub login can also be 24 hex
// characters, and ban or promote must never hit a different account.
export function adminUserFilter(param: string) {
const id = /^id:([a-f0-9]{24})$/.exec(param);
return id ? { _id: id[1] } : { username: param };
}
router.get(
+14
View File
@@ -0,0 +1,14 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const { adminUserFilter } = require("../src/server/routes/admin");
describe("admin user lookup", () => {
it("looks a user up by _id only when asked with id:", () => {
const hex = "0123456789abcdef01234567";
// A 24-hex GitHub login is a username, never another account's _id.
expect(adminUserFilter(hex)).to.deep.equal({ username: hex });
expect(adminUserFilter("id:" + hex)).to.deep.equal({ _id: hex });
expect(adminUserFilter("id:not-an-id")).to.deep.equal({ username: "id:not-an-id" });
expect(adminUserFilter("alice")).to.deep.equal({ username: "alice" });
});
});
+1 -1
View File
@@ -363,7 +363,7 @@ const uri = process.env.PERFORMANCE_MONGO_URI;
expect(await File.countDocuments({ repoId: row.repoId })).to.equal(0); expect(await Path.countDocuments({ repoId: row.repoId })).to.equal(0);
expect(jobs).to.have.length(1);
const { logJobId, ...jobData } = jobs[0][1];
expect(jobData).to.deep.equal({ repoId: row.repoId }); expect(logJobId).to.match(/^[a-f0-9-]{36}$/);
expect(jobData).to.deep.equal({ repoId: row.repoId, ownerId: String(row.owner) }); expect(logJobId).to.match(/^[a-f0-9-]{36}$/);
});
for (const [label, change] of [...changedSnapshots, ["settings revision", { settingsSavedAt: new Date(1) }]] ) {
+20 -8
View File
@@ -44,12 +44,19 @@ describe("log identity context", function () {
expect(logIdentity({ route: "other", service: "api", userId: VISITOR })).to.deep.equal({});
expect(logIdentity({ service: "streamer", userId: VISITOR })).to.deep.equal({});
for (const viewer of ["owner", "coauthor", "admin"]) {
expect(logIdentity({ route, service: "api", repoId: "r123", userId: OWNER, viewer }))
expect(logIdentity({ route, service: "api", repoId: "r123", userId: OWNER, viewer }, {}, "warn"))
.to.deep.equal({ repoId: "r123", userId: OWNER, viewer });
}
// Account routes record the signed-in user; jobs record the owner.
expect(logIdentity({ route: "/api/user/:action", service: "api", userId: OWNER })).to.deep.equal({ userId: OWNER });
expect(logIdentity({ route: "/api/billing/checkout", service: "api", userId: OWNER })).to.deep.equal({ userId: OWNER });
expect(logIdentity({ route: "/api/user/:action", service: "api", userId: OWNER }, {}, "error")).to.deep.equal({ userId: OWNER });
expect(logIdentity({ route: "/api/billing/checkout", service: "api", userId: OWNER }, {}, "warn")).to.deep.equal({ userId: OWNER });
// Routine request records never carry userId: the /api/user call on every
// page load would otherwise be matched by time to the repoId a reviewer opens.
for (const level of ["info", "debug", undefined]) {
expect(logIdentity({ route: "/api/user", service: "api", userId: OWNER }, {}, level)).to.deep.equal({});
expect(logIdentity({ route: "/api/repo/:repoId/files", service: "api", repoId: "r123", userId: OWNER, viewer: "owner" }, {}, level))
.to.deep.equal({ repoId: "r123", viewer: "owner" });
}
expect(logIdentity({ service: "worker", userId: OWNER, repoId: "r123" })).to.deep.equal({ repoId: "r123", userId: OWNER });
// Logger arguments cannot inject identities; only a repoId in a job or on an anonymized route.
const injected = { userId: OWNER, gistId: "upstream-gist", viewer: "owner", repoId: "r999" };
@@ -66,7 +73,7 @@ describe("log identity context", function () {
logRequestUser(req, {}, () => undefined);
if (owner !== undefined) logProjectViewer(req, owner, coauthor);
});
return logIdentity(store);
return logIdentity(store, {}, "warn");
};
expect(viewer({}, undefined)).to.deep.equal({ viewer: "anonymous" });
expect(viewer(sessionReq(VISITOR), undefined)).to.deep.equal({ viewer: "visitor" });
@@ -77,7 +84,7 @@ describe("log identity context", function () {
// Account routes get the user without a viewer label.
const account = { route: "/dashboard", service: "api" };
logContext.run(account, () => logRequestUser(sessionReq(OWNER), {}, () => undefined));
expect(logIdentity(account)).to.deep.equal({ userId: OWNER });
expect(logIdentity(account, {}, "warn")).to.deep.equal({ userId: OWNER });
});
it("puts identity set by a handler after next() on the request-completed record", async () => {
@@ -106,10 +113,11 @@ describe("log identity context", function () {
} finally { server.close(); }
const pick = (r) => ({ event: r.event, repoId: r.repoId, userId: r.userId, viewer: r.viewer });
expect(records.map(pick)).to.deep.equal([
{ event: "request_completed", repoId: "abc123", userId: OWNER, viewer: "owner" },
// Info records carry no userId, even for the owner (see logIdentity).
{ event: "request_completed", repoId: "abc123", userId: undefined, viewer: "owner" },
{ event: "request_completed", repoId: "abc123", userId: undefined, viewer: "visitor" },
{ event: "request_completed", repoId: "abc123", userId: undefined, viewer: "anonymous" },
{ event: "request_completed", repoId: undefined, userId: OWNER, viewer: undefined },
{ event: "request_completed", repoId: undefined, userId: undefined, viewer: undefined },
]);
expect(JSON.stringify(records[1])).not.to.include(VISITOR);
});
@@ -182,7 +190,7 @@ describe("log identity context", function () {
const image = fs.readFileSync(path.join(__dirname, "..", "deploy/logging/compose.yml"), "utf8").match(/image: (timberio\/vector:[^\s]+)/)[1];
const probe = spawnSync("docker", ["image", "inspect", image.split("@")[0]], { stdio: "ignore" });
if (probe.error || probe.status !== 0) this.skip();
const base = { timestamp: new Date().toISOString(), severity: "info", event: "request_completed", module: "requests", method: "GET" };
const base = { timestamp: new Date().toISOString(), severity: "warn", event: "request_completed", module: "requests", method: "GET" };
const records = [
{ ...base, service: "api", route: "/api/repo/:repoId/files", repoId: "my-repo", viewer: "owner", userId: OWNER },
{ ...base, service: "api", route: "/api/repo/:repoId/files", repoId: "my-repo", viewer: "visitor", userId: VISITOR },
@@ -191,6 +199,8 @@ describe("log identity context", function () {
{ ...base, service: "worker", userId: OWNER, repoId: "bad/id", gistId: "g-123", viewer: "reviewer" },
{ ...base, service: "api", route: "other", userId: VISITOR },
{ ...base, service: "api", route: "/api/repo/:owner/:repo/readme", repoId: "private-owner", userId: OWNER },
{ ...base, severity: "info", service: "api", route: "/api/user", userId: OWNER },
{ ...base, severity: "info", service: "worker", userId: OWNER },
];
const input = records.map((r) => JSON.stringify({ file: "/host/docker/x/log.json", message: JSON.stringify({ attrs: { tag: "api" }, log: JSON.stringify(r) }) })).join("\n") + "\n";
const run = spawnSync("docker", ["run", "--rm", "-i", "--network", "none", "--memory", "256m", image.split("@")[0], "vrl", "-i", "/dev/stdin", vrl + "\nencode_json(.)"], { input, encoding: "utf8", timeout: 60000 });
@@ -205,6 +215,8 @@ describe("log identity context", function () {
{ repoId: undefined, gistId: "g-123", userId: OWNER, viewer: undefined },
{ repoId: undefined, gistId: undefined, userId: undefined, viewer: undefined },
{ repoId: undefined, gistId: undefined, userId: OWNER, viewer: undefined },
{ repoId: undefined, gistId: undefined, userId: undefined, viewer: undefined },
{ repoId: undefined, gistId: undefined, userId: OWNER, viewer: undefined },
]);
});
});