Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pypi): support GCloud credentials for Google Artifact Registry #31262

Merged
merged 3 commits into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
43 changes: 43 additions & 0 deletions lib/modules/datasource/pypi/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,49 @@ exports[`modules/datasource/pypi/index getReleases respects constraints 1`] = `
}
`;

exports[`modules/datasource/pypi/index supports Google Auth with simple endpoint 1`] = `
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
{
"isPrivate": true,
"registryUrl": "https://someregion-python.pkg.dev/some-project/some-repo/simple",
"releases": [
{
"version": "0.1.2",
},
{
"version": "0.1.3",
},
{
"version": "0.1.4",
},
{
"version": "0.2.0",
},
{
"version": "0.2.1",
},
{
"version": "0.2.2",
},
{
"version": "0.3.0",
},
{
"version": "0.4.0",
},
{
"version": "0.4.1",
},
{
"version": "0.4.2",
},
{
"isDeprecated": true,
"version": "0.5.0",
},
],
}
`;

exports[`modules/datasource/pypi/index uses https://pypi.org/pypi/ instead of https://pypi.org/simple/ 1`] = `
{
"registryUrl": "https://pypi.org/simple",
Expand Down
101 changes: 101 additions & 0 deletions lib/modules/datasource/pypi/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { GoogleAuth as _googleAuth } from 'google-auth-library';
import { getPkgReleases } from '..';
import { Fixtures } from '../../../../test/fixtures';
import * as httpMock from '../../../../test/http-mock';
import { mocked } from '../../../../test/util';
import * as hostRules from '../../../util/host-rules';
import { PypiDatasource } from '.';

const googleAuth = mocked(_googleAuth);
jest.mock('google-auth-library');

const res1 = Fixtures.get('azure-cli-monitor.json');
const htmlResponse = Fixtures.get('versions-html.html');
const mixedCaseResponse = Fixtures.get('versions-html-mixed-case.html');
Expand Down Expand Up @@ -125,6 +130,64 @@ describe('modules/datasource/pypi/index', () => {
});
});

it('supports Google Auth', async () => {
httpMock
.scope('https://someregion-python.pkg.dev/some-project/some-repo/')
.get('/azure-cli-monitor/json')
.matchHeader(
'authorization',
'Basic b2F1dGgyYWNjZXNzdG9rZW46c29tZS10b2tlbg==',
)
.reply(200, Fixtures.get('azure-cli-monitor-updated.json'));
const config = {
registryUrls: [
'https://someregion-python.pkg.dev/some-project/some-repo',
],
};
googleAuth.mockImplementationOnce(
jest.fn().mockImplementationOnce(() => ({
getAccessToken: jest.fn().mockResolvedValue('some-token'),
})),
);
const res = await getPkgReleases({
...config,
datasource,
packageName: 'azure-cli-monitor',
});
expect(res?.releases.pop()).toMatchObject({
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
version: '0.2.15',
releaseTimestamp: '2019-06-18T13:58:55.000Z',
});
expect(googleAuth).toHaveBeenCalledTimes(1);
});

it('supports Google Auth not being configured', async () => {
httpMock
.scope('https://someregion-python.pkg.dev/some-project/some-repo/')
.get('/azure-cli-monitor/json')
.reply(200, Fixtures.get('azure-cli-monitor-updated.json'));
const config = {
registryUrls: [
'https://someregion-python.pkg.dev/some-project/some-repo',
],
};
googleAuth.mockImplementation(
jest.fn().mockImplementation(() => ({
getAccessToken: jest.fn().mockResolvedValue(undefined),
})),
);
const res = await getPkgReleases({
...config,
datasource,
packageName: 'azure-cli-monitor',
});
expect(res?.releases.pop()).toMatchObject({
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
version: '0.2.15',
releaseTimestamp: '2019-06-18T13:58:55.000Z',
});
expect(googleAuth).toHaveBeenCalledTimes(1);
});

it('returns non-github home_page', async () => {
httpMock
.scope(baseUrl)
Expand Down Expand Up @@ -643,6 +706,44 @@ describe('modules/datasource/pypi/index', () => {
});
});

it('supports Google Auth with simple endpoint', async () => {
httpMock
.scope('https://someregion-python.pkg.dev/some-project/some-repo/simple/')
.get('/dj-database-url/')
.reply(200, htmlResponse);
const config = {
registryUrls: [
'https://someregion-python.pkg.dev/some-project/some-repo/simple/',
],
};
googleAuth.mockImplementationOnce(
jest.fn().mockImplementationOnce(() => ({
getAccessToken: jest.fn().mockResolvedValue('some-token'),
})),
);
expect(
await getPkgReleases({
datasource,
...config,
constraints: { python: '2.7' },
packageName: 'dj-database-url',
}),
).toMatchSnapshot();
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
expect(googleAuth).toHaveBeenCalledTimes(1);
});

it('ignores an invalid URL when checking for auth headers', async () => {
const config = {
registryUrls: ['not-a-url/simple/'],
};
const res = await getPkgReleases({
...config,
datasource,
packageName: 'azure-cli-monitor',
});
expect(res?.releases.pop()).toBeNil();
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
});

it('uses https://pypi.org/pypi/ instead of https://pypi.org/simple/', async () => {
httpMock.scope(baseUrl).get('/azure-cli-monitor/json').reply(200, res1);
const config = {
Expand Down
31 changes: 29 additions & 2 deletions lib/modules/datasource/pypi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ import changelogFilenameRegex from 'changelog-filename-regex';
import { logger } from '../../../logger';
import { coerceArray } from '../../../util/array';
import { parse } from '../../../util/html';
import type { OutgoingHttpHeaders } from '../../../util/http/types';
import { regEx } from '../../../util/regex';
import { ensureTrailingSlash } from '../../../util/url';
import * as pep440 from '../../versioning/pep440';
import { Datasource } from '../datasource';
import type { GetReleasesConfig, Release, ReleaseResult } from '../types';
import { getGoogleAuthToken } from '../util';
import { isGitHubRepo, normalizePythonDepName } from './common';
import type { PypiJSON, PypiJSONRelease, Releases } from './types';

const googleArtifactRegistryDomain = '.pkg.dev';
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved

export class PypiDatasource extends Datasource {
static readonly id = 'pypi';

Expand Down Expand Up @@ -82,6 +86,27 @@ export class PypiDatasource extends Datasource {
return dependency;
}

private async getAuthHeaders(
lookupUrl: string,
): Promise<OutgoingHttpHeaders> {
let url: URL;
try {
url = new URL(lookupUrl);
maxbrunet marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
logger.once.debug({ lookupUrl, err }, 'Failed to parse URL');
return {};
}
if (url.hostname.endsWith(googleArtifactRegistryDomain)) {
const auth = await getGoogleAuthToken();
if (auth) {
return { authorization: `Basic ${auth}` };
}
logger.once.debug({ lookupUrl }, 'Could not get Google access token');
return {};
}
return {};
}

private async getDependency(
packageName: string,
hostUrl: string,
Expand All @@ -92,7 +117,8 @@ export class PypiDatasource extends Datasource {
);
const dependency: ReleaseResult = { releases: [] };
logger.trace({ lookupUrl }, 'Pypi api got lookup');
const rep = await this.http.getJson<PypiJSON>(lookupUrl);
const headers = await this.getAuthHeaders(lookupUrl);
const rep = await this.http.getJson<PypiJSON>(lookupUrl, { headers });
const dep = rep?.body;
if (!dep) {
logger.trace({ dependency: packageName }, 'pip package not found');
Expand Down Expand Up @@ -237,7 +263,8 @@ export class PypiDatasource extends Datasource {
ensureTrailingSlash(normalizePythonDepName(packageName)),
);
const dependency: ReleaseResult = { releases: [] };
const response = await this.http.get(lookupUrl);
const headers = await this.getAuthHeaders(lookupUrl);
const response = await this.http.get(lookupUrl, { headers });
const dep = response?.body;
if (!dep) {
logger.trace({ dependency: packageName }, 'pip package not found');
Expand Down