Skip to content

Commit

Permalink
feat(core,schemas): add org resource scopes to consent get
Browse files Browse the repository at this point in the history
  • Loading branch information
wangsijie committed May 6, 2024
1 parent 5adf3df commit a7d6844
Show file tree
Hide file tree
Showing 6 changed files with 220 additions and 56 deletions.
13 changes: 8 additions & 5 deletions packages/core/src/libraries/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,15 +175,18 @@ export const createUserLibrary = (queries: Queries) => {
const findUserScopesForResourceIndicator = async (
userId: string,
resourceIndicator: string,
findFromOrganizations = false,
organizationId?: string
): Promise<readonly Scope[]> => {
const usersRoles = await findUsersRolesByUserId(userId);
const rolesScopes = await findRolesScopesByRoleIds(usersRoles.map(({ roleId }) => roleId));
const organizationScopes = await organizations.relations.rolesUsers.getUserResourceScopes(
userId,
resourceIndicator,
organizationId
);
const organizationScopes = findFromOrganizations
? await organizations.relations.rolesUsers.getUserResourceScopes(
userId,
resourceIndicator,
organizationId
)

Check warning on line 188 in packages/core/src/libraries/user.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/libraries/user.ts#L185-L188

Added lines #L185 - L188 were not covered by tests
: [];

const scopes = await findScopesByIdsAndResourceIndicator(
[...rolesScopes.map(({ scopeId }) => scopeId), ...organizationScopes.map(({ id }) => id)],
Expand Down
15 changes: 10 additions & 5 deletions packages/core/src/oidc/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ export default function initOidc(

const { accessTokenTtl: accessTokenTTL } = resourceServer;

const { client, params } = ctx.oidc;
const { client, params, session, entities } = ctx.oidc;
const userId = session?.accountId ?? entities.Account?.accountId;

Check warning on line 148 in packages/core/src/oidc/init.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/init.ts#L146-L148

Added lines #L146 - L148 were not covered by tests
/**
* In consent or code exchange flow, the organization_id is undefined,
* and all the scopes inherited from the all organization roles will be granted.
Expand All @@ -152,16 +154,19 @@ export default function initOidc(
* and will then narrow down the scopes to the specific organization.
*/
const organizationId = params?.organization_id;
const scopes = await findResourceScopes(
const scopes = await findResourceScopes({

Check warning on line 157 in packages/core/src/oidc/init.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/init.ts#L157

Added line #L157 was not covered by tests
queries,
libraries,
ctx,
indicator,
typeof organizationId === 'string' ? organizationId : undefined
);
findFromOrganizations: true,
organizationId: typeof organizationId === 'string' ? organizationId : undefined,
applicationId: client?.clientId,
userId,
});

Check warning on line 165 in packages/core/src/oidc/init.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/init.ts#L161-L165

Added lines #L161 - L165 were not covered by tests

// Need to filter out the unsupported scopes for the third-party application.
if (client && (await isThirdPartyApplication(queries, client.clientId))) {
// Get application consent resource scopes, from RBAC roles

Check warning on line 169 in packages/core/src/oidc/init.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/init.ts#L169

Added line #L169 was not covered by tests
const filteredScopes = await filterResourceScopesForTheThirdPartyApplication(
libraries,
client.clientId,
Expand Down
62 changes: 39 additions & 23 deletions packages/core/src/oidc/resource.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { ReservedResource } from '@logto/core-kit';
import { type Resource } from '@logto/schemas';
import { trySafe, type Nullable } from '@silverhand/essentials';
import { type ResourceServer, type KoaContextWithOIDC } from 'oidc-provider';
import { type ResourceServer } from 'oidc-provider';

import { type EnvSet } from '#src/env-set/index.js';
import { EnvSet } from '#src/env-set/index.js';
import type Libraries from '#src/tenants/Libraries.js';
import type Queries from '#src/tenants/Queries.js';

Expand All @@ -28,13 +28,23 @@ export const getSharedResourceServerData = (
*
* @see {@link ReservedResource} for the list of reserved resources.
*/
export const findResourceScopes = async (
queries: Queries,
libraries: Libraries,
ctx: KoaContextWithOIDC,
indicator: string,
organizationId?: string
): Promise<ReadonlyArray<{ name: string; id: string }>> => {
export const findResourceScopes = async ({
queries,
libraries,
userId,
applicationId,
indicator,
organizationId,
findFromOrganizations,
}: {
queries: Queries;
libraries: Libraries;
indicator: string;
findFromOrganizations: boolean;
userId?: string;
applicationId?: string;
organizationId?: string;
}): Promise<ReadonlyArray<{ name: string; id: string }>> => {

Check warning on line 47 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L32-L47

Added lines #L32 - L47 were not covered by tests
if (isReservedResource(indicator)) {
switch (indicator) {
case ReservedResource.Organization: {
Expand All @@ -44,21 +54,22 @@ export const findResourceScopes = async (
}
}

const { oidc } = ctx;
const {
users: { findUserScopesForResourceIndicator },
applications: { findApplicationScopesForResourceIndicator },
} = libraries;
const userId = oidc.session?.accountId ?? oidc.entities.Account?.accountId;

if (userId) {
return findUserScopesForResourceIndicator(userId, indicator, organizationId);
return findUserScopesForResourceIndicator(
userId,
indicator,
findFromOrganizations,
organizationId
);

Check warning on line 68 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L63-L68

Added lines #L63 - L68 were not covered by tests
}

const clientId = oidc.entities.Client?.clientId;

if (clientId) {
return findApplicationScopesForResourceIndicator(clientId, indicator);
if (applicationId) {
return findApplicationScopesForResourceIndicator(applicationId, indicator);

Check warning on line 72 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L71-L72

Added lines #L71 - L72 were not covered by tests
}

return [];
Expand Down Expand Up @@ -115,6 +126,7 @@ export const filterResourceScopesForTheThirdPartyApplication = async (
applications: {
getApplicationUserConsentOrganizationScopes,
getApplicationUserConsentResourceScopes,
getApplicationUserConsentOrganizationResourceScopes,

Check warning on line 129 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L129

Added line #L129 was not covered by tests
},
} = libraries;

Expand Down Expand Up @@ -146,16 +158,20 @@ export const filterResourceScopesForTheThirdPartyApplication = async (
const userConsentResource = userConsentResources.find(
({ resource }) => resource.indicator === indicator
);
const userConsentOrganizationResources = EnvSet.values.isDevFeaturesEnabled
? await getApplicationUserConsentOrganizationResourceScopes(applicationId)
: [];
const userConsentOrganizationResource = userConsentOrganizationResources.find(
({ resource }) => resource.indicator === indicator
);

Check warning on line 166 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L161-L166

Added lines #L161 - L166 were not covered by tests

// If the resource is not in the application enabled user consent resources, return empty array
if (!userConsentResource) {
return [];
}

const { scopes: userConsentResourceScopes } = userConsentResource;
const resourceScopes = [
...(userConsentResource?.scopes ?? []),
...(userConsentOrganizationResource?.scopes ?? []),
];

Check warning on line 171 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L168-L171

Added lines #L168 - L171 were not covered by tests

return scopes.filter(({ id: resourceScopeId }) =>
userConsentResourceScopes.some(
resourceScopes.some(

Check warning on line 174 in packages/core/src/oidc/resource.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/oidc/resource.ts#L174

Added line #L174 was not covered by tests
({ id: consentResourceScopeId }) => consentResourceScopeId === resourceScopeId
)
);
Expand Down
98 changes: 83 additions & 15 deletions packages/core/src/routes/interaction/consent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
publicApplicationGuard,
publicUserInfoGuard,
applicationSignInExperienceGuard,
publicOrganizationGuard,
missingResourceScopesGuard,
type ConsentInfoResponse,
type MissingResourceScopes,
Expand All @@ -16,8 +15,10 @@ import { type IRouterParamContext } from 'koa-router';
import { errors } from 'oidc-provider';
import { z } from 'zod';

import { EnvSet } from '#src/env-set/index.js';
import { consent, getMissingScopes } from '#src/libraries/session.js';
import koaGuard from '#src/middleware/koa-guard.js';
import { findResourceScopes } from '#src/oidc/resource.js';
import type Queries from '#src/tenants/Queries.js';
import type TenantContext from '#src/tenants/TenantContext.js';
import assertThat from '#src/utils/assert-that.js';
Expand Down Expand Up @@ -98,14 +99,12 @@ const parseMissingResourceScopesInfo = async (

export default function consentRoutes<T extends IRouterParamContext>(
router: Router<unknown, WithInteractionDetailsContext<T>>,
{
provider,
queries,
libraries: {
applications: { validateUserConsentOrganizationMembership },
},
}: TenantContext
{ provider, queries, libraries }: TenantContext
) {
const {
applications: { validateUserConsentOrganizationMembership },
users: { findUserScopesForResourceIndicator },
} = libraries;
const consentPath = `${interactionPrefix}/consent`;

router.post(
Expand Down Expand Up @@ -201,12 +200,84 @@ export default function consentRoutes<T extends IRouterParamContext>(

const userInfo = await queries.users.findUserById(accountId);

const { missingOIDCScope, missingResourceScopes } = getMissingScopes(prompt);
const { missingOIDCScope, missingResourceScopes: allMissingResourceScopes = {} } =
getMissingScopes(prompt);

// The missingResourceScopes from the prompt details are from `getResourceServerInfo`,
// which contains resource scopes and organization resource scopes.
// We need to separate the organization resource scopes from the resource scopes.
// The "scopes" in `missingResourceScopes` do not have "id", so we have to rebuild the scopes list.
const missingResourceScopes = await parseMissingResourceScopesInfo(
queries,
Object.fromEntries(
await Promise.all(
Object.entries(allMissingResourceScopes).map(
async ([resourceIndicator, missingScopes]): Promise<[string, string[]]> => {
if (!EnvSet.values.isDevFeaturesEnabled) {
return [resourceIndicator, missingScopes];
}

// Fetch the list of scopes, `findFromOrganizations` is set to false,
// so it will only search the user resource scopes.
const scopes = await findResourceScopes({
queries,
libraries,
indicator: resourceIndicator,
userId: accountId,
findFromOrganizations: false,
});

return [
resourceIndicator,
missingScopes.filter((scope) => scopes.some(({ name }) => name === scope)),
];
}
)
)
)
);

Check warning on line 238 in packages/core/src/routes/interaction/consent.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/interaction/consent.ts#L203-L238

Added lines #L203 - L238 were not covered by tests

// Find the organizations if the application is requesting the organizations scope
const organizations = missingOIDCScope?.includes(UserScope.Organizations)
? await queries.organizations.relations.users.getOrganizationsByUserId(accountId)
: undefined;
: [];

const organizationsWithMissingResourceScopes = await Promise.all(
organizations.map(async ({ name, id }) => {
if (!EnvSet.values.isDevFeaturesEnabled) {
return { name, id };
}

const missingResourceScopes = await parseMissingResourceScopesInfo(
queries,
Object.fromEntries(
await Promise.all(
Object.entries(allMissingResourceScopes).map(
async ([resourceIndicator, missingScopes]): Promise<[string, string[]]> => {
// Fetch the list of scopes, `organizationId` is set,
// so it will only search the specific organization to get orgniazation resource scopes.
const scopes = await findResourceScopes({
queries,
libraries,
indicator: resourceIndicator,
userId: accountId,
findFromOrganizations: true,
organizationId: id,
});

return [
resourceIndicator,
missingScopes.filter((scope) => scopes.some(({ name }) => name === scope)),

Check warning on line 270 in packages/core/src/routes/interaction/consent.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/core/src/routes/interaction/consent.ts#L270

[max-nested-callbacks] Too many nested callbacks (5). Maximum allowed is 4.
];
}
)
)
)
);

return { name, id, missingResourceScopes };
})
);

Check warning on line 280 in packages/core/src/routes/interaction/consent.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/interaction/consent.ts#L243-L280

Added lines #L243 - L280 were not covered by tests

ctx.body = {
// Merge the public application data and application sign-in-experience data
Expand All @@ -218,15 +289,12 @@ export default function consentRoutes<T extends IRouterParamContext>(
),
},
user: publicUserInfoGuard.parse(userInfo),
organizations: organizations?.map((organization) =>
publicOrganizationGuard.parse(organization)
),
organizations: organizationsWithMissingResourceScopes,

Check warning on line 292 in packages/core/src/routes/interaction/consent.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/interaction/consent.ts#L292

Added line #L292 was not covered by tests
// Filter out the OIDC scopes that are not needed for the consent page.
missingOIDCScope: missingOIDCScope?.filter(
(scope) => scope !== 'openid' && scope !== 'offline_access'
),
// Parse the missing resource scopes info with details.
missingResourceScopes: await parseMissingResourceScopesInfo(queries, missingResourceScopes),
missingResourceScopes: missingResourceScopes.filter(({ scopes }) => scopes.length > 0),

Check warning on line 297 in packages/core/src/routes/interaction/consent.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/interaction/consent.ts#L297

Added line #L297 was not covered by tests
redirectUri,
} satisfies ConsentInfoResponse;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,18 @@ import { assignUserConsentScopes } from '#src/api/application-user-consent-scope
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 { createResource, deleteResource } from '#src/api/resource.js';
import { createScope } from '#src/api/scope.js';
import { initClient } from '#src/helpers/client.js';
import { OrganizationApiTest, OrganizationRoleApiTest } from '#src/helpers/organization.js';
import { enableAllPasswordSignInMethods } from '#src/helpers/sign-in-experience.js';
import { generateNewUser } from '#src/helpers/user.js';
import {
generateResourceIndicator,
generateResourceName,
generateRoleName,
generateScopeName,
} from '#src/utils.js';

describe('consent api', () => {
const applications = new Map<string, Application>();
Expand Down Expand Up @@ -126,6 +135,63 @@ describe('consent api', () => {
await deleteUser(user.id);
});

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

const resource = await createResource(generateResourceName(), generateResourceIndicator());
const scope = await createScope(resource.id, generateScopeName());
const scope2 = await createScope(resource.id, generateScopeName());
const roleApi = new OrganizationRoleApiTest();
const role = await roleApi.create({
name: generateRoleName(),
resourceScopeIds: [scope.id],
});
const organizationApi = new OrganizationApiTest();
const organization = await organizationApi.create({ name: 'test_org' });
const { userProfile, user } = await generateNewUser({ username: true, password: true });
await organizationApi.addUsers(organization.id, [user.id]);
await organizationApi.addUserRoles(organization.id, user.id, [role.id]);

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

const client = await initClient(
{
appId: application.id,
appSecret: application.secret,
scopes: [UserScope.Organizations, UserScope.Profile, scope.name, scope2.name],
resources: [resource.indicator],
},
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).toHaveLength(0);
// Only scope1, scope2 is removed
expect(result.organizations?.[0]?.missingResourceScopes).toHaveLength(1);

await roleApi.cleanUp();
await organizationApi.cleanUp();
await deleteResource(resource.id);
await deleteUser(user.id);
});

afterAll(async () => {
for (const application of applications.values()) {
void deleteApplication(application.id);
Expand Down
Loading

0 comments on commit a7d6844

Please sign in to comment.