Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions deploy/env/zendesk.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
# Claude API key for the digest, the transcripts and the `claude:` notes.
ANTHROPIC_API_KEY=
ZENDESK_SUBDOMAIN=
# Authors every comment the reply flow posts.
ZENDESK_EMAIL=
ZENDESK_API_TOKEN=
# 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=
# 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.
Expand Down
2 changes: 1 addition & 1 deletion docs/jobs/token-expiry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 4 additions & 5 deletions docs/jobs/zendesk-digest.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -131,8 +131,7 @@ 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 |
| `ZENDESK_DISCORD_WEBHOOK_URL` | Discord incoming webhook for the triage channel, shared with the tally and the failure alerts |

## Claude Authentication
Expand Down Expand Up @@ -220,7 +219,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
Expand Down Expand Up @@ -300,7 +299,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.

Expand Down
4 changes: 2 additions & 2 deletions src/session_ops/jobs.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
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.
Expand Down
2 changes: 1 addition & 1 deletion src/session_ops/monitor/alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
59 changes: 55 additions & 4 deletions src/session_ops/zendesk/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
"""
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


Expand All @@ -25,10 +28,58 @@
SEARCH_RESULT_LIMIT = 1000


def zendesk_session(email, token):
# 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):
"""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):
"""A session authenticated as the admin who created the OAuth client."""
session = http.Session()
# Zendesk API-token auth: username is "{email}/token", password is the token.
session.auth = (f"{email}/token", token)
session.auth = ClientCredentials(subdomain, get_env("ZENDESK_OAUTH_CLIENT_ID"),
get_env("ZENDESK_OAUTH_CLIENT_SECRET"))
session.headers["Accept"] = "application/json"
return session

Expand Down Expand Up @@ -92,7 +143,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
Expand Down
10 changes: 5 additions & 5 deletions src/session_ops/zendesk/note_reply.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@

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
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
Expand Down Expand Up @@ -207,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
Expand Down Expand Up @@ -1327,8 +1328,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)
Expand Down
5 changes: 3 additions & 2 deletions src/session_ops/zendesk/relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@

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
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
Expand Down
13 changes: 5 additions & 8 deletions src/session_ops/zendesk/resolve_reviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@

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
ZENDESK_DISCORD_WEBHOOK_URL
Discord incoming webhook for the triage channel, the one
the digest posts to (only needed with --apply)
Expand Down Expand Up @@ -313,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,
Expand All @@ -338,23 +339,19 @@ 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("--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.
needs_webhook = args.apply and not args.no_discord
webhook = get_env("ZENDESK_DISCORD_WEBHOOK_URL", args.webhook,
required=needs_webhook)

session = api.zendesk_session(email, 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
Expand Down
14 changes: 5 additions & 9 deletions src/session_ops/zendesk/triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@

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
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
Expand Down Expand Up @@ -1038,8 +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).")
parser.add_argument("--api-token", help="Zendesk API token (else ZENDESK_API_TOKEN).")
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). "
Expand Down Expand Up @@ -1110,9 +1109,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")
Expand All @@ -1127,7 +1123,7 @@ def main(argv=None):
else:
query = DEFAULT_QUERY

zd = zendesk_session(email, 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}).")
Expand Down Expand Up @@ -1271,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).")
Expand Down
Loading