Skip to content

feat(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

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
65 changes: 65 additions & 0 deletions packages/backend/src/api/endpoints/MachineApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { joinPaths } from '../../util/path';
import type { PaginatedResourceResponse } from '../resources/Deserializer';
import type { Machine } from '../resources/Machine';
import { AbstractAPI } from './AbstractApi';

const basePath = '/machines';

type CreateMachineParams = {
name: string;
};

type UpdateMachineParams = {
machineId: string;
name: string;
};

type GetMachineListParams = {
limit?: number;
offset?: number;
query?: string;
};

export class MachineApi extends AbstractAPI {
async list(queryParams: GetMachineListParams = {}) {
return this.request<PaginatedResourceResponse<Machine[]>>({
method: 'GET',
path: basePath,
queryParams,
});
}

async create(bodyParams: CreateMachineParams) {
return this.request<Machine>({
method: 'POST',
path: basePath,
bodyParams,
});
}

async update(params: UpdateMachineParams) {
const { machineId, ...bodyParams } = params;
this.requireId(machineId);
return this.request<Machine>({
method: 'PATCH',
path: joinPaths(basePath, machineId),
bodyParams,
});
}

async delete(machineId: string) {
this.requireId(machineId);
return this.request<Machine>({
method: 'DELETE',
path: joinPaths(basePath, machineId),
});
}

async get(machineId: string) {
this.requireId(machineId);
return this.request<Machine>({
method: 'GET',
path: joinPaths(basePath, machineId),
});
}
}
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 a 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/endpoints/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from './EmailAddressApi';
export * from './IdPOAuthAccessTokenApi';
export * from './InstanceApi';
export * from './InvitationApi';
export * from './MachineApi';
export * from './MachineTokensApi';
export * from './JwksApi';
export * from './JwtTemplatesApi';
Expand Down
3 changes: 3 additions & 0 deletions packages/backend/src/api/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
InvitationAPI,
JwksAPI,
JwtTemplatesApi,
MachineApi,
MachineTokensApi,
OAuthApplicationsApi,
OrganizationAPI,
Expand Down Expand Up @@ -64,10 +65,12 @@ export function createBackendApiClient(options: CreateBackendApiOptions) {
invitations: new InvitationAPI(request),
jwks: new JwksAPI(request),
jwtTemplates: new JwtTemplatesApi(request),
machines: new MachineApi(request),
machineTokens: new MachineTokensApi(
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
3 changes: 3 additions & 0 deletions packages/backend/src/api/resources/Deserializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
InstanceSettings,
Invitation,
JwtTemplate,
Machine,
MachineToken,
OauthAccessToken,
OAuthApplication,
Expand Down Expand Up @@ -132,6 +133,8 @@ function jsonToObject(item: any): any {
return Invitation.fromJSON(item);
case ObjectType.JwtTemplate:
return JwtTemplate.fromJSON(item);
case ObjectType.Machine:
return Machine.fromJSON(item);
case ObjectType.MachineToken:
return MachineToken.fromJSON(item);
case ObjectType.OauthAccessToken:
Expand Down
11 changes: 11 additions & 0 deletions packages/backend/src/api/resources/JSON.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const ObjectType = {
InstanceRestrictions: 'instance_restrictions',
InstanceSettings: 'instance_settings',
Invitation: 'invitation',
Machine: 'machine',
MachineToken: 'machine_to_machine_token',
JwtTemplate: 'jwt_template',
OauthAccessToken: 'oauth_access_token',
Expand Down Expand Up @@ -698,9 +699,19 @@ export interface SamlAccountConnectionJSON extends ClerkResourceJSON {
updated_at: number;
}

export interface MachineJSON extends ClerkResourceJSON {
object: typeof ObjectType.Machine;
id: string;
name: string;
instance_id: string;
created_at: number;
updated_at: number;
}

export interface MachineTokenJSON extends ClerkResourceJSON {
object: typeof ObjectType.MachineToken;
name: string;
secret?: string;
subject: string;
scopes: string[];
claims: Record<string, any> | null;
Expand Down
15 changes: 15 additions & 0 deletions packages/backend/src/api/resources/Machine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { MachineJSON } from './JSON';

export class Machine {
constructor(
readonly id: string,
readonly name: string,
readonly instanceId: string,
readonly createdAt: number,
readonly updatedAt: number,
) {}

static fromJSON(data: MachineJSON): Machine {
return new Machine(data.id, data.name, data.instance_id, data.created_at, data.updated_at);
}
}
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,
);
}
}
1 change: 1 addition & 0 deletions packages/backend/src/api/resources/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export * from './InstanceRestrictions';
export * from './InstanceSettings';
export * from './Invitation';
export * from './JSON';
export * from './Machine';
export * from './MachineToken';
export * from './JwtTemplate';
export * from './OauthAccessToken';
Expand Down
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
Loading