feat(logging): record repository, user and viewer on log records

Handlers that resolve an anonymized repository, pull request or gist now
put its public ID on the log context, so request, job and error records
carry repoId, pullRequestId or gistId. The signed-in user's internal _id
(userId) is recorded on account routes. On routes that serve anonymized
content, userId is kept only when the user owns, co-authors or
administers the project; otherwise the record carries viewer "visitor"
or "anonymous" and no userId. The collector, the Redis mirror and the
admin log APIs apply the same rule. Jobs carry repoId and the owner's
userId stamped at enqueue time.

The admin Errors page links repoId to the admin repository search and
userId to the admin user page, which now accepts a user _id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-29 12:36:09 +00:00
1 parent 2f38fc6a51
commit 86a35d62f1
22 files changed
+474 -70

No files matched your search

+9 -3
View File
@@ -1,7 +1,8 @@
import { createHash } from "crypto";
import { logRecord, LOG_NUMBERS, LOG_STAGES } from "../core/log-record";
import { logContext, validTraceId } from "../core/log-context";
import { LogContext, logContext, validTraceId } from "../core/log-context";
import { LOG_EVENTS } from "../core/log-schema";
import { LOG_ROUTES } from "../core/log-diagnostic-schema";
const services = ["api", "streamer", "worker", "nginx", "mongodb", "redis", "backup"];
const events = new Set([...Object.values(LOG_EVENTS), "deployment", "application_log", "webhook_log", "request_completed", "request_slow", "request_cancelled", "process_fatal_error", "process_started", "process_heartbeat", "job_started", "job_completed", "job_failed", "job_stalled", "queue_heartbeat", "edge_request", "infrastructure_log"]);
@@ -57,9 +58,14 @@ function safeRow(input: Record<string, unknown>): Row | null {
data[field] = Object.fromEntries(LOG_STAGES.map(stage => [stage, data[`stage_${stage}_${suffix}`]]));
}
// Revalidate finite route and diagnostic allowlists; never pass raw strings.
const projected = logContext.run({}, () => logRecord(["error", "warn", "info", "debug"].includes(String(input.severity)) ? String(input.severity) : "info", String(input.module || "application"), ["", data]));
// Identity fields are revalidated, including the double-blind userId rule, from the stored route and viewer.
const identity: LogContext = { route: typeof input.route === "string" && LOG_ROUTES.includes(input.route) ? input.route : undefined,
service: ["api", "streamer", "worker"].includes(String(input.service)) ? String(input.service) : undefined };
const keys = identity.route && !/^\/api\/repo\/:owner\/:repo(?:\/|$)/.test(identity.route) ? ["repoId", "pullRequestId", "gistId", "userId", "viewer"] : ["pullRequestId", "gistId", "userId", "viewer"];
for (const key of keys) if (typeof input[key] === "string") (identity as Record<string, unknown>)[key] = input[key];
const projected = logContext.run(identity, () => logRecord(["error", "warn", "info", "debug"].includes(String(input.severity)) ? String(input.severity) : "info", String(input.module || "application"), ["", data]));
const result: Row = { timestamp: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/.test(time) ? time : new Date(time).toISOString(), severity: String(projected.severity), service: services.includes(String(input.service)) ? String(input.service) : "unknown", event: events.has(String(input.event)) ? String(input.event) : "application_log", module: String(projected.module), release: /^(?:[a-f0-9]{7,40}|unknown)$/.test(String(input.release)) ? String(input.release) : "unknown" };
for (const key of [...numeric, "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "outcome", "endpointKind", "cancellationOrigin", "cancellationEvidence", "hopId", "parentHopId", "errorCode", "requestId", "jobId", "queue", "route", "method", "errorType", "errorStack", "causeType", "causeStack", "repoId", "requestPath"]) if (typeof projected[key] === "string" || typeof projected[key] === "number") result[key] = projected[key] as string | number;
for (const key of [...numeric, "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "outcome", "endpointKind", "cancellationOrigin", "cancellationEvidence", "hopId", "parentHopId", "errorCode", "requestId", "jobId", "queue", "route", "method", "errorType", "errorStack", "causeType", "causeStack", "repoId", "pullRequestId", "gistId", "userId", "viewer", "requestPath"]) if (typeof projected[key] === "string" || typeof projected[key] === "number") result[key] = projected[key] as string | number;
if (validTraceId(input.instance)) result.instance = input.instance;
return result;
}
+2 -1
View File
@@ -39,7 +39,7 @@ import {
getStatsHistory,
ensureTodaySnapshot,
} from "./dailyStatsSnapshot";
import { getUser } from "./routes/route-utils";
import { getUser, logRequestUser } from "./routes/route-utils";
import config from "../config";
import { resolveTrustProxy } from "./trustProxy";
import { requestRateLimitKey } from "./rate-limit-key";
@@ -187,6 +187,7 @@ export default async function start() {
app.use(passport.initialize());
app.use(passport.session());
app.use(bearerTokenAuth);
app.use(logRequestUser);
app.use(rateLimit({
...maintenanceRefreshLimitOptions,
store: new RedisStore({
+12 -9
View File
@@ -1041,7 +1041,7 @@ router.delete(
const repo = await getRepo(req, res, { nocheck: true });
if (!repo) return;
try {
await cacheQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace() }, { jobId: `repo-${repo.repoId}` });
await cacheQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace(repo.model.owner) }, { jobId: `repo-${repo.repoId}` });
return res.json({ status: repo.status });
} catch (error) {
handleError(error, res, req);
@@ -1207,13 +1207,16 @@ 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 };
}
router.get(
"/users/:username",
async (req: express.Request, res: express.Response) => {
try {
const model = await UserModel.findOne({
username: req.params.username,
}).populate({
const model = await UserModel.findOne(adminUserFilter(String(req.params.username))).populate({
path: "repositories",
model: "Repository",
foreignField: "_id",
@@ -1238,7 +1241,7 @@ router.get(
"/users/:username/repos",
async (req: express.Request, res: express.Response) => {
try {
const model = await UserModel.findOne({ username: req.params.username });
const model = await UserModel.findOne(adminUserFilter(String(req.params.username)));
if (!model) {
req.logout((error) =>
logger.error("logout failed", serializeError(error))
@@ -1259,7 +1262,7 @@ router.post(
"/users/:username/ban",
async (req: express.Request, res: express.Response) => {
try {
const user = await UserModel.findOne({ username: req.params.username });
const user = await UserModel.findOne(adminUserFilter(String(req.params.username)));
if (!user) {
throw new AnonymousError("user_not_found", { httpStatus: 404 });
}
@@ -1296,7 +1299,7 @@ router.post(
async (req: express.Request, res: express.Response) => {
try {
const result = await UserModel.updateOne(
{ username: req.params.username },
adminUserFilter(String(req.params.username)),
{ $set: { status: "active" } }
);
if (result.matchedCount === 0) {
@@ -1314,7 +1317,7 @@ router.post(
async (req: express.Request, res: express.Response) => {
try {
const result = await UserModel.updateOne(
{ username: req.params.username },
adminUserFilter(String(req.params.username)),
{ $set: { isAdmin: true } }
);
if (result.matchedCount === 0) {
@@ -1332,7 +1335,7 @@ router.post(
async (req: express.Request, res: express.Response) => {
try {
const result = await UserModel.updateOne(
{ username: req.params.username },
adminUserFilter(String(req.params.username)),
{ $set: { isAdmin: false } }
);
if (result.matchedCount === 0) {
+4 -3
View File
@@ -1,4 +1,4 @@
import { jobTrace } from "../../core/log-context";
import { jobTrace, setLogContext } from "../../core/log-context";
import Repository from "../../core/Repository";
import { sourceStorageSize } from "../../core/source/Source";
import { maximumExpiration, neverExpirationDeadline, validateBillingExpiration } from "../../core/billing/expiration";
@@ -43,7 +43,7 @@ router.use(ensureAuthenticated);
async function enqueueSavedSnapshot(model: IAnonymizedRepositoryDocument) {
try {
await downloadQueue.add(model.repoId, { repoId: model.repoId, ...jobTrace() }, {
await downloadQueue.add(model.repoId, { repoId: model.repoId, ...jobTrace(model.owner) }, {
jobId: `repo-${model.repoId}`, attempts: 3,
});
} catch (error) {
@@ -837,6 +837,7 @@ router.post("/", async (req, res) => {
repo.settingsSavedAt = repo.anonymizeDate;
repo.owner = user.id;
repo.githubAccess = selectedAccess.binding;
setLogContext({ repoId: repo.repoId });
validateBillingExpiration(repoUpdate.options, await maximumExpiration(user.id, repoUpdate.repoId, repoUpdate.conference));
if (repoUpdate.options.expirationMode === "never") {
@@ -879,7 +880,7 @@ router.post("/", async (req, res) => {
}
res.send({ status: repo.status });
downloadQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace() }, {
downloadQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace(repo.owner) }, {
jobId: `repo-${repo.repoId}`,
attempts: 3,
});
+1 -1
View File
@@ -335,7 +335,7 @@ router.get(
repo.statusActivityDate < fiveMinuteAgo
) {
await repo.updateStatus(RepositoryStatus.PREPARING);
await downloadQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace() }, {
await downloadQueue.add(repo.repoId, { repoId: repo.repoId, ...jobTrace(repo.model.owner) }, {
jobId: `repo-${repo.repoId}`,
attempts: 3,
});
+44
View File
@@ -10,9 +10,46 @@ import { RepositoryStatus } from "../../core/types";
import { createLogger, serializeError } from "../../core/logger";
import { isDisabledAccount } from "./auth-utils";
import { measureStage } from "../../core/request-monitoring";
import { anonymizedRoute, logContext, LogViewer, setLogContext, validUserId } from "../../core/log-context";
import { IUserDocument } from "../../core/model/users/users.types";
const logger = createLogger("route");
function sessionUser(req: express.Request): IUserDocument | undefined {
const user = (req.user as { user?: IUserDocument } | undefined)?.user;
return user && validUserId(String(user._id)) ? user : undefined;
}
/**
* Record the signed-in user on the log context. On anonymized-content routes
* the default viewer is "visitor"/"anonymous"; logIdentity then withholds the
* userId unless a handler later finds the user owns, co-authors or administers
* the project.
*/
export function logRequestUser(req: express.Request, _res: express.Response, next: express.NextFunction) {
const store = logContext.getStore();
if (store) {
const user = sessionUser(req);
if (user) setLogContext({ userId: String(user._id) });
if (anonymizedRoute(store.route, store.service)) setLogContext({ viewer: user ? "visitor" : "anonymous" });
}
next();
}
/** Label how the signed-in user relates to the anonymized project this request resolved. */
export function logProjectViewer(req: express.Request, ownerId: unknown, coauthor?: (user: User) => boolean) {
const model = sessionUser(req);
let viewer: LogViewer = "anonymous";
if (model) {
const user = new User(model);
if (ownerId != null && String(ownerId) === String(model._id)) viewer = "owner";
else if (coauthor?.(user)) viewer = "coauthor";
else if (user.isAdmin) viewer = "admin";
else viewer = "visitor";
}
setLogContext({ viewer });
}
export async function getGist(
req: express.Request,
res: express.Response,
@@ -22,7 +59,9 @@ export async function getGist(
if (typeof req.params.gistId !== "string") {
throw new AnonymousError("invalid_path", { httpStatus: 400 });
}
setLogContext({ gistId: req.params.gistId });
const gist = await db.getGist(req.params.gistId);
logProjectViewer(req, gist.model.owner);
if (opt?.nocheck !== true) {
if (
gist.status == "expired" &&
@@ -50,7 +89,9 @@ export async function getPullRequest(
if (typeof req.params.pullRequestId !== "string") {
throw new AnonymousError("invalid_path", { httpStatus: 400 });
}
setLogContext({ pullRequestId: req.params.pullRequestId });
const pullRequest = await db.getPullRequest(req.params.pullRequestId);
logProjectViewer(req, pullRequest.model.owner);
if (opt?.nocheck !== true) {
// redirect if the repository is expired
if (
@@ -84,7 +125,9 @@ export async function getRepo(
throw new AnonymousError("invalid_path", { httpStatus: 400 });
}
const repoId = req.params.repoId;
setLogContext({ repoId });
const repo = await measureStage("repository", () => db.getRepository(repoId));
logProjectViewer(req, repo.model.owner, (user) => isCoauthor(repo, user));
if (opt.nocheck !== true) {
// redirect if the repository is expired
if (
@@ -329,6 +372,7 @@ export async function getUser(req: express.Request) {
if (!model) {
notConnected();
}
setLogContext({ userId: String(model._id) });
if (isDisabledAccount(model.status)) {
req.logout((error) => {
if (error) {