Compare commits
5
Commits
5e8e2b8c0a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16aa73251b | ||
|
|
c60c9bb317 | ||
|
|
debdeb6754 | ||
|
|
7dd9c947fd | ||
|
|
349a68b8b7 |
No files matched your search
+9
-3
@@ -15,7 +15,7 @@ A human Principal (the Owner, family, friends).
|
||||
_Avoid_: User, human user, member
|
||||
|
||||
**Bot**:
|
||||
A non-human Principal: a script, automation, or integration such as Home Assistant.
|
||||
A non-human Principal: a script, automation, or integration such as Home Assistant. Some Bots are built into hAPI itself, such as the scheduler, and never hold a Token.
|
||||
_Avoid_: Service account, machine user, integration account
|
||||
|
||||
**Owner**:
|
||||
@@ -60,6 +60,12 @@ _Avoid_: Shared data, common data
|
||||
The Principal that created or last changed a record, distinct from who owns it.
|
||||
_Avoid_: Author, owner, creator
|
||||
|
||||
### Notifications
|
||||
|
||||
**Notification**:
|
||||
A message hAPI keeps for one Person or for the Household about something that needs their attention, delivered through one or more channels such as ntfy. A Notification to a Person is seen only by that Person; one to the Household by every Household member. Platform alerts to the Owner (from CI, delivery, or monitoring) are not Notifications.
|
||||
_Avoid_: Alert, event, message
|
||||
|
||||
### Smart home
|
||||
|
||||
Smart home is hAPI's side of the house: queuing Jobs for Home Assistant, which remains the source of truth for the house's state.
|
||||
@@ -108,10 +114,10 @@ _Avoid_: Rule, auto-categorization
|
||||
|
||||
### Maintenance
|
||||
|
||||
Maintenance is the upkeep of the Household's physical property: the home, its land, its equipment, and its vehicles.
|
||||
Maintenance is the recurring upkeep of the Household's property: the home, its land, its equipment, its vehicles, and its digital systems (such as the hAPI cluster). It is not a to-do list: errands, bills, and one-off chores don't belong.
|
||||
|
||||
**Asset**:
|
||||
A physical thing the Household keeps up, such as the roof, the furnace, a fridge, or a car. It may have a meter whose Readings track its use.
|
||||
A thing the Household keeps up, such as the roof, the furnace, a car, or the hAPI cluster. It may have a meter whose Readings track its use.
|
||||
_Avoid_: Equipment, item, entity (a Home Assistant term); in Finance, use another word
|
||||
|
||||
**Task**:
|
||||
|
||||
@@ -28,6 +28,6 @@ hAPI uses a **Linode Managed PostgreSQL 18** cluster (Shared 2 GB, 1 node) attac
|
||||
- **Cross-Person work runs per Person.** Purging a removed Person's data, or a job such as reminders, sets `hapi.principal_id` to each Person in turn.
|
||||
- **Data repairs** normally ship as reviewed Alembic data migrations run as `hapi_migrator`, targeting rows by id or condition without printing them.
|
||||
- **Break-glass goes through `hapi db breakglass --reason "…"`.** It opens `psql` as `hapi_migrator` from a pod and emits structured audit events to hAPI's centralized logs: start, end, reason, and every statement. Query results are never logged. The platform offers no statement logging or pgaudit, so this is the only audit trail.
|
||||
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget.
|
||||
- **Plan changes are restores.** An in-place resize stalled during verification. Changing size or node count is done as a restore-to-new-cluster, with the same runbook as disaster recovery: fork, wait for DNS, `hapi db bootstrap`, repoint the app. Single-node maintenance windows (pinned to a quiet slot) cause short downtime, covered by 14-day point-in-time recovery.
|
||||
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget. **Amended by ADR-0012:** housekeeping CronJobs use a pool of 1, so the rule is app pods (with surge) × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
|
||||
- **Plan changes are restores.** An in-place resize stalled during verification. Changing size or node count is done as a restore-to-new-cluster, with the same runbook as disaster recovery: fork, wait for DNS, `hapi db bootstrap`, repoint the app. Single-node maintenance windows (pinned to a quiet slot) cause short downtime, covered by 14-day point-in-time recovery. **Amended by ADR-0014:** our own daily dumps (an Object Lock bucket, pulled off-account) cover damage found after 14 days and account loss, and `hapi db bootstrap` also creates a read-only `BYPASSRLS` `hapi_backup` role for `hapi db backup`.
|
||||
- Passwords are rotated manually with a runbook. `password_encryption` is set explicitly to `scram-sha-256`.
|
||||
@@ -14,7 +14,7 @@ hAPI needs Home Assistant to carry out actions in the house: things queued while
|
||||
|
||||
- **The bridge needs no new infrastructure or credentials.** HA is the `home-assistant` Bot with a Household grant of `smart_home:write`, and its Token lives in HA's `secrets.yaml`. There's no `jobs` Scope: `smart_home:write` both creates Jobs and consumes them, and ADR-0005 allows splitting the Scope later.
|
||||
- **Delivery is at-least-once, FIFO by `not_before` (or creation time).** `next` hands out the oldest eligible Job and hides it for a 2-minute lease. After 3 deliveries with no result, the Job becomes `failed` (`no_result`), so one broken Job can't stall the queue. HA scripts must be idempotent: set states, don't toggle. After each result, HA calls `homeassistant.update_entity` on the sensor so a backlog drains without waiting for the next poll.
|
||||
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. Until scheduling exists, `hapi jobs purge` removes them.
|
||||
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. `hapi jobs sweep`, a CronJob every 15 min (ADR-0012), removes them and marks pending Jobs past `expires_at` as `expired`; until it does, reads derive `expired` from `expires_at`.
|
||||
- **hAPI checks only the shape of a Job, not what it does.** Script names must match `hapi_[a-z0-9_]+`, and variables are capped at 16 KB. hAPI keeps no catalogue of HA scripts. HA rejects unknown scripts, which comes back as a failed result.
|
||||
- **HA-side configuration** is a reference package in this repo (`integrations/home-assistant/hapi_jobs.yaml`: rest sensor, automation, rest_command), copied into HA by hand. The `hapi_*` scripts themselves live in a separate HA configuration repo.
|
||||
- **hAPI records HA's last poll**, so a stalled bridge can be detected. Turning that into an alert is part of observability.
|
||||
@@ -20,5 +20,5 @@ Every green merge to protected `main` reaches production, with no release tags a
|
||||
- **The CI write credential is a deploy key with write access**, stored as an Actions secret and allowlisted past `main`'s branch protection. The build workflow's path filter skips bump commits, so a bump doesn't trigger another build.
|
||||
- **Renovate runs nightly** on the same runner as its own bot user. It auto-merges only dev-only tooling. Anything that ships (runtime dependencies, base image, charts, Flux, Talos, OpenTofu providers) arrives as a PR the Owner merges.
|
||||
- **Not delivered through Flux:** the runner VM, Cilium, and the Linode CCM live in OpenTofu under `infra/`, and the Owner runs `tofu apply` over the tailnet. Talos and Kubernetes upgrades are a manual `talosctl` runbook. CI never holds the Tofu state key.
|
||||
- **Failures notify through ntfy:** a final `if: failure()` step in each workflow, and Flux's notification-controller for failed reconciles and rollouts. Topics and auth are designed with notifications.
|
||||
- **Failures notify through ntfy:** a final `if: failure()` step in each workflow, and Flux's notification-controller for failed reconciles and rollouts. Topics and auth: ADR-0013 (`ops` topic, each sender its own publish-only ntfy user).
|
||||
- **Deferred:** having Flux verify commit signatures, and signing images (cosign) with admission-time verification. Both guard against a compromised Gitea and belong together in cluster hardening.
|
||||
@@ -16,9 +16,9 @@ ADR-0002 allows no anonymous public endpoints, but kubelet probes can't carry a
|
||||
|
||||
- **`/livez`** returns a constant. **`/readyz`** passes once startup is done (config loaded, pools created). On SIGTERM, `/readyz` fails first and the pod drains for about 5 s before it shuts down. Readiness also gates rollouts (ADR-0007): an image that never becomes Ready stalls the rollout.
|
||||
- **`/v1/health`** checks `db` (a `SELECT 1` through the app pool) and `schema` (at the expected Alembic head). These are critical: if either fails, the status is `down` with HTTP 503. It also checks `ha_bridge` (no poll for 5 min, see ADR-0006) and `job_backlog` (oldest pending Job too old). These are non-critical: if one fails, the status is `degraded` with HTTP 200. Bodies carry no error text, hostnames, versions or latencies. Kuma points two monitors at it: *up* (HTTP status) and *healthy* (a JSON query asserting `status == "ok"`).
|
||||
- **Collection:** vmagent scrapes the app, kubelet/cAdvisor, kube-state-metrics, node-exporter, Flux and Cilium. A Vector DaemonSet takes pod stdout and Talos service logs (`machine.logging`, JSON over TCP). An event exporter ships Kubernetes Events as logs. Everything lives in a `monitoring` namespace on Block Storage PVs and arrives as Flux `HelmRelease`s.
|
||||
- **Collection:** vmagent scrapes the app, kubelet/cAdvisor, kube-state-metrics, node-exporter, Flux and Cilium. A Vector DaemonSet takes pod stdout and Talos service logs (`machine.logging`, JSON over TCP). An event exporter ships Kubernetes Events as logs. Everything lives in a `monitoring` namespace on Block Storage PVs and arrives as Flux `HelmRelease`s. **Amended by ADR-0015:** the Vector and node-exporter DaemonSets run in a separate `privileged` namespace, `monitoring-node`, while `monitoring` enforces Pod Security `restricted`. Vector also ships the Kubernetes audit log.
|
||||
- **App metrics** come from `prometheus-client`: requests by route template, method and status; latency; DB pool usage; Job depth, age and failures; seconds since HA's last poll; auth failures by reason. **Labels never carry `principal_id` or Personal data.** Per-Principal detail stays in logs.
|
||||
- **Retention:** logs and metrics are kept for 30 days, breakglass audit events for 1 year.
|
||||
- **Retention:** logs and metrics are kept for 30 days, breakglass audit events for 1 year. **Amended by ADR-0014:** the daily backup job also exports breakglass audit events to the backup bucket, and the off-account copy keeps them for 1 year, so they survive a cluster rebuild. **Amended by ADR-0015:** Kubernetes audit logs are also kept 1 year and included in the same export.
|
||||
- **Locked down:** Grafana requires login, with analytics, update checks and Gravatar off. Datasource plugins are pinned in the image. Outbound traffic from `monitoring` is denied by default, except vmalert → ntfy and the Watchdog → Kuma push.
|
||||
- **Every failure has one alerting owner.**
|
||||
- Kuma: reachability and degraded status.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Importer Bots run in-cluster and call hAPI's internal Service
|
||||
|
||||
Finance fills its ledger from importer Bots that call `POST /v1/finance/transactions/ingest`; hAPI itself holds no bank credentials. v1 ships one importer, the **SimpleFIN Bot**, for the Household's Financial Accounts only. It is a **CronJob in the cluster's `bots` namespace**, built from its own package (`bots/simplefin/`) and image in this repo, delivered by the same CI and Flux as hAPI (ADR-0007). It calls hAPI through the **in-cluster Service** rather than `hapi.bobbypalko.com`, still authenticating with its own Bot Token like every other Principal (ADR-0005). We chose this because the cluster already provides SOPS secrets, logs, delivery and Kuma push, and because an outage at the public edge shouldn't stop imports.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **A home machine.** Outbound traffic works fine from behind CGNAT, but it's one more box to patch, monitor and keep secrets on, outside Flux and SOPS.
|
||||
- **Calling the public hostname.** This fits ADR-0002's "one public surface" more literally, but it ties imports to the NodeBalancer and Envoy and charges the edge's per-IP limits for traffic that never leaves the cluster.
|
||||
- **A subcommand of the hAPI image** (`hapi import simplefin`). This would put bank-facing code and its egress inside the API's image and blur the line that importers are Bots outside hAPI.
|
||||
- **A separate repo.** Rejected under the standing "in this repo, cleanly separable" preference. import-linter forbids `bots/` from importing `hapi.*`, so the Bot talks to hAPI over HTTP only.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **ADR-0002 is narrowed rather than broken.** Every request still needs a Principal's Token. Only in-cluster Bots skip the edge, and the Gateway still never routes `:8081`.
|
||||
- **Credentials:** the Bot is the Principal `simplefin-importer`, holding a single Household grant of `finance:write` and no Bindings. Its Token, the SimpleFIN Access URL, the mapping from SimpleFIN account ids to Financial Account ids, and its Kuma push URL all live in one SOPS secret (`bot-simplefin`) and are mounted as files (ADR-0008). The Vaultwarden item "SimpleFIN Access URL" stays the source of truth. The mapping is encrypted because account ids and institutions are metadata we keep out of a public repo. Unmapped SimpleFIN accounts are skipped with a warning.
|
||||
- **Runs:** every 6 h with `concurrencyPolicy: Forbid`, fetching a `start-date` 14 days back. The overlap absorbs posting lag and outages of up to two weeks, and idempotent ingest drops repeats. History starts at each Account's `tracked_from`, and there is no backfill.
|
||||
- **Failure:** a SimpleFIN transport error, a non-empty `errors` array (e.g. a bank needs reconnecting), or a failed ingest makes the run exit non-zero. A clean run pings a Kuma push monitor with a 13 h window, which allows two missed runs (ADR-0009).
|
||||
- **Network:** `bots` is default-deny. Egress is allowed only to DNS, the hAPI app port, and, through Cilium `toFQDNs`, the SimpleFIN bridge and Kuma push hosts on 443. Pods run non-root, with a read-only root filesystem and no service-account token.
|
||||
- **No shared Bot library** until a second Bot exists.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Scheduled work runs as CronJobs of the hAPI image, as a tokenless `scheduler` Bot
|
||||
|
||||
hAPI's recurring work is a small set of **Kubernetes CronJobs that run `hapi <subcommand>`** from the same digest-pinned image as the app, delivered the same way as the migrate Job (ADR-0007). There is no worker Deployment, no in-process scheduler and no task queue. Most domain logic is computed on read (Finance summaries, Maintenance due dates, Fitness bests), so little has to run on a timer. A CronJob keeps nothing running between runs, gets retries and `concurrencyPolicy: Forbid` from Kubernetes, and is a CLI command the Owner can also run by hand.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **A worker Deployment with an in-process scheduler** (APScheduler, arq). Rejected: it runs all the time, holds its own pool of up to 10 connections from ADR-0004's budget, and needs leader election before it can have more than one replica.
|
||||
- **Scheduling inside the API pods.** Rejected: with 2 replicas every task needs an advisory lock, and the work competes with requests for the event loop.
|
||||
- **A transactional outbox of domain events** (e.g. "Reading recorded"), drained by a CronJob. Rejected for v1. The state already in the database is the event: a scheduled check compares it with what has already been notified, at the cost of up to one interval of latency. A generic event model can arrive once something needs sub-minute reactions.
|
||||
- **FastAPI `BackgroundTasks` after commit.** Rejected: the work is lost if the pod dies.
|
||||
- **Running as `hapi_migrator`**, which bypasses RLS as the table owner. Rejected: it would put migrator credentials in a recurring pod.
|
||||
- **Giving the scheduler Bindings to Personal data.** Rejected: every Person would have to consent, and v1's per-Person work is read-only anyway.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **v1 inventory:** `hapi jobs sweep` every 15 min marks pending Jobs past `expires_at` as `expired` and deletes finished Jobs older than 90 days (replacing ADR-0006's `hapi jobs purge`). Reads derive `expired` from `expires_at` until the sweep catches up, so correctness never depends on how often it runs. The notification checks are CronJobs running `hapi notify <check>` (`tasks`, `jobs`, `budget`, `tokens`), plus `hapi notify deliver` every 2 min, which alone publishes to ntfy (ADR-0013). Purging a removed Person's data stays an on-demand Owner CLI command, and Finance month rollover, Banked carry-forward and `date_review` need no schedule.
|
||||
- **Principal:** work on Household data runs as a built-in **`scheduler` Bot**. A migration creates it, it can never hold a Token (so it can't be reached from the API), and the Owner gives it Household grants like any other Bot. Recorded by shows `scheduler`. Work on Personal data runs once per Person with `hapi.principal_id` set to that Person (ADR-0004), and is **read-only**: a scheduled write to Personal data needs a new decision.
|
||||
- **Event-triggered work** (e.g. a new Reading making a Task due) is picked up by the next scheduled check. Checks write **durable Notifications**, which double as the record of what was already notified. A Notification not yet delivered stays pending and is retried on the next run, so an ntfy outage loses nothing, and a future frontend inbox reads the same records.
|
||||
- **Connection budget (amends ADR-0004):** each housekeeping CronJob uses a pool of 1 with no overflow and `concurrencyPolicy: Forbid`. The rule becomes: app pods including surge × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
|
||||
- **Monitoring:** one generic vmalert rule fires when any CronJob hasn't succeeded within twice its interval (kube-state-metrics' `kube_cronjob_status_last_successful_time`). ADR-0009's Watchdog covers vmalert itself. Kuma push monitors are kept for jobs whose silence must be caught even when the whole cluster is down: the importer (ADR-0011) and backups.
|
||||
- **Time:** the Household timezone is one setting in `deploy/`, fed both to the app config and to `spec.timeZone` on calendar-based CronJobs (daily checks, month-end). Interval jobs like the sweep ignore it.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Notifications are durable records delivered by one CronJob; platform alerts bypass hAPI
|
||||
|
||||
hAPI's **Notifications** are database records addressed to one Person or to the Household, written by `hapi notify <check>` CronJobs (ADR-0012) and published to ntfy at **notify.bobbypalko.com** by a single `hapi notify deliver` CronJob. **Platform alerts are a separate lane:** CI, Flux, vmalert and Kuma publish straight to Owner-only ntfy topics with their own credentials and never touch hAPI, because they must work when hAPI or its database is down. ntfy is the only channel in v1: no preferences, no read state, no Notifications API; a Person opts out by muting in the ntfy app.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Routing platform alerts through hAPI** (one Notification model for everything). Rejected: an alert that hAPI is down can't depend on hAPI.
|
||||
- **Each check delivering what it wrote, or every check draining all pending Notifications.** Rejected: a budget run sending Token reminders is surprising, and an ntfy outage would fail every check. One deliver job keeps checks pure writers and isolates ntfy failures to one CronJob.
|
||||
- **Checks over Personal domain data** (e.g. a Person's Budget). Deferred to v2 with the Personal importer: they'd need scheduled writes for a Person, which ADR-0012 forbids.
|
||||
- **Per-Person preferences and a frontend inbox.** Deferred: the records already support an inbox and read state later.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **ntfy access:** the server denies anonymous read and publish. The Owner manages users by hand from a runbook in `docs/` (also an off-boarding step alongside Token revocation): a read-only user per Person for `hapi-p-<person-id>` and `hapi-household`; the Owner's user also reads `ops` and `ops-urgent`; each sender (hAPI, vmalert, Flux, CI, Kuma) has its own publish-only user limited to its topics. hAPI's, vmalert's and Flux's tokens come through SOPS (ADR-0008), CI's is a Gitea secret, Kuma's lives in Kuma. Topics are named by id, never by name. `upstream-base-url` points at ntfy.sh for iOS (only a poll request leaves, never content), the cache stays at 12 h, attachments are off.
|
||||
- **Content:** a short title and a link to the resource. Never amounts, balances, Measurements or other domain values.
|
||||
- **v1 checks** (all run as the `scheduler` Bot, read only Household and platform data):
|
||||
|
||||
| Check | Recipient | Fires | Schedule |
|
||||
|---|---|---|---|
|
||||
| `tasks` | Household | once on entering `lead_days`, once on overdue, per due occurrence (a Service or snooze starts the next) | daily 08:00 |
|
||||
| `jobs` | Household | a Job ends `failed` or `expired` | every 15 min |
|
||||
| `budget` | Household | a Household Budget Category goes into the red this month (Banked: its banked balance goes negative); refires only after it recovers | hourly |
|
||||
| `tokens` | the Token's Person, or the Owner for Bot Tokens | 30 and 7 days before expiry | daily |
|
||||
|
||||
- **Record:** recipient (Person or Household), `kind`, `dedupe_key` (unique with `kind`; it is the "already notified" ledger), `title`, `body`, priority 1–5, optional link, `created_at`, `delivered_at`, `attempts`. `hapi jobs sweep` deletes delivered Notifications after 180 days.
|
||||
- **Delivery:** `hapi notify deliver` every 2 min publishes pending Notifications oldest first, using the Notification id as ntfy's message/sequence id so retries don't double-push. It gives up after 24 h; a vmalert rule fires on undelivered Notifications that old. It counts as one more pool-1 CronJob in ADR-0012's connection rule.
|
||||
- **Breakglass fails closed:** `hapi db breakglass` publishes a priority-5 Household alert synchronously (and records a Notification) before opening the session, and refuses to start if the publish fails. Bypassing the wrapper with raw credentials remains the residual risk ADR-0009 accepts.
|
||||
- **Platform topics and priorities:** `ops` (Flux, vmalert, CI) and `ops-urgent` (Kuma *down*, the Watchdog). Priority 5: Kuma down, breakglass. 4: vmalert critical, Flux reconcile/rollout failure, Task overdue. 3: CI failure, Kuma degraded, Job failed/expired, Token expiring in 7 days. 2: Task due soon, budget overspend, Token expiring in 30 days.
|
||||
- **Importer staleness** needs no hAPI check: the SimpleFIN Bot already fails on a non-empty `errors` array and Kuma's 13 h push monitor catches it (ADR-0011).
|
||||
- **Egress** to notify.bobbypalko.com:443 is needed from hAPI's CronJobs and Flux's notification-controller (vmalert's is already allowed by ADR-0009); the policies themselves belong to cluster hardening.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Backups go to an Object Lock bucket the cluster can't read back, pulled off-account to the Owner's machine
|
||||
|
||||
Linode's 14-day point-in-time recovery covers a bad migration, a bad delete or a lost database (ADR-0004). It doesn't cover damage found after 14 days, or losing the Linode account. So hAPI also takes its own daily dump. A **`hapi db backup` CronJob** streams `pg_dump -Fc | age | upload` into **`hapi-backups`**, a Linode Object Storage bucket with **Object Lock in compliance mode**. Dumps are encrypted to a **dedicated backup age recipient**, and its private key is never in the cluster. A **puller outside Linode**, holding only a `read_only` key, copies new objects out and never deletes or overwrites them. A compromised cluster can therefore neither read nor erase backups, and losing the account doesn't lose them. Recovery targets: (a) inside Linode, minutes of data lost and back within about 2 h; (b) damage found late, up to one day lost; (c) account loss, everything since the puller's last copy lost, with a weekend of downtime acceptable. Nothing is highly available.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Backblaze B2 (or R2 or S3) as the off-platform target.** Rejected in favour of Linode plus a pull: no new vendor, and Object Lock plus an off-account copy give the same protection. Linode keys are only `read_only` or `read_write` (there's no write-only key), so compliance-mode lock is what stops the cluster's key from deleting.
|
||||
- **Pushing to a home NAS.** Impossible: no connection may start from home into the cluster (ADR-0002, CGNAT). The pull direction works.
|
||||
- **Encrypting with the SOPS age key.** Rejected: Flux holds it in the cluster, so a compromised cluster could decrypt every old dump.
|
||||
- **Dumping as `hapi_migrator`** (it owns the tables, so it bypasses RLS). Rejected by ADR-0012: no migrator credentials in recurring pods.
|
||||
- **A separate backup image** (postgres + age + rclone). Rejected: ADR-0012's one-image, one-delivery-path rule. `postgresql-client-18` is added to the hAPI image instead, and `pg_restore` comes with it.
|
||||
- **etcd / Talos snapshots.** Not taken: everything in etcd is in git or can be recreated (certificates get reissued, the Tailscale operator re-authenticates from SOPS, the CCM recreates the NodeBalancer on the reserved IP). Losing the cluster means rebuilding it from code (ADR-0003).
|
||||
- **Keeping breakglass audit events only in VictoriaLogs**, or also writing them to Postgres. Rejected: the monitoring PVs don't survive a rebuild, and `hapi_migrator` could edit rows in Postgres.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **`hapi_backup` role** (amends ADR-0004): LOGIN, `BYPASSRLS`, SELECT only, created by `hapi db bootstrap`. Its reads stay complete through `ALTER DEFAULT PRIVILEGES` set as `hapi_migrator`. Its password is its own SOPS secret, mounted only into the backup pod. Whoever holds it, or the backup private key, can read all Personal data. Like `akmadmin` and the Tofu state, that is controlled by policy and audit, not by cryptography (ADR-0001). The dump uses one connection, counted in ADR-0012's CronJob term. To verify during the build: that `akmadmin` can create a `BYPASSRLS` role on Aiven.
|
||||
- **Backup key:** an age keypair generated offline. The cluster has only the public recipient, in plain config. The private key is in Vaultwarden and the offline copy (ADR-0008), next to the other Owner roots.
|
||||
- **Bucket:** created by Tofu with Object Lock (compliance mode, which turns on versioning). Each object is locked for 35 days, and a lifecycle rule expires it after 35 days. The cluster's key is `read_write` and limited to this bucket (through SOPS). To verify during the build: that it can't delete a locked version.
|
||||
- **Schedule and content:** daily at 03:00 Household time (`spec.timeZone`, ADR-0012). The job copies the plaintext stream into `pg_restore --list` before encrypting it, so an archive whose table of contents doesn't parse fails the run. The same job exports the previous day's breakglass audit events from VictoriaLogs to `audit/`, encrypted to the same recipient (amends ADR-0009: the 1-year retention now survives a rebuild). The backup pod's egress is limited to the DB, Object Storage, VictoriaLogs and Kuma.
|
||||
- **Puller:** a script in `infra/backup-pull/` (with a `just` recipe) running `rclone copy --immutable` plus pruning. It keeps 90 dailies, the dump from each 1st of the month for 3 years, and `audit/` for 1 year. It also pulls the versioned Tofu state bucket (which holds the Talos machine secrets, ADR-0003) with a second `read_only` key. It isn't a Principal: it never talks to hAPI. **For now it runs on the Owner's PC** as a systemd user timer (daily, `Persistent=true`). There, tier (c)'s data loss is "since the last pull", which is safe as long as the PC pulls at least once in 35 days. **It moves unchanged to a NAS** when one exists.
|
||||
- **Monitoring:** two Kuma push monitors. The backup CronJob's alerts after 26 h of silence. The puller's (it pushes only after copying an object less than 26 h old) alerts after **8 days while it runs on the PC. Change that to 26 h when it moves to the NAS.** ADR-0012's generic vmalert rule also covers the CronJob.
|
||||
- **Restore runbook:** the database is VPC-only, so restores run as **`hapi db restore`** in a pod. The Owner pastes in the backup private key at run time (like the `akmadmin` password), and it's never stored. Path **(A)**: a Linode point-in-time fork, then bootstrap, then repoint the app (ADR-0004's runbook, shared with plan resizes). Path **(B)**: a new database, then bootstrap, then `hapi db restore` from our dump as `hapi_migrator`, then repoint the app. If the account is lost, the Owner first uploads the dump from the puller's copy into the new account's bucket. A cluster rebuild needs the SOPS age key, the Tofu state passphrase (Vaultwarden or the offline copy) and Gitea. Backing up Gitea is out of scope. Its fallbacks are the Owner's local clone and rebuilding images in CI.
|
||||
- **Rehearsal:** before go-live, as acceptance for the build epic, run one full drill: rebuild the cluster from code in an empty Linode project, then path (B) from a pulled copy. After that, every 6 months, run path (B) into a throwaway database, check the Alembic revision and row counts per table, then delete it. This also rehearses plan resizes. It's tracked as a Household Maintenance Task, "Rehearse disaster recovery" (fixed RRULE), so the `tasks` check reminds through ntfy. **Amended by ADR-0015:** the Task concerns the "hAPI cluster" Asset, now that Maintenance covers the Household's digital systems.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Cluster hardening baseline: deny-by-default network, restricted pods, audit logs; signing deferred
|
||||
|
||||
v1 hardens the cluster with built-in mechanisms only. That means **default-deny CiliumNetworkPolicies** in every namespace we own, **Pod Security `restricted`** wherever it fits, two **ValidatingAdmissionPolicies** (in-apiserver CEL rules), **Kubernetes audit logging**, and a written **upgrade runbook** with a fixed cadence. **Commit signature verification and cosign image signing are deferred.** We chose this because each measure here closes a real gap without adding a controller to run. Signing would only move trust onto keys held by the same Gitea and runner it's meant to protect against.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Flux commit verification plus cosign signing with admission-time verification, in v1.** Rejected for now. CI commits the digest bump to `main` (ADR-0007), so HEAD is usually a CI commit, and CI would need its own signing key. There's no keyless identity for Gitea, so the cosign key would be key-based too. Both keys would live in Gitea Actions secrets or on the runner, where an attacker who controls Gitea can run a workflow that uses them. Signed tags from a hardware key would break "every green merge deploys". Flux image automation would need git write credentials in the cluster.
|
||||
- **Kyverno (or sigstore policy-controller) for admission.** Rejected for two rules. It adds a controller, a webhook that can fail open or closed, and more upgrades to keep up with. Revisit when signing returns.
|
||||
- **Moving `monitoring` to `privileged` as a whole.** Rejected in favour of isolating the node agents in their own namespace.
|
||||
- **Keeping ops reminders out of hAPI** (a personal calendar), since hAPI can't remind you to fix hAPI while it's down. Rejected: these are recurring upkeep, which is what Maintenance Tasks are for, and Kuma covers the outage case. The glossary's Maintenance now includes the Household's digital systems.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **NetworkPolicy:** every namespace we own (`hapi`, `bots`, `gateway`, `envoy-gateway-system`, `monitoring`, `monitoring-node`, `cert-manager`, `flux-system`) is default-deny for ingress and egress. Each component's allows sit next to its manifests in `deploy/`. Rules that name hosts are `CiliumNetworkPolicy`, using `toFQDNs` for ntfy, Linode Object Storage, the Linode API, SimpleFIN, Kuma and Let's Encrypt, and `toCIDR` for the Managed DB's VPC address. This includes the allows already promised by ADR-0009, ADR-0011, ADR-0013 and ADR-0014. `kube-system` (Cilium, CCM and CoreDNS, installed by Tofu) stays open.
|
||||
- **Pod Security:** the cluster default stays at Talos's `baseline`. Every namespace we own enforces `restricted`, except **`monitoring-node`**, which is `privileged` and holds only the Vector and node-exporter DaemonSets. This amends ADR-0009.
|
||||
- **Admission (ValidatingAdmissionPolicy, Deny from day one, delivered by Flux):**
|
||||
1. Images must come from Gitea's registry, or carry an `@sha256:` digest. Applies everywhere except `kube-system`.
|
||||
2. Pods in `hapi` and `bots` must set `readOnlyRootFilesystem: true` and `automountServiceAccountToken: false`.
|
||||
- **Audit logging:** the apiserver audit policy is set in Talos machine config at `Metadata` level. It keeps every write and every access to `secrets`, `pods/exec`, `pods/portforward` and `serviceaccounts/token`, and drops controllers' and Flux's reads, health endpoints and Events. Vector in `monitoring-node` ships the control-plane node's audit file to VictoriaLogs, where it's **kept 1 year** and included in ADR-0014's daily `audit/` export. A `pods/exec` or a Secret read by a human sends an alert to the ntfy `ops` topic. Dial the policy back if it's too noisy.
|
||||
- **Upgrades:** Talos, Kubernetes, Cilium and CCM versions are pinned in `infra/`. Renovate opens PRs for them and never auto-merges. Security patches go in within 14 days; minor versions after their `.1`, staying within upstream support. The procedure goes in `docs/runbooks/cluster-upgrade.md`, written during the build:
|
||||
1. Take a throwaway local `talosctl etcd snapshot`, never stored (ADR-0014's no-etcd-backups rule still holds).
|
||||
2. Upgrade and drain the workers one at a time.
|
||||
3. Upgrade the control plane, accepting a few minutes without the API.
|
||||
4. Run `talosctl health` and check that Flux reconciles.
|
||||
|
||||
The reminder is a monthly Household Maintenance Task, "Upgrade the cluster", on a **"hAPI cluster" Asset**. ADR-0014's "Rehearse disaster recovery" Task hangs off the same Asset.
|
||||
- **Supply chain in v1:** images stay digest-pinned (ADR-0007), admission rule 1 limits where images come from, CI's Trivy scan stays, and `main` has branch protection in Gitea. Revisit signing once CI has an identity a compromised Gitea can't use.
|
||||
- **Deferred to v2:** runtime detection (Tetragon/Falco), in-cluster vulnerability scanning (Trivy Operator), CIS scanning, the Cilium host firewall (the Linode Cloud Firewall already covers nodes), least-privilege kubeconfigs (the Owner keeps Talos's admin kubeconfig, used only over the tailnet), and any CI check of policy coverage. etcd secret encryption needs no decision: Talos enables it by default.
|
||||
Reference in new issue
Block a user