Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- Fixed vulnerability triage for reusable-workflow callers, repositories without CodeQL, and transient non-JSON Linear query responses. [#1515](https://github.com/sourcebot-dev/sourcebot/pull/1515)
- [EE] Continued syncing valid GitHub organizations when the GitHub App is not installed for another configured organization. [#1522](https://github.com/sourcebot-dev/sourcebot/pull/1522)

## [5.1.4] - 2026-07-24

Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/ee/accountPermissionSyncer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ensureFreshAccountToken, TokenRefreshError } from "./tokenRefresh.js";
import { DelayedError, Job, Queue, Worker } from "bullmq";
import { Redis } from "ioredis";
import {
createOctokitFromToken,
createOctokit,
getOAuthScopesForAuthenticatedUser as getGitHubOAuthScopesForAuthenticatedUser,
getReposForAuthenticatedUser,
} from "../github.js";
Expand Down Expand Up @@ -296,7 +296,7 @@ export class AccountPermissionSyncer {
}

if (idpConfig.provider === 'github') {
const { octokit } = await createOctokitFromToken({
const { octokit } = await createOctokit({
token: accessToken,
url: idpConfig.baseUrl,
});
Expand Down
9 changes: 8 additions & 1 deletion packages/backend/src/ee/githubAppManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ type Installation = {
};
};

export class GithubAppInstallationNotFoundError extends Error {
constructor(owner: string, deploymentHostname: string) {
super(`GitHub App installation not found for ${deploymentHostname}/${owner}`);
this.name = 'GithubAppInstallationNotFoundError';
}
}

export class GithubAppManager {
private static instance: GithubAppManager | null = null;
private octokitApps: Map<number, App>;
Expand Down Expand Up @@ -112,7 +119,7 @@ export class GithubAppManager {
const key = this.generateMapKey(owner, deploymentHostname);
const installation = this.installationMap.get(key) as Installation | undefined;
if (!installation) {
throw new Error(`GitHub App Installation not found for ${key}`);
throw new GithubAppInstallationNotFoundError(owner, deploymentHostname);
}

const octokitApp = this.octokitApps.get(installation.appId) as App;
Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/ee/repoPermissionSyncer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { env } from "@sourcebot/shared";
import { hasEntitlement } from "../entitlements.js";
import { DelayedError, Job, Queue, Worker } from 'bullmq';
import { Redis } from 'ioredis';
import { createOctokitFromToken, getRepoCollaborators, GITHUB_CLOUD_HOSTNAME } from "../github.js";
import { createOctokit, getRepoCollaborators, GITHUB_CLOUD_HOSTNAME } from "../github.js";
import { createGitLabFromPersonalAccessToken, getProjectMembers } from "../gitlab.js";
import { createBitbucketCloudClient, createBitbucketServerClient, getExplicitUserPermissionsForCloudRepo, getUserPermissionsForServerRepo } from "../bitbucket.js";
import { repoMetadataSchema } from "@sourcebot/shared";
Expand Down Expand Up @@ -209,7 +209,7 @@ export class RepoPermissionSyncer {
}> => {
if (repo.external_codeHostType === 'github') {
const isGitHubCloud = credentials.hostUrl ? new URL(credentials.hostUrl).hostname === GITHUB_CLOUD_HOSTNAME : true;
const { octokit } = await createOctokitFromToken({
const { octokit } = await createOctokit({
token: credentials.token,
url: isGitHubCloud ? undefined : credentials.hostUrl,
});
Expand Down
132 changes: 80 additions & 52 deletions packages/backend/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { hasEntitlement } from "./entitlements.js";
import micromatch from "micromatch";
import pLimit from "p-limit";
import { processPromiseResults, throwIfAnyFailed } from "./connectionUtils.js";
import { GithubAppManager } from "./ee/githubAppManager.js";
import { GithubAppInstallationNotFoundError, GithubAppManager } from "./ee/githubAppManager.js";
import { fetchWithRetry, measure } from "./utils.js";

export const GITHUB_CLOUD_HOSTNAME = "github.com";
Expand Down Expand Up @@ -100,56 +100,60 @@ const isHttpError = (error: unknown, status: number): boolean => {
&& error.status === status;
}

export const createOctokitFromToken = async ({ token, url }: { token?: string, url?: string }): Promise<{ octokit: Octokit, isAuthenticated: boolean }> => {
/**
* Creates an Octokit client using a GitHub App installation when one is
* configured for the requested owner, or falls back to the provided token.
*/
export const createOctokit = async ({
token,
url,
owner,
context,
}: {
token?: string,
url?: string,
owner?: string,
context?: string,
}): Promise<{ octokit: Octokit, isAuthenticated: boolean }> => {
let resolvedToken = token;

if (owner) {
const githubAppManager = GithubAppManager.getInstance();
await githubAppManager.ensureInitialized();

if (githubAppManager.appsConfigured()) {
if (!await hasEntitlement('github-app')) {
throw new Error(`GitHub App authentication is not currently licensed for ${context ?? owner}.`);
}

try {
const hostname = url ? new URL(url).hostname : GITHUB_CLOUD_HOSTNAME;
resolvedToken = await githubAppManager.getInstallationToken(owner, hostname);
} catch (error) {
if (error instanceof GithubAppInstallationNotFoundError) {
throw error;
}

logger.error(`Error getting GitHub App token for ${context ?? owner}.`, error);
throw error;
}
}
}

const isGitHubCloud = url ? new URL(url).hostname === GITHUB_CLOUD_HOSTNAME : true;
const octokit = new Octokit({
auth: token,
auth: resolvedToken,
...(url && !isGitHubCloud ? {
baseUrl: `${url}/api/v3`
} : {}),
});

return {
octokit,
isAuthenticated: !!token,
isAuthenticated: !!resolvedToken,
};
}

/**
* Uses GitHub App authentication when an app is configured. App initialization
* and token failures are propagated so callers cannot mistake a partial,
* unauthenticated response for an authoritative repository list.
*/
export const getOctokitWithGithubApp = async (
octokit: Octokit,
owner: string,
url: string | undefined,
context: string
): Promise<Octokit> => {
const githubAppManager = GithubAppManager.getInstance();
await githubAppManager.ensureInitialized();
if (!githubAppManager.appsConfigured()) {
return octokit;
}

if (!await hasEntitlement('github-app')) {
throw new Error(`GitHub App authentication is not currently licensed for ${context}.`);
}

try {
const hostname = url ? new URL(url).hostname : GITHUB_CLOUD_HOSTNAME;
const token = await githubAppManager.getInstallationToken(owner, hostname);
const { octokit: octokitFromToken } = await createOctokitFromToken({
token,
url,
});
return octokitFromToken;
} catch (error) {
logger.error(`Error getting GitHub App token for ${context}.`, error);
throw error;
}
}

export const getGitHubReposFromConfig = async (config: GithubConnectionConfig, signal: AbortSignal): Promise<{ repos: OctokitRepository[], warnings: string[] }> => {
const hostname = config.url ?
new URL(config.url).hostname :
Expand All @@ -161,7 +165,7 @@ export const getGitHubReposFromConfig = async (config: GithubConnectionConfig, s
env.FALLBACK_GITHUB_CLOUD_TOKEN :
undefined;

const { octokit, isAuthenticated } = await createOctokitFromToken({
const { octokit, isAuthenticated } = await createOctokit({
token,
url: config.url,
});
Expand All @@ -181,19 +185,19 @@ export const getGitHubReposFromConfig = async (config: GithubConnectionConfig, s
let allWarnings: string[] = [];

if (config.orgs) {
const { repos, warnings } = await getReposForOrgs(config.orgs, octokit, signal, config.url);
const { repos, warnings } = await getReposForOrgs(config.orgs, token, signal, config.url);
allRepos = allRepos.concat(repos);
allWarnings = allWarnings.concat(warnings);
}

if (config.repos) {
const { repos, warnings } = await getRepos(config.repos, octokit, signal, config.url);
const { repos, warnings } = await getRepos(config.repos, token, signal, config.url);
allRepos = allRepos.concat(repos);
allWarnings = allWarnings.concat(warnings);
}

if (config.users) {
const { repos, warnings } = await getReposOwnedByUsers(config.users, octokit, signal, config.url);
const { repos, warnings } = await getReposOwnedByUsers(config.users, token, signal, config.url);
allRepos = allRepos.concat(repos);
allWarnings = allWarnings.concat(warnings);
}
Expand Down Expand Up @@ -291,12 +295,17 @@ export const getOAuthScopesForAuthenticatedUser = async (octokit: Octokit, token
}
}

const getReposOwnedByUsers = async (users: string[], octokit: Octokit, signal: AbortSignal, url?: string) => {
const getReposOwnedByUsers = async (users: string[], token: string | undefined, signal: AbortSignal, url?: string) => {
const results = await Promise.allSettled(users.map((user) => githubQueryLimit(async () => {
try {
logger.debug(`Fetching repository info for user ${user}...`);

const octokitToUse = await getOctokitWithGithubApp(octokit, user, url, `user ${user}`);
const { octokit } = await createOctokit({
token,
url,
owner: user,
context: `user ${user}`,
});
const { durationMs, data } = await measure(async () => {
const fetchFn = async () => {
let query = `user:${user}`;
Expand All @@ -313,7 +322,7 @@ const getReposOwnedByUsers = async (users: string[], octokit: Octokit, signal: A
// signal.aborted between pages. paginate() only passes the signal to
// individual fetch requests but doesn't check abort state between pages.
const allRepos: OctokitRepository[] = [];
const iterator = octokitToUse.paginate.iterator(octokitToUse.rest.search.repos, {
const iterator = octokit.paginate.iterator(octokit.rest.search.repos, {
q: query,
per_page: 100,
request: {
Expand Down Expand Up @@ -364,19 +373,24 @@ const getReposOwnedByUsers = async (users: string[], octokit: Octokit, signal: A
};
}

const getReposForOrgs = async (orgs: string[], octokit: Octokit, signal: AbortSignal, url?: string) => {
const getReposForOrgs = async (orgs: string[], token: string | undefined, signal: AbortSignal, url?: string) => {
const results = await Promise.allSettled(orgs.map((org) => githubQueryLimit(async () => {
try {
logger.debug(`Fetching repository info for org ${org}...`);

const octokitToUse = await getOctokitWithGithubApp(octokit, org, url, `org ${org}`);
const { octokit } = await createOctokit({
token,
url,
owner: org,
context: `org ${org}`,
});
const { durationMs, data } = await measure(async () => {
// @note: We use paginate.iterator() instead of paginate() to check
// signal.aborted between pages. paginate() only passes the signal to
// individual fetch requests but doesn't check abort state between pages.
const fetchFn = async () => {
const allRepos: OctokitRepository[] = [];
const iterator = octokitToUse.paginate.iterator(octokitToUse.repos.listForOrg, {
const iterator = octokit.paginate.iterator(octokit.repos.listForOrg, {
org: org,
per_page: 100,
request: {
Expand All @@ -403,6 +417,15 @@ const getReposForOrgs = async (orgs: string[], octokit: Octokit, signal: AbortSi
data
};
} catch (error) {
if (error instanceof GithubAppInstallationNotFoundError) {
const warning = error.message;
logger.warn(warning);
return {
type: 'warning' as const,
warning
};
}

Sentry.captureException(error);
logger.error(`Failed to fetch repositories for org ${org}.`, error);

Expand All @@ -427,15 +450,20 @@ const getReposForOrgs = async (orgs: string[], octokit: Octokit, signal: AbortSi
};
}

const getRepos = async (repoList: string[], octokit: Octokit, signal: AbortSignal, url?: string) => {
const getRepos = async (repoList: string[], token: string | undefined, signal: AbortSignal, url?: string) => {
const results = await Promise.allSettled(repoList.map((repo) => githubQueryLimit(async () => {
try {
const [owner, repoName] = repo.split('/');
logger.debug(`Fetching repository info for ${repo}...`);

const octokitToUse = await getOctokitWithGithubApp(octokit, owner, url, `repo ${repo}`);
const { octokit } = await createOctokit({
token,
url,
owner,
context: `repo ${repo}`,
});
const { durationMs, data: result } = await measure(async () => {
const fetchFn = () => octokitToUse.repos.get({
const fetchFn = () => octokit.repos.get({
owner,
repo: repoName,
request: {
Expand Down
Loading
Loading