Skip to content

Notices: add Discord webhook channel (#1204) - #1247

Open
embrace897 wants to merge 3 commits into
Cygnux-Labs:mainfrom
embrace897:feat/notices-discord-channel
Open

embrace897 wants to merge 3 commits into
Cygnux-Labs:mainfrom
embrace897:feat/notices-discord-channel

Conversation

@embrace897

Copy link
Copy Markdown
Contributor

Closes the Discord channel item in #1204 (leaving the other channels and earlier email work in #1211 untouched).

Summary

  • tracekit/signer/notice.py:
    • Added discord: {secret_file: ...} support in load(), dev(), and targets() via a shared _load_webhook_url() helper.
    • Enforced https:// + remote_url_error() validation, strict {secret_file} shape checking, and st_mode & 0o077 refusal (chmod 600 guidance) on POSIX hosts.
  • tracekit/signer/webhook.py:
    • Added _discord() Markdown/mention escaping (\, `, *, _, ~, |, <, >, [, ], @) and _discord_chunks() (DISCORD_MAX = 2000 batch packing/truncation).
    • Updated Sender._send() for fmt="discord" to omit the viewer token from [see it: ...] links, send {"content": ..., "allowed_mentions": {"parse": []}}, and return the first failing status across chunks.
    • Added User-Agent: Tracekit/<version> in post() so Discord's edge proxy accepts urllib POST requests.
  • docs/notices.md: Documented the Discord channel in the channel table, signer.yaml example, secret-file permissions, retry/drop behavior, and token-free links.
  • tests/test_notice.py: Added unit tests covering all 6 notice kinds, mention/link escaping, local HTTP 204 end-to-end delivery over ThreadingHTTPServer, 2,000-character batch splitting and single-line truncation, 503 retries / 400 refusal / queue_full non-blocking behavior, OneLine cross-channel formatting, and config / permission validation.

Verification

  • Ran pytest tests/test_notice.py tests/test_webhook.py -v on Windows (rebased on cdb8807): 62 passed, 45 subtests passed in 7.43s (every Channels, OneLine, Config, ViewerStart, and test_webhook.py test passed; 1 unrelated upstream #1219 test Sentences.test_an_outage_the_hook_kept_is_told_once_its_lines_have_come fails on Windows because time.tzset is POSIX-only).
  • Ran python -m pyflakes tracekit tracekit_sdk.py tests eval examples contrib integrations -> exit code 0.
  • Exercised webhook.Sender(..., fmt="discord") end-to-end against a local ThreadingHTTPServer returning 204 No Content (POST /api/webhooks/1/tok), confirming headers (User-Agent: Tracekit/1.8.1, Content-Type: application/json) and JSON body:
    {"content": "Your agent tried this and Tracekit stopped it: reading or touching a credentials file (\\@everyone \\[x\\](https://bad)). Rules: TK-S004. [see it: run `tracekit view --dev`]", "allowed_mentions": {"parse": []}}
  • Note: local verification used an offline mock 204 HTTP server rather than a live public Discord webhook URL.

Signed-off-by: embrace897 <208367873+embrace897@users.noreply.github.com>
@LoopGlitch26

Copy link
Copy Markdown
Member

Thanks @embrace897. We are reviewing it now and will reply here. Since #1211 (email) changes the same two files, we will look at how the two fit together too.

@LoopGlitch26

Copy link
Copy Markdown
Member

@embrace897 Thanks. We ran it end to end in a container: a real signer, a local HTTPS server standing in for Discord, and all six kinds of notice. A lot holds:

  • Every Discord markup character is escaped.
  • allowed_mentions: {parse: []} goes on every message. @everyone, <@id>, role and channel mentions, masked links, code fences and spoilers all came out as plain text.
  • The viewer token never reached a Discord body, and the webhook URL appeared in no log, error or record.
  • A slow or failing Discord never held up the signer or the other channels.

Before merge, one thing makes notices wrong:

  1. A retried batch duplicates some notices and loses others. _send posts each 2,000-character chunk and returns on the first failure. _loop then retries the whole batch from the first chunk, and Retry-After is ignored. With a server that answers 429 after 5 posts in 2 s, 100 deny notices went out as 8 messages. 65 notices arrived three times, 35 never arrived, and the counter said 100 failed. Please retry from the chunk that failed. On a 429, wait the Retry-After it gives (capped, say at 30 s). Count as dropped only what wasn't delivered. Please also add a test: a local server that answers 429 to the 6th post, and every sentence arrives exactly once.

Also needed:

  1. Send "flags": 4 (suppress embeds) on every message, so a link an agent put in a tool name or a reason shows no preview card. The test with 3+ messages should check flags and allowed_mentions on every post, not only the first.
  2. One bad reply kills the sender thread. post() catches only HTTPError and OSError. A reply that isn't HTTP raises BadStatusLine, and a URL with a space raises InvalidURL. Either one ends the thread for good. Python's default handler then prints the exception, and with InvalidURL that includes the webhook token, to the signer's stderr. This is older than your PR and hits Slack too. Please guard self._send(body) in Sender._loop so any exception counts as a failed send, and warn once with only the exception's class name. Test it with an endpoint that answers something that isn't HTTP, then check that a later notice still arrives.
  3. At start, refuse a URL with whitespace or control characters. A check that the path is /api/webhooks/<id>/<token> would give a pasted wrong URL a clear error. The "non-private" docstring at notice.py:365 isn't what the code checks.
  4. The secret file: open it, then fstat the open file, so what you check is what you read. Then refuse group or other bits. Please also refuse discord: with no value, as slack: is refused.
  5. A single line over 2,000 characters is cut at the end and loses its [see it: …] link. Please cut the agent's text in the middle and keep the end of the sentence and the link.
  6. Docs: name Discord in docs/support.md and docs/webhooks.md, which list the channels. In docs/notices.md, say that a large batch goes out as several messages and how a 429 is handled.

#1211 (email) changes the same code in notice.py and webhook.py. Whichever is ready first lands first, and the other rebases. If yours is first, item 3's guard is yours, and #1211 builds on it.

Once these are in, please show the 100-notice run again with each sentence arriving once, as in your PR body's example.

…ion)

Signed-off-by: embrace897 <208367873+embrace897@users.noreply.github.com>
@embrace897

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough E2E test and detailed feedback, @LoopGlitch26! Addressed all seven items in 165c249:

  1. Per-chunk retry, Retry-After, and exact drop counts (tracekit/signer/webhook.py):
    • Sender._parts() now pre-packs Discord batches into 2,000-character JSON payloads with per-chunk record counts, and Sender._loop() retries from the failed chunk instead of restarting from chunk 1.
    • post() attaches Retry-After (numeric seconds, HTTP-date, or Discord JSON retry_after, capped at BACKOFF_S[1] = 30.0 s) on 429, which Sender._loop() waits before retrying. Only undelivered notices in the failing chunk (or remaining chunks on shutdown) are counted in dropped.
    • Added local-server tests in tests/test_notice.py covering a 100-notice batch hitting 429 on the 6th POST (all 100 delivered once) and partial-batch failure drop accounting.
  2. Suppress embeds ("flags": 4): Every Discord payload now includes "flags": 4 (DISCORD_FLAGS), and tests/test_notice.py asserts both flags and allowed_mentions on every POST in multi-message (3+) batches.
  3. Sender thread resilience (Sender._loop): Guarded self._send(body) against any Exception, logging WARNING once with only type(exc).__name__ (no webhook URL/token) and counting the failed chunk while keeping the sender thread alive. Tested against a raw TCP server replying NOT HTTP AT ALL\r\n (BadStatusLine) followed by a 204 notice.
  4. URL validation (tracekit/signer/notice.py, tracekit/signer/webhook.py): Refuses whitespace/control characters at load time for Discord, Slack, and OCSF webhooks, enforces /api/webhooks/<id>/<token> on Discord URLs (preserving valid query strings such as ?thread_id=), and corrected the _load_webhook_url docstring.
  5. fstat check & empty discord: (tracekit/signer/notice.py): Opens secret_file first and checks os.fstat(f.fileno()).st_mode & 0o077 on the open descriptor; changed load() to check "discord" in section so bare discord: (None) is rejected like slack:.
  6. Middle truncation preserving sentence tail and link (tracekit/signer/webhook.py): Added _discord_truncate() / _discord_line() to cut overlong (>2,000 char) lines in the middle while keeping the sentence ending, [see it: …] link, and backslash-escape token boundaries intact.
  7. Docs: Updated docs/support.md, docs/webhooks.md, and docs/notices.md.

Verification

  • pytest tests/test_notice.py tests/test_webhook.py -v on Windows (165c249): 65 passed, 57 subtests passed (excluding the pre-existing POSIX-only Sentences.test_an_outage_the_hook_kept_is_told_once_its_lines_have_come which calls time.tzset); pyflakes on modified files passed cleanly.
  • Real SignerService 100-notice deny E2E run against a local rate-limiting receiver (answering 429 with Retry-After after 5 POSTs in 2 s):
    • POST status counts: {204: 13, 429: 2}
    • Max content length: 1945 (<= 2000)
    • All have allowed_mentions={'parse': []}: True, All have flags=4: True
    • Total sentences received: 100 | Unique: 100 | Duplicates: 0 | Missing: [] | tracekit_signer_webhook_dropped_total: 0
    • Sample line: Your agent tried this and Tracekit stopped it: a rule in your own policy (tool-000). Rules: NO-RM-000. [see it: run \tracekit view --dev`]`

@LoopGlitch26

Copy link
Copy Markdown
Member

Thanks @embrace897. We are reviewing 165c249 now and will reply here. #1211 (email) is about to land with the Sender._loop guard and a secret-file reader, so the rebase onto it is the next step after this review.

@LoopGlitch26

Copy link
Copy Markdown
Member

@embrace897 Thanks. 165c249 does all seven, and we checked each in a container. The 100-notice run against a server that answers 429 after 5 posts in 2 s now delivers every sentence exactly once: the chunk that got the 429 is resent after its Retry-After, and nothing is dropped. Every post carries flags: 4 and allowed_mentions. A cut line keeps its start, its end and its link: 5,000 fuzzed lines kept every rule. A reply that isn't HTTP no longer stops any sender.

Before merge:

  1. Four fixes have no test that fails without them. We took each fix out and every test still passed:
    • The sender ignoring Retry-After: the 429 test sends Retry-After: 0.05, which the 0.5 s backoff also passes. Please pick a value the backoff can't match.
    • close() during a wait counting only the current chunk as shutdown instead of every chunk left.
    • The warning carrying the exception's message: please test with a message that holds the webhook token, and check the log has no token.
    • The cut landing inside an escape pair (\@, \`, \\): without the check, a seeded fuzz like ours leaves unescaped markup in about 40% of lines.
  2. A URL with non-ASCII or zero-width characters still loads, and then every notice to it is dropped. Please refuse it at start (not url.isascii()).
  3. docs/webhooks.md still says a 429 waits 0.5, 1, 2 and 4 s. Every webhook sender now waits the endpoint's Retry-After, capped at 30 s.
  4. Rebase on Notices: an email channel over SMTP (#1204) #1211 once it lands (email, about to merge). Both change the same code:
    • One guard in Sender._loop: Notices: an email channel over SMTP (#1204) #1211's, which resets its warning after a success.
    • One secret-file reader, shared by email and Discord.
    • One channel table in docs/notices.md.
    • The viewer token as an allowlist (token = self.fmt == "feed"), so no future remote channel can carry it by default.
    • Like email, Discord gets its own events, defaulting to asks only. A chat channel is where a person reads the lines that need them, and the viewer has the rest.

Once these are in, please paste the 100-notice run's result into the PR body.

…vents

Signed-off-by: embrace897 <208367873+embrace897@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants