/
auth.ts
91 lines (83 loc) · 2.63 KB
/
auth.ts
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
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
export const envPrefix = 'BUILDER_NODE';
export function setCredentials(credsdir: string, index: number, driver: string, endpoint: string): Array<string> {
let url: URL;
try {
url = new URL(endpoint);
} catch (e) {
return [];
}
switch (url.protocol) {
case 'ssh:': {
return setSSHCreds(credsdir, index, driver, url);
}
case 'tcp:': {
return setBuildKitClientCerts(credsdir, index, driver, url);
}
}
return [];
}
function setSSHCreds(credsdir: string, index: number, driver: string, endpoint: URL): Array<string> {
const driverOpts: Array<string> = [];
const sshkey = process.env[`${envPrefix}_${index}_AUTH_SSH_PPK`] || '';
if (sshkey.length == 0) {
return driverOpts;
}
const sshkeypath = `${credsdir}/ssh_${endpoint.host}.ppk`;
fs.writeFileSync(sshkeypath, sshkey);
fs.chmodSync(sshkeypath, 0o600);
const sshdir = getSSHDir();
fs.mkdirSync(sshdir, {recursive: true});
const sshconfig = `${sshdir}/config`;
fs.appendFileSync(
fs.openSync(sshconfig, 'a'),
`
Host ${endpoint.host}
IdentityFile ${sshkeypath}
ControlMaster auto
ControlPath ~/.ssh/control-%C
ControlPersist yes
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
`
);
fs.chmodSync(sshconfig, 0o600);
return driverOpts;
}
function setBuildKitClientCerts(credsdir: string, index: number, driver: string, endpoint: URL): Array<string> {
const driverOpts: Array<string> = [];
const buildkitCacert = process.env[`${envPrefix}_${index}_AUTH_TLS_CACERT`] || '';
const buildkitCert = process.env[`${envPrefix}_${index}_AUTH_TLS_CERT`] || '';
const buildkitKey = process.env[`${envPrefix}_${index}_AUTH_TLS_KEY`] || '';
if (buildkitCacert.length == 0 && buildkitCert.length == 0 && buildkitKey.length == 0) {
return driverOpts;
}
let host = endpoint.hostname;
if (endpoint.port.length > 0) {
host += `-${endpoint.port}`;
}
if (buildkitCacert.length > 0) {
const cacertpath = `${credsdir}/cacert_${host}.pem`;
fs.writeFileSync(cacertpath, buildkitCacert);
driverOpts.push(`cacert=${cacertpath}`);
}
if (buildkitCert.length > 0) {
const certpath = `${credsdir}/cert_${host}.pem`;
fs.writeFileSync(certpath, buildkitCert);
driverOpts.push(`cert=${certpath}`);
}
if (buildkitKey.length > 0) {
const keypath = `${credsdir}/key_${host}.pem`;
fs.writeFileSync(keypath, buildkitKey);
driverOpts.push(`key=${keypath}`);
}
if (driver != 'remote') {
return [];
}
return driverOpts;
}
export function getSSHDir(): string {
return path.join(os.homedir(), '.ssh');
}