From 6e546ce6c7bcc6d711b41ab177ba40ed185401ee Mon Sep 17 00:00:00 2001 From: James Gregory Date: Wed, 16 Feb 2022 18:45:47 +1100 Subject: [PATCH] feat(api): support for ListUserPoolClients --- README.md | 4 +- .../aws-sdk/createUserPool.test.ts | 3 - .../aws-sdk/createUserPoolClient.test.ts | 2 - .../aws-sdk/listUserPoolClients.test.ts | 33 +++++++ src/__tests__/mockCognitoService.ts | 1 + src/__tests__/mockUserPoolService.ts | 2 +- src/__tests__/testDataBuilder.ts | 27 ++++++ src/services/appClient.ts | 88 +++++++++++++++++- src/services/cognitoService.ts | 18 ++++ src/services/userPoolService.test.ts | 18 ++-- src/services/userPoolService.ts | 44 ++++----- src/targets/adminCreateUser.ts | 13 +-- src/targets/adminGetUser.ts | 2 +- src/targets/adminListGroupsForUser.ts | 11 +-- src/targets/createGroup.ts | 11 +-- src/targets/createUserPool.ts | 3 +- src/targets/createUserPoolClient.test.ts | 33 +++---- src/targets/createUserPoolClient.ts | 44 +++++++-- src/targets/describeUserPoolClient.ts | 7 +- src/targets/getGroup.ts | 11 +-- src/targets/getUser.ts | 13 +-- src/targets/listGroups.ts | 11 +-- src/targets/listUserPoolClients.test.ts | 38 ++++++++ src/targets/listUserPoolClients.ts | 27 ++++++ src/targets/listUserPools.ts | 6 +- src/targets/listUsers.ts | 10 +- src/targets/listUsersInGroup.ts | 11 +-- src/targets/responses.ts | 92 +++++++++++++++++++ src/targets/targets.ts | 2 + src/targets/updateGroup.ts | 11 +-- 30 files changed, 440 insertions(+), 156 deletions(-) create mode 100644 integration-tests/aws-sdk/listUserPoolClients.test.ts create mode 100644 src/targets/listUserPoolClients.test.ts create mode 100644 src/targets/listUserPoolClients.ts create mode 100644 src/targets/responses.ts diff --git a/README.md b/README.md index 328829cc..07afdfdb 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ A _Good Enough_ offline emulator for [Amazon Cognito](https://aws.amazon.com/cog | CreateResourceServer | โŒ | | CreateUserImportJob | โŒ | | CreateUserPool | โœ… | -| CreateUserPoolClient | ๐Ÿ•’ (partial support) | +| CreateUserPoolClient | โœ… | | CreateUserPoolDomain | โŒ | | DeleteGroup | โœ… | | DeleteIdentityProvider | โŒ | @@ -102,7 +102,7 @@ A _Good Enough_ offline emulator for [Amazon Cognito](https://aws.amazon.com/cog | ListResourceServers | โŒ | | ListTagsForResource | โŒ | | ListUserImportJobs | โŒ | -| ListUserPoolClients | โŒ | +| ListUserPoolClients | โœ…ยน | | ListUserPools | โœ…ยน | | ListUsers | โœ…ยน | | ListUsersInGroup | โœ…ยน | diff --git a/integration-tests/aws-sdk/createUserPool.test.ts b/integration-tests/aws-sdk/createUserPool.test.ts index 20f45cc5..10460454 100644 --- a/integration-tests/aws-sdk/createUserPool.test.ts +++ b/integration-tests/aws-sdk/createUserPool.test.ts @@ -1,6 +1,4 @@ -import Pino from "pino"; import { ClockFake } from "../../src/__tests__/clockFake"; -import { UUID } from "../../src/__tests__/patterns"; import { USER_POOL_AWS_DEFAULTS } from "../../src/services/cognitoService"; import { withCognitoSdk } from "./setup"; @@ -39,7 +37,6 @@ describe( }, { clock, - logger: Pino(), } ) ); diff --git a/integration-tests/aws-sdk/createUserPoolClient.test.ts b/integration-tests/aws-sdk/createUserPoolClient.test.ts index b809f4c3..fa7d2e9b 100644 --- a/integration-tests/aws-sdk/createUserPoolClient.test.ts +++ b/integration-tests/aws-sdk/createUserPoolClient.test.ts @@ -15,12 +15,10 @@ describe( expect(result).toEqual({ UserPoolClient: { - AllowedOAuthFlowsUserPoolClient: false, ClientId: expect.stringMatching(/^[a-z0-9]{25}$/), ClientName: "test", CreationDate: expect.any(Date), LastModifiedDate: expect.any(Date), - RefreshTokenValidity: 30, UserPoolId: "test", }, }); diff --git a/integration-tests/aws-sdk/listUserPoolClients.test.ts b/integration-tests/aws-sdk/listUserPoolClients.test.ts new file mode 100644 index 00000000..87371aaf --- /dev/null +++ b/integration-tests/aws-sdk/listUserPoolClients.test.ts @@ -0,0 +1,33 @@ +import { withCognitoSdk } from "./setup"; + +describe( + "CognitoIdentityServiceProvider.listUserPoolClients", + withCognitoSdk((Cognito) => { + it("can list app clients", async () => { + const client = Cognito(); + + const result = await client + .createUserPoolClient({ + ClientName: "test", + UserPoolId: "test", + }) + .promise(); + + const clientList = await client + .listUserPoolClients({ + UserPoolId: "test", + }) + .promise(); + + expect(clientList).toEqual({ + UserPoolClients: [ + { + ClientId: result.UserPoolClient?.ClientId, + ClientName: result.UserPoolClient?.ClientName, + UserPoolId: "test", + }, + ], + }); + }); + }) +); diff --git a/src/__tests__/mockCognitoService.ts b/src/__tests__/mockCognitoService.ts index 4be0b84c..8be95fa2 100644 --- a/src/__tests__/mockCognitoService.ts +++ b/src/__tests__/mockCognitoService.ts @@ -9,6 +9,7 @@ export const newMockCognitoService = ( getAppClient: jest.fn(), getUserPool: jest.fn().mockResolvedValue(userPoolClient), getUserPoolForClientId: jest.fn().mockResolvedValue(userPoolClient), + listAppClients: jest.fn(), listUserPools: jest.fn(), }); diff --git a/src/__tests__/mockUserPoolService.ts b/src/__tests__/mockUserPoolService.ts index c84dbe04..b27d02d1 100644 --- a/src/__tests__/mockUserPoolService.ts +++ b/src/__tests__/mockUserPoolService.ts @@ -7,7 +7,6 @@ export const newMockUserPoolService = ( } ): jest.Mocked => ({ config, - createAppClient: jest.fn(), deleteGroup: jest.fn(), deleteUser: jest.fn(), getGroupByGroupName: jest.fn(), @@ -16,6 +15,7 @@ export const newMockUserPoolService = ( listGroups: jest.fn(), listUsers: jest.fn(), removeUserFromGroup: jest.fn(), + saveAppClient: jest.fn(), saveGroup: jest.fn(), saveUser: jest.fn(), storeRefreshToken: jest.fn(), diff --git a/src/__tests__/testDataBuilder.ts b/src/__tests__/testDataBuilder.ts index 9dd50f5a..0481d78c 100644 --- a/src/__tests__/testDataBuilder.ts +++ b/src/__tests__/testDataBuilder.ts @@ -1,9 +1,36 @@ import { v4 } from "uuid"; +import { AppClient } from "../services/appClient"; import { Group, User, UserPool } from "../services/userPoolService"; export const id = (prefix: string, number?: number) => `${prefix}${number ?? Math.floor(Math.random() * 100000)}`; +export const appClient = (partial?: Partial): AppClient => ({ + AccessTokenValidity: partial?.AccessTokenValidity, + AllowedOAuthFlows: partial?.AllowedOAuthFlows, + AllowedOAuthFlowsUserPoolClient: partial?.AllowedOAuthFlowsUserPoolClient, + AllowedOAuthScopes: partial?.AllowedOAuthScopes, + AnalyticsConfiguration: partial?.AnalyticsConfiguration, + CallbackURLs: partial?.CallbackURLs, + ClientId: partial?.ClientId ?? id("AppClient"), + ClientName: partial?.ClientName ?? id("ClientName"), + ClientSecret: partial?.ClientSecret ?? undefined, + CreationDate: partial?.CreationDate ?? new Date(), + DefaultRedirectURI: partial?.DefaultRedirectURI, + EnableTokenRevocation: partial?.EnableTokenRevocation, + ExplicitAuthFlows: partial?.ExplicitAuthFlows, + IdTokenValidity: partial?.IdTokenValidity, + LastModifiedDate: partial?.LastModifiedDate ?? new Date(), + LogoutURLs: partial?.LogoutURLs, + PreventUserExistenceErrors: partial?.PreventUserExistenceErrors, + ReadAttributes: partial?.ReadAttributes, + RefreshTokenValidity: partial?.RefreshTokenValidity, + SupportedIdentityProviders: partial?.SupportedIdentityProviders, + TokenValidityUnits: partial?.TokenValidityUnits, + UserPoolId: partial?.UserPoolId ?? id("UserPool"), + WriteAttributes: partial?.WriteAttributes, +}); + export const group = (partial?: Partial): Group => ({ CreationDate: partial?.CreationDate ?? new Date(), Description: partial?.Description ?? undefined, diff --git a/src/services/appClient.ts b/src/services/appClient.ts index 2dbb4232..a9503da2 100644 --- a/src/services/appClient.ts +++ b/src/services/appClient.ts @@ -1,13 +1,97 @@ +import { + AnalyticsConfigurationType, + ExplicitAuthFlowsListType, + OAuthFlowsType, + PreventUserExistenceErrorTypes, + TokenValidityUnitsType, +} from "aws-sdk/clients/cognitoidentityserviceprovider"; import shortUUID from "short-uuid"; export interface AppClient { UserPoolId: string; ClientName: string; ClientId: string; + + /** + * The client secret from the user pool request of the client type. + */ + ClientSecret?: string; + /** + * The date the user pool client was last modified. + */ LastModifiedDate: Date; + /** + * The date the user pool client was created. + */ CreationDate: Date; - RefreshTokenValidity: number; - AllowedOAuthFlowsUserPoolClient: boolean; + /** + * The time limit, in days, after which the refresh token is no longer valid and cannot be used. + */ + RefreshTokenValidity?: number; + /** + * The time limit, specified by tokenValidityUnits, defaulting to hours, after which the access token is no longer valid and cannot be used. + */ + AccessTokenValidity?: number; + /** + * The time limit, specified by tokenValidityUnits, defaulting to hours, after which the refresh token is no longer valid and cannot be used. + */ + IdTokenValidity?: number; + /** + * The time units used to specify the token validity times of their respective token. + */ + TokenValidityUnits?: TokenValidityUnitsType; + /** + * The Read-only attributes. + */ + ReadAttributes?: string[]; + /** + * The writeable attributes. + */ + WriteAttributes?: string[]; + /** + * The authentication flows that are supported by the user pool clients. Flow names without the ALLOW_ prefix are deprecated in favor of new names with the ALLOW_ prefix. Note that values with ALLOW_ prefix cannot be used along with values without ALLOW_ prefix. Valid values include: ALLOW_ADMIN_USER_PASSWORD_AUTH: Enable admin based user password authentication flow ADMIN_USER_PASSWORD_AUTH. This setting replaces the ADMIN_NO_SRP_AUTH setting. With this authentication flow, Cognito receives the password in the request instead of using the SRP (Secure Remote Password protocol) protocol to verify passwords. ALLOW_CUSTOM_AUTH: Enable Lambda trigger based authentication. ALLOW_USER_PASSWORD_AUTH: Enable user password-based authentication. In this flow, Cognito receives the password in the request instead of using the SRP protocol to verify passwords. ALLOW_USER_SRP_AUTH: Enable SRP based authentication. ALLOW_REFRESH_TOKEN_AUTH: Enable authflow to refresh tokens. + */ + ExplicitAuthFlows?: ExplicitAuthFlowsListType; + /** + * A list of provider names for the identity providers that are supported on this client. + */ + SupportedIdentityProviders?: string[]; + /** + * A list of allowed redirect (callback) URLs for the identity providers. A redirect URI must: Be an absolute URI. Be registered with the authorization server. Not include a fragment component. See OAuth 2.0 - Redirection Endpoint. Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing purposes only. App callback URLs such as myapp://example are also supported. + */ + CallbackURLs?: string[]; + /** + * A list of allowed logout URLs for the identity providers. + */ + LogoutURLs?: string[]; + /** + * The default redirect URI. Must be in the CallbackURLs list. A redirect URI must: Be an absolute URI. Be registered with the authorization server. Not include a fragment component. See OAuth 2.0 - Redirection Endpoint. Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing purposes only. App callback URLs such as myapp://example are also supported. + */ + DefaultRedirectURI?: string; + /** + * The allowed OAuth flows. Set to code to initiate a code grant flow, which provides an authorization code as the response. This code can be exchanged for access tokens with the token endpoint. Set to implicit to specify that the client should get the access token (and, optionally, ID token, based on scopes) directly. Set to client_credentials to specify that the client should get the access token (and, optionally, ID token, based on scopes) from the token endpoint using a combination of client and client_secret. + */ + AllowedOAuthFlows?: OAuthFlowsType; + /** + * The allowed OAuth scopes. Possible values provided by OAuth are: phone, email, openid, and profile. Possible values provided by Amazon Web Services are: aws.cognito.signin.user.admin. Custom scopes created in Resource Servers are also supported. + */ + AllowedOAuthScopes?: string[]; + /** + * Set to true if the client is allowed to follow the OAuth protocol when interacting with Cognito user pools. + */ + AllowedOAuthFlowsUserPoolClient?: boolean; + /** + * The Amazon Pinpoint analytics configuration for the user pool client. Cognito User Pools only supports sending events to Amazon Pinpoint projects in the US East (N. Virginia) us-east-1 Region, regardless of the region in which the user pool resides. + */ + AnalyticsConfiguration?: AnalyticsConfigurationType; + /** + * Use this setting to choose which errors and responses are returned by Cognito APIs during authentication, account confirmation, and password recovery when the user does not exist in the user pool. When set to ENABLED and the user does not exist, authentication returns an error indicating either the username or password was incorrect, and account confirmation and password recovery return a response indicating a code was sent to a simulated destination. When set to LEGACY, those APIs will return a UserNotFoundException exception if the user does not exist in the user pool. Valid values include: ENABLED - This prevents user existence-related errors. LEGACY - This represents the old behavior of Cognito where user existence related errors are not prevented. After February 15th 2020, the value of PreventUserExistenceErrors will default to ENABLED for newly created user pool clients if no value is provided. + */ + PreventUserExistenceErrors?: PreventUserExistenceErrorTypes; + /** + * Indicates whether token revocation is enabled for the user pool client. When you create a new user pool client, token revocation is enabled by default. For more information about revoking tokens, see RevokeToken. + */ + EnableTokenRevocation?: boolean; } const generator = shortUUID("0123456789abcdefghijklmnopqrstuvwxyz"); diff --git a/src/services/cognitoService.ts b/src/services/cognitoService.ts index 8b883ab0..e9fa8804 100644 --- a/src/services/cognitoService.ts +++ b/src/services/cognitoService.ts @@ -271,6 +271,10 @@ export interface CognitoService { ctx: Context, clientId: string ): Promise; + listAppClients( + ctx: Context, + userPoolId: string + ): Promise; listUserPools(ctx: Context): Promise; } @@ -358,6 +362,20 @@ export class CognitoServiceImpl implements CognitoService { return this.clients.get(ctx, ["Clients", clientId]); } + public async listAppClients( + ctx: Context, + userPoolId: string + ): Promise { + ctx.logger.debug({ userPoolId }, "CognitoServiceImpl.listAppClients"); + const clients = await this.clients.get>( + ctx, + "Clients", + {} + ); + + return Object.values(clients).filter((x) => x.UserPoolId === userPoolId); + } + public async listUserPools(ctx: Context): Promise { ctx.logger.debug("CognitoServiceImpl.listUserPools"); const entries = await readdir(this.dataDirectory, { withFileTypes: true }); diff --git a/src/services/userPoolService.test.ts b/src/services/userPoolService.test.ts index 54356d80..854a557d 100644 --- a/src/services/userPoolService.test.ts +++ b/src/services/userPoolService.test.ts @@ -5,6 +5,7 @@ import { newMockDataStoreFactory, } from "../__tests__/mockDataStore"; import { TestContext } from "../__tests__/testContext"; +import { AppClient } from "./appClient"; import { DataStore } from "./dataStore/dataStore"; import { attributesFromRecord, @@ -57,7 +58,7 @@ describe("User Pool Service", () => { mockClientsDataStore = newMockDataStore(); }); - describe("createAppClient", () => { + describe("saveAppClient", () => { it("saves an app client", async () => { const ds = newMockDataStore(); ds.get.mockImplementation((ctx, key, defaults) => @@ -74,22 +75,21 @@ describe("User Pool Service", () => { } ); - const result = await userPool.createAppClient(TestContext, "clientName"); - - expect(result).toEqual({ - AllowedOAuthFlowsUserPoolClient: false, - ClientId: expect.stringMatching(/^[a-z0-9]{25}$/), + const appClient: AppClient = { + ClientId: "clientId", ClientName: "clientName", CreationDate: currentDate, LastModifiedDate: currentDate, RefreshTokenValidity: 30, UserPoolId: "local", - }); + }; + + await userPool.saveAppClient(TestContext, appClient); expect(mockClientsDataStore.set).toHaveBeenCalledWith( TestContext, - ["Clients", result.ClientId], - result + ["Clients", "clientId"], + appClient ); }); }); diff --git a/src/services/userPoolService.ts b/src/services/userPoolService.ts index 9e456ad8..f2f623d5 100644 --- a/src/services/userPoolService.ts +++ b/src/services/userPoolService.ts @@ -3,11 +3,13 @@ import { AttributeType, MFAOptionListType, SchemaAttributesListType, + StringType, + UserMFASettingListType, UserPoolType, UserStatusType, } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { InvalidParameterError } from "../errors"; -import { AppClient, newId } from "./appClient"; +import { AppClient } from "./appClient"; import { Clock } from "./clock"; import { Context } from "./context"; import { DataStore } from "./dataStore/dataStore"; @@ -78,13 +80,15 @@ export const customAttributes = ( (attributes ?? []).filter((attr) => attr.Name.startsWith("custom:")); export interface User { - Username: string; + Attributes: AttributeListType; + Enabled: boolean; + MFAOptions?: MFAOptionListType; + PreferredMfaSetting?: StringType; UserCreateDate: Date; UserLastModifiedDate: Date; - Enabled: boolean; + UserMFASettingList?: UserMFASettingListType; + Username: string; UserStatus: UserStatusType; - Attributes: AttributeListType; - MFAOptions?: MFAOptionListType; // extra attributes for Cognito Local Password: string; @@ -134,7 +138,7 @@ export type UserPool = UserPoolType & { export interface UserPoolService { readonly config: UserPool; - createAppClient(ctx: Context, name: string): Promise; + saveAppClient(ctx: Context, appClient: AppClient): Promise; deleteGroup(ctx: Context, group: Group): Promise; deleteUser(ctx: Context, user: User): Promise; getGroupByGroupName(ctx: Context, groupName: string): Promise; @@ -182,24 +186,16 @@ export class UserPoolServiceImpl implements UserPoolService { this.dataStore = dataStore; } - public async createAppClient(ctx: Context, name: string): Promise { - ctx.logger.debug({ name }, "UserPoolServiceImpl.createAppClient"); - const id = newId(); - const now = this.clock.get(); - - const appClient: AppClient = { - ClientId: id, - ClientName: name, - UserPoolId: this.config.Id, - CreationDate: now, - LastModifiedDate: now, - AllowedOAuthFlowsUserPoolClient: false, - RefreshTokenValidity: 30, - }; - - await this.clientsDataStore.set(ctx, ["Clients", id], appClient); - - return appClient; + public async saveAppClient( + ctx: Context, + appClient: AppClient + ): Promise { + ctx.logger.debug("UserPoolServiceImpl.saveAppClient"); + await this.clientsDataStore.set( + ctx, + ["Clients", appClient.ClientId], + appClient + ); } public async deleteGroup(ctx: Context, group: Group): Promise { diff --git a/src/targets/adminCreateUser.ts b/src/targets/adminCreateUser.ts index 0cac92ad..5ac6105b 100644 --- a/src/targets/adminCreateUser.ts +++ b/src/targets/adminCreateUser.ts @@ -11,13 +11,14 @@ import { UsernameExistsError, } from "../errors"; import { Messages, Services, UserPoolService } from "../services"; +import { Context } from "../services/context"; import { DeliveryDetails } from "../services/messageDelivery/messageDelivery"; import { attributesInclude, attributeValue, User, } from "../services/userPoolService"; -import { Context } from "../services/context"; +import { userToResponseObject } from "./responses"; import { Target } from "./Target"; const generator = shortUUID( @@ -145,14 +146,6 @@ export const AdminCreateUser = ); return { - User: { - Username: req.Username, - Attributes: attributes, - Enabled: true, - UserStatus: "FORCE_CHANGE_PASSWORD", - UserCreateDate: now, - UserLastModifiedDate: now, - MFAOptions: undefined, - }, + User: userToResponseObject(user), }; }; diff --git a/src/targets/adminGetUser.ts b/src/targets/adminGetUser.ts index 90c22ed6..8abefcea 100644 --- a/src/targets/adminGetUser.ts +++ b/src/targets/adminGetUser.ts @@ -2,8 +2,8 @@ import { AdminGetUserRequest, AdminGetUserResponse, } from "aws-sdk/clients/cognitoidentityserviceprovider"; -import { Services } from "../services"; import { UserNotFoundError } from "../errors"; +import { Services } from "../services"; import { Target } from "./Target"; export type AdminGetUserTarget = Target< diff --git a/src/targets/adminListGroupsForUser.ts b/src/targets/adminListGroupsForUser.ts index db06eafd..e833e686 100644 --- a/src/targets/adminListGroupsForUser.ts +++ b/src/targets/adminListGroupsForUser.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { UserNotFoundError } from "../errors"; import { Services } from "../services"; +import { groupToResponseObject } from "./responses"; import { Target } from "./Target"; export type AdminListGroupsForUserTarget = Target< @@ -26,14 +27,6 @@ export const AdminListGroupsForUser = const usersGroups = groups.filter((x) => x.members?.includes(req.Username)); return { - Groups: usersGroups.map((x) => ({ - CreationDate: x.CreationDate, - Description: x.Description, - GroupName: x.GroupName, - LastModifiedDate: x.LastModifiedDate, - Precedence: x.Precedence, - RoleArn: x.RoleArn, - UserPoolId: req.UserPoolId, - })), + Groups: usersGroups.map(groupToResponseObject(req.UserPoolId)), }; }; diff --git a/src/targets/createGroup.ts b/src/targets/createGroup.ts index 2c1acf4c..2bd8c605 100644 --- a/src/targets/createGroup.ts +++ b/src/targets/createGroup.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; import { Group } from "../services/userPoolService"; +import { groupToResponseObject } from "./responses"; import { Target } from "./Target"; export type CreateGroupTarget = Target; @@ -28,14 +29,6 @@ export const CreateGroup = await userPool.saveGroup(ctx, group); return { - Group: { - CreationDate: group.CreationDate, - Description: group.Description, - GroupName: group.GroupName, - LastModifiedDate: group.LastModifiedDate, - Precedence: group.Precedence, - RoleArn: group.RoleArn, - UserPoolId: req.UserPoolId, - }, + Group: groupToResponseObject(req.UserPoolId)(group), }; }; diff --git a/src/targets/createUserPool.ts b/src/targets/createUserPool.ts index 9d936345..f774a427 100644 --- a/src/targets/createUserPool.ts +++ b/src/targets/createUserPool.ts @@ -6,6 +6,7 @@ import { import shortUUID from "short-uuid"; import { Services } from "../services"; import { USER_POOL_AWS_DEFAULTS } from "../services/cognitoService"; +import { userPoolToResponseObject } from "./responses"; import { Target } from "./Target"; const REGION = "local"; @@ -107,6 +108,6 @@ export const CreateUserPool = }); return { - UserPool: userPool, + UserPool: userPoolToResponseObject(userPool), }; }; diff --git a/src/targets/createUserPoolClient.test.ts b/src/targets/createUserPoolClient.test.ts index 7cc5794c..a6b3dcc2 100644 --- a/src/targets/createUserPoolClient.test.ts +++ b/src/targets/createUserPoolClient.test.ts @@ -1,3 +1,4 @@ +import { ClockFake } from "../__tests__/clockFake"; import { newMockCognitoService } from "../__tests__/mockCognitoService"; import { newMockUserPoolService } from "../__tests__/mockUserPoolService"; import { TestContext } from "../__tests__/testContext"; @@ -8,6 +9,8 @@ import { CreateUserPoolClientTarget, } from "./createUserPoolClient"; +const originalDate = new Date(); + describe("CreateUserPoolClient target", () => { let createUserPoolClient: CreateUserPoolClientTarget; let mockUserPoolService: jest.Mocked; @@ -15,37 +18,35 @@ describe("CreateUserPoolClient target", () => { beforeEach(() => { mockUserPoolService = newMockUserPoolService(); createUserPoolClient = CreateUserPoolClient({ + clock: new ClockFake(originalDate), cognito: newMockCognitoService(mockUserPoolService), }); }); it("creates a new app client", async () => { - const createdAppClient: AppClient = { - RefreshTokenValidity: 30, - AllowedOAuthFlowsUserPoolClient: false, - LastModifiedDate: new Date(), - CreationDate: new Date(), - UserPoolId: "userPoolId", - ClientId: "abc", - ClientName: "clientName", - }; - mockUserPoolService.createAppClient.mockResolvedValue(createdAppClient); - const result = await createUserPoolClient(TestContext, { ClientName: "clientName", UserPoolId: "userPoolId", }); - expect(mockUserPoolService.createAppClient).toHaveBeenCalledWith( + expect(mockUserPoolService.saveAppClient).toHaveBeenCalledWith( TestContext, - "clientName" + { + ClientId: expect.any(String), + ClientName: "clientName", + CreationDate: originalDate, + LastModifiedDate: originalDate, + UserPoolId: "userPoolId", + } ); expect(result).toEqual({ UserPoolClient: { - ...createdAppClient, - LastModifiedDate: new Date(createdAppClient.LastModifiedDate), - CreationDate: new Date(createdAppClient.CreationDate), + ClientId: expect.any(String), + ClientName: "clientName", + CreationDate: originalDate, + LastModifiedDate: originalDate, + UserPoolId: "userPoolId", }, }); }); diff --git a/src/targets/createUserPoolClient.ts b/src/targets/createUserPoolClient.ts index 3702ecf1..bb1a8f4f 100644 --- a/src/targets/createUserPoolClient.ts +++ b/src/targets/createUserPoolClient.ts @@ -3,6 +3,8 @@ import { CreateUserPoolClientResponse, } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; +import { AppClient, newId } from "../services/appClient"; +import { appClientToResponseObject } from "./responses"; import { Target } from "./Target"; export type CreateUserPoolClientTarget = Target< @@ -10,17 +12,45 @@ export type CreateUserPoolClientTarget = Target< CreateUserPoolClientResponse >; +type CreateUserPoolClientServices = Pick; + export const CreateUserPoolClient = - ({ cognito }: Pick): CreateUserPoolClientTarget => + ({ + clock, + cognito, + }: CreateUserPoolClientServices): CreateUserPoolClientTarget => async (ctx, req) => { const userPool = await cognito.getUserPool(ctx, req.UserPoolId); - const appClient = await userPool.createAppClient(ctx, req.ClientName); + + const appClient: AppClient = { + AccessTokenValidity: req.AccessTokenValidity, + AllowedOAuthFlows: req.AllowedOAuthFlows, + AllowedOAuthFlowsUserPoolClient: req.AllowedOAuthFlowsUserPoolClient, + AllowedOAuthScopes: req.AllowedOAuthScopes, + AnalyticsConfiguration: req.AnalyticsConfiguration, + CallbackURLs: req.CallbackURLs, + ClientId: newId(), + ClientName: req.ClientName, + ClientSecret: req.GenerateSecret ? newId() : undefined, + CreationDate: clock.get(), + DefaultRedirectURI: req.DefaultRedirectURI, + EnableTokenRevocation: req.EnableTokenRevocation, + ExplicitAuthFlows: req.ExplicitAuthFlows, + IdTokenValidity: req.IdTokenValidity, + LastModifiedDate: clock.get(), + LogoutURLs: req.LogoutURLs, + PreventUserExistenceErrors: req.PreventUserExistenceErrors, + ReadAttributes: req.ReadAttributes, + RefreshTokenValidity: req.RefreshTokenValidity, + SupportedIdentityProviders: req.SupportedIdentityProviders, + TokenValidityUnits: req.TokenValidityUnits, + UserPoolId: req.UserPoolId, + WriteAttributes: req.WriteAttributes, + }; + + await userPool.saveAppClient(ctx, appClient); return { - UserPoolClient: { - ...appClient, - CreationDate: appClient.CreationDate, - LastModifiedDate: appClient.LastModifiedDate, - }, + UserPoolClient: appClientToResponseObject(appClient), }; }; diff --git a/src/targets/describeUserPoolClient.ts b/src/targets/describeUserPoolClient.ts index 9cb51663..3b8def75 100644 --- a/src/targets/describeUserPoolClient.ts +++ b/src/targets/describeUserPoolClient.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { ResourceNotFoundError } from "../errors"; import { Services } from "../services"; +import { appClientToResponseObject } from "./responses"; import { Target } from "./Target"; export type DescribeUserPoolClientTarget = Target< @@ -20,10 +21,6 @@ export const DescribeUserPoolClient = } return { - UserPoolClient: { - ...client, - CreationDate: client.CreationDate, - LastModifiedDate: client.LastModifiedDate, - }, + UserPoolClient: appClientToResponseObject(client), }; }; diff --git a/src/targets/getGroup.ts b/src/targets/getGroup.ts index 5742b4a9..786ab7b1 100644 --- a/src/targets/getGroup.ts +++ b/src/targets/getGroup.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { GroupNotFoundError } from "../errors"; import { Services } from "../services"; +import { groupToResponseObject } from "./responses"; import { Target } from "./Target"; export type GetGroupTarget = Target; @@ -18,14 +19,6 @@ export const GetGroup = } return { - Group: { - CreationDate: group.CreationDate, - Description: group.Description, - GroupName: group.GroupName, - LastModifiedDate: group.LastModifiedDate, - Precedence: group.Precedence, - RoleArn: group.RoleArn, - UserPoolId: req.UserPoolId, - }, + Group: groupToResponseObject(req.UserPoolId)(group), }; }; diff --git a/src/targets/getUser.ts b/src/targets/getUser.ts index 43cb56f3..31e2027f 100644 --- a/src/targets/getUser.ts +++ b/src/targets/getUser.ts @@ -28,14 +28,11 @@ export const GetUser = throw new UserNotFoundError(); } - const output: GetUserResponse = { - Username: user.Username, + return { + MFAOptions: user.MFAOptions, + PreferredMfaSetting: user.PreferredMfaSetting, UserAttributes: user.Attributes, + UserMFASettingList: user.UserMFASettingList, + Username: user.Username, }; - - if (user.MFAOptions) { - output.MFAOptions = user.MFAOptions; - } - - return output; }; diff --git a/src/targets/listGroups.ts b/src/targets/listGroups.ts index b33b68a8..545ab377 100644 --- a/src/targets/listGroups.ts +++ b/src/targets/listGroups.ts @@ -3,6 +3,7 @@ import { ListGroupsResponse, } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; +import { groupToResponseObject } from "./responses"; import { Target } from "./Target"; export type ListGroupsTarget = Target; @@ -19,14 +20,6 @@ export const ListGroups = const groups = await userPool.listGroups(ctx); return { - Groups: groups.map((group) => ({ - CreationDate: group.CreationDate, - Description: group.Description, - GroupName: group.GroupName, - LastModifiedDate: group.LastModifiedDate, - Precedence: group.Precedence, - RoleArn: group.RoleArn, - UserPoolId: req.UserPoolId, - })), + Groups: groups.map(groupToResponseObject(req.UserPoolId)), }; }; diff --git a/src/targets/listUserPoolClients.test.ts b/src/targets/listUserPoolClients.test.ts new file mode 100644 index 00000000..6fcb8482 --- /dev/null +++ b/src/targets/listUserPoolClients.test.ts @@ -0,0 +1,38 @@ +import { newMockCognitoService } from "../__tests__/mockCognitoService"; +import { newMockUserPoolService } from "../__tests__/mockUserPoolService"; +import { TestContext } from "../__tests__/testContext"; +import * as TDB from "../__tests__/testDataBuilder"; +import { CognitoService } from "../services"; +import { + ListUserPoolClients, + ListUserPoolClientsTarget, +} from "./listUserPoolClients"; + +describe("ListUserPoolClients target", () => { + let mockCognitoService: jest.Mocked; + let listUserPoolClients: ListUserPoolClientsTarget; + + beforeEach(() => { + mockCognitoService = newMockCognitoService(newMockUserPoolService()); + listUserPoolClients = ListUserPoolClients({ + cognito: mockCognitoService, + }); + }); + + it("lists user pool clients", async () => { + const appClient1 = TDB.appClient(); + const appClient2 = TDB.appClient(); + + mockCognitoService.listAppClients.mockResolvedValue([ + appClient1, + appClient2, + ]); + + const output = await listUserPoolClients(TestContext, { + UserPoolId: "userPoolId", + }); + + expect(output).toBeDefined(); + expect(output.UserPoolClients).toEqual([appClient1, appClient2]); + }); +}); diff --git a/src/targets/listUserPoolClients.ts b/src/targets/listUserPoolClients.ts new file mode 100644 index 00000000..f4ad5437 --- /dev/null +++ b/src/targets/listUserPoolClients.ts @@ -0,0 +1,27 @@ +import { + ListUserPoolClientsRequest, + ListUserPoolClientsResponse, +} from "aws-sdk/clients/cognitoidentityserviceprovider"; +import { Services } from "../services"; +import { appClientToResponseObject } from "./responses"; +import { Target } from "./Target"; + +export type ListUserPoolClientsTarget = Target< + ListUserPoolClientsRequest, + ListUserPoolClientsResponse +>; + +type ListGroupServices = Pick; + +export const ListUserPoolClients = + ({ cognito }: ListGroupServices): ListUserPoolClientsTarget => + async (ctx, req) => { + // TODO: NextToken support + // TODO: MaxResults support + + const clients = await cognito.listAppClients(ctx, req.UserPoolId); + + return { + UserPoolClients: clients.map(appClientToResponseObject), + }; + }; diff --git a/src/targets/listUserPools.ts b/src/targets/listUserPools.ts index 04807f9f..199c4e25 100644 --- a/src/targets/listUserPools.ts +++ b/src/targets/listUserPools.ts @@ -3,7 +3,7 @@ import { ListUserPoolsResponse, } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; -import { UserPool } from "../services/userPoolService"; +import { userPoolToResponseObject } from "./responses"; import { Target } from "./Target"; export type ListUserPoolsTarget = Target< @@ -19,9 +19,9 @@ export const ListUserPools = // TODO: NextToken support // TODO: MaxResults support - const userPools = (await cognito.listUserPools(ctx)) as UserPool[]; + const userPools = await cognito.listUserPools(ctx); return { - UserPools: userPools, + UserPools: userPools.map(userPoolToResponseObject), }; }; diff --git a/src/targets/listUsers.ts b/src/targets/listUsers.ts index b302eb05..148e2c6e 100644 --- a/src/targets/listUsers.ts +++ b/src/targets/listUsers.ts @@ -3,6 +3,7 @@ import { ListUsersResponse, } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; +import { userToResponseObject } from "./responses"; import { Target } from "./Target"; export type ListUsersTarget = Target; @@ -19,13 +20,6 @@ export const ListUsers = // TODO: support PaginationToken return { - Users: users.map((user) => ({ - Username: user.Username, - UserCreateDate: user.UserCreateDate, - UserLastModifiedDate: user.UserLastModifiedDate, - Enabled: user.Enabled, - UserStatus: user.UserStatus, - Attributes: user.Attributes, - })), + Users: users.map(userToResponseObject), }; }; diff --git a/src/targets/listUsersInGroup.ts b/src/targets/listUsersInGroup.ts index 5bf6eba7..8d2b036b 100644 --- a/src/targets/listUsersInGroup.ts +++ b/src/targets/listUsersInGroup.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { GroupNotFoundError, UserNotFoundError } from "../errors"; import { Services } from "../services"; +import { userToResponseObject } from "./responses"; import { Target } from "./Target"; export type ListUsersInGroupTarget = Target< @@ -28,15 +29,7 @@ export const ListUsersInGroup = throw new UserNotFoundError(); } - return { - Username: user.Username, - Attributes: user.Attributes, - UserCreateDate: user.UserCreateDate, - UserLastModifiedDate: user.UserLastModifiedDate, - Enabled: user.Enabled, - UserStatus: user.UserStatus, - MFAOptions: user.MFAOptions, - }; + return userToResponseObject(user); }) ?? [] ), }; diff --git a/src/targets/responses.ts b/src/targets/responses.ts new file mode 100644 index 00000000..5a127a33 --- /dev/null +++ b/src/targets/responses.ts @@ -0,0 +1,92 @@ +import { + GroupType, + UserPoolClientType, + UserPoolType, + UserType, +} from "aws-sdk/clients/cognitoidentityserviceprovider"; +import { AppClient } from "../services/appClient"; +import { Group, User, UserPool } from "../services/userPoolService"; + +export const appClientToResponseObject = ( + appClient: AppClient +): UserPoolClientType => ({ + AccessTokenValidity: appClient.AccessTokenValidity, + AllowedOAuthFlows: appClient.AllowedOAuthFlows, + AllowedOAuthFlowsUserPoolClient: appClient.AllowedOAuthFlowsUserPoolClient, + AllowedOAuthScopes: appClient.AllowedOAuthScopes, + AnalyticsConfiguration: appClient.AnalyticsConfiguration, + CallbackURLs: appClient.CallbackURLs, + ClientId: appClient.ClientId, + ClientName: appClient.ClientName, + ClientSecret: appClient.ClientSecret, + CreationDate: appClient.CreationDate, + DefaultRedirectURI: appClient.DefaultRedirectURI, + EnableTokenRevocation: appClient.EnableTokenRevocation, + ExplicitAuthFlows: appClient.ExplicitAuthFlows, + IdTokenValidity: appClient.IdTokenValidity, + LastModifiedDate: appClient.LastModifiedDate, + LogoutURLs: appClient.LogoutURLs, + PreventUserExistenceErrors: appClient.PreventUserExistenceErrors, + ReadAttributes: appClient.ReadAttributes, + RefreshTokenValidity: appClient.RefreshTokenValidity, + SupportedIdentityProviders: appClient.SupportedIdentityProviders, + TokenValidityUnits: appClient.TokenValidityUnits, + UserPoolId: appClient.UserPoolId, + WriteAttributes: appClient.WriteAttributes, +}); + +export const userToResponseObject = (user: User): UserType => ({ + Attributes: user.Attributes, + Enabled: user.Enabled, + MFAOptions: user.MFAOptions, + UserCreateDate: user.UserCreateDate, + UserLastModifiedDate: user.UserLastModifiedDate, + Username: user.Username, + UserStatus: user.UserStatus, +}); + +export const groupToResponseObject = + (userPoolId: string) => + (group: Group): GroupType => ({ + CreationDate: group.CreationDate, + Description: group.Description, + GroupName: group.GroupName, + LastModifiedDate: group.LastModifiedDate, + Precedence: group.Precedence, + RoleArn: group.RoleArn, + UserPoolId: userPoolId, + }); + +export const userPoolToResponseObject = (userPool: UserPool): UserPoolType => ({ + AccountRecoverySetting: userPool.AccountRecoverySetting, + AdminCreateUserConfig: userPool.AdminCreateUserConfig, + AliasAttributes: userPool.AliasAttributes, + Arn: userPool.Arn, + AutoVerifiedAttributes: userPool.AutoVerifiedAttributes, + CreationDate: userPool.CreationDate, + CustomDomain: userPool.CustomDomain, + DeviceConfiguration: userPool.DeviceConfiguration, + Domain: userPool.Domain, + EmailConfiguration: userPool.EmailConfiguration, + EmailConfigurationFailure: userPool.EmailConfigurationFailure, + EmailVerificationMessage: userPool.EmailVerificationMessage, + EmailVerificationSubject: userPool.EmailVerificationSubject, + EstimatedNumberOfUsers: userPool.EstimatedNumberOfUsers, + Id: userPool.Id, + LambdaConfig: userPool.LambdaConfig, + LastModifiedDate: userPool.LastModifiedDate, + MfaConfiguration: userPool.MfaConfiguration, + Name: userPool.Name, + Policies: userPool.Policies, + SchemaAttributes: userPool.SchemaAttributes, + SmsAuthenticationMessage: userPool.SmsAuthenticationMessage, + SmsConfiguration: userPool.SmsConfiguration, + SmsConfigurationFailure: userPool.SmsConfigurationFailure, + SmsVerificationMessage: userPool.SmsVerificationMessage, + Status: userPool.Status, + UsernameAttributes: userPool.UsernameAttributes, + UsernameConfiguration: userPool.UsernameConfiguration, + UserPoolAddOns: userPool.UserPoolAddOns, + UserPoolTags: userPool.UserPoolTags, + VerificationMessageTemplate: userPool.VerificationMessageTemplate, +}); diff --git a/src/targets/targets.ts b/src/targets/targets.ts index 2bba0022..771ef70c 100644 --- a/src/targets/targets.ts +++ b/src/targets/targets.ts @@ -26,6 +26,7 @@ import { GetUser } from "./getUser"; import { GetUserAttributeVerificationCode } from "./getUserAttributeVerificationCode"; import { InitiateAuth } from "./initiateAuth"; import { ListGroups } from "./listGroups"; +import { ListUserPoolClients } from "./listUserPoolClients"; import { ListUserPools } from "./listUserPools"; import { ListUsers } from "./listUsers"; import { ListUsersInGroup } from "./listUsersInGroup"; @@ -64,6 +65,7 @@ export const Targets = { GetUserAttributeVerificationCode, InitiateAuth, ListGroups, + ListUserPoolClients, ListUserPools, ListUsers, ListUsersInGroup, diff --git a/src/targets/updateGroup.ts b/src/targets/updateGroup.ts index 199f5709..4d9d1a49 100644 --- a/src/targets/updateGroup.ts +++ b/src/targets/updateGroup.ts @@ -4,6 +4,7 @@ import { } from "aws-sdk/clients/cognitoidentityserviceprovider"; import { Services } from "../services"; import { GroupNotFoundError } from "../errors"; +import { groupToResponseObject } from "./responses"; import { Target } from "./Target"; export type UpdateGroupTarget = Target; @@ -30,14 +31,6 @@ export const UpdateGroup = await userPool.saveGroup(ctx, updatedGroup); return { - Group: { - CreationDate: updatedGroup.CreationDate, - Description: updatedGroup.Description, - GroupName: updatedGroup.GroupName, - LastModifiedDate: updatedGroup.LastModifiedDate, - Precedence: updatedGroup.Precedence, - RoleArn: updatedGroup.RoleArn, - UserPoolId: req.UserPoolId, - }, + Group: groupToResponseObject(req.UserPoolId)(updatedGroup), }; };