1 import { MedusaError } from "@medusajs/framework/utils"
2 import { GithubAuthService } from "../../src/services/github"
3 import { http, HttpResponse } from "msw"
4 import { setupServer } from "msw/node"
5
6 jest.setTimeout(100000)
7
8 const sampleIdPayload = {
9 login: "octocat",
10 id: 1,
11 node_id: "MDQ6VXNlcjE=",
12 avatar_url: "https://github.com/images/error/octocat_happy.gif",
13 gravatar_id: "",
14 url: "https://api.github.com/users/octocat",
15 name: "monalisa octocat",
16 company: "GitHub",
17 location: "San Francisco",
18 email: "octocat@github.com",
19 two_factor_authentication: true,
20 }
21
22 const baseUrl = "https://someurl.com"
23 const callbackUrl = encodeURIComponent(
24 "https://someurl.com/auth/github/callback"
25 )
26
27 let state = {}
28 const defaultSpies = {
29 retrieve: jest.fn(),
30 create: jest.fn(),
31 update: jest.fn(),
32 setState: jest.fn().mockImplementation((key, value) => {
33 state[key] = value
34 }),
35 getState: jest.fn().mockImplementation((key) => {
36 return Promise.resolve(state[key])
37 }),
38 }
39
40 // This is just a network-layer mocking, it doesn't start an actual server
41 const server = setupServer(
42 http.post(
43 "https://github.com/login/oauth/access_token",
44 async ({ request, params, cookies }) => {
45 const url = request.url
46 if (
47 url ===
48 `https://github.com/login/oauth/access_token?client_id=test&client_secret=test&code=invalid-code&redirect_uri=${callbackUrl}`
49 ) {
50 return new HttpResponse(null, {
51 status: 401,
52 statusText: "Unauthorized",
53 })
54 }
55
56 if (
57 url ===
58 `https://github.com/login/oauth/access_token?client_id=test&client_secret=test&code=valid-code&redirect_uri=${callbackUrl}`
59 ) {
60 return new HttpResponse(
61 JSON.stringify({
62 access_token: "test",
63 expires_in: 3600,
64 refresh_token: "test",
65 refresh_token_expires_in: 7200,
66 })
67 )
68 }
69 }
70 ),
71
72 http.get(
73 "https://api.github.com/user",
74 async ({ request, params, cookies }) => {
75 return new HttpResponse(JSON.stringify(sampleIdPayload), {
76 status: 200,
77 statusText: "OK",
78 })
79 }
80 ),
81
82 http.all("*", ({ request, params, cookies }) => {
83 return new HttpResponse(null, {
84 status: 404,
85 statusText: "Not Found",
86 })
87 })
88 )
89
90 describe("Github auth provider", () => {
91 let githubService: GithubAuthService
92 beforeAll(() => {
93 githubService = new GithubAuthService(
94 {
95 logger: console as any,
96 },
97 {
98 clientId: "test",
99 clientSecret: "test",
100 callbackUrl: `${baseUrl}/auth/github/callback`,
101 }
102 )
103
104 server.listen()
105 })
106
107 afterEach(() => {
108 server.resetHandlers()
109 jest.restoreAllMocks()
110 state = {}
111 })
112
113 afterAll(() => server.close())
114
115 it("throw an error if required options are not passed", async () => {
116 let msg = ""
117 try {
118 GithubAuthService.validateOptions({
119 clientId: "test",
120 clientSecret: "test",
121 } as any)
122 } catch (e) {
123 msg = e.message
124 }
125
126 expect(msg).toEqual("Github callbackUrl is required")
127 })
128
129 it("returns a redirect URL on authenticate", async () => {
130 const res = await githubService.authenticate({}, defaultSpies)
131 expect(res).toEqual({
132 success: true,
133 location: `https://github.com/login/oauth/authorize?redirect_uri=${callbackUrl}&client_id=test&response_type=code&state=${
134 Object.keys(state)[0]
135 }`,
136 })
137 })
138
139 it("returns a custom redirect_uri on authenticate", async () => {
140 const res = await githubService.authenticate(
141 {
142 body: { callback_url: "https://someotherurl.com" },
143 },
144 defaultSpies
145 )
146 expect(res).toEqual({
147 success: true,
148 location: `https://github.com/login/oauth/authorize?redirect_uri=https%3A%2F%2Fsomeotherurl.com&client_id=test&response_type=code&state=${
149 Object.keys(state)[0]
150 }`,
151 })
152 })
153
154 it("validate callback should return an error on empty code", async () => {
155 const res = await githubService.validateCallback(
156 {
157 query: {},
158 },
159 defaultSpies
160 )
161 expect(res).toEqual({
162 success: false,
163 error: "No code provided",
164 })
165 })
166
167 it("validate callback should return an error on missing state", async () => {
168 const res = await githubService.validateCallback(
169 {
170 query: {
171 code: "valid-code",
172 },
173 },
174 defaultSpies
175 )
176 expect(res).toEqual({
177 success: false,
178 error: "No state provided, or session expired",
179 })
180 })
181
182 it("validate callback should return an error on expired/invalid state", async () => {
183 const res = await githubService.validateCallback(
184 {
185 query: {
186 code: "valid-code",
187 state: "somekey",
188 },
189 },
190 defaultSpies
191 )
192 expect(res).toEqual({
193 success: false,
194 error: "No state provided, or session expired",
195 })
196 })
197
198 it("validate callback should return on a missing access token for code", async () => {
199 state = {
200 somekey: {
201 callback_url: callbackUrl,
202 },
203 }
204 const res = await githubService.validateCallback(
205 {
206 query: {
207 code: "invalid-code",
208 state: "somekey",
209 },
210 },
211 defaultSpies
212 )
213
214 expect(res).toEqual({
215 success: false,
216 error: "Could not exchange token, 401, Unauthorized",
217 })
218 })
219
220 it("validate callback should return successfully on a correct code for a new user", async () => {
221 const authServiceSpies = {
222 ...defaultSpies,
223 retrieve: jest.fn().mockImplementation(() => {
224 throw new MedusaError(MedusaError.Types.NOT_FOUND, "Not found")
225 }),
226 create: jest.fn().mockImplementation(() => {
227 return {
228 provider_identities: [
229 {
230 entity_id: "test@admin.com",
231 provider: "github",
232 },
233 ],
234 }
235 }),
236 update: jest.fn().mockImplementation(() => {
237 throw new MedusaError(MedusaError.Types.NOT_FOUND, "Not found")
238 }),
239 }
240
241 state = {
242 somekey: {
243 callback_url: callbackUrl,
244 },
245 }
246
247 const res = await githubService.validateCallback(
248 {
249 query: {
250 code: "valid-code",
251 state: "somekey",
252 },
253 },
254 authServiceSpies
255 )
256
257 expect(res).toEqual({
258 success: true,
259 authIdentity: {
260 provider_identities: [
261 {
262 entity_id: "test@admin.com",
263 provider: "github",
264 },
265 ],
266 },
267 })
268 })
269
270 it("validate callback should return successfully on a correct code for an existing user", async () => {
271 const authServiceSpies = {
272 ...defaultSpies,
273 retrieve: jest.fn().mockImplementation(() => {
274 return {
275 provider_identities: [
276 {
277 entity_id: "test@admin.com",
278 provider: "github",
279 },
280 ],
281 }
282 }),
283 create: jest.fn().mockImplementation(() => {
284 return {}
285 }),
286 update: jest.fn().mockImplementation(() => {
287 return {
288 provider_identities: [
289 {
290 entity_id: "test@admin.com",
291 provider: "github",
292 provider_metadata: {
293 access_token: "test",
294 },
295 },
296 ],
297 }
298 }),
299 }
300
301 state = {
302 somekey: {
303 callback_url: callbackUrl,
304 },
305 }
306
307 const res = await githubService.validateCallback(
308 {
309 query: {
310 code: "valid-code",
311 state: "somekey",
312 },
313 },
314 authServiceSpies
315 )
316
317 expect(res).toEqual({
318 success: true,
319 authIdentity: {
320 provider_identities: [
321 {
322 entity_id: "test@admin.com",
323 provider: "github",
324 provider_metadata: {
325 access_token: "test",
326 },
327 },
328 ],
329 },
330 })
331 })
332 })