Files
anonymous_github/src/server/routes/route-utils.ts
T
Thomas DurieuxandClaude Opus 5.5 3f8812c99e fix(logging): give raw GitHub failures an error code, log missing branches as warnings
Overnight, GitHub refusals reached the logs as bare HTTPError/UnknownError
with no code: a ZIP whose archive request was refused became a cut
connection and a 502 zip_not_available, a 401 while checking a file
became an uncoded 401, and an Octokit 403 on /options answered
internal_error.

- codeUpstreamError maps got/Octokit replies to repo_not_accessible,
  github_rate_limit_exceeded, github_unavailable or upstream_error;
  handleError applies it, the streamer file route uses the file-level
  mapping, and programming errors pass through unchanged.
- A ZIP that fails before any byte answers with the code, so the API
  relays it; 4xx archive refusals log at warn.
- branch_not_found (owner deleted the branch) logs at warn.
- Octokit's HttpError is an allowlisted error type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:52:23 +00:00

395 lines
14 KiB
TypeScript

import { isResponseCancellation } from "../../core/response-cancellation";
import * as express from "express";
import AnonymousError from "../../core/AnonymousError";
import * as db from "../database";
import UserModel from "../../core/model/users/users.model";
import User from "../../core/User";
import Repository from "../../core/Repository";
import { HTTPError } from "got";
import { codeUpstreamError } from "../../core/upstream-error";
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,
opt?: { nocheck?: boolean }
) {
try {
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" &&
gist.options.expirationMode == "redirect"
) {
res.redirect(`https://gist.github.com/${gist.source.gistId}`);
return null;
}
await gist.check();
}
return gist;
} catch (error) {
handleError(error, res, req);
return null;
}
}
export async function getPullRequest(
req: express.Request,
res: express.Response,
opt?: { nocheck?: boolean }
) {
try {
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 (
pullRequest.status == "expired" &&
pullRequest.options.expirationMode == "redirect"
) {
res.redirect(
`https://github.com/${pullRequest.source.repositoryFullName}/pull/${pullRequest.source.pullRequestId}`
);
return null;
}
await pullRequest.check();
}
return pullRequest;
} catch (error) {
handleError(error, res, req);
return null;
}
}
export async function getRepo(
req: express.Request,
res: express.Response,
opt: { nocheck?: boolean } = {
nocheck: false,
}
) {
try {
if (typeof req.params.repoId !== "string") {
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 (
repo.status == RepositoryStatus.EXPIRED &&
repo.options.expirationMode == "redirect" &&
repo.model.source.repositoryId
) {
res.redirect(`https://github.com/${repo.model.source.repositoryName}`);
return null;
}
await repo.check();
}
return repo;
} catch (error) {
handleError(error, res, req);
return null;
}
}
export function isOwnerOrAdmin(authorizedUsers: string[], user: User) {
if (authorizedUsers.indexOf(user.model.id) == -1 && !user.isAdmin) {
throw new AnonymousError("not_authorized", {
httpStatus: 401,
});
}
}
export function isCoauthor(repo: Repository, user: User): boolean {
const githubId = user.model.externalIDs?.github;
return (repo.model.coauthors || []).some((coauthor) => {
if (coauthor.githubId) {
return Boolean(githubId && coauthor.githubId === githubId);
}
return Boolean(user.username && coauthor.username === user.username);
});
}
export function isOwnerCoauthorOrAdmin(repo: Repository, user: User) {
if (user.isAdmin) return;
if (repo.owner.id === user.model.id) return;
if (isCoauthor(repo, user)) return;
throw new AnonymousError("not_authorized", {
httpStatus: 403,
});
}
// Compute a new expiration date `months` ahead. Anchors on the current
// expiration date when it is still in the future, otherwise on now, so an
// already-expired item is pushed forward from today rather than from a stale
// past date.
export function extendExpirationDate(
current: Date | null | undefined,
months = 6
): Date {
const now = new Date();
const base = current && new Date(current) > now ? new Date(current) : now;
base.setMonth(base.getMonth() + months);
return base;
}
// Pull the first project-relevant frame ("file:line:col") out of a stack so
// background-job errors (no req.originalUrl) still get a debug pointer in the
// `url` slot. Skips node internals and node_modules.
function originFromStack(stack: unknown): string | undefined {
if (typeof stack !== "string") return undefined;
const lines = stack.split("\n");
for (const line of lines) {
const m = line.match(/\(([^()\s]+:\d+:\d+)\)\s*$/) ||
line.match(/at\s+([^()\s]+:\d+:\d+)\s*$/);
if (!m) continue;
const loc = m[1];
if (loc.startsWith("node:") || loc.includes("node_modules")) continue;
return loc;
}
return undefined;
}
function ensureUrl(
payload: Record<string, unknown>,
req?: express.Request
) {
if (req?.originalUrl) {
payload.url = req.originalUrl;
return;
}
if (typeof payload.url === "string" && payload.url) return;
const origin = originFromStack(payload.stack);
if (origin) payload.url = origin;
}
/** Use the same validated upstream status for response mapping and log severity. */
export function explicitErrorStatus(error: unknown): number | undefined {
const value = error as { httpStatus?: number; status?: number; response?: { statusCode?: number };
$metadata?: { httpStatusCode?: number } } | null;
return [value?.httpStatus, value?.status, value?.response?.statusCode, value?.$metadata?.httpStatusCode]
.find(status => Number.isInteger(status) && status! >= 400 && status! <= 599);
}
// Request end states that need no operator action: the visitor asked for
// something that is gone, expired, unsupported or not theirs. They are logged
// at info so the admin Errors page (warn and error) keeps to faults. Rate
// limits, expired owner tokens and upstream failures are left out on purpose.
export const EXPECTED_CLIENT_ERRORS: ReadonlySet<string> = new Set([
"repo_not_found", "repository_not_found", "commit_not_found", "branch_not_found",
"file_not_found", "folder_not_supported", "file_not_supported", "file_too_big",
"readme_not_available", "submodule_not_available",
"repository_expired", "repository_archived", "repository_not_ready", "is_removed",
"github_app_access_required", "not_connected", "not_authorized",
"page_not_activated", "page_not_supported_on_different_branch", "download_not_enabled",
"gist_not_found", "gist_expired", "gist_not_ready",
"pull_request_not_found", "pull_request_expired", "pull_request_not_ready",
"conf_not_found", "conference_not_found", "repoId_already_used", "invalid_repoId",
]);
export type ErrorLogOptions = {
/** The reply goes to another service that logs the request's end state. */
internal?: boolean;
};
type LogLevel = "debug" | "info" | "warn" | "error";
/** One record per failed request, at a level that matches who has to act. */
export function errorLogLevel(error: unknown, options: ErrorLogOptions = {}): LogLevel {
const status = explicitErrorStatus(error);
let level: LogLevel = status !== undefined && status < 500 ? "warn" : "error";
if (error instanceof AnonymousError) {
// The internal service that answered logged the failure at its own level.
if (error.upstreamLogged) level = "info";
else if (level === "warn" && EXPECTED_CLIENT_ERRORS.has(error.message)) level = "info";
}
return level === "info" && options.internal ? "debug" : level;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function printError(error: any, req?: express.Request, options: ErrorLogOptions = {}) {
const level = errorLogLevel(error, options);
if (error instanceof AnonymousError) {
if (req?.originalUrl === "/api/repo/undefined/options") return;
const payload: Record<string, unknown> = serializeError(error);
ensureUrl(payload, req);
// Use the error's snake_case message as the logger summary so the admin
// Errors page surfaces something meaningful (e.g. "repoId_already_used")
// instead of a generic "anonymous error" wrapper.
const summary = error.message || error.name || "AnonymousError";
logger[level](summary, payload);
} else if (error instanceof HTTPError) {
const payload: Record<string, unknown> = serializeError(error);
ensureUrl(payload, req);
logger[level](error.code || error.name || "HTTPError", payload);
} else {
// Unhandled errors: use the error class name (SyntaxError, TypeError,
// RangeError, ...) as the summary so the admin page shows
// something far more useful than a generic "unhandled error" label.
const serialized = serializeError(error) as Record<string, unknown>;
if (
typeof serialized.status !== "number" &&
typeof serialized.httpStatus !== "number"
) {
serialized.httpStatus = explicitErrorStatus(error) ?? 500;
}
ensureUrl(serialized, req);
const summary =
(error && typeof error === "object" &&
((error as { name?: string }).name ||
(error as { message?: string }).message)) ||
"UnhandledError";
logger[level](summary, serialized);
}
}
export function handleError(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: any,
res?: express.Response,
req?: express.Request,
options?: ErrorLogOptions
) {
if (isResponseCancellation(error, res)) return;
// A raw GitHub reply (got or Octokit) is an upstream outcome, not a bug:
// log and answer it with a code instead of "HTTPError"/"internal_error".
error = codeUpstreamError(error);
printError(error, req, options);
let errorCode = error;
if (error instanceof Error) {
errorCode = error.message;
} else if (typeof error !== "string") {
errorCode = String(error);
}
let status = 500;
const explicitStatus = explicitErrorStatus(error);
if (explicitStatus !== undefined) {
status = explicitStatus;
} else if (
errorCode &&
(errorCode.indexOf("not_found") > -1 ||
errorCode.indexOf("(Not Found)") > -1)
) {
status = 404;
} else if (errorCode && errorCode.indexOf("not_connected") > -1) {
status = 401;
}
if (res && !res.headersSent) {
const safeCode =
error instanceof AnonymousError ? errorCode : "internal_error";
const body: Record<string, unknown> = { error: safeCode };
if (
error instanceof AnonymousError &&
safeCode === "rate_limited" &&
error.value &&
typeof error.value === "object" &&
"resetAt" in (error.value as Record<string, unknown>)
) {
body.resetAt = (error.value as Record<string, unknown>).resetAt;
}
res.status(status).json(body);
}
return;
}
export async function getUser(req: express.Request) {
function notConnected(): never {
// Anonymous sessions can hold an in-progress OAuth flow. Passport's
// logout regenerates the session, so only clear an invalid identity.
if (req.user) {
req.logout((error) => {
if (error) {
logger.error("logout failed", serializeError(error));
}
});
}
throw new AnonymousError("not_connected", {
httpStatus: 401,
});
}
if (!req.user) {
notConnected();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user = (req.user as any).user;
if (!user) {
notConnected();
}
const model = await UserModel.findById(user._id);
if (!model) {
notConnected();
}
setLogContext({ userId: String(model._id) });
if (isDisabledAccount(model.status)) {
req.logout((error) => {
if (error) {
logger.error("logout failed", serializeError(error));
}
});
throw new AnonymousError(
model.status === "banned" ? "user_banned" : "not_connected",
{
httpStatus: model.status === "banned" ? 403 : 401,
}
);
}
return new User(model);
}