The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Make eajs and react sdk pass JWT via POST instead of GET (#73462)
Nicolò Pretto02126bccf399
diff --git a/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsxindex 605335265f9..5aa367ffd73 100644--- a/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx@@ -334,7 +334,7 @@ describe(cy.intercept("GET", /\/auth\/sso(\?preferred_method=\w+)?$/).as("authSsoDiscovery",);- cy.intercept("GET", /\/auth\/sso\?.*jwt=/).as("authSsoTokenExchange");+ cy.intercept("POST", "**/auth/sso").as("authSsoTokenExchange");cy.intercept("GET", "/api/user/current").as("getCurrentUser");cy.intercept("GET", "/api/session/properties").as("getSessionProperties",diff --git a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsxindex 1fe6472f17e..debf2c7e6b8 100644--- a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx@@ -45,7 +45,7 @@ describe("scenarios > embedding-sdk > requests", () => {const sessionIds: string[] = [];- cy.intercept("GET", "/auth/sso?jwt=**", (req) => {+ cy.intercept("POST", "/auth/sso", (req) => {req.continue((res) => {sessionIds.push(res.body.id);});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.tsindex 4433b6cbdf4..f3f29dc26bc 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts@@ -20,7 +20,7 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>cy.intercept("GET", "http://auth-provider/sso?response=json").as("ssoProvider",);- cy.intercept("GET", "http://localhost:4000/auth/sso?*").as(+ cy.intercept("POST", "http://localhost:4000/auth/sso").as("tokenInSessionOut",);});diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsxindex 3116ca98bc2..7ee49f66882 100644--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx@@ -31,15 +31,16 @@ const setup = ({setupMockJwtEndpoints();const getFirstSsoDiscoveryCall = () => {- // This is `/auth/sso` or `auth/sso?preferred_method=...`- // that returns the method (jwt/saml) and the url of the sso provider- // `auth/sso?jwt=...` is the second call and should be excluded from this+ // This is GET `/auth/sso` or `auth/sso?preferred_method=...`+ // that returns the method (jwt/saml) and the url of the sso provider.+ // The requests that exchanges the JWT for a session is a POST+ // to /auth/sso and should not be matched by this.return fetchMock.callHistory.calls().filter((call) =>new URL(call.url).pathname === "/auth/sso" &&- !new URL(call.url).searchParams.has("jwt"),+ (call.options?.method ?? "GET").toUpperCase() === "GET",);};@@ -91,6 +92,29 @@ describe("Auth Flow - JWT", () => {).toBeInTheDocument();});+ it("should send the JWT in the JSON body via POST to /auth/sso, not in the URL via GET (EMB-1645)", async () => {+ const authConfig = defineMetabaseAuthConfig({+ metabaseInstanceUrl: MOCK_INSTANCE_URL,+ });++ const { getLastUserApiCall } = setup({ authConfig });++ await waitForRequest(() => getLastUserApiCall());++ const ssoExchange = fetchMock.callHistory+ .calls(`${MOCK_INSTANCE_URL}/auth/sso`)+ .find((call) => (call.options?.method ?? "GET").toUpperCase() === "POST");++ expect(ssoExchange).toBeDefined();+ expect(ssoExchange!.url).not.toContain("jwt=");+ expect(ssoExchange!.options.headers).toMatchObject({+ "content-type": "application/json",+ });+ expect(JSON.parse(ssoExchange!.options.body as string)).toEqual({+ jwt: MOCK_VALID_JWT_RESPONSE,+ });+ });+it("should retrieve the session from the authProviderUri and send it as 'X-Metabase-Session' header", async () => {const authConfig = defineMetabaseAuthConfig({metabaseInstanceUrl: MOCK_INSTANCE_URL,@@ -212,16 +236,13 @@ describe("Auth Flow - JWT", () => {},});- fetchMock.get(- `${instanceUrlWithSubpath}/auth/sso?jwt=${MOCK_VALID_JWT_RESPONSE}`,- {- status: 200,- body: {- id: MOCK_SESSION_TOKEN_ID,- user: { id: 1 },- },+ fetchMock.post(`${instanceUrlWithSubpath}/auth/sso`, {+ status: 200,+ body: {+ id: MOCK_SESSION_TOKEN_ID,+ user: { id: 1 },},- );+ });fetchMock.get(`${instanceUrlWithSubpath}/api/user/current`, {status: 200,@@ -268,17 +289,14 @@ describe("Auth Flow - JWT", () => {);// Mock the Metabase SSO validation endpoint- fetchMock.get(- `${MOCK_INSTANCE_URL}/auth/sso?jwt=${MOCK_VALID_JWT_RESPONSE}`,- {- status: 200,- body: {- id: MOCK_SESSION_TOKEN_ID,- exp: 1965805007,- iat: 1609459200,- },+ fetchMock.post(`${MOCK_INSTANCE_URL}/auth/sso`, {+ status: 200,+ body: {+ id: MOCK_SESSION_TOKEN_ID,+ exp: 1965805007,+ iat: 1609459200,},- );+ });const authConfig = defineMetabaseAuthConfig({metabaseInstanceUrl: MOCK_INSTANCE_URL,diff --git a/enterprise/frontend/src/embedding/auth-common/jwt.ts b/enterprise/frontend/src/embedding/auth-common/jwt.tsindex 7a8e7269aee..8a02f0c0378 100644--- a/enterprise/frontend/src/embedding/auth-common/jwt.ts+++ b/enterprise/frontend/src/embedding/auth-common/jwt.ts@@ -13,18 +13,20 @@ export async function jwtDefaultRefreshTokenFunction(const mbAuthUrl = `${instanceUrl}/auth/sso`;- const mbAuthUrlWithJwt = new URL(mbAuthUrl);- mbAuthUrlWithJwt.searchParams.set("jwt", jwtTokenResponse);-let authSsoResponse;try {- authSsoResponse = await fetch(mbAuthUrlWithJwt.toString(), {- headers: requestHeaders,+ authSsoResponse = await fetch(mbAuthUrl, {+ method: "POST",+ headers: {+ ...requestHeaders,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ jwt: jwtTokenResponse }),});} catch (e) {// Network error when connecting to Metabase SSOthrow MetabaseError.CANNOT_FETCH_JWT_TOKEN({- url: mbAuthUrl.toString(),+ url: mbAuthUrl,message: e instanceof Error ? e.message : String(e),});}@@ -32,7 +34,7 @@ export async function jwtDefaultRefreshTokenFunction(if (!authSsoResponse.ok) {// HTTP status error from Metabase SSOthrow MetabaseError.CANNOT_FETCH_JWT_TOKEN({- url: mbAuthUrl.toString(),+ url: mbAuthUrl,status: String(authSsoResponse.status),});}@@ -113,7 +115,7 @@ const refreshUserJwt = async (url: string) => {}const text = await clientBackendResponse.text();- // This should return {url: /auth/sso?jwt=[...]} with the signed token from the client backend+ // This should return { jwt: "<signed-token>" } from the customer's auth providertry {return JSON.parse(text);} catch (e) {diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts b/frontend/src/embedding-sdk-bundle/test/mocks/sso.tsindex c378d83d3ab..c20b3674882 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts@@ -150,7 +150,7 @@ export const setupSamlPopup = () => {* The default setup uses TEST_JWT_TOKEN and automatically mocks the validation endpoint for it.* If you need a different JWT token, you have two options:* 1. Use setupMockJwtEndpoints({ providerResponse: { jwt: "your-token" } }) and manually mock- * fetchMock.get("http://localhost/auth/sso?jwt=your-token", { your response })+ * fetchMock.post("http://localhost/auth/sso", { your response })* 2. Keep the default and use TEST_JWT_TOKEN in your test assertions** To test provider failures, return an error from providerResponse:@@ -207,16 +207,13 @@ export const setupMockJwtEndpoints = ({return { status: 400, body: { error: "Invalid request" } };});- const jwtValidationMock = fetchMock.get(- `${instanceUrl}/auth/sso?jwt=${MOCK_VALID_JWT_RESPONSE}`,- {- body: {- id: sessionToken,- exp,- iat,- },+ const jwtValidationMock = fetchMock.post(`${instanceUrl}/auth/sso`, {+ body: {+ id: sessionToken,+ exp,+ iat,},- );+ });const failureMock = fetchMock.get(failureUrl, {status: 500,body: { error: failureError },