diff --git a/.changeset/fuzzy-geckos-grab.md b/.changeset/fuzzy-geckos-grab.md new file mode 100644 index 0000000..af067a5 --- /dev/null +++ b/.changeset/fuzzy-geckos-grab.md @@ -0,0 +1,5 @@ +--- +'@open-iga/aws': minor +--- + +Support list accounts with cursor, pass tenant info from core and support cursor for entitlement discovery diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2fa0052..74ca3c5 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -14,6 +14,8 @@ jobs: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.4 - name: Install extism-js env: @@ -34,8 +36,8 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - - name: Lint, test and compile - run: bunx turbo run "//#lint" test compile + - name: Typecheck, Lint, test and compile + run: bunx turbo run typecheck "//#lint" test compile changeset-check: runs-on: ubuntu-latest diff --git a/connectors/aws/e2e/account-acctions.create.test.ts b/connectors/aws/e2e/account-acctions.create.test.ts index c8a47e0..1bb2715 100644 --- a/connectors/aws/e2e/account-acctions.create.test.ts +++ b/connectors/aws/e2e/account-acctions.create.test.ts @@ -2,6 +2,8 @@ import { createMockedHost, type MockedHost } from '@open-iga/connector-sdk/test' import { awsConnector } from '../src/aws-connector.ts'; import { getLoginProfile } from '../src/utils/iam.login-profile.ts'; +const tenant = { id: '000000000000' }; + describe('account-actions.create', () => { let host: MockedHost; @@ -25,6 +27,7 @@ describe('account-actions.create', () => { it('should create an iam user with temporary credentials', async () => { const email = `test.user@openiga.dev`; const result = await host.callAccountActions('iam-user', 'create', { + tenant, email, firstname: 'test', lastname: 'user', @@ -56,28 +59,79 @@ describe('account-actions.create', () => { expect(profile.passwordResetRequired).toBe(true); }); - it('should return an error for a duplicate email', async () => { + it('should return the existing user without creating a new one for a duplicate email', async () => { const email = `test.dup-user@openiga.dev`; const firstname = 'test'; const lastname = 'dup-user'; - const first = await host.callAccountActions('iam-user', 'create', { email, firstname, lastname }); + const first = await host.callAccountActions('iam-user', 'create', { tenant, email, firstname, lastname }); expect(first.ok).toBe(true); + // for type-safety + if (!first.ok) return; + expect(first.output.created).toBe(true); - const second = await host.callAccountActions('iam-user', 'create', { + const emailsBefore = host.hostFunctions.sentEmails.length; + const second = await host.callAccountActions('iam-user', 'create', { tenant, email, firstname, lastname }); + + expect(second.ok).toBe(true); + if (second.ok) { + expect(second.output).toEqual({ id: first.output.id, created: false }); + } + // No new password is sent for an existing user + expect(host.hostFunctions.sentEmails.length).toBe(emailsBefore); + }); + + it('should fail instead of reporting success when the existing user has no console access', async () => { + const email = 'no.access@openiga.dev'; + const created = await host.callAccountActions('iam-user', 'create', { + tenant, + email, + firstname: 'no', + lastname: 'access', + }); + expect(created.ok).toBe(true); + if (!created.ok) return; + await host.callAccountActions('iam-user', 'disable', { tenant, id: created.output.id }); + + const again = await host.callAccountActions('iam-user', 'create', { + tenant, email, - firstname, - lastname, + firstname: 'no', + lastname: 'access', + }); + + expect(again.ok).toBe(false); + if (!again.ok) { + expect(again.error).toContain('without console access'); + } + }); + + it('should not adopt an existing user that belongs to a different email', async () => { + const first = await host.callAccountActions('iam-user', 'create', { + tenant, + email: 'same.name@openiga.dev', + firstname: 'a', + lastname: 'b', + }); + expect(first.ok).toBe(true); + + // Same IAM username (the email's first part), different person + const second = await host.callAccountActions('iam-user', 'create', { + tenant, + email: 'same.name@other.dev', + firstname: 'c', + lastname: 'd', }); expect(second.ok).toBe(false); if (!second.ok) { - expect(second.error).toContain('409'); + expect(second.error).toContain('not tagged'); } }); it('should reject invalid input before calling the upstream', async () => { const result = await host.callAccountActions('iam-user', 'create', { + tenant, email: 'not-an-email', firstname: 'Foo', lastname: 'Bar', @@ -102,6 +156,7 @@ describe('account-actions.create', () => { }); const result = await hostWithoutRole.callAccountActions('iam-user', 'create', { + tenant, email: 'no-role@openiga.dev', firstname: 'Foo', lastname: 'Bar', diff --git a/connectors/aws/e2e/account-actions.lifecycle.test.ts b/connectors/aws/e2e/account-actions.lifecycle.test.ts index 9335cce..a663b89 100644 --- a/connectors/aws/e2e/account-actions.lifecycle.test.ts +++ b/connectors/aws/e2e/account-actions.lifecycle.test.ts @@ -2,6 +2,8 @@ import { createMockedHost, type MockedHost } from '@open-iga/connector-sdk/test' import { awsConnector } from '../src/aws-connector.ts'; import { getLoginProfile } from '../src/utils/iam.login-profile.ts'; +const tenant = { id: '000000000000' }; + const endpoint = () => process.env.AWS_ENDPOINT_URL ?? ''; const credentials = { accessKeyId: 'test', secretAccessKey: 'test' }; @@ -43,6 +45,7 @@ describe('account-actions.lifecycle', () => { // Create — user exists with a login profile. const created = await host.callAccountActions('iam-user', 'create', { + tenant, email, firstname: 'life', lastname: 'cycle', @@ -53,36 +56,36 @@ describe('account-actions.lifecycle', () => { expect(await hasLoginProfile(userName)).toBe(true); // Read — exists and enabled. - const afterCreate = await host.callAccountActions('iam-user', 'read', { id }); + const afterCreate = await host.callAccountActions('iam-user', 'read', { tenant, id }); expect(afterCreate.ok).toBe(true); if (afterCreate.ok) expect(afterCreate.output).toEqual({ exists: true, enabled: true }); // Disable — console access revoked. - const disabled = await host.callAccountActions('iam-user', 'disable', { id }); + const disabled = await host.callAccountActions('iam-user', 'disable', { tenant, id }); expect(disabled.ok).toBe(true); if (disabled.ok) expect(disabled.output.disabled).toBe(true); expect(await hasLoginProfile(userName)).toBe(false); // Read — still exists, now disabled. - const afterDisable = await host.callAccountActions('iam-user', 'read', { id }); + const afterDisable = await host.callAccountActions('iam-user', 'read', { tenant, id }); expect(afterDisable.ok).toBe(true); if (afterDisable.ok) expect(afterDisable.output).toEqual({ exists: true, enabled: false }); // Enable — console access restored and credentials re-sent via the email capability. - const enabled = await host.callAccountActions('iam-user', 'enable', { id }); + const enabled = await host.callAccountActions('iam-user', 'enable', { tenant, id }); expect(enabled.ok).toBe(true); if (enabled.ok) expect(enabled.output.enabled).toBe(true); expect(await hasLoginProfile(userName)).toBe(true); expect(host.hostFunctions.sentEmails.at(-1)?.subject).toBe('Your AWS access has been re-enabled'); // Delete — user removed entirely. - const deleted = await host.callAccountActions('iam-user', 'delete', { id }); + const deleted = await host.callAccountActions('iam-user', 'delete', { tenant, id }); expect(deleted.ok).toBe(true); if (deleted.ok) expect(deleted.output.deleted).toBe(true); expect(await hasLoginProfile(userName)).toBe(false); // Read — no longer exists. - const afterDelete = await host.callAccountActions('iam-user', 'read', { id }); + const afterDelete = await host.callAccountActions('iam-user', 'read', { tenant, id }); expect(afterDelete.ok).toBe(true); if (afterDelete.ok) expect(afterDelete.output).toEqual({ exists: false, enabled: false }); }); diff --git a/connectors/aws/e2e/entitlements.test.ts b/connectors/aws/e2e/entitlements.test.ts index 18c0dc5..6ba1fab 100644 --- a/connectors/aws/e2e/entitlements.test.ts +++ b/connectors/aws/e2e/entitlements.test.ts @@ -3,6 +3,8 @@ import { createMockedHost, type MockedHost } from '@open-iga/connector-sdk/test' import { awsConnector } from '../src/aws-connector.ts'; import { createGroup } from '../src/utils/iam.group.ts'; +const tenant = { id: '000000000000' }; + const endpoint = () => process.env.AWS_ENDPOINT_URL ?? ''; const credentials = { accessKeyId: 'test', secretAccessKey: 'test' }; @@ -36,7 +38,7 @@ describe('entitlements', () => { }); it('should discover user groups, excluding operator-filtered ones', async () => { - const result = await host.callEntitlements('iam-user-group', 'discover'); + const result = await host.callEntitlements('iam-user-group', 'discover', { tenant }); expect(result.ok).toBe(true); if (!result.ok) return; @@ -54,6 +56,7 @@ describe('entitlements', () => { it('should grant, read, and revoke a group membership for a user', async () => { // A user to receive the entitlement. const created = await host.callAccountActions('iam-user', 'create', { + tenant, email: 'grant.target@openiga.dev', firstname: 'grant', lastname: 'target', @@ -63,13 +66,14 @@ describe('entitlements', () => { const userArn = created.output.id; // Discover to get a real group ARN to grant. - const discovered = await host.callEntitlements('iam-user-group', 'discover'); + const discovered = await host.callEntitlements('iam-user-group', 'discover', { tenant }); expect(discovered.ok).toBe(true); if (!discovered.ok) return; const groupArn = discovered.output.entitlements.find((e) => e.name === 'ReadOnly')!.entitlementId; // Grant — the user is added to the group. const granted = await host.callEntitlements('iam-user-group', 'grant', { + tenant, id: userArn, entitlementId: groupArn, }); @@ -77,12 +81,13 @@ describe('entitlements', () => { if (granted.ok) expect(granted.output.granted).toBe(true); // Read (drift detection) — the group ARN is reported back. - const readGranted = await host.callEntitlements('iam-user-group', 'read', { id: userArn }); + const readGranted = await host.callEntitlements('iam-user-group', 'read', { tenant, id: userArn }); expect(readGranted.ok).toBe(true); if (readGranted.ok) expect(readGranted.output.entitlementIds).toContain(groupArn); // Revoke — the user is removed from the group. const revoked = await host.callEntitlements('iam-user-group', 'revoke', { + tenant, id: userArn, entitlementId: groupArn, }); @@ -90,7 +95,7 @@ describe('entitlements', () => { if (revoked.ok) expect(revoked.output.revoked).toBe(true); // Read after revoke — no longer reported. - const readRevoked = await host.callEntitlements('iam-user-group', 'read', { id: userArn }); + const readRevoked = await host.callEntitlements('iam-user-group', 'read', { tenant, id: userArn }); expect(readRevoked.ok).toBe(true); if (readRevoked.ok) expect(readRevoked.output.entitlementIds).not.toContain(groupArn); }); diff --git a/connectors/aws/package.json b/connectors/aws/package.json index f7fa125..08b2b3f 100644 --- a/connectors/aws/package.json +++ b/connectors/aws/package.json @@ -5,7 +5,7 @@ "scripts": { "compile": "open-iga compile --entryPoint src/aws-connector.ts", "test": "bun test", - "typecheck": "tsc -p tsconfig.app.json && tsc -p tsconfig.test.json" + "typecheck": "bun --check" }, "dependencies": { "aws4fetch": "catalog:", diff --git a/connectors/aws/src/account-actions/create.ts b/connectors/aws/src/account-actions/create.ts index 7228a30..0f41778 100644 --- a/connectors/aws/src/account-actions/create.ts +++ b/connectors/aws/src/account-actions/create.ts @@ -1,10 +1,12 @@ import { sendEmail } from '@open-iga/connector-sdk'; import type awsConnector from '../aws-connector.ts'; +import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { assumeRole } from '../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { resolveRegion } from '../utils/region.ts'; -import { createUser } from '../utils/iam.create-user.ts'; -import { createLoginProfile } from '../utils/iam.login-profile.ts'; +import { createUser, EMAIL_TAG } from '../utils/iam.create-user.ts'; +import { getUser } from '../utils/iam.get-user.ts'; +import { createLoginProfile, hasLoginProfile } from '../utils/iam.login-profile.ts'; import { generateTemporaryPassword } from '../utils/password.ts'; import { userNameFromEmail } from '../utils/username.ts'; @@ -17,11 +19,7 @@ export const registerAccountActionCreation = (plugin: typeof awsConnector) => { description: 'IAM User account creation', endpoints: IAM_ACTION_ENDPOINTS, config: [ - { - name: 'AWS_USER_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage IAM users', - required: true, - }, + USER_MANAGEMENT_ROLE, { name: 'AWS_PASSWORD_PATTERN', description: @@ -43,11 +41,32 @@ export const registerAccountActionCreation = (plugin: typeof awsConnector) => { roleSessionName: 'openiga-aws-iam-user-create', }); - const created = await createUser({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName: userNameFromEmail(input.email), - }); + const userName = userNameFromEmail(input.email); + let created; + try { + created = await createUser({ + endpoint: IAM_ENDPOINT, + credentials: assumed, + userName, + email: input.email, + }); + } catch (error) { + if (!String(error).includes('EntityAlreadyExists')) throw error; + + // Reuse the existing user only if its Email tag matches; the username is just the email's first part. + const existing = await getUser({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); + if (existing.tags[EMAIL_TAG]?.toLowerCase() !== input.email.trim().toLowerCase()) { + throw new Error( + `IAM user "${userName}" already exists and is not tagged ${EMAIL_TAG}=${input.email}`, + ); + } + + // No login profile means disabled or half-created, so report failure instead of success + if (!(await hasLoginProfile({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }))) { + throw new Error(`IAM user "${userName}" exists without console access; enable or delete it first`); + } + return { id: existing.arn, created: false }; + } // To grant the console access to user with a one-time password that must be changed after the first login const temporaryPassword = generateTemporaryPassword(config.AWS_PASSWORD_PATTERN); @@ -77,6 +96,7 @@ export const registerAccountActionCreation = (plugin: typeof awsConnector) => { return { id: created.arn, + created: true, }; }, }); diff --git a/connectors/aws/src/account-actions/delete.ts b/connectors/aws/src/account-actions/delete.ts index 7788d56..66a67cc 100644 --- a/connectors/aws/src/account-actions/delete.ts +++ b/connectors/aws/src/account-actions/delete.ts @@ -1,4 +1,5 @@ import type awsConnector from '../aws-connector.ts'; +import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { assumeRole } from '../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { resolveRegion } from '../utils/region.ts'; @@ -11,13 +12,7 @@ export const registerAccountActionDelete = (plugin: typeof awsConnector) => { type: 'delete', description: 'Delete an IAM user', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_USER_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage IAM users', - required: true, - }, - ], + config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/account-actions/disable.ts b/connectors/aws/src/account-actions/disable.ts index 6295ddf..8a117f7 100644 --- a/connectors/aws/src/account-actions/disable.ts +++ b/connectors/aws/src/account-actions/disable.ts @@ -1,4 +1,5 @@ import type awsConnector from '../aws-connector.ts'; +import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { assumeRole } from '../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { resolveRegion } from '../utils/region.ts'; @@ -10,13 +11,7 @@ export const registerAccountActionDisable = (plugin: typeof awsConnector) => { type: 'disable', description: 'Disable an IAM user by revoking console access', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_USER_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage IAM users', - required: true, - }, - ], + config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/account-actions/enable.ts b/connectors/aws/src/account-actions/enable.ts index 30d1a04..854eb71 100644 --- a/connectors/aws/src/account-actions/enable.ts +++ b/connectors/aws/src/account-actions/enable.ts @@ -1,5 +1,6 @@ import { sendEmail } from '@open-iga/connector-sdk'; import type awsConnector from '../aws-connector.ts'; +import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { assumeRole } from '../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { resolveRegion } from '../utils/region.ts'; @@ -12,13 +13,7 @@ export const registerAccountActionEnable = (plugin: typeof awsConnector) => { type: 'enable', description: 'Enable an IAM user by restoring console access', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_USER_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage IAM users', - required: true, - }, - ], + config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/account-actions/read.ts b/connectors/aws/src/account-actions/read.ts index 2dc1f81..14abbf1 100644 --- a/connectors/aws/src/account-actions/read.ts +++ b/connectors/aws/src/account-actions/read.ts @@ -1,4 +1,5 @@ import type awsConnector from '../aws-connector.ts'; +import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { assumeRole } from '../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { resolveRegion } from '../utils/region.ts'; @@ -11,13 +12,7 @@ export const registerAccountActionRead = (plugin: typeof awsConnector) => { type: 'read', description: 'Read an IAM user account state for drift detection', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_USER_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage IAM users', - required: true, - }, - ], + config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/aws-connector.ts b/connectors/aws/src/aws-connector.ts index 0212bff..4594f0c 100644 --- a/connectors/aws/src/aws-connector.ts +++ b/connectors/aws/src/aws-connector.ts @@ -16,13 +16,13 @@ export const awsConnector = new OpenIgaConnector({ { name: 'AWS_REGION', description: 'AWS region', required: true }, { name: 'AWS_ACCESS_KEY_ID', - description: 'Base access key id used by the host. Handler level roles are assumed with this access key.', + description: + 'Access key id of the IAM user that assumes the three handler roles. The user needs no IAM permissions of its own; each role trusts the user by ARN.', required: true, }, { name: 'AWS_SECRET_ACCESS_KEY', - description: - 'Base secret access key used to call STS. Handler level roles are assumed with this access key.', + description: 'Secret access key for AWS_ACCESS_KEY_ID.', required: true, }, ], diff --git a/connectors/aws/src/entitlements/iam-user-groups/discover.ts b/connectors/aws/src/entitlements/iam-user-groups/discover.ts index 6448add..090201e 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/discover.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/discover.ts @@ -1,4 +1,5 @@ import type awsConnector from '../../aws-connector.ts'; +import { GROUP_DISCOVERY_ROLE } from '../../utils/role-config.ts'; import { assumeRole } from '../../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { listGroups } from '../../utils/iam.group.ts'; @@ -27,11 +28,7 @@ export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { description: 'Discover assignable IAM user groups for the entitlement catalog', endpoints: IAM_ACTION_ENDPOINTS, config: [ - { - name: 'AWS_GROUP_DISCOVERY_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to list IAM user groups', - required: true, - }, + GROUP_DISCOVERY_ROLE, { name: 'AWS_GROUP_EXCLUDE_PATTERNS', description: ` @@ -43,7 +40,7 @@ export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { required: false, }, ], - handler: async ({ config }) => { + handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); const excludePatterns = parseExcludePatterns(config.AWS_GROUP_EXCLUDE_PATTERNS); @@ -59,10 +56,16 @@ export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { roleSessionName: 'openiga-aws-iam-user-group-discover', }); - const groups = await listGroups({ endpoint: IAM_ENDPOINT, credentials: assumed }); + // The AWS marker is the cursor: one page per call + const { groups, nextMarker } = await listGroups({ + endpoint: IAM_ENDPOINT, + credentials: assumed, + marker: input.cursor, + }); const catalog = groups.filter( - (group) => !excludePatterns.some((pattern) => pattern.test(group.groupName) || pattern.test(group.path)), + (group) => + !excludePatterns.some((pattern) => pattern.test(group.groupName) || pattern.test(group.path)), ); return { @@ -70,6 +73,7 @@ export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { entitlementId: group.arn, name: group.groupName, })), + ...(nextMarker ? { nextCursor: nextMarker } : {}), }; }, }); diff --git a/connectors/aws/src/entitlements/iam-user-groups/grant.ts b/connectors/aws/src/entitlements/iam-user-groups/grant.ts index b410458..28797d1 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/grant.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/grant.ts @@ -1,4 +1,5 @@ import type awsConnector from '../../aws-connector.ts'; +import { ENTITLEMENT_MANAGEMENT_ROLE } from '../../utils/role-config.ts'; import { assumeRole } from '../../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { addUserToGroup } from '../../utils/iam.group.ts'; @@ -10,13 +11,7 @@ export const registerEntitlementGrant = (plugin: typeof awsConnector) => { type: 'grant', description: 'Grant a user membership in an IAM user group', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_ENTITLEMENT_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage user group membership', - required: true, - }, - ], + config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/entitlements/iam-user-groups/read.ts b/connectors/aws/src/entitlements/iam-user-groups/read.ts index 717dc89..c8913cd 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/read.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/read.ts @@ -1,4 +1,5 @@ import type awsConnector from '../../aws-connector.ts'; +import { ENTITLEMENT_MANAGEMENT_ROLE } from '../../utils/role-config.ts'; import { assumeRole } from '../../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { listGroupsAssignedToUser } from '../../utils/iam.group.ts'; @@ -10,13 +11,7 @@ export const registerEntitlementRead = (plugin: typeof awsConnector) => { type: 'read', description: 'Read the IAM user groups a user belongs to (for entitlement drift detection)', endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_ENTITLEMENT_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage user group membership', - required: true, - }, - ], + config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/entitlements/iam-user-groups/revoke.ts b/connectors/aws/src/entitlements/iam-user-groups/revoke.ts index 796e042..eb0c6f1 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/revoke.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/revoke.ts @@ -1,4 +1,5 @@ import type awsConnector from '../../aws-connector.ts'; +import { ENTITLEMENT_MANAGEMENT_ROLE } from '../../utils/role-config.ts'; import { assumeRole } from '../../utils/sts.ts'; import { IAM_ENDPOINT, stsEndpoint, IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { removeUserFromGroup } from '../../utils/iam.group.ts'; @@ -8,15 +9,9 @@ import { resolveRegion } from '../../utils/region.ts'; export const registerEntitlementRevoke = (plugin: typeof awsConnector) => { plugin.registerEntitlements('iam-user-group', { type: 'revoke', - description: 'Revoke a user\'s membership in an IAM user group', + description: "Revoke a user's membership in an IAM user group", endpoints: IAM_ACTION_ENDPOINTS, - config: [ - { - name: 'AWS_ENTITLEMENT_MANAGEMENT_ROLE', - description: 'ARN of the least-privilege role assumed (via STS) to manage user group membership', - required: true, - }, - ], + config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { const region = resolveRegion(config.AWS_REGION); diff --git a/connectors/aws/src/utils/iam.create-user.ts b/connectors/aws/src/utils/iam.create-user.ts index f86144b..1e06526 100644 --- a/connectors/aws/src/utils/iam.create-user.ts +++ b/connectors/aws/src/utils/iam.create-user.ts @@ -2,6 +2,8 @@ import * as z from 'zod/mini'; import { awsRequest, type AwsCredentials } from './client.ts'; import { IAM_API_VERSION, IAM_SIGNING_REGION } from './iam.common.ts'; +export const EMAIL_TAG = 'Email'; + // Parsed CreateUser XML: arn is required (it is the account's stable id) const createUserResponseSchema = z.object({ CreateUserResponse: z.object({ @@ -19,6 +21,8 @@ export interface CreateUserOptions { endpoint: string; credentials: AwsCredentials; userName: string; + // Saved as the user's `Email` tag, since IAM has no email field. + email: string; } export interface CreatedUser { @@ -28,7 +32,12 @@ export interface CreatedUser { } // https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html -export const createUser = async ({ endpoint, credentials, userName }: CreateUserOptions): Promise => { +export const createUser = async ({ + endpoint, + credentials, + userName, + email, +}: CreateUserOptions): Promise => { const { CreateUserResponse } = await awsRequest({ endpoint: endpoint, region: IAM_SIGNING_REGION, @@ -36,7 +45,7 @@ export const createUser = async ({ endpoint, credentials, userName }: CreateUser action: 'CreateUser', version: IAM_API_VERSION, credentials: credentials, - params: { UserName: userName }, + params: { UserName: userName, 'Tags.member.1.Key': EMAIL_TAG, 'Tags.member.1.Value': email }, schema: createUserResponseSchema, }); diff --git a/connectors/aws/src/utils/iam.get-user.ts b/connectors/aws/src/utils/iam.get-user.ts new file mode 100644 index 0000000..6632433 --- /dev/null +++ b/connectors/aws/src/utils/iam.get-user.ts @@ -0,0 +1,41 @@ +import * as z from 'zod/mini'; +import { awsRequest } from './client.ts'; +import { IAM_API_VERSION, IAM_SIGNING_REGION, type IamUserOptions } from './iam.common.ts'; + +const tagSchema = z.object({ Key: z.string(), Value: z.string() }); + +// fast-xml-parser yields an object for one , an array for many, and '' for an empty +const getUserResponseSchema = z.object({ + GetUserResponse: z.object({ + GetUserResult: z.object({ + User: z.object({ + Arn: z.string(), + Tags: z.optional( + z.union([z.literal(''), z.object({ member: z.union([tagSchema, z.array(tagSchema)]) })]), + ), + }), + }), + }), +}); + +// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html +export const getUser = async ({ + endpoint, + credentials, + userName, +}: IamUserOptions): Promise<{ arn: string; tags: Record }> => { + const { GetUserResponse } = await awsRequest({ + endpoint, + region: IAM_SIGNING_REGION, + service: 'iam', + action: 'GetUser', + version: IAM_API_VERSION, + credentials, + params: { UserName: userName }, + schema: getUserResponseSchema, + }); + + const { Arn, Tags } = GetUserResponse.GetUserResult.User; + const members = !Tags ? [] : [Tags.member].flat(); + return { arn: Arn, tags: Object.fromEntries(members.map(({ Key, Value }) => [Key, Value])) }; +}; diff --git a/connectors/aws/src/utils/iam.group.test.ts b/connectors/aws/src/utils/iam.group.test.ts new file mode 100644 index 0000000..ea3dadd --- /dev/null +++ b/connectors/aws/src/utils/iam.group.test.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, it } from 'bun:test'; +import { listGroups } from './iam.group.ts'; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; +}); + +const credentials = { accessKeyId: 'AKIA', secretAccessKey: 'secret' }; + +const respond = (truncated: boolean) => { + const marker = truncated ? 'next-page' : ''; + return new Response( + `${truncated}${marker}arn:aws:iam::1:group/aa/`, + ); +}; + +describe('listGroups', () => { + it('should return one page with its marker and send the given marker', async () => { + let body = ''; + globalThis.fetch = (async (_url: unknown, init: { body: string }) => { + body = init.body; + return respond(true); + }) as never; + + const page = await listGroups({ endpoint: 'https://iam.amazonaws.com', credentials, marker: 'prev' }); + + expect(body).toContain('Marker=prev'); + expect(page.groups.map((g) => g.groupName)).toEqual(['a']); + expect(page.nextMarker).toBe('next-page'); + }); + + it('should omit nextMarker on the last page', async () => { + globalThis.fetch = (async () => respond(false)) as never; + + const page = await listGroups({ endpoint: 'https://iam.amazonaws.com', credentials }); + + expect(page.nextMarker).toBeUndefined(); + }); +}); diff --git a/connectors/aws/src/utils/iam.group.ts b/connectors/aws/src/utils/iam.group.ts index 26305ab..0c2004d 100644 --- a/connectors/aws/src/utils/iam.group.ts +++ b/connectors/aws/src/utils/iam.group.ts @@ -39,31 +39,31 @@ const listGroupsResponseSchema = z.object({ }); // https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html +// One page of groups; `nextMarker` is set while more pages remain. export const listGroups = async ({ endpoint, credentials, -}: Pick): Promise => { - const groups: IamGroup[] = []; - let marker: string | undefined; - - do { - const { ListGroupsResponse } = await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'ListGroups', - version: IAM_API_VERSION, - credentials, - params: { Marker: marker }, - schema: listGroupsResponseSchema, - }); - - const { IsTruncated, Marker, Groups } = ListGroupsResponse.ListGroupsResult; - groups.push(...toIamGroups(Groups)); - marker = IsTruncated === 'true' ? Marker : undefined; - } while (marker); + marker, +}: Pick & { marker?: string | undefined }): Promise<{ + groups: IamGroup[]; + nextMarker?: string; +}> => { + const { ListGroupsResponse } = await awsRequest({ + endpoint, + region: IAM_SIGNING_REGION, + service: 'iam', + action: 'ListGroups', + version: IAM_API_VERSION, + credentials, + params: { Marker: marker }, + schema: listGroupsResponseSchema, + }); - return groups; + const { IsTruncated, Marker, Groups } = ListGroupsResponse.ListGroupsResult; + return { + groups: toIamGroups(Groups), + ...(IsTruncated === 'true' && Marker ? { nextMarker: Marker } : {}), + }; }; const listGroupsForUserResponseSchema = z.object({ diff --git a/connectors/aws/src/utils/role-config.ts b/connectors/aws/src/utils/role-config.ts new file mode 100644 index 0000000..9209647 --- /dev/null +++ b/connectors/aws/src/utils/role-config.ts @@ -0,0 +1,38 @@ +// Each role below is assumed by the base access key via STS. The descriptions state the exact +// permissions so an operator (or an LLM) can write a least-privilege policy for each role. +// Resource scopes follow the IAM action table: https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsidentityandaccessmanagementiam.html +const TRUST = [ + 'Trust policy: one Allow statement with Action "sts:AssumeRole" and Principal {"AWS": ""},', + 'where is the ARN of the IAM user that owns AWS_ACCESS_KEY_ID.', + 'Do not use the account root as the Principal. The role must be in the same AWS account as that user.', + 'The user then needs no sts:AssumeRole permission of its own.', +].join(' '); + +export const USER_MANAGEMENT_ROLE = { + name: 'AWS_USER_MANAGEMENT_ROLE', + description: [ + 'ARN of the IAM role assumed to manage IAM users. ' + TRUST, + 'Allow only: iam:CreateUser, iam:TagUser, iam:GetUser, iam:CreateLoginProfile, iam:GetLoginProfile, iam:DeleteLoginProfile, iam:DeleteUser.', + 'Resource: arn:aws:iam:::user/* (the connector creates users without a path, so they sit at the root).', + ].join(' '), + required: true, +} as const; + +export const GROUP_DISCOVERY_ROLE = { + name: 'AWS_GROUP_DISCOVERY_ROLE', + description: [ + 'ARN of the IAM role assumed to list assignable IAM groups. ' + TRUST, + 'Allow only: iam:ListGroups. Resource must be "*" because IAM has no resource-level permission for ListGroups.', + ].join(' '), + required: true, +} as const; + +export const ENTITLEMENT_MANAGEMENT_ROLE = { + name: 'AWS_ENTITLEMENT_MANAGEMENT_ROLE', + description: [ + 'ARN of the IAM role assumed to manage IAM group membership. ' + TRUST, + 'Allow only: iam:AddUserToGroup, iam:RemoveUserFromGroup, iam:ListGroupsForUser.', + 'Resource: for AddUserToGroup and RemoveUserFromGroup, the assignable groups (arn:aws:iam:::group/*); for ListGroupsForUser, the managed users (arn:aws:iam:::user/*).', + ].join(' '), + required: true, +} as const; diff --git a/package.json b/package.json index 757bb8b..a2f229c 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "scripts": { "test": "turbo run test", "compile": "turbo run compile", + "typecheck": "turbo run typecheck", "lint": "oxlint", "changeset": "changeset", "version-packages": "changeset version" @@ -46,7 +47,7 @@ "extism-js-version": "v1.5.1" }, "engines": { - "bun": ">=1.4.0" + "bun": ">=1.4.4" }, "packageManager": "bun@1.4.0" } diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action-handler.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action-handler.schema.ts index 1b97795..93fdfa5 100644 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action-handler.schema.ts +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action-handler.schema.ts @@ -1,9 +1,17 @@ import * as z from 'zod/mini'; +import { tenantSchema } from './connector.tenant.schema.ts'; const metadataSchema = z.optional(z.record(z.string(), z.json())); +// Handlers are idempotent: repeating an action that already took effect succeeds, `false` means it failed. + +// Page token that only the connector understands; the Host passes it back as is. +const cursorSchema = z.optional(z.string()); + +// If an account with this email already exists, return its id with created=false and change nothing. const creationHandlerSchema = { input: z.object({ + tenant: tenantSchema, email: z.email(), firstname: z.string(), lastname: z.string(), @@ -11,12 +19,15 @@ const creationHandlerSchema = { }), output: z.object({ id: z.string(), + // false when an existing account was returned + created: z.boolean(), metadata: metadataSchema, }), }; const enableHandlerSchema = { input: z.object({ + tenant: tenantSchema, id: z.string(), }), output: z.object({ @@ -26,6 +37,7 @@ const enableHandlerSchema = { const disableHandlerSchema = { input: z.object({ + tenant: tenantSchema, id: z.string(), }), output: z.object({ @@ -35,6 +47,7 @@ const disableHandlerSchema = { const deleteHandlerSchema = { input: z.object({ + tenant: tenantSchema, id: z.string(), }), output: z.object({ @@ -44,6 +57,7 @@ const deleteHandlerSchema = { const readHandlerSchema = { input: z.object({ + tenant: tenantSchema, id: z.string(), }), // Read is an account-drift primitive: it reports whether the account still exists and @@ -54,10 +68,31 @@ const readHandlerSchema = { }), }; +// Lists the tenant's accounts one page at a time; keep calling with `nextCursor` until it is missing. +const listHandlerSchema = { + input: z.object({ + tenant: tenantSchema, + cursor: cursorSchema, + }), + output: z.object({ + accounts: z.array( + z.object({ + id: z.string(), + email: z.string(), + enabled: z.boolean(), + firstname: z.optional(z.string()), + lastname: z.optional(z.string()), + }), + ), + nextCursor: cursorSchema, + }), +}; + export const handlerInputOutputSchema = { create: creationHandlerSchema, read: readHandlerSchema, enable: enableHandlerSchema, disable: disableHandlerSchema, delete: deleteHandlerSchema, + list: listHandlerSchema, }; diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts index ac24190..510161d 100644 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts @@ -3,7 +3,7 @@ import { connectorConfigSchema } from './connector.config.schema.ts'; // Build-time validation schema for an account action export const connectorAccountActionSchema = z.object({ - type: z.enum(['create', 'disable', 'enable', 'delete', 'read']), + type: z.enum(['create', 'disable', 'enable', 'delete', 'read', 'list']), description: z.string(), endpoints: z.array( z.object({ diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement-handler.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement-handler.schema.ts index f1d0f03..c51c840 100644 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement-handler.schema.ts +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement-handler.schema.ts @@ -1,12 +1,15 @@ import * as z from 'zod/mini'; +import { tenantSchema } from './connector.tenant.schema.ts'; const metadataSchema = z.optional(z.record(z.string(), z.json())); // Discovery returns the catalog of entitlements the host indexes for search / self-request. -// An entitlement is generic: a stable id, a human name, an optional description. +// An entitlement is generic: a stable id, a human name, an optional description. The catalog is +// paged: keep calling with `nextCursor` until it is missing. const discoverHandlerSchema = { - input: z.object({}), + input: z.object({ tenant: tenantSchema, cursor: z.optional(z.string()) }), output: z.object({ + nextCursor: z.optional(z.string()), entitlements: z.array( z.object({ entitlementId: z.string(), @@ -20,6 +23,7 @@ const discoverHandlerSchema = { const grantHandlerSchema = { input: z.object({ + tenant: tenantSchema, // id returned by the account creation handler id: z.string(), // id returned by the entitlement discovery handler @@ -32,6 +36,7 @@ const grantHandlerSchema = { const revokeHandlerSchema = { input: z.object({ + tenant: tenantSchema, // id returned by the account creation handler id: z.string(), // id returned by the entitlement discovery handler @@ -46,6 +51,7 @@ const revokeHandlerSchema = { // account currently holds, so the host can reconcile them against its recorded grants. const readHandlerSchema = { input: z.object({ + tenant: tenantSchema, // id returned by the account creation handler id: z.string(), }), diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.tenant.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.tenant.schema.ts new file mode 100644 index 0000000..2b77924 --- /dev/null +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.tenant.schema.ts @@ -0,0 +1,6 @@ +import * as z from 'zod/mini'; + +// The tenant an operation runs against; `id` is its id in the target system. +export const tenantSchema = z.object({ + id: z.string(), +}); diff --git a/packages/connector-sdk/lib/iga/dispatcher.test.ts b/packages/connector-sdk/lib/iga/dispatcher.test.ts index 96d3a79..24e077a 100644 --- a/packages/connector-sdk/lib/iga/dispatcher.test.ts +++ b/packages/connector-sdk/lib/iga/dispatcher.test.ts @@ -17,13 +17,14 @@ const setHostInput = (value: unknown) => { const readHostOutput = () => JSON.parse(hostOutput); const validInput = { + tenant: { id: 'tenant-1' }, email: 'test.user@openiga.dev', firstname: 'test', lastname: 'user', }; const buildPlugin = ( - handler: AccountAction['handler'] = () => ({ id: 'user-1' }), + handler: AccountAction['handler'] = () => ({ id: 'user-1', created: true }), config: ConnectorConfig = [], ) => new OpenIgaConnector({ @@ -76,7 +77,7 @@ describe('createRuntimeDispatcher', () => { it('should throw error if the input in handler is invalid', async () => { const dispatch = createRuntimeDispatcher(buildPlugin()); // email is not a valid email address - setHostInput({ ...routing, config: {}, input: { email: 'not-an-email', firstname: 'test', lastname: 'user' } }); + setHostInput({ ...routing, config: {}, input: { tenant: { id: 'tenant-1' }, email: 'not-an-email', firstname: 'test', lastname: 'user' } }); const code = await dispatch(); @@ -114,7 +115,7 @@ describe('createRuntimeDispatcher', () => { ({ config, input }) => { expect(config).toEqual({ REGION: 'us-east-1' }); expect(input.email).toBe(validInput.email); - return { id: 'user-1', metadata: { region: (config as { REGION: string }).REGION } } as never; + return { id: 'user-1', created: false, metadata: { region: (config as { REGION: string }).REGION } } as never; }, [{ name: 'REGION', description: 'region', required: true }], ), @@ -124,6 +125,35 @@ describe('createRuntimeDispatcher', () => { const code = await dispatch(); expect(code).toBe(0); - expect(readHostOutput()).toEqual({ id: 'user-1', metadata: { region: 'us-east-1' } }); + expect(readHostOutput()).toEqual({ id: 'user-1', created: false, metadata: { region: 'us-east-1' } }); + }); + + it('should dispatch a paged account list', async () => { + const plugin = new OpenIgaConnector({ + name: 'connector', + description: 'desc', + config: [], + allowedDomains: ['domain.com'], + }).registerAccountActions('iam-user', { + type: 'list', + description: 'list users', + endpoints: [{ method: 'GET', url: 'https://domain.com', description: 'endpoint' }], + handler: ({ input }) => { + expect(input.cursor).toBe('p1'); + return { accounts: [{ id: 'user-1', email: 'a@b.co', enabled: true }], nextCursor: 'p2' }; + }, + }); + setHostInput({ + __kind: 'account-action', + __managedResource: 'iam-user', + __type: 'list', + config: {}, + input: { tenant: { id: 'tenant-1' }, cursor: 'p1' }, + }); + + const code = await createRuntimeDispatcher(plugin)(); + + expect(code).toBe(0); + expect(readHostOutput().nextCursor).toBe('p2'); }); }); diff --git a/packages/connector-sdk/lib/utils/config.ts b/packages/connector-sdk/lib/utils/config.ts index 381dc31..8dbc48c 100644 --- a/packages/connector-sdk/lib/utils/config.ts +++ b/packages/connector-sdk/lib/utils/config.ts @@ -18,7 +18,8 @@ export const buildConfig = ( throw new Error(`Config "${name}" is required but missing from the Host config`); } - config[name] = value; + config[name] = value ?? null; } + return config; }; diff --git a/packages/connector-sdk/package.json b/packages/connector-sdk/package.json index 88a231e..77a141c 100644 --- a/packages/connector-sdk/package.json +++ b/packages/connector-sdk/package.json @@ -26,7 +26,8 @@ "./tsconfig.connector.json": "./tsconfig.connector.json" }, "scripts": { - "test": "bun test" + "test": "bun test", + "typecheck": "bun --check" }, "dependencies": { "@extism/extism": "catalog:", diff --git a/turbo.json b/turbo.json index ad47d38..a781cbb 100644 --- a/turbo.json +++ b/turbo.json @@ -9,6 +9,9 @@ "dependsOn": ["^compile"], "outputs": [".open-iga/**"] }, - "//#lint": {} + "//#lint": {}, + "typecheck": { + "dependsOn": ["^typecheck"] + } } }