Skip to content

Prioritize JWT over service API keys in authentication #7020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shaky-eels-shine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thirdweb-dev/service-utils": patch
---

Prioritize JWT over service API keys in authentication
4 changes: 4 additions & 0 deletions packages/service-utils/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist/
coverage/
.watchmanconfig
*storybook.log
4 changes: 3 additions & 1 deletion packages/service-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"devDependencies": {
"@cloudflare/workers-types": "4.20250421.0",
"@types/node": "22.14.1",
"@vitest/coverage-v8": "3.1.2",
"typescript": "5.8.3",
"vitest": "3.1.2"
},
Expand All @@ -64,6 +65,7 @@
"build:cjs": "tsc --noCheck --project ./tsconfig.build.json --module commonjs --outDir ./dist/cjs --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./dist/cjs/package.json",
"build:esm": "tsc --noCheck --project ./tsconfig.build.json --module es2020 --outDir ./dist/esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./dist/esm/package.json",
"build:types": "tsc --project ./tsconfig.build.json --module esnext --declarationDir ./dist/types --emitDeclarationOnly --declaration --declarationMap",
"test": "vitest run"
"test": "vitest run",
"coverage": "vitest run --coverage"
}
}
14 changes: 6 additions & 8 deletions packages/service-utils/src/core/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { AuthorizationInput } from "./authorize/index.js";
import { getAuthHeaders } from "./get-auth-headers.js";
import type { ServiceName } from "./services.js";

export type UserOpData = {
Expand Down Expand Up @@ -240,7 +241,7 @@ export async function fetchTeamAndProject(
config: CoreServiceConfig,
): Promise<ApiResponse> {
const { apiUrl, serviceApiKey } = config;
const { teamId, clientId, incomingServiceApiKey } = authData;
const { teamId, clientId } = authData;

const url = new URL("/v2/keys/use", apiUrl);
if (clientId) {
Expand All @@ -250,20 +251,17 @@ export async function fetchTeamAndProject(
url.searchParams.set("teamId", teamId);
}

// compute the appropriate auth headers based on the auth data
const authHeaders = getAuthHeaders(authData, serviceApiKey);

const retryCount = config.retryCount ?? 3;
let error: unknown | undefined;
for (let i = 0; i < retryCount; i++) {
try {
const response = await fetch(url, {
method: "GET",
headers: {
...(authData.secretKey ? { "x-secret-key": authData.secretKey } : {}),
...(authData.jwt ? { Authorization: `Bearer ${authData.jwt}` } : {}),
// use the incoming service api key if it exists, otherwise use the service api key
// this is done to ensure that the incoming service API key is VALID in the first place
"x-service-api-key": incomingServiceApiKey
? incomingServiceApiKey
: serviceApiKey,
...authHeaders,
"content-type": "application/json",
},
});
Expand Down
114 changes: 114 additions & 0 deletions packages/service-utils/src/core/get-auth-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { describe, expect, it } from "vitest";

import type { AuthorizationInput } from "./authorize/index.js";
import { getAuthHeaders } from "./get-auth-headers.js";

describe("getAuthHeaders", () => {
const mockServiceApiKey = "test-service-api-key";
const defaultAuthData: AuthorizationInput = {
incomingServiceApiKey: null,
incomingServiceApiKeyHash: null,
secretKey: null,
clientId: null,
ecosystemId: null,
ecosystemPartnerId: null,
origin: null,
bundleId: null,
secretKeyHash: null,
jwt: null,
hashedJWT: null,
};

it("should use secret key when provided", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
secretKey: "test-secret-key",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
"x-secret-key": "test-secret-key",
});
});

it("should use JWT when both JWT and teamId are provided", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
jwt: "test-jwt",
teamId: "test-team-id",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
Authorization: "Bearer test-jwt",
});
});

it("should use JWT when both JWT and clientId are provided", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
jwt: "test-jwt",
clientId: "test-client-id",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
Authorization: "Bearer test-jwt",
});
});

it("should use incoming service api key when provided", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
incomingServiceApiKey: "test-incoming-service-api-key",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
"x-service-api-key": "test-incoming-service-api-key",
});
});

it("should fall back to service api key when no other auth method is provided", () => {
const headers = getAuthHeaders(defaultAuthData, mockServiceApiKey);

expect(headers).toEqual({
"x-service-api-key": mockServiceApiKey,
});
});

it("should prioritize secret key over other auth methods", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
secretKey: "test-secret-key",
jwt: "test-jwt",
teamId: "test-team-id",
incomingServiceApiKey: "test-incoming-service-api-key",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
"x-secret-key": "test-secret-key",
});
});

it("should prioritize JWT over incoming service api key when teamId is present", () => {
const authData: AuthorizationInput = {
...defaultAuthData,
jwt: "test-jwt",
teamId: "test-team-id",
incomingServiceApiKey: "test-incoming-service-api-key",
};

const headers = getAuthHeaders(authData, mockServiceApiKey);

expect(headers).toEqual({
Authorization: "Bearer test-jwt",
});
});
});
43 changes: 43 additions & 0 deletions packages/service-utils/src/core/get-auth-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { AuthorizationInput } from "./authorize/index.js";

/**
* Computes the appropriate auth headers based on the auth data.
*
* @param authData - The auth data to use.
* @param serviceApiKey - The service api key to use.
* @returns The auth headers.
*/
export function getAuthHeaders(
authData: AuthorizationInput,
serviceApiKey: string,
): Record<string, string> {
const { teamId, clientId, jwt, secretKey, incomingServiceApiKey } = authData;

switch (true) {
// 1. if we have a secret key, we'll use it
case !!secretKey:
return {
"x-secret-key": secretKey,
} as Record<string, string>;

// 2. if we have a JWT AND either a teamId or clientId, we'll use the JWT for auth
case !!(jwt && (teamId || clientId)):
return {
Authorization: `Bearer ${jwt}`,
} as Record<string, string>;

// 3. if we have an incoming service api key, we'll use it
case !!incomingServiceApiKey: {
return {
"x-service-api-key": incomingServiceApiKey,
} as Record<string, string>;
}

// 4. if nothing else is present, we'll use the service api key
default: {
return {
"x-service-api-key": serviceApiKey,
};
}
}
}
Loading
Loading