Skip to content

chore(backend): WIP M2M Tokens #6229

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

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
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/hot-tables-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/backend": minor
---

WIP M2M Tokens
108 changes: 102 additions & 6 deletions packages/backend/src/api/endpoints/MachineTokensApi.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,111 @@
import { joinPaths } from '../../util/path';
import type { ClerkBackendApiRequestOptions } from '../request';
import type { MachineToken } from '../resources/MachineToken';
import { AbstractAPI } from './AbstractApi';

const basePath = '/m2m_tokens';

type WithMachineSecret<T> = T & { machineSecret?: string | null };

type CreateMachineTokenParams = WithMachineSecret<{
name: string;
subject: string;
claims?: Record<string, any> | null;
scopes?: string[];
createdBy?: string | null;
secondsUntilExpiration?: number | null;
}>;

type UpdateMachineTokenParams = WithMachineSecret<
{
m2mTokenId: string;
revoked?: boolean;
} & Pick<CreateMachineTokenParams, 'secondsUntilExpiration' | 'claims' | 'scopes'>
>;

type RevokeMachineTokenParams = WithMachineSecret<{
m2mTokenId: string;
revocationReason?: string | null;
}>;

type VerifyMachineTokenParams = WithMachineSecret<{
secret: string;
}>;

export class MachineTokensApi extends AbstractAPI {
async verifySecret(secret: string) {
return this.request<MachineToken>({
method: 'POST',
path: joinPaths(basePath, 'verify'),
bodyParams: { secret },
});
/**
* Overrides the instance secret with the machine secret.
*/
#withMachineSecretHeader(
options: ClerkBackendApiRequestOptions,
machineSecret?: string | null,
): ClerkBackendApiRequestOptions {
if (machineSecret) {
return {
...options,
headerParams: {
Authorization: `Bearer ${machineSecret}`,
},
};
}
return options;
}

async create(params: CreateMachineTokenParams) {
const { machineSecret, ...bodyParams } = params;
return this.request<MachineToken>(
this.#withMachineSecretHeader(
{
method: 'POST',
path: basePath,
bodyParams,
},
machineSecret,
),
);
}

async update(params: UpdateMachineTokenParams) {
const { m2mTokenId, machineSecret, ...bodyParams } = params;
this.requireId(m2mTokenId);
return this.request<MachineToken>(
this.#withMachineSecretHeader(
{
method: 'PATCH',
path: joinPaths(basePath, m2mTokenId),
bodyParams,
},
machineSecret,
),
);
}

async revoke(params: RevokeMachineTokenParams) {
const { m2mTokenId, machineSecret, ...bodyParams } = params;
this.requireId(m2mTokenId);
return this.request<MachineToken>(
this.#withMachineSecretHeader(
{
method: 'POST',
path: joinPaths(basePath, m2mTokenId, 'revoke'),
bodyParams,
},
machineSecret,
),
);
}

async verifySecret(params: VerifyMachineTokenParams) {
const { secret, machineSecret } = params;
return this.request<MachineToken>(
this.#withMachineSecretHeader(
{
method: 'POST',
path: joinPaths(basePath, 'verify'),
bodyParams: { secret },
},
machineSecret,
),
);
}
}
1 change: 1 addition & 0 deletions packages/backend/src/api/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export function createBackendApiClient(options: CreateBackendApiOptions) {
buildRequest({
...options,
skipApiVersionInUrl: true,
requireSecretKey: false,
}),
),
oauthApplications: new OAuthApplicationsApi(request),
Expand Down
6 changes: 3 additions & 3 deletions packages/backend/src/api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ export function buildRequest(options: BuildRequestOptions) {
// Build headers
const headers = new Headers({
'Clerk-API-Version': SUPPORTED_BAPI_VERSION,
'User-Agent': userAgent,
[constants.Headers.UserAgent]: userAgent,
...headerParams,
});

if (secretKey) {
headers.set('Authorization', `Bearer ${secretKey}`);
if (secretKey && !headers.has(constants.Headers.Authorization)) {
headers.set(constants.Headers.Authorization, `Bearer ${secretKey}`);
}

let res: Response | undefined;
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/api/resources/JSON.ts
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,7 @@ export interface SamlAccountConnectionJSON extends ClerkResourceJSON {
export interface MachineTokenJSON extends ClerkResourceJSON {
object: typeof ObjectType.MachineToken;
name: string;
secret?: string;
subject: string;
scopes: string[];
claims: Record<string, any> | null;
Expand Down
4 changes: 3 additions & 1 deletion packages/backend/src/api/resources/MachineToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ export class MachineToken {
readonly creationReason: string | null,
readonly createdAt: number,
readonly updatedAt: number,
readonly secret?: string,
) {}

static fromJSON(data: MachineTokenJSON) {
static fromJSON(data: MachineTokenJSON): MachineToken {
return new MachineToken(
data.id,
data.name,
Expand All @@ -32,6 +33,7 @@ export class MachineToken {
data.creation_reason,
data.created_at,
data.updated_at,
data.secret,
);
}
}
2 changes: 1 addition & 1 deletion packages/backend/src/tokens/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ async function verifyMachineToken(
): Promise<MachineTokenReturnType<MachineToken, MachineTokenVerificationError>> {
try {
const client = createBackendApiClient(options);
const verifiedToken = await client.machineTokens.verifySecret(secret);
const verifiedToken = await client.machineTokens.verifySecret({ secret });
return { data: verifiedToken, tokenType: TokenType.MachineToken, errors: undefined };
} catch (err: any) {
return handleClerkAPIError(TokenType.MachineToken, err, 'Machine token not found');
Expand Down