Skip to content
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

fix(schemas): fix the get interation/consent api bug #5503

Merged
merged 5 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
fix(schemas): fix the get interation/consent api bug
fix the get interation/consent api bug
  • Loading branch information
simeng-li committed Mar 20, 2024
commit e080e099f2e991bb74b5190d763bd60b36a9a91b
24 changes: 24 additions & 0 deletions .changeset/seven-socks-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
"@logto/schemas": patch
---

## Fix third-party app get /interaction/consent 500 bug

### Steps to reproduce

1. Create a organization scope with empty description, add assign the scope to a third-party app
2. Sign in the third-party app and request for the organization scope
3. Follow the interaction flow till the consent page
4. A internal server error 500 is returned

### Root cause

For the get /interaction/consent endpoint, organization scope is returned with other resource scopes in the `missingResourceScopes` property.

In the `consentInfoResponseGuard`, we use the resource `Scopes` zod guard to validate the `missingResourceScopes` property. However, the description field in resource scope is required. A organization scope with empty description will fail the validation.

### Fix

Update the `consentInfoResponseGuard`'s missingResourceScopes property. Use the organization scope zod guard which does not require the description field.

The alignment of the resource scope and organization scope type will be handled in the next release.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ReservedResource, UserScope } from '@logto/core-kit';
import { type ConsentInfoResponse } from '@logto/schemas';
import { type Nullable } from '@silverhand/essentials';
import classNames from 'classnames';
import { useCallback, useMemo, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
Expand All @@ -20,7 +21,7 @@ type ScopeGroupProps = {
scopes: Array<{
id: string;
name: string;
description?: string;
description?: Nullable<string>; // Organization scopes description is nullable
simeng-li marked this conversation as resolved.
Show resolved Hide resolved
}>;
};

Expand Down
9 changes: 9 additions & 0 deletions packages/integration-tests/src/api/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
RequestVerificationCodePayload,
BindMfaPayload,
VerifyMfaPayload,
ConsentInfoResponse,
} from '@logto/schemas';
import type { Got } from 'got';

Expand Down Expand Up @@ -154,6 +155,14 @@ export const consent = async (api: Got, cookie: string) =>
})
.json<RedirectResponse>();

export const getConsentInfo = async (cookie: string) =>
api
.get('interaction/consent', {
headers: { cookie },
followRedirect: false,
})
.json<ConsentInfoResponse>();

