diff --git a/README.md b/README.md index c3b18f7..7975e1e 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,11 @@ share for translations. One package, `session_ops`, deployed to one self-hosted | --- | --- | --- | | `zendesk-digest` | Weekday Discord digest of the Zendesk tickets awaiting a reply, after closing positive app-store reviews | [zendesk-digest](docs/jobs/zendesk-digest.md) | | `zendesk-relay` | Drafts and sends Zendesk replies from `claude:` private notes | [zendesk-relay](docs/jobs/zendesk-relay.md) | +| `session-ops-discord` | `/run` a job and see `/versions` from Discord | [session-ops-discord](docs/jobs/session-ops-discord.md) | | `github-prs-digest` | Weekday Discord digest of open pull requests from outside contributors | [github-prs-digest](docs/jobs/github-prs-digest.md) | | `crowdin-duplicates` | Crowdin string slots holding more than one translation, as they open and close | [crowdin-duplicates](docs/jobs/crowdin-duplicates.md) | | `crowdin-sync` | Weekday: Crowdin translations into iOS, Android and the localization module, and its submodule bumped in each client | [crowdin-sync](docs/jobs/crowdin-sync.md) | | `snode-list` | Weekday: the fallback service node list from the seed nodes into dynamic-assets, Desktop and iOS | [snode-list](docs/jobs/snode-list.md) | -| `release-stats` | On demand: download counts of the latest releases | [release-stats](docs/jobs/release-stats.md) | | `session-ops-silence` | Discord alerts for a job that failed, or stopped running | [session-ops-silence](docs/jobs/session-ops-silence.md) | | `token-expiry` | Discord alerts 14 days, 7 days and 24 hours before a token expires | [token-expiry](docs/jobs/token-expiry.md) | | `store-versions` | Every 5 minutes: each store's Session release against GitHub's, posted as they diverge | [store-versions](docs/jobs/store-versions.md) | diff --git a/deploy/README.md b/deploy/README.md index 2ec337e..1900007 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,9 +6,11 @@ does the work: accounts, venv, env files, units, timers, and migrating an older | Unit | What it is | | --- | --- | -| `session-ops@.timer` → `.service` | One per job; a generated drop-in sets its account, env files and schedule. | +| `session-ops@.timer` → `.service` | One per job with a `schedule`; a generated drop-in sets its account, env files and schedule. | +| `session-ops@.path` → `.service` | For a job with `discord = true`: starts it when `/run` requests it. | | `session-ops-queue.timer` → `.service` | Starts the jobs in `jobs.toml`'s `[queue]`, which then run one at a time in its order. | | `zendesk-relay.service` | Always on, `127.0.0.1:8080`: Zendesk's `claude:` note webhooks. | +| `session-ops-discord.service` | Always on, `127.0.0.1:8081`: the `/run` and `/versions` slash commands. See [Discord commands](#discord-commands). | | `session-ops-alert@.service` | Every unit's `OnFailure=` backstop; see [session-ops-silence](../docs/jobs/session-ops-silence.md). | `session-ops list` shows the jobs; `session-ops run [--dry-run] [-- job arguments]` @@ -60,6 +62,37 @@ From a host that ran the digests out of `/opt/zendesk`, `install.sh` copies thei files and state over. Remove `/opt/zendesk`, `/etc/zendesk` and `/var/lib/zendesk` (and the `github-prs` equivalents) once both digests have run from the new units. +## Discord commands + +What `/run` and `/versions` do, and who may run them: +[session-ops-discord](../docs/jobs/session-ops-discord.md). To set them up: + +1. In the Developer Portal, create an application. Put its public key, its application + id, the server's id and who may run the commands in `/etc/session-ops/discord.env`, + then run `install.sh` again. +2. Invite it with the `applications.commands` scope only: + `https://discord.com/oauth2/authorize?client_id=&scope=applications.commands`. +3. Copy the `location = /discord/interactions` block from + [`nginx-webhooks.conf`](nginx-webhooks.conf) into the live + `/etc/nginx/sites-available/webhooks.session.codes`, which certbot owns, then + `nginx -t && systemctl reload nginx`. Until then the route is a 404 and Discord will + not save the URL. +4. Set its Interactions Endpoint URL to `https://webhooks.session.codes/discord/interactions`. + Discord checks it with a signed PING before saving. +5. Register the commands, with the bot token from the Bot page, typed in rather than kept: + + ```bash + read -rs DISCORD_BOT_TOKEN && export DISCORD_BOT_TOKEN + set -a && . /etc/session-ops/discord.env && set +a + /opt/session-ops/.venv/bin/session-ops discord-register + ``` + +6. The commands start hidden from everyone but server administrators. In Server + Settings → Integrations, allow them for the role or channel that runs jobs. Seeing + them is not running them: the relay's allowlist still decides. + +Register again after changing which jobs have `discord = true`. + ## Secrets Each `/etc/session-ops/.env` has a commented `.env.example` beside it, @@ -79,6 +112,8 @@ systemctl start session-ops@.service && journalctl -fu session-ops@ systemctl start session-ops-alert@test.service # posts to the alerts channel curl -sS -o /dev/null -w '%{http_code}\n' -X POST 127.0.0.1:8080/zendesk/notes \ -H 'Content-Type: application/json' -d '{"ticket_id":"1"}' # expect 401 +curl -sS -o /dev/null -w '%{http_code}\n' -X POST 127.0.0.1:8081/discord/interactions -d '{}' # expect 401 +systemctl list-units 'session-ops@*.path' # one per ready job with discord = true, active ``` ## Rehearsing on a spare host @@ -95,7 +130,10 @@ To end it, stop the timers, then close the rehearsal pull requests: for link in /etc/systemd/system/timers.target.wants/session-ops@*.timer; do [ -L "$link" ] && systemctl disable --now "${link##*/}" done -systemctl disable --now session-ops-queue.timer zendesk-relay.service +for link in /etc/systemd/system/paths.target.wants/session-ops@*.path; do + [ -L "$link" ] && systemctl disable --now "${link##*/}" +done +systemctl disable --now session-ops-queue.timer zendesk-relay.service session-ops-discord.service for repo in session-android session-ios session-localization session-desktop-dynamic-assets \ session-desktop session-app session-website session-appium session-playwright; do gh pr list -R "session-foundation/$repo" --state open --json number,headRefName \ diff --git a/deploy/env/alerts.env.example b/deploy/env/alerts.env.example index 3a0d509..d36b964 100644 --- a/deploy/env/alerts.env.example +++ b/deploy/env/alerts.env.example @@ -1,3 +1,3 @@ -# /etc/session-ops/alerts.env: the OnFailure backstop, the silence checker and -# release-stats. Empty disables the first two, and install.sh warns until it is set. +# /etc/session-ops/alerts.env: the OnFailure backstop and the silence checker. +# Empty disables both, and install.sh warns until it is set. ALERT_DISCORD_WEBHOOK_URL= diff --git a/deploy/env/discord.env.example b/deploy/env/discord.env.example new file mode 100644 index 0000000..6a663de --- /dev/null +++ b/deploy/env/discord.env.example @@ -0,0 +1,16 @@ +# /etc/session-ops/discord.env: the Discord app behind /run and /versions. +# A `#` starts a comment only as a line's first character. Restart session-ops-discord +# after an edit: it reads this file at start. + +# General Information in the Developer Portal. Unset refuses every interaction. +DISCORD_PUBLIC_KEY= +# The one server the commands are registered on and answered from. +DISCORD_GUILD_ID= +# Comma-separated; either list grants. Both empty refuses everybody. +ALLOWED_USER_IDS= +ALLOWED_ROLE_IDS= +# Comma-separated channels the commands work in. Empty allows any channel of the server. +ALLOWED_CHANNEL_IDS= +# For `session-ops discord-register`. Its DISCORD_BOT_TOKEN is typed in when registering, +# not kept here: the relay never needs it. +DISCORD_APP_ID= diff --git a/deploy/install.sh b/deploy/install.sh index cb5eaf7..85cd72f 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -4,8 +4,8 @@ # # It creates the accounts, builds the venv, creates any missing env file empty, moves # state and env files from the layout before session-ops@ units, installs the units -# and each job's drop-ins, and enables every job whose env files have content and no -# other: on its own timer, or on the queue's. It never edits nginx, which certbot owns; see deploy/README.md for the route. +# and each job's drop-ins, and enables every job whose env files have content, and no +# other: on its own timer, on the queue's, or on its path unit. It never edits nginx, which certbot owns; see deploy/README.md for the route. set -eu ROOT=$(cd "$(dirname "$0")/.." && pwd) @@ -37,7 +37,7 @@ account() { id -u "$1" >/dev/null 2>&1 || useradd --system --no-create-home --home /nonexistent --shell /usr/sbin/nologin "$1" } -for user in ghdigest crowdin publisher sessionops; do account "$user"; done +for user in ghdigest crowdin publisher sessionops opsbot; do account "$user"; done # The Claude Code CLI keeps its binary, login and cache under this account's $HOME. if ! id -u zendesk >/dev/null 2>&1; then useradd --system --home /home/zendesk --shell /usr/sbin/nologin zendesk @@ -68,10 +68,9 @@ move /etc/github-prs/env "$ETC/github-prs.env" 600 root move "$ETC/env" "$ETC/alerts.env" 600 root # systemd reads EnvironmentFile= as root before dropping privileges, so these need # no group: a job's account cannot read another job's secrets. -for name in zendesk github-prs crowdin publish alerts; do +for name in zendesk github-prs crowdin publish alerts discord store-versions; do [ -e "$ETC/$name.env" ] || install -m 600 /dev/null "$ETC/$name.env" done -[ -e "$ETC/store-versions.env" ] || install -m 600 /dev/null "$ETC/store-versions.env" # What each file takes, commented; the env files stay empty until filled, since a job # is enabled once its env files have content. install -m 644 "$ROOT"/deploy/env/*.example "$ETC/" @@ -105,14 +104,16 @@ rm -f "$UNITS/zendesk-alert@.service" "$UNITS/github-prs-alert@.service" systemctl disable --now crowdin-relay.service 2>/dev/null || true rm -f "$UNITS/crowdin-relay.service" -install -m 644 "$ROOT"/deploy/*.service "$ROOT"/deploy/*.timer "$UNITS/" +install -m 644 "$ROOT"/deploy/*.service "$ROOT"/deploy/*.timer "$ROOT"/deploy/*.path "$UNITS/" # Only the generated files go, so a drop-in added by hand survives. rm -f "$UNITS"/session-ops@*.service.d/job.conf "$UNITS"/session-ops@*.timer.d/schedule.conf \ - "$UNITS"/session-ops-queue.timer.d/schedule.conf + "$UNITS"/session-ops@*.path.d/request.conf "$UNITS"/session-ops-queue.timer.d/schedule.conf "$OPS" units --out "$UNITS" >/dev/null READY=$("$OPS" list --ready) +TIMED=$("$OPS" list --timers) QUEUED=$("$OPS" list --queued) +PATHED=$("$OPS" list --path-units) listed() { printf '%s\n' $2 | grep -qxF "$1"; } # What the queue's timer starts: its ready jobs, rebuilt from scratch each install. WANTS="$UNITS/session-ops-queue.service.wants" @@ -125,22 +126,39 @@ for job in $QUEUED; do done systemctl daemon-reload -# A job removed from jobs.toml, whose env file was emptied, or now queued, loses its timer. +# A job removed from jobs.toml, whose env file was emptied, now queued or unscheduled, +# loses its timer. for link in "$UNITS"/timers.target.wants/session-ops@*.timer; do [ -L "$link" ] || continue job=${link##*/session-ops@} job=${job%.timer} - if ! listed "$job" "$READY" || listed "$job" "$QUEUED"; then + if ! listed "$job" "$TIMED"; then systemctl disable --now "session-ops@$job.timer" >/dev/null echo "disabled session-ops@$job.timer (no longer a ready job with a timer of its own)" fi done -for job in $READY; do - if listed "$job" "$QUEUED"; then +for job in $TIMED; do + systemctl enable --now "session-ops@$job.timer" >/dev/null + echo "enabled session-ops@$job.timer" +done +for job in $QUEUED; do + if listed "$job" "$READY"; then echo "queued session-ops@$job.service" - else - systemctl enable --now "session-ops@$job.timer" >/dev/null - echo "enabled session-ops@$job.timer" + fi +done +for link in "$UNITS"/paths.target.wants/session-ops@*.path; do + [ -L "$link" ] || continue + job=${link##*/session-ops@} + job=${job%.path} + if ! listed "$job" "$READY" || ! listed "$job" "$PATHED"; then + systemctl disable --now "session-ops@$job.path" >/dev/null + echo "disabled session-ops@$job.path (no longer a ready job Discord starts)" + fi +done +for job in $PATHED; do + if listed "$job" "$READY"; then + systemctl enable --now "session-ops@$job.path" >/dev/null + echo "enabled session-ops@$job.path" fi done if [ -d "$WANTS" ]; then @@ -152,16 +170,21 @@ fi for job in $("$OPS" list --not-ready); do echo "not enabled: session-ops@$job (its env file is empty)" done -if [ -s "$ETC/zendesk.env" ]; then - systemctl enable zendesk-relay.service >/dev/null - # A relay that hit its start limit refuses `start` until the limit is cleared. - systemctl reset-failed zendesk-relay.service 2>/dev/null || true - systemctl try-restart zendesk-relay.service - systemctl start zendesk-relay.service - echo "running zendesk-relay.service" -else - echo "not enabled: zendesk-relay.service ($ETC/zendesk.env is empty)" -fi +# An always-on service, enabled once its env file has content. +relay() { + if [ -s "$ETC/$2.env" ]; then + systemctl enable "$1.service" >/dev/null + # A relay that hit its start limit refuses `start` until the limit is cleared. + systemctl reset-failed "$1.service" 2>/dev/null || true + systemctl try-restart "$1.service" + systemctl start "$1.service" + echo "running $1.service" + else + echo "not enabled: $1.service ($ETC/$2.env is empty)" + fi +} +relay zendesk-relay zendesk +relay session-ops-discord discord if [ ! -s "$ETC/alerts.env" ]; then cat >&2 </` and are pruned -after 14 days. From a checkout, `uv run python -m session_ops.platforms.release_stats ---out .` writes them to a timestamped folder in the current directory, `.//`. - -| Desktop column | Assets counted | -| --- | --- | -| `.deb`, `.appimage`, `.rpm`, `.exe` | by extension | -| `.dmg_arm64`, `.dmg_x64`, `.zip_arm64`, `.zip_x64` | by extension and architecture | - -| Android column | Assets counted | -| --- | --- | -| `.aab` | `play-release` bundles | -| `.apk_arm64`, `.apk_armv7a`, `.apk_x86_64` | `play-release` APKs for `arm64-v8a`, `armeabi-v7a`, `x86_64` | -| `.apk_x86` | `play-release` x86 APKs, not x86_64 | -| `.apk_universal_play`, `.apk_universal_huawei` | universal APKs per store | diff --git a/docs/jobs/session-ops-discord.md b/docs/jobs/session-ops-discord.md new file mode 100644 index 0000000..6bb9cbd --- /dev/null +++ b/docs/jobs/session-ops-discord.md @@ -0,0 +1,34 @@ +# Discord Commands for the Jobs + +| | | +| --- | --- | +| Runs | `session-ops-discord.service`, always on, behind nginx at `POST /discord/interactions` | +| Secrets | `/etc/session-ops/discord.env`: the app's public key, the server and who may run the commands | +| Setup | [deploy/README.md](../../deploy/README.md#discord-commands) | +| Logs | `journalctl -u session-ops-discord -n 50 --no-pager`: who ran what, and each outcome | + +| Command | Does | +| --- | --- | +| `/run job:` | Starts `session-ops@.service` for a job `jobs.toml` marks `discord = true` by writing `/run/session-ops/requests/`, which the job's path unit watches, then waiting up to 1.5 seconds for the unit to start. If it has not, the reply says the job did not start. Refused while that job or any queued job is running or waiting to, or when the queue's next run is sooner than the job's timeout from now, or while another command is starting a job. The job posts its outcome in its own channel. | +| `/versions` | One line per platform from [store-versions](store-versions.md)' last run: the store's version, GitHub's, ⚠️ while a warning is out, and since when a source has not read. Visible to the channel, and noting when that run is over 15 minutes old. | + +The app has no gateway connection and only the `applications.commands` scope, so Discord +sends it the commands run against it and nothing else: no messages, members or other +channels. Each request carries who ran it, their roles, the server, the channel and the +options chosen. + +A request is refused unless Discord signed it in the last five minutes, it comes from +`DISCORD_GUILD_ID` and, when `ALLOWED_CHANNEL_IDS` is set, one of its channels, and its +author is in `ALLOWED_USER_IDS` or holds a role in `ALLOWED_ROLE_IDS`. Both lists empty +refuses everybody. `/run` is registered hidden from everyone but server administrators, +and the server's Integrations settings show it to the right role; that only hides it, and +these checks are what refuse everyone else, administrators included. `/versions` only reads, so it is shown to +everyone and skips the author check. + +The relay runs as `opsbot`, which can start no unit itself. It can write only to +`/run/session-ops/requests`, where `session-ops units` writes a `PathChanged=` watch for +each `discord = true` job and nothing else, so a file of any other name starts nothing. +It reads store-versions' `state.json`, which that job writes 0644. A +write to a request starts its job once, so nothing removes requests, and root never acts +on a file `opsbot` controls. The job runs as its own account with its own unit's +settings. The request carries nothing. diff --git a/docs/jobs/store-versions.md b/docs/jobs/store-versions.md index ddf1574..40e6f44 100644 --- a/docs/jobs/store-versions.md +++ b/docs/jobs/store-versions.md @@ -9,6 +9,7 @@ highest GitHub release, and posts as they diverge and come back. | Secrets | `/etc/session-ops/store-versions.env`: `STORE_VERSIONS_DISCORD_WEBHOOK_URL` | | Tags | `/etc/session-ops/store-versions.toml`, from [`store-versions.toml.example`](../../deploy/env/store-versions.toml.example); without it nobody is tagged | | Dry run | `session-ops run store-versions --dry-run` prints every version and what it would post. On the host, through `systemd-run` as in [deploy/README.md](../../deploy/README.md), so it gets the env file | +| On demand | [`/versions`](session-ops-discord.md) in Discord shows each platform's versions from the last run | | Logs | `journalctl -u session-ops@store-versions -n 50 --no-pager` | | Platform | GitHub | Store | Warns when the store is | diff --git a/src/session_ops/github_prs/digest.py b/src/session_ops/github_prs/digest.py index f2247b6..a75a7d5 100755 --- a/src/session_ops/github_prs/digest.py +++ b/src/session_ops/github_prs/digest.py @@ -236,7 +236,7 @@ def window_start(state, now, window_hours, retention_days=DEFAULT_RETENTION_DAYS the state says reporting is complete. A fixed window alone drops whatever moved in a gap longer than it: a DST weekend, - a timer's random delay, a host down across a run, a run whose post failed partway. + a host down across a run, a run whose post failed partway. Never further back than the retention, past which the state has forgotten what it reported anyway. """ diff --git a/src/session_ops/jobs.toml b/src/session_ops/jobs.toml index cd8d59d..091834d 100644 --- a/src/session_ops/jobs.toml +++ b/src/session_ops/jobs.toml @@ -12,6 +12,7 @@ # repeat_alert_hours report the same failure again only this often until a run # succeeds, for a schedule short enough to repeat it every few minutes # unit further [Service] lines, over the template's hardening +# discord startable by the Discord relay's account: offered to `/run` # # max_age_hours for a queued job, its queue's: the weekend's 72 h (73 h across # April's DST change), plus every job ahead of it running to its timeout @@ -67,6 +68,7 @@ channel_env = "CROWDIN_DISCORD_WEBHOOK_URL" max_age_hours = 80 # About 9 minutes; a full scan without --croql is ~110k requests, about 85 minutes. timeout = "2h" +discord = true [[job]] name = "session-ops-silence" @@ -120,6 +122,7 @@ env = ["CROWDIN_API_TOKEN", "PUBLISH_GIT_AUTHOR", "CROWDIN_DISCORD_WEBHOOK_URL"] channel_env = "CROWDIN_DISCORD_WEBHOOK_URL" max_age_hours = 80 timeout = "1h" +discord = true # Readable by this unit alone, at $CREDENTIALS_DIRECTORY; publishing needs it. unit = ["LoadCredential=github-app.pem:/etc/session-ops/github-app.pem"] @@ -134,12 +137,3 @@ channel_env = "CROWDIN_DISCORD_WEBHOOK_URL" max_age_hours = 80 timeout = "10min" unit = ["LoadCredential=github-app.pem:/etc/session-ops/github-app.pem"] - -[[job]] -name = "release-stats" -description = "Download counts of the latest Desktop and Android releases" -entry = "session_ops.platforms.release_stats:main" -args = ["--out", "{state}/runs"] -user = "sessionops" -env_files = ["/etc/session-ops/alerts.env"] -timeout = "5min" diff --git a/src/session_ops/ops/discord_commands.py b/src/session_ops/ops/discord_commands.py new file mode 100644 index 0000000..d431b04 --- /dev/null +++ b/src/session_ops/ops/discord_commands.py @@ -0,0 +1,59 @@ +"""The slash commands session-ops-discord.service answers, and their registration. + + session-ops discord-register # with discord.env's variables in the environment + +Registered on one guild rather than globally: a guild's commands update at once, and +nobody outside that server can see or run them. /run starts hidden from every member but +server administrators; the server's Integrations settings grant it to a role or channel. +That only hides it, and the relay's allowlist is what refuses everyone else, +administrators included. /versions only reads, so everyone sees it. +""" +import os +import sys + +from session_ops.ops import registry +from session_ops.shared import discord, http + +API = "https://discord.com/api/v10" +RUN = "run" +VERSIONS = "versions" +STORE_VERSIONS_JOB = "store-versions" + +OPTION_STRING = 3 +CHAT_INPUT = 1 +# Discord's cap on a choice's label. +MAX_CHOICE_NAME = 100 + + +def commands(jobs): + choices = [{"name": discord.clip(f"{job.name}: {job.description}", MAX_CHOICE_NAME), + "value": job.name} for job in jobs if job.discord] + hidden = {"type": CHAT_INPUT, "default_member_permissions": "0"} + found = [{**hidden, "name": RUN, "description": "Start a session-ops job now", + "options": [{"type": OPTION_STRING, "name": "job", "required": True, + "description": "The job to start", "choices": choices}]}] + if any(job.name == STORE_VERSIONS_JOB for job in jobs): + found.append({"type": CHAT_INPUT, "name": VERSIONS, + "description": "Each Session platform's store and GitHub versions"}) + return found + + +def register(session, app_id, guild_id, token, jobs): + """Replace every command on the guild with these. Returns the names registered.""" + response = session.request("PUT", f"{API}/applications/{app_id}/guilds/{guild_id}/commands", + headers={"Authorization": f"Bot {token}"}, json=commands(jobs)) + if response.status_code != 200: + raise SystemExit(f"Discord refused the commands: {response.status_code} " + f"{response.text[:300]}") + return [command["name"] for command in response.json()] + + +def main(): + missing = [name for name in ("DISCORD_APP_ID", "DISCORD_GUILD_ID", "DISCORD_BOT_TOKEN") + if not os.environ.get(name)] + if missing: + sys.exit(f"missing {', '.join(missing)} in the environment") + names = register(http.Session(attempts=3), os.environ["DISCORD_APP_ID"], + os.environ["DISCORD_GUILD_ID"], os.environ["DISCORD_BOT_TOKEN"], + registry.load()) + print("Registered /" + ", /".join(names)) diff --git a/src/session_ops/ops/discord_relay.py b/src/session_ops/ops/discord_relay.py new file mode 100644 index 0000000..20d2009 --- /dev/null +++ b/src/session_ops/ops/discord_relay.py @@ -0,0 +1,323 @@ +"""Discord slash commands for session-ops jobs: POST /discord/interactions. + + /run job: asks for session-ops@.service with a request file, which the + job's path unit picks up + /versions each platform's store and GitHub versions, from store-versions' + last run + +Discord signs every interaction with the app's Ed25519 key. One is refused unless it +comes from DISCORD_GUILD_ID, from a channel in ALLOWED_CHANNEL_IDS when that is set, and, +except for the read-only /versions, from someone in ALLOWED_USER_IDS or ALLOWED_ROLE_IDS. + +The account this runs as cannot start a unit itself. It can only write files in +/run/session-ops/requests, where a path unit watches for a write to each job jobs.toml +marks `discord`, so a file of any other name starts nothing. + +Config (env vars, /etc/session-ops/discord.env): + DISCORD_PUBLIC_KEY the app's public key. Unset refuses every request + DISCORD_GUILD_ID the one server it answers + ALLOWED_USER_IDS comma-separated Discord user ids + ALLOWED_ROLE_IDS comma-separated role ids + ALLOWED_CHANNEL_IDS (optional) comma-separated channel ids; unset allows any channel + +Usage: + uvicorn session_ops.ops.discord_relay:app --host 127.0.0.1 --port 8081 +""" +import json +import math +import os +import subprocess +import threading +import time + +from fastapi import FastAPI, Request, Response +from nacl.exceptions import BadSignatureError +from nacl.signing import VerifyKey +from starlette.concurrency import run_in_threadpool + +from session_ops.ops import registry +from session_ops.ops.discord_commands import RUN, STORE_VERSIONS_JOB, VERSIONS +from session_ops.store_versions import job as store_versions + +# Bounds replay of a request Discord genuinely signed; the signature covers the timestamp. +MAX_SIGNATURE_AGE_SECONDS = 300 +# Without it, a host whose clock trails Discord's refuses every interaction, the +# endpoint-registering PING included. +MAX_CLOCK_SKEW_SECONDS = 60 +SYSTEMCTL_TIMEOUT_SECONDS = 10 +RUNNING_STATES = frozenset({"active", "activating", "deactivating", "reloading"}) +USEC_INFINITY = 2**64 - 1 +# A path unit reacts within milliseconds; this leaves the rest of Discord's three seconds, +# even to a command that waited on the lock for another's. +START_WAIT_SECONDS = 1.5 +START_POLL_SECONDS = 0.1 +# store-versions runs every 5 minutes; older state means its timer has stopped. +VERSIONS_STALE_SECONDS = 15 * 60 + +INTERACTION_PING = 1 +INTERACTION_COMMAND = 2 +RESPONSE_PONG = 1 +RESPONSE_MESSAGE = 4 +EPHEMERAL = 64 +NO_PINGS = {"parse": []} + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +# Across the check and the start, so two /run a moment apart cannot both pass; one process only. +_starting = threading.Lock() + + +def env(name, default=None): + return os.environ.get(name, default) + + +def id_list(raw): + return [item.strip() for item in (raw or "").split(",") if item.strip()] + + +def signature_ok(raw, signature, timestamp, key): + if not (signature and timestamp and key): + return False + try: + age = time.time() - float(timestamp) + except (TypeError, ValueError): + return False + if age < -MAX_CLOCK_SKEW_SECONDS or age > MAX_SIGNATURE_AGE_SECONDS: + return False + try: + VerifyKey(bytes.fromhex(key)).verify(timestamp.encode() + raw, bytes.fromhex(signature)) + except (BadSignatureError, ValueError): + return False + return True + + +def user_id(interaction): + member = interaction.get("member") or {} + return (member.get("user") or interaction.get("user") or {}).get("id") + + +def place_refusal(interaction): + """Why the commands do not work where this was sent, or None. A DM carries no + guild_id, so it is refused with the wrong server.""" + guild = env("DISCORD_GUILD_ID") + if not guild or interaction.get("guild_id") != guild: + return "These commands do not work here." + channels = id_list(env("ALLOWED_CHANNEL_IDS")) + if channels and interaction.get("channel_id") not in channels: + return "These commands do not work in this channel." + return None + + +def refusal(interaction): + """Why this person may not use the commands here, or None. + + Both allowlists empty refuses everybody: an unconfigured relay must not mean an open one. + """ + place = place_refusal(interaction) + if place: + return place + users = id_list(env("ALLOWED_USER_IDS")) + roles = id_list(env("ALLOWED_ROLE_IDS")) + if not users and not roles: + return "Neither ALLOWED_USER_IDS nor ALLOWED_ROLE_IDS is set on the relay." + if user_id(interaction) in users: + return None + if any(role in roles for role in (interaction.get("member") or {}).get("roles") or []): + return None + return "You are not on the list of people who can run session-ops jobs." + + +def reply(text, ephemeral=True): + data = {"content": text, "allowed_mentions": NO_PINGS} + if ephemeral: + data["flags"] = EPHEMERAL + return {"type": RESPONSE_MESSAGE, "data": data} + + +def option(interaction, name): + for item in (interaction.get("data") or {}).get("options") or []: + if item.get("name") == name: + return item.get("value") + return None + + +def systemctl(*args): + return subprocess.run(["systemctl", "--no-ask-password", *args], check=False, + capture_output=True, text=True, timeout=SYSTEMCTL_TIMEOUT_SECONDS) + + +def unit_name(job_name): + return f"session-ops@{job_name}.service" + + +def busy(job): + """The first of `job` and the queue's jobs that is running or waiting to, else None. + + The queue runs its jobs one at a time so no two share the host or their APIs; a run + started from here keeps to that. + """ + units = [unit_name(name) for name in dict.fromkeys([job.name, *registry.load_queue().jobs])] + waiting = {line.split()[1] for line in + systemctl("list-jobs", "--no-legend", "--plain").stdout.splitlines() + if len(line.split()) > 1} + states = systemctl("is-active", *units).stdout.split() + if len(states) != len(units): + raise RuntimeError(f"systemctl is-active gave {len(states)} states for {len(units)} units") + for unit, state in zip(units, states): + if unit in waiting or state in RUNNING_STATES: + return unit + return None + + +def next_queue_run(): + """The queue timer's next run as a Unix time, or None while it has none. + + From list-timers' JSON, in microseconds: systemd 252 prints this property as local + time under `show`, --timestamp=unix or not. + """ + timers = json.loads(systemctl("list-timers", "--all", "--output=json", + registry.QUEUE_TIMER).stdout or "[]") + next_us = timers[0].get("next") if timers else None + return next_us / 1e6 if next_us and next_us != USEC_INFINITY else None + + +def hold_off(job): + """Why `job` cannot start now, or None.""" + blocking = busy(job) + if blocking: + return f"⏳ `{blocking}` is running or waiting to; try again once it has finished." + queue_at = next_queue_run() + # A run is killed at its timeout, so the queue starting later cannot overlap it. + if queue_at is None or queue_at >= time.time() + job.timeout_seconds: + return None + at = f" ()" + if job.queued: + return (f"⏳ The queue runs **{job.name}** at {at}, sooner than a run started now " + f"would be sure to end.") + return (f"⏳ The queue starts at {at}, sooner than **{job.name}** would be sure to end; " + f"try again once it has run.") + + +def started_at(unit): + """When `unit` last left the inactive state, in microseconds since boot; 0 if never.""" + return int(systemctl("show", "-P", "InactiveExitTimestampMonotonic", unit).stdout.strip() or 0) + + +def request_start(job): + """Write the job's request, then wait for its path unit to start it. True once it has.""" + unit = unit_name(job.name) + before = started_at(unit) + with open(job.request_path, "w"): + pass + deadline = time.monotonic() + START_WAIT_SECONDS + while time.monotonic() < deadline: + if started_at(unit) != before: + return True + time.sleep(START_POLL_SECONDS) + return False + + +def start(job, interaction): + """None once `job` has started, else the reply saying why not.""" + command = (interaction.get("data") or {}).get("name") + # Waiting out another start's poll would miss Discord's 3 s. + if not _starting.acquire(blocking=False): + return reply("⏳ Another job is being started; try again in a moment.") + try: + held = hold_off(job) + if held: + return reply(held) + started = request_start(job) + except (OSError, subprocess.SubprocessError, RuntimeError, ValueError) as exc: + print(f"/{command} {job.name}: {exc!r}", flush=True) + return reply("❌ Could not ask for the job on the host; see " + "`journalctl -u session-ops-discord`.") + finally: + _starting.release() + if not started: + print(f"/{command} {job.name} by {user_id(interaction)}: nothing picked the request up", + flush=True) + return reply(f"❌ **{job.name}** did not start: nothing picked up its request. See " + f"`systemctl status session-ops@{job.name}.path session-ops@{job.name}`.") + print(f"/{command} {job.name} by {user_id(interaction)}: started", flush=True) + return None + + +def handle_run(interaction): + name = option(interaction, "job") + job = next((job for job in registry.load() if job.discord and job.name == name), None) + if job is None: + return reply(f"❌ `{name}` is not a job /run can start.") + return start(job, interaction) or reply( + f"▶️ <@{user_id(interaction)}> started **{job.name}**. It posts in its own channel " + "when it is done.", ephemeral=False) + + +def versions_message(path=None, now=None): + """divemo's /versions: a line per platform from store-versions' state.""" + path = path or os.path.join(registry.get(STORE_VERSIONS_JOB).state_dir, "state.json") + try: + with open(path, encoding="utf-8") as handle: + state = json.load(handle) + written = os.stat(path).st_mtime + except (OSError, ValueError) as exc: + print(f"/versions: {exc!r}", flush=True) + return "❌ No versions to show: store-versions' state cannot be read on the host." + seen = state.get("platforms") if isinstance(state, dict) else None + if not isinstance(seen, dict) or state.get("version") != store_versions.STATE_VERSION: + return "❌ No versions to show: store-versions' state is in a format this cannot read." + failing = state.get("sources") + failing = failing if isinstance(failing, dict) else {} + lines = [] + for platform in store_versions.PLATFORMS: + last = seen.get(platform.name) + if not isinstance(last, dict) or not last: + lines.append(f"**{platform.display}**: no data yet") + continue + # The watermark, since that is what the warnings compare. + store = last.get("store_high") or last.get("store") + line = (f"**{platform.display}**: {store_versions.store_name(platform)} " + f"`{store}` / GitHub `{last.get('github')}`" + + (" ⚠️" if last.get("warning") else "")) + # A failing source leaves the platform's last good versions in place. + since = [f.get("since") for key in store_versions.source_keys(platform) + if isinstance(f := failing.get(key), dict) + and isinstance(f.get("since"), (int, float)) and math.isfinite(f["since"])] + if since: + line += f" (not read since )" + lines.append(line) + if (now or time.time()) - written > VERSIONS_STALE_SECONDS: + lines.append(f"-# As of : store-versions may not be running.") + return "\n".join(lines) + + +@app.get("/healthz") +def healthz(): + return {"ok": True} + + +@app.post("/discord/interactions") +async def interactions(request: Request): + raw = await request.body() + if not signature_ok(raw, request.headers.get("x-signature-ed25519"), + request.headers.get("x-signature-timestamp"), env("DISCORD_PUBLIC_KEY")): + return Response("bad signature", status_code=401) + try: + interaction = json.loads(raw) + except ValueError: + interaction = None + if not isinstance(interaction, dict): + return Response("not an interaction", status_code=400) + kind = interaction.get("type") + if kind == INTERACTION_PING: + return {"type": RESPONSE_PONG} + if kind != INTERACTION_COMMAND: + return Response("unsupported interaction", status_code=400) + command = (interaction.get("data") or {}).get("name") + denied = place_refusal(interaction) if command == VERSIONS else refusal(interaction) + if denied: + return reply(f"❌ {denied}") + if command == VERSIONS: + return reply(await run_in_threadpool(versions_message), ephemeral=False) + if command == RUN: + return await run_in_threadpool(handle_run, interaction) + return reply(f"❌ This relay has no /{command}.") diff --git a/src/session_ops/ops/registry.py b/src/session_ops/ops/registry.py index 8348aa6..ea136ce 100644 --- a/src/session_ops/ops/registry.py +++ b/src/session_ops/ops/registry.py @@ -4,6 +4,7 @@ silence checker, so a job is added in one place. """ import os +import re import tomllib from dataclasses import dataclass, field, replace @@ -11,6 +12,32 @@ "jobs.toml") STATE_ROOT = "/var/lib/session-ops" QUEUE_TIMER = "session-ops-queue.timer" +# Where the Discord relay asks for a `discord` job: its path unit starts the job. +REQUESTS_DIR = "/run/session-ops/requests" +# Discord's cap on a string option's choices, which `/run` offers these jobs as. +MAX_DISCORD_JOBS = 25 +SPAN_UNITS = { + **dict.fromkeys(("us", "usec"), 1e-6), **dict.fromkeys(("ms", "msec"), 1e-3), + **dict.fromkeys(("", "s", "sec", "second", "seconds"), 1), + **dict.fromkeys(("m", "min", "minute", "minutes"), 60), + **dict.fromkeys(("h", "hr", "hour", "hours"), 3600), + **dict.fromkeys(("d", "day", "days"), 86400), + **dict.fromkeys(("w", "week", "weeks"), 604800), +} +SPAN_PART = re.compile(r"\s*(\d+(?:\.\d+)?)\s*([a-z]*)") + + +def span_seconds(text): + """Seconds in a systemd time span such as "1h 30min"; a bare number is seconds.""" + parts = list(SPAN_PART.finditer(text)) + if not parts or "".join(part.group(0) for part in parts).strip() != text.strip(): + raise ValueError(f"{text!r} is not a time span") + total = 0 + for part in parts: + if part.group(2) not in SPAN_UNITS: + raise ValueError(f"{text!r} has an unknown unit {part.group(2)!r}") + total += float(part.group(1)) * SPAN_UNITS[part.group(2)] + return total @dataclass(frozen=True) @@ -31,6 +58,7 @@ class Job: unit: tuple = field(default=()) queued: bool = False after: tuple = () + discord: bool = False @property def scheduled(self): @@ -40,10 +68,18 @@ def scheduled(self): def timer(self): return QUEUE_TIMER if self.queued else f"session-ops@{self.name}.timer" + @property + def timeout_seconds(self): + return span_seconds(self.timeout) + @property def state_dir(self): return os.path.join(STATE_ROOT, self.name) + @property + def request_path(self): + return os.path.join(REQUESTS_DIR, self.name) if self.discord else None + def argv(self, dry_run=False, state_dir=None): """The job's arguments, with {state} standing for its state directory.""" state = state_dir or self.state_dir @@ -87,6 +123,14 @@ def load(path=REGISTRY): for job in jobs: if job.scheduled and not isinstance(job.max_age_hours, (int, float)): raise ValueError(f"{path}: scheduled job {job.name} needs a numeric max_age_hours") + if not isinstance(job.discord, bool): + raise ValueError(f"{path}: {job.name}'s discord must be true or false") + try: + job.timeout_seconds + except (TypeError, ValueError) as exc: + raise ValueError(f"{path}: {job.name}'s timeout: {exc}") from None + if sum(job.discord for job in jobs) > MAX_DISCORD_JOBS: + raise ValueError(f"{path}: Discord offers at most {MAX_DISCORD_JOBS} jobs to /run") return jobs diff --git a/src/session_ops/ops/runner.py b/src/session_ops/ops/runner.py index b727c0a..58b161e 100644 --- a/src/session_ops/ops/runner.py +++ b/src/session_ops/ops/runner.py @@ -3,6 +3,7 @@ session-ops list session-ops run github-prs-digest [--dry-run] [-- further job arguments] session-ops units --out /etc/systemd/system + session-ops discord-register A run owns what every job would otherwise repeat: checking the environment it needs, a scratch directory, and telling Discord when it fails. The alert names the job, the @@ -210,11 +211,9 @@ def _invoke(function, argv): return None, one_sentence(describe(exc)) -def call(job, argv): - """Run the job's entry point. Returns (outcome, error).""" +def entry_point(job): module_name, function = job.entry.split(":") - result, error = _invoke(getattr(importlib.import_module(module_name), function), argv) - return (result if isinstance(result, Outcome) else Outcome()), error + return getattr(importlib.import_module(module_name), function) def run(job, dry_run=False, extra=()): @@ -237,7 +236,15 @@ def run(job, dry_run=False, extra=()): _step = "checking for a rehearsal" outcome, error = Outcome(), rehearsal else: - outcome, error = call(job, job.argv(dry_run, state_dir) + list(extra)) + try: + function = entry_point(job) + except Exception as exc: # a broken install, reported like any failure + traceback.print_exc() + _step = "loading the job" + outcome, error = Outcome(), one_sentence(describe(exc)) + else: + result, error = _invoke(function, job.argv(dry_run, state_dir) + list(extra)) + outcome = result if isinstance(result, Outcome) else Outcome() finally: shutil.rmtree(work, ignore_errors=True) if outcome.summary: @@ -277,17 +284,24 @@ def main(argv=None): list_parser = sub.add_parser("list", help="Every registered job, its schedule and account.") readiness = list_parser.add_mutually_exclusive_group() readiness.add_argument("--ready", action="store_true", - help="Only the names of scheduled jobs whose env files have content.") + help="Only the names of the jobs a timer, the queue or a path unit " + "starts, whose env files have content.") readiness.add_argument("--not-ready", action="store_true", - help="Only the names of scheduled jobs with an empty env file.") + help="Only the names of those jobs with an empty env file.") + readiness.add_argument("--timers", action="store_true", + help="Only the names of the ready jobs with a timer of their own.") readiness.add_argument("--queued", action="store_true", help="Only the names of the queued jobs, in the order they run.") + readiness.add_argument("--path-units", action="store_true", + help="Only the names of the jobs a request from Discord starts.") run_parser = sub.add_parser("run", help="Run a job as its timer does.") run_parser.add_argument("job") run_parser.add_argument("--dry-run", action="store_true", help="The job's own dry run; an alert is printed, not posted.") units_parser = sub.add_parser("units", help="Write each job's systemd drop-ins.") units_parser.add_argument("--out", required=True, metavar="DIR") + sub.add_parser("discord-register", help="Register the Discord slash commands, from " + "discord.env's variables.") argv = sys.argv[1:] if argv is None else list(argv) extra = argv[argv.index("--") + 1:] if "--" in argv else [] args = parser.parse_args(argv[:argv.index("--")] if "--" in argv else argv) @@ -297,9 +311,16 @@ def main(argv=None): if args.queued: print("\n".join(queue.jobs)) return + if args.path_units: + print("\n".join(job.name for job in registry.load() if job.discord)) + return for job in registry.load(): - if args.ready or args.not_ready: - if job.scheduled and ready(job) == args.ready: + started = job.scheduled or job.discord + if args.timers: + if job.schedule and not job.queued and ready(job): + print(job.name) + elif args.ready or args.not_ready: + if started and ready(job) == args.ready: print(job.name) else: when = f"queue: {queue.schedule}" if job.queued else job.schedule or "on demand" @@ -310,6 +331,10 @@ def main(argv=None): for path in units.write(registry.load(), registry.load_queue(), args.out): print(path) return + if args.command == "discord-register": + from session_ops.ops import discord_commands + discord_commands.main() + return try: job = registry.get(args.job) except KeyError: diff --git a/src/session_ops/ops/units.py b/src/session_ops/ops/units.py index 0d1ec64..41d32b8 100644 --- a/src/session_ops/ops/units.py +++ b/src/session_ops/ops/units.py @@ -7,6 +7,8 @@ import os HEADER = "# Generated by `session-ops units` from jobs.toml. Edit the registry, not this.\n" +# The account session-ops-discord.service runs as, and install.sh creates. +RELAY_USER = "opsbot" def service_dropin(job): @@ -25,6 +27,10 @@ def timer_dropin(schedule): return "\n".join([HEADER, "[Timer]", f"OnCalendar={schedule}"]) + "\n" +def path_dropin(job): + return "\n".join([HEADER, "[Path]", f"PathChanged={job.request_path}"]) + "\n" + + def dropins(jobs, queue): """{relative path: content} for every job, and the queue's schedule. @@ -38,6 +44,8 @@ def dropins(jobs, queue): files[f"session-ops@{job.name}.service.d/job.conf"] = service_dropin(job) if job.schedule: files[f"session-ops@{job.name}.timer.d/schedule.conf"] = timer_dropin(job.schedule) + if job.discord: + files[f"session-ops@{job.name}.path.d/request.conf"] = path_dropin(job) return files diff --git a/src/session_ops/platforms/release_stats.py b/src/session_ops/platforms/release_stats.py deleted file mode 100644 index 844de28..0000000 --- a/src/session_ops/platforms/release_stats.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Download counts of the last ten Desktop and Android releases, per installer, as two -CSV files. On demand only: nothing schedules it. - - session-ops run release-stats # CSVs kept under the job's runs/ - uv run python -m session_ops.platforms.release_stats --out . -""" -import argparse -import os -import time -from datetime import datetime, timezone - -from session_ops.ops.runner import step -from session_ops.shared import http - -API = "https://api.github.com/repos/session-foundation/{repo}/releases" -RELEASES = 10 - -DESKTOP_HEADER = ("version,snapshot_date,release_date,.deb,.appimage,.rpm,.dmg_arm64," - ".dmg_x64,.zip_arm64,.zip_x64,.exe") -ANDROID_HEADER = ("version,snapshot_date,release_date,.aab,.apk_arm64,.apk_armv7a," - ".apk_universal_huawei,.apk_universal_play,.apk_x86,.apk_x86_64") - - -def downloads(assets, keep): - return sum(a["download_count"] for a in assets if keep(a["name"])) - - -def desktop_row(release): - assets = release["assets"] - return [ - downloads(assets, lambda n: n.endswith(".deb")), - downloads(assets, lambda n: n.endswith(".AppImage")), - downloads(assets, lambda n: n.endswith(".rpm")), - downloads(assets, lambda n: n.endswith(".dmg") and "arm64" in n), - downloads(assets, lambda n: n.endswith(".dmg") and "x64" in n), - downloads(assets, lambda n: n.endswith(".zip") and "arm64" in n), - downloads(assets, lambda n: n.endswith(".zip") and "x64" in n), - downloads(assets, lambda n: n.endswith(".exe")), - ] - - -def android_row(release): - assets = release["assets"] - - def apk(arch): - return downloads(assets, lambda n: n.endswith(".apk") and arch in n - and "play-release" in n) - - return [ - downloads(assets, lambda n: n.endswith(".aab") and "play-release" in n), - apk("arm64-v8a"), - apk("armeabi-v7a"), - downloads(assets, lambda n: n.endswith(".apk") and "universal" in n - and "huawei-release" in n), - downloads(assets, lambda n: n.endswith(".apk") and "universal" in n - and "play-release" in n), - # x86 without x86_64, which contains it. - downloads(assets, lambda n: n.endswith(".apk") and "x86" in n - and "x86_64" not in n and "play-release" in n), - apk("x86_64"), - ] - - -def csv(releases, header, row, snapshot): - lines = [header] - for release in releases[:RELEASES]: - version = release["tag_name"][1:] if release["tag_name"].startswith("v") \ - else release["tag_name"] - lines.append(",".join(str(v) for v in [version, snapshot, - release["published_at"].split("T")[0], - *row(release)])) - return "\n".join(lines) - - -def fetch(session, repo): - resp = session.request("GET", API.format(repo=repo)) - if resp.status_code != 200: - raise RuntimeError(f"HTTP {resp.status_code}: {resp.text[:200]}") - return resp.json() - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__.strip().split("\n")[0]) - parser.add_argument("--out", default=".", metavar="DIR", - help="Where the CSVs go; a directory per run is made under it.") - parser.add_argument("--dry-run", action="store_true", help="Print the CSVs only.") - args = parser.parse_args(argv) - - session = http.Session() - session.headers.update({"Accept": "application/vnd.github.v3+json"}) - snapshot = datetime.now(timezone.utc).date().isoformat() - out = os.path.join(args.out, time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())) - for repo, header, row in (("session-desktop", DESKTOP_HEADER, desktop_row), - ("session-android", ANDROID_HEADER, android_row)): - step(repo) - content = csv(fetch(session, repo), header, row, snapshot) - print(f"# {repo}\n{content}\n") - if not args.dry_run: - os.makedirs(out, exist_ok=True) - with open(os.path.join(out, f"{repo}-release-stats.csv"), "w", - encoding="utf-8") as handle: - handle.write(content) - if not args.dry_run: - print(f"Written to {out}") - - -if __name__ == "__main__": - main() diff --git a/src/session_ops/shared/state.py b/src/session_ops/shared/state.py index 54c08f7..0100db7 100644 --- a/src/session_ops/shared/state.py +++ b/src/session_ops/shared/state.py @@ -73,7 +73,7 @@ def save_state(path, state, records, retention_days, version, extra=None): return len(kept), len(seen) - len(kept) -def write_json(path, data): +def write_json(path, data, mode=None): """Write `data` to `path` atomically: a crash mid-write cannot corrupt the state.""" directory = os.path.dirname(path) if directory: @@ -81,4 +81,6 @@ def write_json(path, data): temporary = f"{path}.tmp" with open(temporary, "w", encoding="utf-8") as handle: json.dump(data, handle, indent=2) + if mode is not None: + os.fchmod(handle.fileno(), mode) os.replace(temporary, path) diff --git a/src/session_ops/store_versions/job.py b/src/session_ops/store_versions/job.py index d4fc77a..c2dfcc4 100644 --- a/src/session_ops/store_versions/job.py +++ b/src/session_ops/store_versions/job.py @@ -44,6 +44,8 @@ TAGS_FILE = "/etc/session-ops/store-versions.toml" STATE_VERSION = 1 +# The job's UMask makes it 0600; the Discord relay's /versions reads it as another account. +STATE_MODE = 0o644 HOUR = 3600 REMINDER_SECONDS = 12 * HOUR FAILING_AFTER_SECONDS = HOUR @@ -339,9 +341,9 @@ def main(argv=None): apply() # Saved per step: a run killed mid-way reposts at most the step it was on. if args.state and step_messages: - write_json(args.state, state) + write_json(args.state, state, STATE_MODE) if args.state: - write_json(args.state, state) + write_json(args.state, state, STATE_MODE) if refused: # Without counts: the runner repeats an alert only when its text changes. sys.exit("Discord refused a post; it is retried next run.") diff --git a/tests/goldens/units/dropins.txt b/tests/goldens/units/dropins.txt index f6a4fee..4fe1894 100644 --- a/tests/goldens/units/dropins.txt +++ b/tests/goldens/units/dropins.txt @@ -4,6 +4,12 @@ [Timer] OnCalendar=Mon..Fri 10:00 Australia/Melbourne +==> session-ops@crowdin-duplicates.path.d/request.conf <== +# Generated by `session-ops units` from jobs.toml. Edit the registry, not this. + +[Path] +PathChanged=/run/session-ops/requests/crowdin-duplicates + ==> session-ops@crowdin-duplicates.service.d/job.conf <== # Generated by `session-ops units` from jobs.toml. Edit the registry, not this. @@ -17,6 +23,12 @@ Group=crowdin EnvironmentFile=/etc/session-ops/crowdin.env TimeoutStartSec=2h +==> session-ops@crowdin-sync.path.d/request.conf <== +# Generated by `session-ops units` from jobs.toml. Edit the registry, not this. + +[Path] +PathChanged=/run/session-ops/requests/crowdin-sync + ==> session-ops@crowdin-sync.service.d/job.conf <== # Generated by `session-ops units` from jobs.toml. Edit the registry, not this. @@ -44,18 +56,6 @@ Group=ghdigest EnvironmentFile=/etc/session-ops/github-prs.env TimeoutStartSec=15min -==> session-ops@release-stats.service.d/job.conf <== -# Generated by `session-ops units` from jobs.toml. Edit the registry, not this. - -[Unit] -Description=Download counts of the latest Desktop and Android releases - -[Service] -User=sessionops -Group=sessionops -EnvironmentFile=/etc/session-ops/alerts.env -TimeoutStartSec=5min - ==> session-ops@session-ops-silence.service.d/job.conf <== # Generated by `session-ops units` from jobs.toml. Edit the registry, not this. diff --git a/tests/ops/test_deploy.py b/tests/ops/test_deploy.py index ffe4a0f..02dcf2f 100644 --- a/tests/ops/test_deploy.py +++ b/tests/ops/test_deploy.py @@ -62,6 +62,15 @@ def test_a_scheduled_job_gets_a_timer_and_an_unscheduled_one_does_not(self): self.assertEqual(f"session-ops@{job.name}.timer.d/schedule.conf" in files, bool(job.schedule)) + def test_a_discord_job_starts_on_a_write_to_its_request_and_never_removes_it(self): + files = units.dropins(registry.load(), registry.load_queue()) + for job in registry.load(): + with self.subTest(job=job.name): + watch = files.get(f"session-ops@{job.name}.path.d/request.conf", "") + request = os.path.join(registry.REQUESTS_DIR, job.name) + self.assertEqual(f"\nPathChanged={request}\n" in watch, job.discord) + self.assertNotIn(request, files[f"session-ops@{job.name}.service.d/job.conf"]) + def test_each_queued_job_runs_after_every_one_before_it(self): queue = registry.load_queue() files = units.dropins(registry.load(), queue) @@ -74,11 +83,30 @@ def test_each_queued_job_runs_after_every_one_before_it(self): files[f"session-ops@{job}.service.d/job.conf"]) self.assertNotIn("After=", files[f"session-ops@{queue.jobs[0]}.service.d/job.conf"]) + def test_install_enables_timers_only_for_jobs_with_a_schedule_of_their_own(self): + with open(os.path.join(ROOT, "deploy", "install.sh"), encoding="utf-8") as handle: + script = handle.read() + self.assertEqual(re.findall(r'systemctl enable --now "session-ops@\$job\.timer"', script), + ['systemctl enable --now "session-ops@$job.timer"']) + self.assertIn('for job in $TIMED; do\n systemctl enable --now "session-ops@$job.timer"', + script) + def test_the_generated_dropins(self): files = units.dropins(registry.load(), registry.load_queue()) text = "".join(f"==> {path} <==\n{files[path]}\n" for path in sorted(files)) assert_golden(self, "units/dropins.txt", text) + def test_only_the_discord_relay_s_account_can_write_requests(self): + self.assertIn(f"\nUser={units.RELAY_USER}\n", unit_text("session-ops-discord.service")) + with open(os.path.join(ROOT, "deploy", "session-ops.tmpfiles"), encoding="utf-8") as handle: + self.assertIn(f"\nd {registry.REQUESTS_DIR} 0770 root {units.RELAY_USER} -\n", + handle.read()) + + def test_the_discord_relay_can_write_requests_and_nothing_else(self): + writable = re.findall(r"^ReadWritePaths=-?(.*)$", + unit_text("session-ops-discord.service"), re.MULTILINE) + self.assertEqual(writable, [registry.REQUESTS_DIR]) + class TestInstallScript(unittest.TestCase): @unittest.skipIf(ROOT == "/opt/session-ops", "this checkout is the one it installs from") diff --git a/tests/ops/test_discord_relay.py b/tests/ops/test_discord_relay.py new file mode 100644 index 0000000..f647d2f --- /dev/null +++ b/tests/ops/test_discord_relay.py @@ -0,0 +1,359 @@ +""" + uv run python -m unittest tests.ops.test_discord_relay + +Offline: systemctl, the path units and Discord's API are fakes, and +requests go through FastAPI's TestClient. The relay can start jobs on the host, so most +of this is about who it refuses. +""" +import json +import os +import shutil +import subprocess +import tempfile +import time +import unittest +from unittest import mock + +from fastapi.testclient import TestClient +from nacl.signing import SigningKey + +from session_ops.ops import discord_commands, discord_relay as relay, registry +from session_ops.store_versions import job as store_versions +from session_ops.shared.testing import FakeResponse, FakeSession, Patched + +KEY = SigningKey.generate() +GUILD = "111" +ALLOWED_USER = "222" +ALLOWED_ROLE = "333" +CHANNEL = "444" +ENV = {"DISCORD_PUBLIC_KEY": KEY.verify_key.encode().hex(), "DISCORD_GUILD_ID": GUILD, + "ALLOWED_USER_IDS": ALLOWED_USER, "ALLOWED_ROLE_IDS": ALLOWED_ROLE} + + + +class FakePathUnits: + """Each discord job's path unit: a new write to its request starts its unit.""" + + def __init__(self): + self.started, self.picks_up, self.seen = [], True, {} + + def started_at(self, unit): + name = unit.removeprefix("session-ops@").removesuffix(".service") + path = os.path.join(registry.REQUESTS_DIR, name) + if self.picks_up and os.path.exists(path): + written = os.stat(path).st_mtime_ns + if self.seen.get(path) != written: + self.seen[path] = written + self.started.append(unit) + return self.started.count(unit) * 1_000_000 + + +class FakeSystemd: + def __init__(self, running=(), waiting=(), queue_at=None, path_units=None): + self.running, self.waiting, self.queue_at = set(running), set(waiting), queue_at + self.path_units = path_units + self.locked = [] + + def __call__(self, *args): + self.locked.append(relay._starting.locked()) + out = "" + if args[0] == "list-jobs": + out = "".join(f"7 {unit} start waiting\n" for unit in self.waiting) + elif args[0] == "is-active": + out = "".join(("active" if u in self.running else "inactive") + "\n" + for u in args[1:]) + elif args[0] == "show": + out = f"{self.path_units.started_at(args[-1]) if self.path_units else 0}\n" + elif args[0] == "list-timers": + out = json.dumps([] if self.queue_at is None else [ + {"next": int(self.queue_at * 1e6), "unit": args[-1]}]) + return subprocess.CompletedProcess(["systemctl", *args], 0, out, "") + + +def command(name, options=(), *, user=ALLOWED_USER, roles=(), guild=GUILD, channel=CHANNEL): + data = {"name": name, "options": [{"name": k, "value": v} for k, v in options]} + return {"type": relay.INTERACTION_COMMAND, "id": "999", "application_id": "app", + "token": "tok", "guild_id": guild, "channel_id": channel, "data": data, + "member": {"user": {"id": user}, "roles": list(roles)}} + + + +def post(body, *, key=KEY, age=0, tamper=False): + raw = json.dumps(body).encode() + timestamp = str(int(time.time() - age)) + signature = key.sign(timestamp.encode() + raw).signature.hex() + if tamper: + raw = raw.replace(b"}", b" }", 1) + return TestClient(relay.app).post("/discord/interactions", content=raw, headers={ + "x-signature-ed25519": signature, "x-signature-timestamp": timestamp}) + + +class RelayCase(unittest.TestCase): + def setUp(self): + patcher = mock.patch.dict(os.environ, ENV) + patcher.start() + self.addCleanup(patcher.stop) + self.path_units = FakePathUnits() + self.systemd = FakeSystemd(path_units=self.path_units) + self.requests = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.requests, True) + self.patch(registry, REQUESTS_DIR=self.requests) + self.patch(relay, systemctl=self.systemd, START_WAIT_SECONDS=0.2, + START_POLL_SECONDS=0.01) + + @property + def started(self): + return self.path_units.started + + def patch(self, module, **attrs): + patched = Patched(module, **attrs) + patched.__enter__() + self.addCleanup(patched.__exit__) + + def content(self, response): + self.assertEqual(response.status_code, 200) + return response.json()["data"]["content"] + + +class TestGate(RelayCase): + def test_a_ping_is_answered(self): + self.assertEqual(post({"type": relay.INTERACTION_PING}).json(), {"type": relay.RESPONSE_PONG}) + + def test_an_unsigned_tampered_stale_or_foreign_request_is_refused(self): + for case in ({"tamper": True}, {"age": relay.MAX_SIGNATURE_AGE_SECONDS + 5}, + {"age": -relay.MAX_CLOCK_SKEW_SECONDS - 5}, {"key": SigningKey.generate()}): + with self.subTest(**{k: str(v) for k, v in case.items()}): + self.assertEqual(post({"type": relay.INTERACTION_PING}, **case).status_code, 401) + + def test_no_public_key_refuses_everything(self): + with mock.patch.dict(os.environ, {"DISCORD_PUBLIC_KEY": ""}): + self.assertEqual(post({"type": relay.INTERACTION_PING}).status_code, 401) + + def test_another_server_or_a_dm_is_refused(self): + for guild in ("444", None): + with self.subTest(guild=guild): + text = self.content(post(command("run", [("job", "crowdin-sync")], guild=guild))) + self.assertIn("do not work here", text) + self.assertEqual(self.started, []) + + def test_someone_on_neither_list_is_refused(self): + text = self.content(post(command("run", [("job", "crowdin-sync")], user="5", roles=["6"]))) + self.assertIn("not on the list", text) + self.assertEqual(self.started, []) + + def test_empty_allowlists_refuse_everybody(self): + with mock.patch.dict(os.environ, {"ALLOWED_USER_IDS": "", "ALLOWED_ROLE_IDS": ""}): + text = self.content(post(command("run", [("job", "crowdin-sync")]))) + self.assertIn("Neither", text) + + def test_a_role_on_the_list_is_enough(self): + post(command("run", [("job", "crowdin-sync")], user="5", roles=[ALLOWED_ROLE])) + self.assertEqual(self.started, ["session-ops@crowdin-sync.service"]) + + def test_with_a_channel_list_another_channel_is_refused(self): + with mock.patch.dict(os.environ, {"ALLOWED_CHANNEL_IDS": f"9, {CHANNEL}"}): + text = self.content(post(command("run", [("job", "crowdin-sync")], channel="5"))) + self.assertIn("do not work in this channel", text) + self.assertEqual(self.started, []) + post(command("run", [("job", "crowdin-sync")])) + self.assertEqual(self.started, ["session-ops@crowdin-sync.service"]) + + def test_without_a_channel_list_any_channel_of_the_server_works(self): + post(command("run", [("job", "crowdin-sync")], channel="5")) + self.assertEqual(self.started, ["session-ops@crowdin-sync.service"]) + + +class TestRun(RelayCase): + def test_a_discord_job_is_started_and_the_channel_told_who_started_it(self): + response = post(command("run", [("job", "crowdin-duplicates")])) + self.assertEqual(self.started, ["session-ops@crowdin-duplicates.service"]) + data = response.json()["data"] + self.assertIn(f"<@{ALLOWED_USER}> started **crowdin-duplicates**", data["content"]) + self.assertNotIn("flags", data) + self.assertEqual(data["allowed_mentions"], {"parse": []}) + + def test_a_job_not_marked_discord_is_refused(self): + for name in ("token-expiry", "nope"): + with self.subTest(job=name): + self.assertIn("not a job /run can start", + self.content(post(command("run", [("job", name)])))) + self.assertEqual(self.started, []) + + def test_a_running_or_waiting_queue_job_holds_it_off(self): + queued = registry.load_queue().jobs + for systemd in (FakeSystemd(running=[f"session-ops@{queued[0]}.service"]), + FakeSystemd(waiting=[f"session-ops@{queued[-1]}.service"]), + FakeSystemd(running=["session-ops@crowdin-sync.service"])): + with self.subTest(running=systemd.running, waiting=systemd.waiting), \ + Patched(relay, systemctl=systemd): + self.assertIn("running or waiting", self.content( + post(command("run", [("job", "crowdin-sync")])))) + self.assertEqual(self.started, []) + + def test_the_check_and_the_request_happen_under_one_lock(self): + post(command("run", [("job", "crowdin-sync")])) + self.assertTrue(self.systemd.locked) + self.assertTrue(all(self.systemd.locked)) + self.assertFalse(relay._starting.locked()) + + def test_a_start_already_under_way_is_refused_without_waiting(self): + with relay._starting: + self.assertIn("Another job is being started", + self.content(post(command("run", [("job", "crowdin-sync")])))) + self.assertEqual(self.started, []) + self.assertFalse(relay._starting.locked()) + + def test_each_run_writes_the_request_again_and_nothing_removes_it(self): + for _ in range(2): + self.assertIn("started **crowdin-sync**", + self.content(post(command("run", [("job", "crowdin-sync")])))) + time.sleep(0.01) + self.assertEqual(self.started, ["session-ops@crowdin-sync.service"] * 2) + self.assertEqual(os.listdir(self.requests), ["crowdin-sync"]) + + def test_a_request_nothing_picks_up_is_reported_in_the_reply(self): + self.path_units.picks_up = False + data = post(command("run", [("job", "crowdin-sync")])).json()["data"] + self.assertIn("**crowdin-sync** did not start", data["content"]) + self.assertEqual(data["flags"], relay.EPHEMERAL) + + def test_a_run_that_could_still_be_going_when_the_queue_starts_is_refused(self): + timeout = registry.get("crowdin-sync").timeout_seconds + systemd = FakeSystemd(queue_at=time.time() + timeout - 60) + with Patched(relay, systemctl=systemd): + text = self.content(post(command("run", [("job", "crowdin-sync")]))) + self.assertIn(f"The queue runs **crowdin-sync** at ", text) + self.assertEqual(self.started, []) + + def test_a_run_sure_to_end_before_the_queue_starts_goes_ahead(self): + timeout = registry.get("crowdin-duplicates").timeout_seconds + systemd = FakeSystemd(queue_at=time.time() + timeout + 60, path_units=self.path_units) + with Patched(relay, systemctl=systemd): + post(command("run", [("job", "crowdin-duplicates")])) + self.assertEqual(self.started, ["session-ops@crowdin-duplicates.service"]) + + def test_a_disabled_queue_timer_holds_nothing_off(self): + post(command("run", [("job", "crowdin-sync")])) + self.assertEqual(self.started, ["session-ops@crowdin-sync.service"]) + + def test_a_missing_request_directory_is_reported_not_raised(self): + with Patched(registry, REQUESTS_DIR=os.path.join(self.requests, "gone")): + self.assertIn("Could not ask for the job", + self.content(post(command("run", [("job", "crowdin-sync")])))) + self.assertEqual(self.started, []) + + def test_systemctl_missing_is_reported_not_raised(self): + def missing(*args): + raise FileNotFoundError("systemctl") + with Patched(relay, systemctl=missing): + self.assertIn("Could not ask for the job", + self.content(post(command("run", [("job", "crowdin-sync")])))) + + + + +def platform_state(**platforms): + return {"version": store_versions.STATE_VERSION, "platforms": platforms, "sources": {}} + + +class TestVersions(RelayCase): + def setUp(self): + super().setUp() + folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, folder, True) + os.mkdir(os.path.join(folder, "store-versions")) + self.state = os.path.join(folder, "store-versions", "state.json") + self.patch(registry, STATE_ROOT=folder) + + def write(self, state): + with open(self.state, "w", encoding="utf-8") as handle: + json.dump(state, handle) + + def test_a_line_per_platform_visible_to_the_channel(self): + self.write(platform_state( + ios={"github": "2.15.5", "store": "2.15.5", "store_high": "2.15.6", "warning": True}, + android={"github": "1.33.7", "store": "1.33.7", "warning": False})) + lines = relay.versions_message().splitlines() + self.assertEqual(len(lines), len(store_versions.PLATFORMS)) + self.assertIn("**Session iOS**: App Store `2.15.6` / GitHub `2.15.5` ⚠️", lines) + self.assertIn("**Session Android**: Play Store `1.33.7` / GitHub `1.33.7`", lines) + self.assertIn("**Session Desktop**: no data yet", lines) + + def test_a_failing_source_says_since_when(self): + state = platform_state(android={"github": "1.33.7", "store": "1.33.7", "warning": False}) + state["sources"] = {"Play Store (android)": {"since": 1000.0, "alerted_at": None, + "error": "boom"}} + self.write(state) + self.assertIn("**Session Android**: Play Store `1.33.7` / GitHub `1.33.7` " + "(not read since )", relay.versions_message().splitlines()) + + def test_a_non_finite_since_reads_as_unknown(self): + for since in (float("nan"), float("inf")): + state = platform_state(android={"github": "1.33.7", "store": "1.33.7", + "warning": False}) + state["sources"] = {"Play Store (android)": {"since": since, "error": "boom"}} + self.write(state) + self.assertIn("**Session Android**: Play Store `1.33.7` / GitHub `1.33.7`", + relay.versions_message().splitlines()) + + def test_a_malformed_platform_reads_as_no_data(self): + self.write(platform_state(ios="x")) + self.assertIn("**Session iOS**: no data yet", relay.versions_message().splitlines()) + + def test_stale_state_says_so(self): + self.write(platform_state()) + message = relay.versions_message(self.state, now=time.time() + 3600) + self.assertIn("may not be running", message) + self.assertNotIn("may not be running", relay.versions_message(self.state)) + + def test_missing_or_foreign_state_is_one_line(self): + self.assertIn("cannot be read", relay.versions_message(self.state)) + for state in ([], {"version": 99, "platforms": {}}): + with self.subTest(state=state): + self.write(state) + self.assertIn("format", relay.versions_message(self.state)) + + def test_anyone_in_the_server_can_ask_but_not_from_elsewhere(self): + self.write(platform_state()) + with Patched(relay, versions_message=lambda: "the versions"): + response = post(command(discord_commands.VERSIONS, user="5", roles=["6"])) + self.assertEqual(response.json()["data"], {"content": "the versions", + "allowed_mentions": relay.NO_PINGS}) + self.assertIn("do not work here", + self.content(post(command(discord_commands.VERSIONS, guild="9")))) + with mock.patch.dict(os.environ, {"ALLOWED_CHANNEL_IDS": "9"}): + self.assertIn("do not work in this channel", + self.content(post(command(discord_commands.VERSIONS)))) + + +class TestCommands(unittest.TestCase): + def test_run_offers_the_discord_jobs_and_starts_hidden(self): + jobs = registry.load() + run, versions = discord_commands.commands(jobs) + offered = [choice["value"] for choice in run["options"][0]["choices"]] + self.assertEqual(offered, [job.name for job in jobs if job.discord]) + self.assertIn("crowdin-sync", offered) + self.assertEqual(run["default_member_permissions"], "0") + for choice in run["options"][0]["choices"]: + self.assertLessEqual(len(choice["name"]), discord_commands.MAX_CHOICE_NAME) + self.assertEqual(versions["name"], discord_commands.VERSIONS) + self.assertNotIn("default_member_permissions", versions) + + def test_registration_replaces_the_guild_commands(self): + session = FakeSession([FakeResponse([{"name": "run"}, {"name": "versions"}])]) + names = discord_commands.register(session, "app", GUILD, "bot", registry.load()) + method, url, kwargs = session.calls[0] + self.assertEqual((method, url), ("PUT", f"{discord_commands.API}/applications/app" + f"/guilds/{GUILD}/commands")) + self.assertEqual(kwargs["headers"], {"Authorization": "Bot bot"}) + self.assertEqual(names, ["run", "versions"]) + + def test_a_refused_registration_exits_saying_why(self): + session = FakeSession([FakeResponse({"message": "Missing Access"}, status_code=403)]) + with self.assertRaises(SystemExit) as raised: + discord_commands.register(session, "app", GUILD, "bot", registry.load()) + self.assertIn("Missing Access", str(raised.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/ops/test_registry.py b/tests/ops/test_registry.py index 88842f3..e5c6cad 100644 --- a/tests/ops/test_registry.py +++ b/tests/ops/test_registry.py @@ -70,6 +70,30 @@ def test_a_name_listed_twice_is_refused(self): with self.assertRaises(ValueError): load(VALID + VALID) + def test_a_job_is_offered_to_discord_only_when_it_says_so(self): + self.assertFalse(load(VALID)[0].discord) + self.assertTrue(load(VALID + "discord = true\n")[0].discord) + + def test_a_discord_flag_that_is_not_a_boolean_is_refused(self): + with self.assertRaises(ValueError): + load(VALID + 'discord = "yes"\n') + + def test_more_jobs_than_discord_offers_choices_for_is_refused(self): + many = "".join(VALID.replace('"a"', f'"j{i}"') + "discord = true\n" + for i in range(registry.MAX_DISCORD_JOBS + 1)) + with self.assertRaises(ValueError): + load(many) + + def test_a_timeout_is_read_as_a_systemd_time_span(self): + self.assertEqual(load(VALID)[0].timeout_seconds, 1800) + self.assertEqual(load(VALID + 'timeout = "1h 30min"\n')[0].timeout_seconds, 5400) + self.assertEqual(registry.span_seconds("90"), 90) + + def test_a_timeout_systemd_would_not_read_is_refused(self): + for timeout in ("soon", "2x", "1h later", ""): + with self.subTest(timeout=timeout), self.assertRaises(ValueError): + load(VALID + f'timeout = "{timeout}"\n') + def test_the_shipped_registry_loads(self): names = [job.name for job in registry.load()] self.assertIn("zendesk-digest", names) diff --git a/tests/ops/test_runner.py b/tests/ops/test_runner.py index ef2aa0a..8d875d2 100644 --- a/tests/ops/test_runner.py +++ b/tests/ops/test_runner.py @@ -118,6 +118,10 @@ def test_a_bare_webhook_path_is_scrubbed_too(self): self.assertNotIn("abcdef", scrubbed) self.assertIn("(Caused", scrubbed) + def test_a_job_that_cannot_be_loaded_is_reported(self): + self.assertEqual(self.run_job(job("no_such_entry")), 1) + self.assertIn("during **loading the job**", self.posted[0][1][0]["content"]) + def test_missing_environment_is_reported_without_running_the_job(self): the_job = job("succeeds", env=("DEMO_MISSING",)) self.assertEqual(self.run_job(the_job), 1) @@ -217,6 +221,11 @@ def test_an_alert_post_has_a_deadline(self): class TestCommandLine(unittest.TestCase): + def listed(self, *flags): + with contextlib.redirect_stdout(io.StringIO()) as out: + runner.main(["list", *flags]) + return out.getvalue().split() + def test_dry_run_is_the_runners_and_what_follows_dashes_is_the_jobs(self): with mock.patch.object(runner, "run", return_value=0) as run, \ self.assertRaises(SystemExit): diff --git a/tests/store_versions/test_job.py b/tests/store_versions/test_job.py index 8d07f84..1cc8bc5 100644 --- a/tests/store_versions/test_job.py +++ b/tests/store_versions/test_job.py @@ -3,6 +3,7 @@ """ import json import os +import stat import tempfile import unittest @@ -73,6 +74,16 @@ def test_first_run_in_sync_posts_nothing_and_records_both(self): self.assertEqual(run.posted, []) self.assertEqual(set(run.saved()["platforms"]), {"ios", "desktop"}) + def test_the_state_is_readable_by_the_discord_relay_despite_the_umask(self): + run = Run({"session-ios": "2.15.5", "session-desktop": "1.18.2"}, + {"appstore": "2.15.5", "deb": "1.18.2"}) + previous = os.umask(0o077) + try: + run() + finally: + os.umask(previous) + self.assertEqual(stat.S_IMODE(os.stat(run.state).st_mode), 0o644) + def test_warning_tags_the_platforms_people_only(self): run = Run({"session-ios": "2.15.5", "session-desktop": "1.18.2"}, {"appstore": "2.15.6", "deb": "1.18.2"}, tags="[tag]\nios = [42]\n")