Skip to content
Open
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/busy-wasps-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@logto/core": patch
---

reject nonexistent organizations when creating one-time tokens
3 changes: 3 additions & 0 deletions packages/core/src/routes/one-time-tokens.openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@
"context": {
"description": "Additional context to store with the one-time token. Set `interactionEvent` to scope the token to a specific flow, such as `ForgotPassword` for reset-password magic links.",
"properties": {
"jitOrganizationIds": {
"description": "Organizations to add the user to when the token is used. All IDs must exist when creating the token; otherwise, the request returns 400 request.invalid_input. Organizations deleted before the token is used are skipped."
},
"jitOrganizationRoles": {
"description": "The organization roles to assign to the user when the token is used, instead of the default JIT roles of the given organizations. Each organization must be in `jitOrganizationIds` and appear only once, and an empty `organizationRoleIds` assigns no roles. Organizations in `jitOrganizationIds` without an entry keep their default JIT roles. Only organization roles for users are accepted, and roles deleted before the token is used are skipped. Existing members keep their current roles; the given roles are added."
}
Expand Down
117 changes: 117 additions & 0 deletions packages/core/src/routes/one-time-tokens.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import {
type CreateOneTimeToken,
Organizations,
OneTimeTokenStatus,
RoleType,
} from '@logto/schemas';
import { pickDefault } from '@logto/shared/esm';

import koaErrorHandler from '#src/middleware/koa-error-handler.js';
import koaI18next from '#src/middleware/koa-i18next.js';
import { mockIdGenerators } from '#src/test-utils/nanoid.js';
import { MockTenant } from '#src/test-utils/tenant.js';
import { createRequester } from '#src/utils/test-utils.js';

const { jest } = import.meta;

await mockIdGenerators();

const mockOrganization = Organizations.guard.parse({
id: 'organization-id',
tenantId: 'mock_id',
name: 'Test organization',
description: null,
customData: {},
isMfaRequired: false,
isTrustedDeviceAllowed: true,
color: {},
branding: {},
customCss: null,
createdAt: 0,
});

const findByIds = jest.fn(async () => [mockOrganization]);
const findRolesByIds = jest.fn(async () => [
{ id: 'role-id', type: RoleType.User, tenantId: 'mock_id', name: 'Role', description: null },
]);
const insertOneTimeToken = jest.fn(async (data: CreateOneTimeToken) => ({
...data,
tenantId: 'mock_id',
context: data.context ?? {},
status: OneTimeTokenStatus.Active,
createdAt: Date.now(),
}));
const updateExpiredOneTimeTokensStatusByEmail = jest.fn();
const routes = await pickDefault(import('./one-time-tokens.js'));
const tenantContext = new MockTenant(undefined, {
organizations: {
findByIds,
},
oneTimeTokens: { insertOneTimeToken, updateExpiredOneTimeTokensStatusByEmail },
});
jest
.spyOn(tenantContext.queries.organizations.roles, 'findByIds')
.mockImplementation(findRolesByIds);
const requester = createRequester({
authedRoutes: routes,
tenantContext,
middlewares: [koaI18next(), koaErrorHandler()],
});

const createToken = async (context?: CreateOneTimeToken['context']) =>
requester.post('/one-time-tokens').send({ email: 'foo@example.com', context });

describe('one-time token organization validation', () => {
afterEach(() => {
jest.clearAllMocks();
});

it.each([undefined, {}, { jitOrganizationIds: [] }])(
'does not query organizations when no IDs are provided: %p',
async (context) => {
const response = await createToken(context);
expect(response.status).toBe(201);
expect(findByIds).not.toHaveBeenCalled();
}
);

it('accepts existing organizations and queries distinct IDs', async () => {
const response = await createToken({
jitOrganizationIds: [mockOrganization.id, mockOrganization.id],
});

expect(response.status).toBe(201);
expect(findByIds).toHaveBeenCalledWith([mockOrganization.id]);
});

it.each([
{ withRoles: false, organizationIds: ['missing-org'] },
{ withRoles: true, organizationIds: ['missing-org'] },
{ withRoles: false, organizationIds: [mockOrganization.id, 'missing-org'] },
{ withRoles: true, organizationIds: [mockOrganization.id, 'missing-org'] },
])('rejects missing organizations: %p', async ({ withRoles, organizationIds }) => {
const response = await createToken({
jitOrganizationIds: organizationIds,
...(withRoles && {
jitOrganizationRoles: [{ organizationId: 'missing-org', organizationRoleIds: ['role-id'] }],
}),
});

expect(response.status).toBe(400);
expect(response.body).toMatchObject({ code: 'request.invalid_input' });
expect(response.body.message).toContain('missing-org');
expect(insertOneTimeToken).not.toHaveBeenCalled();
expect(updateExpiredOneTimeTokensStatusByEmail).not.toHaveBeenCalled();
});

it('accepts a role assignment for an existing organization', async () => {
const response = await createToken({
jitOrganizationIds: [mockOrganization.id],
jitOrganizationRoles: [
{ organizationId: mockOrganization.id, organizationRoleIds: ['role-id'] },
],
});
expect(response.status).toBe(201);
expect(findRolesByIds).toHaveBeenCalledWith(['role-id']);
});
});
23 changes: 20 additions & 3 deletions packages/core/src/routes/one-time-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,30 @@ export default function oneTimeTokenRoutes<T extends ManagementApiRouter>(
]: RouterInitArgs<T>
) {
/**
* Reject the organization roles that can never be assigned when the token is used, so the caller
* Reject organizations and roles that cannot be assigned when the token is created, so the caller
* learns about them now instead of the user being signed in with fewer roles than intended.
*/
const assertJitOrganizationRoles = async ({
const assertJitOrganizationContext = async ({
jitOrganizationIds = [],
jitOrganizationRoles = [],
}: OneTimeTokenContext = {}) => {
const requestedOrganizationIds = [...new Set(jitOrganizationIds)];
if (requestedOrganizationIds.length > 0) {
const existingOrganizations = await organizations.findByIds(requestedOrganizationIds);
const existingOrganizationIds = new Set(existingOrganizations.map(({ id }) => id));
const missingOrganizationIds = requestedOrganizationIds.filter(
(id) => !existingOrganizationIds.has(id)
);

assertThat(
missingOrganizationIds.length === 0,
new RequestError({
code: 'request.invalid_input',
details: `The following organization IDs in \`jitOrganizationIds\` do not exist: ${missingOrganizationIds.join(', ')}.`,
})
);
}

if (jitOrganizationRoles.length === 0) {
return;
}
Expand Down Expand Up @@ -157,7 +174,7 @@ export default function oneTimeTokenRoutes<T extends ManagementApiRouter>(
const { body } = ctx.guard;
const { expiresIn, ...rest } = body;

await assertJitOrganizationRoles(rest.context);
await assertJitOrganizationContext(rest.context);

void trySafe(async () => updateExpiredOneTimeTokensStatusByEmail(rest.email));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,35 @@ describe('one-time token with organization roles', () => {
await deleteUser(userId);
});

it('should skip organizations deleted after the token is created', async () => {
const email = generateEmail();
const kept = await createOrganizationWithRoles();
const deleted = await createOrganizationWithRoles();
const { id, token } = await createOneTimeToken({
email,
context: {
jitOrganizationIds: [kept.organization.id, deleted.organization.id],
jitOrganizationRoles: [
{ organizationId: kept.organization.id, organizationRoleIds: [kept.invitedRole.id] },
{
organizationId: deleted.organization.id,
organizationRoleIds: [deleted.invitedRole.id],
},
],
},
});
await organizationApi.delete(deleted.organization.id);

const userId = await completeOneTimeTokenInteraction(InteractionEvent.Register, email, token);

await expect(getUserRoleIds(kept.organization.id, userId)).resolves.toEqual([
kept.invitedRole.id,
]);

await deleteOneTimeTokenById(id);
await deleteUser(userId);
});

it('should add the given roles to the roles of an existing member', async () => {
const { user, userProfile } = await generateNewUser({ primaryEmail: true, password: true });
const { organization, invitedRole } = await createOrganizationWithRoles();
Expand Down
Loading
Loading