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
24 changes: 13 additions & 11 deletions cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,30 @@ function killSshAgent() {
}
}

function restoreGitConfig(maxTries = 3) {
async function restoreGitConfig(maxTries = 3) {
try {
console.log("Restoring git config");
const result = alterGitConfigWithRetry(() => {
const result = await alterGitConfigWithRetry(() => {
return execSync(
`${gitCmd} config --global --get-regexp ".git@${keyFilePrefix}."`,
);
});
}, maxTries);
const sections = result
.toString()
.split(os.EOL)
.map((section) => {
return section.substring(0, section.indexOf(".insteadof"));
});
new Set(sections).forEach((section) => {
for (const section of new Set(sections)) {
if (section !== "") {
console.log(`Removing git config section ${section}`);
alterGitConfigWithRetry(() => {
await alterGitConfigWithRetry(() => {
return execSync(
`${gitCmd} config --global --remove-section ${section}`,
);
});
}, maxTries);
}
});
}
} catch (error) {
console.log(error.message);
console.log("Error restoring git config, proceeding anyway");
Expand Down Expand Up @@ -90,7 +90,9 @@ function removeHostEntries() {
}
}

killSshAgent();
restoreGitConfig();
removeCustomSshKeys();
removeHostEntries();
(async () => {
killSshAgent();
await restoreGitConfig();
removeCustomSshKeys();
removeHostEntries();
})();
34 changes: 17 additions & 17 deletions dist/cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -3457,7 +3457,7 @@ const wait = (msec) =>
setTimeout(resolve, msec);
});

function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
async function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
let tries = 0;
while (tries < maxTries) {
try {
Expand All @@ -3471,11 +3471,9 @@ function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
if (tries === maxTries) {
throw error;
}
(async () => {
const delay = Math.floor(Math.random() * 2000);
core.debug(`Retrying in ${delay}ms...`);
await wait(delay);
})();
const delay = 2000 + Math.floor(Math.random() * 2000);
core.debug(`Retrying in ${delay}ms...`);
await wait(delay);
}
}
}
Expand Down Expand Up @@ -3675,30 +3673,30 @@ function killSshAgent() {
}
}

function restoreGitConfig(maxTries = 3) {
async function restoreGitConfig(maxTries = 3) {
try {
console.log("Restoring git config");
const result = alterGitConfigWithRetry(() => {
const result = await alterGitConfigWithRetry(() => {
return execSync(
`${gitCmd} config --global --get-regexp ".git@${keyFilePrefix}."`,
);
});
}, maxTries);
const sections = result
.toString()
.split(os.EOL)
.map((section) => {
return section.substring(0, section.indexOf(".insteadof"));
});
new Set(sections).forEach((section) => {
for (const section of new Set(sections)) {
if (section !== "") {
console.log(`Removing git config section ${section}`);
alterGitConfigWithRetry(() => {
await alterGitConfigWithRetry(() => {
return execSync(
`${gitCmd} config --global --remove-section ${section}`,
);
});
}, maxTries);
}
});
}
} catch (error) {
console.log(error.message);
console.log("Error restoring git config, proceeding anyway");
Expand Down Expand Up @@ -3750,10 +3748,12 @@ function removeHostEntries() {
}
}

killSshAgent();
restoreGitConfig();
removeCustomSshKeys();
removeHostEntries();
(async () => {
killSshAgent();
await restoreGitConfig();
removeCustomSshKeys();
removeHostEntries();
})();

module.exports = __webpack_exports__;
/******/ })()
Expand Down
180 changes: 92 additions & 88 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3457,7 +3457,7 @@ const wait = (msec) =>
setTimeout(resolve, msec);
});

function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
async function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
let tries = 0;
while (tries < maxTries) {
try {
Expand All @@ -3471,11 +3471,9 @@ function alterGitConfigWithRetry(alterFunction, maxTries = 3) {
if (tries === maxTries) {
throw error;
}
(async () => {
const delay = Math.floor(Math.random() * 2000);
core.debug(`Retrying in ${delay}ms...`);
await wait(delay);
})();
const delay = 2000 + Math.floor(Math.random() * 2000);
core.debug(`Retrying in ${delay}ms...`);
await wait(delay);
}
}
}
Expand Down Expand Up @@ -3674,89 +3672,94 @@ const { homePath, sshAgentCmd, sshAddCmd, gitCmd } = __nccwpck_require__(644);
const { keyFilePrefix } = __nccwpck_require__(334);
const { alterGitConfigWithRetry } = __nccwpck_require__(561);

