snyk-docker-plugin
Version:
Snyk CLI docker plugin
144 lines • 6.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveRegistryCredentials = resolveRegistryCredentials;
const child_process_1 = require("child_process");
const cli_interface_1 = require("@snyk/cli-interface");
const Debug = require("debug");
const fs = require("fs");
const os = require("os");
const path = require("path");
const error_utils_1 = require("../error-utils");
const debug = Debug("snyk");
const DOCKER_HUB_HOST = "docker.io";
const DOCKER_HUB_ALIASES = [
"docker.io",
"index.docker.io",
"registry-1.docker.io",
];
// The key Docker uses for Docker Hub in config.json and credential stores.
const DOCKER_HUB_SERVER_URL = "https://index.docker.io/v1/";
const CREDENTIAL_HELPER_TIMEOUT_MS = 10000;
const CREDENTIAL_HELPER_NAME = /^[A-Za-z0-9._-]+$/;
// Credential helpers return this username for OAuth identity (refresh) tokens.
const IDENTITY_TOKEN_USERNAME = "<token>";
/**
* Resolves credentials for talking to a registry directly.
* Explicit credentials (flags / SNYK_REGISTRY_* env vars) always win. Otherwise
* we fall back to the credentials `docker login` stored, in Docker's own lookup
* order: credHelpers[host], then credsStore, then auths[host].
* Best-effort: never throws, and returns no credentials when none are found.
*/
async function resolveRegistryCredentials(registryHost, username, password) {
if (username || password) {
return { username, password };
}
try {
const credentials = await getDockerConfigCredentials(registryHost);
if (credentials) {
debug(`using docker config credentials for registry ${registryHost}`);
return credentials;
}
}
catch (error) {
debug(`could not read docker config credentials for ${registryHost}: ${(0, error_utils_1.getErrorMessage)(error)}`);
}
return {};
}
async function getDockerConfigCredentials(registryHost) {
const config = readDockerConfig();
if (!config) {
return undefined;
}
const host = normalizeRegistryHost(registryHost);
const findKey = (entries) => Object.keys(entries !== null && entries !== void 0 ? entries : {}).find((key) => normalizeRegistryHost(key) === host);
// Helpers store Docker Hub credentials under its canonical server address,
// whichever alias the config uses.
const serverAddress = (key) => host === DOCKER_HUB_HOST ? DOCKER_HUB_SERVER_URL : key;
const helperKey = findKey(config.credHelpers);
if (helperKey) {
const credentials = await runCredentialHelper(config.credHelpers[helperKey], serverAddress(helperKey));
if (credentials) {
return credentials;
}
}
const authKey = findKey(config.auths);
if (config.credsStore) {
// Stores are keyed by the server address used at `docker login`, which
// `auths` records (with an empty entry) when a store is in use.
const credentials = await runCredentialHelper(config.credsStore, serverAddress(authKey !== null && authKey !== void 0 ? authKey : host));
if (credentials) {
return credentials;
}
}
return authKey ? decodeAuthEntry(config.auths[authKey]) : undefined;
}
function readDockerConfig() {
const configDir = process.env.DOCKER_CONFIG || path.join(os.homedir(), ".docker");
const configPath = path.join(configDir, "config.json");
if (!fs.existsSync(configPath)) {
return undefined;
}
try {
return JSON.parse(fs.readFileSync(configPath, "utf-8"));
}
catch (_a) {
// The parse error is not logged: it can quote config contents, which hold credentials.
debug(`invalid docker config at ${configPath}`);
return undefined;
}
}
// Reduces "https://index.docker.io/v1/", "registry-1.docker.io", etc. to a comparable host.
function normalizeRegistryHost(serverAddress) {
const host = serverAddress
.replace(/^https?:\/\//, "")
.split("/")[0]
.toLowerCase();
return DOCKER_HUB_ALIASES.includes(host) ? DOCKER_HUB_HOST : host;
}
function decodeAuthEntry(entry) {
if (entry === null || entry === void 0 ? void 0 : entry.auth) {
const decoded = Buffer.from(entry.auth, "base64").toString("utf-8");
const separator = decoded.indexOf(":");
if (separator > 0) {
return {
username: decoded.substring(0, separator),
password: decoded.substring(separator + 1),
};
}
}
if ((entry === null || entry === void 0 ? void 0 : entry.username) && (entry === null || entry === void 0 ? void 0 : entry.password)) {
return { username: entry.username, password: entry.password };
}
return undefined;
}
function runCredentialHelper(helperName, serverUrl) {
if (!CREDENTIAL_HELPER_NAME.test(helperName)) {
debug(`ignoring docker credential helper with invalid name`);
return Promise.resolve(undefined);
}
return new Promise((resolve) => {
var _a, _b;
const child = (0, child_process_1.execFile)(`docker-credential-${helperName}`, ["get"], {
timeout: CREDENTIAL_HELPER_TIMEOUT_MS,
env: (0, cli_interface_1.cleanSnykEnv)(process.env, process.env),
}, (error, stdout) => {
if (error) {
debug(`docker-credential-${helperName} returned no credentials for ${serverUrl}`);
return resolve(undefined);
}
try {
const { Username, Secret } = JSON.parse(stdout);
if (!Secret || Username === IDENTITY_TOKEN_USERNAME) {
return resolve(undefined);
}
resolve({ username: Username, password: Secret });
}
catch (_a) {
resolve(undefined);
}
});
(_a = child.stdin) === null || _a === void 0 ? void 0 : _a.on("error", () => undefined);
(_b = child.stdin) === null || _b === void 0 ? void 0 : _b.end(serverUrl);
});
}
//# sourceMappingURL=registry-credentials.js.map