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

+1 -1
View File
@@ -860,7 +860,7 @@ export default class Repository {
const current = await AnonymizedRepositoryModel.exists({ _id: this.model._id, ...this.refreshFilter() });
if (!current) throw new AnonymousError("invalid_status", { httpStatus: 409 });
}
await downloadQueue.add(this.repoId, { repoId: this.repoId, ...jobTrace() }, {
await downloadQueue.add(this.repoId, { repoId: this.repoId, ...jobTrace(this.model.owner) }, {
jobId: `repo-${this.repoId}`,
attempts: 3,
});
+70 -3
View File
@@ -1,11 +1,78 @@
import { AsyncLocalStorage } from "async_hooks";
import { randomUUID } from "crypto";
export interface LogContext { requestId?: string; hopId?: string; parentHopId?: string; jobId?: string; attempt?: number; service?: string; route?: string; method?: string; requestPath?: string }
export type LogViewer = "owner" | "coauthor" | "admin" | "visitor" | "anonymous";
export interface LogContext {
requestId?: string; hopId?: string; parentHopId?: string; jobId?: string; attempt?: number; service?: string; route?: string; method?: string; requestPath?: string;
/** Public anonymized project IDs. */
repoId?: string; pullRequestId?: string; gistId?: string;
/** Internal Mongo user _id of the signed-in user or job owner. Emitted only under the rules in logIdentity. */
userId?: string;
viewer?: LogViewer;
}
export const logContext = new AsyncLocalStorage<LogContext>();
export const validTraceId = (value: unknown): value is string => typeof value === "string" &&
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
export function jobTrace() {
// Same character set and bounds as the repository, pull request and gist ID validators.
export const validProjectId = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9_-]{3,200}$/.test(value);
export const validUserId = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{24}$/.test(value);
export const LOG_VIEWERS: readonly LogViewer[] = ["owner", "coauthor", "admin", "visitor", "anonymous"];
const PRIVILEGED_VIEWERS: readonly LogViewer[] = ["owner", "coauthor", "admin"];
export const validViewer = (value: unknown): value is LogViewer => typeof value === "string" && (LOG_VIEWERS as readonly string[]).includes(value);
/** Routes that serve anonymized content. A reviewer's identity must never be logged here. */
export function anonymizedRoute(route: unknown, service?: unknown): boolean {
if (service === "streamer") return true;
return typeof route === "string" && /^\/(?:api\/repo\/:(?:repoId|id)(?:\/|$)|r\/|w\/|viewer\/|api\/pr\/|api\/gist\/)/.test(route);
}
/** Signed-in account pages where the actor is the account holder, never a reviewer. */
export function accountRoute(route: unknown): boolean {
return typeof route === "string" && (["/dashboard", "/anonymize", "/profile", "/api/repo", "/api/anonymize-preview",
"/api/conferences/plans", "/conference/:id", "/github/:action"].includes(route)
|| /^\/api\/(?:user|billing|admin)(?:\/|$)/.test(route) || /^\/api\/repo\/:owner\/:repo(?:\/|$)/.test(route));
}
/** Add validated identity fields to the current request or job. Invalid values are dropped. */
export function setLogContext(fields: Pick<LogContext, "repoId" | "pullRequestId" | "gistId" | "userId" | "viewer">) {
const store = logContext.getStore();
if (!store) return;
for (const key of ["repoId", "pullRequestId", "gistId"] as const) if (validProjectId(fields[key])) store[key] = fields[key];
if (validUserId(fields.userId)) store.userId = fields.userId;
if (validViewer(fields.viewer)) store.viewer = fields.viewer;
}
/**
* Identity fields for one record, read from the request or job context only.
* Logger arguments may supply repoId in jobs and on anonymized routes; other
* identity fields from arguments are ignored because code such as the gist
* downloader logs upstream IDs under similar names.
*
* Double-blind rule: on anonymized-content routes, userId is emitted only for
* 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.
*/
export function logIdentity(context: LogContext, details: Record<string, unknown> = {}) {
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.
const argumentRepoId = anonymizedRoute(route, service) || (route === undefined && service === "worker") ? details.repoId : undefined;
const repoId = context.repoId ?? argumentRepoId;
if (validProjectId(repoId)) out.repoId = repoId;
if (validProjectId(context.pullRequestId)) out.pullRequestId = context.pullRequestId;
if (validProjectId(context.gistId)) out.gistId = context.gistId;
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;
}
return out;
}
export function jobTrace(ownerId?: unknown) {
const requestId = logContext.getStore()?.requestId;
return { logJobId: randomUUID(), ...(requestId ? { requestId } : {}) };
const owner = ownerId == null ? undefined : String(ownerId);
return { logJobId: randomUUID(), ...(requestId ? { requestId } : {}), ...(validUserId(owner) ? { ownerId: owner } : {}) };
}
+26 -4
View File
@@ -1020,13 +1020,27 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
],
"src/core/log-context.ts": [
"<anonymous>",
"accountRoute",
"anonymizedRoute",
"jobTrace",
"validTraceId"
"logIdentity",
"setLogContext",
"validProjectId",
"validTraceId",
"validUserId",
"validViewer"
],
"build/core/log-context.js": [
"<anonymous>",
"accountRoute",
"anonymizedRoute",
"jobTrace",
"validTraceId"
"logIdentity",
"setLogContext",
"validProjectId",
"validTraceId",
"validUserId",
"validViewer"
],
"src/core/log-diagnostics.ts": [
"<anonymous>",
@@ -2420,6 +2434,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
],
"src/server/routes/admin.ts": [
"<anonymous>",
"adminUserFilter",
"csvEscape",
"dashboardCache",
"escapeRegex",
@@ -2435,6 +2450,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
],
"build/server/routes/admin.js": [
"<anonymous>",
"adminUserFilter",
"csvEscape",
"dashboardCache",
"escapeRegex",
@@ -2688,9 +2704,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"isCoauthor",
"isOwnerCoauthorOrAdmin",
"isOwnerOrAdmin",
"logProjectViewer",
"logRequestUser",
"notConnected",
"originFromStack",
"printError"
"printError",
"sessionUser"
],
"build/server/routes/route-utils.js": [
"<anonymous>",
@@ -2706,9 +2725,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"isCoauthor",
"isOwnerCoauthorOrAdmin",
"isOwnerOrAdmin",
"logProjectViewer",
"logRequestUser",
"notConnected",
"originFromStack",
"printError"
"printError",
"sessionUser"
],
"src/server/routes/token-auth.ts": [
"<anonymous>",
+6 -2
View File
@@ -4,7 +4,7 @@ import { safeDiagnosticFields, errorDiagnostics } from "./log-diagnostics";
import { LOG_ROUTES, LOG_THROWN_ERROR_CODES } from "./log-diagnostic-schema";
import { LOG_MODULES, ERROR_CODES, LOG_EVENTS } from "./log-schema";
import { randomUUID } from "crypto";
import { logContext, validTraceId } from "./log-context";
import { logContext, logIdentity, validTraceId } from "./log-context";
// No arbitrary strings: upstream errors, paths and even innocuous-looking messages
// can contain a private repository name. Add diagnostics here deliberately.
@@ -33,7 +33,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
const context = logContext.getStore() || {};
const details: Record<string, unknown> = {};
const keys = [...LOG_NUMBERS, "requestId", "jobId", "hopId", "parentHopId", "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "cancellationOrigin", "cancellationEvidence", "endpointKind", "stageCounts", "stageOpen", "code", "message", "outcome", "method", "route", "queue",
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service"];
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "repoId", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service"];
// Do not traverse arbitrary objects or invoke error getters while logging.
for (const arg of args.slice(0, 8)) if (arg && typeof arg === "object") {
for (const key of keys) {
@@ -77,9 +77,13 @@ export function logRecord(level: string, module: string, args: unknown[]) {
if (typeof route === "string" && LOG_ROUTES.includes(route)) record.route = route.replace(/^\/api\/repo\/:id(?=\/|$)/, "/api/repo/:repoId");
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));
// 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));
// A rejected request path may name an upstream owner; keep no repoId beside it.
else if (context.requestPath || details.requestPath) delete record.repoId;
if (allowed(["download", "remove", "cache"], details.queue)) record.queue = details.queue;
if (details.stages && typeof details.stages === "object") for (const key of LOG_STAGES) {
let value: unknown;
+1 -1
View File
@@ -164,7 +164,7 @@ function clampPayload(entry: {
if (first && typeof first === "object" && !Array.isArray(first)) {
const diagnostic = first as Record<string, unknown>;
const compact: Record<string, unknown> = {};
for (const key of ["timestamp", "severity", "service", "event", "module", "release", "requestId", "jobId", "method", "route", "requestPath", "repoId", "httpStatus", "status", "errorCode", "errorType", "causeType", "code", "message"]) {
for (const key of ["timestamp", "severity", "service", "event", "module", "release", "requestId", "jobId", "method", "route", "requestPath", "repoId", "pullRequestId", "gistId", "userId", "viewer", "httpStatus", "status", "errorCode", "errorType", "causeType", "code", "message"]) {
if (diagnostic[key] !== undefined) compact[key] = diagnostic[key];
}
for (const key of ["errorStack", "causeStack"]) {
+9 -4
View File
@@ -1,6 +1,6 @@
import { responseEvidence, expectedResponseBytes } from "./request-evidence";
import { requestReproduction } from "./log-reproduction";
import { logContext, validTraceId } from "./log-context";
import { LogContext, logContext, validTraceId } from "./log-context";
import { AsyncLocalStorage } from "async_hooks";
import { randomUUID } from "crypto";
import { performance } from "perf_hooks";
@@ -181,6 +181,8 @@ export function monitorRequests(service: Service, metrics = requestMetrics,
let transferDone: (() => void) | undefined;
let bytes = 0;
let ended = false;
// Handlers add repoId, userId and viewer to this object after next() runs.
const logStore: LogContext = { ...reproduction, requestId: id, hopId, parentHopId, service, route, method };
activeRequests++;
res.setHeader("X-Request-ID", id);
const writeHead = res.writeHead;
@@ -224,10 +226,13 @@ export function monitorRequests(service: Service, metrics = requestMetrics,
bytes, expectedBytes: expectedResponseBytes(req.method, res.statusCode, res.getHeader("content-length")),
endpointKind: service === "streamer" ? "internal" : "public", hopId, parentHopId,
...(aborted ? responseEvidence(res, req.aborted) : {}), ...trace.timing.finish(started + ms) };
if (slow || aborted) log.warn(aborted ? "request interrupted" : "slow request", detail);
else if (!route.includes("healthcheck")) log.info("request", detail);
// "close" can fire outside the request's async context; read the store directly.
logContext.run(logStore, () => {
if (slow || aborted) log.warn(aborted ? "request interrupted" : "slow request", detail);
else if (!route.includes("healthcheck")) log.info("request", detail);
});
};
res.once("finish", done); res.once("close", done);
context.run(trace, () => logContext.run({ ...reproduction, requestId: id, hopId, parentHopId, service, route, method }, next));
context.run(trace, () => logContext.run(logStore, next));
};
}
+2
View File
@@ -19,6 +19,8 @@ export interface RepoJobData {
repoId: string;
requestId?: string;
logJobId?: string;
/** Owner's internal user _id, for log records only. */
ownerId?: string;
}
const IN_FLIGHT_STATUSES: RepositoryStatus[] = [
+4 -1
View File
@@ -1,7 +1,7 @@
import { logMemory } from "../core/log-memory";
import { randomUUID } from "crypto";
import { SandboxedJob } from "bullmq";
import { logContext, validTraceId } from "../core/log-context";
import { logContext, validProjectId, validTraceId, validUserId } from "../core/log-context";
import { createLogger, reportOutputDrops } from "../core/logger";
import type { RepoJobData } from "./index";
const logger = createLogger("queue");
@@ -10,6 +10,9 @@ export function loggedJob(queue: "download" | "remove" | "cache", work: (job: Sa
service: "worker", jobId: validTraceId(job.data.logJobId) ? job.data.logJobId : randomUUID(),
requestId: validTraceId(job.data.requestId) ? job.data.requestId : undefined,
attempt: job.attemptsMade + 1,
// Owner _id is stamped at enqueue time (jobTrace); no lookup per job.
...(validProjectId(job.data.repoId) ? { repoId: job.data.repoId } : {}),
...(validUserId(job.data.ownerId) ? { userId: job.data.ownerId } : {}),
}, async () => {
logger.info("job started", { queue });
const started = Date.now();
+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) {
+3
View File
@@ -1,6 +1,7 @@
import { recordResponseFailure } from "../core/request-evidence";
import { sendSharedContent } from "../core/cached-response";
import * as express from "express";
import { setLogContext } from "../core/log-context";
import GitHubStream from "../core/source/GitHubStream";
import {
AnonymizeTransformer,
@@ -29,6 +30,7 @@ router.post(
}
const repoFullName = req.body.repoFullName.split("/");
const repoId = req.body.repoId;
setLogContext({ repoId });
const commit = req.body.commit;
const anonymizerOptions = req.body.anonymizerOptions;
const contentOptions = req.body.contentOptions;
@@ -62,6 +64,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
}
const repoFullName = req.body.repoFullName.split("/");
const repoId = req.body.repoId;
setLogContext({ repoId });
const fileSha = req.body.sha;
const fileSize: number | undefined =
typeof req.body.size === "number" ? req.body.size : undefined;