mirror of
https://github.com/renovatebot/renovate.git
synced 2026-11-01 10:09:50 +00:00
f0dd862bd5
* refactor(python): share PyPI index credential resolution
pipenv, poetry, uv, pip-compile and the pypi datasource each resolved
index credentials differently, so a host rule that worked for one Python
manager did not necessarily work for the next. Add
`findPypiIndexCredentials()` in `lib/modules/datasource/pypi/host-rules.ts`,
which strips the URL's own `user:password@` part, runs a `pypi`-scoped
`hostRules.find()`, and only falls back to Google Artifact Registry when
the matched rule has no username and no password. The repeated
`.pkg.dev` test moves into a single `isGoogleArtifactRegistry()`
predicate next to `getGoogleAuthHostRule()`.
Behaviour changes:
- pipenv now supports Google Artifact Registry; previously it only ever
consulted host rules.
Spec: manager/pipenv/artifacts > "passes Google Artifact Registry
credential environment vars"
- pip-compile now supports Google Artifact Registry.
Spec: manager/pip-compile/common > getRegistryCredVarsFromPackageFiles()
> "supports Google Artifact Registry"
- pip-compile now matches `hostType: pypi` rules; its find call was
unscoped, so such rules were skipped.
Spec: manager/pip-compile/common > getRegistryCredVarsFromPackageFiles()
> "ignores a rule scoped to another hostType"
- pip-compile now matches a `matchHost` that contains a path; it reduced
every registry URL to its origin first, and `matchesHost()` compares
with `href.startsWith()`, so a path-scoped rule could never match.
Spec: manager/pip-compile/common > getRegistryCredVarsFromPackageFiles()
> "matches a rule scoped to a path"
- poetry and uv now strip `${USER}:${PASS}@` style placeholders from the
index URL before matching, so a `matchHost` can match those URLs too.
Spec: datasource/pypi/host-rules > "strips credentials from the URL
before matching"
- poetry now falls back to Google Artifact Registry when the matched rule
carries no username or password; any non-empty rule used to suppress
the fallback. Its dead unscoped `find({ url })` fallback is gone: a
`pypi`-scoped find already matches every rule an unscoped one would.
Spec: manager/poetry/artifacts > "falls back to Google auth when the
matching rule has no credentials"
- the pypi datasource now prefers host rule credentials over the Google
token for `*.pkg.dev`; it took the Google token unconditionally, and
the resulting `authorization` header made `applyHostRule()` skip the
configured credentials.
Spec: datasource/pypi/index > getReleases > "prefers host rule
credentials over Google Auth"
`getRegistryCredEnvVars()` also no longer logs the whole matched host
rule as the log merge object.
* test(pipenv): inline the Google Artifact Registry Pipfile
The fixture was used by a single spec case; inline it as requested in the
review of #46127.
* test(datasource/pypi): cover partial Google Artifact Registry credentials
A host rule that carries only a username or only a password still produces a
Basic header, but nothing exercised those two `?? ''` fallbacks, so the merge
queue failed the global branch threshold.
189 lines
6.0 KiB
TypeScript
189 lines
6.0 KiB
TypeScript
import { pipenv as pipenvDetect } from '@renovatebot/detect-tools';
|
|
import {
|
|
isNonEmptyStringAndNotWhitespace,
|
|
isUrlInstance,
|
|
} from '@sindresorhus/is';
|
|
import { TEMPORARY_ERROR } from '../../../constants/error-messages.ts';
|
|
import { logger } from '../../../logger/index.ts';
|
|
import { coerceArray } from '../../../util/array.ts';
|
|
import { exec } from '../../../util/exec/index.ts';
|
|
import type { ExecOptions, ExtraEnv, Opt } from '../../../util/exec/types.ts';
|
|
import {
|
|
deleteLocalFile,
|
|
ensureCacheDir,
|
|
getParentDir,
|
|
localPathExists,
|
|
readLocalFile,
|
|
writeLocalFile,
|
|
} from '../../../util/fs/index.ts';
|
|
import { ensureLocalPath } from '../../../util/fs/util.ts';
|
|
import { getRepoStatus } from '../../../util/git/index.ts';
|
|
import { regEx } from '../../../util/regex.ts';
|
|
import { parseUrl } from '../../../util/url.ts';
|
|
import { findPypiIndexCredentials } from '../../datasource/pypi/host-rules.ts';
|
|
import type { UpdateArtifact, UpdateArtifactsResult } from '../types.ts';
|
|
import { resolveToolConstraint } from '../util.ts';
|
|
import { extractPackageFile } from './extract.ts';
|
|
|
|
async function findPipfileSourceUrlsWithCredentials(
|
|
pipfileContent: string,
|
|
pipfileName: string,
|
|
): Promise<URL[]> {
|
|
const pipfile = await extractPackageFile(pipfileContent, pipfileName);
|
|
|
|
return coerceArray(
|
|
pipfile?.registryUrls
|
|
?.map(parseUrl)
|
|
.filter(isUrlInstance)
|
|
.filter((url) => isNonEmptyStringAndNotWhitespace(url.username)),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* This will extract the actual variable name from an environment-placeholder:
|
|
* ${USERNAME:-defaultvalue} will yield 'USERNAME'
|
|
*/
|
|
export function extractEnvironmentVariableName(
|
|
credential: string,
|
|
): string | null {
|
|
const match = regEx('([a-z0-9_]+)', 'i').exec(decodeURI(credential));
|
|
return match?.length ? match[0] : null;
|
|
}
|
|
|
|
export function addExtraEnvVariable(
|
|
extraEnv: ExtraEnv,
|
|
environmentVariableName: string,
|
|
environmentValue: string,
|
|
): void {
|
|
logger.trace(
|
|
`Adding ${environmentVariableName} environment variable for pipenv`,
|
|
);
|
|
if (
|
|
extraEnv[environmentVariableName] &&
|
|
extraEnv[environmentVariableName] !== environmentValue
|
|
) {
|
|
logger.warn(
|
|
{ envVar: environmentVariableName },
|
|
'Possible misconfiguration, environment variable already set to a different value',
|
|
);
|
|
}
|
|
extraEnv[environmentVariableName] = environmentValue;
|
|
}
|
|
|
|
/**
|
|
* Pipenv allows configuring source-urls for remote repositories with placeholders for credentials, i.e. http://$USER:$PASS@myprivate.repo
|
|
* if a matching host rule exists for that repository, we need to set the corresponding variables.
|
|
* Simply substituting them in the URL is not an option as it would impact the hash for the resulting Pipfile.lock
|
|
*
|
|
*/
|
|
async function addCredentialsForSourceUrls(
|
|
newPipfileContent: string,
|
|
pipfileName: string,
|
|
extraEnv: ExtraEnv,
|
|
): Promise<void> {
|
|
const sourceUrls = await findPipfileSourceUrlsWithCredentials(
|
|
newPipfileContent,
|
|
pipfileName,
|
|
);
|
|
for (const parsedSourceUrl of sourceUrls) {
|
|
logger.trace(`Trying to add credentials for ${parsedSourceUrl.toString()}`);
|
|
const credentials = await findPypiIndexCredentials(
|
|
parsedSourceUrl.toString(),
|
|
);
|
|
const usernameVariableName = extractEnvironmentVariableName(
|
|
parsedSourceUrl.username,
|
|
);
|
|
// v8 ignore else -- needs a host rule carrying only one of the two
|
|
if (credentials.username && usernameVariableName) {
|
|
addExtraEnvVariable(extraEnv, usernameVariableName, credentials.username);
|
|
}
|
|
const passwordVariableName = extractEnvironmentVariableName(
|
|
parsedSourceUrl.password,
|
|
);
|
|
// v8 ignore else -- needs a host rule carrying only one of the two
|
|
if (credentials.password && passwordVariableName) {
|
|
addExtraEnvVariable(extraEnv, passwordVariableName, credentials.password);
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function updateArtifacts({
|
|
packageFileName: pipfileName,
|
|
newPackageFileContent: newPipfileContent,
|
|
config,
|
|
}: UpdateArtifact): Promise<UpdateArtifactsResult[] | null> {
|
|
logger.debug(`pipenv.updateArtifacts(${pipfileName})`);
|
|
|
|
const lockFileName = `${pipfileName}.lock`;
|
|
if (!(await localPathExists(lockFileName))) {
|
|
logger.debug('No Pipfile.lock found');
|
|
return null;
|
|
}
|
|
try {
|
|
await writeLocalFile(pipfileName, newPipfileContent);
|
|
if (config.isLockFileMaintenance) {
|
|
await deleteLocalFile(lockFileName);
|
|
}
|
|
const cmd = 'pipenv lock';
|
|
const pipfileDir = getParentDir(ensureLocalPath(pipfileName));
|
|
const tagConstraint = await resolveToolConstraint(config, 'python', () =>
|
|
pipenvDetect.getPythonConstraint(pipfileDir),
|
|
);
|
|
const pipenvConstraint = await resolveToolConstraint(config, 'pipenv', () =>
|
|
pipenvDetect.getPipenvConstraint(pipfileDir),
|
|
);
|
|
const extraEnv: Opt<ExtraEnv> = {
|
|
PIPENV_CACHE_DIR: await ensureCacheDir('pipenv'),
|
|
PIP_CACHE_DIR: await ensureCacheDir('pip'),
|
|
WORKON_HOME: await ensureCacheDir('virtualenvs'),
|
|
};
|
|
const execOptions: ExecOptions = {
|
|
cwdFile: pipfileName,
|
|
docker: {},
|
|
toolConstraints: [
|
|
{
|
|
toolName: 'python',
|
|
constraint: tagConstraint,
|
|
},
|
|
{
|
|
toolName: 'pipenv',
|
|
constraint: pipenvConstraint,
|
|
},
|
|
],
|
|
};
|
|
await addCredentialsForSourceUrls(newPipfileContent, pipfileName, extraEnv);
|
|
execOptions.extraEnv = extraEnv;
|
|
|
|
logger.trace({ cmd }, 'pipenv lock command');
|
|
await exec(cmd, execOptions);
|
|
const status = await getRepoStatus();
|
|
if (!status?.modified.includes(lockFileName)) {
|
|
return null;
|
|
}
|
|
logger.debug('Returning updated Pipfile.lock');
|
|
return [
|
|
{
|
|
file: {
|
|
type: 'addition',
|
|
path: lockFileName,
|
|
contents: await readLocalFile(lockFileName, 'utf8'),
|
|
},
|
|
},
|
|
];
|
|
} catch (err) {
|
|
// istanbul ignore if
|
|
if (err.message === TEMPORARY_ERROR) {
|
|
throw err;
|
|
}
|
|
logger.debug({ err }, 'Failed to update Pipfile.lock');
|
|
return [
|
|
{
|
|
artifactError: {
|
|
fileName: lockFileName,
|
|
stderr: err.message,
|
|
},
|
|
},
|
|
];
|
|
}
|
|
}
|