From 96facc76d4de0f8a1da98d2e85306cd6af64ffdb Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Tue, 24 Nov 2026 11:50:40 +1100 Subject: [PATCH 1/3] feat(zendesk): authenticate with an OAuth client, API token as fallback Zendesk stops accepting API tokens on 2027-04-30 and no longer issues new ones. With ZENDESK_OAUTH_CLIENT_ID and ZENDESK_OAUTH_CLIENT_SECRET set, every Zendesk job now takes a client-credentials token and renews it before its 30-minute expiry; without them it keeps using the API token, so angus runs unchanged until the client is added to zendesk.env. --- deploy/env/zendesk.env.example | 7 +- docs/jobs/zendesk-digest.md | 9 +-- src/session_ops/jobs.toml | 4 +- src/session_ops/zendesk/api.py | 66 ++++++++++++++++++- src/session_ops/zendesk/note_reply.py | 10 +-- src/session_ops/zendesk/relay.py | 7 +- src/session_ops/zendesk/resolve_reviews.py | 17 +++-- src/session_ops/zendesk/triage.py | 18 ++--- tests/zendesk/test_api.py | 77 ++++++++++++++++++++++ 9 files changed, 184 insertions(+), 31 deletions(-) diff --git a/deploy/env/zendesk.env.example b/deploy/env/zendesk.env.example index e576e8d..17b2936 100644 --- a/deploy/env/zendesk.env.example +++ b/deploy/env/zendesk.env.example @@ -5,7 +5,12 @@ # Claude API key for the digest, the transcripts and the `claude:` notes. ANTHROPIC_API_KEY= ZENDESK_SUBDOMAIN= -# Authors every comment the reply flow posts. +# A confidential OAuth client (Admin Center > Apps and integrations > APIs > OAuth +# clients), created while logged in as the admin every comment should come from. +ZENDESK_OAUTH_CLIENT_ID= +ZENDESK_OAUTH_CLIENT_SECRET= +# Used only while the OAuth client above is unset; Zendesk refuses API tokens from +# 2027-04-30. ZENDESK_EMAIL authors every comment the reply flow posts. ZENDESK_EMAIL= ZENDESK_API_TOKEN= # The triage channel: the digest, the review tally and this job's failures. diff --git a/docs/jobs/zendesk-digest.md b/docs/jobs/zendesk-digest.md index 929600b..bbb6f3b 100644 --- a/docs/jobs/zendesk-digest.md +++ b/docs/jobs/zendesk-digest.md @@ -131,8 +131,9 @@ Two caveats worth knowing: | Secret | Description | | --------------------- | ------------------------------------------------------- | | `ZENDESK_SUBDOMAIN` | Zendesk subdomain (`mycompany` → `mycompany.zendesk.com`) | -| `ZENDESK_EMAIL` | Agent email used for Zendesk API-token auth | -| `ZENDESK_API_TOKEN` | Zendesk API token | +| `ZENDESK_OAUTH_CLIENT_ID`, `ZENDESK_OAUTH_CLIENT_SECRET` | A confidential OAuth client. Its token acts as the admin who created it, so create it as the admin the reply flow posts as. Wins over the API token when both are set | +| `ZENDESK_EMAIL` | Agent email for API-token auth, used only without the OAuth client | +| `ZENDESK_API_TOKEN` | Zendesk API token, used only without the OAuth client. Zendesk refuses API tokens from 2027-04-30 | | `ZENDESK_DISCORD_WEBHOOK_URL` | Discord incoming webhook for the triage channel, shared with the tally and the failure alerts | ## Claude Authentication @@ -220,7 +221,7 @@ Local runs need `ANTHROPIC_API_KEY` alongside the Zendesk credentials. `--dry-ru ``` uv sync -export ZENDESK_SUBDOMAIN=... ZENDESK_EMAIL=... ZENDESK_API_TOKEN=... +export ZENDESK_SUBDOMAIN=... ZENDESK_OAUTH_CLIENT_ID=... ZENDESK_OAUTH_CLIENT_SECRET=... # what the unit runs, minus the Discord post and the state file uv run zendesk-triage --window-hours 72 --dry-run @@ -300,7 +301,7 @@ A dry run prints the message it would have posted instead of posting it, and `-- ### Required Secrets -`ZENDESK_SUBDOMAIN`, `ZENDESK_EMAIL`, `ZENDESK_API_TOKEN` — the same three the triage uses — plus `ZENDESK_DISCORD_WEBHOOK_URL`, the triage channel's own webhook, so the tally lands next to the digests it accounts for. Not the shared `DISCORD_WEBHOOK_URL`: a webhook is bound to the channel it was created in. No Claude credentials: it classifies nothing. +`ZENDESK_SUBDOMAIN` and the Zendesk credentials, the same ones the triage uses, plus `ZENDESK_DISCORD_WEBHOOK_URL`, the triage channel's own webhook, so the tally lands next to the digests it accounts for. Not the shared `DISCORD_WEBHOOK_URL`: a webhook is bound to the channel it was created in. No Claude credentials: it classifies nothing. The webhook is resolved before the run fetches anything, so a missing secret stops it rather than letting it bulk-edit tickets it then can't report; a dry run doesn't need one. diff --git a/src/session_ops/jobs.toml b/src/session_ops/jobs.toml index 091834d..4727a7c 100644 --- a/src/session_ops/jobs.toml +++ b/src/session_ops/jobs.toml @@ -47,8 +47,8 @@ entry = "session_ops.zendesk.digest_job:main" args = ["--state", "{state}/seen.json"] user = "zendesk" env_files = ["/etc/session-ops/zendesk.env"] -env = ["ZENDESK_SUBDOMAIN", "ZENDESK_EMAIL", "ZENDESK_API_TOKEN", "ZENDESK_DISCORD_WEBHOOK_URL", - "ANTHROPIC_API_KEY"] +# The Zendesk credentials are either the OAuth client or the API token; the job checks. +env = ["ZENDESK_SUBDOMAIN", "ZENDESK_DISCORD_WEBHOOK_URL", "ANTHROPIC_API_KEY"] channel_env = "ZENDESK_DISCORD_WEBHOOK_URL" max_age_hours = 80 # A full 1000-ticket resolve is ten bulk jobs polled for up to 300 s each. diff --git a/src/session_ops/zendesk/api.py b/src/session_ops/zendesk/api.py index 9c0b83a..666ff6c 100644 --- a/src/session_ops/zendesk/api.py +++ b/src/session_ops/zendesk/api.py @@ -1,14 +1,18 @@ """Zendesk's API as the jobs use it: tickets, their comments and users, the markers a run leaves, and what a customer's side of a ticket looks like. """ +import os import re import sys +import threading +import time from datetime import datetime import requests from session_ops.shared import http from session_ops.shared.discord import clip +from session_ops.shared.env import get_env from session_ops.shared.text import squash @@ -25,10 +29,66 @@ SEARCH_RESULT_LIMIT = 1000 -def zendesk_session(email, token): +# Renew this long before expiry so a request never leaves with a token that dies in flight. +TOKEN_RENEW_MARGIN_SECONDS = 120 + + +class ClientCredentials(requests.auth.AuthBase): + """Bearer auth from an OAuth client-credentials grant, renewed as it nears expiry. + + The token acts as the admin who created the OAuth client. Zendesk issues no + refresh token for this grant, so renewing is a fresh grant with the same secret. + https://developer.zendesk.com/api-reference/ticketing/oauth/grant_type_tokens/ + """ + + def __init__(self, subdomain, client_id, client_secret): + self.url = f"https://{subdomain}.zendesk.com/oauth/tokens" + self.client_id = client_id + self.client_secret = client_secret + self.transport = http.Session() + self.lock = threading.Lock() + self.token = None + self.renew_at = 0.0 + + def current(self): + with self.lock: + if self.token is None or time.monotonic() >= self.renew_at: + resp = self.transport.request("POST", self.url, json={ + "grant_type": "client_credentials", "client_id": self.client_id, + "client_secret": self.client_secret, "scope": "read write"}) + if not 200 <= resp.status_code < 300: + # The body names the cause (invalid_client, invalid_scope) and + # never echoes the secret. + raise RuntimeError(f"Zendesk refused the OAuth client: HTTP " + f"{resp.status_code} {resp.text[:200]}") + body = resp.json() + self.token = body["access_token"] + # A null expires_in is a token that does not expire. + lifetime = body.get("expires_in") or float("inf") + self.renew_at = time.monotonic() + lifetime - TOKEN_RENEW_MARGIN_SECONDS + return self.token + + def __call__(self, request): + request.headers["Authorization"] = f"Bearer {self.current()}" + return request + + +def zendesk_session(subdomain, email=None, api_token=None): + """A session authenticated as the reply-flow's admin user. + + OAuth when ZENDESK_OAUTH_CLIENT_ID and ZENDESK_OAUTH_CLIENT_SECRET are set, else + the API token, which Zendesk stops accepting on 2027-04-30. `email` and + `api_token` override their env vars, as the jobs' --email and --api-token do. + """ session = http.Session() - # Zendesk API-token auth: username is "{email}/token", password is the token. - session.auth = (f"{email}/token", token) + client_id = os.environ.get("ZENDESK_OAUTH_CLIENT_ID") + client_secret = os.environ.get("ZENDESK_OAUTH_CLIENT_SECRET") + if client_id and client_secret: + session.auth = ClientCredentials(subdomain, client_id, client_secret) + else: + # Zendesk API-token auth: username is "{email}/token", password is the token. + session.auth = (f"{get_env('ZENDESK_EMAIL', email)}/token", + get_env("ZENDESK_API_TOKEN", api_token)) session.headers["Accept"] = "application/json" return session diff --git a/src/session_ops/zendesk/note_reply.py b/src/session_ops/zendesk/note_reply.py index 8ffab10..22679c4 100644 --- a/src/session_ops/zendesk/note_reply.py +++ b/src/session_ops/zendesk/note_reply.py @@ -47,8 +47,11 @@ Config (env vars, or flags for local runs): ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com - ZENDESK_EMAIL agent email for API token auth; authors every comment - ZENDESK_API_TOKEN Zendesk API token + ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET + a confidential OAuth client; its token acts as, and + authors every comment as, the admin who created it. Wins over the API token when both are set + ZENDESK_EMAIL agent email for API token auth (without the OAuth client) + ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 ZENDESK_HOUSE_ANSWERS (optional) path to the house-answer file — what support usually replied to each kind of problem, per platform. Absent, drafting works exactly as it does without it @@ -1327,8 +1330,7 @@ def main(argv=None): help="do everything except write to Zendesk") args = parser.parse_args(argv) subdomain = get_env("ZENDESK_SUBDOMAIN") - session = api.zendesk_session(get_env("ZENDESK_EMAIL"), - get_env("ZENDESK_API_TOKEN")) + session = api.zendesk_session(subdomain) api_user = api_user_id(session, subdomain) ticket = api.fetch_ticket(session, subdomain, args.ticket) diff --git a/src/session_ops/zendesk/relay.py b/src/session_ops/zendesk/relay.py index d85ab12..59b64c2 100644 --- a/src/session_ops/zendesk/relay.py +++ b/src/session_ops/zendesk/relay.py @@ -26,8 +26,11 @@ Config (env vars): ZENDESK_SUBDOMAIN e.g. "mycompany" - ZENDESK_EMAIL agent email for API token auth - ZENDESK_API_TOKEN Zendesk API token + ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET + a confidential OAuth client; its token acts as the admin + who created it. Wins over the API token when both are set + ZENDESK_EMAIL agent email for API token auth (without the OAuth client) + ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 ZENDESK_WEBHOOK_SECRET shared secret Zendesk signs its webhooks with. Unset refuses every request RELAY_DRY_RUN (optional) "1" passes --dry-run to note_reply.py, so the diff --git a/src/session_ops/zendesk/resolve_reviews.py b/src/session_ops/zendesk/resolve_reviews.py index 0e44a3b..4e6a50f 100644 --- a/src/session_ops/zendesk/resolve_reviews.py +++ b/src/session_ops/zendesk/resolve_reviews.py @@ -49,8 +49,11 @@ Config (env vars, or flags for local runs): ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com - ZENDESK_EMAIL agent email for API token auth - ZENDESK_API_TOKEN Zendesk API token + ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET + a confidential OAuth client; its token acts as the admin + who created it. Wins over the API token when both are set + ZENDESK_EMAIL agent email for API token auth (without the OAuth client) + ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 ZENDESK_DISCORD_WEBHOOK_URL Discord incoming webhook for the triage channel, the one the digest posts to (only needed with --apply) @@ -338,15 +341,15 @@ def main(argv=None): parser.add_argument("--no-discord", action="store_true", help="Solve the tickets without posting the summary to Discord.") parser.add_argument("--subdomain", help="Zendesk subdomain (else ZENDESK_SUBDOMAIN).") - parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL).") - parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN).") + parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL). " + "Unused when the OAuth client is configured.") + parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN). " + "Unused when the OAuth client is configured.") parser.add_argument("--webhook", help="Discord webhook URL (else ZENDESK_DISCORD_WEBHOOK_URL).") args = parser.parse_args(argv) subdomain = get_env("ZENDESK_SUBDOMAIN", args.subdomain) - email = get_env("ZENDESK_EMAIL", args.email) - api_token = get_env("ZENDESK_API_TOKEN", args.api_token) # Resolved up front, before anything is fetched or solved: a missing webhook # should stop the run rather than have it bulk-edit tickets it cannot report. A # dry run posts nothing, so it never needs one. @@ -354,7 +357,7 @@ def main(argv=None): webhook = get_env("ZENDESK_DISCORD_WEBHOOK_URL", args.webhook, required=needs_webhook) - session = api.zendesk_session(email, api_token) + session = api.zendesk_session(subdomain, args.email, args.api_token) query = build_query() # Every match, not the newest 1000: the tail of this query is held open by # low-star reviews the job never solves, so a plain fetch hides the solvable diff --git a/src/session_ops/zendesk/triage.py b/src/session_ops/zendesk/triage.py index 659e42a..87069be 100644 --- a/src/session_ops/zendesk/triage.py +++ b/src/session_ops/zendesk/triage.py @@ -28,8 +28,11 @@ Config (env vars, or flags for local runs): ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com - ZENDESK_EMAIL agent email for API token auth - ZENDESK_API_TOKEN Zendesk API token + ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET + a confidential OAuth client; its token acts as the admin + who created it. Wins over the API token when both are set + ZENDESK_EMAIL agent email for API token auth (without the OAuth client) + ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 ANTHROPIC_API_KEY Claude API key (not needed with --findings or --dump-batch) ZENDESK_DISCORD_WEBHOOK_URL Discord incoming webhook for the triage channel, shared @@ -1038,8 +1041,10 @@ def build_messages(findings, subdomain, stats=None, updated_ids=None): def main(argv=None): parser = argparse.ArgumentParser(description="Triage open Zendesk tickets with Claude and post a Discord summary.") parser.add_argument("--subdomain", help="Zendesk subdomain (else ZENDESK_SUBDOMAIN).") - parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL).") - parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN).") + parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL). " + "Unused when the OAuth client is configured.") + parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN). " + "Unused when the OAuth client is configured.") parser.add_argument("--webhook", help="Discord webhook URL (else ZENDESK_DISCORD_WEBHOOK_URL).") parser.add_argument("--query", help="Zendesk search query (else ZENDESK_QUERY, else default). " @@ -1110,9 +1115,6 @@ def main(argv=None): findings = load_findings(args.findings) print(f"Loaded {len(findings)} findings from {args.findings}.") else: - email = get_env("ZENDESK_EMAIL", args.email) - api_token = get_env("ZENDESK_API_TOKEN", args.api_token) - # An explicit query wins over --window-hours; warn rather than silently drop it. window_start = None explicit_query = args.query or os.environ.get("ZENDESK_QUERY") @@ -1127,7 +1129,7 @@ def main(argv=None): else: query = DEFAULT_QUERY - zd = zendesk_session(email, api_token) + zd = zendesk_session(subdomain, args.email, args.api_token) tickets, total_matched = fetch_tickets(zd, subdomain, query, args.max_tickets) matched = "?" if total_matched is None else total_matched print(f"Fetched {len(tickets)} of {matched} matching tickets (query: {query!r}).") diff --git a/tests/zendesk/test_api.py b/tests/zendesk/test_api.py index 59d513c..c9ce36d 100644 --- a/tests/zendesk/test_api.py +++ b/tests/zendesk/test_api.py @@ -3,7 +3,9 @@ """ import contextlib import io +import os import unittest +from unittest import mock import requests @@ -108,5 +110,80 @@ def test_only_sunshine_channels_are_messaging(self): self.assertFalse(api.is_messaging({})) +class TestClientCredentials(unittest.TestCase): + def auth(self, *responses): + auth = api.ClientCredentials("acme", "client", "s3cret") + auth.transport = FakeSession(list(responses)) + return auth + + def grant(self, token, expires_in=1800): + return FakeResponse({"access_token": token, "token_type": "bearer", + "expires_in": expires_in}, status_code=201) + + def test_the_grant_is_a_client_credentials_post_to_the_token_endpoint(self): + auth = self.auth(self.grant("t1")) + self.assertEqual(auth.current(), "t1") + method, url, kwargs = auth.transport.calls[0] + self.assertEqual((method, url), ("POST", "https://acme.zendesk.com/oauth/tokens")) + self.assertEqual(kwargs["json"]["grant_type"], "client_credentials") + self.assertEqual(kwargs["json"]["client_secret"], "s3cret") + + def test_a_token_is_reused_until_it_nears_expiry_then_renewed(self): + auth = self.auth(self.grant("t1"), self.grant("t2")) + self.assertEqual([auth.current(), auth.current()], ["t1", "t1"]) + auth.renew_at = 0.0 + self.assertEqual(auth.current(), "t2") + self.assertEqual(len(auth.transport.calls), 2) + + def test_a_token_without_expiry_is_never_renewed(self): + auth = self.auth(self.grant("t1", expires_in=None)) + self.assertEqual(auth.current(), "t1") + self.assertEqual(auth.renew_at, float("inf")) + + def test_a_short_lived_token_is_renewed_on_the_next_request(self): + auth = self.auth(self.grant("t1", expires_in=60), self.grant("t2")) + self.assertEqual([auth.current(), auth.current()], ["t1", "t2"]) + + def test_a_refused_grant_raises_without_the_secret(self): + auth = self.auth(FakeResponse({"error": "invalid_client"}, status_code=401)) + with self.assertRaises(RuntimeError) as caught: + auth.current() + self.assertIn("invalid_client", str(caught.exception)) + self.assertNotIn("s3cret", str(caught.exception)) + + def test_requests_carry_the_bearer_token(self): + auth = self.auth(self.grant("t1")) + request = requests.Request("GET", "https://acme.zendesk.com/api/v2/x").prepare() + self.assertEqual(auth(request).headers["Authorization"], "Bearer t1") + + +class TestZendeskSession(unittest.TestCase): + OAUTH = {"ZENDESK_OAUTH_CLIENT_ID": "client", "ZENDESK_OAUTH_CLIENT_SECRET": "s3cret"} + TOKEN = {"ZENDESK_EMAIL": "agent@acme.test", "ZENDESK_API_TOKEN": "tok"} + + def session(self, env, *args): + with mock.patch.dict(os.environ, env, clear=True): + return api.zendesk_session("acme", *args) + + def test_oauth_wins_when_both_are_configured(self): + auth = self.session({**self.OAUTH, **self.TOKEN}).auth + self.assertIsInstance(auth, api.ClientCredentials) + self.assertEqual(auth.url, "https://acme.zendesk.com/oauth/tokens") + + def test_the_api_token_is_used_without_a_complete_oauth_client(self): + for oauth in ({}, {"ZENDESK_OAUTH_CLIENT_ID": "client"}): + with self.subTest(oauth=oauth): + self.assertEqual(self.session({**oauth, **self.TOKEN}).auth, + ("agent@acme.test/token", "tok")) + + def test_flags_override_the_api_token_env(self): + self.assertEqual(self.session(self.TOKEN, "flag@acme.test", "flagtok").auth, + ("flag@acme.test/token", "flagtok")) + + def test_no_credentials_at_all_stops_the_run(self): + with self.assertRaises(SystemExit): + self.session({}) + + if __name__ == "__main__": unittest.main() From 6b719f023ae2df76fc6b657dd41893cfd2df0b0a Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Tue, 24 Nov 2026 12:02:56 +1100 Subject: [PATCH 2/3] feat(zendesk): drop API-token auth, the OAuth client is required ZENDESK_OAUTH_CLIENT_ID and ZENDESK_OAUTH_CLIENT_SECRET are now the only Zendesk credentials, and the job runner requires them. The --email and --api-token flags are gone with the token they configured. --- deploy/env/zendesk.env.example | 4 --- docs/jobs/token-expiry.md | 2 +- docs/jobs/zendesk-digest.md | 6 ++-- src/session_ops/jobs.toml | 4 +-- src/session_ops/monitor/alert.py | 2 +- src/session_ops/zendesk/api.py | 22 ++++---------- src/session_ops/zendesk/note_reply.py | 6 ++-- src/session_ops/zendesk/relay.py | 4 +-- src/session_ops/zendesk/resolve_reviews.py | 12 ++------ src/session_ops/zendesk/triage.py | 12 ++------ tests/zendesk/test_api.py | 35 ++++++++-------------- tests/zendesk/test_note_reply.py | 3 +- tests/zendesk/test_relay.py | 4 +-- tests/zendesk/test_resolve_reviews.py | 2 +- 14 files changed, 38 insertions(+), 80 deletions(-) diff --git a/deploy/env/zendesk.env.example b/deploy/env/zendesk.env.example index 17b2936..668cb18 100644 --- a/deploy/env/zendesk.env.example +++ b/deploy/env/zendesk.env.example @@ -9,10 +9,6 @@ ZENDESK_SUBDOMAIN= # clients), created while logged in as the admin every comment should come from. ZENDESK_OAUTH_CLIENT_ID= ZENDESK_OAUTH_CLIENT_SECRET= -# Used only while the OAuth client above is unset; Zendesk refuses API tokens from -# 2027-04-30. ZENDESK_EMAIL authors every comment the reply flow posts. -ZENDESK_EMAIL= -ZENDESK_API_TOKEN= # The triage channel: the digest, the review tally and this job's failures. ZENDESK_DISCORD_WEBHOOK_URL= # The secret on the Zendesk webhook. Empty refuses every note webhook. diff --git a/docs/jobs/token-expiry.md b/docs/jobs/token-expiry.md index 06826c7..5e83588 100644 --- a/docs/jobs/token-expiry.md +++ b/docs/jobs/token-expiry.md @@ -20,5 +20,5 @@ as Crowdin's, counts from 00:00 UTC that day. `CROWDIN_API_TOKEN` is reported on every daily run until `expiry.toml` has a date or `"never"` for it. -The Zendesk API token, the Claude API key, the Discord webhooks and the GitHub App key +The Zendesk OAuth client, the Claude API key, the Discord webhooks and the GitHub App key do not expire. diff --git a/docs/jobs/zendesk-digest.md b/docs/jobs/zendesk-digest.md index bbb6f3b..678382d 100644 --- a/docs/jobs/zendesk-digest.md +++ b/docs/jobs/zendesk-digest.md @@ -5,7 +5,7 @@ Claude reviews the Zendesk tickets awaiting a reply — `new` and `open`, no app | | | | --- | --- | | Runs | `session-ops-queue.timer`, Mon–Fri from 10:00 Australia/Melbourne, after `github-prs-digest`: `zendesk-resolve-reviews --apply`, then `zendesk-triage` | -| Secrets | `/etc/session-ops/zendesk.env`: the Zendesk API token, the triage channel's webhook, and the Claude API key | +| Secrets | `/etc/session-ops/zendesk.env`: the Zendesk OAuth client, the triage channel's webhook, and the Claude API key | | Dry run | `session-ops run zendesk-digest --dry-run`; `uv run zendesk-triage --window-hours 72 --dry-run` from a checkout. On the host, through `systemd-run` as in [deploy/README.md](../../deploy/README.md). | | Re-run | `systemctl start session-ops@zendesk-digest.service` | | Logs | `journalctl -u session-ops@zendesk-digest -n 50 --no-pager` | @@ -131,9 +131,7 @@ Two caveats worth knowing: | Secret | Description | | --------------------- | ------------------------------------------------------- | | `ZENDESK_SUBDOMAIN` | Zendesk subdomain (`mycompany` → `mycompany.zendesk.com`) | -| `ZENDESK_OAUTH_CLIENT_ID`, `ZENDESK_OAUTH_CLIENT_SECRET` | A confidential OAuth client. Its token acts as the admin who created it, so create it as the admin the reply flow posts as. Wins over the API token when both are set | -| `ZENDESK_EMAIL` | Agent email for API-token auth, used only without the OAuth client | -| `ZENDESK_API_TOKEN` | Zendesk API token, used only without the OAuth client. Zendesk refuses API tokens from 2027-04-30 | +| `ZENDESK_OAUTH_CLIENT_ID`, `ZENDESK_OAUTH_CLIENT_SECRET` | A confidential OAuth client. Its token acts as the admin who created it, so create it as the admin the reply flow posts as | | `ZENDESK_DISCORD_WEBHOOK_URL` | Discord incoming webhook for the triage channel, shared with the tally and the failure alerts | ## Claude Authentication diff --git a/src/session_ops/jobs.toml b/src/session_ops/jobs.toml index 4727a7c..35364a0 100644 --- a/src/session_ops/jobs.toml +++ b/src/session_ops/jobs.toml @@ -47,8 +47,8 @@ entry = "session_ops.zendesk.digest_job:main" args = ["--state", "{state}/seen.json"] user = "zendesk" env_files = ["/etc/session-ops/zendesk.env"] -# The Zendesk credentials are either the OAuth client or the API token; the job checks. -env = ["ZENDESK_SUBDOMAIN", "ZENDESK_DISCORD_WEBHOOK_URL", "ANTHROPIC_API_KEY"] +env = ["ZENDESK_SUBDOMAIN", "ZENDESK_OAUTH_CLIENT_ID", "ZENDESK_OAUTH_CLIENT_SECRET", + "ZENDESK_DISCORD_WEBHOOK_URL", "ANTHROPIC_API_KEY"] channel_env = "ZENDESK_DISCORD_WEBHOOK_URL" max_age_hours = 80 # A full 1000-ticket resolve is ten bulk jobs polled for up to 300 s each. diff --git a/src/session_ops/monitor/alert.py b/src/session_ops/monitor/alert.py index e8c2317..afe6d7a 100644 --- a/src/session_ops/monitor/alert.py +++ b/src/session_ops/monitor/alert.py @@ -129,7 +129,7 @@ def main(argv=None): message = build_message(unit, socket.gethostname(), detail=detail, result=unit_property(unit, "Result")) payload = {"content": message, "allowed_mentions": {"parse": []}} - # A fresh session, never a Zendesk one — that carries the API-token auth header, + # A fresh session, never a Zendesk one: that carries the Zendesk credentials, # and Discord has no business receiving it. if not post_to_discord(http.Session(), webhook, [payload]): sys.exit("Could not post the failure to Discord.") diff --git a/src/session_ops/zendesk/api.py b/src/session_ops/zendesk/api.py index 666ff6c..4ad60e3 100644 --- a/src/session_ops/zendesk/api.py +++ b/src/session_ops/zendesk/api.py @@ -1,7 +1,6 @@ """Zendesk's API as the jobs use it: tickets, their comments and users, the markers a run leaves, and what a customer's side of a ticket looks like. """ -import os import re import sys import threading @@ -73,22 +72,11 @@ def __call__(self, request): return request -def zendesk_session(subdomain, email=None, api_token=None): - """A session authenticated as the reply-flow's admin user. - - OAuth when ZENDESK_OAUTH_CLIENT_ID and ZENDESK_OAUTH_CLIENT_SECRET are set, else - the API token, which Zendesk stops accepting on 2027-04-30. `email` and - `api_token` override their env vars, as the jobs' --email and --api-token do. - """ +def zendesk_session(subdomain): + """A session authenticated as the admin who created the OAuth client.""" session = http.Session() - client_id = os.environ.get("ZENDESK_OAUTH_CLIENT_ID") - client_secret = os.environ.get("ZENDESK_OAUTH_CLIENT_SECRET") - if client_id and client_secret: - session.auth = ClientCredentials(subdomain, client_id, client_secret) - else: - # Zendesk API-token auth: username is "{email}/token", password is the token. - session.auth = (f"{get_env('ZENDESK_EMAIL', email)}/token", - get_env("ZENDESK_API_TOKEN", api_token)) + session.auth = ClientCredentials(subdomain, get_env("ZENDESK_OAUTH_CLIENT_ID"), + get_env("ZENDESK_OAUTH_CLIENT_SECRET")) session.headers["Accept"] = "application/json" return session @@ -152,7 +140,7 @@ def fetch_tickets(session, subdomain, query, max_tickets): resp = session.request("GET", url, params=params) params = None # next_page already carries the query if resp.status_code == 403: - sys.exit("Zendesk returned 403 — the API token/email may lack search access.") + sys.exit("Zendesk returned 403: the OAuth client may lack search access.") # 422 past the result limit: `cap` should have stopped us first, so this only # fires if the account's effective limit is lower than documented. Keep the # tickets already in hand — a partial digest beats no digest — and let the diff --git a/src/session_ops/zendesk/note_reply.py b/src/session_ops/zendesk/note_reply.py index 22679c4..51753d6 100644 --- a/src/session_ops/zendesk/note_reply.py +++ b/src/session_ops/zendesk/note_reply.py @@ -49,9 +49,7 @@ ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET a confidential OAuth client; its token acts as, and - authors every comment as, the admin who created it. Wins over the API token when both are set - ZENDESK_EMAIL agent email for API token auth (without the OAuth client) - ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 + authors every comment as, the admin who created it ZENDESK_HOUSE_ANSWERS (optional) path to the house-answer file — what support usually replied to each kind of problem, per platform. Absent, drafting works exactly as it does without it @@ -210,7 +208,7 @@ def comment_text(comment): def api_user_id(session, subdomain): - """The user the API token authenticates as. + """The user the OAuth client authenticates as. Its own notes are skipped when looking for a command, which is the in-code half of the loop guard. The other half is the Zendesk trigger, which should exclude diff --git a/src/session_ops/zendesk/relay.py b/src/session_ops/zendesk/relay.py index 59b64c2..44f5507 100644 --- a/src/session_ops/zendesk/relay.py +++ b/src/session_ops/zendesk/relay.py @@ -28,9 +28,7 @@ ZENDESK_SUBDOMAIN e.g. "mycompany" ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET a confidential OAuth client; its token acts as the admin - who created it. Wins over the API token when both are set - ZENDESK_EMAIL agent email for API token auth (without the OAuth client) - ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 + who created it ZENDESK_WEBHOOK_SECRET shared secret Zendesk signs its webhooks with. Unset refuses every request RELAY_DRY_RUN (optional) "1" passes --dry-run to note_reply.py, so the diff --git a/src/session_ops/zendesk/resolve_reviews.py b/src/session_ops/zendesk/resolve_reviews.py index 4e6a50f..e33bfed 100644 --- a/src/session_ops/zendesk/resolve_reviews.py +++ b/src/session_ops/zendesk/resolve_reviews.py @@ -51,9 +51,7 @@ ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET a confidential OAuth client; its token acts as the admin - who created it. Wins over the API token when both are set - ZENDESK_EMAIL agent email for API token auth (without the OAuth client) - ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 + who created it ZENDESK_DISCORD_WEBHOOK_URL Discord incoming webhook for the triage channel, the one the digest posts to (only needed with --apply) @@ -316,7 +314,7 @@ def build_message(counts, *, url=None, examined=0, attempted=0, remaining=0, def post_summary(webhook_url, message): """Post the summary; return whether Discord accepted it. - A fresh session, never the Zendesk one — that carries the API-token auth header, + A fresh session, never the Zendesk one: that carries the Zendesk credentials, and Discord has no business receiving it. """ return bool(post_to_discord(http.Session(), webhook_url, @@ -341,10 +339,6 @@ def main(argv=None): parser.add_argument("--no-discord", action="store_true", help="Solve the tickets without posting the summary to Discord.") parser.add_argument("--subdomain", help="Zendesk subdomain (else ZENDESK_SUBDOMAIN).") - parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL). " - "Unused when the OAuth client is configured.") - parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN). " - "Unused when the OAuth client is configured.") parser.add_argument("--webhook", help="Discord webhook URL (else ZENDESK_DISCORD_WEBHOOK_URL).") args = parser.parse_args(argv) @@ -357,7 +351,7 @@ def main(argv=None): webhook = get_env("ZENDESK_DISCORD_WEBHOOK_URL", args.webhook, required=needs_webhook) - session = api.zendesk_session(subdomain, args.email, args.api_token) + session = api.zendesk_session(subdomain) query = build_query() # Every match, not the newest 1000: the tail of this query is held open by # low-star reviews the job never solves, so a plain fetch hides the solvable diff --git a/src/session_ops/zendesk/triage.py b/src/session_ops/zendesk/triage.py index 87069be..3f8fdd8 100644 --- a/src/session_ops/zendesk/triage.py +++ b/src/session_ops/zendesk/triage.py @@ -30,9 +30,7 @@ ZENDESK_SUBDOMAIN e.g. "mycompany" -> https://mycompany.zendesk.com ZENDESK_OAUTH_CLIENT_ID, ZENDESK_OAUTH_CLIENT_SECRET a confidential OAuth client; its token acts as the admin - who created it. Wins over the API token when both are set - ZENDESK_EMAIL agent email for API token auth (without the OAuth client) - ZENDESK_API_TOKEN Zendesk API token, refused by Zendesk from 2027-04-30 + who created it ANTHROPIC_API_KEY Claude API key (not needed with --findings or --dump-batch) ZENDESK_DISCORD_WEBHOOK_URL Discord incoming webhook for the triage channel, shared @@ -1041,10 +1039,6 @@ def build_messages(findings, subdomain, stats=None, updated_ids=None): def main(argv=None): parser = argparse.ArgumentParser(description="Triage open Zendesk tickets with Claude and post a Discord summary.") parser.add_argument("--subdomain", help="Zendesk subdomain (else ZENDESK_SUBDOMAIN).") - parser.add_argument("--email", help="Zendesk agent email (else ZENDESK_EMAIL). " - "Unused when the OAuth client is configured.") - parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN). " - "Unused when the OAuth client is configured.") parser.add_argument("--webhook", help="Discord webhook URL (else ZENDESK_DISCORD_WEBHOOK_URL).") parser.add_argument("--query", help="Zendesk search query (else ZENDESK_QUERY, else default). " @@ -1129,7 +1123,7 @@ def main(argv=None): else: query = DEFAULT_QUERY - zd = zendesk_session(subdomain, args.email, args.api_token) + zd = zendesk_session(subdomain) tickets, total_matched = fetch_tickets(zd, subdomain, query, args.max_tickets) matched = "?" if total_matched is None else total_matched print(f"Fetched {len(tickets)} of {matched} matching tickets (query: {query!r}).") @@ -1273,7 +1267,7 @@ def main(argv=None): f"next run.") return - # A fresh session, never the Zendesk one: that carries the API-token auth header. + # A fresh session, never the Zendesk one: that carries the Zendesk credentials. posted = post_to_discord(http.Session(), discord.components_webhook_url(webhook), messages) print(f"Posted {posted} of {len(messages)} Discord message(s).") diff --git a/tests/zendesk/test_api.py b/tests/zendesk/test_api.py index c9ce36d..f24b520 100644 --- a/tests/zendesk/test_api.py +++ b/tests/zendesk/test_api.py @@ -158,31 +158,22 @@ def test_requests_carry_the_bearer_token(self): class TestZendeskSession(unittest.TestCase): - OAUTH = {"ZENDESK_OAUTH_CLIENT_ID": "client", "ZENDESK_OAUTH_CLIENT_SECRET": "s3cret"} - TOKEN = {"ZENDESK_EMAIL": "agent@acme.test", "ZENDESK_API_TOKEN": "tok"} - - def session(self, env, *args): + def session(self, env): with mock.patch.dict(os.environ, env, clear=True): - return api.zendesk_session("acme", *args) + return api.zendesk_session("acme") - def test_oauth_wins_when_both_are_configured(self): - auth = self.session({**self.OAUTH, **self.TOKEN}).auth + def test_the_session_authenticates_with_the_oauth_client(self): + auth = self.session({"ZENDESK_OAUTH_CLIENT_ID": "client", + "ZENDESK_OAUTH_CLIENT_SECRET": "s3cret"}).auth self.assertIsInstance(auth, api.ClientCredentials) - self.assertEqual(auth.url, "https://acme.zendesk.com/oauth/tokens") - - def test_the_api_token_is_used_without_a_complete_oauth_client(self): - for oauth in ({}, {"ZENDESK_OAUTH_CLIENT_ID": "client"}): - with self.subTest(oauth=oauth): - self.assertEqual(self.session({**oauth, **self.TOKEN}).auth, - ("agent@acme.test/token", "tok")) - - def test_flags_override_the_api_token_env(self): - self.assertEqual(self.session(self.TOKEN, "flag@acme.test", "flagtok").auth, - ("flag@acme.test/token", "flagtok")) - - def test_no_credentials_at_all_stops_the_run(self): - with self.assertRaises(SystemExit): - self.session({}) + self.assertEqual((auth.url, auth.client_id, auth.client_secret), + ("https://acme.zendesk.com/oauth/tokens", "client", "s3cret")) + + def test_an_incomplete_oauth_client_stops_the_run(self): + for env in ({}, {"ZENDESK_OAUTH_CLIENT_ID": "client"}, + {"ZENDESK_EMAIL": "agent@acme.test", "ZENDESK_API_TOKEN": "tok"}): + with self.subTest(env=env), self.assertRaises(SystemExit): + self.session(env) if __name__ == "__main__": diff --git a/tests/zendesk/test_note_reply.py b/tests/zendesk/test_note_reply.py index 85414df..75fd2b7 100644 --- a/tests/zendesk/test_note_reply.py +++ b/tests/zendesk/test_note_reply.py @@ -1288,7 +1288,8 @@ def test_the_brief_is_bounded(self): class Model(unittest.TestCase): def run_main(self, action, flag=(), ticket=None, open_chat=False): - env = {"ZENDESK_SUBDOMAIN": "sub", "ZENDESK_EMAIL": "e", "ZENDESK_API_TOKEN": "t"} + env = {"ZENDESK_SUBDOMAIN": "sub", "ZENDESK_OAUTH_CLIENT_ID": "c", + "ZENDESK_OAUTH_CLIENT_SECRET": "s"} command = {"id": 9, "author": AGENT, "action": action, "brief": "x"} ran = [] with mock.patch.dict(os.environ, env), \ diff --git a/tests/zendesk/test_relay.py b/tests/zendesk/test_relay.py index c925350..ff0c7c3 100644 --- a/tests/zendesk/test_relay.py +++ b/tests/zendesk/test_relay.py @@ -29,8 +29,8 @@ # arbitrary — but it must not be empty, since an unset secret refuses everything. ZENDESK_SECRET = "s3cret" -BASE_ENV = {"ZENDESK_SUBDOMAIN": "acme", "ZENDESK_EMAIL": "agent@acme.test", - "ZENDESK_API_TOKEN": "tok", "RELAY_DRY_RUN": None} +BASE_ENV = {"ZENDESK_SUBDOMAIN": "acme", "ZENDESK_OAUTH_CLIENT_ID": "client", + "ZENDESK_OAUTH_CLIENT_SECRET": "secret", "RELAY_DRY_RUN": None} class Env: diff --git a/tests/zendesk/test_resolve_reviews.py b/tests/zendesk/test_resolve_reviews.py index d29cae2..c678061 100644 --- a/tests/zendesk/test_resolve_reviews.py +++ b/tests/zendesk/test_resolve_reviews.py @@ -348,7 +348,7 @@ def test_the_message_fits_one_discord_post(self): self.assertLess(len(message), triage.MAX_MESSAGE_CHARS) def test_the_summary_does_not_reuse_the_zendesk_session(self): - """That session carries the API-token auth header; Discord must not see it.""" + """That session carries the Zendesk credentials; Discord must not see them.""" posted = [] def post(session, url, messages): posted.append((session, url, messages)) From d2595942f634ecc89b17bd23fcee4036cfe401d9 Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Tue, 24 Nov 2026 12:26:53 +1100 Subject: [PATCH 3/3] fix(zendesk): renew the OAuth token before a retried call can outlive it urllib3 resends a call's original Authorization header on every retry, so the renewal margin now covers the session's whole default retry span (510 s) rather than two minutes. --- src/session_ops/zendesk/api.py | 7 +++++-- tests/zendesk/test_api.py | 11 +++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/session_ops/zendesk/api.py b/src/session_ops/zendesk/api.py index 4ad60e3..9e17362 100644 --- a/src/session_ops/zendesk/api.py +++ b/src/session_ops/zendesk/api.py @@ -28,8 +28,11 @@ SEARCH_RESULT_LIMIT = 1000 -# Renew this long before expiry so a request never leaves with a token that dies in flight. -TOKEN_RENEW_MARGIN_SECONDS = 120 +# The token is set once per call and urllib3's retries resend it, so it must outlive the +# session's whole retry span: every attempt timing out and every wait at its longest. +# A caller passing a larger `attempts` than the default can still outrun it. +TOKEN_RENEW_MARGIN_SECONDS = 60 + (http.DEFAULT_ATTEMPTS - 1) * ( + http.DEFAULT_TIMEOUT + max(http.MAX_RETRY_AFTER, http.MAX_BACKOFF)) class ClientCredentials(requests.auth.AuthBase): diff --git a/tests/zendesk/test_api.py b/tests/zendesk/test_api.py index f24b520..9966bdf 100644 --- a/tests/zendesk/test_api.py +++ b/tests/zendesk/test_api.py @@ -9,6 +9,7 @@ import requests +from session_ops.shared import http from session_ops.shared.testing import FakeResponse, FakeSession, NonJsonResponse from session_ops.zendesk import api, triage @@ -140,10 +141,16 @@ def test_a_token_without_expiry_is_never_renewed(self): self.assertEqual(auth.current(), "t1") self.assertEqual(auth.renew_at, float("inf")) - def test_a_short_lived_token_is_renewed_on_the_next_request(self): - auth = self.auth(self.grant("t1", expires_in=60), self.grant("t2")) + def test_a_token_shorter_than_the_margin_is_renewed_on_the_next_request(self): + lifetime = api.TOKEN_RENEW_MARGIN_SECONDS - 1 + auth = self.auth(self.grant("t1", expires_in=lifetime), self.grant("t2")) self.assertEqual([auth.current(), auth.current()], ["t1", "t2"]) + def test_the_margin_outlasts_a_call_retried_through_its_whole_budget(self): + waits = (http.DEFAULT_ATTEMPTS - 1) * max(http.MAX_RETRY_AFTER, http.MAX_BACKOFF) + sends = (http.DEFAULT_ATTEMPTS - 1) * http.DEFAULT_TIMEOUT + self.assertGreater(api.TOKEN_RENEW_MARGIN_SECONDS, waits + sends) + def test_a_refused_grant_raises_without_the_secret(self): auth = self.auth(FakeResponse({"error": "invalid_client"}, status_code=401)) with self.assertRaises(RuntimeError) as caught: