1 import { IApiKeyModuleService } from "@medusajs/framework/types"
2 import { ApiKeyType, Module, Modules } from "@medusajs/framework/utils"
3 import { ApiKeyModuleService } from "@services"
4 import crypto from "crypto"
5 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
6 import {
7 createPublishableKeyFixture,
8 createSecretKeyFixture,
9 } from "../__fixtures__"
10
11 jest.setTimeout(100000)
12
13 const mockPublishableKeyBytes = () => {
14 jest.spyOn(crypto, "randomBytes").mockImplementationOnce(() => {
15 return Buffer.from(
16 "44de31ebcf085fa423fc584aa854067025e937a79edb565f472404345f0f23be",
17 "hex"
18 )
19 })
20 }
21
22 const mockSecretKeyBytes = () => {
23 jest
24 .spyOn(crypto, "randomBytes")
25 .mockImplementationOnce(() => {
26 return Buffer.from(
27 "44de31ebcf085fa423fc584aa854067025e937a79edb565f472404345f0f23be",
28 "hex"
29 )
30 })
31 .mockImplementationOnce(() => {
32 return Buffer.from("44de31ebcf085fa423fc584aa8540670", "hex")
33 })
34 }
35
36 moduleIntegrationTestRunner<IApiKeyModuleService>({
37 moduleName: Modules.API_KEY,
38 testSuite: ({ service }) => {
39 afterEach(() => {
40 jest.restoreAllMocks()
41 })
42
43 it(`should export the appropriate linkable configuration`, () => {
44 const linkable = Module(Modules.API_KEY, {
45 service: ApiKeyModuleService,
46 }).linkable
47
48 expect(Object.keys(linkable)).toEqual(["apiKey"])
49
50 Object.keys(linkable).forEach((key) => {
51 delete linkable[key].toJSON
52 })
53
54 expect(linkable.apiKey).toEqual({
55 id: {
56 linkable: "api_key_id",
57 entity: "ApiKey",
58 primaryKey: "id",
59 serviceName: "api_key",
60 field: "apiKey",
61 },
62 publishable_key_id: {
63 field: "apiKey",
64 entity: "ApiKey",
65 linkable: "publishable_key_id",
66 primaryKey: "publishable_key_id",
67 serviceName: "api_key",
68 },
69 })
70 })
71
72 describe("API Key Module Service", () => {
73 describe("creating a publishable API key", () => {
74 it("should create it successfully", async function () {
75 mockPublishableKeyBytes()
76 const apiKey = await service.createApiKeys(
77 createPublishableKeyFixture
78 )
79
80 expect(apiKey).toEqual(
81 expect.objectContaining({
82 title: "Test API Key",
83 type: ApiKeyType.PUBLISHABLE,
84 salt: undefined,
85 created_by: "test",
86 last_used_at: null,
87 revoked_by: null,
88 revoked_at: null,
89 redacted: "pk_44d***3be",
90 token:
91 "pk_44de31ebcf085fa423fc584aa854067025e937a79edb565f472404345f0f23be",
92 })
93 )
94 })
95 })
96
97 describe("creating a secret API key", () => {
98 it("should get created successfully", async function () {
99 mockSecretKeyBytes()
100 const apiKey = await service.createApiKeys(createSecretKeyFixture)
101
102 expect(apiKey).toEqual(
103 expect.objectContaining({
104 title: "Secret key",
105 type: ApiKeyType.SECRET,
106 salt: undefined,
107 created_by: "test",
108 last_used_at: null,
109 revoked_by: null,
110 revoked_at: null,
111 redacted: "sk_44d***3be",
112 token:
113 "sk_44de31ebcf085fa423fc584aa854067025e937a79edb565f472404345f0f23be",
114 })
115 )
116 })
117
118 it("should allow creating multiple active token", async function () {
119 const apiKeys = await service.createApiKeys([
120 createSecretKeyFixture,
121 createSecretKeyFixture,
122 ])
123
124 apiKeys.push(await service.createApiKeys(createSecretKeyFixture))
125
126 expect(apiKeys).toHaveLength(3)
127 expect(apiKeys[0].revoked_at).toBeFalsy()
128 expect(apiKeys[1].revoked_at).toBeFalsy()
129 expect(apiKeys[2].revoked_at).toBeFalsy()
130 })
131 })
132
133 describe("revoking API keys", () => {
134 it("should have the revoked at and revoked by set when a key is revoked", async function () {
135 const firstApiKey = await service.createApiKeys(
136 createSecretKeyFixture
137 )
138 const revokedKey = await service.revoke(firstApiKey.id, {
139 revoked_by: "test",
140 })
141
142 expect(revokedKey).toEqual(
143 expect.objectContaining({
144 revoked_by: "test",
145 revoked_at: expect.any(Date),
146 })
147 )
148 })
149
150 it("should be able to revoke a key in the future", async function () {
151 const now = Date.parse("2021-01-01T00:00:00Z")
152 const hourInSec = 3600
153 jest.useFakeTimers().setSystemTime(now)
154
155 const createdKey = await service.createApiKeys(createSecretKeyFixture)
156 const revokedKey = await service.revoke(createdKey.id, {
157 revoked_by: "test",
158 revoke_in: hourInSec,
159 })
160
161 expect(revokedKey).toEqual(
162 expect.objectContaining({
163 revoked_by: "test",
164 revoked_at: new Date(now + hourInSec * 1000),
165 })
166 )
167
168 jest.useRealTimers()
169 })
170
171 it("should do nothing if the revokal list is empty", async function () {
172 const firstApiKey = await service.createApiKeys(
173 createSecretKeyFixture
174 )
175 let revokedKeys = await service.revoke([])
176 expect(revokedKeys).toHaveLength(0)
177
178 const apiKey = await service.retrieveApiKey(firstApiKey.id)
179 expect(apiKey.revoked_at).toBeFalsy()
180 expect(apiKey.revoked_by).toBeFalsy()
181 })
182
183 it("should not allow revoking an already revoked API key", async function () {
184 const firstApiKey = await service.createApiKeys(
185 createSecretKeyFixture
186 )
187 await service.revoke(firstApiKey.id, {
188 revoked_by: "test",
189 })
190
191 const err = await service
192 .revoke(firstApiKey.id, {
193 revoked_by: "test2",
194 })
195 .catch((e) => e)
196
197 expect(err.message).toEqual(
198 `There are 1 secret keys that are already revoked.`
199 )
200 })
201 })
202
203 describe("updating an API key", () => {
204 it("should update the name successfully", async function () {
205 const createdApiKey = await service.createApiKeys(
206 createSecretKeyFixture
207 )
208
209 const updatedApiKey = await service.updateApiKeys(createdApiKey.id, {
210 title: "New Name",
211 })
212 expect(updatedApiKey.title).toEqual("New Name")
213 })
214
215 it("should not reflect any updates on other fields", async function () {
216 const createdApiKey = await service.createApiKeys(
217 createSecretKeyFixture
218 )
219
220 const updatedApiKey = await service.updateApiKeys(createdApiKey.id, {
221 title: createdApiKey.title,
222 revoked_by: "test",
223 revoked_at: new Date(),
224 last_used_at: new Date(),
225 })
226
227 // These should not be returned on an update
228 createdApiKey.token = ""
229 expect(createdApiKey).toEqual(updatedApiKey)
230 })
231 })
232
233 describe("deleting API keys", () => {
234 it("should successfully delete existing api keys", async function () {
235 const createdApiKeys = await service.createApiKeys([
236 createPublishableKeyFixture,
237 createSecretKeyFixture,
238 ])
239
240 await service.revoke(
241 { id: [createdApiKeys[0].id, createdApiKeys[1].id] },
242 { revoked_by: "test_user" }
243 )
244
245 await service.deleteApiKeys([
246 createdApiKeys[0].id,
247 createdApiKeys[1].id,
248 ])
249
250 const apiKeysInDatabase = await service.listApiKeys()
251 expect(apiKeysInDatabase).toHaveLength(0)
252 })
253
254 it("should throw when trying to delete unrevoked api keys", async function () {
255 const createdApiKeys = await service.createApiKeys([
256 createPublishableKeyFixture,
257 createSecretKeyFixture,
258 ])
259
260 const error = await service
261 .deleteApiKeys([createdApiKeys[0].id, createdApiKeys[1].id])
262 .catch((e) => e)
263
264 expect(error.type).toEqual("not_allowed")
265 expect(error.message).toContain(
266 `Cannot delete api keys that are not revoked - `
267 )
268
269 const apiKeysInDatabase = await service.listApiKeys()
270 expect(apiKeysInDatabase).toHaveLength(2)
271 })
272 })
273
274 describe("authenticating with API keys", () => {
275 it("should authenticate a secret key successfully", async function () {
276 const createdApiKey = await service.createApiKeys(
277 createSecretKeyFixture
278 )
279 const authenticated = await service.authenticate(createdApiKey.token)
280
281 expect(authenticated).toBeTruthy()
282 expect(authenticated.title).toEqual(createSecretKeyFixture.title)
283 })
284 it("should authenticate with a token to be revoked in the future", async function () {
285 const createdApiKey = await service.createApiKeys(
286 createSecretKeyFixture
287 )
288
289 // We simulate setting the revoked_at in the future here
290 jest.useFakeTimers().setSystemTime(new Date().setFullYear(3000))
291 await service.revoke(createdApiKey.id, {
292 revoked_by: "test",
293 })
294 jest.useRealTimers()
295
296 const authenticated = await service.authenticate(createdApiKey.token)
297 expect(authenticated).toBeTruthy()
298 expect(authenticated.title).toEqual(createdApiKey.title)
299 })
300
301 it("should not authenticate a publishable key", async function () {
302 const createdApiKey = await service.createApiKeys(
303 createPublishableKeyFixture
304 )
305 const authenticated = await service.authenticate(createdApiKey.token)
306
307 expect(authenticated).toBeFalsy()
308 })
309 it("should not authenticate with a non-existent token", async function () {
310 const createdApiKey = await service.createApiKeys(
311 createSecretKeyFixture
312 )
313 const authenticated = await service.authenticate("some-token")
314
315 expect(authenticated).toBeFalsy()
316 })
317 it("should not authenticate with a revoked token", async function () {
318 const createdApiKey = await service.createApiKeys(
319 createSecretKeyFixture
320 )
321 await service.revoke(createdApiKey.id, {
322 revoked_by: "test",
323 })
324 const authenticated = await service.authenticate(createdApiKey.token)
325
326 expect(authenticated).toBeFalsy()
327 })
328 })
329
330 describe("retrieving API keys", () => {
331 it("should successfully return all existing api keys", async function () {
332 await service.createApiKeys([
333 createPublishableKeyFixture,
334 createSecretKeyFixture,
335 ])
336
337 const apiKeysInDatabase = await service.listApiKeys()
338 expect(apiKeysInDatabase).toHaveLength(2)
339 })
340
341 it("should only return keys with matching token", async function () {
342 const created = await service.createApiKeys([
343 createPublishableKeyFixture,
344 createPublishableKeyFixture,
345 ])
346
347 const apiKeysInDatabase = await service.listApiKeys({
348 token: created[0].token,
349 })
350 expect(apiKeysInDatabase).toHaveLength(1)
351 expect(apiKeysInDatabase[0].token).toEqual(created[0].token)
352 })
353
354 it("should not return the token and salt for secret keys when listing", async function () {
355 await service.createApiKeys([createSecretKeyFixture])
356
357 const apiKeysInDatabase = await service.listApiKeys()
358 expect(apiKeysInDatabase).toHaveLength(1)
359 expect(apiKeysInDatabase[0].token).toBeFalsy()
360 expect(apiKeysInDatabase[0].salt).toBeFalsy()
361 })
362
363 it("should return the token for publishable keys when listing", async function () {
364 await service.createApiKeys([createPublishableKeyFixture])
365
366 const apiKeysInDatabase = await service.listApiKeys()
367 expect(apiKeysInDatabase).toHaveLength(1)
368 expect(apiKeysInDatabase[0].token).toBeTruthy()
369 expect(apiKeysInDatabase[0].salt).toBeFalsy()
370 })
371
372 it("should not return the token and salt for secret keys when listing and counting", async function () {
373 await service.createApiKeys([createSecretKeyFixture])
374
375 const [apiKeysInDatabase] = await service.listAndCountApiKeys()
376 expect(apiKeysInDatabase).toHaveLength(1)
377 expect(apiKeysInDatabase[0].token).toBeFalsy()
378 expect(apiKeysInDatabase[0].salt).toBeFalsy()
379 })
380
381 it("should return the token for publishable keys when listing and counting", async function () {
382 await service.createApiKeys([createPublishableKeyFixture])
383
384 const [apiKeysInDatabase] = await service.listAndCountApiKeys()
385 expect(apiKeysInDatabase).toHaveLength(1)
386 expect(apiKeysInDatabase[0].token).toBeTruthy()
387 expect(apiKeysInDatabase[0].salt).toBeFalsy()
388 })
389
390 it("should not return the token and salt for secret keys when retrieving", async function () {
391 const [createdApiKey] = await service.createApiKeys([
392 createSecretKeyFixture,
393 ])
394
395 const apiKeyInDatabase = await service.retrieveApiKey(
396 createdApiKey.id
397 )
398 expect(apiKeyInDatabase.token).toBeFalsy()
399 expect(apiKeyInDatabase.salt).toBeFalsy()
400 })
401
402 it("should return the token for publishable keys when retrieving", async function () {
403 const [createdApiKey] = await service.createApiKeys([
404 createPublishableKeyFixture,
405 ])
406
407 const apiKeyInDatabase = await service.retrieveApiKey(
408 createdApiKey.id
409 )
410 expect(apiKeyInDatabase.token).toBeTruthy()
411 expect(apiKeyInDatabase.salt).toBeFalsy()
412 })
413 })
414 })
415 },
416 })