-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
134 lines (106 loc) · 5.58 KB
/
index.js
File metadata and controls
134 lines (106 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
const core = require('@actions/core');
const child_process = require('child_process');
const fs = require('fs');
const crypto = require('crypto');
const { homePath, sshAgentCmd, sshAddCmd, gitCmd } = require('./paths.js');
const axios = require('axios');
async function validateSubscription() {
let repoPrivate;
const eventPath = process.env.GITHUB_EVENT_PATH;
if (eventPath && fs.existsSync(eventPath)) {
const payload = JSON.parse(fs.readFileSync(eventPath, "utf8"));
repoPrivate = payload?.repository?.private;
}
const upstream = "webfactory/ssh-agent";
const action = process.env.GITHUB_ACTION_REPOSITORY;
const docsUrl =
"https://docs.stepsecurity.io/actions/stepsecurity-maintained-actions";
core.info("");
core.info("\u001b[1;36mStepSecurity Maintained Action\u001b[0m");
core.info(`Secure drop-in replacement for ${upstream}`);
if (repoPrivate === false)
core.info("\u001b[32m\u2713 Free for public repositories\u001b[0m");
core.info(`\u001b[36mLearn more:\u001b[0m ${docsUrl}`);
core.info("");
if (repoPrivate === false) return;
const serverUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
const body = { action: action || "" };
if (serverUrl !== "https://github.com") body.ghes_server = serverUrl;
try {
await axios.post(
`https://agent.api.stepsecurity.io/v1/github/${process.env.GITHUB_REPOSITORY}/actions/maintained-actions-subscription`,
body,
{ timeout: 3000 },
);
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 403) {
core.error(
`\u001b[1;31mThis action requires a StepSecurity subscription for private repositories.\u001b[0m`,
);
core.error(
`\u001b[31mLearn how to enable a subscription: ${docsUrl}\u001b[0m`,
);
process.exit(1);
}
core.info("Timeout or API not reachable. Continuing to next step.");
}
}
try {
(async () => {
await validateSubscription();
const privateKey = core.getInput('ssh-private-key');
const logPublicKey = core.getBooleanInput('log-public-key', {default: true});
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.");
return;
}
const homeSsh = homePath + '/.ssh';
fs.mkdirSync(homeSsh, { recursive: true });
console.log("Starting ssh-agent");
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(function(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]}`);
}
});
console.log("Adding private key(s) to agent");
privateKey.split(/(?=-----BEGIN)/).forEach(function(key) {
child_process.execFileSync(sshAddCmd, ['-'], { input: key.trim() + "\n" });
});
console.log("Key(s) added:");
child_process.execFileSync(sshAddCmd, ['-l'], { stdio: 'inherit' });
console.log('Configuring deployment key(s)');
child_process.execFileSync(sshAddCmd, ['-L']).toString().trim().split(/\r?\n/).forEach(function(key) {
const parts = key.match(/\bgithub\.com[:/]([_.a-z0-9-]+\/[_.a-z0-9-]+)/i);
if (!parts) {
if (logPublicKey) {
console.log(`Comment for (public) key '${key}' does not match GitHub URL pattern. Not treating it as a GitHub deploy key.`);
}
return;
}
const sha256 = crypto.createHash('sha256').update(key).digest('hex');
const ownerAndRepo = parts[1].replace(/\.git$/, '');
fs.writeFileSync(`${homeSsh}/key-${sha256}`, key + "\n", { mode: '600' });
child_process.execSync(`${gitCmd} config --global --replace-all url."git@key-${sha256}.github.com:${ownerAndRepo}".insteadOf "https://github.com/${ownerAndRepo}"`);
child_process.execSync(`${gitCmd} config --global --add url."git@key-${sha256}.github.com:${ownerAndRepo}".insteadOf "git@github.com:${ownerAndRepo}"`);
child_process.execSync(`${gitCmd} config --global --add url."git@key-${sha256}.github.com:${ownerAndRepo}".insteadOf "ssh://git@github.com/${ownerAndRepo}"`);
const sshConfig = `\nHost key-${sha256}.github.com\n`
+ ` HostName github.com\n`
+ ` IdentityFile ${homeSsh}/key-${sha256}\n`
+ ` IdentitiesOnly yes\n`;
fs.appendFileSync(`${homeSsh}/config`, sshConfig);
console.log(`Added deploy-key mapping: Use identity '${homeSsh}/key-${sha256}' 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}`);
}
core.setFailed(error.message);
}