1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { ApiKeyType } from "@medusajs/utils"
3 import {
4 adminHeaders,
5 createAdminUser,
6 } from "../../../../helpers/create-admin-user"
7
8 jest.setTimeout(50000)
9
10 medusaIntegrationTestRunner({
11 env: {},
12 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
13 describe("API Keys - Admin", () => {
14 beforeAll(async () => {
15 await createAdminUser(dbConnection, adminHeaders, getContainer())
16
17 await dbUtils.snapshot()
18 })
19
20 it("should correctly implement the entire lifecycle of an api key", async () => {
21 const created = await api.post(
22 `/admin/api-keys`,
23 {
24 title: "Test Secret Key",
25 type: ApiKeyType.SECRET,
26 },
27 adminHeaders
28 )
29
30 expect(created.status).toEqual(200)
31 expect(created.data.api_key).toEqual(
32 expect.objectContaining({
33 id: created.data.api_key.id,
34 title: "Test Secret Key",
35 created_by: expect.any(String),
36 })
37 )
38 // On create we get the token in raw form so we can store it.
39 expect(created.data.api_key.token).toContain("sk_")
40
41 const updated = await api.post(
42 `/admin/api-keys/${created.data.api_key.id}`,
43 {
44 title: "Updated Secret Key",
45 },
46 adminHeaders
47 )
48
49 expect(updated.status).toEqual(200)
50 expect(updated.data.api_key).toEqual(
51 expect.objectContaining({
52 id: created.data.api_key.id,
53 title: "Updated Secret Key",
54 })
55 )
56
57 const revoked = await api.post(
58 `/admin/api-keys/${created.data.api_key.id}/revoke`,
59 {},
60 adminHeaders
61 )
62
63 expect(revoked.status).toEqual(200)
64 expect(revoked.data.api_key).toEqual(
65 expect.objectContaining({
66 id: created.data.api_key.id,
67 revoked_by: expect.stringMatching(/^user_*/),
68 })
69 )
70 expect(revoked.data.api_key.revoked_at).toBeTruthy()
71
72 const deleted = await api.delete(
73 `/admin/api-keys/${created.data.api_key.id}`,
74 adminHeaders
75 )
76 const listedApiKeys = await api.get(`/admin/api-keys`, adminHeaders)
77
78 expect(deleted.status).toEqual(200)
79 expect(listedApiKeys.data.api_keys).toHaveLength(1) // we still have the default publishable api key
80 })
81
82 it("should allow searching for api keys", async () => {
83 await api.post(
84 `/admin/api-keys`,
85 {
86 title: "Test Secret Key",
87 type: ApiKeyType.SECRET,
88 },
89 adminHeaders
90 )
91 await api.post(
92 `/admin/api-keys`,
93 {
94 title: "Test Publishable Key",
95 type: ApiKeyType.PUBLISHABLE,
96 },
97 adminHeaders
98 )
99
100 const listedSecretKeys = await api.get(
101 `/admin/api-keys?q=Secret`,
102 adminHeaders
103 )
104 const listedPublishableKeys = await api.get(
105 `/admin/api-keys?q=Publish`,
106 adminHeaders
107 )
108
109 expect(listedSecretKeys.data.api_keys).toHaveLength(1)
110 expect(listedSecretKeys.data.api_keys[0].title).toEqual(
111 "Test Secret Key"
112 )
113 expect(listedPublishableKeys.data.api_keys).toHaveLength(2)
114 expect(listedPublishableKeys.data.api_keys).toEqual(
115 expect.arrayContaining([
116 expect.objectContaining({
117 title: "Test Publishable Key",
118 }),
119 expect.objectContaining({
120 title: "Default Publishable API Key",
121 }),
122 ])
123 )
124 })
125
126 it("can use a secret api key for authentication", async () => {
127 const created = await api.post(
128 `/admin/api-keys`,
129 {
130 title: "Test Secret Key",
131 type: ApiKeyType.SECRET,
132 },
133 adminHeaders
134 )
135
136 const createdRegion = await api.post(
137 `/admin/regions`,
138 {
139 name: "Test Region",
140 currency_code: "usd",
141 countries: ["us", "ca"],
142 },
143 {
144 auth: {
145 username: created.data.api_key.token,
146 },
147 }
148 )
149
150 expect(createdRegion.status).toEqual(200)
151 expect(createdRegion.data.region.name).toEqual("Test Region")
152 })
153
154 it("falls back to other mode of authentication when an api key is not valid", async () => {
155 const created = await api.post(
156 `/admin/api-keys`,
157 {
158 title: "Test Secret Key",
159 type: ApiKeyType.SECRET,
160 },
161 adminHeaders
162 )
163
164 await api.post(
165 `/admin/api-keys/${created.data.api_key.id}/revoke`,
166 {},
167 adminHeaders
168 )
169
170 const err = await api
171 .post(
172 `/admin/regions`,
173 {
174 name: "Test Region",
175 currency_code: "usd",
176 countries: ["us", "ca"],
177 },
178 {
179 auth: {
180 username: created.data.api_key.token,
181 },
182 }
183 )
184 .catch((e) => e.message)
185
186 // With axios 1.6+, the 'auth' field takes precedence over headers
187 // So we need to manually construct the Basic auth header and let adminHeaders override it
188 const basicAuthHeader = `Basic ${Buffer.from(
189 created.data.api_key.token + ":"
190 ).toString("base64")}`
191
192 const createdRegion = await api.post(
193 `/admin/regions`,
194 {
195 name: "Test Region",
196 currency_code: "usd",
197 countries: ["us", "ca"],
198 },
199 {
200 headers: {
201 Authorization: basicAuthHeader, // Try revoked API key first
202 ...adminHeaders.headers, // This will override with valid Bearer token
203 },
204 }
205 )
206
207 expect(err).toEqual("Request failed with status code 401")
208 expect(createdRegion.status).toEqual(200)
209 expect(createdRegion.data.region.name).toEqual("Test Region")
210 })
211
212 it("should associate sales channels with a publishable API key", async () => {
213 const salesChannelRes = await api.post(
214 `/admin/sales-channels`,
215 {
216 name: "Test Sales Channel",
217 },
218 adminHeaders
219 )
220
221 const { sales_channel } = salesChannelRes.data
222
223 const apiKeyRes = await api.post(
224 `/admin/api-keys`,
225 {
226 title: "Test publishable KEY",
227 type: ApiKeyType.PUBLISHABLE,
228 },
229 adminHeaders
230 )
231
232 const { api_key } = apiKeyRes.data
233
234 const keyWithChannelsRes = await api.post(
235 `/admin/api-keys/${api_key.id}/sales-channels`,
236 {
237 add: [sales_channel.id],
238 },
239 adminHeaders
240 )
241
242 const keyWithChannels = (
243 await api.get(
244 `/admin/api-keys/${api_key.id}?fields=*sales_channels`,
245 adminHeaders
246 )
247 ).data.api_key
248
249 expect(keyWithChannelsRes.status).toEqual(200)
250 expect(keyWithChannels.title).toEqual("Test publishable KEY")
251 expect(keyWithChannels.sales_channels).toEqual([
252 expect.objectContaining({
253 id: sales_channel.id,
254 name: "Test Sales Channel",
255 }),
256 ])
257 })
258
259 it("should throw if API key is not a publishable key", async () => {
260 const salesChannelRes = await api.post(
261 `/admin/sales-channels`,
262 {
263 name: "Test Sales Channel",
264 },
265 adminHeaders
266 )
267
268 const { sales_channel } = salesChannelRes.data
269
270 const apiKeyRes = await api.post(
271 `/admin/api-keys`,
272 {
273 title: "Test secret KEY",
274 type: ApiKeyType.SECRET,
275 },
276 adminHeaders
277 )
278
279 const errorRes = await api
280 .post(
281 `/admin/api-keys/${apiKeyRes.data.api_key.id}/sales-channels`,
282 {
283 add: [sales_channel.id],
284 },
285 adminHeaders
286 )
287 .catch((err) => err)
288
289 expect(errorRes.response.status).toEqual(400)
290 expect(errorRes.response.data.message).toEqual(
291 "Sales channels can only be associated with publishable API keys"
292 )
293 })
294
295 it("should throw if sales channel does not exist", async () => {
296 const apiKeyRes = await api.post(
297 `/admin/api-keys`,
298 {
299 title: "Test publishable KEY",
300 type: ApiKeyType.PUBLISHABLE,
301 },
302 adminHeaders
303 )
304
305 const errorRes = await api
306 .post(
307 `/admin/api-keys/${apiKeyRes.data.api_key.id}/sales-channels`,
308 {
309 add: ["phony"],
310 },
311 adminHeaders
312 )
313 .catch((err) => err)
314
315 expect(errorRes.response.status).toEqual(400)
316 expect(errorRes.response.data.message).toEqual(
317 "Sales channels with IDs phony do not exist"
318 )
319 })
320
321 it("should detach sales channels from a publishable API key", async () => {
322 const salesChannelRes = await api.post(
323 `/admin/sales-channels`,
324 {
325 name: "Test Sales Channel",
326 },
327 adminHeaders
328 )
329
330 const { sales_channel } = salesChannelRes.data
331
332 const apiKeyRes = await api.post(
333 `/admin/api-keys`,
334 {
335 title: "Test publishable KEY",
336 type: ApiKeyType.PUBLISHABLE,
337 },
338 adminHeaders
339 )
340
341 const { api_key } = apiKeyRes.data
342
343 const keyWithChannelsRes = await api.post(
344 `/admin/api-keys/${api_key.id}/sales-channels`,
345 {
346 add: [sales_channel.id],
347 },
348 adminHeaders
349 )
350
351 const keyWithChannels = (
352 await api.get(
353 `/admin/api-keys/${api_key.id}?fields=*sales_channels`,
354 adminHeaders
355 )
356 ).data.api_key
357
358 expect(keyWithChannelsRes.status).toEqual(200)
359 expect(keyWithChannels.title).toEqual("Test publishable KEY")
360 expect(keyWithChannels.sales_channels).toEqual([
361 expect.objectContaining({
362 id: sales_channel.id,
363 name: "Test Sales Channel",
364 }),
365 ])
366
367 const keyWithoutChannelsRes = await api.post(
368 `/admin/api-keys/${api_key.id}/sales-channels`,
369 {
370 remove: [sales_channel.id],
371 },
372 adminHeaders
373 )
374
375 const keyWithoutChannels = (
376 await api.get(
377 `/admin/api-keys/${api_key.id}?fields=*sales_channels`,
378 adminHeaders
379 )
380 ).data.api_key
381
382 expect(keyWithoutChannelsRes.status).toEqual(200)
383 expect(keyWithoutChannels.title).toEqual("Test publishable KEY")
384 expect(keyWithoutChannels.sales_channels).toEqual([])
385 })
386
387 it("should detach sales channels from a publishable API key on delete", async () => {
388 const salesChannelRes = await api.post(
389 `/admin/sales-channels`,
390 { name: "Test Sales Channel" },
391 adminHeaders
392 )
393
394 const { sales_channel } = salesChannelRes.data
395
396 const apiKeyRes = await api.post(
397 `/admin/api-keys`,
398 {
399 title: "Test publishable KEY",
400 type: ApiKeyType.PUBLISHABLE,
401 },
402 adminHeaders
403 )
404
405 const { api_key } = apiKeyRes.data
406
407 const keyWithChannelsRes = await api.post(
408 `/admin/api-keys/${api_key.id}/sales-channels`,
409 { add: [sales_channel.id] },
410 adminHeaders
411 )
412
413 const keyWithChannels = (
414 await api.get(
415 `/admin/api-keys/${api_key.id}?fields=*sales_channels`,
416 adminHeaders
417 )
418 ).data.api_key
419
420 expect(keyWithChannelsRes.status).toEqual(200)
421 expect(keyWithChannels.title).toEqual("Test publishable KEY")
422 expect(keyWithChannels.sales_channels).toEqual([
423 expect.objectContaining({
424 id: sales_channel.id,
425 name: "Test Sales Channel",
426 }),
427 ])
428
429 const revoked = await api.post(
430 `/admin/api-keys/${api_key.id}/revoke`,
431 {},
432 adminHeaders
433 )
434
435 expect(revoked.status).toEqual(200)
436 expect(revoked.data.api_key).toEqual(
437 expect.objectContaining({
438 id: api_key.id,
439 revoked_by: expect.stringMatching(/^user_*/),
440 })
441 )
442 expect(revoked.data.api_key.revoked_at).toBeTruthy()
443
444 await api.delete(`/admin/api-keys/${api_key.id}`, adminHeaders)
445
446 const deletedApiKeys = await api.get(
447 `/admin/api-keys?id=${api_key.id}`,
448 adminHeaders
449 )
450
451 expect(deletedApiKeys.data.api_keys).toHaveLength(0)
452
453 const fetchedSalesChannel = (
454 await api.get(
455 `/admin/sales-channels/${sales_channel.id}?fields=*publishable_api_keys`,
456 adminHeaders
457 )
458 ).data.sales_channel
459
460 expect(fetchedSalesChannel.publishable_api_keys).toEqual([])
461 })
462 })
463 },
464 })