Skip to content

Commit

Permalink
feat(api): support for ListUserPoolClients
Browse files Browse the repository at this point in the history
  • Loading branch information
jagregory committed Feb 16, 2022
1 parent 1fc025c commit 6e546ce
Show file tree
Hide file tree
Showing 30 changed files with 440 additions and 156 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ||
Expand Down Expand Up @@ -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 | ✅¹ |
Expand Down
3 changes: 0 additions & 3 deletions integration-tests/aws-sdk/createUserPool.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -39,7 +37,6 @@ describe(
},
{
clock,
logger: Pino(),
}
)
);
2 changes: 0 additions & 2 deletions integration-tests/aws-sdk/createUserPoolClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
});
Expand Down
33 changes: 33 additions & 0 deletions integration-tests/aws-sdk/listUserPoolClients.test.ts
Original file line number Diff line number Diff line change
@@ -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",
},
],
});
});
})
);
1 change: 1 addition & 0 deletions src/__tests__/mockCognitoService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
});

Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/mockUserPoolService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export const newMockUserPoolService = (
}
): jest.Mocked<UserPoolService> => ({
config,
createAppClient: jest.fn(),
deleteGroup: jest.fn(),
deleteUser: jest.fn(),
getGroupByGroupName: jest.fn(),
Expand All @@ -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(),
Expand Down
27 changes: 27 additions & 0 deletions src/__tests__/testDataBuilder.ts
Original file line number Diff line number Diff line change
@@ -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>): 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>): Group => ({
CreationDate: partial?.CreationDate ?? new Date(),
Description: partial?.Description ?? undefined,
Expand Down
88 changes: 86 additions & 2 deletions src/services/appClient.ts
Original file line number Diff line number Diff line change
@@ -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");
Expand Down
18 changes: 18 additions & 0 deletions src/services/cognitoService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,10 @@ export interface CognitoService {
ctx: Context,
clientId: string
): Promise<UserPoolService>;
listAppClients(
ctx: Context,
userPoolId: string
): Promise<readonly AppClient[]>;
listUserPools(ctx: Context): Promise<readonly UserPool[]>;
}

Expand Down Expand Up @@ -358,6 +362,20 @@ export class CognitoServiceImpl implements CognitoService {
return this.clients.get(ctx, ["Clients", clientId]);
}

public async listAppClients(
ctx: Context,
userPoolId: string
): Promise<readonly AppClient[]> {
ctx.logger.debug({ userPoolId }, "CognitoServiceImpl.listAppClients");
const clients = await this.clients.get<Record<string, AppClient>>(
ctx,
"Clients",
{}
);

return Object.values(clients).filter((x) => x.UserPoolId === userPoolId);
}

public async listUserPools(ctx: Context): Promise<readonly UserPool[]> {
ctx.logger.debug("CognitoServiceImpl.listUserPools");
const entries = await readdir(this.dataDirectory, { withFileTypes: true });
Expand Down
18 changes: 9 additions & 9 deletions src/services/userPoolService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) =>
Expand All @@ -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
);
});
});
Expand Down
44 changes: 20 additions & 24 deletions src/services/userPoolService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -134,7 +138,7 @@ export type UserPool = UserPoolType & {
export interface UserPoolService {
readonly config: UserPool;

createAppClient(ctx: Context, name: string): Promise<AppClient>;
saveAppClient(ctx: Context, appClient: AppClient): Promise<void>;
deleteGroup(ctx: Context, group: Group): Promise<void>;
deleteUser(ctx: Context, user: User): Promise<void>;
getGroupByGroupName(ctx: Context, groupName: string): Promise<Group | null>;
Expand Down Expand Up @@ -182,24 +186,16 @@ export class UserPoolServiceImpl implements UserPoolService {
this.dataStore = dataStore;
}

public async createAppClient(ctx: Context, name: string): Promise<AppClient> {
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<void> {
ctx.logger.debug("UserPoolServiceImpl.saveAppClient");
await this.clientsDataStore.set(
ctx,
["Clients", appClient.ClientId],
appClient
);
}

public async deleteGroup(ctx: Context, group: Group): Promise<void> {
Expand Down
Loading

0 comments on commit 6e546ce

Please sign in to comment.