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
4 changes: 2 additions & 2 deletions deploy/tts-audio/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ dev-synth: ## Build the image and speak TEXT=... in LOCALE=en|es|br to OUT (defa

# ── GCP bootstrap ─────────────────────────────────────────────────────────────

GCP_PROJECT ?= sredevops-audio
GCS_BUCKET ?= sredevops-audio
GCP_PROJECT ?= sredevopsorg
GCS_BUCKET ?= tts-sredevopsorg
GCP_LOCATION ?= us-central1
GSA_NAME ?= tts-audio-runner
SITE_ORIGINS ?= https://www.sredevops.org,https://sredevops.org,http://localhost:2368
Expand Down
48 changes: 48 additions & 0 deletions deploy/tts-audio/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,37 @@ for the reader-facing behaviour.

## 1. Google Cloud

The defaults in the Makefile (and `base/configmap.yaml`) are
`GCP_PROJECT=sredevopsorg`, `GCS_BUCKET=tts-sredevopsorg`; override them for another
project. The service account is `tts-audio-runner@<project>.iam.gserviceaccount.com` and
needs object access to that bucket only.

```bash
make gcp-bootstrap GCP_PROJECT=<project> GCS_BUCKET=<bucket> GCP_LOCATION=<region>
```

`gcp-bootstrap` needs a principal that can **administer** the bucket (IAM + CORS). The
runner service account deliberately cannot: it is scoped to objects, so it can write audio
but not widen its own permissions. If you are using the runner key by mistake you will see
`storage.buckets.get` / `storage.buckets.update` denied.

Three failures are worth naming, because each one leaves a pipeline that looks deployed
but produces nothing a reader can hear:

| Symptom | Cause |
|---|---|
| `The specified bucket does not exist` | `GCS_BUCKET` names a bucket that was never created, or the wrong project |
| Anonymous `GET` on an object returns **403** | `allUsers` → `roles/storage.objectViewer` is missing; the player cannot read it |
| `OPTIONS` preflight has no `access-control-allow-origin` | CORS was never applied; a ranged seek fails in the browser |

Verify all three after the bootstrap:

```bash
curl -s -o /dev/null -w 'anonymous: %{http_code}\n' "https://storage.googleapis.com/$GCS_BUCKET/<any-object>"
curl -sI -X OPTIONS -H 'Origin: https://www.sredevops.org' -H 'Access-Control-Request-Method: GET' \
"https://storage.googleapis.com/$GCS_BUCKET/<any-object>" | grep -i access-control
```

That command is idempotent and does four things:

1. Creates the bucket with **uniform bucket-level access** and public-access prevention, so
Expand Down Expand Up @@ -223,11 +250,32 @@ hash includes the voice, so every post is regenerated on its next edit or backfi

## Operating it

### Is the Admin key actually valid?

Do not judge it by `/site/`: that endpoint answers **200 without any auth**, so a revoked key
looks fine there. Test an endpoint that requires an integration and compare it with a
deliberately wrong key — the two must differ:

```bash
curl -s -o /dev/null -w 'given: %{http_code}\n' \
-H "Authorization: Ghost $ADMIN_KEY" https://www.sredevops.org/ghost/api/admin/settings/
curl -s -o /dev/null -w 'garbage: %{http_code}\n' \
-H "Authorization: Ghost 000000000000000000000000:$(printf 'f%.0s' $(seq 64))" \
https://www.sredevops.org/ghost/api/admin/settings/
```

A **403** is "no key sent"; **400 `INVALID_JWT`** is "a key was sent and rejected". If the
given key returns the same 400 as the garbage one, the integration was deleted or its key
regenerated — create/repair it in Ghost Admin → Integrations, give it the **Administrator**
role, and re-run `make secret` + `make restart`.

| Symptom | Look at | Likely cause |
|---|---|---|
| Post stays silent after publishing | `make logs` (receiver), then `kubectl -n tts-audio logs job/tts-...` | webhook secret mismatch (401), Gateway not routing, post has no locale tag |
| Backfill job fails immediately | `kubectl -n tts-audio logs job/tts-backfill` | `INVALID_JWT` — see "Is the Admin key actually valid?" above |
| Receiver logs `ignore … content hash unchanged` | — | Ghost re-saved the post; expected |
| Job fails with `Ghost 401` | Secret | Admin API key revoked or wrong format |
| Job fails with `Ghost 400 INVALID_JWT` | Secret | the Admin API key is not valid on this instance: revoked, or copied from a different integration. `/site/` still answering 200 proves nothing — it is public without auth |
| Job fails with `bucket` errors | Secret | key rotated without `make secret`, or the GSA lost its binding |
| Player falls back to Cloud TTS on an old post | `make status` | its marker was removed, or the object expired (90-day lifecycle) |
| `cf-verify` fails on partial content | Cloudflare | proxy stripped ranges — use a DNS-only record |
Expand Down
2 changes: 1 addition & 1 deletion deploy/tts-audio/base/configmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ metadata:
data:
GHOST_API_URL: "https://www.sredevops.org"
SITE_URL: "https://www.sredevops.org"
GCS_BUCKET: "sredevops-audio"
GCS_BUCKET: "tts-sredevopsorg"
AUDIO_BASE_URL: "https://audio.sredevops.org"

# Kokoro-82M v1.0 voices. Same female timbre across locales, replacing Chirp 3: HD
Expand Down
2 changes: 1 addition & 1 deletion deploy/tts-audio/scripts/cors.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUCKET="${GCS_BUCKET:-sredevops-audio}"
BUCKET="${GCS_BUCKET:-tts-sredevopsorg}"

