Skip to content
Merged
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
3 changes: 2 additions & 1 deletion apps/service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ const tokens = new AppwriteInstallationTokens(appwrite);
const clients: Record<Provider, GitHubClientFactory> = {
github: new InstallationGitHubClientFactory(tokens, { fetch: metrics.instrumentFetch('github') }),
origin: new InstallationOriginClientFactory(tokens, { fetch: metrics.instrumentFetch('origin') }),
// Not handed out by Appwrite yet: these speak to GitLab.com, Bitbucket Cloud and gitea.com.
// GitLab and Gitea default to GitLab.com and gitea.com; a self-hosted installation's token names
// its own API root.
gitlab: new InstallationGitLabClientFactory(tokens, { fetch: metrics.instrumentFetch('gitlab') }),
bitbucket: new InstallationBitbucketClientFactory(tokens, {
fetch: metrics.instrumentFetch('bitbucket')
Expand Down
16 changes: 12 additions & 4 deletions packages/appwrite/src/installation-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { AppwriteApi } from './api';
import type { AppwriteConfig } from './config';

/**
* Installation tokens minted by Appwrite, which owns the GitHub App and its private key. Each is
* scoped to the one repository a review is for; the service never holds the key itself.
* Installation tokens minted by Appwrite, which owns the GitHub and Origin apps and their private
* keys, and the OAuth tokens of GitLab, Gitea and Bitbucket installations. Each is scoped to the
* one repository a review is for; the service never holds a key itself.
*/
export class AppwriteInstallationTokens implements InstallationTokens {
private readonly api: AppwriteApi;
Expand All @@ -14,14 +15,21 @@ export class AppwriteInstallationTokens implements InstallationTokens {
}

async get(repository: { projectId: string; repositoryId: string }): Promise<InstallationToken> {
const { token, expiresAt, appId, appSlug } = await this.api.request<{
const { token, expiresAt, appId, appSlug, endpoint } = await this.api.request<{
token: string;
expiresAt: string;
appId: string;
appSlug: string;
/** A self-hosted GitLab or Gitea's API root. */
endpoint?: string;
}>('POST', `/reviews/repositories/${encodeURIComponent(repository.repositoryId)}/tokens`, {
projectId: repository.projectId
});
return { token, expiresAt: new Date(expiresAt), app: { id: appId, slug: appSlug } };
return {
token,
expiresAt: new Date(expiresAt),
app: { id: appId, slug: appSlug },
...(endpoint ? { endpoint } : {})
};
}
}
22 changes: 22 additions & 0 deletions packages/appwrite/src/results.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,4 +344,26 @@ describe('AppwriteInstallationTokens', () => {
}
]);
});

test('passes on the API root of a self-hosted provider', async () => {
const tokens = new AppwriteInstallationTokens(
serve(() =>
Response.json(
{
token: 'glo_x',
expiresAt: '2026-10-27T13:00:00Z',
appId: '7',
appSlug: 'ada',
provider: 'gitlab',
endpoint: 'https://git.example.com/api/v4'
},
{ status: 201 }
)
)
);

const token = await tokens.get({ projectId: 'project-1', repositoryId: 'repo-1' });

expect(token.endpoint).toBe('https://git.example.com/api/v4');
});
});
22 changes: 22 additions & 0 deletions packages/bitbucket/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,25 @@ describe('BitbucketClient', () => {
expect(await github.hasWriteAccess('ada')).toBe(true);
});
});

describe('InstallationBitbucketClientFactory', () => {
test('reads the workspace from a repository named by its full name', async () => {
const requested: string[] = [];
const apiUrl = serve({
'GET /2.0/repositories/acme/rocket': (request) => {
requested.push(request.path);
return Response.json({
full_name: 'acme/rocket',
links: { html: { href: 'https://bitbucket.org/acme/rocket' }, clone: [] }
});
}
});

const { filesUrl } = await new InstallationBitbucketClientFactory(source, {
apiUrl
}).forRepository({ ...repository, providerRepositoryId: 'acme/rocket', owner: 'Acme Inc' });

expect(requested).toEqual(['/2.0/repositories/acme/rocket']);
expect(filesUrl).toBe('https://bitbucket.org/acme/rocket/src');
});
});
11 changes: 7 additions & 4 deletions packages/bitbucket/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,13 @@ export class InstallationBitbucketClientFactory implements GitHubClientFactory {
}
return current.token;
};
// The repository's `{uuid}` survives a rename; its slug is the fallback.
const path = `/repositories/${encodeURIComponent(repository.owner)}/${encodeURIComponent(
repository.providerRepositoryId || repository.name
)}`;
// The repository's `{uuid}` survives a rename; its slug is the fallback. Appwrite names a
// repository by its full name, `workspace/slug`, which carries the workspace too.
const id = repository.providerRepositoryId || repository.name;
const [workspace, slug] = id.includes('/')
? [id.slice(0, id.indexOf('/')), id.slice(id.indexOf('/') + 1)]
: [repository.owner, id];
const path = `/repositories/${encodeURIComponent(workspace)}/${encodeURIComponent(slug)}`;
const github = new BitbucketClient(
new BitbucketApi(token, this.config),
path,
Expand Down
25 changes: 25 additions & 0 deletions packages/gitea/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,3 +321,28 @@ describe('GiteaClient', () => {
expect(await github.hasWriteAccess('nobody')).toBe(false);
});
});

