1 import { IAuthModuleService, UserDTO } from "@medusajs/framework/types"
2 import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
3 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
4 import jwt from "jsonwebtoken"
5 import {
6 adminHeaders,
7 createAdminUser,
8 } from "../../../helpers/create-admin-user"
9
10 jest.setTimeout(100000)
11
12 const PROVIDER_ID = "oidc-okta"
13
14 const signActorlessToken = (
15 jwtSecret: string,
16 {
17 authIdentityId,
18 userMetadata,
19 provider = PROVIDER_ID,
20 actorId = "",
21 }: {
22 authIdentityId: string
23 userMetadata: Record<string, unknown>
24 provider?: string
25 actorId?: string
26 }
27 ) =>
28 jwt.sign(
29 {
30 actor_id: actorId,
31 actor_type: "user",
32 auth_identity_id: authIdentityId,
33 auth_provider: provider,
34 user_metadata: userMetadata,
35 },
36 jwtSecret,
37 { expiresIn: "1d" }
38 )
39
40 medusaIntegrationTestRunner({
41 testSuite: ({ getContainer, api, dbConnection, dbUtils }) => {
42 describe("Auth provider discovery", () => {
43 // The HTTP test env registers a single "emailpass" auth provider, and
44 // allowlists ["emailpass", "oidc-okta"] for the `user` actor. Only
45 // registered providers are listed, so the allowlisted-but-unregistered
46 // "oidc-okta" never shows up here.
47 const emailpassProvider = {
48 id: "emailpass",
49 identifier: "emailpass",
50 display_name: "Email/Password Authentication",
51 flow: "credentials",
52 }
53
54 it("lists the auth providers for the user actor type without authentication", async () => {
55 const response = await api.get("/auth/user/providers")
56
57 expect(response.status).toEqual(200)
58 expect(response.data.providers).toEqual([emailpassProvider])
59 })
60
61 it("lists the auth providers for the customer actor type", async () => {
62 const response = await api.get("/auth/customer/providers")
63
64 expect(response.status).toEqual(200)
65 expect(response.data.providers).toEqual([emailpassProvider])
66 })
67
68 it("never exposes provider options or secrets", async () => {
69 const response = await api.get("/auth/user/providers")
70
71 for (const provider of response.data.providers) {
72 expect(Object.keys(provider).sort()).toEqual([
73 "display_name",
74 "flow",
75 "id",
76 "identifier",
77 ])
78 }
79 })
80 })
81
82 describe("user provisioning - POST /auth/:auth_provider/user", () => {
83 let authModule: IAuthModuleService
84 let jwtSecret: string
85 let existingUser: UserDTO
86
87 beforeAll(async () => {
88 const container = getContainer()
89 authModule = container.resolve(Modules.AUTH)
90 jwtSecret = container
91 .resolve(ContainerRegistrationKeys.CONFIG_MODULE)
92 .projectConfig.http.jwtSecret!.toString()
93
94 const adminUser = await createAdminUser(
95 dbConnection,
96 adminHeaders,
97 container
98 )
99 existingUser = adminUser.user
100
101 await dbUtils.snapshot()
102 })
103
104 // Creates an auth identity as the auth module would after a redirect
105 // provider's callback: a single provider identity carrying the profile
106 // claims in `user_metadata`.
107 const createProviderIdentity = (
108 userMetadata: Record<string, unknown>,
109 provider = PROVIDER_ID
110 ) =>
111 authModule.createAuthIdentities({
112 provider_identities: [
113 {
114 provider,
115 entity_id: `${provider}-${userMetadata.email ?? "no-email"}`,
116 user_metadata: userMetadata,
117 },
118 ],
119 })
120
121 it("creates a new user when none exists for the verified email", async () => {
122 const claims = {
123 email: "sso-new@acme.com",
124 given_name: "New",
125 family_name: "User",
126 }
127 const authIdentity = await createProviderIdentity(claims)
128 const token = signActorlessToken(jwtSecret, {
129 authIdentityId: authIdentity.id,
130 userMetadata: claims,
131 })
132
133 const response = await api.post(
134 `/auth/${PROVIDER_ID}/user`,
135 {},
136 { headers: { authorization: `Bearer ${token}` } }
137 )
138
139 expect(response.status).toEqual(200)
140 expect(response.data.user).toMatchObject({
141 id: expect.any(String),
142 email: "sso-new@acme.com",
143 first_name: "New",
144 last_name: "User",
145 })
146 const createdUserId = response.data.user.id
147 expect(createdUserId).not.toEqual(existingUser.id)
148
149 // The identity is linked to the new user.
150 const linkedIdentity = await authModule.retrieveAuthIdentity(
151 authIdentity.id
152 )
153 expect(linkedIdentity.app_metadata?.user_id).toEqual(createdUserId)
154
155 // Refreshing the (still-actorless) token now yields an actor token.
156 const refreshResponse = await api.post(
157 "/auth/token/refresh",
158 {},
159 { headers: { authorization: `Bearer ${token}` } }
160 )
161 expect(refreshResponse.status).toEqual(200)
162 expect(jwt.decode(refreshResponse.data.token)).toMatchObject({
163 actor_type: "user",
164 auth_identity_id: authIdentity.id,
165 actor_id: createdUserId,
166 })
167
168 const meResponse = await api.get("/admin/users/me", {
169 headers: { authorization: `Bearer ${refreshResponse.data.token}` },
170 })
171 expect(meResponse.status).toEqual(200)
172 expect(meResponse.data.user).toMatchObject({ id: createdUserId })
173 })
174
175 it("links the existing user when one already exists for the email", async () => {
176 const claims = {
177 email: existingUser.email,
178 given_name: "Existing",
179 family_name: "Admin",
180 }
181 const authIdentity = await createProviderIdentity(claims)
182 const token = signActorlessToken(jwtSecret, {
183 authIdentityId: authIdentity.id,
184 userMetadata: claims,
185 })
186
187 const response = await api.post(
188 `/auth/${PROVIDER_ID}/user`,
189 {},
190 { headers: { authorization: `Bearer ${token}` } }
191 )
192
193 expect(response.status).toEqual(200)
194 // The existing user is returned, not a newly created one.
195 expect(response.data.user).toMatchObject({
196 id: existingUser.id,
197 email: existingUser.email,
198 })
199
200 // The new identity is linked to the existing user.
201 const linkedIdentity = await authModule.retrieveAuthIdentity(
202 authIdentity.id
203 )
204 expect(linkedIdentity.app_metadata?.user_id).toEqual(existingUser.id)
205
206 const refreshResponse = await api.post(
207 "/auth/token/refresh",
208 {},
209 { headers: { authorization: `Bearer ${token}` } }
210 )
211 expect(jwt.decode(refreshResponse.data.token)).toMatchObject({
212 actor_id: existingUser.id,
213 })
214 })
215
216 it("rejects when the identity was issued by a different provider", async () => {
217 const claims = { email: "sso-mismatch@acme.com" }
218 // Identity created by "github"; provisioning attempted via "oidc-okta".
219 const authIdentity = await createProviderIdentity(claims, "github")
220 const token = signActorlessToken(jwtSecret, {
221 authIdentityId: authIdentity.id,
222 userMetadata: claims,
223 provider: "github",
224 })
225
226 const response = await api
227 .post(
228 `/auth/${PROVIDER_ID}/user`,
229 {},
230 { headers: { authorization: `Bearer ${token}` } }
231 )
232 .catch((error) => error.response)
233
234 expect(response.status).toEqual(401)
235 })
236
237 it("rejects when the identity carries no email claim", async () => {
238 const authIdentity = await createProviderIdentity({
239 email: "sso-noemail@acme.com",
240 })
241 // Sign a token whose user_metadata has no email (the route reads the
242 // email from the backend-signed token, never the request body).
243 const token = signActorlessToken(jwtSecret, {
244 authIdentityId: authIdentity.id,
245 userMetadata: { given_name: "No", family_name: "Email" },
246 })
247
248 const response = await api
249 .post(
250 `/auth/${PROVIDER_ID}/user`,
251 {},
252 { headers: { authorization: `Bearer ${token}` } }
253 )
254 .catch((error) => error.response)
255
256 expect(response.status).toEqual(400)
257 })
258
259 it("rejects when the token is already linked to an actor", async () => {
260 const claims = { email: "sso-already-linked@acme.com" }
261 const authIdentity = await createProviderIdentity(claims)
262 const token = signActorlessToken(jwtSecret, {
263 authIdentityId: authIdentity.id,
264 userMetadata: claims,
265 actorId: existingUser.id,
266 })
267
268 const response = await api
269 .post(
270 `/auth/${PROVIDER_ID}/user`,
271 {},
272 { headers: { authorization: `Bearer ${token}` } }
273 )
274 .catch((error) => error.response)
275
276 expect(response.status).toEqual(400)
277 })
278
279 it("rejects an unauthenticated request", async () => {
280 const response = await api
281 .post(`/auth/${PROVIDER_ID}/user`, {})
282 .catch((error) => error.response)
283
284 expect(response.status).toEqual(401)
285 })
286
287 it("rejects a provider that is not allowlisted for the user actor type", async () => {
288 const claims = { email: "sso-not-allowed@acme.com" }
289 const authIdentity = await createProviderIdentity(claims, "google")
290 const token = signActorlessToken(jwtSecret, {
291 authIdentityId: authIdentity.id,
292 userMetadata: claims,
293 provider: "google",
294 })
295
296 const response = await api
297 .post(
298 "/auth/google/user",
299 {},
300 { headers: { authorization: `Bearer ${token}` } }
301 )
302 .catch((error) => error.response)
303
304 expect(response.status).toEqual(400)
305 expect(response.data.message).toEqual(
306 "The actor type user is not allowed to use the auth provider google"
307 )
308 })
309 })
310 },
311 })