-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.js
244 lines (244 loc) · 8.62 KB
/
config.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
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
import { DeleteParameterCommand, GetParameterCommand, GetParametersByPathCommand, PutParameterCommand, SSMClient, } from "@aws-sdk/client-ssm";
import { GetFunctionConfigurationCommand, LambdaClient, UpdateFunctionConfigurationCommand, } from "@aws-sdk/client-lambda";
import { pipe, map } from "remeda";
import { useProject } from "./project.js";
import { useAWSClient } from "./credentials.js";
import { useIOT } from "./iot.js";
import { Stacks } from "./stacks/index.js";
const FALLBACK_STAGE = ".fallback";
const SECRET_UPDATED_AT_ENV = "SST_ADMIN_SECRET_UPDATED_AT";
const PREFIX = {
get STAGE() {
const project = useProject();
return project.config.ssmPrefix;
},
get FALLBACK() {
const project = useProject();
return `/sst/${project.config.name}/${FALLBACK_STAGE}/`;
},
};
export var Config;
(function (Config) {
async function parameters() {
const result = [];
for await (const p of scanParameters(PREFIX.FALLBACK)) {
const parsed = parse(p.Name, PREFIX.FALLBACK);
if (parsed.type === "secrets")
continue;
result.push({
...parsed,
value: p.Value,
});
}
for await (const p of scanParameters(PREFIX.STAGE)) {
const parsed = parse(p.Name, PREFIX.STAGE);
if (parsed.type === "secrets")
continue;
result.push({
...parsed,
value: p.Value,
});
}
return result;
}
Config.parameters = parameters;
function envFor(input) {
return `SST_${input.type}_${input.prop}_${normalizeID(input.id)}`;
}
Config.envFor = envFor;
function pathFor(input) {
return `${input.fallback ? PREFIX.FALLBACK : PREFIX.STAGE}${input.type}/${normalizeID(input.id)}/${input.prop}`;
}
Config.pathFor = pathFor;
function normalizeID(input) {
return input.replace(/-/g, "_");
}
Config.normalizeID = normalizeID;
async function secrets() {
const result = {};
for await (const p of scanParameters(PREFIX.STAGE + "Secret")) {
const parsed = parse(p.Name, PREFIX.STAGE);
if (!result[parsed.id])
result[parsed.id] = {};
result[parsed.id].value = p.Value;
}
for await (const p of scanParameters(PREFIX.FALLBACK + "Secret")) {
const parsed = parse(p.Name, PREFIX.FALLBACK);
if (!result[parsed.id])
result[parsed.id] = {};
result[parsed.id].fallback = p.Value;
}
return result;
}
Config.secrets = secrets;
async function env() {
const project = useProject();
const parameters = await Config.parameters();
const env = {
SST_APP: project.config.name,
SST_STAGE: project.config.stage,
...pipe(parameters, map((p) => [envFor(p), p.value]), Object.fromEntries),
};
return env;
}
Config.env = env;
async function setSecret(input) {
const paramName = pathFor({
id: input.key,
type: "Secret",
prop: "value",
fallback: input.fallback,
});
try {
await putParameter(paramName, input.value);
}
catch (e) {
// If the parameter was previously ADVANCED, re-create it in STANDARD tier.
const wasAdvanced = e.name === "ValidationException" &&
e.message.startsWith("This parameter uses the advanced-parameter tier. You can't downgrade a parameter from the advanced-parameter tier to the standard-parameter tier.");
if (!wasAdvanced)
throw e;
await deleteParameter(paramName);
await putParameter(paramName, input.value);
}
// Publish event
const iot = await useIOT();
const topic = `${iot.prefix}/events`;
await iot.publish(topic, "config.secret.updated", { name: input.key });
}
Config.setSecret = setSecret;
async function getSecret(input) {
const result = await getParameter(pathFor({
id: input.key,
prop: "value",
type: "Secret",
fallback: input.fallback,
}));
return result.Parameter?.Value;
}
Config.getSecret = getSecret;
async function removeSecret(input) {
await deleteParameter(pathFor({
id: input.key,
type: "Secret",
prop: "value",
fallback: input.fallback,
}));
}
Config.removeSecret = removeSecret;
async function restart(keys) {
const metadata = await Stacks.metadata();
const siteData = Object.values(metadata)
.flat()
.filter((c) => c.type === "AstroSite" ||
c.type === "NextjsSite" ||
c.type === "RemixSite" ||
c.type === "SolidStartSite" ||
c.type === "SvelteKitSite")
.filter((c) => keys.some((key) => c.data.secrets.includes(key)));
const siteDataPlaceholder = siteData.filter((c) => c.data.mode === "placeholder");
const siteDataEdge = siteData
.filter((c) => c.data.mode === "deployed")
.filter((c) => c.data.edge);
const siteDataRegional = siteData
.filter((c) => c.data.mode === "deployed")
.filter((c) => !c.data.edge);
const regionalSiteArns = siteData.map((s) => s.data.server);
const functionData = Object.values(metadata)
.flat()
.filter((c) => c.type === "Function")
// filter out SSR functions for sites
.filter((c) => !regionalSiteArns.includes(c.data.arn))
.filter((c) => keys.some((key) => c.data.secrets.includes(key)));
// Restart sites
const restartedSites = (await Promise.all(siteDataRegional.map(async (s) => {
const restarted = await restartFunction(s.data.server);
return restarted ? s : restarted;
}))).filter((c) => Boolean(c));
// Restart functions
const restartedFunctions = (await Promise.all(functionData.map(async (f) => {
const restarted = await restartFunction(f.data.arn);
return restarted ? f : restarted;
}))).filter((c) => Boolean(c));
return {
edgeSites: siteDataEdge,
sites: restartedSites,
placeholderSites: siteDataPlaceholder,
functions: restartedFunctions,
};
}
Config.restart = restart;
})(Config || (Config = {}));
async function* scanParameters(prefix) {
const ssm = useAWSClient(SSMClient);
let token;
while (true) {
const results = await ssm.send(new GetParametersByPathCommand({
Path: prefix,
WithDecryption: true,
Recursive: true,
NextToken: token,
}));
yield* results.Parameters || [];
if (!results.NextToken)
break;
token = results.NextToken;
}
}
function getParameter(name) {
const ssm = useAWSClient(SSMClient);
return ssm.send(new GetParameterCommand({
Name: name,
WithDecryption: true,
}));
}
function putParameter(name, value) {
const ssm = useAWSClient(SSMClient);
return ssm.send(new PutParameterCommand({
Name: name,
Value: value,
Type: "SecureString",
Overwrite: true,
Tier: value.length > 4096 ? "Advanced" : "Standard",
}));
}
function deleteParameter(name) {
const ssm = useAWSClient(SSMClient);
return ssm.send(new DeleteParameterCommand({
Name: name,
}));
}
function parse(ssmName, prefix) {
const parts = ssmName.substring(prefix.length).split("/");
return {
type: parts[0],
id: parts[1],
prop: parts.slice(2).join("/"),
};
}
async function restartFunction(arn) {
const lambda = useAWSClient(LambdaClient);
// Note: in the case where the function is removed, but the metadata
// is not updated, we ignore the Function not found error.
try {
const config = await lambda.send(new GetFunctionConfigurationCommand({
FunctionName: arn,
}));
await lambda.send(new UpdateFunctionConfigurationCommand({
FunctionName: arn,
Environment: {
Variables: {
...(config.Environment?.Variables || {}),
[SECRET_UPDATED_AT_ENV]: Date.now().toString(),
},
},
}));
return true;
}
catch (e) {
if (e.name === "ResourceNotFoundException" &&
e.message.startsWith("Function not found")) {
return;
}
}
}