export const createSingleSignOnAuthorizationUri = async (
cookie: string,
payload: SocialAuthorizationUriPayload
Expand Down
7 changes: 6 additions & 1 deletion packages/integration-tests/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default class MockClient {
assert(this.interactionCookie, new Error('Get cookie from authorization endpoint failed'));
}

public async processSession(redirectTo: string) {
public async processSession(redirectTo: string, consent = true) {
simeng-li marked this conversation as resolved.
Show resolved Hide resolved
// Note: should redirect to OIDC auth endpoint
assert(
redirectTo.startsWith(`${this.config.endpoint}/oidc/auth`),
Expand All @@ -106,6 +106,11 @@ export default class MockClient {

this.rawCookies = authResponse.headers['set-cookie'] ?? [];

// Manually handle the consent flow
if (!consent) {
return;
}

const signInCallbackUri = await this.consent();
await this.logto.handleSignInCallback(signInCallbackUri);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { ReservedResource, UserScope } from '@logto/core-kit';
import { type Application, InteractionEvent, ApplicationType } from '@logto/schemas';
import { assert } from '@silverhand/essentials';

import { deleteUser } from '#src/api/admin-user.js';
import { assignUserConsentScopes } from '#src/api/application-user-consent-scope.js';
import { createApplication, deleteApplication } from '#src/api/application.js';
import { getConsentInfo, putInteraction } from '#src/api/interaction.js';
import { OrganizationScopeApi } from '#src/api/organization-scope.js';
import { initClient } from '#src/helpers/client.js';
import { enableAllPasswordSignInMethods } from '#src/helpers/sign-in-experience.js';
import { generateNewUser } from '#src/helpers/user.js';

describe('consent api', () => {
const applications = new Map<string, Application>();
const thirdPartyApplicationName = 'consent-third-party-app';
const redirectUri = 'http://example.com';

const bootStrapApplication = async () => {
const thirdPartyApplication = await createApplication(
thirdPartyApplicationName,
ApplicationType.Traditional,
{
isThirdParty: true,
oidcClientMetadata: {
redirectUris: [redirectUri],
postLogoutRedirectUris: [],
},
}
);

applications.set(thirdPartyApplicationName, thirdPartyApplication);

await assignUserConsentScopes(thirdPartyApplication.id, {
userScopes: [UserScope.Profile],
});
};

beforeAll(async () => {
await Promise.all([enableAllPasswordSignInMethods(), bootStrapApplication()]);
});

it('get consent info', async () => {
const application = applications.get(thirdPartyApplicationName);
assert(application, new Error('application.not_found'));

const { userProfile, user } = await generateNewUser({ username: true, password: true });

const client = await initClient(
{
appId: application.id,
appSecret: application.secret,
},
redirectUri
);

await client.successSend(putInteraction, {
event: InteractionEvent.SignIn,
identifier: {
username: userProfile.username,
password: userProfile.password,
},
});

const { redirectTo } = await client.submitInteraction();

await client.processSession(redirectTo, false);

const result = await client.send(getConsentInfo);

expect(result.application.id).toBe(application.id);
expect(result.user.id).toBe(user.id);
expect(result.redirectUri).toBe(redirectUri);
expect(result.missingOIDCScope).toEqual([UserScope.Profile]);

await deleteUser(user.id);
});

it('get consent info with organization scope', async () => {
const application = applications.get(thirdPartyApplicationName);
assert(application, new Error('application.not_found'));

const organizationScopeApi = new OrganizationScopeApi();

const organizationScope = await organizationScopeApi.create({
name: 'organization-scope',
});

await assignUserConsentScopes(application.id, {
organizationScopes: [organizationScope.id],
userScopes: [UserScope.Organizations],
});

const { userProfile, user } = await generateNewUser({ username: true, password: true });

const client = await initClient(
{
appId: application.id,
appSecret: application.secret,
scopes: [UserScope.Organizations, UserScope.Profile, organizationScope.name],
},
redirectUri
);

await client.successSend(putInteraction, {
event: InteractionEvent.SignIn,
identifier: {
username: userProfile.username,
password: userProfile.password,
},
});

const { redirectTo } = await client.submitInteraction();

await client.processSession(redirectTo, false);

const result = await client.send(getConsentInfo);

expect(
result.missingResourceScopes?.find(
({ resource }) => resource.name === ReservedResource.Organization
)
).not.toBeUndefined();

await organizationScopeApi.delete(organizationScope.id);
await deleteUser(user.id);
});

afterAll(async () => {
for (const application of applications.values()) {
void deleteApplication(application.id);
}
});
});
9 changes: 8 additions & 1 deletion packages/schemas/src/types/consent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Resources,
Scopes,
ApplicationSignInExperiences,
OrganizationScopes,
} from '../db-entries/index.js';

/**
Expand Down Expand Up @@ -44,11 +45,17 @@ export const publicOrganizationGuard = Organizations.guard.pick({
id: true,
name: true,
});

export const missingResourceScopesGuard = z.object({
// The original resource id has a maximum length of 21 restriction. We need to make it compatible with the logto reserved organization name.
// use string here, as we do not care about the resource id length here.
resource: Resources.guard.pick({ name: true }).extend({ id: z.string() }),
scopes: Scopes.guard.pick({ id: true, name: true, description: true }).array(),
scopes: Scopes.guard
.pick({ id: true, name: true })
// The description is optional for organization scopes. Manually extend the schema to make it optional.
// TODO: make the resource scopes description optional at the schema level.
.merge(OrganizationScopes.guard.pick({ description: true }).partial())
.array(),
});

/**
Expand Down