Add Bitbucket Cloud OAuth support

Signed-off-by: Jake Smith <jakemgsmith@gmail.com>
This commit is contained in:
Jake Smith
2025-11-22 01:47:59 +00:00
committed by Fredrik Adelöw
parent e404b12604
commit 959e6ecc5a
15 changed files with 398 additions and 46 deletions
+11 -1
View File
@@ -174,7 +174,7 @@ export interface Config {
* The username to use for authenticated requests.
* @visibility secret
*/
username: string;
username?: string;
/**
* Token used to authenticate requests.
* @visibility secret
@@ -186,6 +186,16 @@ export interface Config {
* @deprecated Use `token` instead.
*/
appPassword?: string;
/**
* OAuth client ID for Bitbucket Cloud.
* @visibility secret
*/
clientId?: string;
/**
* OAuth client secret for Bitbucket Cloud.
* @visibility secret
*/
clientSecret?: string;
/**
* PGP signing key for signing commits.
* @visibility secret
@@ -85,6 +85,39 @@ describe('readBitbucketCloudIntegrationConfig', () => {
).toThrow(/token/);
});
it('reads OAuth configuration', () => {
const output = readBitbucketCloudIntegrationConfig(
buildConfig({
clientId: 'my-client-id',
clientSecret: 'my-client-secret',
}),
);
expect(output).toEqual({
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
clientId: 'my-client-id',
clientSecret: 'my-client-secret',
});
});
it('rejects incomplete OAuth configuration', () => {
expect(() =>
readBitbucketCloudIntegrationConfig(
buildConfig({
clientId: 'my-client-id',
}),
),
).toThrow(/incomplete OAuth configuration/);
expect(() =>
readBitbucketCloudIntegrationConfig(
buildConfig({
clientSecret: 'my-client-secret',
}),
),
).toThrow(/incomplete OAuth configuration/);
});
it('credentials hidden on the frontend', async () => {
const frontendConfig = await buildFrontendConfig({
token: 't',
@@ -103,6 +136,24 @@ describe('readBitbucketCloudIntegrationConfig', () => {
]);
});
it('OAuth credentials hidden on the frontend', async () => {
const frontendConfig = await buildFrontendConfig({
clientId: 'my-client-id',
clientSecret: 'my-client-secret',
});
expect(
readBitbucketCloudIntegrationConfigs(
frontendConfig.getOptionalConfigArray('integrations.bitbucketCloud') ??
[],
),
).toEqual([
{
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
},
]);
});
// TODO: appPassword can be removed once fully
// deprecated by BitBucket on 9th June 2026.
describe('handles deprecated appPassword', () => {
@@ -54,6 +54,20 @@ export type BitbucketCloudIntegrationConfig = {
*/
token?: string;
/**
* The OAuth client ID for Bitbucket Cloud.
*
* See https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/
*/
clientId?: string;
/**
* The OAuth client secret for Bitbucket Cloud.
*
* See https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/
*/
clientSecret?: string;
/** PGP private key for signing commits. */
commitSigningKey?: string;
};
@@ -71,24 +85,36 @@ export function readBitbucketCloudIntegrationConfig(
const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;
// If config is provided, we assume authenticated access is desired
// (as the anonymous one is provided by default).
const username = config.getString('username');
const username = config.getOptionalString('username');
// TODO: appPassword can be removed once fully
// deprecated by BitBucket on 9th June 2026.
const appPassword = config.getOptionalString('appPassword')?.trim();
const token = config.getOptionalString('token');
const clientId = config.getOptionalString('clientId')?.trim();
const clientSecret = config.getOptionalString('clientSecret')?.trim();
if (!token && !appPassword) {
// Validate: if username is provided, token or appPassword is required
if (username && !token && !appPassword) {
throw new Error(
`Bitbucket Cloud integration must be configured with as username and either a token or an appPassword.`,
);
}
// Validate: OAuth requires both clientId and clientSecret
if ((clientId && !clientSecret) || (clientSecret && !clientId)) {
throw new Error(
`Bitbucket Cloud integration has incomplete OAuth configuration. Both clientId and clientSecret are required.`,
);
}
return {
host,
apiBaseUrl,
username,
appPassword,
token,
clientId,
clientSecret,
commitSigningKey: config.getOptionalString('commitSigningKey'),
};
}
@@ -28,13 +28,15 @@ import {
// Mock constants
const BITBUCKET_CLOUD_HOST = 'bitbucket.org';
const BITBUCKET_CLOUD_API_BASE_URL = 'https://api.bitbucket.org/2.0';
const BITBUCKET_CLOUD_OAUTH_TOKEN_URL =
'https://bitbucket.org/site/oauth2/access_token';
describe('bitbucketCloud core', () => {
const worker = setupServer();
registerMswTestHooks(worker);
describe('getBitbucketCloudRequestOptions', () => {
it('insert basic auth when needed', () => {
it('insert basic auth when needed', async () => {
const withUsernameAndToken: BitbucketCloudIntegrationConfig = {
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
@@ -54,20 +56,98 @@ describe('bitbucketCloud core', () => {
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
};
expect(
(getBitbucketCloudRequestOptions(withUsernameAndToken).headers as any)
(await getBitbucketCloudRequestOptions(withUsernameAndToken)).headers
.Authorization,
).toEqual('Basic c29tZS11c2VyQGRvbWFpbi5jb206bXktdG9rZW4=');
expect(
(
getBitbucketCloudRequestOptions(withUsernameAndPassword)
.headers as any
).Authorization,
(await getBitbucketCloudRequestOptions(withUsernameAndPassword)).headers
.Authorization,
).toEqual('Basic c29tZS11c2VyOm15LXNlY3JldA==');
expect(
(getBitbucketCloudRequestOptions(withoutUsername).headers as any)
(await getBitbucketCloudRequestOptions(withoutUsername)).headers
.Authorization,
).toBeUndefined();
});
it('uses OAuth Bearer token when clientId and clientSecret provided', async () => {
worker.use(
rest.post(BITBUCKET_CLOUD_OAUTH_TOKEN_URL, (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({
access_token: 'test-oauth-token',
expires_in: 3600,
}),
),
),
);
const withOAuth: BitbucketCloudIntegrationConfig = {
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
clientId: 'test-client-id',
clientSecret: 'test-client-secret',
};
const result = await getBitbucketCloudRequestOptions(withOAuth);
expect(result.headers.Authorization).toEqual('Bearer test-oauth-token');
});
it('caches OAuth tokens', async () => {
let callCount = 0;
worker.use(
rest.post(BITBUCKET_CLOUD_OAUTH_TOKEN_URL, (_, res, ctx) => {
callCount++;
return res(
ctx.status(200),
ctx.json({
access_token: 'cached-oauth-token',
expires_in: 3600,
}),
);
}),
);
const withOAuth: BitbucketCloudIntegrationConfig = {
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
clientId: 'cache-test-client',
clientSecret: 'cache-test-secret',
};
// First call should fetch token
const result1 = await getBitbucketCloudRequestOptions(withOAuth);
expect(result1.headers.Authorization).toEqual(
'Bearer cached-oauth-token',
);
expect(callCount).toBe(1);
// Second call should use cached token
const result2 = await getBitbucketCloudRequestOptions(withOAuth);
expect(result2.headers.Authorization).toEqual(
'Bearer cached-oauth-token',
);
expect(callCount).toBe(1); // Should still be 1
});
it('handles OAuth token fetch errors', async () => {
worker.use(
rest.post(BITBUCKET_CLOUD_OAUTH_TOKEN_URL, (_, res, ctx) =>
res(ctx.status(401), ctx.json({ error: 'invalid_client' })),
),
);
const withOAuth: BitbucketCloudIntegrationConfig = {
host: BITBUCKET_CLOUD_HOST,
apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,
clientId: 'invalid-client',
clientSecret: 'invalid-secret',
};
await expect(getBitbucketCloudRequestOptions(withOAuth)).rejects.toThrow(
/Failed to fetch OAuth token/,
);
});
});
describe('getBitbucketCloudFileFetchUrl', () => {
+126 -5
View File
@@ -14,9 +14,119 @@
* limitations under the License.
*/
import { createHash } from 'crypto';
import fetch from 'cross-fetch';
import parseGitUrl from 'git-url-parse';
import { BitbucketCloudIntegrationConfig } from './config';
import { DateTime } from 'luxon';
type OAuthTokenData = {
token: string;
expiresAt: DateTime;
};
// In-memory token cache keyed by hashed credentials
const tokenCache = new Map<string, OAuthTokenData>();
// Track in-flight token refresh requests to prevent concurrent fetches
const refreshPromises = new Map<string, Promise<string>>();
/**
* Creates a cache key from OAuth credentials by hashing them.
* This prevents storing credentials in memory in plain text.
*/
function createCacheKey(clientId: string, clientSecret: string): string {
return createHash('sha256')
.update(`${clientId}:${clientSecret}`)
.digest('hex');
}
/**
* Fetches an OAuth access token from Bitbucket Cloud using client credentials flow.
* Tokens are cached with a 10-minute grace period to account for clock skew.
* Implements concurrent refresh protection to prevent multiple simultaneous token requests.
*
* @param clientId - OAuth client ID
* @param clientSecret - OAuth client secret
* @public
*/
export async function getBitbucketCloudOAuthToken(
clientId: string,
clientSecret: string,
): Promise<string> {
const cacheKey = createCacheKey(clientId, clientSecret);
// Check cache
const cached = tokenCache.get(cacheKey);
if (cached && DateTime.now() < cached.expiresAt) {
return cached.token;
}
// Check if there's already a refresh in progress
const inFlight = refreshPromises.get(cacheKey);
if (inFlight) {
return inFlight;
}
// Start a new token fetch and track it
const refreshPromise = (async () => {
try {
// Fetch new token
const credentials = Buffer.from(
`${clientId}:${clientSecret}`,
'utf8',
).toString('base64');
const response = await fetch(
'https://bitbucket.org/site/oauth2/access_token',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${credentials}`,
},
body: 'grant_type=client_credentials',
},
);
if (!response.ok) {
throw new Error(
`Failed to fetch OAuth token from Bitbucket Cloud: ${response.status} ${response.statusText}`,
);
}
const data = await response.json();
if (!data.access_token) {
throw new Error('OAuth token response missing access_token field');
}
// Calculate expiration with 10-minute grace period
const expiresIn = data.expires_in || 3600; // Default to 1 hour
const expiresAt = DateTime.now()
.plus({ seconds: expiresIn })
.minus({ minutes: 10 });
// Cache the token
tokenCache.set(cacheKey, {
token: data.access_token,
expiresAt,
});
return data.access_token;
} catch (error) {
throw new Error(
`Failed to fetch OAuth token for Bitbucket Cloud: ${error}`,
);
} finally {
// Clean up the in-flight promise tracking
refreshPromises.delete(cacheKey);
}
})();
refreshPromises.set(cacheKey, refreshPromise);
return refreshPromise;
}
/**
* Given a URL pointing to a path on a provider, returns the default branch.
@@ -34,7 +144,7 @@ export async function getBitbucketCloudDefaultBranch(
const branchUrl = `${config.apiBaseUrl}/repositories/${project}/${repoName}`;
const response = await fetch(
branchUrl,
getBitbucketCloudRequestOptions(config),
await getBitbucketCloudRequestOptions(config),
);
if (!response.ok) {
@@ -118,18 +228,29 @@ export function getBitbucketCloudFileFetchUrl(
/**
* Gets the request options necessary to make requests to a given provider.
* Returns headers for authenticating with Bitbucket Cloud.
* Supports both username/token and username/appPassword auth.
* Supports OAuth (clientId/clientSecret), username/token, and username/appPassword auth.
*
* @param config - The relevant provider config
* @public
*/
export function getBitbucketCloudRequestOptions(
export async function getBitbucketCloudRequestOptions(
config: BitbucketCloudIntegrationConfig,
): {
): Promise<{
headers: Record<string, string>;
} {
}> {
const headers: Record<string, string> = {};
// OAuth authentication (clientId/clientSecret)
if (config.clientId && config.clientSecret) {
const token = await getBitbucketCloudOAuthToken(
config.clientId,
config.clientSecret,
);
headers.Authorization = `Bearer ${token}`;
return { headers };
}
// Basic authentication (username + token/appPassword)
// TODO: appPassword can be removed once fully
// deprecated by BitBucket on 9th June 2026.
if (config.username && (config.token ?? config.appPassword)) {
@@ -24,5 +24,6 @@ export {
getBitbucketCloudDefaultBranch,
getBitbucketCloudDownloadUrl,
getBitbucketCloudFileFetchUrl,
getBitbucketCloudOAuthToken,
getBitbucketCloudRequestOptions,
} from './core';