feat(api): Cognito user actions, groups and test sign-in
Adds enable, disable, confirm, sign-out, password reset and set-password for one user; user group membership; group list, create and delete; and a test sign-in that returns decoded token claims. A refused test sign-in is an outcome rather than a 401, which would end the console session. Also adds a generic GET for one flat item and a schema deleteImpact so delete confirmations can say what else goes with a resource.
This commit is contained in:
@@ -1,5 +1,17 @@
|
||||
import {createHmac} from 'node:crypto'
|
||||
import {describe, expect, test} from 'bun:test'
|
||||
import {
|
||||
AdminAddUserToGroupCommand,
|
||||
AdminConfirmSignUpCommand,
|
||||
AdminDisableUserCommand,
|
||||
AdminListGroupsForUserCommand,
|
||||
AdminRemoveUserFromGroupCommand,
|
||||
AdminUserGlobalSignOutCommand,
|
||||
CreateGroupCommand,
|
||||
DeleteGroupCommand,
|
||||
DescribeUserPoolClientCommand,
|
||||
InitiateAuthCommand,
|
||||
ListGroupsCommand,
|
||||
AdminCreateUserCommand,
|
||||
AdminDeleteUserCommand,
|
||||
AdminGetUserCommand,
|
||||
@@ -14,7 +26,7 @@ import {
|
||||
type CognitoIdentityProviderClient,
|
||||
} from '@aws-sdk/client-cognito-identity-provider'
|
||||
import {AwsUserPoolsAdapter} from './AwsUserPoolsAdapter'
|
||||
import {ValidationError} from '../cloud-spi/errors'
|
||||
import {ConflictError, ValidationError} from '../cloud-spi/errors'
|
||||
|
||||
type SendResult = Record<string, unknown>
|
||||
|
||||
@@ -255,3 +267,110 @@ describe('AwsUserPoolsAdapter users', () => {
|
||||
expect((sent[0] as AdminDeleteUserCommand).input).toEqual({UserPoolId: POOL_ID, Username: alice.Username})
|
||||
})
|
||||
})
|
||||
|
||||
function jwt(claims: Record<string, unknown>): string {
|
||||
return ['{"alg":"RS256"}', JSON.stringify(claims), 'sig'].map((part) => Buffer.from(part).toString('base64url')).join('.')
|
||||
}
|
||||
|
||||
describe('AwsUserPoolsAdapter user actions and groups', () => {
|
||||
test('reads a user with the groups it belongs to', async () => {
|
||||
const {client, sent} = stubCognito((command) => {
|
||||
if (command instanceof AdminGetUserCommand) return {Username: alice.Username, UserAttributes: alice.Attributes, UserStatus: 'CONFIRMED', Enabled: true, UserCreateDate: CREATED}
|
||||
if (command instanceof AdminListGroupsForUserCommand) return {Groups: [{GroupName: 'admins'}]}
|
||||
return {}
|
||||
})
|
||||
const user = await new AwsUserPoolsAdapter(client).items.getItem!(POOL_ID, alice.Username)
|
||||
|
||||
expect(user?.body.groups).toEqual(['admins'])
|
||||
expect((sent[1] as AdminListGroupsForUserCommand).input).toMatchObject({UserPoolId: POOL_ID, Username: alice.Username})
|
||||
})
|
||||
|
||||
test('runs each user action as its Admin call', async () => {
|
||||
const {client, sent} = stubCognito(() => ({}))
|
||||
const adapter = new AwsUserPoolsAdapter(client)
|
||||
|
||||
await adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'disable'})
|
||||
await adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'confirm'})
|
||||
await adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'signOut'})
|
||||
await adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'setPassword', password: ' Passw0rd! '})
|
||||
|
||||
expect(sent[0]).toBeInstanceOf(AdminDisableUserCommand)
|
||||
expect(sent[1]).toBeInstanceOf(AdminConfirmSignUpCommand)
|
||||
expect(sent[2]).toBeInstanceOf(AdminUserGlobalSignOutCommand)
|
||||
expect((sent[3] as AdminSetUserPasswordCommand).input).toEqual({UserPoolId: POOL_ID, Username: 'bob', Password: ' Passw0rd! ', Permanent: true})
|
||||
})
|
||||
|
||||
test('rejects unknown actions and reports a refused one as a conflict, never a 401', async () => {
|
||||
const {client} = stubCognito(() => { throw awsError('NotAuthorizedException') })
|
||||
const adapter = new AwsUserPoolsAdapter(client)
|
||||
|
||||
await expect(adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'explode'} as never)).rejects.toBeInstanceOf(ValidationError)
|
||||
await expect(adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'setPassword'} as never)).rejects.toBeInstanceOf(ValidationError)
|
||||
await expect(adapter.updateUserPoolUser(POOL_ID, 'bob', {action: 'confirm'})).rejects.toBeInstanceOf(ConflictError)
|
||||
})
|
||||
|
||||
test('sets a user\'s groups by adding and removing only the difference', async () => {
|
||||
const {client, sent} = stubCognito((command) => command instanceof AdminListGroupsForUserCommand ? {Groups: [{GroupName: 'staff'}, {GroupName: 'beta'}]} : {})
|
||||
await new AwsUserPoolsAdapter(client).setUserPoolUserGroups(POOL_ID, 'bob', ['staff', 'admins'])
|
||||
|
||||
const changes = sent.slice(1)
|
||||
expect(changes).toHaveLength(2)
|
||||
expect(changes[0]).toBeInstanceOf(AdminAddUserToGroupCommand)
|
||||
expect((changes[0] as AdminAddUserToGroupCommand).input.GroupName).toBe('admins')
|
||||
expect(changes[1]).toBeInstanceOf(AdminRemoveUserFromGroupCommand)
|
||||
expect((changes[1] as AdminRemoveUserFromGroupCommand).input.GroupName).toBe('beta')
|
||||
})
|
||||
|
||||
test('lists, creates and deletes groups', async () => {
|
||||
const {client, sent} = stubCognito((command) => {
|
||||
if (command instanceof ListGroupsCommand) return {Groups: [{GroupName: 'admins', Description: 'Full access', Precedence: 0, CreationDate: CREATED}]}
|
||||
if (command instanceof CreateGroupCommand) return {Group: {GroupName: command.input.GroupName, Precedence: command.input.Precedence, CreationDate: CREATED}}
|
||||
return {}
|
||||
})
|
||||
const adapter = new AwsUserPoolsAdapter(client)
|
||||
|
||||
expect(await adapter.listUserPoolGroups(POOL_ID)).toEqual([{name: 'admins', description: 'Full access', precedence: 0, createdAt: CREATED.toISOString()}])
|
||||
expect(await adapter.createUserPoolGroup(POOL_ID, {name: 'editors', precedence: 5})).toMatchObject({name: 'editors', precedence: 5})
|
||||
await adapter.deleteUserPoolGroup(POOL_ID, 'editors')
|
||||
|
||||
expect((sent[1] as CreateGroupCommand).input).toEqual({UserPoolId: POOL_ID, GroupName: 'editors', Precedence: 5})
|
||||
expect(sent[2]).toBeInstanceOf(DeleteGroupCommand)
|
||||
})
|
||||
|
||||
test('validates a group before creating it', async () => {
|
||||
const {client, sent} = stubCognito(() => ({}))
|
||||
const adapter = new AwsUserPoolsAdapter(client)
|
||||
|
||||
await expect(adapter.createUserPoolGroup(POOL_ID, {name: 'has space'})).rejects.toBeInstanceOf(ValidationError)
|
||||
await expect(adapter.createUserPoolGroup(POOL_ID, {name: 'ok', precedence: -1})).rejects.toBeInstanceOf(ValidationError)
|
||||
expect(sent).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('test sign-in returns decoded claims, adding SECRET_HASH for a client with a secret', async () => {
|
||||
const {client, sent} = stubCognito((command) => {
|
||||
if (command instanceof DescribeUserPoolClientCommand) return {UserPoolClient: {ClientId: 'client-1', ClientSecret: 'shh'}}
|
||||
if (command instanceof InitiateAuthCommand) return {AuthenticationResult: {ExpiresIn: 3600, IdToken: jwt({sub: 's-1', email: 'alice@example.com', token_use: 'id'}), AccessToken: jwt({sub: 's-1', token_use: 'access'})}}
|
||||
return {}
|
||||
})
|
||||
const result = await new AwsUserPoolsAdapter(client).testUserPoolSignIn(POOL_ID, {clientId: 'client-1', username: 'alice@example.com', password: 'Passw0rd!'})
|
||||
|
||||
expect(result).toEqual({outcome: 'signed-in', expiresIn: 3600, idToken: {sub: 's-1', email: 'alice@example.com', token_use: 'id'}, accessToken: {sub: 's-1', token_use: 'access'}})
|
||||
const auth = (sent[1] as InitiateAuthCommand).input
|
||||
expect(auth.AuthFlow).toBe('USER_PASSWORD_AUTH')
|
||||
expect(auth.AuthParameters?.SECRET_HASH).toBe(createHmac('sha256', 'shh').update('alice@example.comclient-1').digest('base64'))
|
||||
})
|
||||
|
||||
test('test sign-in reports a wrong password or a challenge as its outcome', async () => {
|
||||
const refusing = stubCognito((command) => {
|
||||
if (command instanceof InitiateAuthCommand) throw Object.assign(awsError('NotAuthorizedException'), {message: 'Incorrect username or password.'})
|
||||
return {UserPoolClient: {ClientId: 'client-1'}}
|
||||
})
|
||||
expect(await new AwsUserPoolsAdapter(refusing.client).testUserPoolSignIn(POOL_ID, {clientId: 'client-1', username: 'a', password: 'x'}))
|
||||
.toEqual({outcome: 'rejected', code: 'NotAuthorizedException', message: 'Incorrect username or password.'})
|
||||
expect((refusing.sent[1] as InitiateAuthCommand).input.AuthParameters?.SECRET_HASH).toBeUndefined()
|
||||
|
||||
const challenging = stubCognito((command) => command instanceof InitiateAuthCommand ? {ChallengeName: 'NEW_PASSWORD_REQUIRED'} : {UserPoolClient: {}})
|
||||
expect(await new AwsUserPoolsAdapter(challenging.client).testUserPoolSignIn(POOL_ID, {clientId: 'c', username: 'a', password: 'x'}))
|
||||
.toEqual({outcome: 'challenge', challengeName: 'NEW_PASSWORD_REQUIRED'})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user