try {
const privateKey = core.getInput("ssh-private-key");
const logPublicKey = core.getBooleanInput("log-public-key", {
default: true,
});
const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", {
default: false,
});
(async () => {
try {
const privateKey = core.getInput("ssh-private-key");
const logPublicKey = core.getBooleanInput("log-public-key", {
default: true,
});
const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", {
default: false,
});

if (!privateKey) {
core.setFailed(
"The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.",
);
if (!privateKey) {
core.setFailed(
"The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.",
);

process.exit(1);
}
process.exit(1);
}

const homeSsh = `${homePath}/.ssh`;
fs.mkdirSync(homeSsh, { recursive: true });
const homeSsh = `${homePath}/.ssh`;
fs.mkdirSync(homeSsh, { recursive: true });

if (fetchGithubHostKeys) {
console.log("Fetching GitHub host keys");
try {
// Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows)
const curlCmd =
process.platform === "win32"
? "curl.exe --silent https://api.github.com/meta"
: "curl --silent https://api.github.com/meta";

const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" });

const meta = JSON.parse(metaJson);
const knownHostsFile = `${homeSsh}/known_hosts`;
const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`;
fs.appendFileSync(knownHostsFile, hostKeyLines);
console.log(
`Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`,
);
} catch (error) {
console.warn(`Failed to fetch GitHub host keys: ${error.message}`);
if (fetchGithubHostKeys) {
console.log("Fetching GitHub host keys");
try {
// Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows)
const curlCmd =
process.platform === "win32"
? "curl.exe --silent https://api.github.com/meta"
: "curl --silent https://api.github.com/meta";

const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" });

const meta = JSON.parse(metaJson);
const knownHostsFile = `${homeSsh}/known_hosts`;
const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`;
fs.appendFileSync(knownHostsFile, hostKeyLines);
console.log(
`Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`,
);
} catch (error) {
console.warn(`Failed to fetch GitHub host keys: ${error.message}`);
}
}
}

console.log("Starting ssh-agent");
console.log("Starting ssh-agent");

const authSock = core.getInput("ssh-auth-sock");
const sshAgentArgs = authSock && authSock.length > 0 ? ["-a", authSock] : [];
const authSock = core.getInput("ssh-auth-sock");
const sshAgentArgs =
authSock && authSock.length > 0 ? ["-a", authSock] : [];

// Extract auth socket path and agent pid and set them as job variables
child_process
.execFileSync(sshAgentCmd, sshAgentArgs)
.toString()
.split("\n")
.forEach((line) => {
const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec(
line,
);
// Extract auth socket path and agent pid and set them as job variables
child_process
.execFileSync(sshAgentCmd, sshAgentArgs)
.toString()
.split("\n")
.forEach((line) => {
const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec(
line,
);

if (matches && matches.length > 0) {
// This will also set process.env accordingly, so changes take effect for this script
core.exportVariable(matches[1], matches[2]);
console.log(`${matches[1]}=${matches[2]}`);
}
});
if (matches && matches.length > 0) {
// This will also set process.env accordingly, so changes take effect for this script
core.exportVariable(matches[1], matches[2]);
console.log(`${matches[1]}=${matches[2]}`);
}
});

console.log("Adding private key(s) to agent");
console.log("Adding private key(s) to agent");

privateKey.split(/(?=-----BEGIN)/).forEach((key) => {
child_process.execFileSync(sshAddCmd, ["-"], { input: `${key.trim()}\n` });
});
privateKey.split(/(?=-----BEGIN)/).forEach((key) => {
child_process.execFileSync(sshAddCmd, ["-"], {
input: `${key.trim()}\n`,
});
});

console.log("Key(s) added:");

console.log("Key(s) added:");
child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" });

child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" });
console.log("Configuring deployment key(s)");

console.log("Configuring deployment key(s)");
const publicKeys = child_process
.execFileSync(sshAddCmd, ["-L"])
.toString()
.trim()
.split(/\r?\n/);

child_process
.execFileSync(sshAddCmd, ["-L"])
.toString()
.trim()
.split(/\r?\n/)
.forEach((key) => {
for (const key of publicKeys) {
const parts = key.match(/\bgithub\.com[:/]([_.a-z0-9-]+\/[_.a-z0-9-]+)/i);

if (!parts) {
Expand All @@ -3765,7 +3768,7 @@ try {
`Comment for (public) key '${key}' does not match GitHub URL pattern. Not treating it as a GitHub deploy key.`,
);
}
return;
continue;
}

const sha256 = crypto.createHash("sha256").update(key).digest("hex");
Expand All @@ -3774,17 +3777,17 @@ try {

fs.writeFileSync(`${homeSsh}/${keyFile}`, `${key}\n`, { mode: "600" });

alterGitConfigWithRetry(() => {
await alterGitConfigWithRetry(() => {
return child_process.execSync(
`${gitCmd} config --global --replace-all url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "https://github.com/${ownerAndRepo}"`,
);
});
alterGitConfigWithRetry(() => {
await alterGitConfigWithRetry(() => {
return child_process.execSync(
`${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "git@github.com:${ownerAndRepo}"`,
);
});
alterGitConfigWithRetry(() => {
await alterGitConfigWithRetry(() => {
return child_process.execSync(
`${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "ssh://git@github.com/${ownerAndRepo}"`,
);
Expand All @@ -3797,17 +3800,18 @@ try {
console.log(
`Added deploy-key mapping: Use identity '${homeSsh}/${keyFile}' for GitHub repository ${ownerAndRepo}`,
);
});
} catch (error) {
if (error.code === "ENOENT") {
console.log(
`The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`,
);
console.log(`PATH is set to: ${process.env.PATH}`);
}
}
} catch (error) {
if (error.code === "ENOENT") {
console.log(
`The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`,
);
console.log(`PATH is set to: ${process.env.PATH}`);
}

core.setFailed(error.message);
}
core.setFailed(error.message);
}
})();

module.exports = __webpack_exports__;
/******/ })()
Expand Down
Loading
Loading