describe('InstallationGiteaClientFactory', () => {
test('speaks to the self-hosted instance the token names', async () => {
const endpoint = serve({
[`GET ${BY_ID}`]: () =>
Response.json({
name: 'rocket',
owner: { id: 1, login: 'acme' },
html_url: 'https://git.example.com/acme/rocket',
clone_url: 'https://git.example.com/acme/rocket.git'
})
});
const selfHosted: InstallationTokens = {
async get() {
return { ...(await source.get({ projectId: '', repositoryId: '' })), endpoint };
}
};

const { filesUrl } = await new InstallationGiteaClientFactory(selfHosted, {
apiUrl: 'http://127.0.0.1:9/api/v1'
}).forRepository(repository);

expect(filesUrl).toBe('https://git.example.com/acme/rocket/src/commit');
});
});
20 changes: 15 additions & 5 deletions packages/gitea/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export interface InstallationToken {
expiresAt: Date;
/** The bot account: its user id, and the login people mention it by. */
app: { id: string; slug: string };
/**
* The instance's API root when it is self-hosted, e.g. `https://git.example.com/api/v4`. Wins
* over the configured one, since each installation names its own host.
*/
endpoint?: string;
}

/** Hands out the bot's token for one repository: the project's `repositories` row. */
Expand Down Expand Up @@ -71,7 +76,10 @@ export class InstallationGiteaClientFactory implements GitHubClientFactory {
}
return current.token;
};
const api = new GiteaApi(token, this.config);
const api = new GiteaApi(token, {
...this.config,
apiUrl: current.endpoint || this.config.apiUrl
});
// Gitea addresses a repository by owner and name only; its id finds them after a rename.
const found = repository.providerRepositoryId
? await api.request<Repository>(
Expand Down Expand Up @@ -429,10 +437,12 @@ export class GiteaClient implements GitHubClient {
const issues: LinkedIssueRef[] = [];
for (const number of numbers) {
const issue = await this.api
.request<{ number: number; title: string; body?: string; pull_request?: unknown }>(
'GET',
`${this.path}/issues/${number}`
)
.request<{
number: number;
title: string;
body?: string;
pull_request?: unknown;
}>('GET', `${this.path}/issues/${number}`)
.catch(() => null);
if (!issue || issue.pull_request) continue;
issues.push({
Expand Down
2 changes: 2 additions & 0 deletions packages/github/src/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ export interface InstallationToken {
expiresAt: Date;
/** The GitHub App the token is for. */
app: { id: string; slug: string };
/** The provider's API root, when Appwrite names one: a self-hosted GitLab or Gitea. */
endpoint?: string;
}

/**
Expand Down
20 changes: 20 additions & 0 deletions packages/gitlab/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,23 @@ test('contextLines maps unchanged lines to their old numbers', () => {
[13, 12]
]);
});

describe('InstallationGitLabClientFactory', () => {
test('speaks to the self-hosted instance the token names', async () => {
const endpoint = serve({
[`GET ${PROJECT}`]: () =>
Response.json({ id: 42, web_url: 'https://git.example.com/acme/platform/rocket' })
});
const selfHosted: InstallationTokens = {
async get() {
return { ...(await source.get({ projectId: '', repositoryId: '' })), endpoint };
}
};

const { filesUrl } = await new InstallationGitLabClientFactory(selfHosted, {
apiUrl: 'http://127.0.0.1:9/api/v4'
}).forRepository(repository);

expect(filesUrl).toBe('https://git.example.com/acme/platform/rocket/-/blob');
});
});
7 changes: 6 additions & 1 deletion packages/gitlab/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export interface InstallationToken {
expiresAt: Date;
/** The bot account: its user id, and the username people mention it by. */
app: { id: string; slug: string };
/**
* The instance's API root when it is self-hosted, e.g. `https://git.example.com/api/v4`. Wins
* over the configured one, since each installation names its own host.
*/
endpoint?: string;
}

/** Hands out the bot's token for one repository: the project's `repositories` row. */
Expand Down Expand Up @@ -81,7 +86,7 @@ export class InstallationGitLabClientFactory implements GitHubClientFactory {
repository.providerRepositoryId || `${repository.owner}/${repository.name}`
);
const github = new GitLabClient(
new GitLabApi(token, this.config),
new GitLabApi(token, { ...this.config, apiUrl: current.endpoint || this.config.apiUrl }),
`/projects/${project}`,
token,
current.app
Expand Down