Skip to content

Commit ab54179

Browse files
authored
Send user-bot DMs through Slack using the token in SSM (#214)
1 parent 1c93e6f commit ab54179

10 files changed

Lines changed: 376 additions & 26 deletions

File tree

‎lambda/user-bot/README.md‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# user-bot
22

3-
A Lambda that gives each new IAM user a temporary AWS console password and sends it to them as a Slack DM, with sign-in instructions. Tracked in [#209](https://github.com/hackforla/devops-security/issues/209).
4-
5-
> **Not sending DMs yet.** The deployed function uses `StubMessageSender`, which sends nothing and logs who would have been messaged. `SlackMessageSender` is written and tested, but switching to it needs a Slack app, its bot token, a secret the function can read, and permission to read it. None of these exist yet. Until then, the bot resets the password and the new user does not receive it, which is no worse than before: the password Terraform generates was never sent to anyone either.
3+
A Lambda that gives each new IAM user a temporary AWS console password and sends it to them as a Slack DM, with sign-in instructions. Built in [#209](https://github.com/hackforla/devops-security/issues/209); connected to Slack in [#212](https://github.com/hackforla/devops-security/issues/212).
64

75
## When it runs
86

@@ -23,29 +21,57 @@ It reads the user's tags and **does nothing at all** (no password change, no mes
2321

2422
When both hold, it:
2523

26-
1. generates a 20-character password containing all four character classes;
27-
2. sets it with `UpdateLoginProfile` and `PasswordResetRequired: true`, so the user must replace it at first sign-in;
28-
3. sends the user a message with the sign-in page, their IAM user name and the temporary password.
24+
1. reads the Slack bot token (see [The Slack token](#the-slack-token)). **If that fails, it stops here and the user's password is not touched;**
25+
2. generates a 20-character password containing all four character classes;
26+
3. sets it with `UpdateLoginProfile` and `PasswordResetRequired: true`, so the user must replace it at first sign-in;
27+
4. DMs the user, as the Slack app, with the sign-in page, their IAM user name and the temporary password.
28+
29+
Step 1 comes before the reset on purpose. Reading the token at send time would mean a bad token leaves the user with a new password that nobody received.
2930

3031
Every skip is logged with its reason and the user name. **The password is never logged**, on any path; the tests assert this.
3132

3233
The `managed-by` check is also enforced by IAM. The execution role may call `UpdateLoginProfile` only on users carrying that tag, so a bug or a hand-crafted invocation still cannot reset anyone else's password, such as an admin or a user tagged `exempt`. If you change the check in `src/handler.ts`, change the policy in `terraform/user-bot.tf` with it.
3334

3435
If sending fails after the password was changed, the function throws. Lambda's asynchronous retry then runs it again from the start, which sets a fresh password and sends again.
3536

37+
## The Slack token
38+
39+
The bot posts as a Slack app with the `chat:write` bot scope, and the app's **Messages tab** is turned on so that users can see the DM thread. Its bot token (`xoxb-…`) is stored in the SSM Parameter Store `SecureString` **`/user-bot/slack-bot-token`**, in us-east-1. The function finds it through its `SLACK_TOKEN_PARAMETER` environment variable.
40+
41+
Terraform (`terraform/user-bot.tf`) creates the parameter with a placeholder through the write-only `value_wo`. The real token is set by hand, so it never appears in git **or in Terraform state**. Read the comment above that resource before changing it: bumping `value_wo_version` writes the placeholder back over the real token.
42+
43+
To set or rotate the token, run this from your own terminal. It reads the token from a prompt, so it stays out of your shell history:
44+
45+
```bash
46+
read -rs SLACK_TOKEN && MSYS_NO_PATHCONV=1 aws ssm put-parameter --region us-east-1 \
47+
--name /user-bot/slack-bot-token --type SecureString --overwrite --value "$SLACK_TOKEN"; unset SLACK_TOKEN
48+
```
49+
50+
`MSYS_NO_PATHCONV=1` only matters in Git Bash on Windows, which would otherwise rewrite `/user-bot/...` into a Windows path.
51+
52+
The function keeps the token for the life of an execution environment, so a rotated token is picked up as environments are recycled. To pick it up at once, redeploy: run **Deploy user-bot Lambda** from the Actions tab.
53+
54+
If the token is missing, unreadable, or still the placeholder (anything not starting `xoxb-`), every user the bot would act on is **refused**:
55+
- the password is left unchanged;
56+
- an error naming the parameter is logged (never its value);
57+
- the invocation fails, so it shows up in the function's error metrics.
58+
59+
A failed read is not cached, so the next new user is tried again.
60+
3661
## Layout
3762

3863
```
3964
src/
40-
index.ts Lambda entry point; wires the handler to the stub sender
65+
index.ts Lambda entry point; wires the handler to SlackMessageSender
4166
handler.ts the logic above
67+
slack-token.ts reads and caches the token from SSM
4268
password.ts password generation
4369
message.ts the message text and sign-in URL
4470
logger.ts JSON-line logger
4571
senders/
4672
types.ts MessageSender interface
4773
slack.ts SlackMessageSender (chat.postMessage)
48-
stub.ts StubMessageSender (logs only)
74+
stub.ts StubMessageSender (logs only; not deployed, kept for local runs and tests)
4975
test/ Vitest unit tests; AWS is mocked with aws-sdk-client-mock, Slack by mocking fetch
5076
```
5177

@@ -69,7 +95,7 @@ Two halves, each with its own workflow:
6995

7096
| | Managed by | Runs when |
7197
|---|---|---|
72-
| The function's configuration, execution role, log group, EventBridge rule, and the deploy role | `terraform/user-bot.tf` and `terraform/aws-gha-oidc-providers.tf`, via the existing `terraform-plan.yaml` / `terraform-apply.yaml` | a `.tf` file changes |
98+
| The function's configuration, execution role, log group, EventBridge rule, the token parameter (not its value), and the deploy role | `terraform/user-bot.tf` and `terraform/aws-gha-oidc-providers.tf`, via the existing `terraform-plan.yaml` / `terraform-apply.yaml` | a `.tf` file changes |
7399
| The function's **code** | `.github/workflows/user-bot-deploy.yml` | a change under `lambda/user-bot/` merges to `main` |
74100

75101
Pull requests touching `lambda/user-bot/` run `.github/workflows/user-bot-test.yml`, which typechecks, tests and builds with no AWS credentials.

‎lambda/user-bot/package-lock.json‎

Lines changed: 20 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎lambda/user-bot/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
"test": "vitest run"
1111
},
1212
"dependencies": {
13-
"@aws-sdk/client-iam": "^3.1146.0"
13+
"@aws-sdk/client-iam": "^3.1146.0",
14+
"@aws-sdk/client-ssm": "^3.1146.0"
1415
},
1516
"devDependencies": {
1617
"@types/aws-lambda": "^8.10.164",

‎lambda/user-bot/src/handler.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ export type Result =
4949

5050
export interface Dependencies {
5151
iam: IAMClient;
52-
sender: MessageSender;
52+
// Called after the tag checks and before the password is touched. Anything the
53+
// sender needs that can fail -- reading the Slack token, above all -- belongs in
54+
// here, so that a failure leaves the user's password unchanged instead of resetting
55+
// it to something nobody receives.
56+
getSender: () => Promise<MessageSender>;
5357
logger: Logger;
5458
generatePassword?: () => string;
5559
}
@@ -74,7 +78,7 @@ function errorName(error: unknown): string {
7478
}
7579

7680
export function createHandler(deps: Dependencies) {
77-
const { iam, sender, logger } = deps;
81+
const { iam, getSender, logger } = deps;
7882
const generatePassword = deps.generatePassword ?? defaultGeneratePassword;
7983

8084
function skip(reason: SkipReason, userName?: string): Result {
@@ -123,6 +127,23 @@ export function createHandler(deps: Dependencies) {
123127
return skip("invalid-slack-id", userName);
124128
}
125129

130+
// Resolved before the password is reset, not when sending. If the Slack token is
131+
// missing, unreadable or still the placeholder, the user keeps their current
132+
// password. Errors from here are logged with their message, so getSender must never
133+
// put a secret in one (SlackTokenError names the parameter, not its value).
134+
let sender: MessageSender;
135+
try {
136+
sender = await getSender();
137+
} catch (error) {
138+
const detail = error instanceof Error ? error.message : undefined;
139+
logger.error("No message sender available; password left unchanged", {
140+
userName,
141+
error: errorName(error),
142+
detail,
143+
});
144+
throw new Error(`No message sender available for ${userName}: ${errorName(error)}`);
145+
}
146+
126147
const password = generatePassword();
127148

128149
try {

‎lambda/user-bot/src/index.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
import { IAMClient } from "@aws-sdk/client-iam";
2+
import { SSMClient } from "@aws-sdk/client-ssm";
23

34
import { createHandler } from "./handler";
45
import { consoleLogger } from "./logger";
5-
import { StubMessageSender } from "./senders/stub";
6+
import { SlackMessageSender } from "./senders/slack";
7+
import { createSlackTokenLoader } from "./slack-token";
8+
9+
// SLACK_TOKEN_PARAMETER names the SSM SecureString holding the Slack bot token; it is
10+
// set by terraform/user-bot.tf. The token is read on the first invocation that needs to
11+
// send, not at import, so a missing token surfaces as a logged refusal for that user
12+
// rather than as a cold-start crash -- and always before their password is touched.
13+
const loadSlackToken = createSlackTokenLoader(new SSMClient({}), process.env.SLACK_TOKEN_PARAMETER);
614

7-
// Wired to the stub sender on purpose. Switching to SlackMessageSender needs a Slack
8-
// app, its bot token, a secret the function can read, and permission to read it --
9-
// none of which exist yet. See the "Out of scope" section of
10-
// hackforla/devops-security#209.
1115
export const handler = createHandler({
1216
iam: new IAMClient({}),
13-
sender: new StubMessageSender(consoleLogger),
17+
getSender: async () => new SlackMessageSender(await loadSlackToken()),
1418
logger: consoleLogger,
1519
});

‎lambda/user-bot/src/senders/stub.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import type { Logger } from "../logger";
22
import type { DirectMessage, MessageSender } from "./types";
33

4-
// What the deployed Lambda uses until it is switched to SlackMessageSender, which
5-
// needs a Slack app and bot token that do not exist yet. It sends nothing and logs
6-
// who would have been messaged, never the message itself.
4+
// Not deployed: index.ts wires the Lambda to SlackMessageSender. Kept for local runs and
5+
// tests, where sending a real DM is unwanted. It sends nothing and logs who would have
6+
// been messaged, never the message itself.
77
export class StubMessageSender implements MessageSender {
88
constructor(private readonly logger: Logger) {}
99

‎lambda/user-bot/src/slack-token.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { GetParameterCommand, type SSMClient } from "@aws-sdk/client-ssm";
2+
3+
// Slack bot tokens start with this. Terraform creates the parameter holding a
4+
// placeholder, so this is also how a token that was never set is caught.
5+
export const SLACK_BOT_TOKEN_PREFIX = "xoxb-";
6+
7+
// Messages name the parameter and the failure, never the value.
8+
export class SlackTokenError extends Error {
9+
override name = "SlackTokenError";
10+
}
11+
12+
function errorName(error: unknown): string {
13+
return error instanceof Error ? error.name : "UnknownError";
14+
}
15+
16+
// Returns a function that reads the token from SSM Parameter Store once per execution
17+
// environment and reuses it. A failed read is not cached, so the next invocation tries
18+
// again rather than failing forever on a rejected promise; that matters right after the
19+
// token is first set or rotated.
20+
export function createSlackTokenLoader(
21+
ssm: SSMClient,
22+
parameterName: string | undefined,
23+
): () => Promise<string> {
24+
let cached: Promise<string> | undefined;
25+
26+
async function load(): Promise<string> {
27+
if (!parameterName) {
28+
throw new SlackTokenError("SLACK_TOKEN_PARAMETER is not set");
29+
}
30+
31+
let value: string | undefined;
32+
try {
33+
const output = await ssm.send(new GetParameterCommand({ Name: parameterName, WithDecryption: true }));
34+
value = output.Parameter?.Value;
35+
} catch (error) {
36+
throw new SlackTokenError(`could not read ${parameterName}: ${errorName(error)}`);
37+
}
38+
39+
if (!value?.startsWith(SLACK_BOT_TOKEN_PREFIX)) {
40+
throw new SlackTokenError(
41+
`${parameterName} does not hold a Slack bot token; it may still be the placeholder Terraform created`,
42+
);
43+
}
44+
return value;
45+
}
46+
47+
return () => {
48+
cached ??= load().catch((error: unknown) => {
49+
cached = undefined;
50+
throw error;
51+
});
52+
return cached;
53+
};
54+
}

‎lambda/user-bot/test/handler.test.ts‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,15 @@ function setup(tags: { Key: string; Value: string }[] = [MANAGED, SLACK]) {
2424

2525
const sent: DirectMessage[] = [];
2626
const sender: MessageSender = { send: vi.fn(async (message) => void sent.push(message)) };
27+
const getSender = vi.fn(async () => sender);
2728
const logger = captureLogger();
2829
const deps: Dependencies = {
2930
iam: new IAMClient({ region: "us-east-1" }),
30-
sender,
31+
getSender,
3132
logger,
3233
generatePassword: () => TEST_PASSWORD,
3334
};
34-
return { handler: createHandler(deps), sender, sent, logger };
35+
return { handler: createHandler(deps), sender, getSender, sent, logger };
3536
}
3637

3738
beforeEach(() => {
@@ -91,13 +92,15 @@ describe("skips without touching the password or sending anything", () => {
9192
];
9293

9394
it.each(cases)("when %s", async (_name, tags, reason) => {
94-
const { handler, sender, logger } = setup(tags);
95+
const { handler, sender, getSender, logger } = setup(tags);
9596

9697
const result = await handler(createLoginProfileEvent());
9798

9899
expect(result).toEqual({ outcome: "skipped", reason, userName: "new.member" });
99100
expect(iamMock.commandCalls(UpdateLoginProfileCommand)).toHaveLength(0);
100101
expect(sender.send).not.toHaveBeenCalled();
102+
// A skipped user does not even cause the Slack token to be read.
103+
expect(getSender).not.toHaveBeenCalled();
101104
expect(logger.lines).toContainEqual(
102105
expect.objectContaining({ fields: expect.objectContaining({ reason, userName: "new.member" }) }),
103106
);
@@ -148,6 +151,45 @@ describe("skips without touching the password or sending anything", () => {
148151
});
149152
});
150153

154+
describe("when no sender is available (e.g. the Slack token cannot be read)", () => {
155+
it("throws before touching the password, and sends nothing", async () => {
156+
const { handler, getSender, sender, logger } = setup();
157+
const failure = new Error("/user-bot/slack-bot-token does not hold a Slack bot token");
158+
failure.name = "SlackTokenError";
159+
getSender.mockRejectedValueOnce(failure);
160+
161+
const error = await handler(createLoginProfileEvent()).catch((e: unknown) => e);
162+
163+
expect(error).toBeInstanceOf(Error);
164+
expect((error as Error).message).toContain("SlackTokenError");
165+
expect(iamMock.commandCalls(UpdateLoginProfileCommand)).toHaveLength(0);
166+
expect(sender.send).not.toHaveBeenCalled();
167+
expect(logger.lines).toContainEqual(
168+
expect.objectContaining({
169+
level: "error",
170+
fields: expect.objectContaining({ userName: "new.member", error: "SlackTokenError" }),
171+
}),
172+
);
173+
});
174+
175+
it("resolves the sender only after the tag checks pass, and before the reset", async () => {
176+
const { handler, getSender } = setup();
177+
const order: string[] = [];
178+
getSender.mockImplementationOnce(async () => {
179+
order.push("getSender");
180+
return { send: async () => void order.push("send") };
181+
});
182+
iamMock.on(UpdateLoginProfileCommand).callsFake(() => {
183+
order.push("UpdateLoginProfile");
184+
return {};
185+
});
186+
187+
await handler(createLoginProfileEvent());
188+
189+
expect(order).toEqual(["getSender", "UpdateLoginProfile", "send"]);
190+
});
191+
});
192+
151193
describe("failures", () => {
152194
it("rethrows when ListUserTags fails for another reason, and changes nothing", async () => {
153195
const { handler, sender } = setup();
@@ -193,7 +235,7 @@ describe("the password never reaches a log", () => {
193235
const generated: string[] = [];
194236
const handler = createHandler({
195237
iam: new IAMClient({ region: "us-east-1" }),
196-
sender: { send: async () => {} },
238+
getSender: async () => ({ send: async () => {} }),
197239
logger,
198240
generatePassword: () => {
199241
const password = generatePassword();

0 commit comments

Comments
 (0)