openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Slack bot: turn a Slack thread (text + images) into a GitHub issue (members-only, scoped to #openlibrary-g / #open-librarians-g)

Open mekarpeles opened this issue 4 months ago • 1 comments

Motivation

A lot of Open Library's real bug reports and feature ideas start life as a Slack thread in #openlibrary-g or #open-librarians-g — often with screenshots attached. Today, turning one of those threads into a tracked GitHub issue is manual copy-paste: re-typing the discussion, re-attaching the images by hand, and losing the link back to the original conversation. Most of the time it simply doesn't happen, and the report is lost.

This issue proposes a small Slack bot that does that conversion in one action: pick a message in a thread, and the bot files a GitHub issue on internetarchive/openlibrary containing the thread's text (with author display names), any embedded images, the channel name, and a permalink back to the Slack thread.

Scope

Trigger UX

A Slack message shortcut (right-click / "more actions" on a message → Create GitHub issue), not a slash command. A shortcut payload carries the message and thread context implicitly (channel.id, message.ts, message.thread_ts, user.id), which is exactly what "operate on this thread" needs. A slash command has no implicit message context — the invoker would have to paste a permalink, which is most of the friction we're trying to remove.

Membership check (hard requirement)

Call users.info for the invoking user and refuse unless both is_restricted and is_ultra_restricted are false. Either flag true means a guest (multi-channel or single-channel guest) and the bot must decline politely without creating an issue. Guests must not be able to file into our public repo through us.

Channel restriction (hard requirement)

Functional only in #openlibrary-g and #open-librarians-g. Anywhere else — including for a full member — the bot responds with a polite ephemeral refusal and creates nothing. The allowed channels should be configuration, not hard-coded literals, but the deployed default is exactly those two.

Content extraction

  • Fetch the whole thread (conversations.replies), preserving order, with author display names resolved via users.info (cached per run).
  • Collect image files attached to any message in the thread.
  • Slack file URLs (url_private) require the bot token to fetch and are not publicly readable, so a raw Slack URL pasted into a GitHub issue renders as a broken image. Images therefore have to be re-hosted somewhere GitHub can embed by URL.

Issue creation

Created via gh/the GitHub API as @openlibrary-bot (this is the bot's own automated action). Body includes: thread text, re-hosted image embeds, originating channel name, thread permalink (chat.getPermalink), and an explicit byline saying the issue was generated from a Slack thread and by whom.

Open question 1 — privacy sign-off (needs @mekarpeles, separate from "does the code work")

Copying an internal Slack discussion — even one held in a Slack-public channel — onto a fully public GitHub repository is a policy decision, not just a technical one. Participants in a thread did not necessarily consent to their words and screenshots being republished publicly and permanently, and screenshots in particular can contain patron data, emails, or admin UI that nobody intended to publish.

The POC will ship with a conservative default (a confirmation step — either an ephemeral "this will post publicly, confirm?" dialog to the invoker, or a ✅ reaction requested in-thread before the issue is filed) so that no thread can be republished by accident.

But the default is a POC default, not an approved policy. Before any real/production use this needs an explicit decision on:

  1. Is per-use confirmation from the invoker sufficient, or does republishing need consent from the thread participants (not just the person clicking the shortcut)?
  2. Should images be re-hosted at all by default, given they are the highest-risk content (screenshots of patron data / admin screens)? A viable stricter default is: text only, with images listed as "N image(s) omitted — attach manually if appropriate."
  3. Should there be a redaction/edit step (bot opens a pre-filled modal the invoker can edit) rather than filing verbatim?

Flagging, not deciding. This wants an answer before install, independent of whether the code is correct.

Open question 2 — where to re-host images

Two real options; picking one is part of the implementation plan, not settled here.

  • A dedicated GitHub assets repo via the Contents API (PUT /repos/{owner}/{repo}/contents/{path}), embedding the resulting raw.githubusercontent.com URL. Documented, supported, permanent, versioned, and needs no credential the bot doesn't already have. Downside: it's a new repo to create, and content is public and effectively permanent (deleting a file leaves it reachable in history).
  • An archive.org item, matching this codebase's existing bot pattern (the OLModSecurityBot daily upload described in #13225). Downside: that pattern uses an access-restricted item, which by definition GitHub cannot embed — so this variant would require a public item, which is a meaningfully different privacy posture than the pattern it's borrowing from. It also needs the bot's IA S3 keypair on the host.

Current lean is the GitHub assets repo for robustness (documented API, no extra credentials, renders reliably in issue markdown). Explicitly not in scope: GitHub's browser-only attachment upload endpoint — it is not a public API and building on it would be fragile by design.

Deliverables

  1. Working handler code — Slack request-signature verification (X-Slack-Signature / X-Slack-Request-Timestamp, HMAC-SHA256 with the signing secret, timestamp replay window), membership check, channel check, thread fetch, image re-host, issue creation. Slack requires an ack within 3 seconds, so the slow work (fetching, uploading, filing) runs after the ack, not inline.
  2. Tests against recorded/mocked Slack payloads — including the refusal paths: guest user, unlisted channel, bad signature, stale timestamp. No live workspace needed to run the suite.
  3. A step-by-step setup guide for @mekarpeles covering the parts a bot cannot do for itself: creating the app at api.slack.com/apps, the required OAuth scopes (channels:history, groups:history if a private channel is ever in play, users:read, files:read, chat:write), enabling Interactivity & Shortcuts and registering the message shortcut, setting the Request URL (with ngrok-style tunnelling called out as the POC step, distinct from the eventual hosted deployment), installing to the workspace, and where the Bot Token + Signing Secret go in olsystem — following how other bot secrets are handled there. The real token must never be pasted into any chat/agent session; the guide points at the file location instead.

Out of scope

  • Creating the Slack app itself (workspace-admin action, requires Mek's own browser session).
  • Two-way sync, issue updates from later thread replies, or Slack notifications when the issue changes.
  • Any channel beyond the two named above.

Notes

Related existing Slack integration in this repo runs the other direction (GitHub → Slack): scripts/gh_scripts/issue_comment_bot.py and scripts/pr_slack_digest.py, both cron-driven via GitHub Actions with SLACK_TOKEN from the environment. This is the first inbound Slack → GitHub path, and the first one needing a persistently reachable HTTPS endpoint rather than a cron job — so deployment shape is a genuine design decision, covered in the implementation plan.

mekarpeles avatar Jul 29 '26 15:07 mekarpeles

Implementation plan

Approach

Deployment shape — mount the webhook as a router in the existing FastAPI app rather than standing up a new service. Slack needs a persistently reachable HTTPS endpoint, and the FastAPI app (openlibrary/asgi_app.py) is the only one we already have; it also already loads its config through infogami.config, which is how every other credential in this codebase reaches the process (ia_ol_xauth_s3, internal_tests_api_key, etc.). A standalone service would need its own compose service and its own nginx route for no benefit. All the logic lives in a service module so it can be lifted out later if this ever deserves its own process.

The route is hidden from the public OpenAPI schema the same way openlibrary/fastapi/internal/api.py hides its internal routes.

Request flow — Slack expects an ack within 3 seconds, and a trigger_id is only valid for ~3 seconds for views.open, so the work is split:

  1. POST /_slack/interactivity — verify the Slack signature first, before parsing anything: HMAC-SHA256 over v0:{timestamp}:{raw_body} with the signing secret, compared with hmac.compare_digest, plus a 300-second timestamp window to kill replays. Failure → 401, no outbound calls.
  2. Channel check (free — the payload carries channel.id/channel.name). Not in the allowlist → politely refuse via the payload's response_url (ephemeral, visible only to the invoker), create nothing.
  3. Guest check — users.info for user.id; proceed only when is_restricted and is_ultra_restricted are both false. Either true → ephemeral refusal via response_url, create nothing.
  4. Open a deliberately lightweight confirmation modal (views.open) — editable issue title, an "include N image(s)" checkbox, and explicit text that this posts publicly to a public GitHub repo. It carries channel/message_ts in private_metadata. Keeping the thread fetch out of this step is what keeps us inside the 3s/trigger_id budget.
  5. view_submission — ack immediately, then do the slow work in a BackgroundTasks job: conversations.replies for the full thread, users.info (memoised per run) for display names, chat.getPermalink, image re-host, issue creation. Result (issue URL, or the specific failure) is reported back to the invoker via response_url/DM — never a silent failure.

Image re-hosting — dedicated GitHub assets repo via the documented Contents API (PUT /repos/{owner}/{repo}/contents/{path}), embedding the resulting raw.githubusercontent.com URL. Slack's url_private needs Authorization: Bearer <bot token> to fetch and is not publicly readable, so a raw Slack URL renders broken in an issue. Rationale for GitHub over an archive.org item is in the issue description above: the archive.org pattern this would borrow from (#13225) uses an access-restricted item, which GitHub cannot embed by URL at all — matching the pattern would mean a public item, i.e. a different privacy posture than the pattern it is imitating, plus an extra credential on the host. The GitHub route needs no credential the bot doesn't already have.

No new dependencies — httpx (already in requirements.txt, already what the FastAPI app uses) for Slack and GitHub calls; hmac/hashlib from the stdlib for signature verification. The existing outbound Slack scripts (scripts/gh_scripts/issue_comment_bot.py, scripts/pr_slack_digest.py) hand-roll requests calls against slack.com/api/* rather than pulling in slack_sdk; this follows that.

Files

File Change
openlibrary/fastapi/slack.py new — router: POST /_slack/interactivity, signature dependency, ack/background split
openlibrary/fastapi/services/slack_issue_service.py new — signature verification, gating predicates, thread fetch + markdown rendering, image re-host, issue creation
openlibrary/asgi_app.py include the new router
conf/openlibrary.yml new slack_issue_bot: block with dev placeholders (signing_secret, bot_token, allowed_channels, github_repo, assets_repo); real values live only in olsystem's openlibrary.yml
openlibrary/tests/fastapi/test_slack_issue_bot.py new — endpoint tests against recorded payloads
openlibrary/tests/fastapi/test_slack_issue_service.py new — unit tests for verification/gating/rendering
docs/slack-issue-bot-setup.md new — the api.slack.com setup guide (scopes, shortcut registration, Request URL, ngrok POC step, where the secrets go)

Tests (input → expected)

Input Expected
Valid signature, allowed channel, is_restricted:false/is_ultra_restricted:false 200; views.open called once with our callback_id and private_metadata carrying channel + message_ts
Tampered body / wrong signing secret 401; zero outbound Slack or GitHub calls
X-Slack-Request-Timestamp 10 minutes old, otherwise-valid signature 401 (replay window)
users.info → is_restricted: true 200; no views.open, no issue; refusal posted to response_url naming guest accounts as the reason
users.info → is_ultra_restricted: true same as above
Allowed member, channel #random 200; refusal via response_url; users.info never called (channel checked first)
view_submission, 3-message thread, images checkbox on Issue created on internetarchive/openlibrary whose body contains all 3 messages in order with display names, the chat.getPermalink URL, the channel name, the Slack-generated byline, and one raw.githubusercontent.com embed per image
Same, checkbox off Issue body contains no image embeds and an explicit "N image(s) omitted" line
Slack file fetch Request to url_private carries Authorization: Bearer <bot token> (a bare fetch would 403)
GitHub issue creation returns 4xx/5xx No exception escapes the background task; invoker gets a message naming the failure; no half-created state claimed as success

Success criteria

Automated: the table above green under make test-py-uv PYTEST_ARGS="openlibrary/tests/fastapi/test_slack_issue_bot.py openlibrary/tests/fastapi/test_slack_issue_service.py"; pre-commit clean on changed files; existing suite unaffected.

Manual: POST a recorded shortcut payload (correctly signed with a local test secret) at the running dev container and get 200 plus the expected views.open attempt; the two refusal paths return 200 and create nothing. A genuine end-to-end run needs a real Slack app, which only @mekarpeles can create — that's deliverable #3, the setup guide, not something this PR can self-verify.

Out of scope

Creating the Slack app (workspace-admin, browser-only). The olsystem nginx route for /_slack/* and the production secret placement — documented for the operator, not done here. Two-way sync, updating an issue from later replies, notifying Slack on issue changes. Any channel beyond #openlibrary-g and #open-librarians-g. Non-image file types.

Risks

  • 3-second ack / trigger_id expiry — mitigated by doing only users.info + views.open pre-ack and everything slow post-submission. Slack API latency is the one thing that could still blow this; the handler logs elapsed time so it's diagnosable rather than mysterious.
  • New unauthenticated public endpoint on the product app — signature verification is the whole defence, hence verify-before-parse, compare_digest, and the timestamp window. It does nothing on an unsigned request.
  • Publishing internal discussion publicly — the confirmation modal is a guardrail, not a policy. Called out as open question 1 above; this is why installation, not implementation, is what needs @mekarpeles's sign-off. Implementation proceeding does not presume that answer, and the bot cannot do anything at all until someone installs a Slack app that doesn't exist yet.
  • Screenshots are the highest-risk content (patron data, admin UI). The images checkbox exists for this. If the answer to open question 1 is "text only by default", that's a one-line default flip, deliberately.
  • Bot token handling — never in the repo, never pasted into any chat/agent session, config-only, following how other bot credentials in olsystem are handled. The guide points at the location rather than moving the value.
  • Issue spam — a member can file repeatedly. Not solved in the POC; noted, and cheap to add a per-user rate limit later if it ever matters.

Gate assessment

Not gating implementation. Nothing here is destructive or hard to reverse, the approach follows existing patterns rather than inventing one, and the genuinely open policy question blocks installation, which is already blocked on a workspace-admin action only @mekarpeles can perform. Labelling Needs: Response for the lead's read on open questions 1 and 2 — but that answer is not a prerequisite for the code existing and being reviewable.

openlibrary-bot avatar Jul 29 '26 15:07 openlibrary-bot