Compare commits

..
12 changed files with 19 additions and 725 deletions

View file

@ -29,4 +29,3 @@ resources:
- secret-forgejo-pg-app.sops.yaml - secret-forgejo-pg-app.sops.yaml
- secret-forgejo-runner-amd64-token.sops.yaml - secret-forgejo-runner-amd64-token.sops.yaml
- secret-forgejo-runner-deploy-arm64-token.sops.yaml - secret-forgejo-runner-deploy-arm64-token.sops.yaml
- secret-cluster-backup-ssh.sops.yaml

View file

@ -1,24 +0,0 @@
apiVersion: v1
data:
id_ed25519: ENC[AES256_GCM,data:amT/cj/RxpH62Bikn6MgHAZSud+3pzC80QgLFfbE7s83HPzndasB6HHG5FCjuhcU47IkyYwtpZXGa5BkAT5Ohidei6dV9+AbdLuTMer1UbIiPt5WQ6oUFysfTQrmwShbLH8imTr7j/xZ1/0gNpVrXGWjM4udKFqPoACR52JQsGSdH6dNleRyeZhxWmIiqwG5iFY8kJL4ARzTsjZNGCGVLalZFE+QKxiiQo+FTpjNMit+FNub4S8Q6lmHDHC5+gCLSOpJs+V1Jeijp7HCKQEzqgFzt3Gfj/HRHmmqQNHqB0OoP8+pJJ8dWxroHMf3zQv0DHj23Uer3zVpECzL3WInzLvGFq/E5CRbmDgPPaQJLTgy0YYdTwugBR6nf5PfjtJzeXV+EkoaNLsoywCdRwJ2HiT1B5dqZ0TsWu4WnyQzGev8fnfFsQcLxPTUcdhLKwqpFc0esScSPniRHgexR2A2HZqSQkpL5j2eAB/Hmsv9/632fd8iySliSISvwXb0Wv2T5BD5kQPMVqeWK6nmRWQeh2tI+IZbWUPSb6vSKgqQDNgtbL2m2uGV1rEMMdYONZrqzqPPwSWIK2QDoa2IhL50EvtQBk7/lFhVyYD/+k2zNc1jpptV/PTkWd3x4TMki/rVWBDIr87xkCMnAcx0+epMI9y07PpiEPO1OhG6GMNvDSO0B6UpN++RzouO2jgK649Kwk1Qsng9/jva4IasRxXon0biw4fxlKaWZR+pZyNmaSk=,iv:8sYhy8yMT59au1yHGhsfXFS9O4VXbYUMp6DNAjnUL+c=,tag:auvDjZ4Q+qVPNsGhHLkBYg==,type:str]
known_hosts: ENC[AES256_GCM,data:UHGQnYI70Gu3hEhwQKeilrvqNpQcrHyQHSO1Z079Ono6FzGR2yy+0vTBjvu8Jv9jiJKpBvs8INjXgN4RmBsOquuUsTt44Z6efVLZVlU8EsX/w7VIYdovFO5N43opOgeojhMZYb6BpdxF7oA7+VuG/J/AMHjAY2qKd/lESQ==,iv:KE/Nr2RiWFeS+jD289z07JHLxdSI6zqThrFkkmPJQEU=,tag:le8FwTGLY72La1/fiTeQJA==,type:str]
kind: Secret
metadata:
name: cluster-backup-ssh
namespace: forgejo
type: Opaque
sops:
age:
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBENlJFaTFnbkJkMWdkSTdz
Rm03VFo2OG52NFQzRkZpa1ZNNHRiY1kva2dFCm01Vmc0YlFyRGZBUDMweTZrVzNH
YTJjY2YrTHV1VFNXSEM4b1hHcFFkSUUKLS0tIGdNOExKc3BldmFtYmpNcVNqTzk1
VTM3ZEgyK1k0YldmejRERWVhK1BrakEKJQP4I7pCfLn5BYEwEb4I9K1fpYnKL4w+
Jf3c1c+qNaaet9nDrP2WW1L6rug+K6iAkR1H6ywHVKH7Ue1Ft5T/Lw==
-----END AGE ENCRYPTED FILE-----
recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp
encrypted_regex: ^(data|stringData)$
lastmodified: "2026-11-27T05:29:49Z"
mac: ENC[AES256_GCM,data:2RqTlxczkP9OHpqmjwdkOM3Ha68tIfvCnLOl/A2pqERR2bkxnWP87vVCKs3pZBZffQCU8NuK27yzBPSCHAPl4GUgt7QaUFHdHgsrbXIbDw1ZJ8ZVNLeIg2kLkJognhA1VOZZgL1oEKR+djBrqFJvHUWQfbkLrtoW5Rch/Qv+eDA=,iv:03IgpSHCqJuhFCykSjdqQhmoZfk6JNm4TxQtrtMY23E=,tag:Ln9PynG0Jll+0ZHC6D6l/w==,type:str]
version: 3.13.3

View file

@ -38,4 +38,3 @@ resources:
- secret-sirius-growth-portal-app.sops.yaml - secret-sirius-growth-portal-app.sops.yaml
- secret-sirius-growth-portal-db.sops.yaml - secret-sirius-growth-portal-db.sops.yaml
- secret-sirius-growth-portal-s3.sops.yaml - secret-sirius-growth-portal-s3.sops.yaml
- secret-cluster-backup-ssh.sops.yaml

View file

@ -1,24 +0,0 @@
apiVersion: v1
data:
id_ed25519: ENC[AES256_GCM,data:WZ7KnBoV/semXMuMjKQ5AnuzKbJpbSHLjfsayHBvV9Q2IqL9N2/SmlaoZ3vdf/By2Yy2ayOFI/8/MkebY2vSuhGMtJaN3T4A3LEOCMSLfH0VcAQyfzInqLgF7rNPm+7C+FYSGAA5o2fqXwHzz5AlhNme7xYf4NK1hrnXen1T56uBm/dfXfvs2sJUaEuVq8XKQdnfkkWgXxDbk5SZlGJm/Aa0PpCDxHfoL1lAD6MOpgqKPWi6GDLTl1esiq/EqxUhpjoZo5NTnmaYX6IdaoPscrpvC5E4aGiYkihUsgyjkszLg1LjrsMZBLi0pwd1OWC7isRS2B+LOqetkXvCGtxg+0aaWmIBpZS4Y+G/lHK/WSY/QQsfynPwll5L9RtZtp022eeuLa/lnXyIrQQQLZNmzk7RVW+66twAXcymmV8HQRIdAGku4ZtJL3zEpH2yelN/TWi1bo7/+dtnElaa5bb29BrvP03Rb2GA5mNPtIhItgNOYCknkoXIWCVZ85x+60Ah+xa6R/HXRXRR5/D4+so5nDq2ISmZiq0FD7DEumU+WgvL0GyLsNkqRMl7BCGLeOzIuAO9lNuI/TZDcyOyS3eB0LIQNwdNU0FInJwJ4jp0yR3Cxd14hVATcjCU62zNQTmBHfXgAHLe1XUiUbs/ZxFcx5c36snRNot/jugwjMt0UDqgbwn2xqOvJxJT0hPYhf4u9SPH4VTLAbEE7DrwzNoPyb1I39wPeSLsPxBf4Or0cVw=,iv:oRzm1lCz7DDwF5616Hf+rRblPWJEc4ErHmoXLNvxoXQ=,tag:85h7JyO5wNUA89xIs5Pf1g==,type:str]
known_hosts: ENC[AES256_GCM,data:WAC8hq7IuinfG17Rhmr/F/bYZvviOkQwYpaAMdWnwNG7DrhehlN6x0HDCyVbuBWVMqTW4zva2K3tzWsZ8Ivv/xln8AsjSX3P31SWz6b38pyMPiYZ8lVtz449f84rftnb1KgIeYiTjv/5L5z4+Q/J2TR8UYLSwsi/K0G1Fw==,iv:MT20OcwHEA9zXPoloGaW8tGdbS7Kr+HrHMyk2UWByAY=,tag:s69nJ538DSqs/fTR5hgLtQ==,type:str]
kind: Secret
metadata:
name: cluster-backup-ssh
namespace: sirius-growth
type: Opaque
sops:
age:
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSB5ZC9CdER5b1ZXUDNISTF1
VGllTmhDeHk5RUFkREd1UGM1bi9LRGxCNEFZCllSaS9ZOUtsU2N6TWlhemM1aXpS
elErcTE3K0ExYlVIYTBPczdnM2xuOG8KLS0tIDVDVm44UXhEYU84dktNK2I4L04x
VG1sdTVZVHZuWiswb3ljSWtoWWRDWjgKbUhCAclaS7Im9aqeX79VY/ZcJk/7oR6+
z1TgPZbgJNjAeiKJIztQJrZLHwpqIB6kEYddof/tjlKk6i/epZ2ZGw==
-----END AGE ENCRYPTED FILE-----
recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp
encrypted_regex: ^(data|stringData)$
lastmodified: "2026-11-27T05:29:49Z"
mac: ENC[AES256_GCM,data:1tTFNdkgjFiROm0XRqhmedhBqTolSc8oOCTW/QTmv20THC8XrRAt4gYbR3B6fFfzAcyp5I15/OtpPhopfma4VOGrXbShbHxbgKvaAcDWQWh/npwN2pbJJlIldyk0rWYEbRoAlzbDoq2TRfnqL5ejd67XkFQPsOhiWMhWlqfMzv4=,iv:T2rpa4hweAhPnBiUgw+xg2CGXkl2HoGCLGZ5pPSYJGk=,tag:FDat9gyykBOXJ2x2So1dyw==,type:str]
version: 3.13.3

View file

@ -12,11 +12,5 @@ spec:
name: flux-system name: flux-system
path: ./monitoring/controllers/home path: ./monitoring/controllers/home
prune: true prune: true
# Grafana's admin/secret-key, the Alertmanager Telegram bot token and the
# backup SSH key are committed as SOPS/age ciphertext (secret-*.sops.yaml).
decryption:
provider: sops
secretRef:
name: sops-age
dependsOn: dependsOn:
- name: infrastructure - name: infrastructure

View file

@ -1,176 +0,0 @@
# Hubble event loss: why the counter was climbing and the gate on it
Finding **F10** of the [2026-11-27 cluster network-security audit](2026-11-27-cluster-netsec-audit.md).
Written up here because the number looked like data loss and was not, and because the
detector contract that came out of it outlives this particular fix.
## What was observed
```
$ promq 'sum by (node,source) (rate(hubble_lost_events_total[30m]))'
0.0966 node=linode source=hubble_ring_buffer
0.6821 node=siriussec source=hubble_ring_buffer
0.0050 node=rpi source=hubble_ring_buffer
$ promq 'sum by (node) (hubble_lost_events_total)'
23787 linode / 72529 siriussec / 156 rpi (2026-11-27T05:16Z)
```
`source` was always `hubble_ring_buffer`; `perf_event_ring_buffer` and
`observer_events_queue` were 0 on all three nodes the whole time, i.e. the BPF
perf ring (the only place events can genuinely be lost on the way in) never
dropped anything, and the metrics exporter never fell behind.
## Root cause — a measurement artefact, not dropped flows
`Ring.read()` (`pkg/hubble/container/ring.go`) synthesises a
`LostEvent{source: HUBBLE_RING_BUFFER}` **and increments the metric** whenever a
read falls outside the valid window — including the "reader behind writer" case
at the ring's read boundary. `getFlowRate()` (`pkg/hubble/observer/local_observer.go`)
walks the ring *backwards* over a full minute on every `ServerStatus` call, and
`ServerStatus` is called by:
* the agent's own hubble health probe, every **5 s** (12/min, constantly),
* every `hubble status` (including the one in `cilium-dbg status` and the Hubble UI's status panel),
* every UI/relay status request.
When the ring holds **less than one minute of flows**, that walk hits the
boundary, so each probe adds exactly 1 to the loss counter. Cilium's own tracker
is cilium#46584 (`hubble_ring_buffer` lost metric increments even when no events
are actually lost); upstream fixed it by counting only on forward reads, which
is not in the 1.20.1 build deployed here.
Measured proof on this cluster (2026-11-27T05:13Z):
| node | ring | flows/s | 10 back-to-back `hubble status` | +21 s idle |
|---|---|---|---|---|
| siriussec | 4095 (100 %) | ~80 | **+11** | +12 |
| linode | 4095 (100 %) | ~20 | **0** (40 calls) | 0 |
siriussec's ring held ~51 s at 80 flows/s → every probe hit the boundary.
linode's held ~200 s → the walk stopped on the timestamp check and nothing was
counted. That is the whole of the "0.68/s" on siriussec and the bursty ~4/min on
linode (during linode's ingest bursts the ring briefly held <60 s).
The cumulative 72,529 was therefore the counter counting reads, not losses.
No flow was actually dropped: with no client attached the ring only has to hold
history, and `Ring.Write()` never discards — it overwrites, and loss is only
ever reported at read time.
## The change
`infrastructure/networking/cilium/values.yaml` (Flux → HelmRelease `kube-system/cilium`):
```yaml
hubble:
eventBufferCapacity: "16383" # was the chart default, 4095
```
The ring must hold **>= 60 s at peak** so the backward walk exits on the
timestamp check instead of the boundary. 24 h peak flow rates measured in
Prometheus (`max_over_time(sum by (node)(rate(hubble_flows_processed_total[1m]))[24h:1m])`):
| node | 24 h peak flows/s | 16383 events = | 4095 events = |
|---|---|---|---|
| linode | 195.8 | 84 s | 21 s |
| siriussec | 101.5 | 161 s | 40 s |
| rpi | 38.4 | 427 s | 107 s |
16383 is the smallest ring that covers the 60 s walk on **every** node: at
linode's peak 8191 would hold 41 s (still under a minute, still hitting the
boundary), 16383 holds 84 s. 32767 is the next allowed step and doubles the
memory for headroom the 24 h peak does not justify. The ring only accepts
`2^n - 1` (1, 3, 7 … 4095, 8191, 16383, 32767, 65535).
### Memory cost per node (measured, not assumed)
The ring stores `*v1.Event` pointers and keeps the events themselves alive; the
delta is bounded by `(16383 - 4095) × retained bytes per event`. Measured with
`container_memory_working_set_bytes{pod=~"cilium-.*",container="cilium-agent"}`
(average of the last 30 min before the roll vs the same 30 min after, all three
agents restarted onto the new config):
| node | before (4095) | after (16383) | delta |
|---|---|---|---|
| siriussec | 330.2 MiB | 300.6 MiB | -29.6 MiB |
| linode | 309.1 MiB | 240.2 MiB | -68.9 MiB |
| rpi | 194.5 MiB | 222.6 MiB | +28.1 MiB |
The deltas are dominated by restarting a month-old process (the old agents had
31 d of uptime and allocation growth); the ring itself is in the low single-digit
MiB at this event size. The honest statement is: **no measurable growth above
the restart noise; the largest observed node cost is +28 MiB on the Pi, and
linode (the tightest node, ~2 GiB available) went down.** Rejected alternative:
raising the capacity to 65535 to be safe is 4x this for no measured need.
### Rollout
Config-only change: the chart does not put a configmap checksum on the
DaemonSet pod template, so the Helm upgrade updated `cilium-config` without
rolling the agents. The agents were restarted **one node at a time** (rpi →
linode → siriussec), each with the datapath checked before moving on:
* `hubble status` → `Current/Max Flows: … /16,383`
* pod↔pod across the mesh: linode → `forgejo.forgejo.svc:3000`, siriussec →
`osint-nats.osint.svc:8222`, rpi host → `10.10.0.2:8080` (gateway origin)
* linode pod → internet (masquerade) `https://data.gdeltproject.org/...`
* all three nodes `Ready`, `cilium` DaemonSet 3/3
Rollback: set `eventBufferCapacity` back to the default (delete the key) and
restart the agents, the same way. Nothing else changed — L7 is still on
(`enable-l7-proxy=true`), `hubble-metrics` still carries `flow`, no retention
change.
## The gate (this is the durable part)
A deeper ring removes *this* artefact. It does not make the stream
unconditionally complete — a genuinely overloaded agent, or a Hubble client that
cannot keep up with a follow stream, still loses events, and that failure is
silent. So the sensor contract is:
> **A 30-minute window with any lost event may not be reported as clean.**
Threshold and enforcement:
| rule | expression | meaning |
|---|---|---|
| `hubble:lost_events_increase_30m` (recorder) | `sum by (node) (increase(hubble_lost_events_total{source="hubble_ring_buffer"}[30m]))` | the gate value: any non-zero → window incomplete |
| `hubble:flows_processed_increase_30m` (recorder) | `sum by (node) (increase(hubble_flows_processed_total{type="Trace"}[30m]))` | denominator for the ratio |
| `HubbleFlowWindowIncomplete` (warning) | `hubble:lost_events_increase_30m > 0` for 10 m | a flow-shaped detector may not call this window clean |
| `HubbleFlowLossMaterial` (critical) | `lost / processed > 0.001` for 15 m | loss that is material, not a boundary artefact |
| `HubbleFlowSensorMissing` (critical) | `absent(hubble:flows_processed_increase_30m)` for 15 m | no input at all; the gate cannot even be evaluated |
All four live in `monitoring/controllers/home/hubble-loss-gate.yaml`
(Flux → `monitoring` Kustomization), so they evaluate against the same
Prometheus the detectors read and route to Alertmanager.
**How a detector must use it:** evaluate the traffic window and the gate value
over the *same* range; if `hubble:lost_events_increase_30m > 0` for the node(s)
in scope, the result is `incomplete` — never "no anomalous traffic". Alerting on
silence (absence of an expected event) is the case that matters most: a lossy
window produces false silence, not false noise.
## Verification (live, 2026-11-27)
```
# counter stops climbing — identical value 8 minutes apart, on all three nodes
$ promq 'sum by (node) (hubble_lost_events_total{source="hubble_ring_buffer"})'
31 rpi / 31 linode / 30 siriussec (05:20:50Z)
31 rpi / 31 linode / 30 siriussec (05:23:50Z)
# the artefact is gone: 20 status calls + 20 s idle move nothing
siriussec before: 30 after 20 status: 30 after +20s idle: 30
# 30 min window after the last restart (acceptance 1): see the kanban card,
# hubble:lost_events_increase_30m = 0 on all three nodes
# flows still flow, L7 still on
$ hubble observe --last 3 # each of the three agents returns flows, incl. http-request
# scrape targets
hubble-metrics 10.10.0.1:9965 up / 10.10.0.2:9965 up / 10.10.0.5:9965 up
```
The ~30 events on the counter after each restart are the ring's own cold-start:
while the ring is still filling, a backward walk passes nil slots and each one
counts. It is a one-off per agent start, not a rate, and it ages out of the
30-minute window.

