-
Notifications
You must be signed in to change notification settings - Fork 4
/
prepare.ts
268 lines (247 loc) · 7.83 KB
/
prepare.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
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import findRoot from "find-root";
import request, { Response } from "sync-request";
import asyncRequest, { ResponsePromise } from "then-request";
import { readFileSync as readFile } from "fs";
import { inspect } from "util";
import { EventEmitter } from "events";
import parseSecretfile, { SecretSource } from "./parseSecretfile";
function plural(n: number): string {
return n === 1 ? "" : "s";
}
/**
* The key→value mappings associated with a secret in Vault.
*/
type SecretData = Record<string, unknown>;
/**
* Vault gives us "leases" on secrets, which expire at a specified time.
*
* A `Lease` contains the secret data and information about when that lease
* expires.
*/
interface Lease {
data: SecretData;
ttl?: number;
lease_duration?: number;
}
/** Fetch a lease response and parse it. */
function parseLeaseResponse(response: Response | ResponsePromise): Lease {
return JSON.parse(response.getBody().toString());
}
function formatText(text: string, before: number, after: number): string {
return process.stdout.isTTY
? "\u001b[" + before + "m" + text + "\u001b[" + after + "m"
: text;
}
function bold(text: string): string {
return formatText(text, 1, 22);
}
function green(text: string): string {
return formatText(text, 32, 39);
}
function red(text: string): string {
return formatText(text, 31, 39);
}
function blue(text: string): string {
return formatText(text, 34, 39);
}
const logPrefix = bold("vault-env: ");
/** Vault initialization options. */
export interface Options {
VAULT_ADDR?: string;
VAULT_TOKEN?: string;
VAULT_API_VERSION?: string;
VAULT_ENV_PATH?: string;
VAULT_SECRETS?: Record<string, SecretSource>;
silent?: boolean;
autoRotate?: boolean;
local?: boolean;
dryrun?: boolean;
}
// We have historically supported two entirely different return values, so we
// need to overload our exported type below.
/**
* Configure this library to fetch secrets from Vault.
*
* @returns When `autoRotate` is set, this returns an `EventEmitter`.
*/
export default function prepare(
options: Options & { autoRotate: true }
): EventEmitter;
/**
* Configure this library to fetch secrets from Vault.
*
* @returns When `autoRotate` is not set, this returns a mapping from secret
* names to values.
*/
export default function prepare(
options?: Options & { autoRotate?: false }
): Record<string, string>;
/** Configure this library to fetch secrets from Vault. */
export default function prepare(
options: Options
): EventEmitter | Record<string, string>;
export default function prepare(
options: Options = {}
): EventEmitter | Record<string, string> {
const VAULT_ADDR = (
options.VAULT_ADDR ||
process.env.VAULT_ADDR ||
"http://127.0.0.1:8200"
).replace(/([^/])$/, "$1/");
const VAULT_TOKEN = options.VAULT_TOKEN || process.env.VAULT_TOKEN;
const VAULT_API_VERSION =
options.VAULT_API_VERSION || process.env.VAULT_API_VERSION || "v1";
const VAULT_ENV_PATH =
options.VAULT_ENV_PATH ||
process.env.VAULT_ENV_PATH ||
findRoot(process.argv[1] || process.cwd()) + "/Secretfile";
const ORIGINAL_SECRETS =
options.VAULT_SECRETS ?? parseSecretfile(readFile(VAULT_ENV_PATH, "utf8"));
const varsWritten: Record<string, string> = {};
const emitter = new EventEmitter();
const secretsByPath: Record<string, Record<string, string>> = {};
let secretCount = 0;
Object.keys(ORIGINAL_SECRETS).forEach(function (key) {
if (typeof process.env[key] === "undefined") {
const { vaultPath, vaultProp } = ORIGINAL_SECRETS[key];
secretsByPath[vaultPath] = secretsByPath[vaultPath] ?? {};
secretsByPath[vaultPath][key] = vaultProp;
secretCount++;
} else if (!options.silent) {
console.log(logPrefix + key + " already in environment " + blue("✓"));
}
});
if (secretCount && !VAULT_TOKEN) {
throw new Error("Expected VAULT_TOKEN to be set");
}
!options.silent &&
secretCount &&
console.log(
logPrefix +
"fetching " +
secretCount +
" secret" +
plural(secretCount) +
" from " +
VAULT_ADDR
);
class RetryAuthFailure extends Error {}
function checkStatusCode(response: Response) {
if (response.statusCode == 403) {
throw new RetryAuthFailure(
"vault responded with 403 access denied when i tried to rotate, giving up"
);
} else {
return response;
}
}
function getNewLease(vaultPath: string, sync: boolean) {
const fullUrl = VAULT_ADDR + VAULT_API_VERSION + "/" + vaultPath;
if (sync) {
const response = request("GET", fullUrl, {
headers: {
"X-Vault-Token": VAULT_TOKEN,
},
});
try {
onLease(vaultPath, parseLeaseResponse(checkStatusCode(response)));
} catch (e) {
console.error(e.message);
if (!(e instanceof RetryAuthFailure)) {
throw e;
}
}
} else {
const response = asyncRequest("GET", fullUrl, {
headers: {
"X-Vault-Token": VAULT_TOKEN,
},
});
!options.silent &&
console.log(
logPrefix +
"rotating lease for " +
Object.keys(secretsByPath[vaultPath]).join(", ")
);
Promise.resolve(response)
.then(checkStatusCode)
.then(parseLeaseResponse)
.then(onLease.bind(null, vaultPath))
.catch(function retry(err: { stack?: string }) {
console.error(
logPrefix + "ERROR trying to rotate lease " + vaultPath
);
console.error(logPrefix + (err && err.stack ? err.stack : err));
if (!(err instanceof RetryAuthFailure)) {
console.error("retrying in 1s");
setTimeout(getNewLease.bind(null, vaultPath), 1000);
}
});
}
}
function onLease(vaultPath: string, lease: Lease) {
const secretsByName = secretsByPath[vaultPath];
const previousValues: Record<string, string | undefined> = {};
for (const secretName in secretsByName) {
const keyPath = secretsByName[secretName];
const data = lease.data[keyPath];
if (typeof data !== "string" && typeof data !== "number") {
throw new Error(
"Unexpected " +
typeof data +
" " +
inspect(data) +
" for " +
vaultPath +
":" +
secretsByName[secretName]
);
}
if (options.autoRotate) {
previousValues[secretName] = process.env[secretName];
}
if (!options.local) {
process.env[secretName] = String(data);
}
varsWritten[secretName] = String(data);
}
if (!options.dryrun) {
Object.keys(secretsByName).forEach(function (secretName) {
if (process.env[secretName] !== previousValues[secretName]) {
emitter.emit(
secretName,
process.env[secretName],
previousValues[secretName]
);
}
});
}
if (options.autoRotate) {
const ttl = lease.ttl || lease.lease_duration;
if (!ttl) {
const keys = Object.keys(secretsByName).join(", ");
console.error(
`${logPrefix}Refusing to refresh vault lease no lease duration for ${keys} at ${vaultPath}`
);
} else {
setTimeout(getNewLease.bind(null, vaultPath), (ttl / 2) * 1000);
}
}
}
Object.keys(secretsByPath).forEach(function (vaultPath) {
const secretsByName = secretsByPath[vaultPath];
const names = Object.keys(secretsByName);
!options.silent &&
process.stdout.write(
logPrefix + "loading " + names.join(", ") + " from " + vaultPath
);
try {
getNewLease(vaultPath, true);
!options.silent && process.stdout.write(" " + green("✓") + "\n");
} catch (err) {
!options.silent && process.stdout.write(" " + red("✕") + "\n");
throw err;
}
});
return options.autoRotate ? emitter : varsWritten;
}