From dcb710bef68ff5eed9b5bf0b2f41078f4bd20283 Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:39:59 +0530 Subject: [PATCH 1/6] chore: support custom plugin from connector --- packages/connector-sdk/lib/cli/bin.ts | 1 + packages/connector-sdk/lib/cli/compile.ts | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/connector-sdk/lib/cli/bin.ts b/packages/connector-sdk/lib/cli/bin.ts index 37b1a92..d7b4293 100755 --- a/packages/connector-sdk/lib/cli/bin.ts +++ b/packages/connector-sdk/lib/cli/bin.ts @@ -8,6 +8,7 @@ const { values, positionals } = parseArgs({ allowPositionals: true, options: { entryPoint: { type: 'string', short: 'e' }, + plugin: { type: 'string', multiple: true }, }, }); diff --git a/packages/connector-sdk/lib/cli/compile.ts b/packages/connector-sdk/lib/cli/compile.ts index 5bf2b1b..9e60f6a 100644 --- a/packages/connector-sdk/lib/cli/compile.ts +++ b/packages/connector-sdk/lib/cli/compile.ts @@ -1,3 +1,4 @@ +import type { BunPlugin } from 'bun'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { codegenPlugin, VIRTUAL_ENTRY } from '../bun-plugin/codegen.plugin.ts'; @@ -11,7 +12,23 @@ export type BuildContext = { export const OUT_DIR = '.open-iga'; -export const compile = async ({ entryPoint }: { entryPoint?: string }) => { +// Loads the default export of each file given through `--plugin`. +const loadPlugins = (pluginPaths: string[]): Promise => + Promise.all( + pluginPaths.map(async (pluginPath) => { + const { default: plugin } = await import(path.resolve(pluginPath)); + + if (!plugin?.setup) { + throw new Error(`Plugin file ${pluginPath} must default export a build plugin`); + } + + return plugin; + }), + ); + +type CompileArgs = { entryPoint?: string; plugin?: string[] }; + +export const compile = async ({ entryPoint, plugin: pluginPaths = [] }: CompileArgs) => { if (!entryPoint) { throw new Error('Missing --entryPoint'); } @@ -21,6 +38,7 @@ export const compile = async ({ entryPoint }: { entryPoint?: string }) => { } const buildContext: BuildContext = {}; + const connectorPlugins = await loadPlugins(pluginPaths); await Bun.build({ entrypoints: [VIRTUAL_ENTRY], @@ -28,6 +46,6 @@ export const compile = async ({ entryPoint }: { entryPoint?: string }) => { format: 'cjs', target: 'browser', minify: true, - plugins: [codegenPlugin(entryPoint, buildContext), wasmPlugin(buildContext)], + plugins: [codegenPlugin(entryPoint, buildContext), ...connectorPlugins, wasmPlugin(buildContext)], }); }; From 752e36dc1d7c51519509617da9a9fe068bf073fb Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:54:31 +0530 Subject: [PATCH 2/6] refactor: use default IAM client and custom request handler for STS --- connectors/aws/src/utils/aws-endpoints.ts | 4 - connectors/aws/src/utils/client.ts | 130 ++++--------- connectors/aws/src/utils/iam.common.ts | 13 -- connectors/aws/src/utils/iam.create-user.ts | 54 ------ connectors/aws/src/utils/iam.delete-user.ts | 15 -- connectors/aws/src/utils/iam.get-user.ts | 41 ----- connectors/aws/src/utils/iam.group.test.ts | 40 ---- connectors/aws/src/utils/iam.group.ts | 171 ------------------ connectors/aws/src/utils/iam.login-profile.ts | 105 ----------- connectors/aws/src/utils/iam.ts | 25 +++ connectors/aws/src/utils/iam.user-exists.ts | 22 --- connectors/aws/src/utils/request-handler.ts | 23 +++ connectors/aws/src/utils/sts.ts | 67 ------- 13 files changed, 81 insertions(+), 629 deletions(-) delete mode 100644 connectors/aws/src/utils/iam.common.ts delete mode 100644 connectors/aws/src/utils/iam.create-user.ts delete mode 100644 connectors/aws/src/utils/iam.delete-user.ts delete mode 100644 connectors/aws/src/utils/iam.get-user.ts delete mode 100644 connectors/aws/src/utils/iam.group.test.ts delete mode 100644 connectors/aws/src/utils/iam.group.ts delete mode 100644 connectors/aws/src/utils/iam.login-profile.ts create mode 100644 connectors/aws/src/utils/iam.ts delete mode 100644 connectors/aws/src/utils/iam.user-exists.ts create mode 100644 connectors/aws/src/utils/request-handler.ts delete mode 100644 connectors/aws/src/utils/sts.ts diff --git a/connectors/aws/src/utils/aws-endpoints.ts b/connectors/aws/src/utils/aws-endpoints.ts index 1f836cd..2d34741 100644 --- a/connectors/aws/src/utils/aws-endpoints.ts +++ b/connectors/aws/src/utils/aws-endpoints.ts @@ -1,7 +1,3 @@ -export const IAM_ENDPOINT = 'https://iam.amazonaws.com'; - -export const stsEndpoint = (region: string): string => `https://sts.${region}.amazonaws.com`; - type Endpoint = { method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; url: string; description: string }; // Manifest endpoint allow-list shared by every IAM action/entitlement: STS to assume a role, diff --git a/connectors/aws/src/utils/client.ts b/connectors/aws/src/utils/client.ts index 62d67cf..0fa8781 100644 --- a/connectors/aws/src/utils/client.ts +++ b/connectors/aws/src/utils/client.ts @@ -1,107 +1,43 @@ -import { AwsClient } from 'aws4fetch'; -import { XMLParser } from 'fast-xml-parser'; +import { IAMClient } from '@aws-sdk/client-iam'; +import { AssumeRoleCommand, STSClient } from '@aws-sdk/client-sts'; +import { requestHandler } from './request-handler.ts'; +import { resolveRegion } from './region.ts'; -export interface AwsCredentials { - accessKeyId: string; - secretAccessKey: string; - sessionToken?: string; -} +// IAM is global and signs against this region: https://docs.aws.amazon.com/general/latest/gr/iam-service.html +const IAM_SIGNING_REGION = 'us-east-1'; -type SupportedAction = - | 'AssumeRole' - | 'CreateUser' - | 'CreateLoginProfile' - | 'GetLoginProfile' - | 'GetUser' - | 'DeleteLoginProfile' - | 'DeleteUser' - | 'ListGroups' - | 'ListGroupsForUser' - | 'AddUserToGroup' - | 'RemoveUserFromGroup' - | 'CreateGroup'; +// One attempt only: the wasm runtime has no timers for retry backoff. +const CLIENT_DEFAULTS = { requestHandler, maxAttempts: 1 }; -export interface AwsRequestOptions { - endpoint: string; - region: string; - service: 'sts' | 'iam'; - action: SupportedAction; - version: string; // service API version that pins the request/response contract - credentials: AwsCredentials; - // Action-specific params; undefined/empty values are omitted from the request. - params?: Record; - // Optional schema the caller supplies to validate and shape the parsed response. - schema?: ResponseSchema; -} - -const parser = new XMLParser({ ignoreAttributes: true, parseTagValue: false }); - -/** - * Parse an AWS Query-protocol XML response into a plain JS object (QuickJS has no DOMParser). - * Values are kept as strings (parseTagValue: false) so ids/tokens/dates aren't coerced to numbers; - * attributes are ignored — AWS Query responses carry their data in element text. Callers hand the - * result to a zod schema that both validates and shapes the fields they need. - */ -export const parseXml = (xml: string): unknown => parser.parse(xml); - -// Zod schema - TODO: parse throws an error check if safeParse can be used instead -export interface ResponseSchema { - parse(input: unknown): T; -} - -/** - * Make a signed AWS Query-protocol request — build the form body, SigV4-sign, POST, and parse the XML response. - * - * AWS Query protocol common parameters: https://docs.aws.amazon.com/IAM/latest/APIReference/CommonParameters.html - * SigV4: https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html - * Smithy: https://smithy.io/2.0/aws/protocols/aws-query-protocol.html - */ -export const awsRequest = async ({ - endpoint, - action, - credentials, - params, - region, - service, - version, - schema, -}: AwsRequestOptions): Promise => { - const urlSearchParams = new URLSearchParams({ Action: action, Version: version }); - for (const [key, value] of Object.entries(params ?? {})) { - if (value !== undefined && value !== '') urlSearchParams.set(key, String(value)); - } - const body = urlSearchParams.toString(); - - // aws4fetch adds x-amz-security-token automatically when a session token is present. - const aws = new AwsClient({ - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - ...(credentials.sessionToken ? { sessionToken: credentials.sessionToken } : {}), - service, - region, - }); +type BuildIamClientArgs = { + config: { AWS_REGION: string; AWS_ACCESS_KEY_ID: string; AWS_SECRET_ACCESS_KEY: string }; + roleArn: string; + roleSessionName: string; +}; - const signed = await aws.sign(`${endpoint}/`, { - method: 'POST', - body, - headers: { 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' }, +// https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html +export const buildIamClient = async ({ config, roleArn, roleSessionName }: BuildIamClientArgs): Promise => { + const stsClient = new STSClient({ + ...CLIENT_DEFAULTS, + region: resolveRegion(config.AWS_REGION), + credentials: { accessKeyId: config.AWS_ACCESS_KEY_ID, secretAccessKey: config.AWS_SECRET_ACCESS_KEY }, }); - // Extism `fetch` takes (url, init), not a Request instance - const headers: Record = {}; - signed.headers.forEach((value, key) => (headers[key] = value)); + const { Credentials } = await stsClient.send( + new AssumeRoleCommand({ RoleArn: roleArn, RoleSessionName: roleSessionName }), + ); - const res = await fetch(signed.url, { method: signed.method, headers, body }); - const text = await res.text(); - const doc = parseXml(text); - - if (!res.ok) { - // AWS Query errors: ……. - const error = (doc as { ErrorResponse?: { Error?: { Code?: string; Message?: string } } })?.ErrorResponse - ?.Error; - const detail = [error?.Code, error?.Message].filter(Boolean).join(' '); - throw new Error(`${action} failed (${res.status}): ${detail || text}`); + if (!Credentials?.AccessKeyId || !Credentials.SecretAccessKey || !Credentials.SessionToken) { + throw new Error(`AssumeRole returned no credentials for ${roleArn}`); } - return schema ? schema.parse(doc) : (doc as T); + return new IAMClient({ + ...CLIENT_DEFAULTS, + region: IAM_SIGNING_REGION, + credentials: { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + }, + }); }; diff --git a/connectors/aws/src/utils/iam.common.ts b/connectors/aws/src/utils/iam.common.ts deleted file mode 100644 index d81c51a..0000000 --- a/connectors/aws/src/utils/iam.common.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { AwsCredentials } from './client.ts'; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html -export const IAM_API_VERSION = '2010-05-08'; - -// https://docs.aws.amazon.com/general/latest/gr/iam-service.html -export const IAM_SIGNING_REGION = 'us-east-1'; - -export interface IamUserOptions { - endpoint: string; - credentials: AwsCredentials; - userName: string; -} diff --git a/connectors/aws/src/utils/iam.create-user.ts b/connectors/aws/src/utils/iam.create-user.ts deleted file mode 100644 index 1e06526..0000000 --- a/connectors/aws/src/utils/iam.create-user.ts +++ /dev/null @@ -1,54 +0,0 @@ -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({ - CreateUserResult: z.object({ - User: z.object({ - Arn: z.string().check(z.minLength(1, 'CreateUser response missing user ARN')), - UserId: z.string(), - UserName: z.string(), - }), - }), - }), -}); - -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 { - userId: string; - userName: string; - arn: string; -} - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html -export const createUser = async ({ - endpoint, - credentials, - userName, - email, -}: CreateUserOptions): Promise => { - const { CreateUserResponse } = await awsRequest({ - endpoint: endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'CreateUser', - version: IAM_API_VERSION, - credentials: credentials, - params: { UserName: userName, 'Tags.member.1.Key': EMAIL_TAG, 'Tags.member.1.Value': email }, - schema: createUserResponseSchema, - }); - - const { Arn, UserId, UserName } = CreateUserResponse.CreateUserResult.User; - return { userId: UserId, userName: UserName, arn: Arn }; -}; diff --git a/connectors/aws/src/utils/iam.delete-user.ts b/connectors/aws/src/utils/iam.delete-user.ts deleted file mode 100644 index d99b49d..0000000 --- a/connectors/aws/src/utils/iam.delete-user.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { awsRequest } from './client.ts'; -import { IAM_API_VERSION, IAM_SIGNING_REGION, type IamUserOptions } from './iam.common.ts'; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUser.html -export const deleteUser = async ({ endpoint, credentials, userName }: IamUserOptions): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'DeleteUser', - version: IAM_API_VERSION, - credentials, - params: { UserName: userName }, - }); -}; diff --git a/connectors/aws/src/utils/iam.get-user.ts b/connectors/aws/src/utils/iam.get-user.ts deleted file mode 100644 index 6632433..0000000 --- a/connectors/aws/src/utils/iam.get-user.ts +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index ea3dadd..0000000 --- a/connectors/aws/src/utils/iam.group.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 0c2004d..0000000 --- a/connectors/aws/src/utils/iam.group.ts +++ /dev/null @@ -1,171 +0,0 @@ -import * as z from 'zod/mini'; -import { awsRequest, type AwsCredentials } from './client.ts'; -import { IAM_API_VERSION, IAM_SIGNING_REGION, type IamUserOptions } from './iam.common.ts'; - -export interface IamGroup { - arn: string; - groupName: string; - path: string; -} - -const groupSchema = z.object({ - Arn: z.string().check(z.minLength(1, 'IAM group response missing group ARN')), - GroupName: z.string(), - Path: z.string(), -}); - -// fast-xml-parser collapses one to an object, many to an array, and none to an empty -// string — normalize to an array before validating each group. Shared by ListGroups and -// ListGroupsForUser, which both nest the list under Groups.member. -const groupsField = z.pipe( - z.transform((groups: unknown) => { - const member = groups && typeof groups === 'object' ? (groups as { member?: unknown }).member : undefined; - return Array.isArray(member) ? member : member ? [member] : []; - }), - z.array(groupSchema), -); - -const toIamGroups = (groups: z.infer): IamGroup[] => - groups.map((g) => ({ arn: g.Arn, groupName: g.GroupName, path: g.Path })); - -const listGroupsResponseSchema = z.object({ - ListGroupsResponse: z.object({ - ListGroupsResult: z.object({ - IsTruncated: z.optional(z.string()), - Marker: z.optional(z.string()), - Groups: groupsField, - }), - }), -}); - -// 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, - 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, - }); - - const { IsTruncated, Marker, Groups } = ListGroupsResponse.ListGroupsResult; - return { - groups: toIamGroups(Groups), - ...(IsTruncated === 'true' && Marker ? { nextMarker: Marker } : {}), - }; -}; - -const listGroupsForUserResponseSchema = z.object({ - ListGroupsForUserResponse: z.object({ - ListGroupsForUserResult: z.object({ - IsTruncated: z.optional(z.string()), - Marker: z.optional(z.string()), - Groups: groupsField, - }), - }), -}); - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html -// The groups a user belongs to — the entitlement ids for drift detection. Paginated. -export const listGroupsAssignedToUser = async ({ - endpoint, - credentials, - userName, -}: IamUserOptions): Promise => { - const groups: IamGroup[] = []; - let marker: string | undefined; - - do { - const { ListGroupsForUserResponse } = await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'ListGroupsForUser', - version: IAM_API_VERSION, - credentials, - params: { UserName: userName, Marker: marker }, - schema: listGroupsForUserResponseSchema, - }); - - const { IsTruncated, Marker, Groups } = ListGroupsForUserResponse.ListGroupsForUserResult; - groups.push(...toIamGroups(Groups)); - marker = IsTruncated === 'true' ? Marker : undefined; - } while (marker); - - return groups; -}; - -export interface UserGroupOptions extends IamUserOptions { - groupName: string; -} - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html -export const addUserToGroup = async ({ - endpoint, - credentials, - userName, - groupName, -}: UserGroupOptions): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'AddUserToGroup', - version: IAM_API_VERSION, - credentials, - params: { GroupName: groupName, UserName: userName }, - }); -}; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html -export const removeUserFromGroup = async ({ - endpoint, - credentials, - userName, - groupName, -}: UserGroupOptions): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'RemoveUserFromGroup', - version: IAM_API_VERSION, - credentials, - params: { GroupName: groupName, UserName: userName }, - }); -}; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html -// Used to seed groups in tests; groups are provisioned out-of-band in production. -export const createGroup = async ({ - endpoint, - credentials, - groupName, - path, -}: { - endpoint: string; - credentials: AwsCredentials; - groupName: string; - path?: string; -}): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'CreateGroup', - version: IAM_API_VERSION, - credentials, - params: { GroupName: groupName, Path: path }, - }); -}; diff --git a/connectors/aws/src/utils/iam.login-profile.ts b/connectors/aws/src/utils/iam.login-profile.ts deleted file mode 100644 index 6baedec..0000000 --- a/connectors/aws/src/utils/iam.login-profile.ts +++ /dev/null @@ -1,105 +0,0 @@ -import * as z from 'zod/mini'; -import { awsRequest, type AwsCredentials } from './client.ts'; -import { IAM_API_VERSION, IAM_SIGNING_REGION, type IamUserOptions } from './iam.common.ts'; - -const getLoginProfileResponseSchema = z.object({ - GetLoginProfileResponse: z.object({ - GetLoginProfileResult: z.object({ - LoginProfile: z.object({ - UserName: z.string(), - // PasswordResetRequired comes back as the string "true"/"false" - PasswordResetRequired: z.optional(z.string()), - }), - }), - }), -}); - -export interface CreateLoginProfileOptions { - endpoint: string; - credentials: AwsCredentials; - userName: string; - password: string; -} - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html -export const createLoginProfile = async ({ - endpoint, - credentials, - userName, - password, -}: CreateLoginProfileOptions): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'CreateLoginProfile', - version: IAM_API_VERSION, - credentials, - params: { - UserName: userName, - Password: password, - // Force the user to pick their own password at first console sign-in. - PasswordResetRequired: 'true', - }, - }); -}; - -export interface GetLoginProfileOptions { - endpoint: string; - credentials: AwsCredentials; - userName: string; -} - -export interface LoginProfile { - userName: string; - passwordResetRequired: boolean; -} - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html -export const getLoginProfile = async ({ - endpoint, - credentials, - userName, -}: GetLoginProfileOptions): Promise => { - const { GetLoginProfileResponse } = await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'GetLoginProfile', - version: IAM_API_VERSION, - credentials, - params: { UserName: userName }, - schema: getLoginProfileResponseSchema, - }); - - const { UserName, PasswordResetRequired } = GetLoginProfileResponse.GetLoginProfileResult.LoginProfile; - return { - userName: UserName, - passwordResetRequired: PasswordResetRequired === 'true', - }; -}; - -// Whether the user currently has console access (a login profile). Absence = disabled. -export const hasLoginProfile = async (options: IamUserOptions): Promise => { - try { - await getLoginProfile(options); - return true; - } catch (error) { - if (String(error).includes('NoSuchEntity')) return false; - throw error; - } -}; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteLoginProfile.html -// Removes the user's console password, revoking sign-in without deleting the user. -export const deleteLoginProfile = async ({ endpoint, credentials, userName }: IamUserOptions): Promise => { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'DeleteLoginProfile', - version: IAM_API_VERSION, - credentials, - params: { UserName: userName }, - }); -}; diff --git a/connectors/aws/src/utils/iam.ts b/connectors/aws/src/utils/iam.ts new file mode 100644 index 0000000..91eb40d --- /dev/null +++ b/connectors/aws/src/utils/iam.ts @@ -0,0 +1,25 @@ +import { GetLoginProfileCommand, GetUserCommand, NoSuchEntityException, type IAMClient } from '@aws-sdk/client-iam'; + +// Resolves false when the target of the request does not exist. +export const checkTargetExists = async (request: Promise): Promise => { + try { + await request; + + return true; + } catch (error) { + if (error instanceof NoSuchEntityException) { + return false; + } + + throw error; + } +}; + +// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html +export const checkUserExists = (iamClient: IAMClient, userName: string): Promise => + checkTargetExists(iamClient.send(new GetUserCommand({ UserName: userName }))); + +// A user without a login profile has no console access. +// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html +export const checkLoginProfileExists = (iamClient: IAMClient, userName: string): Promise => + checkTargetExists(iamClient.send(new GetLoginProfileCommand({ UserName: userName }))); diff --git a/connectors/aws/src/utils/iam.user-exists.ts b/connectors/aws/src/utils/iam.user-exists.ts deleted file mode 100644 index 458e2b4..0000000 --- a/connectors/aws/src/utils/iam.user-exists.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { awsRequest } from './client.ts'; -import { IAM_API_VERSION, IAM_SIGNING_REGION, type IamUserOptions } from './iam.common.ts'; - -// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html -// Whether the IAM user exists. NoSuchEntity means it was deleted (or never created). -export const userExists = async ({ endpoint, credentials, userName }: IamUserOptions): Promise => { - try { - await awsRequest({ - endpoint, - region: IAM_SIGNING_REGION, - service: 'iam', - action: 'GetUser', - version: IAM_API_VERSION, - credentials, - params: { UserName: userName }, - }); - return true; - } catch (error) { - if (String(error).includes('NoSuchEntity')) return false; - throw error; - } -}; diff --git a/connectors/aws/src/utils/request-handler.ts b/connectors/aws/src/utils/request-handler.ts new file mode 100644 index 0000000..4785b9c --- /dev/null +++ b/connectors/aws/src/utils/request-handler.ts @@ -0,0 +1,23 @@ +// The retry logic of the client does an `instanceof` check on this global, which the wasm runtime lacks. +(globalThis as { ReadableStream?: unknown }).ReadableStream ??= class ReadableStream {}; + +type HttpRequest = { + protocol: string; + hostname: string; + port?: number; + path: string; + method: string; + headers: Record; + body?: string; +}; + +// Sends client requests through `fetch`, because the default transport needs streams and timers. +export const requestHandler = { + handle: async ({ protocol, hostname, port, path, method, headers, body }: HttpRequest) => { + const url = `${protocol}//${hostname}${port ? `:${port}` : ''}${path}`; + const response = await fetch(url, { method, headers, ...(body ? { body } : {}) }); + const responseBody = new TextEncoder().encode(await response.text()); + + return { response: { statusCode: response.status, headers: {}, body: responseBody } }; + }, +}; diff --git a/connectors/aws/src/utils/sts.ts b/connectors/aws/src/utils/sts.ts deleted file mode 100644 index 195f739..0000000 --- a/connectors/aws/src/utils/sts.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as z from 'zod/mini'; -import { awsRequest, type AwsCredentials } from './client.ts'; - -// https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html -const STS_API_VERSION = '2011-06-15'; - -const assumeRoleResponseSchema = z.object({ - AssumeRoleResponse: z.object({ - AssumeRoleResult: z.object({ - Credentials: z.object({ - AccessKeyId: z.string().check(z.minLength(1, 'AssumeRole response missing AccessKeyId')), - SecretAccessKey: z.string().check(z.minLength(1, 'AssumeRole response missing SecretAccessKey')), - SessionToken: z.string().check(z.minLength(1, 'AssumeRole response missing SessionToken')), - Expiration: z.optional(z.string()), - }), - }), - }), -}); - -export interface AssumeRoleOptions { - endpoint: string; - region: string; - credentials: AwsCredentials; - roleArn: string; - roleSessionName: string; - durationSeconds?: number; -} - -export interface AssumedRole { - accessKeyId: string; - secretAccessKey: string; - sessionToken: string; - expiration: string; -} - -export const assumeRole = async ({ - endpoint, - credentials, - durationSeconds, - region, - roleArn, - roleSessionName, -}: AssumeRoleOptions): Promise => { - const { AssumeRoleResponse } = await awsRequest({ - endpoint, - region, - service: 'sts', - action: 'AssumeRole', - version: STS_API_VERSION, - credentials, - params: { - RoleArn: roleArn, - RoleSessionName: roleSessionName, - DurationSeconds: durationSeconds, - }, - schema: assumeRoleResponseSchema, - }); - - const { AccessKeyId, SecretAccessKey, SessionToken, Expiration } = AssumeRoleResponse.AssumeRoleResult.Credentials; - - return { - accessKeyId: AccessKeyId, - secretAccessKey: SecretAccessKey, - sessionToken: SessionToken, - expiration: Expiration ?? '', - }; -}; From d69e15abf684f98d626b750c8390cbcafeaa3739 Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:19:18 +0530 Subject: [PATCH 3/6] refactor: account action --- connectors/aws/src/account-actions/create.ts | 123 +++++++++++------- connectors/aws/src/account-actions/delete.ts | 34 ++--- connectors/aws/src/account-actions/disable.ts | 28 ++-- connectors/aws/src/account-actions/enable.ts | 32 ++--- connectors/aws/src/account-actions/read.ts | 25 ++-- 5 files changed, 115 insertions(+), 127 deletions(-) diff --git a/connectors/aws/src/account-actions/create.ts b/connectors/aws/src/account-actions/create.ts index 268b8a2..a405bbb 100644 --- a/connectors/aws/src/account-actions/create.ts +++ b/connectors/aws/src/account-actions/create.ts @@ -1,17 +1,63 @@ +import { + CreateLoginProfileCommand, + CreateUserCommand, + EntityAlreadyExistsException, + GetUserCommand, + type IAMClient, +} from '@aws-sdk/client-iam'; 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, 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 { buildIamClient } from '../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { generateTemporaryPassword } from '../utils/password.ts'; +import { checkLoginProfileExists } from '../utils/iam.ts'; +import { accountIdFromArn } from '../utils/arn.ts'; import { userNameFromEmail } from '../utils/username.ts'; -// ARN shape: arn:aws:iam:::user/. The console sign-in URL is account-scoped. -const accountIdFromArn = (arn: string): string => arn.split(':')[4] ?? ''; +// IAM has no email field, so the email is saved as a user tag. +const EMAIL_TAG = 'Email'; + +type CreateUserArgs = { iamClient: IAMClient; userName: string; email: string }; + +// Resolves undefined when the user name is already taken. +// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html +const createUser = async ({ iamClient, userName, email }: CreateUserArgs) => { + try { + const { User } = await iamClient.send( + new CreateUserCommand({ UserName: userName, Tags: [{ Key: EMAIL_TAG, Value: email }] }), + ); + + if (!User?.Arn) { + throw new Error(`CreateUser returned no ARN for "${userName}"`); + } + + return { arn: User.Arn }; + } catch (error) { + if (error instanceof EntityAlreadyExistsException) { + return undefined; + } + + throw error; + } +}; + +// Returns the ARN of an existing user, only when it has the same email and console access. +const getReusableUserArn = async ({ iamClient, userName, email }: CreateUserArgs): Promise => { + const { User } = await iamClient.send(new GetUserCommand({ UserName: userName })); + const taggedEmail = User?.Tags?.find((tag) => tag.Key === EMAIL_TAG)?.Value; + + if (!User?.Arn || taggedEmail?.toLowerCase() !== email.trim().toLowerCase()) { + throw new Error(`IAM user "${userName}" already exists and is not tagged ${EMAIL_TAG}=${email}`); + } + + // No login profile means disabled or half-created, so report failure instead of success. + if (!(await checkLoginProfileExists(iamClient, userName))) { + throw new Error(`IAM user "${userName}" exists without console access; enable or delete it first`); + } + + return User.Arn; +}; export const registerAccountActionCreation = (plugin: typeof awsConnector) => { plugin.registerAccountActions('iam-user', { @@ -28,71 +74,48 @@ export const registerAccountActionCreation = (plugin: typeof awsConnector) => { }, ], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_USER_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-create', }); 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 { accountId: existing.arn, created: false }; + const createdUser = await createUser({ iamClient, userName, email: input.email }); + + if (!createdUser) { + const existingArn = await getReusableUserArn({ iamClient, userName, email: input.email }); + + return { accountId: existingArn, 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); - await createLoginProfile({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName: created.userName, - password: temporaryPassword, - }); + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html + await iamClient.send( + new CreateLoginProfileCommand({ + UserName: userName, + Password: temporaryPassword, + PasswordResetRequired: true, + }), + ); // Deliver credentials via the Host email capability so the password only travels // through that side channel — never through this action's return value. The Host // injects the recipient from the invocation input; the connector supplies data only and the Host renders the wording. - const loginUrl = `https://${accountIdFromArn(created.arn)}.signin.aws.amazon.com/console`; + const loginUrl = `https://${accountIdFromArn(createdUser.arn)}.signin.aws.amazon.com/console`; sendEmail({ template: 'credentials', reason: 'onboarded', system: 'AWS', loginUrl, - username: created.userName, + username: userName, password: temporaryPassword, passwordChangeRequired: true, }); return { - accountId: created.arn, + accountId: createdUser.arn, created: true, }; }, diff --git a/connectors/aws/src/account-actions/delete.ts b/connectors/aws/src/account-actions/delete.ts index ccb9f3c..56d355c 100644 --- a/connectors/aws/src/account-actions/delete.ts +++ b/connectors/aws/src/account-actions/delete.ts @@ -1,10 +1,9 @@ +import { DeleteLoginProfileCommand, DeleteUserCommand } from '@aws-sdk/client-iam'; 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 { deleteLoginProfile } from '../utils/iam.login-profile.ts'; -import { deleteUser } from '../utils/iam.delete-user.ts'; +import { buildIamClient } from '../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; +import { checkTargetExists } from '../utils/iam.ts'; import { userNameFromArn } from '../utils/arn.ts'; export const registerAccountActionDelete = (plugin: typeof awsConnector) => { @@ -14,29 +13,20 @@ export const registerAccountActionDelete = (plugin: typeof awsConnector) => { endpoints: IAM_ACTION_ENDPOINTS, config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_USER_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-delete', }); const userName = userNameFromArn(input.accountId); - // DeleteUser fails if a login profile still exists — remove it first (best-effort). - try { - await deleteLoginProfile({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); - } catch (error) { - if (!String(error).includes('NoSuchEntity')) throw error; - } - - await deleteUser({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); + // DeleteUser fails while a login profile exists, so remove that first + // In an ideal world this wouldn't happen; this was introduced as part of CodeRabbit findings and it makes sense for a real world scenario + // (e.g.) User email is changed before the onboarding; so the IT can delete the email and onboard a new email + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUser.html + await checkTargetExists(iamClient.send(new DeleteLoginProfileCommand({ UserName: userName }))); + await iamClient.send(new DeleteUserCommand({ UserName: userName })); return { deleted: true }; }, diff --git a/connectors/aws/src/account-actions/disable.ts b/connectors/aws/src/account-actions/disable.ts index 4e1577d..3ba5d6a 100644 --- a/connectors/aws/src/account-actions/disable.ts +++ b/connectors/aws/src/account-actions/disable.ts @@ -1,9 +1,9 @@ +import { DeleteLoginProfileCommand } from '@aws-sdk/client-iam'; 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 { deleteLoginProfile } from '../utils/iam.login-profile.ts'; +import { buildIamClient } from '../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; +import { checkTargetExists } from '../utils/iam.ts'; import { userNameFromArn } from '../utils/arn.ts'; export const registerAccountActionDisable = (plugin: typeof awsConnector) => { @@ -13,27 +13,17 @@ export const registerAccountActionDisable = (plugin: typeof awsConnector) => { endpoints: IAM_ACTION_ENDPOINTS, config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_USER_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-disable', }); const userName = userNameFromArn(input.accountId); - try { - await deleteLoginProfile({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); - } catch (error) { - // No console access to begin with — already disabled, keep the action idempotent. - if (!String(error).includes('NoSuchEntity')) throw error; - } + // A missing login profile means the user is already disabled. + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteLoginProfile.html + await checkTargetExists(iamClient.send(new DeleteLoginProfileCommand({ UserName: userName }))); return { disabled: true }; }, diff --git a/connectors/aws/src/account-actions/enable.ts b/connectors/aws/src/account-actions/enable.ts index e6e5f66..c13b987 100644 --- a/connectors/aws/src/account-actions/enable.ts +++ b/connectors/aws/src/account-actions/enable.ts @@ -1,10 +1,9 @@ import { sendEmail } from '@open-iga/connector-sdk'; +import { CreateLoginProfileCommand } from '@aws-sdk/client-iam'; 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 { createLoginProfile } from '../utils/iam.login-profile.ts'; +import { buildIamClient } from '../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { generateTemporaryPassword } from '../utils/password.ts'; import { accountIdFromArn, userNameFromArn } from '../utils/arn.ts'; @@ -15,15 +14,8 @@ export const registerAccountActionEnable = (plugin: typeof awsConnector) => { endpoints: IAM_ACTION_ENDPOINTS, config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_USER_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-enable', }); @@ -32,12 +24,14 @@ export const registerAccountActionEnable = (plugin: typeof awsConnector) => { // Restore console access with a fresh one-time password the user must change at login. const temporaryPassword = generateTemporaryPassword(); - await createLoginProfile({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName, - password: temporaryPassword, - }); + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html + await iamClient.send( + new CreateLoginProfileCommand({ + UserName: userName, + Password: temporaryPassword, + PasswordResetRequired: true, + }), + ); const loginUrl = `https://${accountIdFromArn(input.accountId)}.signin.aws.amazon.com/console`; sendEmail({ diff --git a/connectors/aws/src/account-actions/read.ts b/connectors/aws/src/account-actions/read.ts index 4eefb07..843d83c 100644 --- a/connectors/aws/src/account-actions/read.ts +++ b/connectors/aws/src/account-actions/read.ts @@ -1,10 +1,8 @@ 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 { userExists } from '../utils/iam.user-exists.ts'; -import { hasLoginProfile } from '../utils/iam.login-profile.ts'; +import { buildIamClient } from '../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; +import { checkLoginProfileExists, checkUserExists } from '../utils/iam.ts'; import { userNameFromArn } from '../utils/arn.ts'; export const registerAccountActionRead = (plugin: typeof awsConnector) => { @@ -14,28 +12,21 @@ export const registerAccountActionRead = (plugin: typeof awsConnector) => { endpoints: IAM_ACTION_ENDPOINTS, config: [USER_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_USER_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-read', }); const userName = userNameFromArn(input.accountId); - const exists = await userExists({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); + const exists = await checkUserExists(iamClient, userName); + if (!exists) { return { exists: false, enabled: false }; } - // Enabled = the user still has console access (a login profile). - const enabled = await hasLoginProfile({ endpoint: IAM_ENDPOINT, credentials: assumed, userName }); + const enabled = await checkLoginProfileExists(iamClient, userName); return { exists: true, enabled }; }, From 2d81e27fbb7326b3782b41466adb2fbce2504ff7 Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:26:58 +0530 Subject: [PATCH 4/6] refactor: move login URL creation to util --- connectors/aws/src/account-actions/create.ts | 4 ++-- connectors/aws/src/account-actions/enable.ts | 4 ++-- connectors/aws/src/utils/arn.ts | 5 ++++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/connectors/aws/src/account-actions/create.ts b/connectors/aws/src/account-actions/create.ts index a405bbb..763c4a0 100644 --- a/connectors/aws/src/account-actions/create.ts +++ b/connectors/aws/src/account-actions/create.ts @@ -12,7 +12,7 @@ import { buildIamClient } from '../utils/client.ts'; import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { generateTemporaryPassword } from '../utils/password.ts'; import { checkLoginProfileExists } from '../utils/iam.ts'; -import { accountIdFromArn } from '../utils/arn.ts'; +import { buildLoginUrl } from '../utils/arn.ts'; import { userNameFromEmail } from '../utils/username.ts'; // IAM has no email field, so the email is saved as a user tag. @@ -103,7 +103,7 @@ export const registerAccountActionCreation = (plugin: typeof awsConnector) => { // Deliver credentials via the Host email capability so the password only travels // through that side channel — never through this action's return value. The Host // injects the recipient from the invocation input; the connector supplies data only and the Host renders the wording. - const loginUrl = `https://${accountIdFromArn(createdUser.arn)}.signin.aws.amazon.com/console`; + const loginUrl = buildLoginUrl(createdUser.arn); sendEmail({ template: 'credentials', reason: 'onboarded', diff --git a/connectors/aws/src/account-actions/enable.ts b/connectors/aws/src/account-actions/enable.ts index c13b987..7da1781 100644 --- a/connectors/aws/src/account-actions/enable.ts +++ b/connectors/aws/src/account-actions/enable.ts @@ -5,7 +5,7 @@ import { USER_MANAGEMENT_ROLE } from '../utils/role-config.ts'; import { buildIamClient } from '../utils/client.ts'; import { IAM_ACTION_ENDPOINTS } from '../utils/aws-endpoints.ts'; import { generateTemporaryPassword } from '../utils/password.ts'; -import { accountIdFromArn, userNameFromArn } from '../utils/arn.ts'; +import { buildLoginUrl, userNameFromArn } from '../utils/arn.ts'; export const registerAccountActionEnable = (plugin: typeof awsConnector) => { plugin.registerAccountActions('iam-user', { @@ -33,7 +33,7 @@ export const registerAccountActionEnable = (plugin: typeof awsConnector) => { }), ); - const loginUrl = `https://${accountIdFromArn(input.accountId)}.signin.aws.amazon.com/console`; + const loginUrl = buildLoginUrl(input.accountId); sendEmail({ template: 'credentials', reason: 'reenabled', diff --git a/connectors/aws/src/utils/arn.ts b/connectors/aws/src/utils/arn.ts index ba83aea..984a8d6 100644 --- a/connectors/aws/src/utils/arn.ts +++ b/connectors/aws/src/utils/arn.ts @@ -1,6 +1,9 @@ // IAM ARN shape: arn:aws:iam:::user/ // The account actions receive the ARN as the stable `accountId`, so both the account id and the username are derived from it. -export const accountIdFromArn = (arn: string): string => arn.split(':')[4] ?? ''; +const accountIdFromArn = (arn: string): string => arn.split(':')[4] ?? ''; + +// https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_sign-in.html +export const buildLoginUrl = (arn: string): string => `https://${accountIdFromArn(arn)}.signin.aws.amazon.com/console`; export const userNameFromArn = (arn: string): string => arn.split('/').pop() ?? ''; From e9fff1670e385f6c476eb30cff80c22d7e44cd9e Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:42:08 +0530 Subject: [PATCH 5/6] refactor: discovery, XML Parser plugin and E2E tests --- .changeset/quiet-pans-listen.md | 5 ++ bun.lock | 79 +++++++++++++------ connectors/aws/README.md | 3 +- .../aws/e2e/account-acctions.create.test.ts | 11 +-- .../aws/e2e/account-actions.lifecycle.test.ts | 23 +++--- connectors/aws/e2e/entitlements.test.ts | 10 ++- connectors/aws/package.json | 8 +- connectors/aws/src/aws-connector.ts | 16 ++-- .../iam-user-groups/discover.test.ts | 50 ++++++++++++ .../entitlements/iam-user-groups/discover.ts | 45 +++++------ .../src/entitlements/iam-user-groups/grant.ts | 33 +++----- .../src/entitlements/iam-user-groups/read.ts | 37 ++++----- .../entitlements/iam-user-groups/revoke.ts | 42 ++++------ connectors/aws/src/xml-parser.plugin.ts | 16 ++++ package.json | 4 +- 15 files changed, 229 insertions(+), 153 deletions(-) create mode 100644 .changeset/quiet-pans-listen.md create mode 100644 connectors/aws/src/entitlements/iam-user-groups/discover.test.ts create mode 100644 connectors/aws/src/xml-parser.plugin.ts diff --git a/.changeset/quiet-pans-listen.md b/.changeset/quiet-pans-listen.md new file mode 100644 index 0000000..d37a54f --- /dev/null +++ b/.changeset/quiet-pans-listen.md @@ -0,0 +1,5 @@ +--- +'@open-iga/aws': minor +--- + +Call AWS through the official SDK clients diff --git a/bun.lock b/bun.lock index 5d6e9b2..d7d7ac2 100644 --- a/bun.lock +++ b/bun.lock @@ -17,11 +17,10 @@ }, "connectors/aws": { "name": "@open-iga/aws", - "version": "0.0.1", + "version": "0.4.0", "dependencies": { - "aws4fetch": "catalog:", - "fast-xml-parser": "catalog:", - "zod": "catalog:", + "@aws-sdk/client-iam": "catalog:", + "@aws-sdk/client-sts": "catalog:", }, "devDependencies": { "@open-iga/connector-sdk": "workspace:*", @@ -49,14 +48,14 @@ }, }, "catalog": { + "@aws-sdk/client-iam": "3.1174.0", + "@aws-sdk/client-sts": "3.1174.0", "@changesets/cli": "3.0.3", "@extism/extism": "2.0.0-rc13", "@extism/js-pdk": "1.1.1", "@noble/hashes": "2.2.0", "@types/bun": "1.4.0", - "aws4fetch": "1.0.20", "bun-types": "1.4.0", - "fast-xml-parser": "5.11.0", "oxfmt": "0.61.0", "oxlint": "1.76.0", "oxlint-tsgolint": "7.0.2001", @@ -66,6 +65,40 @@ "zod": "4.4.3", }, "packages": { + "@aws-sdk/client-iam": ["@aws-sdk/client-iam@3.1174.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-EMDR4Wn6bvoRcIJ1zaL7VRMbqkqi88q/Er4IJcOTXN1h8wCJyBvkpbUPrjJYNNYaGYTI4yeq6LZARvBYPPVFag=="], + + "@aws-sdk/client-sts": ["@aws-sdk/client-sts@3.1174.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-Hu6QmYwrr0ZjFqBxWVsaftivvsNTNgMb7DIoQcPEzQLVm+nFATMKu4SmE95URnOfhIboO0yMFiGHdcjQpxp5aw=="], + + "@aws-sdk/core": ["@aws-sdk/core@3.981.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sERtJaZjzvBdFMm2uei4k0WwPNUJtIrMBH9h0AEw7G0KkhIbnN3e5ZcwGjbVKClR+rrJCmyL1jhtXkseE7DU4A=="], + + "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.85", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-IkIfFWmDbUyDEdNZpyAMmD3Givrm11I9UrqbgmLu1kUL/oh96QMqbfuHcbH08ErngZPDCQ2+7fW3U4r/W2k2Xg=="], + + "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.87", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-NWQNmfmllENW1TOpMfhEZeRzEvbSaFsS5yrb2TZJ0wu+fVL5hyVSfGVLd8HTWb2UECD2bCw/kDXaA6dR1VJf3g=="], + + "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.31", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/credential-provider-env": "^3.972.85", "@aws-sdk/credential-provider-http": "^3.972.87", "@aws-sdk/credential-provider-login": "^3.972.93", "@aws-sdk/credential-provider-process": "^3.972.85", "@aws-sdk/credential-provider-sso": "^3.973.29", "@aws-sdk/credential-provider-web-identity": "^3.972.91", "@aws-sdk/nested-clients": "^3.998.4", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-K6jkaKaAaVn9qAl/I14lzDHnYWHiESkxYLnmPYnJg3OfTRtWz39NerpidQIzqbMpoE/pmFqhgSJ+Sx/j1++8sA=="], + + "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.93", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/nested-clients": "^3.998.4", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-JofxFKJyNGLc9MmFMKy/vmjVwvNIWKNvHOf8rkXheH9x4+WJpIexhk1cqbmxWkodDYAodqGTiCEdBAVuiyH0iA=="], + + "@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.98", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.85", "@aws-sdk/credential-provider-http": "^3.972.87", "@aws-sdk/credential-provider-ini": "^3.973.31", "@aws-sdk/credential-provider-process": "^3.972.85", "@aws-sdk/credential-provider-sso": "^3.973.29", "@aws-sdk/credential-provider-web-identity": "^3.972.91", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-EpRL6YwSqvNlMjvRmwR2o3exV6DaETTdaWr1U7fZ456LQeK6ErOSluc6mWMY+OjkrBVFK4PgrU4NlERXTcgzKg=="], + + "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.85", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-19kc3xj6woR3Nb2NWFxowRkCnuR43jMFcTLLLCqkzB/rPxxE1+NfHnAP5fpXgrI4xRRgDzvWeDREjhGrJxqfxA=="], + + "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.29", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/nested-clients": "^3.998.4", "@aws-sdk/token-providers": "3.1175.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DJuKIs0bn5MZXc5uE1sf/R67YVC4ivFnL/dbKHukhdb5B6Fy80k8/BqiQykzXEqoT/qlSQaqYXU29hqVAYjcsg=="], + + "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.91", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/nested-clients": "^3.998.4", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-4k4beWSkxhwKeGMVfgppv/LwCfCd1zAycWgqop7GHkdvdNK9TTkWn299LjUQOgDMfBX2Sv08t+J1mAWKHatttw=="], + + "@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.4", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-8Vzg3e9ia6eHQStnoSn17asRNWHrf/ozgQslLMGOdM5JifyV+AAk1+lgVXcQMmrzgRhR9phRUEFxAOg/cBh7MQ=="], + + "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1175.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.1", "@aws-sdk/nested-clients": "^3.998.4", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-irdg9wmKjTDumWoZeXIM3ecgfriHEEm0Q05bjiHwGNRCXXexz+5roMS28IzKWELI5QX/XZjL1vvvaIyptlCfAQ=="], + + "@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], + + "@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.43", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og=="], + + "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.3.0", "", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="], + "@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], "@changesets/apply-release-plan": ["@changesets/apply-release-plan@8.1.1", "", { "dependencies": { "@changesets/config": "^4.0.1", "@changesets/format": "^0.1.2", "@changesets/git": "^4.0.1", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "import-meta-resolve": "^4.2.0", "jsonc-parser": "^3.3.1", "semver": "^7.8.1" } }, "sha512-nk2Hbq3M9NeHMdaIRBDvawKrQJzXB9sGyBUE5yWnIKtvdcNCPj75zBekJYr0gTT2ecJH3eFeTrc8eisPImcv0Q=="], @@ -124,8 +157,6 @@ "@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], - "@nodable/entities": ["@nodable/entities@3.0.0", "", {}, "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw=="], - "@open-iga/aws": ["@open-iga/aws@workspace:connectors/aws"], "@open-iga/connector-sdk": ["@open-iga/connector-sdk@workspace:packages/connector-sdk"], @@ -240,6 +271,18 @@ "@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="], + "@smithy/core": ["@smithy/core@3.41.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-fuZ34H1uizS3WgcX9VXG7Uy8od5A5/kCc+CR3NkHLNm2H/BE9AUHG02VIdu8ZB7FYhLqsr/RZbqAoXuOCg/Oxg=="], + + "@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.5.2", "", { "dependencies": { "@smithy/core": "^3.33.2", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg=="], + + "@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + + "@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + + "@smithy/types": ["@smithy/types@4.20.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A=="], + "@turbo/darwin-64": ["@turbo/darwin-64@2.10.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-/c9cSBRermWDv85oufLhoH6XRLOVbvzJLRd+WLyfJCP+i0HFLQj4PVNDrHcY17/ve5l8X0Oua4bJBqJUgJPnZA=="], "@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.10.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-8lpCCGWZBl9PIF8w8f2iEWrLMbHBWIfJeV6l2UEGqysD6HRIM4ySj/8R7HGEzbECJ4r/gnJcHmxEoG8yjFe64A=="], @@ -310,8 +353,6 @@ "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - "anynum": ["anynum@1.0.1", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="], - "archiver": ["archiver@7.0.1", "", { "dependencies": { "archiver-utils": "^5.0.2", "async": "^3.2.4", "buffer-crc32": "^1.0.0", "readable-stream": "^4.0.0", "readdir-glob": "^1.1.2", "tar-stream": "^3.0.0", "zip-stream": "^6.0.1" } }, "sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ=="], "archiver-utils": ["archiver-utils@5.0.2", "", { "dependencies": { "glob": "^10.0.0", "graceful-fs": "^4.2.0", "is-stream": "^2.0.1", "lazystream": "^1.0.0", "lodash": "^4.17.15", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA=="], @@ -322,8 +363,6 @@ "async-lock": ["async-lock@1.4.1", "", {}, "sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ=="], - "aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], - "b4a": ["b4a@1.8.1", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw=="], "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], @@ -344,6 +383,8 @@ "bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="], + "bowser": ["bowser@2.15.0", "", {}, "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ=="], + "brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="], "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], @@ -408,10 +449,6 @@ "fast-wrap-ansi": ["fast-wrap-ansi@0.2.2", "", { "dependencies": { "fast-string-width": "^3.0.2" } }, "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q=="], - "fast-xml-builder": ["fast-xml-builder@1.3.1", "", { "dependencies": { "path-expression-matcher": "^1.6.2", "xml-naming": "^0.3.0" } }, "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug=="], - - "fast-xml-parser": ["fast-xml-parser@5.11.0", "", { "dependencies": { "@nodable/entities": "^3.0.0", "fast-xml-builder": "^1.2.0", "is-unsafe": "^2.0.0", "path-expression-matcher": "^1.6.2", "strnum": "^2.4.2", "xml-naming": "^0.3.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-9IGxMqvqLOnqP+Egi1nqDHKv5k8aZ7r9n558enxcucmyVGEBNPAU+MOg/8jPIS7rO7sSq4gFm1/nHtiaubMruw=="], - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], @@ -438,8 +475,6 @@ "is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], - "is-unsafe": ["is-unsafe@2.0.0", "", {}, "sha512-2LdV822R+wmI86unXA93WCFpL6g+av8ynWk0nrHyJqGop5VoocYsSLFgN8jrfalT6iGeLNM4KXuVSsULP53kEA=="], - "isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], @@ -488,8 +523,6 @@ "package-manager-detector": ["package-manager-detector@1.8.0", "", {}, "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A=="], - "path-expression-matcher": ["path-expression-matcher@1.6.2", "", {}, "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ=="], - "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], "path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], @@ -552,8 +585,6 @@ "strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - "strnum": ["strnum@2.4.2", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw=="], - "tar-fs": ["tar-fs@3.1.3", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ=="], "tar-stream": ["tar-stream@3.2.0", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg=="], @@ -572,6 +603,8 @@ "tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="], + "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "turbo": ["turbo@2.10.7", "", { "optionalDependencies": { "@turbo/darwin-64": "2.10.7", "@turbo/darwin-arm64": "2.10.7", "@turbo/linux-64": "2.10.7", "@turbo/linux-arm64": "2.10.7", "@turbo/windows-64": "2.10.7", "@turbo/windows-arm64": "2.10.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-GHx6WExIFSKNJ5qMlzDpXBXlu9ApxaMjqxAVrCNcW94xf/+uqgIz41SAuRUMbXva2ExNAaY/h8V0q90SWSzmRw=="], "tweetnacl": ["tweetnacl@0.14.5", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="], @@ -594,8 +627,6 @@ "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - "xml-naming": ["xml-naming@0.3.0", "", {}, "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ=="], - "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], "yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], diff --git a/connectors/aws/README.md b/connectors/aws/README.md index 8fbe7c9..96380e2 100644 --- a/connectors/aws/README.md +++ b/connectors/aws/README.md @@ -6,7 +6,7 @@ Manages **IAM users** (account lifecycle) and **IAM user-group membership** (ent ## How it works -Base credentials call STS to **assume a least-privilege role per handler** (grant/discover/user-management), then hit the IAM Query API (SigV4-signed, `us-east-1` — IAM is global). +Base credentials call STS to **assume a least-privilege role per handler** (grant/discover/user-management), then call the IAM API through the official AWS SDK (`us-east-1` — IAM is global). Never returns secrets: a created user's temp password is delivered via the host email capability (only for now. phishing attack vector is high and email capability might be removed soon), not the action output. ## Config (connector-level) @@ -35,7 +35,6 @@ Account `id` = the user ARN. > [!NOTE] > Entitlement = membership in a pre-existing IAM group (groups are provisioned out-of-band; a group's own policy decides what it grants, e.g. cross-account role assumption) -> Group creation util in this connector is purely for testing and is not exposed outside | Action | Description | Extra config | | ---------- | ------------------------------------------------------------------- | -------------------------------------------------------------- | diff --git a/connectors/aws/e2e/account-acctions.create.test.ts b/connectors/aws/e2e/account-acctions.create.test.ts index c01b7ed..d75894e 100644 --- a/connectors/aws/e2e/account-acctions.create.test.ts +++ b/connectors/aws/e2e/account-acctions.create.test.ts @@ -1,6 +1,6 @@ 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'; +import { GetLoginProfileCommand, IAMClient } from '@aws-sdk/client-iam'; const tenant = { id: '000000000000' }; @@ -51,13 +51,14 @@ describe('account-actions.create', () => { // emulator with the forced-reset flag. The console password itself is write-only and // can't be read back — verifying the profile is the strongest no-real-AWS check. const userName = 'test.user'; - const profile = await getLoginProfile({ + const iamClient = new IAMClient({ + region: 'us-east-1', endpoint: process.env.AWS_ENDPOINT_URL ?? '', credentials: { accessKeyId: 'test', secretAccessKey: 'test' }, - userName, }); - expect(profile.userName).toBe(userName); - expect(profile.passwordResetRequired).toBe(true); + const { LoginProfile } = await iamClient.send(new GetLoginProfileCommand({ UserName: userName })); + expect(LoginProfile?.UserName).toBe(userName); + expect(LoginProfile?.PasswordResetRequired).toBe(true); }); it('should return the existing user without creating a new one for a duplicate email', async () => { diff --git a/connectors/aws/e2e/account-actions.lifecycle.test.ts b/connectors/aws/e2e/account-actions.lifecycle.test.ts index ee86e5a..a282e3e 100644 --- a/connectors/aws/e2e/account-actions.lifecycle.test.ts +++ b/connectors/aws/e2e/account-actions.lifecycle.test.ts @@ -1,20 +1,17 @@ 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'; +import { checkTargetExists } from '../src/utils/iam.ts'; +import { GetLoginProfileCommand, IAMClient } from '@aws-sdk/client-iam'; const tenant = { id: '000000000000' }; const endpoint = () => process.env.AWS_ENDPOINT_URL ?? ''; const credentials = { accessKeyId: 'test', secretAccessKey: 'test' }; -const hasLoginProfile = async (userName: string): Promise => { - try { - await getLoginProfile({ endpoint: endpoint(), credentials, userName }); - return true; - } catch (error) { - if (String(error).includes('NoSuchEntity')) return false; - throw error; - } +const checkLoginProfile = async (userName: string): Promise => { + const iamClient = new IAMClient({ region: 'us-east-1', endpoint: endpoint(), credentials }); + + return checkTargetExists(iamClient.send(new GetLoginProfileCommand({ UserName: userName }))); }; describe('account-actions.lifecycle', () => { @@ -53,7 +50,7 @@ describe('account-actions.lifecycle', () => { expect(created.ok).toBe(true); if (!created.ok) return; const { accountId } = created.output; - expect(await hasLoginProfile(userName)).toBe(true); + expect(await checkLoginProfile(userName)).toBe(true); // Read — exists and enabled. const afterCreate = await host.callAccountActions('iam-user', 'read', { tenant, accountId }); @@ -64,7 +61,7 @@ describe('account-actions.lifecycle', () => { const disabled = await host.callAccountActions('iam-user', 'disable', { tenant, accountId }); expect(disabled.ok).toBe(true); if (disabled.ok) expect(disabled.output.disabled).toBe(true); - expect(await hasLoginProfile(userName)).toBe(false); + expect(await checkLoginProfile(userName)).toBe(false); // Read — still exists, now disabled. const afterDisable = await host.callAccountActions('iam-user', 'read', { tenant, accountId }); @@ -75,14 +72,14 @@ describe('account-actions.lifecycle', () => { const enabled = await host.callAccountActions('iam-user', 'enable', { tenant, accountId }); expect(enabled.ok).toBe(true); if (enabled.ok) expect(enabled.output.enabled).toBe(true); - expect(await hasLoginProfile(userName)).toBe(true); + expect(await checkLoginProfile(userName)).toBe(true); expect(host.hostFunctions.sentEmails.at(-1)?.reason).toBe('reenabled'); // Delete — user removed entirely. const deleted = await host.callAccountActions('iam-user', 'delete', { tenant, accountId }); expect(deleted.ok).toBe(true); if (deleted.ok) expect(deleted.output.deleted).toBe(true); - expect(await hasLoginProfile(userName)).toBe(false); + expect(await checkLoginProfile(userName)).toBe(false); // Read — no longer exists. const afterDelete = await host.callAccountActions('iam-user', 'read', { tenant, accountId }); diff --git a/connectors/aws/e2e/entitlements.test.ts b/connectors/aws/e2e/entitlements.test.ts index 793516d..76089ed 100644 --- a/connectors/aws/e2e/entitlements.test.ts +++ b/connectors/aws/e2e/entitlements.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'bun:test'; 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'; +import { CreateGroupCommand, IAMClient } from '@aws-sdk/client-iam'; const tenant = { id: '000000000000' }; @@ -28,9 +28,11 @@ describe('entitlements', () => { }); // Seed assignable groups plus one internal group excluded by the operator regex. - await createGroup({ endpoint: endpoint(), credentials, groupName: 'ReadOnly', path: '/' }); - await createGroup({ endpoint: endpoint(), credentials, groupName: 'Admins', path: '/' }); - await createGroup({ endpoint: endpoint(), credentials, groupName: 'ci-deployer', path: '/' }); + const iamClient = new IAMClient({ region: 'us-east-1', endpoint: endpoint(), credentials }); + + for (const groupName of ['ReadOnly', 'Admins', 'ci-deployer']) { + await iamClient.send(new CreateGroupCommand({ GroupName: groupName, Path: '/' })); + } }); afterAll(async () => { diff --git a/connectors/aws/package.json b/connectors/aws/package.json index 539b46c..5e2daec 100644 --- a/connectors/aws/package.json +++ b/connectors/aws/package.json @@ -3,14 +3,14 @@ "version": "0.5.0", "type": "module", "scripts": { - "compile": "open-iga compile --entryPoint src/aws-connector.ts", + "compile": "open-iga compile --entryPoint src/aws-connector.ts --plugin src/xml-parser.plugin.ts", "test": "bun test", + "compile-and-test": "bun run compile && bun run test", "typecheck": "bun --check" }, "dependencies": { - "aws4fetch": "catalog:", - "fast-xml-parser": "catalog:", - "zod": "catalog:" + "@aws-sdk/client-iam": "catalog:", + "@aws-sdk/client-sts": "catalog:" }, "devDependencies": { "@open-iga/connector-sdk": "workspace:*", diff --git a/connectors/aws/src/aws-connector.ts b/connectors/aws/src/aws-connector.ts index 4594f0c..83c7cce 100644 --- a/connectors/aws/src/aws-connector.ts +++ b/connectors/aws/src/aws-connector.ts @@ -4,10 +4,10 @@ import { registerAccountActionDisable } from './account-actions/disable.ts'; import { registerAccountActionEnable } from './account-actions/enable.ts'; import { registerAccountActionDelete } from './account-actions/delete.ts'; import { registerAccountActionRead } from './account-actions/read.ts'; -import { registerEntitlementDiscover } from './entitlements/iam-user-groups/discover.ts'; -import { registerEntitlementGrant } from './entitlements/iam-user-groups/grant.ts'; -import { registerEntitlementRevoke } from './entitlements/iam-user-groups/revoke.ts'; -import { registerEntitlementRead } from './entitlements/iam-user-groups/read.ts'; +import { registerIamUserGroupsDiscover } from './entitlements/iam-user-groups/discover.ts'; +import { registerIamUserGroupGrant } from './entitlements/iam-user-groups/grant.ts'; +import { registerIamUserGroupsRevoke } from './entitlements/iam-user-groups/revoke.ts'; +import { registerIamUserGroupsRead } from './entitlements/iam-user-groups/read.ts'; export const awsConnector = new OpenIgaConnector({ name: 'AWS', @@ -35,9 +35,9 @@ registerAccountActionEnable(awsConnector); registerAccountActionDelete(awsConnector); registerAccountActionRead(awsConnector); -registerEntitlementDiscover(awsConnector); -registerEntitlementGrant(awsConnector); -registerEntitlementRevoke(awsConnector); -registerEntitlementRead(awsConnector); +registerIamUserGroupsDiscover(awsConnector); +registerIamUserGroupGrant(awsConnector); +registerIamUserGroupsRevoke(awsConnector); +registerIamUserGroupsRead(awsConnector); export default awsConnector; diff --git a/connectors/aws/src/entitlements/iam-user-groups/discover.test.ts b/connectors/aws/src/entitlements/iam-user-groups/discover.test.ts new file mode 100644 index 0000000..f463f3e --- /dev/null +++ b/connectors/aws/src/entitlements/iam-user-groups/discover.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it } from 'bun:test'; +import { awsConnector } from '../../aws-connector.ts'; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; +}); + +const assumeRoleXml = `ASIAsecrettoken`; + +const buildListGroupsXml = (isTruncated: boolean) => { + const marker = isTruncated ? 'next-page' : ''; + + return `${isTruncated}${marker}arn:aws:iam::1:group/aa/`; +}; + +const discoverGroups = async (isTruncated: boolean, cursor?: string) => { + const requestBodies: string[] = []; + globalThis.fetch = (async (_url: string, { body }: { body: string }) => { + requestBodies.push(body); + + return new Response(body.includes('AssumeRole') ? assumeRoleXml : buildListGroupsXml(isTruncated)); + }) as never; + + const discover = awsConnector.entitlementRegistry.get('iam-user-group')!.get('discover')!; + const output = await discover.handler({ + config: { AWS_REGION: 'us-east-1', AWS_ACCESS_KEY_ID: 'AKIA', AWS_SECRET_ACCESS_KEY: 'secret' }, + input: { tenant: { id: '1' }, cursor }, + } as never); + + return { output, requestBodies }; +}; + +describe('discover', () => { + it('should send the cursor and return the next one', async () => { + const { output, requestBodies } = await discoverGroups(true, 'previous-page'); + + expect(requestBodies.at(-1)).toContain('Marker=previous-page'); + expect(output).toEqual({ + entitlements: [{ entitlementId: 'arn:aws:iam::1:group/a', name: 'a' }], + nextCursor: 'next-page', + }); + }); + + it('should omit the next cursor on the last page', async () => { + const { output } = await discoverGroups(false); + + expect(output).not.toHaveProperty('nextCursor'); + }); +}); diff --git a/connectors/aws/src/entitlements/iam-user-groups/discover.ts b/connectors/aws/src/entitlements/iam-user-groups/discover.ts index 090201e..a2d1e38 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/discover.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/discover.ts @@ -1,9 +1,8 @@ +import { ListGroupsCommand } from '@aws-sdk/client-iam'; 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'; -import { resolveRegion } from '../../utils/region.ts'; +import { buildIamClient } from '../../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; // Parse ';' separated patterns into RegEx const parseExcludePatterns = (raw: string | null): RegExp[] => { @@ -22,7 +21,7 @@ const parseExcludePatterns = (raw: string | null): RegExp[] => { }); }; -export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { +export const registerIamUserGroupsDiscover = (plugin: typeof awsConnector) => { plugin.registerEntitlements('iam-user-group', { type: 'discover', description: 'Discover assignable IAM user groups for the entitlement catalog', @@ -41,39 +40,33 @@ export const registerEntitlementDiscover = (plugin: typeof awsConnector) => { }, ], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - const excludePatterns = parseExcludePatterns(config.AWS_GROUP_EXCLUDE_PATTERNS); - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_GROUP_DISCOVERY_ROLE, roleSessionName: 'openiga-aws-iam-user-group-discover', }); - // The AWS marker is the cursor: one page per call - const { groups, nextMarker } = await listGroups({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - marker: input.cursor, - }); + // The AWS marker is the cursor: one page per call. + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html + const { Groups, IsTruncated, Marker } = await iamClient.send( + new ListGroupsCommand({ Marker: input.cursor }), + ); - const catalog = groups.filter( + const catalog = (Groups ?? []).filter( (group) => - !excludePatterns.some((pattern) => pattern.test(group.groupName) || pattern.test(group.path)), + !excludePatterns.some( + (pattern) => pattern.test(group.GroupName ?? '') || pattern.test(group.Path ?? ''), + ), ); return { - entitlements: catalog.map((group) => ({ - entitlementId: group.arn, - name: group.groupName, + entitlements: catalog.map(({ Arn, GroupName }) => ({ + entitlementId: Arn!, + name: GroupName ?? 'MISSING_GROUP_NAME', })), - ...(nextMarker ? { nextCursor: nextMarker } : {}), + ...(IsTruncated && Marker ? { nextCursor: Marker } : {}), }; }, }); diff --git a/connectors/aws/src/entitlements/iam-user-groups/grant.ts b/connectors/aws/src/entitlements/iam-user-groups/grant.ts index 9d14f6e..48e83fe 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/grant.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/grant.ts @@ -1,37 +1,30 @@ +import { AddUserToGroupCommand } from '@aws-sdk/client-iam'; 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'; +import { buildIamClient } from '../../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { userNameFromArn, nameFromArn } from '../../utils/arn.ts'; -import { resolveRegion } from '../../utils/region.ts'; -export const registerEntitlementGrant = (plugin: typeof awsConnector) => { +export const registerIamUserGroupGrant = (plugin: typeof awsConnector) => { plugin.registerEntitlements('iam-user-group', { type: 'grant', description: 'Grant a user membership in an IAM user group', endpoints: IAM_ACTION_ENDPOINTS, config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_ENTITLEMENT_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-group-grant', }); - await addUserToGroup({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName: userNameFromArn(input.accountId), - groupName: nameFromArn(input.entitlementId), - }); + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html + await iamClient.send( + new AddUserToGroupCommand({ + UserName: userNameFromArn(input.accountId), + GroupName: nameFromArn(input.entitlementId), + }), + ); return { granted: true }; }, diff --git a/connectors/aws/src/entitlements/iam-user-groups/read.ts b/connectors/aws/src/entitlements/iam-user-groups/read.ts index 069b8d3..d15e16a 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/read.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/read.ts @@ -1,38 +1,35 @@ +import { paginateListGroupsForUser } from '@aws-sdk/client-iam'; 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'; +import { buildIamClient } from '../../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; import { userNameFromArn } from '../../utils/arn.ts'; -import { resolveRegion } from '../../utils/region.ts'; -export const registerEntitlementRead = (plugin: typeof awsConnector) => { +export const registerIamUserGroupsRead = (plugin: typeof awsConnector) => { plugin.registerEntitlements('iam-user-group', { type: 'read', description: 'Read the IAM user groups a user belongs to (for entitlement drift detection)', endpoints: IAM_ACTION_ENDPOINTS, config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_ENTITLEMENT_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-group-read', }); - const groups = await listGroupsAssignedToUser({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName: userNameFromArn(input.accountId), - }); + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html + const pages = paginateListGroupsForUser( + { client: iamClient }, + { UserName: userNameFromArn(input.accountId) }, + ); + const entitlementIds: string[] = []; + + for await (const page of pages) { + entitlementIds.push(...(page.Groups ?? []).map((group) => group.Arn!)); + } - return { entitlementIds: groups.map((group) => group.arn) }; + return { entitlementIds }; }, }); }; diff --git a/connectors/aws/src/entitlements/iam-user-groups/revoke.ts b/connectors/aws/src/entitlements/iam-user-groups/revoke.ts index 2be6edd..28f8c8e 100644 --- a/connectors/aws/src/entitlements/iam-user-groups/revoke.ts +++ b/connectors/aws/src/entitlements/iam-user-groups/revoke.ts @@ -1,42 +1,34 @@ +import { RemoveUserFromGroupCommand } from '@aws-sdk/client-iam'; 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'; +import { buildIamClient } from '../../utils/client.ts'; +import { IAM_ACTION_ENDPOINTS } from '../../utils/aws-endpoints.ts'; +import { checkTargetExists } from '../../utils/iam.ts'; import { userNameFromArn, nameFromArn } from '../../utils/arn.ts'; -import { resolveRegion } from '../../utils/region.ts'; -export const registerEntitlementRevoke = (plugin: typeof awsConnector) => { +export const registerIamUserGroupsRevoke = (plugin: typeof awsConnector) => { plugin.registerEntitlements('iam-user-group', { type: 'revoke', description: "Revoke a user's membership in an IAM user group", endpoints: IAM_ACTION_ENDPOINTS, config: [ENTITLEMENT_MANAGEMENT_ROLE], handler: async ({ config, input }) => { - const region = resolveRegion(config.AWS_REGION); - - const assumed = await assumeRole({ - endpoint: stsEndpoint(region), - region, - credentials: { - accessKeyId: config.AWS_ACCESS_KEY_ID, - secretAccessKey: config.AWS_SECRET_ACCESS_KEY, - }, + const iamClient = await buildIamClient({ + config, roleArn: config.AWS_ENTITLEMENT_MANAGEMENT_ROLE, roleSessionName: 'openiga-aws-iam-user-group-revoke', }); - try { - await removeUserFromGroup({ - endpoint: IAM_ENDPOINT, - credentials: assumed, - userName: userNameFromArn(input.accountId), - groupName: nameFromArn(input.entitlementId), - }); - } catch (error) { - // Membership already absent — keep revoke idempotent. - if (!String(error).includes('NoSuchEntity')) throw error; - } + // A missing membership means the group is already revoked. + // https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html + await checkTargetExists( + iamClient.send( + new RemoveUserFromGroupCommand({ + UserName: userNameFromArn(input.accountId), + GroupName: nameFromArn(input.entitlementId), + }), + ), + ); return { revoked: true }; }, diff --git a/connectors/aws/src/xml-parser.plugin.ts b/connectors/aws/src/xml-parser.plugin.ts new file mode 100644 index 0000000..87dc737 --- /dev/null +++ b/connectors/aws/src/xml-parser.plugin.ts @@ -0,0 +1,16 @@ +import type { BunPlugin } from 'bun'; + +const BROWSER_XML_PARSER = /xml-builder[\\/]dist-es[\\/]xml-parser\.browser\.js$/; + +// The wasm runtime has no DOMParser, so use the AWS SDK's own pure JS XML parser. +const xmlParserPlugin: BunPlugin = { + name: 'xml-parser', + setup(build) { + build.onLoad({ filter: BROWSER_XML_PARSER }, () => ({ + loader: 'js', + contents: "export { parseXML } from './xml-parser.js';", + })); + }, +}; + +export default xmlParserPlugin; diff --git a/package.json b/package.json index a2f229c..ef61039 100644 --- a/package.json +++ b/package.json @@ -6,14 +6,14 @@ "packages/*" ], "catalog": { + "@aws-sdk/client-iam": "3.1174.0", + "@aws-sdk/client-sts": "3.1174.0", "@changesets/cli": "3.0.3", "@extism/js-pdk": "1.1.1", "@extism/extism": "2.0.0-rc13", "@noble/hashes": "2.2.0", "@types/bun": "1.4.0", - "aws4fetch": "1.0.20", "bun-types": "1.4.0", - "fast-xml-parser": "5.11.0", "oxfmt": "0.61.0", "oxlint": "1.76.0", "oxlint-tsgolint": "7.0.2001", From d666df841fa05989d556a59fd3f37558eef69a12 Mon Sep 17 00:00:00 2001 From: Prasanna Ramesh <44441571+Prasanna-ramesh@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:50:39 +0530 Subject: [PATCH 6/6] fix: trim the stored email tag before comparing --- connectors/aws/src/account-actions/create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connectors/aws/src/account-actions/create.ts b/connectors/aws/src/account-actions/create.ts index 763c4a0..b03a84e 100644 --- a/connectors/aws/src/account-actions/create.ts +++ b/connectors/aws/src/account-actions/create.ts @@ -47,7 +47,7 @@ const getReusableUserArn = async ({ iamClient, userName, email }: CreateUserArgs const { User } = await iamClient.send(new GetUserCommand({ UserName: userName })); const taggedEmail = User?.Tags?.find((tag) => tag.Key === EMAIL_TAG)?.Value; - if (!User?.Arn || taggedEmail?.toLowerCase() !== email.trim().toLowerCase()) { + if (!User?.Arn || taggedEmail?.trim().toLowerCase() !== email.trim().toLowerCase()) { throw new Error(`IAM user "${userName}" already exists and is not tagged ${EMAIL_TAG}=${email}`); }