Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-pans-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@open-iga/aws': minor
---

Call AWS through the official SDK clients
79 changes: 55 additions & 24 deletions bun.lock

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions connectors/aws/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 |
| ---------- | ------------------------------------------------------------------- | -------------------------------------------------------------- |
Expand Down
11 changes: 6 additions & 5 deletions connectors/aws/e2e/account-acctions.create.test.ts
Original file line number Diff line number Diff line change
@@ -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' };

Expand Down Expand Up @@ -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 () => {
Expand Down
23 changes: 10 additions & 13 deletions connectors/aws/e2e/account-actions.lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> => {
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<boolean> => {
const iamClient = new IAMClient({ region: 'us-east-1', endpoint: endpoint(), credentials });

return checkTargetExists(iamClient.send(new GetLoginProfileCommand({ UserName: userName })));
};

describe('account-actions.lifecycle', () => {
Expand Down Expand Up @@ -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 });
Expand All @@ -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 });
Expand All @@ -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 });
Expand Down
10 changes: 6 additions & 4 deletions connectors/aws/e2e/entitlements.test.ts
Original file line number Diff line number Diff line change
@@ -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' };

Expand All @@ -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 () => {
Expand Down
8 changes: 4 additions & 4 deletions connectors/aws/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
123 changes: 73 additions & 50 deletions connectors/aws/src/account-actions/create.ts
Original file line number Diff line number Diff line change
@@ -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 { buildLoginUrl } from '../utils/arn.ts';
import { userNameFromEmail } from '../utils/username.ts';

// ARN shape: arn:aws:iam::<accountId>:user/<name>. 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<string> => {
const { User } = await iamClient.send(new GetUserCommand({ UserName: userName }));
const taggedEmail = User?.Tags?.find((tag) => tag.Key === EMAIL_TAG)?.Value;

if (!User?.Arn || taggedEmail?.trim().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', {
Expand All @@ -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 = buildLoginUrl(createdUser.arn);
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,
};
},
Expand Down
34 changes: 12 additions & 22 deletions connectors/aws/src/account-actions/delete.ts
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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 };
},
Expand Down
Loading