-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
174 lines (159 loc) · 6.2 KB
/
index.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#! /usr/bin/env node
var debug = require('debug')('vault-pki-client:main'),
config = require('./config'),
Promise = require('bluebird'),
util = require('util'),
request = require('request-promise'),
pkginfo = require('./package.json'),
child = Promise.promisifyAll(require('child_process')),
fs = Promise.promisifyAll(require('fs')),
MAX_TIMEOUT = 0x7FFFFFFF; // http://nodejs.org/api/all.html#all_settimeout_cb_ms
var token = config.vault.token;
function main() {
if (config.version) {
console.log(pkginfo.name + " v" + pkginfo.version);
process.exit(0);
}
Promise.resolve()
.then(config.vault["token-renewable"] ? renewVaultToken : Promise.resolve)
.then(fetchCert)
.catch(function(e) {
if (e && e.name && e.name == "StatusCodeError") {
console.error("Vault error: " + e.statusCode + " " + e.error.errors.join(" "));
} else {
console.error(e);
}
});
}
var fetchCert = (function() {
var debug = require('debug')('vault-pki-client:certRenewal');
var exec, args = [];
if (config.onUpdate) {
args = config.onUpdate.split(/\s+/);
exec = args.shift();
}
return function() {
var path = [config.vault.pki.path, "issue", config.vault.pki.role].join("/");
debug("Attempting to fetch a keypair from " + path);
var opts = {
common_name: config.certCN,
alt_names: config.certAltNames.join(","),
ip_sans: config.certIPs.join(",")
}
if (config.certTTL) opts.ttl = config.certTTL;
return vaultRequest(path, 'POST', opts).then(function(data) {
return Promise.all([
saveKey(data.data.private_key),
saveCert(data.data.certificate),
saveCA(data.data.issuing_ca)
]).then(function() {
if (config.once) return Promise.resolve();
var next = data.lease_duration * config.renewalCoefficient * 1000;
if (next > MAX_TIMEOUT) {
debug("Renewal of " + next + "ms is longer than max timer of " + MAX_TIMEOUT + "ms. Truncating");
next = MAX_TIMEOUT;
}
debug("Next renewal in " + next + "ms");
setTimeout(fetchCert, next);
}).then(function() {
if (config.onUpdate) {
debug("Executing " + exec + " " + args.join(" "));
return child.spawnAsync(exec, args, {});
} else {
return Promise.resolve();
}
}).catch(function(e) {
debug("Failed to fetch and update keypair");
console.error(e);
});
});
};
function saveKey(data) {
debug("Writing private key to " + config.keyFile);
return fs.writeFileAsync(config.keyFile, data);
}
function saveCert(data) {
debug("Writing certificate to " + config.certFile);
return fs.writeFileAsync(config.certFile, data);
}
function saveCA(data) {
if (!config.caFile) return Promise.resolve();
debug("Writing CA certificate to " + config.caFile);
return fs.writeFileAsync(config.caFile, data);
}
})();
// Attempt to periodically renew the vault token
var renewVaultToken = (function() {
var debug = require('debug')('vault-pki-client:tokenRenewal');
return function() {
debug("Attempting to renew vault token");
return vaultRequest('auth/token/renew-self','POST').then(function(data) {
token = data.auth.client_token;
debug("Token renewal succeeded");
if (data.auth.renewable) {
var next = data.auth.lease_duration * config.renewalCoefficient * 1000;
if (next > MAX_TIMEOUT) {
debug("Renewal of " + next + "ms is longer than max timer of " + MAX_TIMEOUT + "ms. Truncating");
next = MAX_TIMEOUT;
}
debug("Next renewal in " + next + "ms");
setTimeout(renewVaultToken, next).unref();
}
return Promise.resolve();
}).catch(function(err) {
debug("Token renewal failed");
console.error(err);
return Promise.reject();
});
};
})();
// Build request options
function buildReqOpts() {
var reqOpts = {
ca:[],
rejectUnauthorized: !config.vault.server["tls-skip-verify"],
followAllRedirects: false
};
if (config.vault.server["ca-path"]) {
// This won't work for bundle files with multiple CAs in a single file...
var match = "-----BEGIN CERTIFICATE-----",
len = match.length;
fs.readdirSync(config.vault.server["ca-path"]).forEach(function(file) {
file = [config.vault.server["ca-path"], file].join("/");
if (!fs.statSync(file).isFile()) return;
var buf = fs.readFileSync(file);
if (buf.slice(0, len) == match)
reqOpts.ca.push(buf);
})
}
if (config.vault.server["ca-cert"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["ca-cert"]));
// Fallback to default node-bundled CAs
if (reqOpts.ca.length == 0)
delete reqOpts.ca;
if (config.vault.server["client-cert"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["client-cert"]));
if (config.vault.server["client-key"])
reqOpts.ca.push(fs.readFileSync(config.vault.server["ca-cert"]));
return reqOpts;
}
var vaultRequest = (function () {
var debug = require('debug')('vault-pki-client:http');
var defOpts = buildReqOpts();
return function(url, method, body) {
method = method || "GET";
body = body || undefined;
var opts = util._extend(defOpts, {
url: [config.vault.server['address'], config.vault.server['api-version'], url].join("/"),
headers: {
"X-Vault-Token": token
},
method: method,
body: body,
json: true
});
debug(method + "ing data to " + opts.url);
return request(opts).then(function(data) {debug("Got data: " + data); return data});
};
})();
main();