-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-keys.ts
More file actions
371 lines (339 loc) · 12.5 KB
/
Copy pathapi-keys.ts
File metadata and controls
371 lines (339 loc) · 12.5 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import type { Command } from "commander";
import { withErrorHandler, createClient, resolveOptions, getFormat, outputResponse } from "../../helpers.js";
import { loadConfig, saveConfig } from "../../config.js";
import { parseJsonInput } from "../../input.js";
import { printApiKeyBox, printError } from "../../output.js";
import { addExamples, addNotes } from "../help.js";
/** Strip masked key placeholder from API key response for cleaner display. */
function cleanApiKeyData(data: unknown): unknown {
if (Array.isArray(data)) return data.map(cleanApiKeyData);
if (typeof data !== "object" || data === null) return data;
const obj = { ...(data as Record<string, unknown>) };
if (obj.key === "******") delete obj.key;
return obj;
}
function validateOrigins(body: unknown, opts: Record<string, unknown>): void {
// Validate origins if provided via flags
if (opts.origins !== undefined) {
const origins = String(opts.origins).split(",").map((s: string) => s.trim()).filter(Boolean);
if (origins.length === 0) {
printError("allowedOrigins must contain at least 1 item. Use '*' to allow all origins.");
process.exit(1);
}
}
// Also validate if provided via JSON input
if (body && typeof body === "object" && "allowedOrigins" in (body as Record<string, unknown>)) {
const origins = (body as Record<string, unknown>).allowedOrigins;
if (Array.isArray(origins) && origins.filter((o: unknown) => typeof o === "string" && o.trim() !== "").length === 0) {
printError("allowedOrigins must contain at least 1 item. Use '*' to allow all origins.");
process.exit(1);
}
}
}
function buildBodyFromFlags(opts: Record<string, unknown>): Record<string, unknown> {
const payload: Record<string, unknown> = {};
if (opts.name) payload.name = opts.name;
if (opts.policy) payload.policyId = opts.policy;
if (opts.origins) payload.allowedOrigins = (opts.origins as string).split(",").map((s: string) => s.trim()).filter(Boolean);
if (opts.rateLimit) {
const raw = String(opts.rateLimit).trim();
if (!/^\d+$/.test(raw)) {
printError("--rate-limit must be a positive integer.");
process.exit(1);
}
const perMinute = Number(raw);
if (perMinute <= 0) {
printError("--rate-limit must be a positive integer.");
process.exit(1);
}
payload.rateLimit = { perMinute };
}
if (opts.dpopRequired !== undefined) payload.dpopRequired = opts.dpopRequired;
if (opts.tenantId) payload.tenantId = opts.tenantId;
return payload;
}
/** Save API key to profile config and print confirmation. Returns false if key missing or save fails. */
function handleSaveKey(
data: Record<string, unknown>,
cmd: Command,
): boolean {
const globalOpts = resolveOptions(cmd);
const key = data.key as string | undefined;
if (!key) {
printError("Response missing key. API key was created, but it could not be saved.");
process.exitCode = 1;
return false;
}
try {
const config = loadConfig(globalOpts.profile);
config.apiKey = key;
saveConfig(config, globalOpts.profile);
console.error("API key saved to config. X-Api-Key header will be sent automatically.");
return true;
} catch (err) {
printError(`Failed to save API key to config: ${err instanceof Error ? err.message : String(err)}`);
printApiKeyBox(key);
process.exitCode = 1;
return false;
}
}
/** Show API key value prominently. Returns false if key is missing (treated as error). */
function showKeyResult(
data: Record<string, unknown>,
save: boolean,
cmd: Command,
): boolean {
const key = data.key as string | undefined;
if (!key) {
printError("Response missing key. The new API key value was not returned.");
process.exitCode = 1;
return false;
}
if (save) return handleSaveKey(data, cmd);
printApiKeyBox(key);
return true;
}
export function registerApiKeysCommand(parent: Command): void {
const apiKeys = parent
.command("api-keys")
.description("Manage API keys");
// api-keys list
const list = apiKeys
.command("list")
.description("List all API keys, showing name, tenant, policy, and status (key values are masked)")
.option("--tenant-id <id>", "Filter by tenant ID")
.action(
withErrorHandler(async (_opts: unknown, cmd: Command) => {
const opts = cmd.opts() as { tenantId?: string };
const client = createClient(cmd);
const format = getFormat(cmd);
const params: Record<string, string> = {};
if (opts.tenantId) params.tenantId = opts.tenantId;
const response = await client.rawRequest("GET", "/admin/api-keys", {
params,
});
response.data = cleanApiKeyData(response.data);
outputResponse(response, format);
console.error("※ API キー値は作成時 (create) またはリフレッシュ時 (refresh) にのみ表示されます。");
}),
);
addExamples(list, [
{
description: "List all API keys",
command: "geonic admin api-keys list",
},
{
description: "List API keys in table format",
command: "geonic admin api-keys list --format table",
},
{
description: "List API keys for a specific tenant",
command: "geonic admin api-keys list --tenant-id <tenant-id>",
},
]);
// api-keys get
const get = apiKeys
.command("get <keyId>")
.description("Get an API key's metadata — name, policy, allowed origins, and rate limit (key value is masked)")
.action(
withErrorHandler(async (keyId: unknown, _opts: unknown, cmd: Command) => {
const client = createClient(cmd);
const format = getFormat(cmd);
const response = await client.rawRequest(
"GET",
`/admin/api-keys/${encodeURIComponent(String(keyId))}`,
);
response.data = cleanApiKeyData(response.data);
outputResponse(response, format);
}),
);
addExamples(get, [
{
description: "Inspect an API key's configuration",
command: "geonic admin api-keys get <key-id>",
},
]);
// api-keys create
const create = apiKeys
.command("create [json]")
.description("Create a new API key")
.option("--name <name>", "Key name")
.option("--policy <policyId>", "Policy ID to attach")
.option("--origins <origins>", "Comma-separated origins")
.option("--rate-limit <n>", "Rate limit per minute")
.option("--dpop-required", "Require DPoP token binding")
.option("--tenant-id <id>", "Tenant ID")
.option("--save", "Save the API key to profile config")
.action(
withErrorHandler(async (json: unknown, _opts: unknown, cmd: Command) => {
const opts = cmd.opts() as {
name?: string;
policy?: string;
origins?: string;
rateLimit?: string;
dpopRequired?: boolean;
tenantId?: string;
save?: boolean;
};
validateOrigins(undefined, opts);
let body: unknown;
if (json) {
body = await parseJsonInput(json as string | undefined);
} else if (opts.name || opts.policy || opts.origins || opts.rateLimit || opts.dpopRequired !== undefined || opts.tenantId) {
body = buildBodyFromFlags(opts);
} else {
body = await parseJsonInput();
}
validateOrigins(body, {});
const client = createClient(cmd);
const format = getFormat(cmd);
const response = await client.rawRequest("POST", "/admin/api-keys", {
body,
});
const data = response.data as Record<string, unknown>;
const ok = showKeyResult(data, !!opts.save, cmd);
outputResponse(response, format);
if (ok) console.error("API key created.");
}),
);
addNotes(create, [
"Use --policy to attach an existing XACML policy to the API key.",
"Manage policies with `geonic admin policies` commands.",
]);
addExamples(create, [
{
description: "Create an API key with a policy",
command: "geonic admin api-keys create --name my-key --policy <policy-id> --origins '*'",
},
{
description: "Create an API key with DPoP required",
command: "geonic admin api-keys create --name my-key --dpop-required",
},
{
description: "Create an API key from JSON and save to config",
command: "geonic admin api-keys create @key.json --save",
},
]);
// api-keys refresh
const refresh = apiKeys
.command("refresh <keyId>")
.description("Refresh (rotate) an API key — generates a new key value")
.option("--save", "Save the new API key to profile config")
.action(
withErrorHandler(async (keyId: unknown, _opts: unknown, cmd: Command) => {
const opts = cmd.opts() as { save?: boolean };
const client = createClient(cmd);
const format = getFormat(cmd);
const response = await client.rawRequest(
"POST",
`/admin/api-keys/${encodeURIComponent(String(keyId))}/refresh`,
);
const data = response.data as Record<string, unknown>;
const ok = showKeyResult(data, !!opts.save, cmd);
outputResponse(response, format);
if (ok) console.error("API key refreshed.");
}),
);
addNotes(refresh, [
"Refreshing generates a new key value while keeping keyId, name, and policy settings.",
"The previous key value is immediately invalidated.",
]);
addExamples(refresh, [
{
description: "Refresh an API key",
command: "geonic admin api-keys refresh <key-id>",
},
{
description: "Refresh and save new key to config",
command: "geonic admin api-keys refresh <key-id> --save",
},
]);
// api-keys update
const update = apiKeys
.command("update <keyId> [json]")
.description("Update an API key")
.option("--name <name>", "Key name")
.option("--policy <policyId>", "Policy ID to attach")
.option("--origins <origins>", "Comma-separated origins")
.option("--rate-limit <n>", "Rate limit per minute")
.option("--dpop-required", "Require DPoP token binding")
.option("--no-dpop-required", "Disable DPoP token binding")
.action(
withErrorHandler(
async (keyId: unknown, json: unknown, _opts: unknown, cmd: Command) => {
const opts = cmd.opts() as {
name?: string;
policy?: string;
origins?: string;
rateLimit?: string;
dpopRequired?: boolean;
};
validateOrigins(undefined, opts);
let body: unknown;
if (json) {
body = await parseJsonInput(json as string | undefined);
} else if (opts.name || opts.policy || opts.origins || opts.rateLimit || opts.dpopRequired !== undefined) {
body = buildBodyFromFlags(opts);
} else {
body = await parseJsonInput();
}
validateOrigins(body, {});
const client = createClient(cmd);
const format = getFormat(cmd);
const response = await client.rawRequest(
"PATCH",
`/admin/api-keys/${encodeURIComponent(String(keyId))}`,
{ body },
);
outputResponse(response, format);
console.error("API key updated.");
},
),
);
addNotes(update, [
"Use --policy to attach an existing XACML policy to the API key.",
"Manage policies with `geonic admin policies` commands.",
]);
addExamples(update, [
{
description: "Update an API key name",
command: "geonic admin api-keys update <key-id> --name new-name",
},
{
description: "Attach a policy",
command: "geonic admin api-keys update <key-id> --policy <policy-id>",
},
{
description: "Enable DPoP requirement",
command: "geonic admin api-keys update <key-id> --dpop-required",
},
{
description: "Disable DPoP requirement",
command: "geonic admin api-keys update <key-id> --no-dpop-required",
},
{
description: "Update an API key from a JSON file",
command: "geonic admin api-keys update <key-id> @key.json",
},
]);
// api-keys delete
const del = apiKeys
.command("delete <keyId>")
.description("Delete an API key. Any requests using this key will be immediately rejected")
.action(
withErrorHandler(async (keyId: unknown, _opts: unknown, cmd: Command) => {
const client = createClient(cmd);
await client.rawRequest(
"DELETE",
`/admin/api-keys/${encodeURIComponent(String(keyId))}`,
);
console.error("API key deleted.");
}),
);
addExamples(del, [
{
description: "Delete an API key by ID",
command: "geonic admin api-keys delete <key-id>",
},
]);
}