-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathexchange.test.ts
More file actions
339 lines (295 loc) · 11.2 KB
/
Copy pathexchange.test.ts
File metadata and controls
339 lines (295 loc) · 11.2 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
import {
exchangeAccessForApplicationTokens,
exchangeCustomPartnerToken,
exchangeAppAutomationTokenForAppManagementAccessToken,
exchangeAppAutomationTokenForBusinessPlatformAccessToken,
InvalidGrantError,
InvalidRequestError,
refreshAccessToken,
requestAppToken,
} from './exchange.js'
import {applicationId, clientId} from './identity.js'
import {IdentityToken} from './schema.js'
import {shopifyFetch} from '../../../public/node/http.js'
import {identityFqdn} from '../../../public/node/context/fqdn.js'
import {getLastSeenUserIdAfterAuth, getLastSeenAuthMethod} from '../session.js'
import {AbortError} from '../../../public/node/error.js'
import {describe, test, expect, vi, afterAll, beforeEach} from 'vitest'
import {Response} from 'node-fetch'
const currentDate = new Date(2022, 1, 1, 10)
const expiredDate = new Date(2022, 1, 1, 11)
const data: any = {
access_token: 'access_token',
refresh_token: 'refresh_token',
scope: 'scope scope2',
expires_in: 3600,
// id_token:{sub: '1234-5678'}
id_token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0LTU2NzgifQ.L8IiNHncR4xe42f1fLQZFD5D_HBo7oMlfop2FS-NUCU',
}
const identityToken: IdentityToken = {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: expiredDate,
scopes: data.scope.split(' '),
userId: '1234-5678',
alias: '1234-5678',
}
vi.mock('../../../public/node/http.js')
vi.mock('../../../public/node/context/fqdn.js')
vi.mock('./identity')
beforeEach(() => {
vi.mocked(clientId).mockReturnValue('clientId')
vi.setSystemTime(currentDate)
vi.mocked(applicationId).mockImplementation((api) => api)
vi.mocked(identityFqdn).mockResolvedValue('fqdn.com')
})
afterAll(() => {
// Restore Date mock
vi.useRealTimers()
})
describe('exchange identity token for application tokens', () => {
const scopes = {admin: [], partners: [], storefront: [], businessPlatform: [], appManagement: []}
test('returns tokens for all APIs if a store is passed', async () => {
// Given
vi.mocked(shopifyFetch).mockImplementation(async () => Promise.resolve(new Response(JSON.stringify(data))))
// When
const got = await exchangeAccessForApplicationTokens(identityToken, scopes, 'storeFQDN')
// Then
const expected = {
'app-management': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
partners: {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
'storefront-renderer': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
'storeFQDN-admin': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
'business-platform': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
}
expect(got).toEqual(expected)
})
test('does not return token for admin if there is no store', async () => {
// Given
const response = new Response(JSON.stringify(data))
// Need to do it 3 times because a Response can only be used once
vi.mocked(shopifyFetch)
.mockResolvedValue(response)
.mockResolvedValueOnce(response.clone())
.mockResolvedValueOnce(response.clone())
.mockResolvedValueOnce(response.clone())
// When
const got = await exchangeAccessForApplicationTokens(identityToken, scopes, undefined)
// Then
const expected = {
'app-management': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
partners: {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
'storefront-renderer': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
'business-platform': {
accessToken: 'access_token',
expiresAt: expiredDate,
scopes: ['scope', 'scope2'],
},
}
expect(got).toEqual(expected)
})
})
describe('refresh access tokens', () => {
test('throws an InvalidGrantError when Identity returns invalid_grant', async () => {
// Given
const error = {error: 'invalid_grant'}
const response = new Response(JSON.stringify(error), {status: 400})
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const got = () => refreshAccessToken(identityToken)
// Then
return expect(got).rejects.toThrowError(InvalidGrantError)
})
test('throws an InvalidRequestError when Identity returns invalid_request', async () => {
// Given
const error = {error: 'invalid_request'}
const response = new Response(JSON.stringify(error), {status: 400})
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const got = () => refreshAccessToken(identityToken)
// Then
return expect(got).rejects.toThrowError(InvalidRequestError)
})
test('throws an InvalidTargetError when Identity returns invalid_target', async () => {
// Given
const error = {error: 'invalid_target'}
const response = new Response(JSON.stringify(error), {status: 400})
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const got = () => refreshAccessToken(identityToken)
// Then
await expect(got).rejects.toThrowError('You are not authorized to use the CLI to develop in the provided store.')
})
describe('when there is a store in the request params', () => {
test('includes the store in the error message', async () => {
// Given
const error = {error: 'invalid_target'}
const response = new Response(JSON.stringify(error), {status: 400})
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const got = () => requestAppToken('admin', 'token', undefined, 'bob.myshopify.com')
// Then
await expect(got).rejects.toThrowError(
'You are not authorized to use the CLI to develop in the provided store: bob.myshopify.com',
)
})
})
test('throws an AbortError when Identity returns another error', async () => {
// Given
const error = {error: 'another'}
const response = new Response(JSON.stringify(error), {status: 400})
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const got = () => refreshAccessToken(identityToken)
// Then
return expect(got).rejects.toThrowError(AbortError)
})
test('preserves the alias when refreshing access token', async () => {
// Given
const tokenWithAlias: IdentityToken = {
...identityToken,
alias: 'my-custom-alias',
}
const refreshData = {
access_token: 'new_access_token',
refresh_token: 'new_refresh_token',
scope: 'new_scope',
expires_in: 7200,
id_token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1Njc4LTEyMzQifQ.2OGPUmd5MTEv-J5p3Ra4mskCN0635qN8lh3p5_BcoYY',
}
const response = new Response(JSON.stringify(refreshData))
vi.mocked(shopifyFetch).mockResolvedValue(response)
// When
const result = await refreshAccessToken(tokenWithAlias)
// Then
expect(result.accessToken).toBe('new_access_token')
expect(result.refreshToken).toBe('new_refresh_token')
expect(result.scopes).toEqual(['new_scope'])
// Original userId is preserved
expect(result.userId).toBe('1234-5678')
// Alias is preserved
expect(result.alias).toBe('my-custom-alias')
})
})
const tokenExchangeMethods = [
{
tokenExchangeMethod: exchangeCustomPartnerToken,
expectedScopes: ['https://api.shopify.com/auth/partners.app.cli.access'],
expectedApi: 'partners',
expectedErrorName: 'Partners',
},
{
tokenExchangeMethod: exchangeAppAutomationTokenForAppManagementAccessToken,
expectedScopes: ['https://api.shopify.com/auth/organization.apps.manage'],
expectedApi: 'app-management',
expectedErrorName: 'App Management',
},
{
tokenExchangeMethod: exchangeAppAutomationTokenForBusinessPlatformAccessToken,
expectedScopes: ['https://api.shopify.com/auth/destinations.readonly'],
expectedApi: 'business-platform',
expectedErrorName: 'Business Platform',
},
]
describe.each(tokenExchangeMethods)(
'Token exchange: %s',
({tokenExchangeMethod, expectedScopes, expectedApi, expectedErrorName}) => {
const automationToken = 'customToken'
// Generated from `customToken` using `nonRandomUUID()`
const userId = '9d5342f1-beb2-14c1-9f5d-deee6b83513c'
const grantType = 'urn:ietf:params:oauth:grant-type:token-exchange'
const accessTokenType = 'urn:ietf:params:oauth:token-type:access_token'
test(`Executing ${tokenExchangeMethod.name} returns access token and user ID for a valid CLI token`, async () => {
// Given
let capturedUrl = ''
let capturedInit: {method?: string; headers?: Record<string, string>; body?: string} = {}
vi.mocked(shopifyFetch).mockImplementation(async (url, options) => {
capturedUrl = url.toString()
capturedInit = (options ?? {}) as typeof capturedInit
return Promise.resolve(
new Response(
JSON.stringify({
access_token: 'expected_access_token',
expires_in: 300,
scope: 'scope,scope2',
}),
),
)
})
// When
const result = await tokenExchangeMethod(automationToken)
// Then
expect(result).toEqual({accessToken: 'expected_access_token', userId})
await expect(getLastSeenUserIdAfterAuth()).resolves.toBe(userId)
await expect(getLastSeenAuthMethod()).resolves.toBe('partners_token')
// Request is sent as POST form-encoded body (not query string), so the
// URL must not contain any OAuth parameters.
const actualUrl = new URL(capturedUrl)
expect(actualUrl).toBeDefined()
expect(actualUrl.href).toBe('https://fqdn.com/oauth/token')
expect(actualUrl.search).toBe('')
expect(capturedInit.method).toBe('POST')
expect(capturedInit.headers).toMatchObject({
'Content-Type': 'application/x-www-form-urlencoded',
})
expect(typeof capturedInit.body).toBe('string')
// Assert token exchange parameters are correct and sent in the body.
const params = new URLSearchParams(capturedInit.body)
expect(params.get('grant_type')).toBe(grantType)
expect(params.get('requested_token_type')).toBe(accessTokenType)
expect(params.get('subject_token_type')).toBe(accessTokenType)
expect(params.get('client_id')).toBe('clientId')
expect(params.get('audience')).toBe(expectedApi)
expect(params.get('scope')).toBe(expectedScopes.join(' '))
expect(params.get('subject_token')).toBe(automationToken)
})
test(`Executing ${tokenExchangeMethod.name} throws AbortError if an error is caught`, async () => {
const expectedErrorMessage = `The custom token provided can't be used for the ${expectedErrorName} API.`
vi.mocked(shopifyFetch).mockImplementation(async () => {
throw new Error('BAD ERROR')
})
try {
await tokenExchangeMethod(automationToken)
} catch (error) {
if (error instanceof Error) {
expect(error).toBeInstanceOf(AbortError)
expect(error.message).toBe(expectedErrorMessage)
} else {
throw error
}
}
})
},
)