mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-03 01:23:31 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # deploy/logging/sanitize.vrl
This commit is contained in:
commit
7c9e803fbd
65 files changed
+6008
-575
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { installDatabaseTiming } from "../core/database-timing";
|
||||
import InstallationModel from "../core/model/github-installation";
|
||||
import { UserRepositoryModel, UserRepositorySyncModel } from "../core/model/user-repositories";
|
||||
import { credentialCipher } from "../core/credentials";
|
||||
import CredentialModel from "../core/model/credentials/credentials.model";
|
||||
import mongoose, { ConnectOptions } from "mongoose";
|
||||
@@ -37,6 +38,8 @@ export async function connect(overrides: Pick<ConnectOptions, "appName" | "maxPo
|
||||
await mongoose.connect(getMongoUrl(), options);
|
||||
await CredentialModel.createIndexes();
|
||||
if (config.GITHUB_APP_ENABLED) await InstallationModel.createIndexes();
|
||||
await UserRepositoryModel.createIndexes();
|
||||
await UserRepositorySyncModel.createIndexes();
|
||||
await initializeOwnerAccessAlerts();
|
||||
isConnected = true;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { getCredentialToken } from "../../core/credentials";
|
||||
import { APP_PROVIDER, appError, appUserToken, AppInstallation, clearAppTokenCache, exchangeAppToken,
|
||||
githubRequest, GitHubRepositoryInfo, reconcileAppGrant, reconcileInstallation, installationURL, saveAppGrant, selectRepositoryAccess, userInstallations } from "../../core/github-app";
|
||||
import { explicitErrorStatus, getUser, handleError } from "./route-utils";
|
||||
import { applyRepositoryWebhook, clearRepositoryList, markRepositoryListStale } from "../../core/user-repository-list";
|
||||
import { isDisabledAccount, safeAuthReturnTo } from "./auth-utils";
|
||||
|
||||
type Flow = { state: string; expires: number; ownerId?: string; returnTo: string; repository?: string; install?: boolean };
|
||||
@@ -156,6 +157,7 @@ router.get("/app/setup", enabled, async (req, res) => {
|
||||
await resetOwnerAccessAlerts(user.id);
|
||||
}
|
||||
await UserModel.updateOne({ _id: user.id }, { $set: { repositories: [] } });
|
||||
await markRepositoryListStale([user.id]);
|
||||
res.redirect(flow.returnTo);
|
||||
} catch (error) { handleError(error, res, req); }
|
||||
});
|
||||
@@ -275,6 +277,8 @@ export async function revokeGrant(ownerId: string, provider: "github" | "github-
|
||||
const token = await getCredentialToken(ownerId, provider);
|
||||
const clientId = provider === "github" ? config.CLIENT_ID : config.GITHUB_APP_CLIENT_ID;
|
||||
const clientSecret = provider === "github" ? config.CLIENT_SECRET : config.GITHUB_APP_CLIENT_SECRET;
|
||||
// Before the GitHub call: a failed revoke must not keep private repo names.
|
||||
await clearRepositoryList(ownerId, provider === "github" ? "oauth" : "github-app");
|
||||
if (token) {
|
||||
const response = await fetch(`https://api.github.com/applications/${clientId}/grant`, { method: "DELETE",
|
||||
headers: { Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`, "Content-Type": "application/json", Accept: "application/vnd.github+json" },
|
||||
@@ -321,7 +325,12 @@ githubAppWebhook.post("/", express.raw({ type: "application/json", limit: "2mb"
|
||||
phase = "find_grant_owners";
|
||||
const users = await UserModel.find({ "externalIDs.github": String(body.sender.id) }).select("_id").lean();
|
||||
phase = "reconcile_grant";
|
||||
for (const user of users) await reconcileAppGrant(String(user._id));
|
||||
for (const user of users) {
|
||||
await reconcileAppGrant(String(user._id));
|
||||
// Private repository names must not outlive the grant; a live grant
|
||||
// simply resyncs on the next picker load.
|
||||
await clearRepositoryList(String(user._id), "github-app");
|
||||
}
|
||||
}
|
||||
if (["installation", "installation_repositories"].includes(String(event)) && Number.isSafeInteger(body.installation?.id) && String(body.installation.app_id) === config.GITHUB_APP_ID) {
|
||||
const installation = body.installation as AppInstallation;
|
||||
@@ -336,6 +345,12 @@ githubAppWebhook.post("/", express.raw({ type: "application/json", limit: "2mb"
|
||||
phase = "reconcile_installation";
|
||||
if (body.action !== "deleted") await reconcileInstallation(installation.id, revision);
|
||||
}
|
||||
if (["installation", "installation_repositories", "repository"].includes(String(event))) {
|
||||
// After the installation block: a failed picker write must never leave a
|
||||
// deleted or suspended installation usable. The lists also resync by age.
|
||||
phase = "update_repository_lists";
|
||||
await applyRepositoryWebhook(String(event), body);
|
||||
}
|
||||
return res.status(204).end();
|
||||
} catch (error) {
|
||||
const delivery = req.headers["x-github-delivery"];
|
||||
|
||||
@@ -17,13 +17,10 @@ import { RepositoryStatus } from "../../core/types";
|
||||
import User from "../../core/User";
|
||||
import { streamAnonymizedZip } from "../../core/zipStream";
|
||||
import FileModel from "../../core/model/files/files.model";
|
||||
import { createLogger, serializeError } from "../../core/logger";
|
||||
import { githubTokenForStreamer } from "../../core/github-token-context";
|
||||
import gh = require("parse-github-url");
|
||||
import { requestHeaders, startStage } from "../../core/request-monitoring";
|
||||
|
||||
const logger = createLogger("repository-public");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get(
|
||||
@@ -94,6 +91,7 @@ router.get(
|
||||
headersDone(true);
|
||||
const upstreamStatus = err?.response?.statusCode;
|
||||
let upstreamBody: string | undefined;
|
||||
let streamerCode = false;
|
||||
let errCode = "zip_not_available";
|
||||
let httpStatus = 502;
|
||||
if (err?.response?.body != null) {
|
||||
@@ -112,6 +110,7 @@ router.get(
|
||||
const parsed = JSON.parse(upstreamBody);
|
||||
if (parsed && typeof parsed.error === "string") {
|
||||
errCode = parsed.error;
|
||||
streamerCode = true;
|
||||
}
|
||||
} catch {
|
||||
/* not JSON */
|
||||
@@ -121,26 +120,17 @@ router.get(
|
||||
if (typeof upstreamStatus === "number") {
|
||||
httpStatus = upstreamStatus >= 500 ? 502 : upstreamStatus;
|
||||
}
|
||||
logger.warn("streamer zip fetch failed", {
|
||||
code: errCode,
|
||||
httpStatus,
|
||||
repoId: repo.repoId,
|
||||
upstreamStatus,
|
||||
upstreamBody: upstreamBody?.slice(0, 500),
|
||||
url: config.STREAMER_ENTRYPOINT
|
||||
? join(config.STREAMER_ENTRYPOINT, "api/download")
|
||||
: undefined,
|
||||
err: serializeError(err),
|
||||
});
|
||||
const streaming = res.headersSent;
|
||||
handleError(
|
||||
new AnonymousError(errCode, {
|
||||
url: req.originalUrl,
|
||||
httpStatus,
|
||||
cause: err,
|
||||
}),
|
||||
res
|
||||
);
|
||||
const error = new AnonymousError(errCode, {
|
||||
url: req.originalUrl,
|
||||
httpStatus,
|
||||
cause: err,
|
||||
});
|
||||
error.upstreamStatus = upstreamStatus;
|
||||
// A coded body comes from the streamer's handleError, which
|
||||
// already logged this failure under the same requestId.
|
||||
error.upstreamLogged = streamerCode && typeof upstreamStatus === "number";
|
||||
handleError(error, res);
|
||||
// Once ZIP bytes have been sent, handleError cannot send JSON.
|
||||
// Terminate the truncated response so the client reports failure
|
||||
// instead of waiting forever for the ZIP's central directory.
|
||||
|
||||
@@ -184,8 +184,44 @@ export function explicitErrorStatus(error: unknown): number | undefined {
|
||||
.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) {
|
||||
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);
|
||||
@@ -194,20 +230,11 @@ function printError(error: any, req?: express.Request) {
|
||||
// Errors page surfaces something meaningful (e.g. "repoId_already_used")
|
||||
// instead of a generic "anonymous error" wrapper.
|
||||
const summary = error.message || error.name || "AnonymousError";
|
||||
// 4xx are expected client errors (not_found, expired, not_connected) —
|
||||
// route them to warn so the admin Errors page can split server faults
|
||||
// (5xx) from client misuse (4xx) cleanly.
|
||||
const status = explicitErrorStatus(error);
|
||||
if (typeof status === "number" && status >= 400 && status < 500) {
|
||||
logger.warn(summary, payload);
|
||||
} else {
|
||||
logger.error(summary, payload);
|
||||
}
|
||||
logger[level](summary, payload);
|
||||
} else if (error instanceof HTTPError) {
|
||||
const payload: Record<string, unknown> = serializeError(error);
|
||||
ensureUrl(payload, req);
|
||||
const status = explicitErrorStatus(error);
|
||||
logger[status && status < 500 ? "warn" : "error"](error.code || error.name || "HTTPError", payload);
|
||||
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
|
||||
@@ -225,8 +252,7 @@ function printError(error: any, req?: express.Request) {
|
||||
((error as { name?: string }).name ||
|
||||
(error as { message?: string }).message)) ||
|
||||
"UnhandledError";
|
||||
const status = explicitErrorStatus(error);
|
||||
logger[status && status < 500 ? "warn" : "error"](summary, serialized);
|
||||
logger[level](summary, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,10 +260,11 @@ export function handleError(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
error: any,
|
||||
res?: express.Response,
|
||||
req?: express.Request
|
||||
req?: express.Request,
|
||||
options?: ErrorLogOptions
|
||||
) {
|
||||
if (isResponseCancellation(error, res)) return;
|
||||
printError(error, req);
|
||||
printError(error, req, options);
|
||||
let errorCode = error;
|
||||
if (error instanceof Error) {
|
||||
errorCode = error.message;
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { repositoryPickerPage } from "../../core/github-repository-picker";
|
||||
import { appUserToken } from "../../core/github-app";
|
||||
import { getCredentialToken } from "../../core/credentials";
|
||||
import { pickerConnection, repositoryListPage } from "../../core/user-repository-list";
|
||||
import AnonymousError from "../../core/AnonymousError";
|
||||
import { BillingQuota, BillingDraft } from "../../core/billing/models";
|
||||
import { cancelAccountBilling } from "../../core/billing/stripe";
|
||||
@@ -383,11 +381,12 @@ router.get("/repository_picker", async (req, res) => {
|
||||
res.status(400).json({ error: "Invalid repository search" });
|
||||
return;
|
||||
}
|
||||
const token = connection === "github-app" ? await appUserToken(user.id)
|
||||
: connection === "oauth" ? await getCredentialToken(user.id) : await user.getAccessToken();
|
||||
if (!token) { res.status(401).json({ error: "GitHub connection required" }); return; }
|
||||
// Served from the stored list; GitHub is only asked when it is empty,
|
||||
// forced, or stale after an installation change.
|
||||
const list = await pickerConnection(user.id, connection);
|
||||
if (!list) { res.status(401).json({ error: "GitHub connection required" }); return; }
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json(await repositoryPickerPage(token, cursor, query));
|
||||
res.json(await repositoryListPage(user.id, list, { cursor, query, force: req.query.force === "1" }));
|
||||
} catch (error) { handleError(error, res, req); }
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user