File size: 9,451 Bytes
af1bee9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | # Chat channels: the two-way bot
**Audience:** engineers changing the bot or adding a channel (Microsoft Teams is next).
People use Patchwise from a chat app as well as from the web app. They link their chat once, then:
- they hear when a test run needs them;
- they ask questions;
- they start runs and approve scenarios, by pressing buttons.
The web app stays the place for sign-off and failure verdicts.
## Architecture
```
Telegram ──getUpdates──▶ channels/telegram.py ──Inbound──▶ channels/core.py ──▶ chat/service.py (Ask)
◀─sendMessage── (adapter, poller) ◀─OutMessage─ (Conversation) api/actions.py (same as REST)
▲
notify_events (outbox) ──deliver_linked()──────────┘ per-chat delivery in channel_deliveries
```
### `channels/core.py`: channel-agnostic
**Types:**
| Type | What it is |
|---|---|
| `Inbound` | Who wrote, which chat, the text or the pressed button |
| `OutMessage` | Plain text plus rows of buttons; each button is either an opaque callback id or an https link |
| `Adapter` | A protocol with `send` and `answer_callback` |
**`Conversation.handle(inbound)`** does three things:
- resolves the linked Patchwise user;
- runs the commands below;
- returns the messages to send.
**Commands:**
| Command | What it does |
|---|---|
| `/start`, `/help` | Shows help |
| `/link CODE` | Links this chat to the person's Patchwise account |
| `/unlink` | Stops using this chat |
| `/status` | Shows what's waiting for this person, plus the latest runs |
| `/run <area> [quick\|browser]` | Proposes a test run |
| Any other text | Goes to the Ask service as that user |
**Actions:**
- The Ask service only proposes an action. The proposal becomes two buttons, for example **[Start test run] [Cancel]**.
- Pressing **Start** runs `ChatService.confirm_action`. That is the same single-use path as the Ask page, with RBAC and run state checked again.
- **[Approve all]** under a notification builds the same proposal Ask makes for "approve all". It then asks **[Yes, approve all] [Cancel]**.
### `channels/telegram.py`: the Telegram adapter
**Poller:**
- Long-polls `getUpdates` (25 s).
- Stores the offset in the `kv` table before handling each update. A restart never answers the same message twice.
- Remembers the chats it saw, which Settings → Find my chat uses.
- Ignores group chats unless someone linked them.
**Delivery to linked people (`deliver_linked`):**
- Each person gets the events about runs they may read, from the moment they linked. Older events are never sent.
- Each event goes to each chat once, with the same retry and back-off as the other channels.
- The administrator chat (`FPT_TELEGRAM_CHAT_ID`, or the chat chosen in Settings) is still served by `notify.py`. A linked chat that is the same chat is skipped, so nobody gets duplicates.
### Data (migration 013)
| Table | Holds |
|---|---|
| `channel_links` | Channel, external user id, chat id, Patchwise user, their Ask conversation |
| `channel_link_codes` | SHA-256 of each one-time code, 10-minute expiry, used-at |
| `channel_callbacks` | Opaque button id, group, chat, user, kind, payload, 24-hour expiry, used-at |
| `channel_deliveries` | Per-chat notification delivery state |
| `channel_run_origins` | Runs started from a chat |
## Security rules
- **The bot acts as the linked person, never as more.** Every action goes through the same RBAC and service functions as the REST API.
- **Linking is self-service with a one-time code.** The code is made by the signed-in person, works once and expires after 10 minutes. Only its hash is stored. After 5 wrong tries, linking pauses for 10 minutes for that sender.
- **Buttons carry only a random id.** Whatever a button does is stored server-side. A press is refused if the button is in another chat, belongs to another person, has expired or was already used. Pressing one button of a pair closes the other.
- **Never offered in a chat:** sign-off, failure verdicts, the kill switch, administration. For these the bot sends a link to the screen.
- **Audit:** every link, unlink, message, proposal, confirm, cancel and refusal is written as `channel.*`, with the linked user as actor.
- **The bot token never leaks:**
- It is a secret: `FPT_TELEGRAM_BOT_TOKEN`, or the vault entry `TELEGRAM_BOT_TOKEN`.
- The audit log records the address as `…/bot(hidden)/<method>`.
- A logging filter masks it in HTTP client log lines.
- The API returns only whether it is set.
## Settings
| Setting | Effect |
|---|---|
| `FPT_TELEGRAM_BOT_TOKEN` (secret) | Enables the bot (polling and sending) |
| `FPT_TELEGRAM_CHAT_ID` | The administrator chat that gets every event |
| `FPT_TELEGRAM_POLLING=0` | Send only; don't read messages (for example when another app reads this bot's updates) |
| `FPT_TELEGRAM_API_BASE` | An https relay that forwards `/bot<token>/<method>` unchanged, for hosts that can't reach api.telegram.org |
| `FPT_PUBLIC_URL` | Needed for link buttons: chat platforms only accept absolute https links |
## API
| Endpoint | Who | What |
|---|---|---|
| `POST /api/channels/telegram/link-code` | Any signed-in person | Returns `{code, expires_at, bot_username}` |
| `GET /api/channels/me` | Any signed-in person | Returns `{telegram: {linked, username, linked_at}}` |
| `DELETE /api/channels/telegram/link` | The person themselves | Unlinks their chat |
| `GET /api/channels/telegram/status` | Admin | Returns `{token_set, bot_username, polling, last_update_at, linked_users}` |
## Incoming-webhook integrations: Slack, Microsoft Teams, Google Chat, Discord
One-way notifications, set up by an administrator on the Integrations page (`/integrations`). They receive the same outbox
events as the other channels; a two-way bot for Teams and Slack is the planned next step (see below).
- **Setup:** paste the service's incoming-webhook address (Slack: an app's Incoming Webhooks; Teams: the Workflows template
"Post to a channel when a webhook request is received"; Google Chat: the space's Webhooks; Discord: the channel's
Integrations > Webhooks). Only that service's own host and path shape is accepted, https only.
- **Secret:** the address is the credential. It is stored in the vault as `INTEGRATION_<KEY>_WEBHOOK`, added to the
redactor, never returned by the API (only its host), and the audit and the server log show `https://<host>/(webhook path hidden)`.
- **Formats:** Slack blocks with an "Open in Patchwise" button (`&`, `<`, `>` escaped so app text can't write `<!channel>`);
a Teams Adaptive Card 1.4 with `Action.OpenUrl`; Google Chat text plus a `cardsV2` button (angle brackets neutralised so
`<users/all>` can't mention anyone); Discord content with `allowed_mentions: {parse: []}`. The button appears only for an
absolute https link (`FPT_PUBLIC_URL`).
- **Delivery (migration 014, `notify_deliveries`):** one row per event and integration, so each retries on its own
(30 s, 2 min, 10 min, then hourly, 8 attempts). 400 / 403 / 404 / 410 (webhook removed) stop after 2 attempts. A new
connection gets at most the last hour of events. "Send a test message" posts to that integration only.
- **API (administrators, CSRF on writes):** `GET /api/integrations`, `PUT /api/integrations/{slack|teams|google_chat|discord}`
`{webhook_url}`, `DELETE /api/integrations/{key}`, `POST /api/integrations/{key}/test`.
## Adding Microsoft Teams (planned)
The core is unchanged. You add `channels/teams.py` with an adapter and an inbound endpoint.
1. **Bot registration.**
- Create an Azure Bot resource (single-tenant, in the customer's tenant) with an app id and secret.
- Store them as secrets `FPT_TEAMS_APP_ID` and `FPT_TEAMS_APP_SECRET`.
- Package a Teams app manifest that points to the bot.
2. **Inbound.** `POST /api/channels/teams/messages` receives Bot Framework activities.
- Verify the `Authorization` JWT against the Bot Framework OpenID metadata: issuer, audience = app id, signing keys. Reject anything unsigned.
- This endpoint is public. It is the one place Teams differs from Telegram's polling.
3. **Mapping to `Inbound`.**
- `external_user_id` = `activity.from.aadObjectId`.
- `chat_id` = `activity.conversation.id`, plus the stored `serviceUrl`.
- `text`, or `value.cb` for Adaptive Card actions.
- `private` = `conversation.conversationType == "personal"`.
4. **Outbound.** Turn `OutMessage` into a message with an Adaptive Card:
- text: a `TextBlock`;
- callback buttons: `Action.Submit` with `{cb: <id>}`;
- link buttons: `Action.OpenUrl`.
- Send it to `{serviceUrl}/v3/conversations/{id}/activities` with a token from the Bot Framework token endpoint.
- The egress allowlist must add the `serviceUrl` hosts and `login.microsoftonline.com`.
5. **Linking.** Same `/link CODE` flow. Alternatively, with SSO, link automatically when the AAD object id matches a Patchwise account's external id (`users.external_id`, from Supabase or Entra sign-in). If you do this, document it in SECURITY.md.
6. **Proactive notifications.** Store `serviceUrl` and the conversation reference on the `channel_links` row when the person first writes, then reuse `deliver_linked`'s logic with the Teams adapter.
|