command -v gcloud >/dev/null || { echo "cors: gcloud is required" >&2; exit 2; }

Expand Down
42 changes: 40 additions & 2 deletions deploy/tts-audio/worker/src/backfill.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ import { createPostJob } from "./k8s.mjs";

const PAGE_LIMIT = 50;

/**
* Ghost's machine-readable error code (`INVALID_JWT`, `RESOURCE_NOT_FOUND`, …), or "".
*
* The body has to be read once; a non-JSON body (an HTML error page from a proxy) is not
* an error in itself, it just adds nothing.
*/
async function ghostErrorCode(response) {
try {
const body = await response.json();
return body?.errors?.[0]?.code ?? "";
} catch {
return "";
}
}

/**
* List published posts with the fields the backfill needs.
*
Expand All @@ -37,7 +52,19 @@ async function listPosts(config, { fetchImpl = fetch, page = 1, limit = PAGE_LIM
headers: { Authorization: `Ghost ${config.adminKey}`, Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`listing posts failed: Ghost ${response.status} ${response.statusText}`);
// Keep Ghost's own error, and say which key failed when it is an auth failure.
// "Ghost 400 Bad Request" is what a revoked or wrong admin key looks like: the whole
// backfill dies on its first request and the runbook's debugging section is about
// buckets, so the message has to carry both facts.
const code = await ghostErrorCode(response);
const keyId = String(config.adminKey ?? "").split(":")[0] || "(unset)";
const hint =
code === "INVALID_JWT"
? ` — the Admin API key was rejected (key id ${keyId}). Check that the integration ` +
`still exists in Ghost Admin → Integrations, regenerate its Admin API key, and ` +
`update the tts-audio Secret`
: "";
throw new Error(`listing posts failed: Ghost ${response.status}${code ? ` ${code}` : ""}${hint}`);
}
const payload = await response.json();
return { posts: payload?.posts ?? [], pagination: payload?.meta?.pagination ?? { page, pages: 1 } };
Expand Down Expand Up @@ -78,7 +105,18 @@ export async function backfill({ config, log = () => {}, fetchImpl = fetch, dryR
const totals = { scanned: 0, eligible: 0, created: 0, skipped: 0, ineligible: 0, failed: 0 };

do {
const { posts, pagination } = await listPosts(config, { fetchImpl, page });
let posts;
let pagination;
try {
({ posts, pagination } = await listPosts(config, { fetchImpl, page }));
} catch (err) {
// A listing failure is the whole run failing — most often a rejected Admin key. Log
// it the same way as a per-post failure and stop, instead of letting the exception
// escape with no structured line around it.
log(`listing page ${page} failed: ${err.message}`);
log(JSON.stringify({ result: "failed", ...totals, page }));
return 1;
}
pages = pagination.pages ?? 1;
log(`page ${page}/${pages}: ${posts.length} post(s)`);

Expand Down
7 changes: 7 additions & 0 deletions deploy/tts-audio/worker/src/ghost.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,19 @@ function headers(adminKey) {
async function fail(response) {
let message = response.statusText;
let body = null;
let code = "";
try {
body = await response.json();
message = body?.errors?.[0]?.message ?? message;
code = body?.errors?.[0]?.code ?? "";
} catch {
// A non-JSON body adds nothing; the status is still reported.
}
// A rejected key is the most common first-run failure and the least self-explanatory:
// Ghost answers `INVALID_JWT` with a 400, which reads like a malformed request.
if (code === "INVALID_JWT") {
message += " (the Admin API key was rejected — regenerate it in Ghost Admin → Integrations and update the Secret)";
}
throw new GhostError(response.status, message, body);
}

Expand Down
36 changes: 36 additions & 0 deletions deploy/tts-audio/worker/test/ghost.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,39 @@ test("a payload without content_hash still gets a unique job name per delivery",
assert.notEqual(created[0].hash, created[1].hash);
assert.match(created[0].hash, /^e[0-9a-f]{9}$/);
});

test("a rejected Admin key is reported as an auth failure, not a bad request", async () => {
// Ghost answers a revoked key with 400 INVALID_JWT, which reads like a malformed query.
// Both the post client and the backfill listing must say what to do about it.
const wrongKey = {
status: 400,
statusText: "Bad Request",
json: async () => ({ errors: [{ message: "Invalid token", code: "INVALID_JWT" }] }),
text: async () => "",
};
const fetchImpl = async () => wrongKey;

await assert.rejects(() => readPost(config, "abc", { fetchImpl }), /Admin API key was rejected/);
});

test("the backfill listing names the failing key on INVALID_JWT", async () => {
const { backfill } = await import("../src/backfill.mjs");
const wrongKey = {
status: 400,
statusText: "Bad Request",
ok: false,
json: async () => ({ errors: [{ message: "Invalid token", code: "INVALID_JWT" }] }),
};
// The first listing request fails, so `backfill` reports through its own log and exits 1.
const lines = [];
const code = await backfill({ config, log: (line) => lines.push(line), fetchImpl: async () => wrongKey });
assert.equal(code, 1);
const joined = lines.join("\n");
assert.match(joined, /INVALID_JWT/);
// The key id is named so an operator can tell *which* integration to regenerate. This
// config's key is `id:s`, so the id is `id`.
assert.match(joined, /key id id\)/);
assert.match(joined, /regenerate its Admin API key/);
// And the run ends with a structured line rather than an escaping exception.
assert.match(joined, /"result":"failed"/);
});