Improve error messaging

This commit is contained in:
Adria Navarro 2025-03-13 10:52:49 +01:00
parent e8201ea490
commit db7fb81591
2 changed files with 41 additions and 3 deletions
packages/server/src/sdk/app/oauth2

View File

@ -52,5 +52,39 @@ describe("oauth2 utils", () => {
expect(response).toEqual(expect.stringMatching(/^Bearer .+/))
})
it("handles wrong secrets", async () => {
await expect(
config.doInContext(config.appId, async () => {
const oauthConfig = await sdk.oauth2.create({
name: generator.guid(),
url: `${keycloakUrl}/realms/myrealm/protocol/openid-connect/token`,
clientId: "my-client",
clientSecret: "wrong-secret",
})
await generateToken(oauthConfig.id)
})
).rejects.toThrow(
"Error fetching oauth2 token: Invalid client or Invalid client credentials"
)
})
it("handles wrong client ids", async () => {
await expect(
config.doInContext(config.appId, async () => {
const oauthConfig = await sdk.oauth2.create({
name: generator.guid(),
url: `${keycloakUrl}/realms/myrealm/protocol/openid-connect/token`,
clientId: "wrong-client-id",
clientSecret: "my-secret",
})
await generateToken(oauthConfig.id)
})
).rejects.toThrow(
"Error fetching oauth2 token: Invalid client or Invalid client credentials"
)
})
})
})

View File

@ -20,9 +20,13 @@ export async function generateToken(id: string) {
}),
redirect: "follow",
})
if (resp.status !== 200) {
throw new Error(`Error fetching oauth2 token: ${resp.statusText}`)
}
const jsonResponse = await resp.json()
if (!resp.ok) {
const message = jsonResponse.error_description ?? resp.statusText
throw new Error(`Error fetching oauth2 token: ${message}`)
}
return `${jsonResponse.token_type} ${jsonResponse.access_token}`
}