View file

@ -1,157 +0,0 @@
# kube-apiserver audit logging (control-plane, host-applied)
Status: **live and verified 2026-11-27** on `siriussec` (kubeadm v1.36.4, single control plane).
Owner: devops. Finding: F1 of the 2026-11-27 cluster network-security audit.
## Why
The apiserver ran with **no audit configuration at all**. Every privileged-but-authorized API
call — reading a Secret, `pods/exec`, RBAC writes, ServiceAccount token minting — completed with
no record anywhere on the cluster. That is the gap that makes every other detector partially
blind: there is nothing to alert on, nothing to reconstruct after an incident, and no way to
answer "who read `forgejo-pg-app` last Tuesday".
## What is installed
| Piece | Path / value |
|---|---|
| Audit policy | `/etc/kubernetes/audit/audit-policy.yaml` (0600 root, in this repo) |
| Audit log | `/var/log/kubernetes/audit/audit.log` (0600 root, JSON, one event per line) |
| Static pod patch | `/etc/kubernetes/manifests/kube-apiserver.yaml` (kubeadm-owned — see Drift) |
| Staged volumes | `hostPath /etc/kubernetes/audit` (ro) and `hostPath /var/log/kubernetes/audit` |
Apiserver flags added (verified in the live container's `/proc/<pid>/cmdline`, not just the pod object):
```
--audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml
--audit-log-path=/var/log/kubernetes/audit/audit.log
--audit-log-format=json
--audit-log-maxsize=100 # MiB per file, then rotate
--audit-log-maxbackup=48 # hard cap: 4.8 GiB raw before compression
--audit-log-maxage=7 # days
--audit-log-compress # rotated files are gzipped
```
Rotation and retention are the apiserver's **own** (lumberjack) rotation, not logrotate. Do not add a
logrotate rule for this path: the apiserver holds the file descriptor, so an external rotate produces
a stale fd and silent loss.
## Policy design
`omitStages: [RequestReceived]` — one record per request instead of two (the completion record is the
one carrying `responseStatus`). `omitManagedFields: true` drops server-managed field blobs.
| # | Level | Scope | Rationale |
|---|---|---|---|
| 1 | None | `/healthz* /livez* /readyz* /version /openapi* /metrics`, GET | kubelet polls these every few seconds per node |
| 2 | None | `coordination.k8s.io/leases`, `events` | leader election / heartbeat / event spam |
| 3 | None | `watch` on pods, nodes, services, endpoints, configmaps, PV/PVC, endpointslices, ingresses, netpols, CRDs, storageclasses | a watch is recorded once at subscribe time and its payload never enters the record. **secrets/RBAC/certs are deliberately not listed** — a watch on those is itself worth a record |
| 4 | Metadata | `secrets` **list, watch** | corpus dumps only, see below |
| 5 | Request | `rbac.authorization.k8s.io/*`, `certificates.k8s.io/*` **list, watch** | whole-object listings; the write paths stay at rule 6 |
| 6 | **RequestResponse** | `secrets` (every verb except list/watch), `serviceaccounts/token`, `pods/exec`, `pods/attach`, `pods/portforward`, `rbac.authorization.k8s.io/*`, `certificates.k8s.io/*`, verb `impersonate` | the privileged-but-authorized calls: full request+response bodies |
| 7 | Request | `pods/proxy`, `nodes/proxy`, `nodes/log`, `nodes/metrics`, `nodes/spec`, `nodes/stats` | who proxied to which kubelet; the multi-MB response body is volume, not evidence |
| 8 | Metadata | everything else | who / what / when / from where / status code |
### Why `list`/`watch` on secrets is Metadata and not RequestResponse
The first cut logged full bodies for every secret verb. During a flux reconcile storm (which happens
after every apiserver restart and every full reconcile) that measured **22.8 GB/day**, i.e. it would
have rotated the entire retention window every couple of hours and buried the useful records:
| verb | events/189 s | avg event | burst rate |
|---|---|---|---|
| `list secrets` | 16 | **1.9 MiB** (every secret in the namespace) | 14 GB/day |
| `update secrets` | 90 | 170 KiB (flux `sh.helm.release.v1.*` + prometheus-operator `tls-assets`) | 7 GB/day |
| `get secrets` | 151 | 6.8 KiB | 1 GB/day |
A `list` body is a corpus dump scaled by how many secrets the cluster holds — it grows with the
cluster, and the security signal ("who enumerated every secret") is fully captured by the metadata.
That verb pair (`list`, `watch`) is therefore Metadata. **Every other secret verb keeps full
request/response bodies**, including writes, so "who rewrote this secret and to what" is
reconstructable.
Steady state with this split is **0.79 GB/day, ~420 events/min** (secret traffic ~0.25 GB/day); the
storm burst is bounded and absorbed by rotation. Retention numbers below account for it.
## Sensitivity: the audit log is secret material
At `RequestResponse`, a `get secret` audit event contains the secret's `data` in `responseObject`.
`/var/log/kubernetes/audit/` is therefore `0700 root` and the log `0600 root`, on the control-plane
node only. Treat any future log shipper as a **secrets pipeline**: no unauthenticated sink, no
plaintext off-node copy, and its own encryption/retention story. Nothing ships this log today.
## Verify it is live
```bash
# 1. flags are in the running container (authoritative: the live process, not the pod object)
CID=$(sudo crictl ps -q --name kube-apiserver | head -1)
PID=$(sudo crictl inspect "$CID" | python3 -c 'import json,sys;print(json.load(sys.stdin)["info"]["pid"])')
sudo tr '\0' '\n' < "/proc/$PID/cmdline" | grep -- --audit-
# (the mirror pod also carries them, but it can lag the container by a few seconds)
kubectl -n kube-system get pod kube-apiserver-siriussec \
-o jsonpath='{.spec.containers[0].command}' | tr ',' '\n' | grep -- --audit-
# 2. the sink grows and the log is 0600
sudo ls -la /var/log/kubernetes/audit/
# 3. make a record and find it (name only — never print secret data)
kubectl -n forgejo get secret forgejo-pg-app -o name
sudo grep -c forgejo-pg-app /var/log/kubernetes/audit/audit.log
```
Live proof captured 2026-11-27T05:18Z (final policy):
```
secret 404 kubernetes-admin get forgejo/pg-superuser code 404 RequestResponse (the audit card's literal command; the secret is named forgejo-pg-app)
secret get kubernetes-admin get forgejo/forgejo-pg-app code 200 request+response (responseObject carries .data)
rbac write kubernetes-admin create forgejo/audit-trail-probe (dryRun=All) code 201 RequestResponse
pods/exec kubernetes-admin get forgejo/<pod>/exec code 101 full command line ResponseStarted + ResponseComplete
```
`pods/exec` produces two records per session (`ResponseStarted`, `ResponseComplete`) — the first is
what makes an interactive session visible while it is still running. Write-path fidelity re-checked
after the final policy revision: `create secret` (server dry-run) records `requestObject.data`.
## Drift: a `kubeadm upgrade` silently resets this
`/etc/kubernetes/manifests/kube-apiserver.yaml` is generated by kubeadm, and **Flux does not
reconcile it**. `kubeadm init`, `kubeadm upgrade apply` and a control-plane re-init regenerate the
file from kubeadm's template and drop every `--audit-*` flag and both mounts. The failure is silent:
the API keeps serving, `/var/log/kubernetes/audit` just stops growing.
Recover with the installer in this directory (also staged on the node at `/root/audit-recovery/`):
```bash
sudo infrastructure/controlplane/audit/install-audit.sh --check # exit 1 = drift
sudo infrastructure/controlplane/audit/install-audit.sh # policy + manifest patch
```
The installer is idempotent and was verified to reproduce the live manifest byte-for-byte; a second
run is a no-op. Patching the manifest makes kubelet restart the apiserver (~40 s of API downtime on a
single-control-plane cluster).
Other drift triggers: moving the API/advertise address (a rewrite of the same manifest),
`kubeadm reset` + re-init.
## Rollback
```bash
sudo cp -a /root/kube-apiserver.yaml.bak-<stamp> /root/.kube-apiserver.rollback
sudo mv /root/.kube-apiserver.rollback /etc/kubernetes/manifests/kube-apiserver.yaml
```
Dropping the flags stops the audit backend; the policy file and log directory can stay (inert).
Never edit the manifest in place with a non-atomic write: kubelet parses the directory, so a torn
file makes it remove the static pod and take the API down.
## Disk headroom
`siriussec` had 102 GiB free of 214 GiB when this landed. Retention is bounded at
`48 × 100 MiB = 4.8 GiB` raw before compression, which at the measured 0.79 GB/day is **~6 days of
history**; realistic on-disk after gzip is several hundred MB. The ≥32 GiB floor is never at risk.
## Not covered here
- No shipping/alerting on audit events (no log store yet) — separate work.
- No kubelet-level audit (`--audit-*` on kubelet), pods' `auditPolicy`, or OPA/admission policy.
- Audit records for `list secrets` are metadata-only by design (see above).

View file

@ -57,9 +57,6 @@ for **rotating** the token.
### Rotate it ### Rotate it
The SOPS file is the source of truth — a `kubectl apply` of a new Secret is reverted by the next
`apps` reconcile, so rotate in git:
```bash ```bash
# 1. token (mint a fresh one; never echo it) # 1. token (mint a fresh one; never echo it)
kubectl -n forgejo exec deploy/forgejo -- su-exec git forgejo admin user generate-access-token \ kubectl -n forgejo exec deploy/forgejo -- su-exec git forgejo admin user generate-access-token \
@ -68,7 +65,7 @@ kubectl -n forgejo exec deploy/forgejo -- su-exec git forgejo admin user generat
# then the command above; the password is only needed for interactive login and is # then the command above; the password is only needed for interactive login and is
# never used by containerd.) # never used by containerd.)
# 2. rewrite the encrypted value in every namespace's file (no plaintext ever hits disk) # 2. build the dockerconfigjson without printing it
umask 077 umask 077
read -r -s -p 'token: ' RT; echo read -r -s -p 'token: ' RT; echo
python3 - "$RT" > /tmp/dc.json <<'PY' python3 - "$RT" > /tmp/dc.json <<'PY'
@ -78,33 +75,21 @@ print(json.dumps({"auths": {"forgejo.siriusdevops.com": {
"username": "registry-reader", "password": t, "username": "registry-reader", "password": t,
"auth": base64.b64encode(f"registry-reader:{t}".encode()).decode()}}})) "auth": base64.b64encode(f"registry-reader:{t}".encode()).decode()}}}))
PY PY
# 3. one Secret per namespace
for ns in osint piedmont sirius-growth siriusdevops; do for ns in osint piedmont sirius-growth siriusdevops; do
f=apps/base/$ns/secret-forgejo-pull.sops.yaml kubectl create secret generic forgejo-pull -n "$ns" \
sops decrypt --output-type json "$f" \ --type=kubernetes.io/dockerconfigjson --from-file=.dockerconfigjson=/tmp/dc.json \
| jq --rawfile dc /tmp/dc.json '.data[".dockerconfigjson"] = ($dc | rtrimstr("\n") | @base64)' \ --dry-run=client -o yaml | kubectl apply -f -
| sops encrypt --filename-override "$f" --input-type json --output-type yaml /dev/stdin > /tmp/new.yaml \
&& mv /tmp/new.yaml "$f"
done done
shred -u /tmp/dc.json shred -u /tmp/dc.json
git commit -am 'registry(auth): rotate the pull token' && git push && # then PR + merge + reconcile
``` ```
The consumer picks the new value up on its **next pull** — the Secret is read per pull, so no pod
restart is needed. Delete the old token in Forgejo afterwards (`profile → Applications`).
The `registry-reader` token is minted without `--expires-at`, i.e. non-expiring; rotating it is
therefore an explicit action, not something the clock forces.
### Add a namespace ### Add a namespace
Three edits, all in git: `kubectl create secret` as above **and** `imagePullSecrets: [{name: forgejo-pull}]` in the
pod spec (or on the namespace's ServiceAccount) — do not add the secret to workloads that do
1. copy an existing `secret-forgejo-pull.sops.yaml` into `apps/base/<ns>/` and point it at the not pull from this registry.
namespace (`sops` re-encrypts on save; `metadata.namespace` is not encrypted);
2. list it plus `secret-<other>.sops.yaml` in that app's `kustomization.yaml` (the "Secrets,
SOPS/age-encrypted in git" block);
3. `imagePullSecrets: [{name: forgejo-pull}]` in the pod spec (or on the namespace's
ServiceAccount) — do not add the secret to workloads that do not pull from this registry.
## Why not a node-level credential ## Why not a node-level credential

View file

@ -84,24 +84,17 @@ Ordering note: a Secret must exist before its consumer starts (CNPG `bootstrap.i
`imagePullSecrets`, env refs). Kustomize sorts `Secret` before `Deployment`/`Cluster`, and all `imagePullSecrets`, env refs). Kustomize sorts `Secret` before `Deployment`/`Cluster`, and all
of these live in the same app directory, so one reconcile creates both. of these live in the same app directory, so one reconcile creates both.
## Inventory — in git (35 Secrets, 8 namespaces) ## Inventory — in git (29 Secrets, 7 namespaces)
| Namespace | Secrets | | Namespace | Secrets |
|-----------|---------| |-----------|---------|
| `forgejo` | `forgejo-pg-app`, `forgejo-runner-amd64-token`, `forgejo-runner-deploy-arm64-token`, `cluster-backup-ssh` | | `forgejo` | `forgejo-pg-app`, `forgejo-runner-amd64-token`, `forgejo-runner-deploy-arm64-token` |
| `siriusdevops` | `siriusdevops-contact`, `garage-media-s3`, `forgejo-pull` | | `siriusdevops` | `siriusdevops-contact`, `garage-media-s3`, `forgejo-pull` |
| `piedmont` | `piedmont-contact`, `forgejo-pull` | | `piedmont` | `piedmont-contact`, `forgejo-pull` |
| `sirius-growth` | `sirius-growth-contact`, `sirius-growth-blog-app`, `sirius-growth-blog-s3`, `sirius-growth-portal-app`, `sirius-growth-portal-db`, `sirius-growth-portal-s3`, `portal-wal-s3`, `forgejo-pull`, `cluster-backup-ssh` | | `sirius-growth` | `sirius-growth-contact`, `sirius-growth-blog-app`, `sirius-growth-blog-s3`, `sirius-growth-portal-app`, `sirius-growth-portal-db`, `sirius-growth-portal-s3`, `portal-wal-s3`, `forgejo-pull` |
| `osint` | `osint-admin`, `osint-db`, `forgejo-pull` | | `osint` | `osint-admin`, `osint-db`, `forgejo-pull` |
| `metabase` | `pg-app`, `metabase-admin`, `metabase-data-source-creds` | | `metabase` | `pg-app`, `metabase-admin`, `metabase-data-source-creds` |
| `customer1` | `pg-app`, `pg-users`, `odoo-config`, `odoo-admin`, `metabase-admin`, `metabase-data-source-creds`, `metabase-secret-key` | | `customer1` | `pg-app`, `pg-users`, `odoo-config`, `odoo-admin`, `metabase-admin`, `metabase-data-source-creds`, `metabase-secret-key` |
| `monitoring` | `grafana-admin`, `grafana-secret-key`, `alertmanager-telegram`, `cluster-backup-ssh` |
`cluster-backup-ssh` is the same ed25519 key in three namespaces — a Secret cannot be
referenced across namespaces and each backup CronJob mounts its own namespace's copy, so there
are three files with identical plaintext (distinct ciphertext; age uses a random nonce).
Rotating it means updating all three.
`*-pg-app` / `pg-app` / `sirius-growth-portal-db` deserve a note: these look like CNPG output but `*-pg-app` / `pg-app` / `sirius-growth-portal-db` deserve a note: these look like CNPG output but
are **ours** — each Cluster's `bootstrap.initdb.secret.name` points at one of them, so CNPG reads are **ours** — each Cluster's `bootstrap.initdb.secret.name` points at one of them, so CNPG reads
@ -131,24 +124,12 @@ from starting, which is exactly what this card exists to prevent. It is a Forgej
| `kube-prometheus-stack-prometheus-token` | `monitoring` | `kubernetes.io/service-account-token`, minted by the token controller. | | `kube-prometheus-stack-prometheus-token` | `monitoring` | `kubernetes.io/service-account-token`, minted by the token controller. |
| `flux-system` | `flux-system` | Git credential created by `flux bootstrap`; it authenticates the very pull that would apply it (chicken-and-egg), and rotating it is a bootstrap operation. | | `flux-system` | `flux-system` | Git credential created by `flux bootstrap`; it authenticates the very pull that would apply it (chicken-and-egg), and rotating it is a bootstrap operation. |
Now covered (added after the drill in the section below proved the recovery path): Out of scope for this pass, tracked separately: `cluster-backup-ssh` (3 copies), `grafana-admin`,
`cluster-backup-ssh` (3 namespaces), `grafana-admin`, `grafana-secret-key`, `alertmanager-telegram`. `grafana-secret-key`, `alertmanager-telegram` live in `monitoring`/backup CronJobs and are being
migrated in a follow-up commit once the delete-and-reconcile drill below proved the path.
## Delete-and-reconcile drill (2026-11-27T05:29Z) ## Delete-and-reconcile drill (2026-11-27)
Target: `siriusdevops/siriusdevops-contact` (Telegram token for the contact form — losing it for
a couple of minutes degrades one form, breaks nothing else).
```
05:28:59Z pre: pod Ready, /health {"ok":true}, keys TG_CHAT,TG_TOKEN, data sha256 1f17a3ac…
05:29:03Z kubectl -n siriusdevops delete secret siriusdevops-contact
05:29:05Z recreated by Flux (~2s, forced reconcile) — same keys, same data sha256 1f17a3ac…
05:29:11Z kubectl rollout restart deploy/siriusdevops-contact (prove env resolves from the
recovered Secret, not pod memory)
05:29:23Z rollout complete; new pod Ready, env TG_CHAT/TG_TOKEN present, /health {"ok":true}
both via localhost:8090 and via svc DNS + ClusterIP
```
Same key names before and after, byte-identical data, Secret back in the `apps` Kustomization
inventory. Only key **names** are recorded here.
`siriusdevops/siriusdevops-contact` — deleted, Flux recreated it from git, values verified
identical to the pre-delete snapshot, contact API still serving `/health`. Evidence in the
kanban card for `t_46f03ecb` (key names only, never values).

View file

@ -1,129 +0,0 @@
apiVersion: audit.k8s.io/v1
kind: Policy
# One record per request instead of two (RequestReceived + ResponseComplete).
# The completion record carries responseStatus and is the forensic one.
omitStages:
- RequestReceived
# server-managed noise, never evidence
omitManagedFields: true
# Volume note (measured 2026-11-27 on this cluster): full bodies for EVERY secret
# verb peaked at 22.8 GB/day, driven almost entirely by `list secrets` (1.9 MiB per
# event: flux helm-controller enumerating every secret on each reconcile) during a
# reconcile storm. Only rule 2 gives up bodies, and only for list/watch, where the
# body is a corpus dump rather than evidence. Everything else - including secret
# writes - keeps full request/response. Measured steady state: ~2.2 GB/day total,
# ~0.25 GB/day of which is secret traffic; a reconcile storm adds a bounded burst
# that rotation absorbs.
rules:
# ---------------------------------------------------------------- 1. silence
# Liveness/version/discovery surface: polled by kubelet on every node every
# few seconds and carries no identity information.
- level: None
verbs: ["get"]
nonResourceURLs:
- /healthz
- /healthz/*
- /livez
- /livez/*
- /readyz
- /readyz/*
- /version
- /version/*
- /openapi/v2
- /openapi/v3
- /openapi/v3/*
- /metrics
# Leader election / heartbeat / event spam.
- level: None
resources:
- group: coordination.k8s.io
resources: ["leases"]
- group: ""
resources: ["events"]
- group: events.k8s.io
resources: ["events"]
# Informer watch subscriptions on high-volume, non-secret resources: recorded
# once at subscribe time and the payload never enters the record. secrets,
# RBAC and certificate objects are deliberately NOT here - a watch on those is
# itself worth a record (rules 4/6 keep it, minus the body).
- level: None
verbs: ["watch"]
resources:
- group: ""
resources: ["pods", "nodes", "services", "endpoints", "configmaps",
"persistentvolumes", "persistentvolumeclaims"]
- group: discovery.k8s.io
resources: ["endpointslices"]
- group: networking.k8s.io
resources: ["ingresses", "networkpolicies"]
- group: apiextensions.k8s.io
resources: ["customresourcedefinitions"]
- group: storage.k8s.io
resources: ["storageclasses"]
# ---------------------------- 2. secrets: bulk enumeration (corpus dumps only)
# A list returns EVERY secret in the namespace: measured 1.9 MiB per event, and a
# flux reconcile storm issues dozens. Identity + verb + namespace is the signal
# (mass enumeration); the body is just the corpus. Writes are NOT here - they stay
# at RequestResponse in rule 4, because "who rewrote this secret and to what" is
# evidence. Steady state with this split: ~0.25 GB/day of secret traffic.
- level: Metadata
verbs: ["list", "watch"]
resources:
- group: ""
resources: ["secrets"]
# ------------------- 3. RBAC / certs enumeration: identity + request, no response
# list/watch of roles & bindings returns whole objects; the write paths are what
# matter and rule 6 keeps those at RequestResponse.
- level: Request
verbs: ["list", "watch"]
resources:
- group: rbac.authorization.k8s.io
resources: ["*"]
- group: certificates.k8s.io
resources: ["*"]
# --------------------- 4. secrets: single-object read/write, full bodies
# THIS FILE IS SECRET MATERIAL from here on: get/read responses and
# create/patch requests carry live secret values. 0600 root, never shipped
# off-node over an unauthenticated path.
- level: RequestResponse
resources:
- group: ""
resources: ["secrets"]
# -------------------------------- 5. everything privileged-but-authorized
- level: RequestResponse
resources:
- group: ""
resources:
- serviceaccounts/token
- pods/exec
- pods/attach
- pods/portforward
# every verb + subresource: create/update/patch/bind/escalate of a
# ClusterRoleBinding is a cluster takeover, not a config change
- group: rbac.authorization.k8s.io
resources: ["*"]
# CSR approval signs new client certs against the cluster CA
- group: certificates.k8s.io
resources: ["*"]
# acting as another identity
- level: RequestResponse
verbs: ["impersonate"]
# Metadata + request body only: kubelet/API proxies can return multi-MB bodies
# (metrics, pprof, logs) and the response is the volume, not the evidence.
- level: Request
resources:
- group: ""
resources: ["pods/proxy", "nodes/proxy", "nodes/log", "nodes/metrics",
"nodes/spec", "nodes/stats"]
# ------------------------------------------------------------------ 6. default
# who / what / when / from where / status code - no bodies.
- level: Metadata

View file

@ -1,147 +0,0 @@
#!/usr/bin/env bash
# Enable kube-apiserver audit logging on a kubeadm control plane (host-side, NOT Flux).
#
# Why this script exists: /etc/kubernetes/manifests/kube-apiserver.yaml is owned by
# kubeadm, not by Flux. `kubeadm init`, `kubeadm upgrade apply` and a control-plane
# re-init all REGENERATE that file from kubeadm's own template, silently dropping every
# --audit-* flag and the two hostPath mounts added here. Audit logging then stops with
# no error anywhere: the API keeps serving, /var/log/kubernetes/audit just stops growing.
# Re-run this after any of those operations.
#
# sudo ./install-audit.sh # install policy + patch the static pod manifest
# sudo ./install-audit.sh --check # exit 0 only if policy + manifest are both applied
# sudo ./install-audit.sh --dry-run # show the diff, change nothing
#
# Idempotent: re-running on an already-patched manifest is a no-op.
# Patching the manifest makes kubelet restart the apiserver (~40 s of API downtime on a
# single-control-plane cluster). Back up the manifest first if you need a rollback:
# sudo cp -a /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak-$(date -u +%Y%m%dT%H%M%SZ)
set -euo pipefail
MANIFEST=${MANIFEST:-/etc/kubernetes/manifests/kube-apiserver.yaml}
AUDIT_DIR=${AUDIT_DIR:-/etc/kubernetes/audit}
LOG_DIR=${LOG_DIR:-/var/log/kubernetes/audit}
# staging dir for the atomic rename into the manifests dir; must be on the SAME fs as
# MANIFEST (both live on the root fs). NOT the manifests dir itself: kubelet would try
# to run a half-written second static pod.
STAGE_DIR=${STAGE_DIR:-/root}
POLICY_NAME=audit-policy.yaml
HERE=$(cd "$(dirname "$0")" && pwd)
MODE=install
for a in "$@"; do
case "$a" in
--check) MODE=check ;;
--dry-run) MODE=dryrun ;;
-h|--help) sed -n '2,20p' "$0"; exit 0 ;;
*) echo "unknown argument: $a" >&2; exit 2 ;;
esac
done
die() { echo "ERROR: $*" >&2; exit 1; }
[ -f "$HERE/$POLICY_NAME" ] || die "policy not found next to script: $HERE/$POLICY_NAME"
[ -f "$MANIFEST" ] || die "manifest not found: $MANIFEST"
patched=$(mktemp)
trap 'rm -f "$patched"' EXIT
# Insert the audit flags, the two volumeMounts and the two hostPath volumes into a
# kubeadm-shaped manifest. Text insertion (not a YAML round-trip) keeps the diff to the
# lines we own, so a later kubeadm manifest stays byte-comparable.
MANIFEST="$MANIFEST" OUT="$patched" python3 - <<'PY'
import os, sys
src, out = os.environ["MANIFEST"], os.environ["OUT"]
s = open(src).read()
FLAGS = """ - --audit-log-compress
- --audit-log-format=json
- --audit-log-maxage=7
- --audit-log-maxbackup=48
- --audit-log-maxsize=100
- --audit-log-path=/var/log/kubernetes/audit/audit.log
- --audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml
"""
MOUNTS = """ - mountPath: /etc/kubernetes/audit
name: audit-policy
readOnly: true
- mountPath: /var/log/kubernetes/audit
name: audit-log
"""
VOLS = """ - hostPath:
path: /etc/kubernetes/audit
type: DirectoryOrCreate
name: audit-policy
- hostPath:
path: /var/log/kubernetes/audit
type: DirectoryOrCreate
name: audit-log
"""
if "--audit-policy-file=" in s:
open(out, "w").write(s)
sys.exit(0)
anchor = None
for cand in (" - --allow-privileged=true\n", " - kube-apiserver\n"):
if s.count(cand) == 1:
anchor = cand
break
if anchor is None:
sys.exit("cannot find a safe anchor for the audit flags")
s = s.replace(anchor, anchor + FLAGS, 1)
i = s.find(" volumeMounts:\n")
if i < 0:
sys.exit("no container volumeMounts block in manifest")
i += len(" volumeMounts:\n")
s = s[:i] + MOUNTS + s[i:]
k = s.find("\n volumes:\n")
if k < 0:
sys.exit("no spec.volumes block in manifest")
k += len("\n volumes:\n")
s = s[:k] + VOLS + s[k:]
open(out, "w").write(s)
PY
manifest_ok=0
cmp -s "$MANIFEST" "$patched" && manifest_ok=1
case "$MODE" in
check)
[ "$manifest_ok" = 1 ] || { echo "DRIFT: $MANIFEST has no audit flags/mounts (kubeadm upgrade? re-run ./install-audit.sh)"; exit 1; }
cmp -s "$HERE/$POLICY_NAME" "$AUDIT_DIR/$POLICY_NAME" || { echo "DRIFT: $AUDIT_DIR/$POLICY_NAME differs from $HERE/$POLICY_NAME"; exit 1; }
[ -d "$LOG_DIR" ] || { echo "DRIFT: $LOG_DIR missing"; exit 1; }
echo "OK: audit policy installed and manifest patched"
;;
dryrun)
if [ "$manifest_ok" = 1 ]; then
echo "manifest already patched, nothing to do"
else
diff -u "$MANIFEST" "$patched" || true
fi
cmp -s "$HERE/$POLICY_NAME" "$AUDIT_DIR/$POLICY_NAME" || echo "policy would be (re)installed to $AUDIT_DIR/$POLICY_NAME"
;;
install)
install -d -m 700 "$AUDIT_DIR" "$LOG_DIR"
install -m 600 "$HERE/$POLICY_NAME" "$AUDIT_DIR/.$POLICY_NAME.new"
if cmp -s "$AUDIT_DIR/.$POLICY_NAME.new" "$AUDIT_DIR/$POLICY_NAME"; then
rm -f "$AUDIT_DIR/.$POLICY_NAME.new"
echo "policy unchanged: $AUDIT_DIR/$POLICY_NAME"
else
mv "$AUDIT_DIR/.$POLICY_NAME.new" "$AUDIT_DIR/$POLICY_NAME" # same fs => atomic
echo "policy installed: $AUDIT_DIR/$POLICY_NAME (takes effect on the next apiserver start)"
fi
if [ "$manifest_ok" = 1 ]; then
echo "manifest already patched, nothing to do"
else
install -m 600 "$patched" "$STAGE_DIR/kube-apiserver.yaml.staged"
mv "$STAGE_DIR/kube-apiserver.yaml.staged" "$MANIFEST" # same fs => atomic rename, kubelet never sees a torn file
echo "manifest patched; kubelet restarts kube-apiserver within ~20 s"
fi
;;
esac

View file

@ -14,13 +14,6 @@ resources:
# Nightly consistent sqlite snapshot of Grafana's dashboards/alerts/users. # Nightly consistent sqlite snapshot of Grafana's dashboards/alerts/users.
- grafana-backup.yaml - grafana-backup.yaml
- dashboards - dashboards
# Secrets, SOPS/age-encrypted in git (decrypted by the `monitoring`
# Kustomization; key = flux-system/sops-age). See docs/secrets-sops.md.
- secret-grafana-admin.sops.yaml
- secret-grafana-secret-key.sops.yaml
- secret-alertmanager-telegram.sops.yaml
- secret-cluster-backup-ssh.sops.yaml
configMapGenerator: configMapGenerator:
- name: kube-prometheus-stack-values - name: kube-prometheus-stack-values
files: files: