diff --git a/.forgejo/workflows/backup-image.yml b/.forgejo/workflows/backup-image.yml deleted file mode 100644 index 6be2909..0000000 --- a/.forgejo/workflows/backup-image.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: backup-image -# Builds the backup tooling image used by the three nightly CronJobs -# (monitoring/grafana-backup, forgejo/cluster-backup, sirius-growth/leadgen-backup). -# -# Why this is a CI build at all (card t_9d0428d8): the jobs used to run -# `apk add rsync openssh-client` at container start, so the backup depended on -# the Alpine CDN at run time. Everything is baked here instead, from a base -# image pinned by digest, and the manifests pin the resulting image by digest. -# -# CI has no cluster credentials: this job only pushes an immutable :$sha tag to -# the in-cluster Forgejo registry and prints the digest to pin. The operator -# copies that digest into the three CronJob manifests in this same repo. -# -# amd64 only, on purpose: all three Jobs are nodeSelector'd to siriussec and -# the baked kubectl release checksum is amd64. Nothing here runs on rpi. - -on: - push: - branches: [master] - paths: - - 'images/backup/**' - - '.forgejo/workflows/backup-image.yml' - workflow_dispatch: - -jobs: - build: - runs-on: docker-amd64 - steps: - - uses: actions/checkout@v4 - - # The job image (node:20-bullseye) has no docker CLI of its own; the - # runner mounts the dind sidecar's client and cli-plugins. Verify both - # instead of assuming, and fail loudly rather than half-pushing. - - name: Verify docker CLI + buildx - run: | - set -euo pipefail - command -v docker - docker version - docker buildx version - - - name: Build and push (amd64, no attestation manifests) - env: - REG_USER: ${{ secrets.REGISTRY_USER }} - REG_PASS: ${{ secrets.REGISTRY_TOKEN }} - run: | - set -euo pipefail - sha=$(git rev-parse HEAD) - image=forgejo.siriusdevops.com/sirius/backup-tools - user="${REG_USER:-sirius}" - pass="${REG_PASS:-${{ github.token }}}" - echo "$pass" | docker login forgejo.siriusdevops.com -u "$user" --password-stdin - # --provenance=false --sbom=false: the tag must resolve to the single - # amd64 image manifest, so the digest a CronJob pins is exactly the - # image the pod runs (an index digest would resolve per-arch). - # --metadata-file carries the pushed manifest digest. Do NOT read it - # back with `buildx imagetools inspect`: Forgejo's /v2/token answers - # 403 to that scope set (measured), while push and kubelet pull are - # fine. - docker buildx build --platform linux/amd64 \ - --provenance=false --sbom=false \ - -t "$image:$sha" \ - --push --metadata-file /tmp/build-meta.json images/backup - echo "pushed $image:$sha" - digest=$(tr -d '\n' < /tmp/build-meta.json \ - | sed -n 's/.*"containerimage\.digest": *"\(sha256:[a-f0-9]*\)".*/\1/p') - [ -n "$digest" ] || { echo "::error::no containerimage.digest in build metadata"; cat /tmp/build-meta.json; exit 1; } - echo "BACKUP_TOOLS_DIGEST=$digest" - { - echo "### Pin this in the three backup CronJob manifests" - echo "" - echo '```' - echo "$image@$digest" - echo '```' - } | tee -a "${GITHUB_STEP_SUMMARY:-/dev/stdout}" diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index aac45f0..0000000 --- a/.gitattributes +++ /dev/null @@ -1,6 +0,0 @@ -# `git diff` on an encrypted Secret is otherwise a wall of ciphertext. -# Enable the driver once per workstation (needs the age key in ~/.config/sops/age/keys.txt): -# git config --global diff.sopsdiffer.textconv 'sops decrypt --output-type yaml' -# Without that config the attribute is inert and git diffs the file as plain text. -*.sops.yaml diff=sopsdiffer -*.sops.yml diff=sopsdiffer diff --git a/.gitignore b/.gitignore index 229bbe3..233b573 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,5 @@ age.agekey secrets/ **/*secret*.yaml !**/kustomization.yaml -# The one exception to the rule above: SOPS ciphertext. Only the `.sops.yaml` -# suffix is un-ignored, so a plaintext Secret file still cannot be committed. -# The age private key (`age.agekey`) stays ignored — it lives in -# flux-system/sops-age and on the Linode, never here. See docs/secrets-sops.md. -!**/secret-*.sops.yaml .DS_Store *.swp diff --git a/.sops.yaml b/.sops.yaml deleted file mode 100644 index cf8483e..0000000 --- a/.sops.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# SOPS configuration for sirius/homek8s. -# -# Age recipient for every encrypted Secret in this repo. The matching private key -# is NOT in git: it lives in the cluster as flux-system/sops-age (key `age.agekey`) -# and is escrowed off-cluster — see docs/secrets-sops.md for both locations. -creation_rules: - - path_regex: (^|/)secret-[a-z0-9.-]+\.sops\.ya?ml$ - encrypted_regex: ^(data|stringData)$ - age: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp diff --git a/Makefile b/Makefile index 1336725..0889404 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,8 @@ -.PHONY: apply diff storage gateway check-sops +.PHONY: apply diff storage gateway apply: kubectl apply -k infrastructure/home -# Static guard: no secret-*.sops.yaml may sit in a tree whose Flux Kustomization -# cannot decrypt it (see docs/secrets-sops.md). No cluster or age key needed. -check-sops: - ./scripts/check-sops-decryption.py - diff: kubectl diff -k infrastructure/home diff --git a/apps/base/customer1/kustomization.yaml b/apps/base/customer1/kustomization.yaml index 226eb29..b25ead7 100644 --- a/apps/base/customer1/kustomization.yaml +++ b/apps/base/customer1/kustomization.yaml @@ -2,8 +2,7 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - namespace.yaml - # Secrets are reconciled by Flux from the secret-*.sops.yaml files in this - # directory (SOPS/age; decrypted by the `apps` Kustomization): + # Secrets are created out of band, before this Kustomization applies: # customer1/pg-app basic-auth, postgres superuser # customer1/pg-users odoo/metabase/metabase_ro role passwords # customer1/odoo-config admin_passwd (database master password) @@ -11,7 +10,7 @@ resources: # customer1/metabase-admin email, password (Metabase's own login) # customer1/metabase-data-source-creds username=metabase_ro + password # customer1/metabase-secret-key MB_ENCRYPTION_SECRET_KEY - # Only ciphertext is committed; the age private key is not in git. + # None of them appear in git; they are not managed (or pruned) by Flux. - postgres-init.yaml - postgres.yaml - odoo-init.yaml @@ -19,17 +18,3 @@ resources: - metabase.yaml - backup.yaml - httproute.yaml - # Default-deny ingress+egress + the tenant's allow list (audit F3 / t_fed52919). - - networkpolicy.yaml - # Tenant guardrails sized from the declared 1-replica shape (same card). - - quota.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-pg-app.sops.yaml - - secret-pg-users.sops.yaml - - secret-odoo-config.sops.yaml - - secret-odoo-admin.sops.yaml - - secret-metabase-admin.sops.yaml - - secret-metabase-data-source-creds.sops.yaml - - secret-metabase-secret-key.sops.yaml diff --git a/apps/base/customer1/namespace.yaml b/apps/base/customer1/namespace.yaml index fa23b20..0fed73f 100644 --- a/apps/base/customer1/namespace.yaml +++ b/apps/base/customer1/namespace.yaml @@ -3,11 +3,5 @@ kind: Namespace metadata: name: customer1 labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: customer1 sirius.dev/purpose: lab-replica-of-client-stack diff --git a/apps/base/customer1/networkpolicy.yaml b/apps/base/customer1/networkpolicy.yaml deleted file mode 100644 index d2be60a..0000000 --- a/apps/base/customer1/networkpolicy.yaml +++ /dev/null @@ -1,78 +0,0 @@ -# Tenant isolation for `customer1` (audit finding F3 / A5-1, card t_fed52919). -# -# Two objects, two jobs: -# 1. `default-deny` (networking.k8s.io/v1) selects every pod in the namespace -# for BOTH directions and allows nothing. It is the only object here that -# creates a deny — a Kubernetes NetworkPolicy with `podSelector: {}` and no -# rules is an unambiguous deny-all in Cilium's k8s-policy path, and unlike a -# CiliumClusterwideNetworkPolicy with `endpointSelector: {}` it cannot -# accidentally select kube-system/Flux/CoreDNS. -# 2. `customer1-allow` (CiliumNetworkPolicy) re-adds exactly the traffic the -# tenant needs. Cilium unions all policies that select an endpoint, so the -# deny above plus this allow list is the effective policy. -# -# Why a CiliumNetworkPolicy for the allows: the sources to permit are Cilium -# *entities* (`ingress` = the Gateway listener proxy, `host` = the node/kubelet), -# which a stock NetworkPolicy cannot name. -# -# What this namespace is allowed to talk to — and nothing else: -# * its own pods (odoo/metabase -> pg:5432, the pg-backup CronJob -> pg), -# * kube-dns on 53. -# It gets NO internet egress (world) and NO API-server egress: the sandbox has -# no external dependency (backup.yaml: dumps stay on the local PVC, the Job has -# `automountServiceAccountToken: false`). If odoo/metabase are ever resumed and -# need an external service, add it here explicitly — that is the point. -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: customer1 -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: customer1-allow - namespace: customer1 -spec: - description: >- - Customer-1 tenant: gateway + kubelet ingress only, egress to own namespace - and cluster DNS only. - endpointSelector: {} - ingress: - # reserved:ingress Cilium Gateway/listener proxy on siriussec (8086/8087) - # reserved:host this node's kubelet probes / host-network datapath - # reserved:remote-node node-sourced traffic when the pod is on another node - # reserved:health cilium-health probes - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace pod -> pod (app -> db, sidecars, the backup CronJob). - # Cilium enforces policy at BOTH ends, so this allow must exist in ingress as - # well as egress — measured on `piedmont`: with only the egress rule a pod - # could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: customer1 - egress: - # Cluster DNS (CoreDNS only). - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - # Intra-namespace only: odoo/metabase -> pg:5432 and the backup Job -> pg. - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: customer1 diff --git a/apps/base/customer1/quota.yaml b/apps/base/customer1/quota.yaml deleted file mode 100644 index b8cbd0b..0000000 --- a/apps/base/customer1/quota.yaml +++ /dev/null @@ -1,80 +0,0 @@ -# `customer1` tenant guardrails (audit finding F3 / A5-1, card t_fed52919). -# -# The sandbox is parked (`replicas: 0`, `suspend: true`, both committed in Git — -# see the README and the F21 note in the audit), so these numbers are derived -# from the DECLARED shape, not from `kubectl top` of a running tenant. Measured -# 2026-11-27 with `kubectl -n customer1 get deploy -o json` + -# `get cronjob pg-backup -o json`: -# -# workload requests limits replicas -# metabase 250m / 1Gi 1 CPU / 2Gi 0 (-> 1 when resumed) -# odoo 200m / 512Mi – / 2Gi 0 (-> 1) -# pg 100m / 256Mi – / 1Gi 0 (-> 1) -# pg-backup 50m / 128Mi – / 512Mi suspended Job -# ------------------------------------------------------------------ -# total 600m / 1.88Gi 1 CPU / 5.5Gi at 1 replica + 1 Job -# -# The quota is the declared total with room for the one thing that always -# happens on a resumed stack: a RollingUpdate keeps maxSurge=25% of one replica -# alive next to the old pod. So requests get ~2x headroom (2 CPU / 4Gi), limits -# ~2x the declared peak (4 CPU / 10Gi) — a tenant cannot use more than two -# replicas' worth of anything at once, and a runaway pod is still cut off by its -# own limit, which is the LimitRange's job. -# -# Storage: 35Gi is already bound (odoo-data 10Gi + odoo-extra-addons 5Gi + -# pg-data 10Gi + backup-data 10Gi) — measured with `kubectl -n customer1 get -# pvc`. 45Gi allows exactly one more 10Gi claim and nothing more. -# -# Do not copy these numbers to another namespace: they describe this stack. -apiVersion: v1 -kind: ResourceQuota -metadata: - name: customer1-quota - namespace: customer1 - labels: - app.kubernetes.io/part-of: customer1 -spec: - hard: - # Compute. Requests ~2x the declared 1-replica total (550m/1792Mi). - requests.cpu: "2" - requests.memory: 4Gi - limits.cpu: "4" - limits.memory: 10Gi - # Object counts. 3 workloads x 2 pods during a rolling update = 6, plus the - # pg-backup Job and room for one debug pod. - pods: "12" - count/jobs.batch: "8" - count/cronjobs.batch: "2" - services: "6" - # Storage: 35Gi bound -> one more 10Gi claim. - requests.storage: 45Gi - persistentvolumeclaims: "6" ---- -# Container defaults so the quota above is satisfiable by every pod in the -# namespace: a ResourceQuota that constrains requests.cpu/limits.cpu rejects any -# pod without them, and the LimitRange injects them. `max` is the per-container -# ceiling — 2Gi is exactly metabase's declared limit, so the parked stack -# schedules unchanged when it is resumed; anything bigger now needs a namespace -# change on purpose. -apiVersion: v1 -kind: LimitRange -metadata: - name: customer1-limits - namespace: customer1 - labels: - app.kubernetes.io/part-of: customer1 -spec: - limits: - - type: Container - defaultRequest: - cpu: 100m - memory: 128Mi - default: - cpu: 500m - memory: 512Mi - max: - cpu: "1" - memory: 2Gi - min: - cpu: 50m - memory: 64Mi diff --git a/apps/base/customer1/secret-metabase-admin.sops.yaml b/apps/base/customer1/secret-metabase-admin.sops.yaml deleted file mode 100644 index 67cf054..0000000 --- a/apps/base/customer1/secret-metabase-admin.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - email: ENC[AES256_GCM,data:pye3Ei9A453apvkVNrfqggFKyx/ATskG77WrMA==,iv:4ZcgCPJNFxCK7htIKuwR+3keDNmV3Knb7zqdhe+yxTc=,tag:VyYkzJUexigD9G9IbMPPhA==,type:str] - password: ENC[AES256_GCM,data:KLYg2onQai5UcYxAFjOqnTV86aXreASsBmE4t83f2YX8b8FM9G0tMcG6tnw6xP9eICKtxBh+Qlq6y/nvjRaVmg==,iv:o8zosg+KBh0QMm4JdqSZVSfl4Zx8QHumaeg9eb+kdcI=,tag:sLHNVvDq/qbyp8jtJ4Bo2A==,type:str] -kind: Secret -metadata: - name: metabase-admin - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBPamdJcnBNaVlCVndCYjZp - U240ZTc3K2dOeGZKT0EvYkQ0Nkk0ZjkxcG5nClcyZ2pYaDhwRUkrN0xXU0g4Mk0w - cmgrOXZvSWl2MDF6QWhuVXc0Q3Z4MU0KLS0tIGJVUVlZczhUSHp5elV1RnBwSzNy - a2tMNnJqbDlPZWcvek9zZDYvL21xbUEKm89bfzcfUXX7Dd6KEDdDx1Ka2kPU+WSS - t/XO7xYheieqkjhEGtFfT+HyOiFsI1Kq3vo/r/TPp1+5xh+5RlJksg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:45Z" - mac: ENC[AES256_GCM,data:PXhSM6xorgIfCefgZkohRH8j+G/UHtZp1itgNcdEvn6SRNTSvLLi+evEIFA1Z9MbPsu9+Q/UtWVikeYMUj5ISriTOc260Z2J2AUrYB2PDqmizqS+rjVrDgqAhPuttBIh7Fk7WEQhQETHwtNPHWfk3T/MH324Ki7mWmru83xP4hw=,iv:CDHi7wczZXpPs8AMWDI6vx6JkY2Wb5de4vbUH3+4GCQ=,tag:Qw+mGUG6l5USLGFwH28BFA==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-metabase-data-source-creds.sops.yaml b/apps/base/customer1/secret-metabase-data-source-creds.sops.yaml deleted file mode 100644 index a306b46..0000000 --- a/apps/base/customer1/secret-metabase-data-source-creds.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:883FQISSJ2D3Kd+rWGC1DOdzKyG+QuUEvlMnQ3L6aDuXgBvXphhTmPhBfrOCR/J5ttGUBLBekzclNbxX37bVAw==,iv:XJ5zNft7ZnE2jsu7FUXbflV0mUdcNjE4R+QT//hmhfo=,tag:7tjYUC/iVDB/rkXE9r93gw==,type:str] - username: ENC[AES256_GCM,data:OD7PyqDx6EY6x0EEQvTLcw==,iv:ngjJgRODgdFVAbYBL4JMm+tv3kM7VvFiyb0KvY+O48Q=,tag:GwzHUK9BKgsXBMHsvBQ/Sw==,type:str] -kind: Secret -metadata: - name: metabase-data-source-creds - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBSc1MvOWIrdENjdUpJYmsy - a0hZZjBQRk9JOThoMWtoK0REdkZ1SVZJbGs0Ck1udWRxc2VWY2dVa2tuY2tjdVU1 - cFNBb3FLWmtuZFZUSHRJd0tFWW9WUUUKLS0tIFQzV2dMeUJONGF4TVJmampHVWhQ - dnNJaGtlQjhFeEYwVUtLSUNCOFdJcFEKj1zVUr5nadbAE6vk5aErwrIHMNx0EyRY - 9O8QPPzQq4kJpiCowLtf4TLXpGvbTCuvIQhddd1H6azOEEL49D3LdQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:45Z" - mac: ENC[AES256_GCM,data:KMhWpTBwsszg7Wiv0h0ojw62dJmqXXHCFoJI3UplEH72RaYAu4dFW8S3Id4NXyA4YuBOLzEMY2OQkuiklybSkgmTS3oefTT7yoQOqhkkkUc1qlHNmmhz2pS5qsdGnEaCw2fMeDrsQdFL2bBLbZn3Qi059OFDwQZcxqAS2EX6N6A=,iv:MUPOjzikSC1ftDKeG+oCPg13E28x53xXUJNPVndWClY=,tag:1A7fWGXe++VdAJumqLTXTw==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-metabase-secret-key.sops.yaml b/apps/base/customer1/secret-metabase-secret-key.sops.yaml deleted file mode 100644 index 2ac188f..0000000 --- a/apps/base/customer1/secret-metabase-secret-key.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - MB_ENCRYPTION_SECRET_KEY: ENC[AES256_GCM,data:JSp0PadR8hdBvLLHesQaHjHneGcj8t+w0JSaiua51JkY4vqvEJ90s65niamHXrdgWjaq3NS7nfS8PMkNfwHqfbiX309Wj3kN8oHRgMyfJpBbj+lnO5ieAw==,iv:rtqT8wlGTbH86MIbw+fDlXMkGyqesHziUGc6iQnao+I=,tag:k99H2PSPgaZobpjxa5UQSQ==,type:str] -kind: Secret -metadata: - name: metabase-secret-key - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBMS2pSRzc3ZVhIYXZiUytC - TmtTWWJCQ3B0SjZ5WCtCLzFVZWQ3YXdyTVJBCnVOa09HQmpIcUkzWmFGaVkvN1BX - S2ovaUhpYmJLQmhoUm9QRmNCN3UrbDgKLS0tIHpraFVzazJBaUNTVTlod1NTOE9Z - cThXbDhRSkNRQVJuYlR2YWhHT3htREEKESpWw+VvIYkR23yy6Q5Hvfm2kpiDUE/B - fijCO62TfCgujWxEWW6pmrm8KnTuyc94k5j2FTV/SiXwmynRYgsvbQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:45Z" - mac: ENC[AES256_GCM,data:6mYN/X5XhqcVEXWSsub/aSkVjvv3+iRE7lFcDjAJVlIgVAZ8TkTn4OywqauqhNc8yJQL3fenpOUwWGsqbte9iu8o02buc2D3vx+iMj/PHEa3nJEJLJ568oQont0rVRYeAmtcEkeQAUSLFWTPyyk41nwZQ93U4NpY2v13rCpDqC4=,iv:DcZa1YDTjIPNkhHLMrQZiLUWqEI7JyKlxLR/E5OylBk=,tag:w7mQWj06ZXOdN9303TZ8RA==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-odoo-admin.sops.yaml b/apps/base/customer1/secret-odoo-admin.sops.yaml deleted file mode 100644 index 6b45106..0000000 --- a/apps/base/customer1/secret-odoo-admin.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - email: ENC[AES256_GCM,data:gI6NwFOxqUnFQzfXQJhvsv+zsFmw9RA5OwnglQ==,iv:Bb4TDSiS1OVNQAXBviA8Dw/kdi09K1uQl/4SVOijC1o=,tag:ThcEMoBBc7yl4RXqyIlb1Q==,type:str] - password: ENC[AES256_GCM,data:6u9gNzQtqDPDN/TyfqzcahX63JOoaKkph4Tgcsz7cSGRt/qpR/Vintnc+VbUeNhLIz8k1P3AI9XkWM1f25qEJQ==,iv:hhtJRFJFUZ4HR+6Cu8rhNdA5tb4g5V3xjMnNy6TTiUY=,tag:Ot84YjRft7xN63XNopRLgQ==,type:str] -kind: Secret -metadata: - name: odoo-admin - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBBNEd1MjlVU1Yzem1yWTdk - ZUZhdkc2VThWM3RrT1lUT1BYb3J3WmhKMVFzCjQzcjJsdGdDMHVzajlNUW42OWNi - VVdqM3pKd2hEelhHQmpHMjh1SW51N28KLS0tIHQxb3Y0M25ZYzFrNXJYVU4wS0Fw - N0hrUHhPc1YwaUxrU0RyY2JsbGIyM0EKhdd2YP9REMTNaQDMSZ9iZVoWmHysjLJv - y1jhciBxTpHP384gdJE2wDQftKvAkLtNMh2og0oZdHJnlQybP+CELA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:45Z" - mac: ENC[AES256_GCM,data:L3RbLA3LdN6uV9NEKtjLpNNwFkBAvXdyT/A3EpYBzmM+3Vj6gFSg8NRSw1ttO4mlCIuebKqJ7rp1MUj0vx4VrnhDt8N/XSOuSh72XRFZpqjVSp9tXnJx6y3TkPo0+87kchFQC2i7MO9ysxKyNbhRQ8Fte7NDE73TM5K7Tbes6sM=,iv:C18NRt2JEBmZRZprpQr4YZNEUVto+sE0G+ZCQ4MU1tA=,tag:4YXb06SVaZkGO1y7LSnKdw==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-odoo-config.sops.yaml b/apps/base/customer1/secret-odoo-config.sops.yaml deleted file mode 100644 index caea3a9..0000000 --- a/apps/base/customer1/secret-odoo-config.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - admin_passwd: ENC[AES256_GCM,data:pBG7LujHDijWRpmmxs9ffv+QR8ASR4Am/IpOFV9GoEeYolG4OrRNEACU4QXS+1Fn1QnDvAVgsXQKeWC7ukwYCg==,iv:pV8OYTFdYzRKxNdLY3qNHSL1X/5FmCE6P4Uuia6Lp5k=,tag:v7ODHmLxlPPvDouU9XdVcg==,type:str] -kind: Secret -metadata: - name: odoo-config - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBHb0dVWENybXJEd3VVNzlI - N051b2tBYlpxNG10TmJWWmVGRUVqTVBiMlNnCnl5SnkzMTV0cXdldis1eWtlM0Nl - TzMrR2ZEREdlZzZ6am5aQU5uQnhoWlUKLS0tIEpiVHJIT1V1aVF1NmJrajVDOVRt - QmQvWkx5UTNRd2RRMk9iVld1dVExeGcK5fIhbRpE9AyvhlXSRbvHQDqaAA1LONKC - LqN0Gsald5QMH9tvQFRFJMnjVOpi1mgfOi3ErwQhgDO8GVn2HmPjPg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:45Z" - mac: ENC[AES256_GCM,data:+bwR9y/ILXyRwIVABTa6RIsK87a7+P+yFChNKB6Li6oukj2pJhEfrE9LIKdqOa24sg7IbAz2f+IyQ86qnR2zKcMUENdlkDq353arta1nCFxZ6A49XVwVXYjbj+OrnFRt3fJBuLhkSwutcXBXNZk5LL4KDmErw75RAAcsNMNjsPA=,iv:/xM9lqO7UCA3S+bRq8DJg4N6YLo5EcCnRSlGNY5CX54=,tag:3nIT7ZXueXmgKL+HeocINw==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-pg-app.sops.yaml b/apps/base/customer1/secret-pg-app.sops.yaml deleted file mode 100644 index 99477b3..0000000 --- a/apps/base/customer1/secret-pg-app.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:8TOZ9hLg1NswEAhf7GFOCB6PSrD8MyBzlYXsDy4kXgRgLaIW2Lm/nTIo9g8IgZQESA/6q/rKaF4vnIJJkaHtZg==,iv:1/sOnAtyjiOE74O02B8aHd2zSl4yY5db/Zn4jmC556s=,tag:WoAGHpZSRWFjIZ6Nbzae5w==,type:str] - username: ENC[AES256_GCM,data:ERoiT+V2+l7/81l6,iv:Dt1Vidd67w0v+trgaEqmpRYS4GqswMm6f+tHS6N1O7o=,tag:DSr46jx9du9nmO+dPXf7dw==,type:str] -kind: Secret -metadata: - name: pg-app - namespace: customer1 -type: kubernetes.io/basic-auth -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBnZWR5SEFZcEVlS0ZEWnNI - TUZUakowdlRvdXhubGR2UmV6SUJITHhXd1Y0ClNiQWl4Y2IzRE5raEE0S2ZVRWVE - b056bHFRZ1E3TFlobDVzaHhpK0xneGsKLS0tIDZRaUJnNmF3SGhtc1NRVGQ0TGdI - aGNYbkh6dWN6ZEZtUTVhUHRjOWFZK28KbkBCjLV7ao5IaQIdBQvZBVi59XXVqneH - BKp+F0OuqRNMCC0B3nQothimBFd2fQTKQ24TAVAji8H4ScK3djnHLQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:ZDeCBfrq7ENthn4MJoLtRS5swjFUoKXeR7Us/7VcunkeDomuEtQWC9T3j57HQujLgKOMWZvAi9f+i6DRi3/UkrwlzQHuGQPPLvGk40pMfpu7ydcTQAiwgC94slGouxhY2/yTkCCJvP/76bvnXpAuunBxta+RikMlruehAC5wBCY=,iv:iVrJh5Ijz9E7FnWHVyfuEr6qG6jRSJ1wySDbXKBaC9I=,tag:yW/4EclmKgNb1kJcz1Vz8Q==,type:str] - version: 3.13.3 diff --git a/apps/base/customer1/secret-pg-users.sops.yaml b/apps/base/customer1/secret-pg-users.sops.yaml deleted file mode 100644 index 75aa39d..0000000 --- a/apps/base/customer1/secret-pg-users.sops.yaml +++ /dev/null @@ -1,25 +0,0 @@ -apiVersion: v1 -data: - metabase_password: ENC[AES256_GCM,data:L7rJGclU3XcAXVbQL8RKEYY3a/if538EDH+TGX9Aw27velxwGOGhHb2sJ4fqI5Or6rmJlgh/UdvWrgJ9lZdzdw==,iv:oG9OUeXcxl5qizX65thHggI0QcPs5/Mv/enSZtt+VF4=,tag:ZUKXEPLVQjJ0778S8B79VQ==,type:str] - metabase_ro_password: ENC[AES256_GCM,data:ozf71aGKA3CFRzaLop9jzliaXPXZ5lmhY5YEIKXBx3AhMtDYmA5FOlJHsORHP3RB1vlPI9EChmQDTRxg1gzOBg==,iv:C4Olqkno9gvWIjh+nKP/dld7586RK3CE/s0mma+4bgQ=,tag:J0+1EKGWiuNAXTE0liUEEw==,type:str] - odoo_password: ENC[AES256_GCM,data:OygJFdgceU2rlA4Gcf+jcMtmLBRH4Tpv4cI24oE7maovzd/5fxDPvAQJOKeJafE70LaLkdmP0GbnCbK5DGZH+A==,iv:85yaLhT4zFRnglDKPbHcA1hsyJCckqUotLsz+Kssa/o=,tag:rfter+CQbKtm9mbwsxwWqw==,type:str] -kind: Secret -metadata: - name: pg-users - namespace: customer1 -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBlcEJFOTRJT1R6WG41b3Nj - c3dTMnhxTllNVDllVndGUS9UdHVGQ2d6c0RJCklHNDhYTVo5SFErdlRvanNNeDhi - MVBuYm1WMFJJMHRMOEFYTm1TbDhueGsKLS0tICtoenNqKzVwSGxIdisvUG92UVBG - VHZkT3ZiRlk0Y2FmdUIrQ1c5VnNFajAKOE2XsfMeAaXMJW7Ao4A9GyYuGShNMl+K - Z+W64wvP3Mub7496laYNccA/Ve/WklZcBdzVPSErWVVaSuId0/6TEA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:VIKZNuiKBQH04Y9EcYzrpoO9hQ85pOS9Iy13Pqgi/MkFm+uMzzEORB9sLdjGK0jQrfYqmzxnTpX4vTW0RXtlzXrFp+ZrrPOlOnjK5qwzLk6T+fz4vIGPi0TDAyWZgNO/xO+fLQhNcGcwkUlPzW+WwZRtg3+B8CfU0cPtfIl4UCM=,iv:AxvNn+3vjOMIsmqfYDDsZGKQuIc0b4RoISc4fVrl4WM=,tag:PVVa4GSMVe833JXFtlHpAA==,type:str] - version: 3.13.3 diff --git a/apps/base/forgejo/ci-runners-namespace.yaml b/apps/base/forgejo/ci-runners-namespace.yaml deleted file mode 100644 index ed2bce5..0000000 --- a/apps/base/forgejo/ci-runners-namespace.yaml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - name: ci-runners - # The Forgejo Actions CI capsule: three runner Deployments (each with a - # privileged docker-in-docker sidecar), their data PVCs, and the nightly - # prune CronJob (hostPath `/var/run/docker.sock`). - # - # `enforce: privileged` is deliberate and is the whole point of this - # namespace existing. Pod Security has no per-workload exception: if these - # pods share `forgejo`, that namespace can only ever be warn/audit, i.e. no - # namespace in the cluster enforces anything. Isolating the capsule here lets - # `forgejo` enforce `baseline` (Forgejo, Postgres, backups) while this - # namespace keeps the one shape that genuinely needs node root and is - # labelled as such in Git. - # - # This is containment, not a grant of new privilege: the dind sidecar was - # already privileged, and CI job containers are unprivileged - # (`container.privileged: false` in the runner ConfigMap). Keep this - # namespace free of anything that is not part of the CI capsule, and give it - # its own NetworkPolicy/RBAC scope rather than widening it. - # - # warn/audit are `privileged` too, on purpose: at that level PSA prints and - # records nothing, which is the honest signal — everything here is allowed by - # design, and the namespace holds only the CI capsule. (Warn/audit at - # `restricted` would emit the same five violations for every pod, every - # restart, and train everyone to ignore them.) Anything added here that is not - # part of the capsule is a review failure in Git, not an admission event. - labels: - pod-security.kubernetes.io/enforce: privileged - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: privileged - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: privileged - pod-security.kubernetes.io/audit-version: latest diff --git a/apps/base/forgejo/cluster-backup.yaml b/apps/base/forgejo/cluster-backup.yaml index 5834af7..5b1518d 100644 --- a/apps/base/forgejo/cluster-backup.yaml +++ b/apps/base/forgejo/cluster-backup.yaml @@ -87,10 +87,12 @@ data: # (the node runs close to DiskPressure and `local-path` lives on it). set -euo pipefail - # No package install here on purpose: rsync/openssh-client/bash/kubectl are - # baked into the pinned image (images/backup/Dockerfile) and this pod's - # egress policy admits DNS, 10.10.0.5:22 and the API only, so a runtime - # fetch would fail rather than silently dial the Alpine CDN (t_9d0428d8). + # alpine/k8s ships kubectl/bash but not rsync/ssh; install them per run + # (~2 s). Nothing else is needed: the DB dumps run inside the CNPG pod. + if ! command -v rsync >/dev/null || ! command -v ssh >/dev/null; then + echo "== installing rsync + openssh-client" + apk add --no-cache rsync openssh-client >/dev/null + fi BACKUP_HOST=${BACKUP_HOST:-root@10.10.0.5} BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} @@ -244,20 +246,16 @@ spec: spec: restartPolicy: Never serviceAccountName: cluster-backup - # Pulled from the in-cluster Forgejo registry (which requires auth). - imagePullSecrets: - - name: forgejo-pull # The forgejo-data PVC is local-path on siriussec; the pod must run # where the volume is. nodeSelector: kubernetes.io/hostname: siriussec containers: - name: backup - # python3.12-alpine + rsync + openssh-client + bash + kubectl - # v1.36.4 (== cluster version, so the CNPG dumps can be taken - # through the exec API), all baked at build time and pinned by - # digest. Nothing is installed at run time. - image: forgejo.siriusdevops.com/sirius/backup-tools@sha256:cc8dc1645111b3a80b7c4d5168f6bce3002cae7417b3725683c057976f6e379a + # alpine/k8s carries kubectl 1.36.4 (== cluster version) so the + # CNPG dumps can be taken through the exec API; rsync + openssh + # are added at start (the pod has normal egress). + image: alpine/k8s:1.36.4 imagePullPolicy: IfNotPresent command: ["/bin/bash", "/scripts/backup.sh"] env: diff --git a/apps/base/forgejo/deployment.yaml b/apps/base/forgejo/deployment.yaml index fe34eb8..1a6c467 100644 --- a/apps/base/forgejo/deployment.yaml +++ b/apps/base/forgejo/deployment.yaml @@ -58,17 +58,6 @@ spec: # Bot signup lockdown: admin-only account creation (web + API). - name: FORGEJO__service__DISABLE_REGISTRATION value: "true" - # Public-repo browsing is ON. Audit F11 had turned this on because - # Forgejo issues anonymous ("ghost user") registry tokens at - # /v2/token with Read on every package, so with public browsing - # every app image was world-pullable. That coupling is now cut at - # the edge instead: a Cloudflare zone custom rule ("Block anonymous - # Forgejo registry tokens") blocks /v2/token unless the request - # carries Basic auth, so anonymous pulls get 403 while containerd - # (which sends its `forgejo-pull` dockerconfigjson credentials) - # still pulls. Re-check that rule before turning this back to true. - - name: FORGEJO__service__REQUIRE_SIGNIN_VIEW - value: "false" volumeMounts: - name: data mountPath: /data diff --git a/apps/base/forgejo/kata-runtimeclass.yaml b/apps/base/forgejo/kata-runtimeclass.yaml deleted file mode 100644 index 1c75abc..0000000 --- a/apps/base/forgejo/kata-runtimeclass.yaml +++ /dev/null @@ -1,27 +0,0 @@ ---- -# Kata Containers microVM RuntimeClass for the CI capsule (card t_8aa4af50). -# -# What this buys and what it does NOT: a pod using this class still declares -# `privileged: true` — a nested dockerd needs CAP_SYS_ADMIN + CAP_NET_ADMIN in -# the pod spec, and PSA `baseline` forbids exactly those two, so `ci-runners` -# stays at `enforce: privileged` (docs/pod-security.md). What changes is what -# privilege applies to: the container runs inside a QEMU/KVM microVM, so -# "privileged" means root in a VM with no host namespaces, no host kernel and -# only the volumes the pod mounts — an escape has to beat KVM first. -# -# The handler name `kata-qemu` must exist in containerd on every node that can -# run a pod with this class (drop-in /etc/containerd/conf.d/50-kata.toml, -# kata-static 4.4.0 under /opt/kata). Installed on rpi 2026-11-27; not yet on -# siriussec — that is why only the rpi-pinned deploy runner uses this class. -apiVersion: node.k8s.io/v1 -kind: RuntimeClass -metadata: - name: kata-qemu -handler: kata-qemu -# VM overhead is charged to the pod so the scheduler accounts for it. The VM -# itself is sized from the pod's memory limits (2Gi here) plus the kata -# agent/kernel. -overhead: - podFixed: - cpu: 250m - memory: 160Mi diff --git a/apps/base/forgejo/kustomization.yaml b/apps/base/forgejo/kustomization.yaml index 8a4ccd0..4c69535 100644 --- a/apps/base/forgejo/kustomization.yaml +++ b/apps/base/forgejo/kustomization.yaml @@ -1,17 +1,8 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - # Two namespaces: `forgejo` (enforce: baseline) and `ci-runners` - # (enforce: privileged — the CI capsule). Namespace objects sort first. - namespace.yaml - - ci-runners-namespace.yaml - httproute.yaml - # Default-deny ingress+egress + the namespace allow list (audit F3 / t_fed52919). - - networkpolicy.yaml - # Egress lockdown for the cluster-backup pod: DNS + 10.10.0.5:22 + the API - # only. The allow list above cannot be narrowed per pod, so the deny for - # `world` in this policy is what applies to the job (card t_9d0428d8). - - networkpolicy-backup.yaml - pvc.yaml - cluster.yaml - podmonitor.yaml @@ -21,19 +12,10 @@ resources: - deployment.yaml - service.yaml - runner-configmap.yaml - # The runner PVCs/Deployments below and the prune CronJob — plus the two - # runner-token Secrets near the bottom — live in namespace `ci-runners`, - # not `forgejo`: the dind sidecars need `privileged` and the prune Job needs a - # hostPath socket, both of which `forgejo` now rejects at admission - # (enforce: baseline). - # # Static PVs/PVCs pinned to rpi: dynamic local-path cannot provision there # (its helper pod is hardcoded to siriussec). Must sort before the runner # Deployments that consume the claims. - runner-dind-storage.yaml - # Cluster-scoped RuntimeClass for the Kata microVM that the rpi deploy runner - # uses (card t_8aa4af50). Its handler exists in containerd on rpi only. - - kata-runtimeclass.yaml - runner-arm64.yaml - runner-amd64.yaml - runner-deploy-arm64.yaml @@ -41,14 +23,3 @@ resources: # Nightly disaster-recovery backup of forgejo-data + every CNPG database to # the Linode VPS. Lives here because a PVC cannot be mounted cross-namespace. - cluster-backup.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-forgejo-pg-app.sops.yaml - - secret-forgejo-runner-amd64-token.sops.yaml - - secret-forgejo-runner-deploy-arm64-token.sops.yaml - - secret-cluster-backup-ssh.sops.yaml - # Registry pull credential: cluster-backup now runs an image from the - # in-cluster Forgejo registry instead of alpine/k8s from Docker Hub - # (card t_9d0428d8). - - secret-forgejo-pull.sops.yaml diff --git a/apps/base/forgejo/namespace.yaml b/apps/base/forgejo/namespace.yaml index 92051f3..6521f89 100644 --- a/apps/base/forgejo/namespace.yaml +++ b/apps/base/forgejo/namespace.yaml @@ -2,29 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: forgejo - # Pod Security: `enforce: baseline` here. Everything that lives in this - # namespace — Forgejo itself, the CNPG Postgres cluster, the nightly - # cluster-backup CronJob — is baseline-clean (no privileged, no hostPath, - # no host namespaces, no added capabilities), so the enforcement is real - # rather than decorative. - # - # The Actions runners are NOT here any more. A docker-in-docker sidecar - # cannot lose `privileged: true` on these nodes (procfs needs CAP_SYS_ADMIN, - # kubelet mounts /sys/fs/cgroup read-only for non-privileged pods, rootless - # dind is blocked by the masked /proc and the absent /dev/net/tun — all - # measured, see docs/pod-security.md), so the three runner Deployments, their - # PVCs and the prune CronJob live in `ci-runners`, which enforces PSA at - # `privileged` on purpose. Moving them out is what lets this namespace - # enforce baseline: if a runner (or anything else privileged/hostPath) is - # ever added here, admission rejects it instead of silently accepting it. - # - # warn/audit stay at `restricted`: a future pod that is baseline-clean but - # not restricted-clean (e.g. missing seccomp/runAsNonRoot) is still printed - # and recorded as audit annotations. - labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/apps/base/forgejo/networkpolicy-backup.yaml b/apps/base/forgejo/networkpolicy-backup.yaml deleted file mode 100644 index b658990..0000000 --- a/apps/base/forgejo/networkpolicy-backup.yaml +++ /dev/null @@ -1,64 +0,0 @@ -# Egress lockdown for the nightly cluster-backup CronJob (card t_9d0428d8). -# -# Why: the job used to `apk add --no-cache rsync openssh-client` at container -# start, so each run depended on the Alpine CDN (Fastly 151.101.x.132:443) and -# tripped `egress-new-dst` whenever that anycast address rotated. rsync/ssh/ -# bash/kubectl are baked into images/backup/Dockerfile now. -# -# `forgejo-allow` (networkpolicy.yaml) selects every pod in this namespace and -# allows `world`, so a pod-scoped allow list alone would NOT restrict the job — -# Cilium unions multiple policies. The `egressDeny` for `world` below is what -# actually closes it (deny always beats allow), and it is scoped to this pod by -# the endpointSelector, so Forgejo's own webhooks/mirror/avatar egress is -# untouched. -# -# Allow list, and nothing else: -# * cluster DNS; -# * root@10.10.0.5:22 — the Linode node's InternalIP, so `remote-node`, not -# `world` (the rsync target and every ssh_r call); -# * kube-apiserver on 6443/443 — `kubectl get cluster` for the CNPG primary -# and `kubectl exec ... pg_dump` for both CNPG and the plain Postgres -# Deployment. Port-scoped on purpose: the apiserver shares its host IP with -# the internal Gateway listeners on 8081/8084-8087. -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: cluster-backup-egress - namespace: forgejo - labels: - app: cluster-backup -spec: - description: >- - cluster-backup pod: cluster DNS, SSH to the backup host (10.10.0.5:22) and - the API (6443/443) only; no internet egress at run time. - endpointSelector: - matchLabels: - app: cluster-backup - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEntities: - - remote-node - toPorts: - - ports: - - port: "22" - protocol: TCP - - toEntities: - - kube-apiserver - toPorts: - - ports: - - port: "6443" - protocol: TCP - - port: "443" - protocol: TCP - egressDeny: - - toEntities: - - world diff --git a/apps/base/forgejo/networkpolicy.yaml b/apps/base/forgejo/networkpolicy.yaml deleted file mode 100644 index e0a6826..0000000 --- a/apps/base/forgejo/networkpolicy.yaml +++ /dev/null @@ -1,143 +0,0 @@ -# Tenant isolation for `forgejo` (audit finding F3 / A5-1, card t_fed52919). -# -# `default-deny` (stock NetworkPolicy, podSelector {}, both directions) is the -# deny. `forgejo-allow` (CiliumNetworkPolicy) re-adds what this namespace uses: -# ingress: the Cilium Gateway proxy (`reserved:ingress`) for -# forgejo.siriusdevops.com -> forgejo:3000; the CI runners in -# `ci-runners` on 3000 only (they register/poll over the PUBLIC URL, -# so THAT traffic arrives as `reserved:ingress` — but their image -# pushes go pod->pod to the internal ClusterIP -# `forgejo.forgejo.svc.cluster.local:3000` -# (`PUSH_REGISTRY` in each repo's `.forgejo/workflows/build.yml`, -# docker daemon in the dind sidecar of the runner pod). Pod->pod is -# not `reserved:ingress`, so `default-deny` dropped it and every -# image build failed 2026-11-27 .. 2026-12-05 with -# `Get "http://forgejo.forgejo.svc.cluster.local:3000/v2/": request -# canceled ... Client.Timeout exceeded` — the cross-namespace rule IS -# required; do not delete it as redundant. Node/health entities -# cover kubelet probes; Prometheus in `monitoring` is allowed on -# 9187 only (the -# `cnpg-pg` PodMonitor scrapes the CNPG instance manager), and the -# CNPG operator in `cnpg-system` on 8000 only — the instance -# manager's HTTPS status endpoint the operator reads to derive the -# system ID and drive failover (card t_4210edec). -# egress: cluster DNS; its own pods (forgejo -> pg-rw:5432); `world` for -# outbound HTTPS (Forgejo webhooks, avatar/mirror fetches, the -# public-URL callbacks the runner flow needs); node IPs on 22, which -# is the nightly `cluster-backup` CronJob rsyncing to -# root@10.10.0.5; and `kube-apiserver`, needed by the CNPG instance -# manager and by cluster-backup's `kubectl get cluster` / -# `kubectl exec` DB dumps. -# -# The CI runner pods themselves are NOT in this namespace (they moved to -# `ci-runners` for `enforce: privileged`); `forgejo-allow` only grants them -# forgejo:3000, which is the registry push path the builds depend on. -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: forgejo -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: forgejo-allow - namespace: forgejo -spec: - description: >- - forgejo: gateway + kubelet + Prometheus + ci-runners registry-push ingress; - egress to own namespace, cluster DNS, the internet, SSH on node IPs and the - API. - endpointSelector: {} - ingress: - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace pod -> pod (app -> db, sidecars, the backup CronJob). - # Cilium enforces policy at BOTH ends, so this allow must exist in ingress as - # well as egress — measured on `piedmont`: with only the egress rule a pod - # could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: forgejo - # CI runners (`ci-runners`) push images to the in-cluster registry at - # forgejo.forgejo.svc.cluster.local:3000 (PUSH_REGISTRY in each repo's - # build workflow; the docker daemon lives in the dind sidecar of the same - # pod, so one namespace selector covers runner + sidecar). Registration and - # polling use the public URL and arrive as `reserved:ingress`, but the push - # is pod -> pod and default-deny drops it without this rule. Port-scoped on - # purpose: the registry API only, nothing else in the namespace. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: ci-runners - toPorts: - - ports: - - port: "3000" - protocol: TCP - # The CNPG operator (`cnpg-system`) reads the instance manager's HTTPS - # status endpoint to derive the system ID and drive switchover/promotion. - # Without it the Cluster reports `Instance Status Extraction Error` and - # Ready=False while the pods serve traffic, and automated failover is dead - # (card t_4210edec). Scoped to 8000: not 5432, not the whole namespace. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: cnpg-system - app.kubernetes.io/name: cloudnative-pg - toPorts: - - ports: - - port: "8000" - protocol: TCP - # Prometheus scrapes the CNPG `pg` instance manager on 9187. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: monitoring - toPorts: - - ports: - - port: "9187" - protocol: TCP - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: forgejo - # Outbound HTTPS: webhooks, mirrors, avatar fetching. - - toEntities: - - world - # cluster-backup rsync/ssh to root@10.10.0.5 (the Linode node). - - toEntities: - - remote-node - toPorts: - - ports: - - port: "22" - protocol: TCP - # CNPG instance manager and cluster-backup's kubectl calls. Port-scoped on - # purpose: the apiserver is host-networked on 10.10.0.2 and Cilium attaches - # the `kube-apiserver` identity to that whole node IP — an unscoped entity - # rule also opens 8081/8084/8085/8086/8087 (the internal Gateway listeners) - # and :10250/:9100 on the same address. Measured: 10.10.0.2:8085 was OPEN - # from this namespace until the ports were named. 443 is the service port - # kubectl dials (kubernetes.default:443 -> backend 6443). - - toEntities: - - kube-apiserver - toPorts: - - ports: - - port: "6443" - protocol: TCP - - port: "443" - protocol: TCP diff --git a/apps/base/forgejo/pg-actions-queries.yaml b/apps/base/forgejo/pg-actions-queries.yaml index 6ad7492..0c937a0 100644 --- a/apps/base/forgejo/pg-actions-queries.yaml +++ b/apps/base/forgejo/pg-actions-queries.yaml @@ -38,13 +38,6 @@ kind: ConfigMap metadata: name: forgejo-actions-queries namespace: forgejo - labels: - # Tells the CNPG instance manager to re-read this ConfigMap on change. - # Without it a query fix (like the actions_runners dedupe below) does not - # reach the exporter until someone runs `kubectl cnpg reload` or the pod - # restarts — i.e. the fix appears to do nothing and /metrics keeps 500ing. - # This is a live reload of the queries, not a PostgreSQL restart. - cnpg.io/reload: "" data: queries: | # Queue depth: jobs handed to a runner that have not started, plus the age @@ -104,28 +97,11 @@ data: # How long ago each runner last polled Forgejo. This is the only signal that # says "the runner process is alive" independently of the pod being Ready — # a runner that cannot reach the forge stays Running but goes stale here. - # - # This query MUST return at most one row per `runner` label value. The - # exporter treats a duplicate label set as a programming error and answers - # the whole /metrics request with HTTP 500 — which also drops every - # pg_stat_*/cnpg_pg_* series, not just this one (incident t_290ff037). - # - # Two defences, both needed: - # * `r.deleted IS NULL` — Forgejo soft-deletes a runner (sets `deleted` to - # an epoch, keeps the row), so stale registrations survive in the table - # after a runner is removed. They are not real runners and stay hidden - # from the admin API, but a raw table read would see them. - # * `GROUP BY r.name` with `max(last_online)` — the label *is* the name, so - # two live rows that share a name (a re-registered runner, or one pod - # started from a copied runner.ini) would otherwise collide. Reporting - # the most recent poll per name is the semantic we want anyway. actions_runners: query: | SELECT r.name AS runner - , COALESCE(EXTRACT(EPOCH FROM pg_catalog.now())::bigint - NULLIF(max(r.last_online), 0), -1) AS last_online_seconds + , COALESCE(EXTRACT(EPOCH FROM pg_catalog.now())::bigint - NULLIF(r.last_online, 0), -1) AS last_online_seconds FROM action_runner r - WHERE r.deleted IS NULL - GROUP BY r.name metrics: - runner: usage: "LABEL" diff --git a/apps/base/forgejo/prune-cronjob.yaml b/apps/base/forgejo/prune-cronjob.yaml index 4722438..e26fd07 100644 --- a/apps/base/forgejo/prune-cronjob.yaml +++ b/apps/base/forgejo/prune-cronjob.yaml @@ -35,18 +35,18 @@ apiVersion: v1 kind: ServiceAccount metadata: name: forgejo-prune - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: prune --- # Least privilege: the job needs to find dind pods (get/list) and to run -# docker inside them (pods/exec create) — in namespace ci-runners only. +# docker inside them (pods/exec create) — in namespace forgejo only. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: forgejo-prune - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: prune @@ -62,7 +62,7 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: forgejo-prune - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: prune @@ -73,13 +73,13 @@ roleRef: subjects: - kind: ServiceAccount name: forgejo-prune - namespace: ci-runners + namespace: forgejo --- apiVersion: v1 kind: ConfigMap metadata: name: forgejo-prune-scripts - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: prune @@ -166,12 +166,12 @@ data: dind-daemons.sh: | #!/bin/sh # Prune every in-cluster dind daemon, discovered by label. - # Selector: pods with app=forgejo-runner in namespace ci-runners that have a + # Selector: pods with app=forgejo-runner in namespace forgejo that have a # container named `dind`. Nothing here is keyed to a pod name, so a new # dind runner (e.g. the arm64 migration) is pruned the night it appears. set -u - NS=${NAMESPACE:-ci-runners} + NS=${NAMESPACE:-forgejo} CAP_BYTES=${CACHE_CAP_BYTES:-4000000000} CACHE_AGE_H=${CACHE_AGE_H:-72} CONTAINER_AGE_H=${CONTAINER_AGE_H:-48} @@ -263,7 +263,7 @@ apiVersion: batch/v1 kind: CronJob metadata: name: forgejo-runner-prune - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: prune @@ -343,7 +343,7 @@ spec: command: ["/bin/sh", "/scripts/dind-daemons.sh"] env: - name: NAMESPACE - value: ci-runners + value: forgejo - name: CACHE_CAP_BYTES value: "4000000000" - name: CACHE_AGE_H diff --git a/apps/base/forgejo/runner-amd64.yaml b/apps/base/forgejo/runner-amd64.yaml index 0b562c5..459971e 100644 --- a/apps/base/forgejo/runner-amd64.yaml +++ b/apps/base/forgejo/runner-amd64.yaml @@ -2,7 +2,7 @@ apiVersion: v1 kind: PersistentVolumeClaim metadata: name: forgejo-runner-amd64 - namespace: ci-runners + namespace: forgejo spec: accessModes: - ReadWriteOnce @@ -15,7 +15,7 @@ apiVersion: apps/v1 kind: Deployment metadata: name: forgejo-runner-amd64 - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner arch: amd64 @@ -25,12 +25,6 @@ spec: matchLabels: app: forgejo-runner arch: amd64 - # RWO PVC: never two pods on one data-root. Consequence to know before you - # touch this template: a rollout SIGKILLs the job container of any run in - # flight, and Forgejo then reports that run as a plain failure with the log - # cut off mid-step (no `exitcode` line) — seen as a 14 min "failing" push on - # sirius/sirius-growth, card t_29249bf0. Land template changes while the - # runner is idle. strategy: type: Recreate template: @@ -42,9 +36,7 @@ spec: nodeSelector: kubernetes.io/hostname: siriussec securityContext: - # Group on the data volume; matches the runner's gid so the cache dir - # stays writable even before fix-data-perms re-owns it. - fsGroup: 1000 + fsGroup: 0 initContainers: - name: register image: alex3305/forgejo-runner-dind:13-dind-rootless-28 @@ -76,42 +68,6 @@ spec: subPath: amd64.toml - name: data mountPath: /data - # The runner container runs as uid 1000 (the image's own user) and needs - # to read its registration and write the actions cache on this PVC. - # Both were created by root before this change, so re-own them once per - # start. Scoped on purpose: a recursive chown of the whole PVC would - # walk the dind data-root (tens of GB on the Pi). - - name: fix-data-perms - image: docker:27-dind - imagePullPolicy: IfNotPresent - securityContext: - # root is needed for exactly one thing: chown of the PVC. - runAsUser: 0 - command: - - sh - - -c - - | - set -e - chown 1000:1000 /data - # Re-own the trees the runner itself writes: runner.ini, the act - # cache (cache/) and the action-repo checkout cache (.cache/act/). - # The re-own MUST be recursive. A top-level owner check is exactly - # what let this through once: /data/.cache was already 1000 while - # the git packs inside it were still root:root from the pre-uid-1000 - # runner, so the guard skipped the one file that mattered and every - # job died in actions/checkout before any step ran: - # open /data/.cache/act/actions-checkout@v4/.git/objects/pack/ - # pack-.pack: permission denied - # (card t_29249bf0: 3 s red X, zero steps.) A few thousand small - # files; the dind data-root (/data/docker, tens of GB) stays - # root-owned and is deliberately not walked. - for d in /data/cache /data/.cache /data/runner.ini; do - if [ -e "$d" ]; then chown -R 1000:1000 "$d"; fi - done - true - volumeMounts: - - name: data - mountPath: /data containers: - name: dind image: docker:27-dind @@ -136,14 +92,12 @@ spec: # layer uploads >~100MB, so in-cluster pushes are the reliable # path for large images. dockerd --host=unix:///var/run/docker.sock --tls=false --mtu=1420 \ - --group 1000 \ --insecure-registry=forgejo.forgejo.svc.cluster.local:3000 & pid=$! i=0 while [ "$i" -lt 30 ]; do - # Readiness only: ownership is set by `dockerd --group 1000` - # (socket 0660 root:1000) so the runner's uid 1000 can use it. if [ -S /var/run/docker.sock ]; then + chmod 666 /var/run/docker.sock break fi i=$((i+1)) @@ -151,31 +105,6 @@ spec: done wait "$pid" securityContext: - # Cannot be dropped on these nodes. Verified live 2026-11-27 - # (card t_2bbe34a8): a pod with `privileged: false` cannot host a - # container runtime in this cluster, at three independent points: - # 1. dind's own containers need CAP_SYS_ADMIN: runc mounts a fresh - # procfs per container, and without the capability the daemon - # fails with `mount src=proc ... operation not permitted`. - # 2. kubelet mounts /sys/fs/cgroup read-only for non-privileged - # pods, so dockerd cannot create /sys/fs/cgroup/docker - # ("read-only file system") and no container can start. - # 3. rootless dind (docker:27-dind-rootless) dies earlier: a - # nested user namespace cannot mount procfs because the pod's - # /proc is masked (kernel mount_too_revealing), and - # procMount: Unmasked is only accepted with hostUsers: false — - # where newuidmap cannot map subuids and /dev/net/tun cannot be - # created (mknod is refused in a userns pod, and hostPath is - # forbidden under Pod Security baseline). - # What this file *does* remove: the runner's uid 0, the privileged - # flag on CI job containers (runner configmap), and the old - # chmod-666 socket race. - # - # Consequence: this Deployment cannot live in namespace - # `forgejo` (PSA enforce: baseline there). All three runners, - # their PVCs and the prune CronJob live in `ci-runners`, - # which enforces PSA at `privileged` by design — keep that - # namespace free of anything but this CI capsule. privileged: true volumeMounts: - name: dind-run @@ -197,12 +126,14 @@ spec: - name: runner image: code.forgejo.org/forgejo/runner:5.0.1 imagePullPolicy: IfNotPresent + # The image runs as uid 1000. The dind socket is created 660 + # root:docker and the one-shot chmod 666 in the dind container can + # race a dockerd restart, after which the runner crashloops on + # "permission denied ... /var/run/docker.sock" (its wait loop only + # checks that the socket exists). Running the runner as root removes + # the dependency on that race; it is the uid the dind setup assumes. securityContext: - # The image's own user. No root needed: the dind socket is 0660 - # root:1000 (`dockerd --group 1000`) and fix-data-perms owns the PVC - # as 1000:1000, so the actions cache is writable. - runAsUser: 1000 - runAsGroup: 1000 + runAsUser: 0 command: - sh - -c diff --git a/apps/base/forgejo/runner-arm64.yaml b/apps/base/forgejo/runner-arm64.yaml index 5eac736..bb66a61 100644 --- a/apps/base/forgejo/runner-arm64.yaml +++ b/apps/base/forgejo/runner-arm64.yaml @@ -2,7 +2,7 @@ apiVersion: apps/v1 kind: Deployment metadata: name: forgejo-runner-arm64 - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner arch: arm64 @@ -12,12 +12,7 @@ spec: matchLabels: app: forgejo-runner arch: arm64 - # RWO PVC: never two pods on one data-root. Consequence to know before you - # touch this template: a rollout SIGKILLs the job container of any run in - # flight, and Forgejo then reports that run as a plain failure with the log - # cut off mid-step (no `exitcode` line) — seen as a 14 min "failing" push on - # sirius/sirius-growth, card t_29249bf0. Land template changes while the - # runner is idle. + # RWO PVC: never two pods on one data-root. strategy: type: Recreate template: @@ -28,10 +23,6 @@ spec: spec: nodeSelector: kubernetes.io/hostname: rpi - # Group on the data volume; matches the runner gid so the actions cache - # stays writable after fix-data-perms re-owns it. - securityContext: - fsGroup: 1000 tolerations: - key: dedicated operator: Equal @@ -40,44 +31,6 @@ spec: # No supplementalGroups: there is no host docker socket and no host # docker gid to match any more. The only daemon this runner talks to is # the privileged `dind` sidecar below. - initContainers: - # The runner container runs as uid 1000 (the image's own user) and needs - # to read its registration and write the actions cache on this PVC. - # Both were created by root before this change, so re-own them once per - # start. Scoped on purpose: a recursive chown of the whole PVC would - # walk the dind data-root (tens of GB on the Pi). - - name: fix-data-perms - image: docker:27-dind - imagePullPolicy: IfNotPresent - securityContext: - # root is needed for exactly one thing: chown of the PVC. - runAsUser: 0 - command: - - sh - - -c - - | - set -e - chown 1000:1000 /data - # Re-own the trees the runner itself writes: runner.ini, the act - # cache (cache/) and the action-repo checkout cache (.cache/act/). - # The re-own MUST be recursive. A top-level owner check is exactly - # what let this through once: /data/.cache was already 1000 while - # the git packs inside it were still root:root from the pre-uid-1000 - # runner, so the guard skipped the one file that mattered and every - # job died in actions/checkout before any step ran: - # open /data/.cache/act/actions-checkout@v4/.git/objects/pack/ - # pack-.pack: permission denied - # (card t_29249bf0: 3 s red X, zero steps.) A few thousand small - # files; the dind data-root (/data/docker, tens of GB) stays - # root-owned and is deliberately not walked. - for d in /data/cache /data/.cache /data/runner.ini; do - if [ -e "$d" ]; then chown -R 1000:1000 "$d"; fi - done - true - volumeMounts: - - name: data - mountPath: /data - containers: # In-pod Docker daemon. Same shape as forgejo-runner-amd64: privileged, # socket on an emptyDir shared with the runner, data-root on the PVC. @@ -105,13 +58,12 @@ spec: # so without this `docker push 10.10.0.1:5000/...` from a job # fails with "server gave HTTP response to HTTPS client". dockerd --host=unix:///var/run/docker.sock --tls=false --mtu=1420 \ - --group 1000 \ --insecure-registry=10.10.0.1:5000 & pid=$! i=0 while [ "$i" -lt 30 ]; do - # Readiness only; ownership is set by dockerd --group 1000. if [ -S /var/run/docker.sock ]; then + chmod 666 /var/run/docker.sock break fi i=$((i+1)) @@ -119,25 +71,6 @@ spec: done wait "$pid" securityContext: - # Cannot be dropped on these nodes. Verified live 2026-11-27 - # (card t_2bbe34a8): a pod with `privileged: false` cannot host a - # container runtime in this cluster, at three independent points: - # 1. dind's containers need CAP_SYS_ADMIN (runc mounts a fresh - # procfs per container). - # 2. kubelet mounts /sys/fs/cgroup read-only for non-privileged - # pods, so dockerd cannot create /sys/fs/cgroup/docker - # ("read-only file system") — no container can start. - # 3. rootless dind (docker:27-dind-rootless) dies earlier: a - # nested user namespace cannot mount procfs because the pod's - # /proc is masked (kernel mount_too_revealing), and - # procMount: Unmasked is only allowed with hostUsers: false, - # where newuidmap cannot map subuids, and /dev/net/tun cannot - # be created (mknod is refused inside a userns pod; hostPath - # is forbidden by Pod Security baseline). - # What *is* removed: privileged job containers (runner configmap), - # the runner's uid 0, and the host docker socket (no hostPath). - # This pod lives in namespace ci-runners (enforce: - # privileged), not forgejo (enforce: baseline) — see runner-amd64.yaml. privileged: true volumeMounts: - name: dind-run @@ -165,12 +98,13 @@ spec: # job in onionwire/siriusdevops-contact. image: code.forgejo.org/forgejo/runner:5.0.1 imagePullPolicy: IfNotPresent + # uid 1000 in this image vs a `660 root:docker` dind socket: the dind + # container's one-shot chmod 666 can race a dockerd restart and the + # runner's wait loop only checks that the socket exists, so it would + # crashloop on "permission denied". Running as root is what the amd64 + # runner proved deterministic (2eff85b). securityContext: - # The image's own user. No root needed: the dind socket is 0660 - # root:1000 (`dockerd --group 1000`) and fix-data-perms owns the PVC - # as 1000:1000, so the actions cache is writable. - runAsUser: 1000 - runAsGroup: 1000 + runAsUser: 0 command: - sh - -c diff --git a/apps/base/forgejo/runner-configmap.yaml b/apps/base/forgejo/runner-configmap.yaml index c223201..fd489fb 100644 --- a/apps/base/forgejo/runner-configmap.yaml +++ b/apps/base/forgejo/runner-configmap.yaml @@ -2,7 +2,7 @@ apiVersion: v1 kind: ConfigMap metadata: name: forgejo-runner-config - namespace: ci-runners + namespace: forgejo data: arm64.toml: | log: @@ -26,12 +26,7 @@ data: enabled: true dir: /data/cache container: - # CI job containers run unprivileged. They still get the dind socket (a - # bind mount in `options` below), which is what the build/deploy - # workflows actually need; nothing in them needs extra capabilities. - # This was `true` until card t_2bbe34a8 (audit F6): a privileged job - # container inside a privileged dind was node root twice over. - privileged: false + privileged: true # No docker_host here: setting it makes the runner inject the socket bind # into the job container itself, which collides with the explicit # -v /var/run/docker.sock in options ("Duplicate mount point"). The @@ -74,28 +69,16 @@ data: enabled: true dir: /data/cache container: - # CI job containers run unprivileged. They still get the dind socket (a - # bind mount in `options` below), which is what the build/deploy - # workflows actually need; nothing in them needs extra capabilities. - # This was `true` until card t_2bbe34a8 (audit F6): a privileged job - # container inside a privileged dind was node root twice over. - privileged: false + privileged: true # Same injection as arm64.toml: the job container is node:20-bullseye, # which has no docker CLI and no buildx, and deploy-site.yml needs both. - # Both come from the dind sidecar's own filesystem. - # - # NO --memory/--memory-swap on this runner: under Kata the guest cgroup - # root is `domain threaded` (only cpuset/cpu/pids are delegated), so - # dockerd cannot apply a memory limit to a job container and every job - # dies at `docker run` with - # unable to apply cgroup configuration: cannot enter cgroupv2 - # "/sys/fs/cgroup/docker" with domain controllers -- it is in threaded mode - # (measured 2026-11-27, run 1442). The bound is now the microVM itself: - # the dind container's 2Gi limit sizes the VM, so a runaway job still - # cannot touch the Pi's memory, and an OOM kills the VM (visible pod - # restart) instead of one job container. Jobs on the runc runners keep - # their limits. - options: -v /usr/local/bin/docker:/usr/bin/docker:ro -v /usr/local/libexec/docker/cli-plugins:/usr/local/lib/docker/cli-plugins:ro -v /var/run/docker.sock:/var/run/docker.sock + # Both come from the dind sidecar's own filesystem. binfmt/QEMU is + # registered kernel-globally on the Pi (the POC pod's + # /proc/sys/fs/binfmt_misc was empty yet an amd64 build ran as x86_64), + # so the `--platform linux/amd64` cross build works inside the pod. + # --memory caps the job container only (sibling `docker run` containers a + # workflow spawns are outside the runner's control). + options: -v /usr/local/bin/docker:/usr/bin/docker:ro -v /usr/local/libexec/docker/cli-plugins:/usr/local/lib/docker/cli-plugins:ro -v /var/run/docker.sock:/var/run/docker.sock --memory 3g --memory-swap 3g valid_volumes: - "**" @@ -115,12 +98,7 @@ data: enabled: true dir: /data/cache container: - # CI job containers run unprivileged. They still get the dind socket (a - # bind mount in `options` below), which is what the build/deploy - # workflows actually need; nothing in them needs extra capabilities. - # This was `true` until card t_2bbe34a8 (audit F6): a privileged job - # container inside a privileged dind was node root twice over. - privileged: false + privileged: true # No docker_host: it injects the socket bind into the job container, # which collides with the explicit -v /var/run/docker.sock in options # ("Duplicate mount point"). The options bind is the deliberate choice. diff --git a/apps/base/forgejo/runner-deploy-arm64.yaml b/apps/base/forgejo/runner-deploy-arm64.yaml index 0ee54ac..3d4bc4f 100644 --- a/apps/base/forgejo/runner-deploy-arm64.yaml +++ b/apps/base/forgejo/runner-deploy-arm64.yaml @@ -19,7 +19,7 @@ apiVersion: apps/v1 kind: Deployment metadata: name: forgejo-runner-deploy-arm64 - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner arch: arm64 @@ -30,12 +30,6 @@ spec: matchLabels: app: forgejo-runner role: deploy - # RWO PVC: never two pods on one data-root. Consequence to know before you - # touch this template: a rollout SIGKILLs the job container of any run in - # flight, and Forgejo then reports that run as a plain failure with the log - # cut off mid-step (no `exitcode` line) — seen as a 14 min "failing" push on - # sirius/sirius-growth, card t_29249bf0. Land template changes while the - # runner is idle. strategy: type: Recreate template: @@ -52,16 +46,6 @@ spec: operator: Equal value: network effect: PreferNoSchedule - # Kata microVM (apps/base/forgejo/kata-runtimeclass.yaml, installed on rpi - # only). The pod is still `privileged: true` — a nested dockerd needs - # SYS_ADMIN+NET_ADMIN in the spec and PSA baseline forbids those two, so - # `ci-runners` stays at enforce: privileged (docs/pod-security.md). Kata - # changes the *consequence*: that privilege is VM root, not rpi's host - # root. Rollback of this whole experiment is this one field. - runtimeClassName: kata-qemu - # Group on the data volume, matching the runner gid (see fix-data-perms). - securityContext: - fsGroup: 1000 initContainers: # Registration guard, NOT a registration step. The runner's identity # (`runner.ini`, action_runner id 14 / uuid a41aad73-…) is copied onto @@ -89,41 +73,6 @@ spec: volumeMounts: - name: data mountPath: /data - # The runner container runs as uid 1000 (the image's own user) and needs - # to read its registration and write the actions cache on this PVC. - # Both were created by root before this change, so re-own them once per - # start. Scoped on purpose: a recursive chown of the whole PVC would - # walk the dind data-root. - - name: fix-data-perms - image: docker:27-dind - imagePullPolicy: IfNotPresent - securityContext: - runAsUser: 0 - command: - - sh - - -c - - | - set -e - chown 1000:1000 /data - # Re-own the trees the runner itself writes: runner.ini, the act - # cache (cache/) and the action-repo checkout cache (.cache/act/). - # The re-own MUST be recursive. A top-level owner check is exactly - # what let this through once: /data/.cache was already 1000 while - # the git packs inside it were still root:root from the pre-uid-1000 - # runner, so the guard skipped the one file that mattered and every - # job died in actions/checkout before any step ran: - # open /data/.cache/act/actions-checkout@v4/.git/objects/pack/ - # pack-.pack: permission denied - # (card t_29249bf0: 3 s red X, zero steps.) A few thousand small - # files; the dind data-root (/data/docker, tens of GB) stays - # root-owned and is deliberately not walked. - for d in /data/cache /data/.cache /data/runner.ini; do - if [ -e "$d" ]; then chown -R 1000:1000 "$d"; fi - done - true - volumeMounts: - - name: data - mountPath: /data containers: - name: dind image: docker:27-dind @@ -132,87 +81,30 @@ spec: - sh - -c - | - set -e - # --- Data root: ext4 on a loop device, not the virtiofs mount --- - # Under Kata every Kubernetes volume is a virtiofs share, and - # overlayfs refuses virtiofs as an upperdir ("failed to mount - # overlay: invalid argument"), which leaves Docker on `vfs` - # (layer copies). A loop-backed ext4 image on the PVC restores - # overlay2: measured inside the guest 2026-11-27, Storage Driver - # overlay2, 16 GiB volume, survives pod restarts because the image - # file lives on the claim. Losing it only costs a cold image cache. - IMG=/data-docker/kata-ext4.img - [ -f "$IMG" ] || fallocate -l 16G "$IMG" - [ -b /dev/loop0 ] || mknod /dev/loop0 b 7 0 - if ! losetup -a | grep -q "$IMG"; then - losetup /dev/loop0 "$IMG" - fi - blkid /dev/loop0 | grep -q 'TYPE="ext4"' || mkfs.ext4 -q -F -L katadocker /dev/loop0 - mount /dev/loop0 /var/lib/docker - echo "dind data-root: $(df -hT /var/lib/docker | tail -1)" # --insecure-registry: the Pi registry is plain HTTP on the WG # hub IP. Docker only treats 127.0.0.0/8 as insecure by default, # so without this `docker push 10.10.0.1:5000/...` from a job # fails with "server gave HTTP response to HTTPS client". dockerd --host=unix:///var/run/docker.sock --tls=false --mtu=1420 \ - --group 1000 \ --insecure-registry=10.10.0.1:5000 & pid=$! i=0 while [ "$i" -lt 30 ]; do - # Readiness only: ownership is set by `dockerd --group 1000`. if [ -S /var/run/docker.sock ]; then + chmod 666 /var/run/docker.sock break fi i=$((i+1)) sleep 1 done - # --- binfmt: the deploy cross-builds linux/amd64 under qemu --- - # deploy-site.yml runs `docker buildx build --platform linux/amd64` - # and until now that worked because the Pi HOST kernel had the - # qemu binfmt handlers registered. A Kata pod has its own guest - # kernel, so nothing is registered and the build dies with - # `exec format error` / `buildkit-qemu-x86_64: not found`. - # Registering inside the guest is per-VM state: it must run on - # every pod start. The tonistiigi/binfmt image is cached in the - # data-root after the first start, and the registration uses the - # F flag (interpreter fd is held by the kernel), so the image can - # exit immediately afterwards. - mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc 2>/dev/null || true - if ! grep -q . /proc/sys/fs/binfmt_misc/qemu-x86_64 2>/dev/null; then - i=0 - until docker run --rm --privileged tonistiigi/binfmt --install amd64 >/dev/null 2>&1; do - i=$((i+1)) - if [ "$i" -ge 3 ]; then - echo "WARNING: could not register qemu-x86_64 binfmt; amd64 cross builds will fail" >&2 - break - fi - sleep 3 - done - fi - grep -q . /proc/sys/fs/binfmt_misc/qemu-x86_64 2>/dev/null && - echo "binfmt: qemu-x86_64 registered" || echo "binfmt: NOT registered" >&2 - # Job containers must not start before the daemon AND the - # cross-build emulation are ready; the runner waits on this file. - touch /var/run/dind-ready wait "$pid" securityContext: - # Still required UNDER KATA: the caps a nested dockerd needs - # (SYS_ADMIN for mounts/overlay, NET_ADMIN for docker0/iptables) - # are caps the pod spec must add, and PSA `baseline` forbids both — - # no runtime works around that (measured: sysbox, gVisor, Kata, see - # docs/pod-security.md). What Kata changes is the blast radius: this - # is root inside a QEMU/KVM microVM, with no host namespaces and no - # host kernel, not root on rpi. On a runc runner the same flag is - # host root. privileged: true volumeMounts: - name: dind-run mountPath: /var/run - # The claim holds the loop-backed ext4 image (kata-ext4.img) rather - # than being dockerd's data-root directly: see the startup script. - name: data - mountPath: /data-docker + mountPath: /var/lib/docker subPath: docker resources: # Deliberately smaller than the shared runner's 4Gi. A deploy is two @@ -233,23 +125,15 @@ spec: image: code.forgejo.org/forgejo/runner:5.0.1 imagePullPolicy: IfNotPresent securityContext: - # Image default user. The dind socket is 0660 root:1000 - # (`dockerd --group 1000`) and fix-data-perms owns the PVC as - # 1000:1000, so no root is needed here. - runAsUser: 1000 - runAsGroup: 1000 + runAsUser: 0 command: - sh - -c - | set -e - # Wait for the dind sidecar AND its per-VM extras (loop-backed - # data-root, qemu-x86_64 binfmt) — under Kata both are set up - # inside the guest on every pod start, so the socket alone is not - # "ready". dind touches /var/run/dind-ready last. i=0 - while [ "$i" -lt 90 ]; do - if [ -S /var/run/docker.sock ] && [ -e /var/run/dind-ready ]; then + while [ "$i" -lt 60 ]; do + if [ -S /var/run/docker.sock ]; then break fi i=$((i+1)) @@ -281,17 +165,4 @@ spec: persistentVolumeClaim: claimName: forgejo-runner-deploy-arm64-dind - name: dind-run - # tmpfs on purpose, NOT the default disk-backed emptyDir: under Kata a - # disk emptyDir is a virtiofs share, and a unix socket created on - # virtiofs is visible to the other containers in the pod but - # unconnectable. Measured 2026-11-27: the runner crashlooped on - # `cannot ping the docker daemon ... unix:///var/run/docker.sock` - # although `ls -l` showed the socket `srw-rw---- root:1000`, while the - # dind sidecar's own `docker version` on the same path worked. A - # memory-backed emptyDir is a tmpfs inside the guest, so the socket is - # a real inode the runner and the job containers can both connect to, - # and the existing `-v /var/run/docker.sock` job option keeps working. - # 64Mi holds the socket, the `dind-ready` marker and nothing else. - emptyDir: - medium: Memory - sizeLimit: 64Mi + emptyDir: {} diff --git a/apps/base/forgejo/runner-dind-storage.yaml b/apps/base/forgejo/runner-dind-storage.yaml index 46a6c8c..2d366d5 100644 --- a/apps/base/forgejo/runner-dind-storage.yaml +++ b/apps/base/forgejo/runner-dind-storage.yaml @@ -64,7 +64,7 @@ apiVersion: v1 kind: PersistentVolumeClaim metadata: name: forgejo-runner-arm64-dind - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner arch: arm64 @@ -108,7 +108,7 @@ apiVersion: v1 kind: PersistentVolumeClaim metadata: name: forgejo-runner-deploy-arm64-dind - namespace: ci-runners + namespace: forgejo labels: app: forgejo-runner role: deploy diff --git a/apps/base/forgejo/secret-cluster-backup-ssh.sops.yaml b/apps/base/forgejo/secret-cluster-backup-ssh.sops.yaml deleted file mode 100644 index 6ff53f5..0000000 --- a/apps/base/forgejo/secret-cluster-backup-ssh.sops.yaml +++ /dev/null @@ -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 diff --git a/apps/base/forgejo/secret-forgejo-pg-app.sops.yaml b/apps/base/forgejo/secret-forgejo-pg-app.sops.yaml deleted file mode 100644 index 60eb205..0000000 --- a/apps/base/forgejo/secret-forgejo-pg-app.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:H4walqRkdqsGO3cz,iv:dNH/Nz3J5c7M4e63af8m61Z36yIoNk4amyzdBE8/Pl0=,tag:MHn7hR/XtLnSIwmPgzwEOg==,type:str] - username: ENC[AES256_GCM,data:mEySjuVo1GP9rKo0,iv:IG+GwOj9QuRh72XLjoG/Ho5MToL7g2PPZzziGlGCMvo=,tag:dR/oB5baTxayoHZzCxbBSg==,type:str] -kind: Secret -metadata: - name: forgejo-pg-app - namespace: forgejo -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBrQ29kbmRoYk4vbVlRZ3Fy - SUFCNnRtZDR0aGQvb0p5WXh1a296QXkveUVVCnlrTzBKSXNvNmRTZ0NTVzVSRHF1 - YldwUlZVSld4dHBnQ2xSeUJVVm9LSEkKLS0tIDR1bDFhRGJkM2dUZ0phRGw2Qkxt - a1p2ckF1UDJCQmtMMThrbE1ydGpFODgKbslEW80bDRppJ+ZlBPS4HWbYZ/s+NeCm - ZoH/JkANBSlIJqb1osQDfSnJ6aBOkIGZcmSFR7GznvO1DsO9TaFUVg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:42Z" - mac: ENC[AES256_GCM,data:k+L4q6BRMFWIjKm1MA+TSpSa9yWCN7KX/6US5HU/+cnrM4hIhBdgdLuCSZjgm0A/Ny8L3unGRK0vdtyU8EVSaQItd2PyhGgZpyzkGkbcme/DzT9ylCJtQTfG3r41Xtya8DHgEppeTmvRWFBGtV2rIYpb0+LtvMcyvf0mLs2MS/k=,iv:x+r5X+NNpcW/wsMx1Lv2FibF6IH7bIcxuEKSEen2LEI=,tag:zsUj99VwOig4jzcp4P+cXQ==,type:str] - version: 3.13.3 diff --git a/apps/base/forgejo/secret-forgejo-pull.sops.yaml b/apps/base/forgejo/secret-forgejo-pull.sops.yaml deleted file mode 100644 index 84ba7a2..0000000 --- a/apps/base/forgejo/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:QS5gZUJ0zi3YYSaCpJWSCA/JakeknWmlQ8WVKlyxh2k4zo/Ul33lhH5iQP27Z3ec6FyEtV8TUSdhkq1wGSCF7cRu00ze4qljMuviU35x2Dl5aMc7JEWvRPnypoBYNmTRulPZh5E3GdiR9VUzok643P0igJyHlQBjO8HkLiuZ41Zd7JYordQRPTH4tXlDbiJPEPfkMEyFHY/6XdEEUNv5eIUyb004d1xZccnGaMwliVNBL5xIbJpb4Bza9/Z8NYsq70cmjHH/hFq7uotnSt3B53vPnwf6Rsq9j44i3M0xQjHQf+QYa34mFncHznwxPczLo8wcmKFmZYkNZNXxzc/NryeC4w950GUZ+cSO1UKLhS8IGIal8S05IWmeIuda1k9V,iv:AN7Fn/JmSYqiERsqneSOMeV3kMRGcawgV4Y9iJrjF7E=,tag:XwEZy+ULOGiFTW1diodMgg==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: forgejo -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBjTmlMUDZOdnc1U3RGM1Jh - TTNmU3pRV3M1Y2lkNitqMkE0WHRZdXNOSlRJCnZ2eDB3ZXpvWDR6dHJBeWJpdElI - a24xelp4dGluNXNGUzJYOWlPNzdwM0EKLS0tIGJuUk1CUEEvZlVWYlFKTnVwWVRS - M2o5LzBJSEpXaklKc0ZMZ0FDa3NlV0UKmNVnlKd/Xqbisox3hrAeK45sbLJW5yS3 - Y6KfweCLwk6edQ9YflAvmk2FWVi0PIMdmloObXVSvB/ZY+jeLlK4lA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-12-04T05:28:22Z" - mac: ENC[AES256_GCM,data:goW5PeSFtc0ga5gTDAZpYFQ8xBTXA2dgOomUK9t9GX3T7nswhu6fmfXJ2zjqyYLKJ5wnVEY4pvwx9RThEpU0khcP8iBqyrzUvIEXUsoQ5lTegRxgyuowPKWBkQcrJPx5GEgHSJr5J6XlDKbbCeOW0SxnerPhpJ03ueh3yULPgKw=,iv:Z/hm3jpUXzWeabPXuecuAIm+bemjluy/xjas8dg7bUY=,tag:3coZnG6p2v6ZT0raG7b1IQ==,type:str] - version: 3.13.3 diff --git a/apps/base/forgejo/secret-forgejo-runner-amd64-token.sops.yaml b/apps/base/forgejo/secret-forgejo-runner-amd64-token.sops.yaml deleted file mode 100644 index 51b86b2..0000000 --- a/apps/base/forgejo/secret-forgejo-runner-amd64-token.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - token: ENC[AES256_GCM,data:TT4kDSMmP259CxpdexoWaHlaBl5hOnYqUDHTPW2hBqiyrvvaCDNmLtVeYCpekdljTTNGE9NhOoA=,iv:Ynh6mW0xb/O2JYKBG/AtWJoAkJT2Z2hWqTaRL7zA+ds=,tag:nhO9I6WNb2mL3DxvQtZROg==,type:str] -kind: Secret -metadata: - name: forgejo-runner-amd64-token - namespace: ci-runners -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBseXNtekZHaUdLbnJTUGVo - cDYxdVBSVWdNU2x3amYwZHVVeTYyS0Y2eER3CnMxZmRiaGQycnZwMzMzV1lLUnBW - RXozMkRKdmlCZ0pWdTN4RlhrZWY5UzgKLS0tIG45b2puajRzVHFPa1U5Q0ltc0Iw - V0YrbFlHdVFQR3lPR3lYZkUzc2dXaW8KLLBVWz48aA3NzxTPXun2Eu7+pTnv0BB4 - k84ePj2d6bMe64BQ9K9q1uieW/LQuXtwV0lMbfSXw5GAPCxBzs6vCA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T06:18:39Z" - mac: ENC[AES256_GCM,data:+hlch3XHEHTl+PUFjAjIL/cJdGIJBtwlA3gldWYpUVtsKOPJ2Vfi5DUfwodvpTCSjZYTTipR4Kz2BoAhQ9y+vVMGfTKko/1fA5UMjf74uiCXhur0B2vyAcFUn79xrZql/J6q7DmkufHveS7baNd5YRQSLV6Catm70IkIL81o1/Q=,iv:6esPz9ggtY0+5NedEfET0NfX39xw5fwokVNQB3ak24s=,tag:+5WduOvKK35AV65auauM2Q==,type:str] - version: 3.13.3 diff --git a/apps/base/forgejo/secret-forgejo-runner-deploy-arm64-token.sops.yaml b/apps/base/forgejo/secret-forgejo-runner-deploy-arm64-token.sops.yaml deleted file mode 100644 index 7fe87d2..0000000 --- a/apps/base/forgejo/secret-forgejo-runner-deploy-arm64-token.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - token: ENC[AES256_GCM,data:e30FrA4NWWy3dSIL1cuzYIWRzcakdC0s3ij9HjoLnkeMEznrg3Y50QgQlnKwilF+DpEdWYmVJRI=,iv:ZKFHDaC0WJF2fFazCb0Z/QhAEk1HIdB+puaOqqCqo9E=,tag:FGSd0IVL16rJr94lBAnVTA==,type:str] -kind: Secret -metadata: - name: forgejo-runner-deploy-arm64-token - namespace: ci-runners -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBzbzJicHJ4V0RFc2Q0ZGpT - Z3ZGVHgxbnpUOXZZUHhydHBVRnlJUFNFbURrClJzRWVFaUhKdXN1dHlPT2o0MHI5 - RjM3SHpTQ29GOUlxTC9GNnhickhZOWMKLS0tIFhwSjlIbWNWMy80R1BBVWc0NUtH - cU5VVGV1YjJSZXdhZ0NCbk9PV2I4WmsKcmyzdWfyD8gMzr/tmuTZZPQILB1HBMTT - /6oxp31Xar+mCMF4OoBZaDb7y3Y1Pn2Rb7L2uu5mfgPgmpN3y+re4Q== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T06:18:39Z" - mac: ENC[AES256_GCM,data:/SrVMnWWPRDMJYCWcGsmyIp3VuBBEw1pzKSHCty/ZUuqlE4IrvAaQpisAF8ByMsOBTc80JfRjaiFYr5nu1L7jlTDbivPHXAc4CgLMX3FGtvqTgrmPCwvjUV2x0kK6pSNgo/AuDmFYCh+UKqyNEToi4uDnqtiXwy91fsfvg60fLw=,iv:S3SOMKy6ZYWdYKC8DZs4mdQhPTMv/bt+d8+UO5cKOLI=,tag:YvHkNscDXMutN5BFekrfow==,type:str] - version: 3.13.3 diff --git a/apps/base/metabase/kustomization.yaml b/apps/base/metabase/kustomization.yaml index 5eff3ea..aaf2916 100644 --- a/apps/base/metabase/kustomization.yaml +++ b/apps/base/metabase/kustomization.yaml @@ -2,16 +2,9 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - namespace.yaml - # Secret metabase/pg-app (kubernetes.io/basic-auth) is reconciled by Flux from - # secret-pg-app.sops.yaml and sorts before this Cluster applies — CNPG's - # initdb reads it. It is hand-made (not operator-generated), so it is in git. + # Secret metabase/pg-app (kubernetes.io/basic-auth) is created out of band + # before this Cluster applies — CNPG's initdb reads it. - cluster.yaml - deployment.yaml - service.yaml - httproute.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-pg-app.sops.yaml - - secret-metabase-admin.sops.yaml - - secret-metabase-data-source-creds.sops.yaml diff --git a/apps/base/metabase/namespace.yaml b/apps/base/metabase/namespace.yaml index cd0ab9b..763c274 100644 --- a/apps/base/metabase/namespace.yaml +++ b/apps/base/metabase/namespace.yaml @@ -3,10 +3,4 @@ kind: Namespace metadata: name: metabase labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: metabase diff --git a/apps/base/metabase/secret-metabase-admin.sops.yaml b/apps/base/metabase/secret-metabase-admin.sops.yaml deleted file mode 100644 index a2923d0..0000000 --- a/apps/base/metabase/secret-metabase-admin.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - email: ENC[AES256_GCM,data:rSxf/qzkNLOYvRhqRxvuFi5SbwH5BdiAh3qUbV5ynIg=,iv:JIOnFqnGCcCgsba36zLU7lAAp43KM9PWRQvlrVmnYfE=,tag:YoKBUG4V0j8nN+/9vCXUpw==,type:str] - password: ENC[AES256_GCM,data:2rIdkTBMe4eK6I6NcGOf2orAxq4=,iv:WlKSOxWd/8I+cWCWCaOZ3WrlhswHUO9RvoTM1lhKFos=,tag:SDLueoH6MtLuxftOtfA4Yg==,type:str] -kind: Secret -metadata: - name: metabase-admin - namespace: metabase -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBlMVUzSnlrZ1FoYWxRVkdm - a3VWTVhOQmlDUmpvT0ZQSjRlaVAxNkxPMWpjCmMvNE1QNzRzdFdqa2k3RU9BNC9N - NFowc1JPVE5HOVA1cTR3TUx6Zi9CWWMKLS0tIFo3UzBJS0c5ZGFNN3pXSzJaZXdw - cThCcDBSRTg1RUpGWi8xR2tacHJySGcKrR7IwYj6xSPVRpo/Gh4QtEmzvaKpQIP3 - kdMqC0JjssYyPa6Ma05WeSwPJc4XYbnJvSdZ30oKCPz/932DqezjEQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:uvinNP0pa9eCvvS369kLdO3Q+ndyjntl9nIeub9ELqcbjmc73PQ9I3ZKGHUp0l5vs3CXHdcs1cj1CPW60cg1W7IM7/vc+9X5pcV3Lm7W16HkUd5HUGeVQ4esvTuIuKbNL3q7RlRJcV8VcAuBy5e1u8RP4q2DgByYFcJHgDO+i7c=,iv:8+VDwUD7z0GN5h/myEAhMxuFQiCqQyCqd4hACzpjF/A=,tag:rUcUXMesFafj+gNfk9ptOQ==,type:str] - version: 3.13.3 diff --git a/apps/base/metabase/secret-metabase-data-source-creds.sops.yaml b/apps/base/metabase/secret-metabase-data-source-creds.sops.yaml deleted file mode 100644 index b85fcf7..0000000 --- a/apps/base/metabase/secret-metabase-data-source-creds.sops.yaml +++ /dev/null @@ -1,34 +0,0 @@ -apiVersion: v1 -data: - forgejo-dbname: ENC[AES256_GCM,data:gmo/OBPxeaP9Fipp,iv:Ox4X0Rarty34CIqGCjq8BEKWtqnHl6HYhg5xCMcJWTE=,tag:/B/acow8oHArOzUCCXN83A==,type:str] - forgejo-host: ENC[AES256_GCM,data:SV7TR0efatA7tEoXWxYIvFAusxvzQ+we8AUPgaBbWOyxc3ELNSCIGOUT+f4=,iv:FxusrKEyCO9QnHhA5eTGRZ2a7dBLBJvvp28E1juRRG0=,tag:jGNv9x6IJBx+iouX4Uou5w==,type:str] - forgejo-password: ENC[AES256_GCM,data:PO6aePZCvedhgNOfuQqGevdrTh1cfTdXYf+Rdexb/uVBSnWTkL6gIg==,iv:T+l5cf/yilZG4Z0tnnHhsftOboQXCBLASKJimh2LUbc=,tag:Uw2vPOExu2D9HDWXSu3iPg==,type:str] - forgejo-port: ENC[AES256_GCM,data:F7H6ChWTeAY=,iv:YUdaHOFEiEz7ZeIyfeC1VWTFQNNoIGaZrmPwlzqMVJs=,tag:l6qT/AWoIIqTZ40Pc9lw9A==,type:str] - forgejo-sslmode: ENC[AES256_GCM,data:BU3vfFVDLkuTZV3E,iv:kDmERO+Gl6D9bX7rkJg6U9Z+g+EKKLlZ7wIBr2VYfLM=,tag:yjcqdBXhJrrU/FJ/Nf6+YA==,type:str] - forgejo-user: ENC[AES256_GCM,data:aJPzpcz5u3Sh1RhcQK3qog==,iv:aodz6CpcBSQL9fgdEJIg69iZHoYc3OCSExG5HeXILjE=,tag:CxAUC7WxS5QLEhY3lVw9qg==,type:str] - portal-dbname: ENC[AES256_GCM,data:0Ti0JmAoS6Y=,iv:qIcLJlZERTwgIOepcBlnXmOgCg65RGXfyC46I9Fovgk=,tag:8RxJYWHrV/vLWSz05Ac9vw==,type:str] - portal-host: ENC[AES256_GCM,data:h6tPmzff8EJ8Ql+WQYOVrEPwQRob1+HKCjLQMsUnLgMSY2+f60dMDz7hLnrUmHFPxxvoJgU7CoM=,iv:et5rzeL4gJHbPCGZ7kQUuM/QP7oJFe9Q+P6POvg/A8E=,tag:nRI8FfVZ390tXhHTGHROCg==,type:str] - portal-password: ENC[AES256_GCM,data:DrZWsGK/f85EHAPepblr/hBPA/dihnz1Kn3bJzYC3gVxgpAcH+dMMw==,iv:hu/d9jTn2vbY27/R47PhA+WofZlT+wyXH26XHnzNMmQ=,tag:VsaO0yzgq98XUicoHZx78A==,type:str] - portal-port: ENC[AES256_GCM,data:SVCVoBJYfS0=,iv:eX6Cs9A2rcqNNFk9K98rBUc3rmwros0TUSOJSm845HI=,tag:BbUr0/piTIEnlU4nqnpZZw==,type:str] - portal-sslmode: ENC[AES256_GCM,data:7ubXQi4spO0NfIgu,iv:2cRu2i3wkMH/iDqn7n83GFFQZWI4OiVoxX+tYDUA5b4=,tag:6gRNiqkNTCOnjjpFQp1EHw==,type:str] - portal-user: ENC[AES256_GCM,data:HUfMGD0WAvmJtJ6JuLH6pA==,iv:Mk8H1L+MJQaog2nqLjT2mMOHa1vglRBq+c/wf+lZEuA=,tag:QzMABZMDoTtI31+2qj+aBA==,type:str] -kind: Secret -metadata: - name: metabase-data-source-creds - namespace: metabase -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBkWmJjUXJRNWp3dXo4TXdG - YnlWWW9GZEo0TVdDOFdNTkhhZDM5S3dENWk0CkErU1AxbkFkNEFXUDRvY0l0RS95 - RndhcXhCWmE3RmhhYXpkWUR5ci9TWlkKLS0tIDFWUFlpWEZlWnljNENwakY1cGxl - ekNHcFRiOCtLME42ZXlxbzY3cjZSZlEKLnBl2Itg/66k3jVj9qf7mw4LNa2e1nvp - ANamRxri3UhgVPH6n7E8avoxhzcPmtk313ySDM7Ooi5+wu7naAP2MA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:TsWeIy/VbxnlxtWBFv4vF2lY0CPPO7eJlSRBFnEDmN3nLkj/IZ4/4BC7UeHsw+fETgU26qq/PGc547rR98qYwcDZvT0OwQRrB1Eqdx9P3673tXrxU4Wy5mvICQoSHFjKqLZ/k/fWawudlG4/fgHhHScTcNDZ+iaxtNcc43Evhmg=,iv:fOLCtNDfiUPCgZL9SYO6YxdMOSJZbtW8WdxJHGH7AEY=,tag:gcJDXghgLSqxu6YkBgpA7Q==,type:str] - version: 3.13.3 diff --git a/apps/base/metabase/secret-pg-app.sops.yaml b/apps/base/metabase/secret-pg-app.sops.yaml deleted file mode 100644 index fd4afd8..0000000 --- a/apps/base/metabase/secret-pg-app.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:C/H4TxLcON+WTr8r0mkhsW0WEdNCFgwcpMUj1BxkDN1R++OYQnqlnQ==,iv:9h/QMnIaZH/gG8sWd1m8VYvwg+LG0L68aEhtMt93ww0=,tag:ReqAmk3Rpo0Fuak712PFUQ==,type:str] - username: ENC[AES256_GCM,data:5p+BVEPC2CElDfdw,iv:qSs3WIvW6agduscSpEinigwnbjLQKY1BcvEK5wTFyic=,tag:t4qnFK/+r2AcFde05XmoBg==,type:str] -kind: Secret -metadata: - name: pg-app - namespace: metabase -type: kubernetes.io/basic-auth -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBIbjlkSnBvQnZOaDFQMVJ0 - RnFPVzJORmNIZVVGMk91YTFjK1g4OTgrS0MwCkNOZnpLOHpESnV0RTdEci9BV2VX - cVMwaXhyT1dkNmFoL085L0N2NFRXa28KLS0tIFQ5dXROejd2OHNMZWtXR3o1dHZu - TldYQ3BLTWMvQnJKVytFRXVtd1JYb00KmURFaB8phn+mYhsO+nsqb6jvNkPB/ooe - 5kj8FJghPsuhPmx+rvm3VMdLlkKLMKFANz594y4QPgakIQh7nGBCgA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:J+e0VKWtFYJnk4XtP70ILnqKKf9TgsS75bExpFWum3zO0Pc3bgx4jQxlSZ+2k7mUnh8UE8Fhttr30mkDBubl/qDETsLtlJWuhdu7uA1att78uEUYG8STZQxN3x51SIoS/Qr8n4tn+wNtVp1Blr2BMNX5f8galhGhBbBO7rc3q1A=,iv:dowiHrhfGuX4LIisa+AhM4XPYlBmUUX3dM9hewhEAC4=,tag:/UwVOIFFUExi8EKiu8kvbA==,type:str] - version: 3.13.3 diff --git a/apps/base/netsec/collect.sh b/apps/base/netsec/collect.sh index 7021d25..363ea9f 100644 --- a/apps/base/netsec/collect.sh +++ b/apps/base/netsec/collect.sh @@ -11,18 +11,8 @@ # beacon/exfil signal). Intra-cluster trace ACK chatter is discarded. # # Bounds (hard, enforced here and not by a follow-up card): -# * the file being appended right now is plain `flows--.jsonl`, so a -# reader always has exactly one file to tail; -# * on rotation the just-closed file is gzip'd to `flows--.jsonl.gz` -# (temp name + atomic rename, so a reader never sees a half-written archive); -# * <= MAX_FILES *plain* flows-*.jsonl (live file + any leftover from a restart); -# * <= MAX_TOTAL_BYTES for the WHOLE directory, archives and in-flight .tmp -# included; oldest deleted first. -# Measured 2026-11-27 on siriussec: 3.1-4.3 MB/min (4.5-6.2 GB/day) of JSONL -# compression at 18.5x (level 9, whole closed files), so the 960 MiB byte bound -# holds 72-100 h of flows (72.6 h at the 6.2 GB/day CI-burst rate, 92-100 h at -# the sustained rate). The byte bound is the binding one: MAX_FILES must NOT be -# applied to the archives, or retention collapses back to a few hours. +# <= MAX_FILES files, <= MAX_TOTAL_BYTES total, oldest deleted first. +# MAX_FILES(6) * MAX_FILE_BYTES(150 MiB) = 900 MiB <= 1 GiB spec cap. # # Only /data (hostPath /var/log/netsec) is ever written. Logs go to stdout so # they land in the container log, never on the node's disk. @@ -32,12 +22,8 @@ DATA_DIR="${DATA_DIR:-/data}" SOCK="${SOCK:-/var/run/cilium/hubble.sock}" FILTER_AWK="${FILTER_AWK:-/scripts/filter.awk}" MAX_FILE_BYTES="${MAX_FILE_BYTES:-157286400}" # 150 MiB -MAX_FILES="${MAX_FILES:-6}" # plain .jsonl only +MAX_FILES="${MAX_FILES:-6}" MAX_TOTAL_BYTES="${MAX_TOTAL_BYTES:-1006632960}" # 960 MiB (spec cap is 1 GiB) -GZIP_LEVEL="${GZIP_LEVEL:-9}" # 18.5x on live data (17.9x at 6); ~1 s per 150 MiB, off the read path -# Never compress a file appended to this recently: a restart must not gzip a -# file another writer still owns. -COMPRESS_MIN_AGE="${COMPRESS_MIN_AGE:-60}" RETRY_SECONDS="${RETRY_SECONDS:-5}" CHECK_EVERY_LINES="${CHECK_EVERY_LINES:-200}" @@ -45,121 +31,35 @@ log() { printf '%s collector: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; } mkdir -p "$DATA_DIR" || { log "cannot create $DATA_DIR"; exit 1; } -fsize() { stat -c %s "$1" 2>/dev/null || echo 0; } -mtime() { stat -c %Y "$1" 2>/dev/null || date -u +%s; } - -# Is $1 the file the writer is appending to right now? `cur` is unset outside -# the write loop (the startup sweep runs before it is assigned). -is_current() { [ -n "${cur:-}" ] && [ "$1" = "$cur" ]; } - -# Is a gzip for $1 currently running? The temp file is created *before* the -# compressor forks, so a prune that runs immediately after compress() sees it -# and leaves that file alone — deleting it mid-gzip would discard the archive -# and lose the whole file's flows. -in_flight() { - for t in "$1".gz.tmp*; do - [ -e "$t" ] && return 0 - done - return 1 -} - -# Compress one closed .jsonl in the BACKGROUND so the flow reader is never -# blocked (blocking it would stall `hubble observe` and make the agent drop -# events for this client). Order: gzip to a temp name, rename into place, then -# drop the plain file. A reader that globs *.jsonl therefore sees either the -# whole plain file or no plain file at all — never a partial .gz. -compress() { - f=$1 - force=${2:-0} # 1 = we just closed it ourselves; skip the age guard - is_current "$f" && return 0 - [ -e "$f" ] || return 0 - [ -e "$f.gz" ] && return 0 - in_flight "$f" && return 0 - if [ "$force" -eq 0 ]; then - age=$(( $(date -u +%s) - $(mtime "$f") )) - [ "$age" -ge "$COMPRESS_MIN_AGE" ] || return 0 - fi - if [ ! -s "$f" ]; then - rm -f "$f" # closed with nothing in it: nothing to keep - log "removed empty $f" - return 0 - fi - tmp="$f.gz.tmp.$$" - : > "$tmp" 2>/dev/null || return 0 # marker: prune must not reap $f now - ( - if gzip -"$GZIP_LEVEL" -c "$f" > "$tmp" 2>/dev/null && [ -s "$tmp" ]; then - # Preserve the source mtime so the pruner still sees true chronology. - touch -r "$f" "$tmp" 2>/dev/null - if [ -e "$f" ] && mv -f "$tmp" "$f.gz"; then - rm -f "$f" - log "compressed $(basename "$f") -> $(basename "$f.gz") $(fsize "$f.gz")B" - else - rm -f "$tmp" # pruner took the plain file meanwhile - fi - else - rm -f "$tmp" - log "compress failed (left plain): $f" - fi - ) & -} - # Delete oldest files until the directory is inside both bounds. -# `ls -1t` is newest-first, so walking it and deleting from the first overflow -# onward removes the oldest data first. Filenames are generated by this script -# and contain no spaces, so plain word splitting is safe. (Do not `set -f` here: -# GNU ls does not glob the pattern itself, so noglob would make this match -# nothing.) +# Newest first, keep while count <= MAX_FILES and running total <= MAX_TOTAL_BYTES. prune() { - files=$(ls -1t "$DATA_DIR"/flows-* 2>/dev/null) + # Filenames are generated by this script and contain no spaces, so plain + # word splitting is safe. (Do not `set -f` here: GNU ls does not glob the + # pattern itself, so noglob would make this match nothing.) + files=$(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null) [ -n "$files" ] || return 0 - total=0 - under=1 - for f in $files; do - case "$f" in - *.gz.tmp*) - # compression in flight: counts toward the cap, never deleted - total=$((total + $(fsize "$f"))) - continue ;; - esac - sz=$(fsize "$f") - total=$((total + sz)) - is_current "$f" && continue - in_flight "$f" && continue # gzip running: this file is about to shrink - case "$f" in - *.jsonl|*.jsonl.gz) ;; - *) continue ;; # unknown junk: counted, left alone - esac - if [ "$under" -eq 0 ] || [ "$total" -gt "$MAX_TOTAL_BYTES" ]; then - under=0 - rm -f "$f" && total=$((total - sz)) && log "pruned $f (dir over ${MAX_TOTAL_BYTES}B)" - fi - done - - # Plain-file bound, independent of the byte bound (the live file counts). n=0 - for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do + total=0 + over=0 + for f in $files; do n=$((n + 1)) - [ "$n" -le "$MAX_FILES" ] && continue - is_current "$f" && continue - in_flight "$f" && continue - rm -f "$f" && log "pruned plain $f (over MAX_FILES=$MAX_FILES)" + if [ "$over" -eq 0 ]; then + sz=$(stat -c %s "$f" 2>/dev/null || echo 0) + total=$((total + sz)) + if [ "$n" -gt "$MAX_FILES" ] || [ "$total" -gt "$MAX_TOTAL_BYTES" ]; then + over=1 + fi + fi + if [ "$over" -eq 1 ]; then + rm -f "$f" && log "pruned $f" + fi done return 0 } -# A compressor killed mid-flight (pod stop) leaves flows-*.gz.tmp* behind. -for t in "$DATA_DIR"/flows-*.gz.tmp*; do - [ -e "$t" ] || continue - rm -f "$t" && log "removed stale temp $t" -done - prune -# Anything plain left by a previous writer is archived on startup, so a restart -# does not leave uncompressed history lying ahead of the byte bound. -for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do - compress "$f" -done -log "starting: dir=$DATA_DIR sock=$SOCK max_file=${MAX_FILE_BYTES}B max_files=$MAX_FILES max_total=${MAX_TOTAL_BYTES}B gzip=-$GZIP_LEVEL" +log "starting: dir=$DATA_DIR sock=$SOCK max_file=${MAX_FILE_BYTES}B max_files=$MAX_FILES max_total=${MAX_TOTAL_BYTES}B" attempt=0 while :; do @@ -195,19 +95,11 @@ while :; do lines=$((lines + 1)) if [ "$lines" -ge "$CHECK_EVERY_LINES" ]; then lines=0 - size=$(fsize "$cur") + size=$(stat -c %s "$cur" 2>/dev/null || echo 0) if [ "$size" -ge "$MAX_FILE_BYTES" ]; then - prev="$cur" seq=$((seq + 1)) cur="$DATA_DIR/flows-$(date -u +%Y%m%dT%H%M%SZ)-$seq.jsonl" - log "rotated: $cur (closed $prev at $(fsize "$prev")B)" - # Archive what we just closed (we own it, so no age guard), - # then re-check the bounds. The sweep also archives any - # orphan a previous writer left behind. - compress "$prev" 1 - for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do - compress "$f" - done + log "rotated: $cur" prune fi fi diff --git a/apps/base/netsec/daemonset.yaml b/apps/base/netsec/daemonset.yaml index 63ba4b1..0727fa5 100644 --- a/apps/base/netsec/daemonset.yaml +++ b/apps/base/netsec/daemonset.yaml @@ -55,10 +55,8 @@ spec: value: /data - name: SOCK value: /var/run/cilium/hubble.sock - # MAX_FILES bounds PLAIN .jsonl files (the live one plus leftovers - # from a restart). Rotated files are gzip'd (~17.9x measured) and - # bounded by MAX_TOTAL_BYTES, the whole-directory ceiling (archives - # included) that stays inside the 1 GiB spec cap. + # 6 files x 150 MiB = 900 MiB ceiling, inside the 1 GiB spec cap; + # MAX_TOTAL_BYTES is the second, independent bound. - name: MAX_FILE_BYTES value: "157286400" - name: MAX_FILES diff --git a/apps/base/netsec/namespace.yaml b/apps/base/netsec/namespace.yaml index 300ddb0..d4f6b03 100644 --- a/apps/base/netsec/namespace.yaml +++ b/apps/base/netsec/namespace.yaml @@ -3,8 +3,4 @@ kind: Namespace metadata: name: netsec labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: netsec diff --git a/apps/base/osint/README.md b/apps/base/osint/README.md index 27845bf..a3f838d 100644 --- a/apps/base/osint/README.md +++ b/apps/base/osint/README.md @@ -15,7 +15,7 @@ instead of a host Docker container on the Pi. | `osint-camera-service` | same app image | public-camera discovery + snapshots (PVC `osint-camera-snapshots` 3 Gi, shared with the app) | | `osint-titiler` | `forgejo…/sirius/titiler:0.26.0` | SAR COG tile proxy, exposed same-origin at `/titiler` | | `osint-news-scraper` | `forgejo…/sirius/osint-news-scraper:amd64-58f71f5b4520` | Scrapy news scraper loop | -| `osint-news-summarizer` | `forgejo…/sirius/osint-news-summarizer:amd64-fb5285df7f38` | "analyst" — Nous Portal briefs every 15 min + 23:00 recap | +| `osint-news-summarizer` | `forgejo…/sirius/osint-news-summarizer:amd64-fe2b5df369d0` | "analyst" — Nous Portal briefs every 15 min + 23:00 recap | Every workload is pinned to `kubernetes.io/hostname: siriussec` (Gateway/Envoy co-location + local-path PVs). @@ -133,29 +133,11 @@ it can actually parse. ## Analyst model -`SUMMARY_MODEL=deepseek/deepseek-v4.1-flash-1017` (Nous Portal, 1M context, -verified to honour `response_format: json_object`; the previous free -`meituan/longcat-2.5:free` id was retired and 404'd every call). When picking a -replacement, confirm it is in `GET /v1/models` — a stale id fails silently -because `chat()` swallows non-200s and returns an empty string. It is set in +`SUMMARY_MODEL=meituan/longcat-2.5:free` (free tier on the Nous Portal, +1M context, verified to honour `response_format: json_object`). It is set in `configmap.yaml`; changing it in the UI (`PUT /api/settings`) only takes effect when the env var is empty, because `resolve_model()` prefers the env. -## Analyst resilience + map concurrency (PR #72) - -`SUMMARY_MAP_CONCURRENCY` (16, in `configmap.yaml`) sets how many map calls are -in flight. Each call is a ~20 s wall clock, so the phase is latency-bound: the -746-batch recap measured **951 s** end-to-end at 16, where 8 is projected at -~98 min. The code default is also 16; the env var is pinned so a default change -upstream cannot silently stretch the 15-min interval past its window. - -A non-retryable Nous rejection (400/404/422 — e.g. a retired model id) now -raises `NousAPIError` and aborts the run with `rc=1` instead of being swallowed -as an empty completion, so the failure shows up in the pod log on the *first* -tick rather than as nine days of "idle" ticks. The per-run summary line is -`summarize done kind= summary_id=… model=… batches=… articles=… -ticker=… map=… elapsed=…s`. - ## Analyst grading (PR #53 + #54) The map call scores every article **0-100** against a rubric in the same request diff --git a/apps/base/osint/analyst-exporter.yaml b/apps/base/osint/analyst-exporter.yaml deleted file mode 100644 index a3c7dbf..0000000 --- a/apps/base/osint/analyst-exporter.yaml +++ /dev/null @@ -1,332 +0,0 @@ -# Freshness exporter for the osint analyst (card t_22334588). -# -# The summarizer (deploy/osint-news-summarizer) wrote no article_summaries rows -# from 2026-11-25 to 2026-12-04 while the scraper kept the articles table fresh -# (61.5k rows, newest within minutes). Nothing paged: the container was Running -# with restarts 0 and only INFO batch lines in the log, so "analyst wedged" and -# "analyst idle" looked identical from every signal the cluster had. -# -# The app has no /metrics endpoint (POST /metrics -> 404 on osint-app), so this -# is a tiny read-only exporter that answers the only question that matters: -# *when* did each side last write a row? It reads two timestamps from -# osint_data and serves them on :9187/metrics: -# -# osint_analyst_last_success_timestamp_seconds max(article_summaries.batch_timestamp) -# osint_ingest_last_article_timestamp_seconds max(articles.timestamp) -# osint_analyst_exporter_up 1 when the last DB read succeeded -# -# PromQL rules live in monitoring/controllers/home/osint-analyst.yaml -# (OsintAnalystStale, OsintIngestAliveButNoBrief). -# -# Why the summarizer image: it is the only image in this namespace that already -# ships psycopg2 and a python3, and it is pinned by tag (no floating base). The -# script uses the stdlib HTTP server, so nothing is installed at runtime and no -# new image build is needed. It tracks the summarizer's own pin (currently -# amd64-fb5285df7f38) — bump BOTH together; two different tags for one image in -# one namespace reads as drift in an audit, and the exporter only needs the -# interpreter + psycopg2, which every summarizer build carries. ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: osint-analyst-exporter - namespace: osint -data: - exporter.py: | - #!/usr/bin/env python3 - """Read-only freshness exporter for the osint analyst. - - Serves /metrics on :9187. Two timestamps, nothing else: - - osint_analyst_last_success_timestamp_seconds - epoch of max(article_summaries.batch_timestamp) -- when the analyst - last wrote a brief. 0 means the table is empty (stale by definition). - osint_ingest_last_article_timestamp_seconds - epoch of max(articles.timestamp) -- when the scraper last ingested. - osint_analyst_exporter_up - 1 when the last database read succeeded, 0 otherwise. - - On a database error the last good values are kept and `up` drops to 0, so - the timestamps keep ageing and a broken exporter escalates through the same - OsintAnalystStale alert instead of hiding behind missing series. - """ - import logging - import os - import threading - import time - from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer - - import psycopg2 - - LOG = logging.getLogger("osint-analyst-exporter") - logging.basicConfig( - level=os.getenv("LOG_LEVEL", "INFO"), - format="%(asctime)s %(levelname)s %(name)s: %(message)s", - ) - - PORT = int(os.getenv("EXPORTER_PORT", "9187")) - # One scrape interval (30 s) of cache: Prometheus + probes hitting the - # endpoint together must not each open a database connection. - CACHE_TTL = float(os.getenv("CACHE_TTL_SECONDS", "10")) - - DB_CONFIG = { - "host": os.getenv("DB_HOST", "osint-db"), - "port": int(os.getenv("DB_PORT", "5432")), - "dbname": os.getenv("DB_NAME", "osint_data"), - "user": os.getenv("DB_USER", "osint"), - "password": os.getenv("DB_PASSWORD", ""), - "connect_timeout": 5, - } - - ANALYST_SQL = ( - "SELECT COALESCE(EXTRACT(EPOCH FROM max(batch_timestamp))::bigint, 0) " - "FROM article_summaries" - ) - INGEST_SQL = ( - "SELECT COALESCE(EXTRACT(EPOCH FROM max(timestamp))::bigint, 0) " - "FROM articles" - ) - - _lock = threading.Lock() - _state = {"analyst": 0, "ingest": 0, "up": 0, "last_attempt": 0.0} - - - def collect() -> tuple[int, int]: - conn = psycopg2.connect(**DB_CONFIG) - try: - conn.autocommit = True - with conn.cursor() as cur: - cur.execute("SET statement_timeout = 5000") - cur.execute(ANALYST_SQL) - analyst = int(cur.fetchone()[0] or 0) - cur.execute(INGEST_SQL) - ingest = int(cur.fetchone()[0] or 0) - finally: - conn.close() - return analyst, ingest - - - def ensure_fresh() -> None: - now = time.time() - with _lock: - if now - _state["last_attempt"] < CACHE_TTL: - return - _state["last_attempt"] = now - try: - analyst, ingest = collect() - except Exception as exc: # noqa: BLE001 - never kill the endpoint - with _lock: - _state["up"] = 0 - LOG.warning("collect failed: %s", exc) - return - with _lock: - _state.update(analyst=analyst, ingest=ingest, up=1) - - - def render() -> str: - with _lock: - analyst = _state["analyst"] - ingest = _state["ingest"] - up = _state["up"] - return ( - "# HELP osint_analyst_last_success_timestamp_seconds " - "Epoch of the newest article_summaries.batch_timestamp (last brief " - "written by the analyst); 0 = no row.\n" - "# TYPE osint_analyst_last_success_timestamp_seconds gauge\n" - f"osint_analyst_last_success_timestamp_seconds {analyst}\n" - "# HELP osint_ingest_last_article_timestamp_seconds " - "Epoch of the newest articles.timestamp (last row ingested by the " - "scraper); 0 = no row.\n" - "# TYPE osint_ingest_last_article_timestamp_seconds gauge\n" - f"osint_ingest_last_article_timestamp_seconds {ingest}\n" - "# HELP osint_analyst_exporter_up 1 when the last database read " - "succeeded.\n" - "# TYPE osint_analyst_exporter_up gauge\n" - f"osint_analyst_exporter_up {up}\n" - ) - - - class Handler(BaseHTTPRequestHandler): - server_version = "osint-analyst-exporter/1.0" - - def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler API - path = self.path.split("?", 1)[0] - if path not in ("/metrics", "/healthz"): - self.send_error(404) - return - ensure_fresh() - body = render().encode() - self.send_response(200) - self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def log_message(self, fmt, *args): # noqa: A003 - stdlib hook - LOG.debug("%s - %s", self.address_string(), fmt % args) - - - def main() -> None: - # Prime the cache so the first scrape has data, but never refuse to - # start on a database blip. - ensure_fresh() - server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) - LOG.info("listening on 0.0.0.0:%s (db=%s/%s)", PORT, DB_CONFIG["host"], DB_CONFIG["dbname"]) - server.serve_forever() - - - if __name__ == "__main__": - main() ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: osint-analyst-exporter - namespace: osint - labels: - app: osint-analyst-exporter -spec: - replicas: 1 - selector: - matchLabels: - app: osint-analyst-exporter - template: - metadata: - labels: - app: osint-analyst-exporter - spec: - imagePullSecrets: - - name: forgejo-pull - # Same placement policy as the other stateless amd64 loops here: prefer - # linode (where osint-db runs) but do not strand if it is absent. - nodeSelector: - kubernetes.io/arch: amd64 - affinity: - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - linode - securityContext: - runAsNonRoot: true - runAsUser: 1000 - runAsGroup: 1000 - seccompProfile: - type: RuntimeDefault - containers: - - name: exporter - # Pinned summarizer image: python3 + psycopg2, see header comment. - # Kept equal to the summarizer pin in news-summarizer-deployment.yaml. - image: forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-fb5285df7f38 - imagePullPolicy: IfNotPresent - command: ["python", "/opt/exporter/exporter.py"] - env: - - name: PYTHONDONTWRITEBYTECODE - value: "1" - - name: EXPORTER_PORT - value: "9187" - - name: DB_HOST - valueFrom: - configMapKeyRef: - name: osint-env - key: DB_HOST - - name: DB_PORT - valueFrom: - configMapKeyRef: - name: osint-env - key: DB_PORT - - name: DB_NAME - valueFrom: - configMapKeyRef: - name: osint-env - key: DB_NAME - - name: DB_USER - valueFrom: - configMapKeyRef: - name: osint-env - key: DB_USER - - name: DB_PASSWORD - valueFrom: - secretKeyRef: - name: osint-db - key: password - ports: - - name: metrics - containerPort: 9187 - protocol: TCP - readinessProbe: - httpGet: - path: /healthz - port: metrics - periodSeconds: 10 - livenessProbe: - httpGet: - path: /healthz - port: metrics - initialDelaySeconds: 10 - periodSeconds: 30 - resources: - requests: - cpu: 10m - memory: 64Mi - limits: - cpu: 100m - memory: 128Mi - securityContext: - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - capabilities: - drop: - - ALL - volumeMounts: - - name: script - mountPath: /opt/exporter - readOnly: true - volumes: - - name: script - configMap: - name: osint-analyst-exporter ---- -apiVersion: v1 -kind: Service -metadata: - name: osint-analyst-exporter - namespace: osint - labels: - app: osint-analyst-exporter -spec: - type: ClusterIP - selector: - app: osint-analyst-exporter - ports: - - name: metrics - port: 9187 - targetPort: metrics - protocol: TCP ---- -# Prometheus (monitoring ns) scrapes this; the ServiceMonitor selector is -# namespace-wide (spec.serviceMonitorNamespaceSelector = {}), so the label is -# what matters. Ingress from monitoring to :9187 is opened in networkpolicy.yaml. -apiVersion: monitoring.coreos.com/v1 -kind: ServiceMonitor -metadata: - name: osint-analyst-exporter - namespace: osint - labels: - release: kube-prometheus-stack -spec: - namespaceSelector: - matchNames: - - osint - selector: - matchLabels: - app: osint-analyst-exporter - endpoints: - - port: metrics - path: /metrics - interval: 30s - scrapeTimeout: 10s diff --git a/apps/base/osint/app-deployment.yaml b/apps/base/osint/app-deployment.yaml index 3b0dbce..99acbc1 100644 --- a/apps/base/osint/app-deployment.yaml +++ b/apps/base/osint/app-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-app spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -26,7 +24,7 @@ spec: initContainers: # Wait for Postgres before alembic runs (the entrypoint migrates). - name: wait-for-db - image: forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-6066ac8e0d6c + image: forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-54897b49bc57 imagePullPolicy: IfNotPresent command: - python @@ -44,7 +42,7 @@ spec: sys.exit("postgres did not become reachable in 300s") containers: - name: app - image: forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-6066ac8e0d6c + image: forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-54897b49bc57 imagePullPolicy: IfNotPresent ports: - containerPort: 8000 diff --git a/apps/base/osint/camera-deployment.yaml b/apps/base/osint/camera-deployment.yaml index f2734bf..4b3d0f8 100644 --- a/apps/base/osint/camera-deployment.yaml +++ b/apps/base/osint/camera-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-camera-service spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/osint/configmap.yaml b/apps/base/osint/configmap.yaml index 1fb953d..fa58991 100644 --- a/apps/base/osint/configmap.yaml +++ b/apps/base/osint/configmap.yaml @@ -66,25 +66,14 @@ data: # never see https here: this flag is what puts `Secure` on the session cookie. ADMIN_COOKIE_SECURE: "1" - # ── news summarizer (analyst) — Nous Portal ───────────────────────────── + # ── news summarizer (analyst) — Nous Portal, free tier model ──────────── NOUS_BASE_URL: https://inference-api.nousresearch.com/v1 - # Meituan LongCat was retired from the portal (every call 404'd from 11/25 - # onward, silently producing no briefs). The :free ids now require a user - # tag and 503 anyway; pin the cheapest model that answers normally and - # honours response_format: json_object (~$0.03/$0.12 per Mtok). - SUMMARY_MODEL: deepseek/deepseek-v4.1-flash-1017 + SUMMARY_MODEL: meituan/longcat-2.5:free # 4, not the upstream default 50: the map phase runs with a hard 60 s httpx - # timeout (news/summerizer/nous_client.py, json_mode=False), so bigger - # batches risk timing out and silently contributing nothing to the reduce - # phase. + # timeout (news/summerizer/nous_client.py, json_mode=False), and this free + # model needs ~30 s for 8 articles, so bigger batches time out and silently + # contribute nothing to the reduce phase. BATCH_SIZE: "4" - # Map-phase fan-out (PR #72). Each map call is a ~20 s wall clock, so the - # phase is latency-bound, not CPU-bound: the 746-batch recap measured 951 s - # end-to-end at 16 in flight, where 8 is projected at ~98 min. 16 is also the - # summarizer's DEFAULT_SUMMARY_MAP_CONCURRENCY; it is pinned here so a future - # code default change cannot silently stretch the 15-min interval past its - # window. - SUMMARY_MAP_CONCURRENCY: "16" # Map-phase grading (PR #53): the map call scores every article 0-100 against # a rubric and only blocks >= SUMMARY_MIN_SCORE reach the brief. When nothing # clears the bar the top SUMMARY_FALLBACK_TOP are used so the HUD is not blank diff --git a/apps/base/osint/ingester-deployment.yaml b/apps/base/osint/ingester-deployment.yaml index 57ca282..d0e8682 100644 --- a/apps/base/osint/ingester-deployment.yaml +++ b/apps/base/osint/ingester-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-ingester spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/osint/kustomization.yaml b/apps/base/osint/kustomization.yaml index 7d66655..02eb79c 100644 --- a/apps/base/osint/kustomization.yaml +++ b/apps/base/osint/kustomization.yaml @@ -18,20 +18,7 @@ resources: - titiler-service.yaml - news-scraper-deployment.yaml - news-summarizer-deployment.yaml - # Freshness exporter for the analyst (max(article_summaries.batch_timestamp) - # and max(articles.timestamp) -> :9187/metrics) + its ServiceMonitor. The - # summarizer has no /metrics and a wedged analyst is invisible otherwise - # (card t_22334588). - - analyst-exporter.yaml - httproute.yaml - # Default-deny ingress+egress + the namespace allow list (audit F3 / t_fed52919). - - networkpolicy.yaml # exec-only RBAC so forgejo/cluster-backup can pg_dump this namespace's plain # Postgres Deployment (osint-db) — not a CNPG cluster, so it needs its own path. - backup-exec-rbac.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-forgejo-pull.sops.yaml - - secret-osint-admin.sops.yaml - - secret-osint-db.sops.yaml diff --git a/apps/base/osint/namespace.yaml b/apps/base/osint/namespace.yaml index ba73280..06e4f8f 100644 --- a/apps/base/osint/namespace.yaml +++ b/apps/base/osint/namespace.yaml @@ -2,10 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: osint - labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/apps/base/osint/nats-deployment.yaml b/apps/base/osint/nats-deployment.yaml index 2f575b9..52fe659 100644 --- a/apps/base/osint/nats-deployment.yaml +++ b/apps/base/osint/nats-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-nats spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/osint/networkpolicy.yaml b/apps/base/osint/networkpolicy.yaml deleted file mode 100644 index 7379108..0000000 --- a/apps/base/osint/networkpolicy.yaml +++ /dev/null @@ -1,87 +0,0 @@ -# Tenant isolation for `osint` (audit finding F3 / A5-1, card t_fed52919). -# -# `default-deny` (stock NetworkPolicy, podSelector {}, both directions) makes -# every pod in this namespace reachable by nothing and able to reach nothing. -# `osint-allow` (CiliumNetworkPolicy) re-adds the traffic the workload actually -# uses, in both directions: -# ingress: the Cilium Gateway proxy (`reserved:ingress`) for -# osint.siriusdevops.com -> app:8000 / titiler:8000, plus node/health -# entities for kubelet probes. -# egress: cluster DNS, its own pods (app -> osint-db:5432, -> nats:4222, -# -> titiler:8000), and `world` — the ingester/news-scraper/ -# news-summarizer fetch external news + Nominatim -# (nominatim.openstreetmap.org) + the Nous inference API, and -# camera-service reads RTSP cameras on the LAN. -# -# `world` in Cilium is everything outside the cluster (internet, LAN, VPN peers) -# but NOT other namespaces' pods and NOT the node IPs — so cross-namespace -# reachability and the internal WireGuard gateway ports stay closed. -# -# Deliberately absent: -# * kube-apiserver egress — no workload here calls the API; the audit's -# `SA token mounted` observation is a separate finding and denying the path -# does not depend on removing the token. -# * monitoring ingress — apart from the one port-scoped rule for the analyst -# freshness exporter below (Prometheus -> osint-analyst-exporter:9187), -# nothing in `monitoring` reaches this namespace. -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: osint -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: osint-allow - namespace: osint -spec: - description: >- - osint: gateway + kubelet ingress; egress to own namespace, cluster DNS and - the public internet only. - endpointSelector: {} - ingress: - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace pod -> pod (app -> db, sidecars, the backup CronJob). - # Cilium enforces policy at BOTH ends, so this allow must exist in ingress as - # well as egress — measured on `piedmont`: with only the egress rule a pod - # could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: osint - # Prometheus (namespace `monitoring`) scrapes the analyst freshness exporter - # on 9187 (apps/base/osint/analyst-exporter.yaml). Port-scoped: no other - # monitoring -> osint traffic is opened. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: monitoring - toPorts: - - ports: - - port: "9187" - protocol: TCP - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: osint - # Internet / LAN / VPN peers: news sources, Nominatim, inference API, RTSP. - - toEntities: - - world diff --git a/apps/base/osint/news-scraper-deployment.yaml b/apps/base/osint/news-scraper-deployment.yaml index 788539e..22cfd07 100644 --- a/apps/base/osint/news-scraper-deployment.yaml +++ b/apps/base/osint/news-scraper-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-news-scraper spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/osint/news-summarizer-deployment.yaml b/apps/base/osint/news-summarizer-deployment.yaml index 931a029..647fdc8 100644 --- a/apps/base/osint/news-summarizer-deployment.yaml +++ b/apps/base/osint/news-summarizer-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-news-summarizer spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -39,12 +37,7 @@ spec: kubernetes.io/arch: amd64 containers: - name: news-summarizer - # amd64-fb5285df7f38 = sirius/osint-dashboard@fb5285d (PR #72, merged): - # the map phase runs concurrently (SUMMARY_MAP_CONCURRENCY) and a - # non-retryable Nous rejection raises NousAPIError instead of being - # swallowed, so a wedged analyst fails loudly instead of idling for - # nine days on silent empty completions (card t_22334588 / t_2ae9f0c0). - image: forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-fb5285df7f38 + image: forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-fe2b5df369d0 imagePullPolicy: IfNotPresent # Loop: batch the last window, call Nous Portal, write summaries. command: ["python", "run_news_summarizer.py"] diff --git a/apps/base/osint/postgres-deployment.yaml b/apps/base/osint/postgres-deployment.yaml index 7761df7..dd4a051 100644 --- a/apps/base/osint/postgres-deployment.yaml +++ b/apps/base/osint/postgres-deployment.yaml @@ -23,8 +23,6 @@ spec: labels: app: osint-db spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/osint/secret-forgejo-pull.sops.yaml b/apps/base/osint/secret-forgejo-pull.sops.yaml deleted file mode 100644 index df6f3ed..0000000 --- a/apps/base/osint/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:d+Qwhs0BLzcJDRecSw3Ij7lJNet7NPZOvMMDcIXHFTT6rzSn9UNVWuRXk4M7LBk/ovJputnUuV2sfUf0XOfvGKzDRBueOBmJKErnO8bcHtN3Nyw/jwziCRAbqV2lNNZ1g5WAyI/G8W386n7vBEZp5GgGdoJHSRQnIXa5TW/XLHRG2ad1fcRXpp3QppDUe1ykH0v+kcl73Xs7oCe9BtYiRI5/H9B8eQw0IIHem4zWDVELbfury86V4vyHfkCG3wveEHGxib2W0IsMmAmPRVzuL1GJCIDcMomQRHTJhK1nMQUDtmhgRXg5wIwy9w6w0FPfX7Qu31TCT22V6X+gOirALstSTrYR4Chi8QIfCypQh5f3J7TGhdWkbA7rYbJZKy1N,iv:K9BsNRmd4cmLlBg/h5Azl22SStUODiCBHA78W6gX+2M=,tag:/p1Yw6IsbQGWltDbzA3bbA==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: osint -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBxbUlrR3ZNTTJJSTJleEdZ - RytMeS81RjhtUi9CbHk5K2EzTi96UnplaWowCkhhWng1R2w4UkdvYm5XU2VDNHJ4 - eWFicUVOOFZqaEQ5RnhxMWVCdkU4aXMKLS0tIDRXRWpkT2tTZ3JiQXRXclg2eUl3 - bGhjak1ueWdMOXdtc2hDL0p3aDBiaDAKEDY5tZnpYcJSjLIY5DcZ28GNdlTRt2QX - cdKQh0ddKwdWu2BuSOtMwgNjB0c1mSdZPAXtIVGeORSDLf//FVfJ/w== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:qVmV+yQSgcShahLRN0I4niDEtYjjGNINLeJPZoKTA8BaKYnvHok8Bj473DW88+TGujLwqhg9mZIOP6pZRBvFks0Ue+NFkE0m9/OHfglCStp/+E9N9C6w0CDITBOpD8jmgOJoK57xseMskLCJmTfIbzN0Afln+m9NZYfPW1fWehY=,iv:3Mq1uXwQZOvZ5uiCfo1lTcobvFqZH9KXShUUQ7Z0aQw=,tag:vMtBilXeLmgFppwNxx6BBA==,type:str] - version: 3.13.3 diff --git a/apps/base/osint/secret-osint-admin.sops.yaml b/apps/base/osint/secret-osint-admin.sops.yaml deleted file mode 100644 index c1263d0..0000000 --- a/apps/base/osint/secret-osint-admin.sops.yaml +++ /dev/null @@ -1,25 +0,0 @@ -apiVersion: v1 -data: - ADMIN_PASSWORD_HASH: ENC[AES256_GCM,data:pM52EBdmrx+ZTJKVL3hK1xcMZ8PkhEExJnMzEx2zRblTRPoTCFM/2ghu/sfz7HpaHNvZ/izx8EQwyyRAHFlUj3rPeA7Cveek3FvXR6PWyMOdJ2t8aW9QN5QF8k3eXDDA7jP0WfF3tVFLc48oRed8V1kjqL0=,iv:Vv3R/Kq2BUlUrQ8y2TEsYSK59sDEPOEVn1hfjrmmFh0=,tag:u8iiY7QcYFGyZh2J9ttrnQ==,type:str] - ADMIN_SESSION_SECRET: ENC[AES256_GCM,data:u6ef6ry1H+jeC5o2fhs6dETG+AHxOz5nMpYhTWFU4wHraJtFgoMUudXX7pfsqvpvQ4SBMhgGNotkpyxW1ubSMf/MD4QYU2SUfCZwXawJoquBgFHGttm8Yg==,iv:phTH+xno6OCHgB1vvn03DIdubjd8qDpxXx6oe4Uc9Jo=,tag:QaTEFWAnj7bRZKUlhiEnkg==,type:str] - ADMIN_USER: ENC[AES256_GCM,data:GTC0VP8jl90=,iv:awQwkQGGpClTE2b/qjHg0gOyY0id4Ns/NJaHniQ0yTw=,tag:Jh0enTrfRUXofp0xOVzhMw==,type:str] -kind: Secret -metadata: - name: osint-admin - namespace: osint -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA0TEJSWHVuR3gwVnVDbkRk - UWhsdnRvaUk5VkNKN3VicERneEpYVnNIeFVjCmg1ZkIrMjAzayt2WFdEc0ZpNzZp - czNhcUszazZ4QWpVTXVaUUk1YW9UcEUKLS0tIDI4T1plYjVEYXhGSUZRSE5JUnNJ - TmJvcmN4dmY2YUU3Zzd2aktEZHM5TFkK8NXP+DRnltYkuUIBJgG0LhxUnK2R3JBm - 6+vgVHNGhtn1Dp7yYWTAbT7dAh9puJyG2E1unXi2cvnWRDyP/xlviA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:tr6R/iqO9lIDrDl5NhKFUeqlAUaEJXOEvsEthaW/FpY9lMnwzzNUYVazFy5i3I34O3o71kPabrUUHfCiMnoD1+Echl/nZGpnQKQNEh2+CaG/cCavqVEYjw18sClGCUnBE8FdL9ccO2iAZAtkOlYjJimwT+9qauZIJGwTPakh22o=,iv:LuJtnsq4XSEI2NNWU3ST9eR5dwLOkeOstnlED6TJTOc=,tag:TlqvkhkP9bdd0ltAhQdghQ==,type:str] - version: 3.13.3 diff --git a/apps/base/osint/secret-osint-db.sops.yaml b/apps/base/osint/secret-osint-db.sops.yaml deleted file mode 100644 index 658dae7..0000000 --- a/apps/base/osint/secret-osint-db.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:/TR9lenGU5gFhORKhBESQd8huplzERixYdRvzmWvyQkTYi+iP6ADZl34M8E=,iv:59YuJ8cmVV8A3bdQim+GH267WozFljhZ92D4GR5Jnek=,tag:8ae3Rsmzyxg0CH1wb8FjFA==,type:str] -kind: Secret -metadata: - name: osint-db - namespace: osint -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBtUXcxU2x3MU5lWHR1c2Rx - VjhhZExUV1FnZHFQbThlRE5UckVYNWVFS3pvCjRBZmtDcHpaak4vUmtKTUtyaWNM - VkIvZ3dadTNraEpKYm92ZU9rbklhbjQKLS0tIGJuZnRQRkkyUmk0TlU5OXJHWE1N - QVQzTCs4M0dld3hybUNyN0Z2c0dtZ1UK1JSSDk6NMGbzP1zDBP6L5CzUSRJU6tdF - 63N2QmOzhSiXBI//H96CAmP20m1hlU9+A2c829nsHUuorievXbjbFw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:vJ2ageffd9eLUeG7CK0gYO1H33/uj3vW+5oIDqqKGHvp8yxJ0F8lrcb1byoEWjWEemIQbNVSipl6fMIiGf8owUK2cm2w6TeNZ7ZCWhOuUE/LoS0ix2dgNB2KHN/HIoC71cKutLiidCulZHJkaMnFEeEyYMMd1OIBStMdyfIFMVU=,iv:Q4sK0gfzXljs02U0w5Npfb6CUU/+hH27AvEXtNwMGTE=,tag:OxbI2WBl4JNPjuxNTj8Fww==,type:str] - version: 3.13.3 diff --git a/apps/base/osint/titiler-deployment.yaml b/apps/base/osint/titiler-deployment.yaml index 189c7ea..a023e07 100644 --- a/apps/base/osint/titiler-deployment.yaml +++ b/apps/base/osint/titiler-deployment.yaml @@ -15,8 +15,6 @@ spec: labels: app: osint-titiler spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/piedmont/deployment-api.yaml b/apps/base/piedmont/deployment-api.yaml index 3a336eb..32fc373 100644 --- a/apps/base/piedmont/deployment-api.yaml +++ b/apps/base/piedmont/deployment-api.yaml @@ -13,8 +13,6 @@ spec: labels: app: piedmont-contact spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -25,7 +23,7 @@ spec: - name: contact-api # Built and pushed by sirius/websites/.forgejo/workflows/deploy-phs-contact.yml # as :$sha (see docs/site-image-pinning.md). - image: forgejo.siriusdevops.com/sirius/phs-contact:0446be8fbc443f59b72eabc54652972d9edd51cd + image: forgejo.siriusdevops.com/sirius/phs-contact:5035443abb62913362e416ab7030a64726886886 imagePullPolicy: IfNotPresent command: ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8090"] ports: diff --git a/apps/base/piedmont/deployment.yaml b/apps/base/piedmont/deployment.yaml index 9d8776f..7d6c735 100644 --- a/apps/base/piedmont/deployment.yaml +++ b/apps/base/piedmont/deployment.yaml @@ -13,8 +13,6 @@ spec: labels: app: piedmont-site spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/piedmont/kustomization.yaml b/apps/base/piedmont/kustomization.yaml index 9019136..04276f6 100644 --- a/apps/base/piedmont/kustomization.yaml +++ b/apps/base/piedmont/kustomization.yaml @@ -7,10 +7,3 @@ resources: - service.yaml - service-api.yaml - httproute.yaml - # Default-deny ingress+egress + the namespace allow list (audit F3 / t_fed52919). - - networkpolicy.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-forgejo-pull.sops.yaml - - secret-piedmont-contact.sops.yaml diff --git a/apps/base/piedmont/namespace.yaml b/apps/base/piedmont/namespace.yaml index 5a41da0..0efa3b6 100644 --- a/apps/base/piedmont/namespace.yaml +++ b/apps/base/piedmont/namespace.yaml @@ -3,10 +3,4 @@ kind: Namespace metadata: name: piedmont labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: piedmont diff --git a/apps/base/piedmont/networkpolicy.yaml b/apps/base/piedmont/networkpolicy.yaml deleted file mode 100644 index 7cad1c5..0000000 --- a/apps/base/piedmont/networkpolicy.yaml +++ /dev/null @@ -1,63 +0,0 @@ -# Tenant isolation for `piedmont` (audit finding F3 / A5-1, card t_fed52919). -# -# `default-deny` (stock NetworkPolicy, podSelector {}, both directions) is the -# deny. `piedmont-allow` (CiliumNetworkPolicy) re-adds: -# ingress: the Cilium Gateway proxy (`reserved:ingress`) for -# piedmonthomesvc.com -> site:80 / contact:8090, plus node/health -# entities for kubelet probes. -# egress: cluster DNS; its own pods (nginx may proxy /api/contact in-namespace); -# and `world` for the Telegram Bot API used by piedmont-contact. -# -# `world` is everything outside the cluster (internet, LAN, VPN peers) but not -# other namespaces' pods and not node IPs, so the tenant boundary holds. -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: piedmont -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: piedmont-allow - namespace: piedmont -spec: - description: >- - piedmont: gateway + kubelet ingress; egress to own namespace, cluster DNS - and the public internet only. - endpointSelector: {} - ingress: - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace: nginx -> contact (and any future pod -> pod call). Cilium - # enforces policy at BOTH ends, so the same-namespace allow must exist in - # ingress as well as egress — measured: with only the egress rule, a pod in - # this namespace could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: piedmont - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: piedmont - # Telegram Bot API (contact form delivery). - - toEntities: - - world diff --git a/apps/base/piedmont/secret-forgejo-pull.sops.yaml b/apps/base/piedmont/secret-forgejo-pull.sops.yaml deleted file mode 100644 index 4d8ee8b..0000000 --- a/apps/base/piedmont/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:cn2e8WXbtnYELrwUJr6rhgMiOHsQnbL34fJHV+yr3B1Z5WEkPeq/kduh9wcjV0dlPg4cYEczqAH7GQm4f+jIx3FlMvtaftZz195HB38srxzcUzUhc6ZF8Iz7h0cZoOB7Vi0nre+FZCZTXQhuSEYuC97H+6pvDluUqAHBvdrHogWmcAb3PEw9i/sfn1bUC7TZoGXy3MBIuTYlDFid/gkX3dIzPQkKRcZsgrNgztwCIHFADWxfzQwTmWOztYrip1y1UgUhkqfTv38qIa+VI7SpM1gztbxX9lsMv3rO/uTlRqGaogPSC4vYpwWcB3uAL0zpTf79QKlhGKAHiA5dXhVkp3ijVBrkf8F1biaivCGeAGLqEK+yeM1UVNZb2IhFErf/,iv:wWaqHXaQyrNYHCiYNvHp7REYTSmYqu/Vl9SP4ptZtPo=,tag:rzU+lCaLyRvCHutae+S4ww==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: piedmont -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBLTmVRS0RaNW0rQzhUODRI - RGFBdDdwdFRsUGt4MVZRdEwzS2Y5d3kxbXlRCjdyRmlUcG90eGU0STVrcVZDVm9R - Nk04UUt1RmUrQnp2QU4vUlY5TmZCQVUKLS0tIGZqSWp4ejBWMzhvWDEzc2lmbWx4 - b21IdElIRWJUOXZZcm1KLzh0ZHQyRWsKWmi0BF33Y5u++jtjO2ypEenYWybtrU9d - HC8TWALXS4OBRWG4T8AHD1YS+lG+ZhdBYiudyIPniYTMaAblVl8RAg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:9zgfinHIb+SOmOIat00bm/oxste1sLA2kOfNtuqAD5mUQ3Ud+zB2YZjOMm5LTN1QU7tc9JAsJ78fgt9P3Dzq5WR+nGIHpE5BqrjmCzV1PPEDvAG8UaKG8B5Ri4NKY2jrJfalai+bwF7fsf+ekS4w/f2av1nVKwAcV/JCxgNg44I=,iv:XfS6wEza4zAcP9a7Mu69X1ye8pgLFW9OZSmszbqRMKM=,tag:mrXNxFCbAOvOYL11fGazcA==,type:str] - version: 3.13.3 diff --git a/apps/base/piedmont/secret-piedmont-contact.sops.yaml b/apps/base/piedmont/secret-piedmont-contact.sops.yaml deleted file mode 100644 index d8f5c0c..0000000 --- a/apps/base/piedmont/secret-piedmont-contact.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - TG_CHAT: ENC[AES256_GCM,data:5yKsAprsD3TKPB1Z14TeEw==,iv:7fbiXNIl3rs8KJe3kJ7ojhIyN0E56IFvmsbTTj7xBw4=,tag:Bdh1ykvi2QgwFYCRZInr9w==,type:str] - TG_TOKEN: ENC[AES256_GCM,data:aVtjdBFosAW+Y3gW5n+4JThfy+KZT/BawTPPrmLD5wzXlBQS0LqHsWHbSAJ8POqvlcKBq5FhvNe2EgpoXtk/xw==,iv:0P9wQSoiK1bMPlu6brEwahJUcootcfq2e33zE8cDRBo=,tag:BHEmtpPIsLRWzTiSrkljAg==,type:str] -kind: Secret -metadata: - name: piedmont-contact - namespace: piedmont -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBENGhuR3JOMnJsQjRGS05Q - aWgzUDh2aFNsSHJ2MVVMdUZCM1ZwTWpEalg0CmlrZUFtdWtHYWZUNTdLQkdUVHJx - WjExS003a2R1TFdsRXNXZDBrZzN4bmcKLS0tIDVxcnhiMXhWVnpFNEw1L3FoNk1P - MkxwUi9KK0t1MWxYRFJLdHpxQzlqb2sKBr3OtODWT8zrZVal8kO0tS4XvNgcaxJS - r6uKRGwr4g0P6uAxqaAp3iIQPTLhVUA2omU0KOEroEDJTbrGmo0V2w== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:5vUnGhYKucbQVIIcTI98pI6Ip8DnI7bo+4wMUebtk2ELxMq6+8zdI9bn0pmm1kdJy+dB9weRUJ+iGi7VnO9uk/1256cMZrjIvpBDcCaBoevuLkdXSNbV7tMAhcTemr8yHVGWeJ6OPFEsqK5GDA9CSx6sDGXjEOnb/Qh1OlWNUTU=,iv:/diwyI8LSSGk45tTjmyvdMvHJ9iWFZtF0SK240Aw2/w=,tag:lsmPS7X+bws2zlOG0qpK9g==,type:str] - version: 3.13.3 diff --git a/apps/base/secops/namespace.yaml b/apps/base/secops/namespace.yaml index 895792c..ea50020 100644 --- a/apps/base/secops/namespace.yaml +++ b/apps/base/secops/namespace.yaml @@ -3,10 +3,4 @@ kind: Namespace metadata: name: secops labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: secops diff --git a/apps/base/sirius-growth/cronjob-leadgen-ncda.yaml b/apps/base/sirius-growth/cronjob-leadgen-ncda.yaml index dbdc27e..898e058 100644 --- a/apps/base/sirius-growth/cronjob-leadgen-ncda.yaml +++ b/apps/base/sirius-growth/cronjob-leadgen-ncda.yaml @@ -23,8 +23,6 @@ spec: labels: app: sgs-leadgen-ncda spec: - imagePullSecrets: - - name: forgejo-pull restartPolicy: Never nodeSelector: kubernetes.io/hostname: siriussec diff --git a/apps/base/sirius-growth/cronjob-leadgen.yaml b/apps/base/sirius-growth/cronjob-leadgen.yaml index bf2a52d..051bfca 100644 --- a/apps/base/sirius-growth/cronjob-leadgen.yaml +++ b/apps/base/sirius-growth/cronjob-leadgen.yaml @@ -21,8 +21,6 @@ spec: labels: app: sgs-leadgen spec: - imagePullSecrets: - - name: forgejo-pull restartPolicy: Never # local-path is a node-local volume: the pod must run where the PV is. nodeSelector: diff --git a/apps/base/sirius-growth/deployment-api.yaml b/apps/base/sirius-growth/deployment-api.yaml index db8618a..7797954 100644 --- a/apps/base/sirius-growth/deployment-api.yaml +++ b/apps/base/sirius-growth/deployment-api.yaml @@ -13,8 +13,6 @@ spec: labels: app: sirius-growth-contact spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -25,7 +23,7 @@ spec: - name: contact-api # Built and pushed by sirius-growth/.forgejo/workflows/deploy-contact.yml # as :$sha (see docs/site-image-pinning.md). - image: forgejo.siriusdevops.com/sirius/sirius-growth-contact:97cfa4fc1345bbc04c56bbc529416f50ce51a965 + image: forgejo.siriusdevops.com/sirius/sirius-growth-contact:c9c9379ebceca6879d3bbeff1c2601b6484e87b0 imagePullPolicy: IfNotPresent command: ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8090"] ports: diff --git a/apps/base/sirius-growth/deployment-blog.yaml b/apps/base/sirius-growth/deployment-blog.yaml index fc1b4d6..bc72f8e 100644 --- a/apps/base/sirius-growth/deployment-blog.yaml +++ b/apps/base/sirius-growth/deployment-blog.yaml @@ -13,8 +13,6 @@ spec: labels: app: sirius-growth-blog spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/sirius-growth/deployment-portal.yaml b/apps/base/sirius-growth/deployment-portal.yaml index 624a965..fc7120a 100644 --- a/apps/base/sirius-growth/deployment-portal.yaml +++ b/apps/base/sirius-growth/deployment-portal.yaml @@ -13,8 +13,6 @@ spec: labels: app: sirius-growth-portal spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/sirius-growth/deployment.yaml b/apps/base/sirius-growth/deployment.yaml index dd88cf4..663cc95 100644 --- a/apps/base/sirius-growth/deployment.yaml +++ b/apps/base/sirius-growth/deployment.yaml @@ -13,8 +13,6 @@ spec: labels: app: sirius-growth-site spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists diff --git a/apps/base/sirius-growth/kustomization.yaml b/apps/base/sirius-growth/kustomization.yaml index 489a444..17365df 100644 --- a/apps/base/sirius-growth/kustomization.yaml +++ b/apps/base/sirius-growth/kustomization.yaml @@ -14,12 +14,6 @@ resources: - service-blog.yaml - service-portal-gate.yaml - httproute.yaml - # Default-deny ingress+egress + the namespace allow list (audit F3 / t_fed52919). - - networkpolicy.yaml - # Egress lockdown for the leadgen-backup pod: DNS + 10.10.0.5:22 only. The - # allow list above cannot be narrowed per pod, so the deny for `world` in - # this policy is what applies to the job (card t_9d0428d8). - - networkpolicy-backup.yaml # The WAL archive store must exist before the Cluster references it. - objectstore-portal-wal.yaml - cluster.yaml @@ -33,15 +27,3 @@ resources: - backup-exec-rbac.yaml # Snapshot mirror of the lead-gen capture PVC to the Linode. - leadgen-backup.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-forgejo-pull.sops.yaml - - secret-portal-wal-s3.sops.yaml - - secret-sirius-growth-blog-app.sops.yaml - - secret-sirius-growth-blog-s3.sops.yaml - - secret-sirius-growth-contact.sops.yaml - - secret-sirius-growth-portal-app.sops.yaml - - secret-sirius-growth-portal-db.sops.yaml - - secret-sirius-growth-portal-s3.sops.yaml - - secret-cluster-backup-ssh.sops.yaml diff --git a/apps/base/sirius-growth/leadgen-backup.yaml b/apps/base/sirius-growth/leadgen-backup.yaml index 01d3c47..70aa0cf 100644 --- a/apps/base/sirius-growth/leadgen-backup.yaml +++ b/apps/base/sirius-growth/leadgen-backup.yaml @@ -20,10 +20,10 @@ data: # Snapshot mirror of /src -> $BACKUP_DIR/leadgen-data// + `latest`. set -euo pipefail - # No package install here on purpose: rsync/openssh-client/bash are baked - # into the pinned image (images/backup/Dockerfile) and this pod's egress - # policy admits DNS + 10.10.0.5:22 only, so a runtime fetch would fail - # rather than silently dial the Alpine CDN (card t_9d0428d8). + if ! command -v rsync >/dev/null || ! command -v ssh >/dev/null; then + echo "== installing rsync + openssh-client" + apk add --no-cache rsync openssh-client >/dev/null + fi BACKUP_HOST=${BACKUP_HOST:-root@10.10.0.5} BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} @@ -102,18 +102,12 @@ spec: app: leadgen-backup spec: restartPolicy: Never - # Pulled from the in-cluster Forgejo registry (which requires auth). - imagePullSecrets: - - name: forgejo-pull # The PVC is local-path on siriussec. nodeSelector: kubernetes.io/hostname: siriussec containers: - name: backup - # rsync + openssh-client + bash baked at build time, pinned by - # digest (images/backup/Dockerfile). Nothing is installed at run - # time. - image: forgejo.siriusdevops.com/sirius/backup-tools@sha256:cc8dc1645111b3a80b7c4d5168f6bce3002cae7417b3725683c057976f6e379a + image: alpine/k8s:1.36.4 imagePullPolicy: IfNotPresent command: ["/bin/bash", "/scripts/backup.sh"] env: diff --git a/apps/base/sirius-growth/namespace.yaml b/apps/base/sirius-growth/namespace.yaml index 93b22de..3b3689e 100644 --- a/apps/base/sirius-growth/namespace.yaml +++ b/apps/base/sirius-growth/namespace.yaml @@ -3,10 +3,4 @@ kind: Namespace metadata: name: sirius-growth labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest app.kubernetes.io/part-of: sirius-growth diff --git a/apps/base/sirius-growth/networkpolicy-backup.yaml b/apps/base/sirius-growth/networkpolicy-backup.yaml deleted file mode 100644 index f13c903..0000000 --- a/apps/base/sirius-growth/networkpolicy-backup.yaml +++ /dev/null @@ -1,49 +0,0 @@ -# Egress lockdown for the nightly leadgen-backup CronJob (card t_9d0428d8). -# -# Why: the job used to `apk add --no-cache rsync openssh-client` at container -# start, so each run depended on the Alpine CDN (Fastly 151.101.x.132:443). -# rsync/ssh/bash (+kubectl, unused here) are baked into -# images/backup/Dockerfile now. -# -# `sirius-growth-allow` (networkpolicy.yaml) selects every pod in this -# namespace and allows `world` (Telegram Bot API, the leadgen crawlers), so a -# pod-scoped allow list alone would NOT restrict this job — Cilium unions -# policies. The `egressDeny` for `world` closes it for this pod only; the app -# pods keep their internet access. -# -# Allow list, and nothing else: cluster DNS, and root@10.10.0.5:22 (the Linode -# node's InternalIP — `remote-node`, not `world`) for the rsync mirror. -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: leadgen-backup-egress - namespace: sirius-growth - labels: - app: leadgen-backup -spec: - description: >- - leadgen-backup pod: cluster DNS + SSH to the backup host (10.10.0.5:22) - only; no internet egress at run time. - endpointSelector: - matchLabels: - app: leadgen-backup - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEntities: - - remote-node - toPorts: - - ports: - - port: "22" - protocol: TCP - egressDeny: - - toEntities: - - world diff --git a/apps/base/sirius-growth/networkpolicy.yaml b/apps/base/sirius-growth/networkpolicy.yaml deleted file mode 100644 index 8a7ddb5..0000000 --- a/apps/base/sirius-growth/networkpolicy.yaml +++ /dev/null @@ -1,121 +0,0 @@ -# Tenant isolation for `sirius-growth` (audit finding F3 / A5-1, card t_fed52919). -# -# `default-deny` (stock NetworkPolicy, podSelector {}, both directions) is the -# deny. `sirius-growth-allow` (CiliumNetworkPolicy) re-adds what the namespace -# actually uses: -# ingress: Cilium Gateway proxy (`reserved:ingress`) for -# siriusgrowthsolutions.com -> site:80 / contact:8090 / -# portal-gate:8080 / portal:8091 / blog:8092, node entities for -# kubelet probes, Prometheus in `monitoring` on 9187 only (the -# `cnpg-portal` PodMonitor scrapes the CNPG instance manager), and -# the CNPG operator in `cnpg-system` on 8000 only — the instance -# manager's HTTPS status endpoint the operator reads to derive the -# system ID and drive failover (card t_4210edec). -# egress: cluster DNS; its own pods (blog/portal -> portal-1:5432, -# portal-gate -> portal:8091); `world` for the Telegram Bot API -# (contact + portal) and the leadgen crawlers; the node IPs on 3900 -# (Garage S3: 10.10.0.1 for blog/portal media, 10.10.0.5 for the -# portal WAL ObjectStore) and on 22 (leadgen-backup rsyncs to -# root@10.10.0.5); and `kube-apiserver` for the CNPG instance -# manager, which needs the API for leader/status updates. -# -# Garage lives on node IPs, which Cilium maps to `reserved:remote-node`, not -# `world` — see apps/base/siriusdevops/networkpolicy.yaml for the original -# measurement (an `ipBlock`/toCIDR rule for 10.10.0.1 is silently inert here). -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: sirius-growth -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: sirius-growth-allow - namespace: sirius-growth -spec: - description: >- - sirius-growth: gateway + kubelet + Prometheus ingress; egress to own - namespace, cluster DNS, the internet, Garage/SSH on node IPs and the API. - endpointSelector: {} - ingress: - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace pod -> pod (app -> db, sidecars, the backup CronJob). - # Cilium enforces policy at BOTH ends, so this allow must exist in ingress as - # well as egress — measured on `piedmont`: with only the egress rule a pod - # could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: sirius-growth - # The CNPG operator (`cnpg-system`) reads the instance manager's HTTPS - # status endpoint to derive the system ID and drive switchover/promotion. - # Without it the Cluster reports `Instance Status Extraction Error` and - # Ready=False while the pods serve traffic, and automated failover is dead - # (card t_4210edec). Scoped to 8000: not 5432, not the whole namespace. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: cnpg-system - app.kubernetes.io/name: cloudnative-pg - toPorts: - - ports: - - port: "8000" - protocol: TCP - # Prometheus scrapes the CNPG `portal` instance manager on 9187. - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: monitoring - toPorts: - - ports: - - port: "9187" - protocol: TCP - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: sirius-growth - # Telegram Bot API + leadgen crawl targets. - - toEntities: - - world - # Garage S3 on the Pi (10.10.0.1) and the Linode (10.10.0.5); leadgen-backup - # SSH/rsync to root@10.10.0.5. Node IPs are `remote-node`, not `world`. - - toEntities: - - remote-node - toPorts: - - ports: - - port: "3900" - protocol: TCP - - port: "22" - protocol: TCP - # CNPG instance manager <-> kube-apiserver. Port-scoped on purpose: the - # apiserver is host-networked on 10.10.0.2, and Cilium attaches the - # `kube-apiserver` identity to that whole node IP — an unscoped entity rule - # also opens 8081/8084/8085/8086/8087 (the internal Gateway listeners) and - # :10250/:9100 on the same address. Measured: 10.10.0.2:8085 was OPEN from - # this namespace until the ports were named. 443 is the service port the - # CNPG instance manager dials (kubernetes.default:443 -> backend 6443). - - toEntities: - - kube-apiserver - toPorts: - - ports: - - port: "6443" - protocol: TCP - - port: "443" - protocol: TCP diff --git a/apps/base/sirius-growth/secret-cluster-backup-ssh.sops.yaml b/apps/base/sirius-growth/secret-cluster-backup-ssh.sops.yaml deleted file mode 100644 index 2c0ad11..0000000 --- a/apps/base/sirius-growth/secret-cluster-backup-ssh.sops.yaml +++ /dev/null @@ -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 diff --git a/apps/base/sirius-growth/secret-forgejo-pull.sops.yaml b/apps/base/sirius-growth/secret-forgejo-pull.sops.yaml deleted file mode 100644 index a3b393d..0000000 --- a/apps/base/sirius-growth/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:0DHKiX4UaYk314D7LEtFEL2XHHYSxjy8Ezde2ZEWjbHzNxVTbV3lLvCEVGcfh5OpWvWjJ0nu3qf7zHZtYpurXpHQW//BsYXcMGsfTcNO2DeTAd2YZ71FRp71h3hruOR97rldz1Fias8ko2e6QtZMo3ZnuWXnmOEt/y03YHJcOZl2FrM3ZZvdvpRV/wOidpj1DxYQkJqYzhthg3BWd69n45fpNbqIz5RAr+prtEHhxW3CU5/qH+kYVagEdVx+pP6x1L5+7vtGU9vLspk1T6ffoRZ1i2tWwbNCUHRnxzuXVY46Ar+Xz0wPwfpRXwv9PN85Bc1gS8JPy1Tk/ecBp//KfYK1xYF0SRX5axb5BtdlYYNJxPAkqKVx444Rs/FPLpcl,iv:fXN6LROLY1vbOQMmrGiiOztYgulXDV2uZXQhaPnK0Q4=,tag:LPu1DaQSkddNbWbYP5dwcA==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: sirius-growth -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBiLzBrd29tNkZpWVh4K1BJ - UWtMMGhsa1RqWG04dkRHaEVUUm5MZkZyRVhjCjdCb2hEYlVCY2hBcEo2Mnk2L1NC - TTd1NnNYU1c5SFNpY3hYY0t1Z2RHbnMKLS0tIFFQVGhodllFUExIV0ZCZm0vTnlZ - ZFE1cURYMU41dmw1T0F2dC9BOFRxMm8KrBF8/v5iSPWYgS6Nb31xJfhJWZHDUk7p - LMZHsoddSToOr4CqL8y91ka7MCtUyoJg1NiMnEng+KpI+EpaGjkQlw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:RfT47fcDHgOxbjX0HBwtFo6ddD5ijW0QahnTJor1qanCH6pFwqmlJM0BuUTcXfCQmyijJ1SKbaOPQEnkQ0O4zLh2mdUEoSCH7Ig4a6tTVaIVm2kwWfi5Un/uQ/Ok0f+Mc9Bjk7PslSO4szsu6/Q0EeSgVaryTZpslkg0q5NEi80=,iv:L0s0e3RRKKeXcu9tS4stXi/0CSxE9e5NS810jTIrHmI=,tag:fKt1vciLFy9U7JFu31p/fQ==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-portal-wal-s3.sops.yaml b/apps/base/sirius-growth/secret-portal-wal-s3.sops.yaml deleted file mode 100644 index c43d484..0000000 --- a/apps/base/sirius-growth/secret-portal-wal-s3.sops.yaml +++ /dev/null @@ -1,25 +0,0 @@ -apiVersion: v1 -data: - ACCESS_KEY_ID: ENC[AES256_GCM,data:Lv5TNsSVLCh03dNOmamaf0N5bb0Os7KSoAKr5fuY+DLv/mtK,iv:0aAyylLmxqr9vaqTjYu81KmwbQdtR5+b9Yp4dyLuUb8=,tag:IqPPBBmAJ6cqAFiX+5+9RQ==,type:str] - ACCESS_SECRET_KEY: ENC[AES256_GCM,data:mpRJy20dQIHjqAV1iWH03P/QwX0R21aF1Y6v5ieKvYIEf+y1P8S9+HJOsHCc3LImRaUterbTWNFNXivdkBpWUCoAIQgHuYwFXhDBfxuK35kfTvcWtfrOqg==,iv:RCxJy+2pOib0dhLQFzz4uEjdRCvvqJNS9FcCIIClPwM=,tag:0+lhnpO5+lHsKCnOvaA5EA==,type:str] - REGION: ENC[AES256_GCM,data:jhWHctCFNl8=,iv:QoO2S/SpsAI4su0Bc2WX8qvEVu1IVt4NqBZdu9jmNG8=,tag:oAACcO+Oi6DlwMMoRR3STQ==,type:str] -kind: Secret -metadata: - name: portal-wal-s3 - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBjd28zeWk1ekp2NlB6S21N - UVVleGM0NjEvWGNuVU5GbmFYWE1ad0hBb2o4Ck5kbC9FNGo5WndpQ05IY1Z0S0cx - aTZlb2g4WlpJTi9ibU16dloxUUtIZEkKLS0tIDBldFhyT3U3ckNiV0hpS1o2Tjdn - enV0L0hPakdva3k2K3pEWFZTMUtSSHcKhO+8DmGwgiRYOBkRtyHroHs2uU8/96fi - VfceBBfXNB/h4Hmt99xuVoEiPSnOAVS5/itBArTMoT1iZdD3gadQqw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:5RK21+O7LMmj7P6bZW5uITv4v60fq7PUJfsIBgNrLuKzplOcSHTrg+8HVN7X2mMxzkjeNshh4FC3Kkc62mIoWk9ECpboZFAAuFIY0T+m/AVsZXBY9QswtwYH1zpN5xmWvAsA5kbx8WkwsFMOTUeF8/nPrGi/oTW15PxmfmT8xNY=,iv:TPiYECXPnz+vvMqQv0JpyTdZ6dzVQpALyvDXXws170I=,tag:MpneZrMZO7JI9J7bmhv3JA==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-blog-app.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-blog-app.sops.yaml deleted file mode 100644 index e7a15c1..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-blog-app.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - database-url: ENC[AES256_GCM,data:2WCA8rHmHIPinTxigCO8tn+dljO1slCXyIRtkQ84v3ekUTRFMuSWL9t6FcnT+MEmogx/MsV3ACxmOfLGZH4FGYsRc9i2SmjqZ4YGlw43HUU58+IlKN8lMRQdFj6ejevBqpwkvMySLkrm2WWaUsYhL+YnwW8svtF1,iv:qYAQONgV0fTYZxtmsSMpXnJPc3OWO2doGdIBJS4Vipc=,tag:xpn8aTWuqaXVPPEs/DnOZw==,type:str] - session-secret: ENC[AES256_GCM,data:39e5B6+dkhr/aa2t/zELR4EJbqbzs1u27UW4AqE1IjtYIAU2EuGGx/Lje7+zrG4s2SKq3EtNwYbINXn/zeL5n/KxboIqSWOPVvmQtU/29qShPVonNkdugw==,iv:+TyDMebxlcRyZDysmeB1WU+oFb9sFMmQDdVzgWt9jD0=,tag:y1tL1gB8Ri/byd3B9htfjg==,type:str] -kind: Secret -metadata: - name: sirius-growth-blog-app - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBBVzMxcXlSMkYyOFRkV3Zx - eGw5Z3RyOSt5Rm95KzIyZTdPclNlSi9IcVJzCmZ3bXZQUHNoRlZhT0JDdmhnZWtO - VVRyUGhKR3V2eHAyb1VzK3IrQXdnZmcKLS0tIGtVaE5NSloyNzJRUkNpQTE5YnZw - T3JsdWtQOW5UNnFKVnJUZ2lOMUdZVjAKEN0eeLT3uMUmRq0RK9WG9I2lpaUMe3EY - +U0nqJnW5ZRO3b32Y7akBu1Tz28Cz/IQo0G+bvXPeBY7tKk8mpP+qA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:hZ92xr8GDGxfeU/sTiD5ouRAZQBHg73B2Rick7OIKWPqFro4tlT7v7qjh32QiysQ8GkJmFN0O3XPuUHF7pKC4UsBrhJi4Co4LUwDib2SrW1OcKEompEdbxO/etg62X3e5LrpaT+ZM4XhYnfUB4lePBX0/dR6T93LtLy0vj/3ktI=,iv:H0Xbgp12vFE9iIAk1emRHOBpPQ4/JSLXMEHrdN1S+VI=,tag:suPN5kd3i6gfw5mhPVpPqQ==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-blog-s3.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-blog-s3.sops.yaml deleted file mode 100644 index 2a3268f..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-blog-s3.sops.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: v1 -data: - access-key: ENC[AES256_GCM,data:BtN7ZYQGm7A6tsBOAMtjtnnJ2ZyCEZiq/6uEWeX4DHy5odX9,iv:0zqKRhHNfw2bv4lMPaHFork9gF+cCTIHCyrM0HtBu0k=,tag:cqvknMjaZzjnyAX6zJ0eYg==,type:str] - bucket: ENC[AES256_GCM,data:tMWUruYwF2hm3rLjl3o1E2BKvpBovVd4znml06lhTpk=,iv:RbHt9Ixr/HEv+ltz57/SCIBEUjjCkNe+wZYKrqieTCU=,tag:epB2Hze7XTAY6Y4AosXQRQ==,type:str] - endpoint: ENC[AES256_GCM,data:3SenxTQo0dclXi8CuV9m0MTJjEFAQwgM4F40QA==,iv:IaJ+sXMaT4IY1DvzjdWV0zAZP8AT18ET1Xm/FD9j8ls=,tag:SRkXngDoQJ/z09AAc3wKZQ==,type:str] - region: ENC[AES256_GCM,data:QBD5OjJUjmE=,iv:tKkFWn/qHhytbAN8gJc5qHC8NR7RmSwaAC3wZv6zklU=,tag:zuhx6B4zn1wSZ7spR3UDRw==,type:str] - secret-key: ENC[AES256_GCM,data:DwyLvmvYpHtflz6em+vIYFM1fAfrHYunRRnl7vpjG+LyE2m/sJQRP5OFGmIggWoiDiz53xCoMTyXXlwheXvLqUe6qy6uicJ2mftjsbjx2OFy0Z/alJzNHw==,iv:gl3bUTMqhQ4bSefvq/r0uQwZ81+m3JZNIxUAruq7XtM=,tag:F3BKwFB1Pjnft/trtk8/6g==,type:str] -kind: Secret -metadata: - name: sirius-growth-blog-s3 - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA3dE1HQ3RWTFJubW5SeU9S - R2ZNYXhNbDVWSDhQWlM0bVNCaWQ1aHV6TEN3Cnp6elpDUkJnV243YjhWQnZXOFBW - bnFYcGY0VTN2aWUzNVl1V3Q1RDI4VmcKLS0tIDAzbnhabVVmOWlSTmNXZ1MrTXUv - c0N0a1hXNTNTdkVjekFid1BXNTU1alEKH7dMTV3thHyo4b/Qnr7F4PmK5XEn4fFA - NJTaVnfqrmDfHjtOBl+D7xR0TnsJGhm0QN8n85mZOs/Ye5Ad1z1zeQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:o9fPTAsNSJ3zZ73Js5oxLCA94n5EHl2wuNfpDX6ADPPM1sRKes1IXCUV803ntWuyKYSa4SOeqSRxmyQobAjLwAfY6SCQA3ICrsZ1Y28Q+1XnpXapQQj/eCOKkg3yvGV/6k8SHxn9xPPatYSYlPSfShpl4NS/ir5NkLnTIW6f4OM=,iv:lLmi9HRrb3Tfw/R7mxGJAGSd7fOETy5orLIk4zP4d38=,tag:xsYWzmDfJezbqZZ2fuZU9A==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-contact.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-contact.sops.yaml deleted file mode 100644 index 0628c79..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-contact.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - TG_CHAT: ENC[AES256_GCM,data:e+QEGcrfPpYCFu76XkhY2w==,iv:fSJndVBB/owy6AoDkfzmUXZSQ4BqvsDoZRbtgvGhaBw=,tag:2JuXWABvTrzcRWZ8J5PCiA==,type:str] - TG_TOKEN: ENC[AES256_GCM,data:tTSb2RRLwSqO+ajl5yHf1BG/AQeanjkBgCqHfNdcwPDESWAlkQTsQJI2m9qqjGmv7qJuLURegRkbRsB3JPM19A==,iv:lSs4+c6k6nSKjpQ8AbXss4ezHOp20G7+DC/7F3Y+AhA=,tag:rFUxlfv0PnRBXYZ1qvXO5Q==,type:str] -kind: Secret -metadata: - name: sirius-growth-contact - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAwUWpYZ2tFMnFTQkNTWE1V - ZmxDL2JCdnVsakt2QVRiTEk5amdEa2UzcUQ4ClBUQU0wOXVPRUMzcTM0UnpYeVNM - UHc0WUZDeE0xM21udCt4ZGRjbUNWRzQKLS0tIGE5Vk1jbjNYZmQ4UVN6YkhRa3JU - bU9VVkYrMTdGSjdySFBxcHJXYTdFOGcKZloleo/maxhWJtUrtW+VZSUxeGNfQkUE - FtAMWO8zZMDpGCPknqrhI/yFs8qn29MtZMQ/5NCxWpNhRxg2/nr9rw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:qdq1M5K8WOJ2mb1S6sjIq9zibau7EeFqKDbpaQoyfypa+NxtBUk6XvDqtb4Wg4503D/AeAvJEbfe1a5rWCBuyD90g0vkj+4S+QpsEh2mN3hHAk96iG+FhNeJtVLDWVOAlgW07BIXx9mcvhFd2eDBSYSZJfS7wWdi52cS3AMZ3C8=,iv:vJ5uJuDkipDrmKiphNPqFMLTN3ChF81lgg5CuoZt88w=,tag:ThS0o18fBByDUu9t1N8a4w==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-portal-app.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-portal-app.sops.yaml deleted file mode 100644 index abf9bf2..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-portal-app.sops.yaml +++ /dev/null @@ -1,31 +0,0 @@ -apiVersion: v1 -data: - admin-password: ENC[AES256_GCM,data:c2nD05J0TxN0nfXtULxT8j/StqlYnfU1vnVkSECdKFtWrE5TkDU86g==,iv:22eU1MDXc+p7R+67qcxADWgyuQkFv9H+XUXo1N4wlm0=,tag:uiAgvJrG0gKMvzS/QEp6Kw==,type:str] - admin-username: ENC[AES256_GCM,data:hGuuNqBS46k=,iv:epr8YnClNEKaHoHF1AW6fY8qMJJRAVTAHfBGV7hBxaU=,tag:QbMOgrY+l1ZnJcil523Zkw==,type:str] - database-url: ENC[AES256_GCM,data:r/2PM6hoMQVFovTf8DKoa/xk9BPV2t3iz2FC8UauvgFSUpMn+EnH8WVCmhJT4amdJ4vhGYX9d4Va54fN8mqw2c8+vERzOkML9XRIVx+tcnln+PKb6BFZGYsrZg1QUmHsyN16NET/NgR2PDIVO7EuqvoS58ngI3fOFZQMrw==,iv:HeRpZylpUTKw3ZdOCeBtGE0d+87rnfYD4LmBPZT1dG0=,tag:y+zfJaLY0loBvuG+fAcwEw==,type:str] - s3-access-key: ENC[AES256_GCM,data:PP5id3M3UCw/M172eVgVcwdkdZRFZUGqh6jnO2dTBjEfL6FJ,iv:e+tUjdmIREAmI1YUxmn4q0NHoP6JEQT7L4d6hBF1tJk=,tag:ssCw3sdIY8QVaT/F4Zu88g==,type:str] - s3-bucket: ENC[AES256_GCM,data:ia/9b7m2juowxhyvGgARpZqN59iiBq2vfPCdXKqmxmGO/dtU,iv:uRy1PAJPX8/X/buDsDmTbb2oKF5jj9PSf3SivdE7lF0=,tag:vmtpngDN3xsFl94Ipq4Mag==,type:str] - s3-endpoint: ENC[AES256_GCM,data:m9P2j9rlA59nkU0mGGELr80VzDGq6J3LG6/x3Q==,iv:WOsbR1zzhFBF3tb9fTsEG/PA1xv/HtWguuj1eew2l/U=,tag:5EMVNv5UTsM0w5XvyCaOtA==,type:str] - s3-region: ENC[AES256_GCM,data:r1GPY6okYy8=,iv:INWRwicCmKKJQ6k5qfeS1AlvbfKZUAJ9qKXycMtajZ8=,tag:2c10isLJoAV8VuJkp0rPJw==,type:str] - s3-secret-key: ENC[AES256_GCM,data:xd+salTGR8+3cYWx1MS6lRgNt3+uxlQRWRmGjQ2kp2WntxgSw2bO6TJbIRuYZ/ofJhiIhdzZwtz0/kHObzQGp0lJBD0peUi0Md7fyMZIDSIyox/DMWFVjw==,iv:cPKLOrANOhnmdx46O17s4zT28pZBoFY3QZMhfWbI7ec=,tag:o9XtqCQxwg9SlsWM+s47pQ==,type:str] - session-secret: ENC[AES256_GCM,data:r+e+fcOx/n5B+HFOVSqUi9J3ZFs3bV3n20rHJ1YbJypMsYvF6/ciKByQccrk4XJj/mh5Vv0EpoAZZ3H/CBbmD+KXhD1fI1urCLuQWQU2keoNTYvtjpJ3YQ==,iv:HPtEQoDYMRzh7EHsI4Bq/R6FP3fGKfXlHWWWToWl2kM=,tag:9TUSmWKmSoAv1niDiRrbRg==,type:str] -kind: Secret -metadata: - name: sirius-growth-portal-app - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA4SVRoZVdYRDhzSnNnTWtB - RUp1Y1ZkaWVIVDJySkhNUFNMLzFKb0I4OW5rCnNJZDRVaWt0c0hCcmNnMFQ1YnFn - UTA3Y2YwMFVVREMrNlFGY0x3ZDdRUzQKLS0tIEVuRXliaFVqUExHV0hLenpkZGI4 - STNPZGp2OEl1ditNdEVzbTZGOTRTN0UKb5K3XFqg4dssLmJ7bIydniEYdgIX+U/J - 18wlw+xjEkYt8hbomMuGMzmb34xB8aqBFuGIqIgAE7X1TmdJjdLSBA== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:S5NpEd6GQ2CCIA5IubpL4ZujlolgxXSOj+xFN1+OdSO4IzVmHu9N9pOjvTOp5yoO0uVRUtcvb26ZdGGRhFShH2oSOgowyHYPZoP/+ISkEcnq8I+T+eP7vMRjJhTxPY99U8itBQEcVk86ZxwUvB0opDEfKcs6sWtSdBAYF0km96U=,iv:pgF2hY5UMXsEo6BK7Lvc8N0qgsaRujm1J+Qn2N/9zrk=,tag:M6PsAj1O6ZIczmo58uY/Ow==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-portal-db.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-portal-db.sops.yaml deleted file mode 100644 index 05ff8cd..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-portal-db.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - password: ENC[AES256_GCM,data:nyMG2GOfeqrLf/Wrc8gpJvWvhmt+mOl4cufF/jEjN3RFTuOxlA2Dpv7Tkcc=,iv:FcVjGBS3VTd0uiIwtCR9bKTC40bBd06NgEiejg++qBM=,tag:qPbU3aXoQUY//ZtsvhZVXw==,type:str] - username: ENC[AES256_GCM,data:MGxy7B3XPoY=,iv:Yl9kg/miYjB5ztWgkNaHotAL9gAJOr0sIIzSnsfJb40=,tag:F6C/xFr7siImFTwejk4qVw==,type:str] -kind: Secret -metadata: - name: sirius-growth-portal-db - namespace: sirius-growth -type: kubernetes.io/basic-auth -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA2cWg3dXdEalVsTjdrcDdq - dVZuM3pIUk9QS1VMLzYxdy94NkFFZzdyZDM4CnRsemVGZUFSMyszK2dTcWtDRzlw - UVFKNVlLWUdZK1g1T1ArdGVpVW9LSmMKLS0tIHI0UG5TOFp0V2RvTVdyeThjL1RM - ekVXekpNdDRTMlppLzdtMWhBcXpuR0EKD4Up4T0fZBvTo4CaT1++eEABGq3QqFWf - jKVP8HH7rrfL3vFiURBq+5hnveGOdG660tOhUwObfqQ+/By/Hd848Q== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:R5ujg3tKTtRJ5xP0n0B4QxLAY17BsMT4PUQS/I4FsGdF3WbWe9a8NDCuauLSW5iWiLwrmnrV+BfTwSFLwawFfFCu06z4+XuqrdRP7MQ29jfnqvMO1rHhO41egJK7D8qZhOlSJSgIjqjP8NmsbAmLDKacUUkK4Iac3xUChJIGUlg=,iv:ntiQQVeTAoz+zlFUsZjqEcrKajv3I9jIHV3HxKZUWMA=,tag:KtcVneaGvgNIYbUVyy69tw==,type:str] - version: 3.13.3 diff --git a/apps/base/sirius-growth/secret-sirius-growth-portal-s3.sops.yaml b/apps/base/sirius-growth/secret-sirius-growth-portal-s3.sops.yaml deleted file mode 100644 index b7f1c1b..0000000 --- a/apps/base/sirius-growth/secret-sirius-growth-portal-s3.sops.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: v1 -data: - access-key: ENC[AES256_GCM,data:nQYK9vgxtGAnxzKatbwBIEdCSKy6PhE3ulzPvVBTxiY7GqCL,iv:PW6Q7Kdq8leuc8wc9JxqX2Sapi1B7JgY5HjNJG3/Jng=,tag:giD4hBn8MWPDD2tUkEGMRA==,type:str] - bucket: ENC[AES256_GCM,data:uNHEPKxdXj0tO3ZLbscAXkNCaU5r5iycob8PZSr2136PxwMH,iv:HWjxUhKQvlU9+jstZDQDFAFk8Zl85sR/V/s0z7VsGcE=,tag:K6xU2KeysNCsqJmgCnITCw==,type:str] - endpoint: ENC[AES256_GCM,data:YiGTsqLihDGvgd9fOheQP+qpi3oGa01yuqSZAA==,iv:OXvr8v1r8OhIjfle2FZSHy5C9gLEn1VPjhz2tntapRE=,tag:fAuc5hodGd1G6E44pYCmAQ==,type:str] - region: ENC[AES256_GCM,data:jCReGhHjKME=,iv:GEFo1jMowRopFJXqg0MhlB7BoeKy9QUAgF8oFEBJoEY=,tag:pbgVYEG9eJLxQc3e9qBMjA==,type:str] - secret-key: ENC[AES256_GCM,data:+cVJh8vODYlikPd1wZUybU9CKavcQNkGUiN3/rIgUKYX6VJr2Vdkhog0lGtWtbEl6ztHtOZYtJKvVGtQsVNaodTiySuhzURdKGECeeBDPYAXuyWoqPCNqw==,iv:KJ2eychXLLI0Nm4CkWCUG8n/sOGcUYOeEjKsz9Spwio=,tag:Q2z3WkLKAanqdN6LDDnBeA==,type:str] -kind: Secret -metadata: - name: sirius-growth-portal-s3 - namespace: sirius-growth -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAyNG9UQU02SmVocUFSQzdF - VER3cktyekQzRHRXa1lrVkkyYTNKQk1EQVdNCnpvVzUvdVNlN0JOUVhkRmxEY21E - YWJlYWVjYS9Xd1VKcU1tM3lsZ29XUHcKLS0tIGlWc21ITnVEZjVPR3JVcEdLQUNN - MEZoUHF6U0xuSFdoMlpvMm1tRGtmc1kKaTnCrsZh2R42IibOojqWWiwpxGS67o9b - vFqpBh25ouxekmJJTdKUApj/GcfqTIiF2PN+05uciWH9SnZl0Ms0wg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:44Z" - mac: ENC[AES256_GCM,data:ibtGyLLBwMgOZuVMRi8uP/vJXYAFv0Y3sy4TROdMnx+Nx9e6uAvCM7nQAWLxKWRN95YGTyAOET/q1Pz1Gm3ipgMa22iIEhH8QqoRl1ruIrUoNAvR/snpt9SxVS1TiCZBszKxpg2+fUXffnSqB5F6N0K3kppVaI7vYBuqYMcMi8Y=,iv:zHefLJ1EhblzQzb3N1IPctOLP1BLSYKGSRkLagP03/o=,tag:musgvP5M2M5ZnHD7LEnEHQ==,type:str] - version: 3.13.3 diff --git a/apps/base/siriusdevops/deployment-api.yaml b/apps/base/siriusdevops/deployment-api.yaml index 938d179..79b475e 100644 --- a/apps/base/siriusdevops/deployment-api.yaml +++ b/apps/base/siriusdevops/deployment-api.yaml @@ -13,8 +13,6 @@ spec: labels: app: siriusdevops-contact spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -23,7 +21,7 @@ spec: kubernetes.io/hostname: siriussec containers: - name: contact-api - image: forgejo.siriusdevops.com/sirius/siriusdevops-contact:467b0875c24af2c69962fc246fd31044d3f666be + image: forgejo.siriusdevops.com/sirius/siriusdevops-contact:8642f1a14b1dd9f217e32856b7a9ea0a0c37e3aa imagePullPolicy: IfNotPresent command: ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8090"] ports: diff --git a/apps/base/siriusdevops/deployment-site.yaml b/apps/base/siriusdevops/deployment-site.yaml index 30ff7b1..67f1fe5 100644 --- a/apps/base/siriusdevops/deployment-site.yaml +++ b/apps/base/siriusdevops/deployment-site.yaml @@ -13,8 +13,6 @@ spec: labels: app: siriusdevops-site spec: - imagePullSecrets: - - name: forgejo-pull tolerations: - key: dedicated operator: Exists @@ -77,7 +75,7 @@ spec: memory: 128Mi containers: - name: nginx - image: forgejo.siriusdevops.com/sirius/siriusdevops-site:3ac9870aa7637cffb789edcc16b9512d7567886d + image: forgejo.siriusdevops.com/sirius/siriusdevops-site:399c421f51a2fd74a87e810641226d58e4e22690 imagePullPolicy: IfNotPresent ports: - containerPort: 80 diff --git a/apps/base/siriusdevops/kustomization.yaml b/apps/base/siriusdevops/kustomization.yaml index 406a609..aa601cb 100644 --- a/apps/base/siriusdevops/kustomization.yaml +++ b/apps/base/siriusdevops/kustomization.yaml @@ -7,12 +7,4 @@ resources: - service-site.yaml - service-api.yaml - httproute.yaml - # Replaces the egress-only `siriusdevops-site-egress` CNP: same Garage + - # DNS allow, plus a namespace-wide default-deny and ingress rules (F3). - - networkpolicy.yaml - # Secrets, SOPS/age-encrypted in git. Flux decrypts them (the `apps` - # Kustomization carries a decryption block; key = flux-system/sops-age). - # Never add a plaintext Secret next to these — see docs/secrets-sops.md. - - secret-forgejo-pull.sops.yaml - - secret-garage-media-s3.sops.yaml - - secret-siriusdevops-contact.sops.yaml + - networkpolicy-site-egress.yaml diff --git a/apps/base/siriusdevops/namespace.yaml b/apps/base/siriusdevops/namespace.yaml index 2dd8d1e..8776e93 100644 --- a/apps/base/siriusdevops/namespace.yaml +++ b/apps/base/siriusdevops/namespace.yaml @@ -2,10 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: siriusdevops - labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/apps/base/siriusdevops/networkpolicy-site-egress.yaml b/apps/base/siriusdevops/networkpolicy-site-egress.yaml new file mode 100644 index 0000000..389e5c8 --- /dev/null +++ b/apps/base/siriusdevops/networkpolicy-site-egress.yaml @@ -0,0 +1,70 @@ +# Egress policy for the public site pod — the first policy in this namespace +# (there were zero before 2026-11-19, so every pod could reach every WireGuard +# address). +# +# What it is for: `siriusdevops-site` runs an initContainer that pulls owner +# media out of the private Garage bucket over the mesh +# (http://10.10.0.1:3900). Nothing else about that pod needs to talk to the +# WireGuard network, and the pod is internet-facing, so it is the right first +# pod to fence off. +# +# WHY A CiliumNetworkPolicy AND NOT A networking.k8s.io NetworkPolicy: +# 10.10.0.1 is a CLUSTER NODE (rpi, the WireGuard hub), not a bare address. +# Cilium resolves it to `reserved:remote-node` (identity 6) in its ipcache +# (`cilium-dbg bpf ipcache list | grep 10.10.0.1` -> identity=6), and `ipBlock` +# / toCIDR rules are only evaluated for `reserved:world`. A standard +# NetworkPolicy with `ipBlock: 10.10.0.1/32` is silently inert here — measured: +# the pod's request to 10.10.0.1:3900 timed out exactly like the denied ports, +# while Prometheus (unrestricted namespace) scraped the same host fine. +# +# The narrower `toNodes: [{matchLabels: {kubernetes.io/hostname: rpi}}]` form +# would name the node exactly, but the agent rejects it unless Cilium runs with +# `enable-node-selector-labels: true` — status: "FromNodes/ToNodes rules can +# only be applied when the \"enable-node-selector-labels\" flag is set". Rather +# than change a cluster-wide Cilium flag for one policy, this uses the +# `remote-node` entity: any cluster node, TCP 3900 only. Every cluster node is +# on the WireGuard overlay, so this still cannot reach the LAN or the public +# internet, and the port scope is what makes the denial test meaningful. +# +# Scope: Egress only, one pod selector. Other pods in siriusdevops (and every +# other namespace) remain unrestricted — this proves the pattern, it is not +# namespace segregation. Ingress is untouched: the Cilium Gateway must still be +# able to reach nginx on :80. +# +# The policy is a whitelist: once it selects a pod, ALL egress from that pod is +# denied except what is listed. Two allowances: +# 1. TCP 3900 to a cluster node — Garage's S3 API on 10.10.0.1. Deliberately +# port-scoped: 10.10.0.1 also serves the container registry on 5000, and +# that stays unreachable from this pod. +# 2. Cluster DNS. Nothing in this pod resolves names today (the S3 endpoint +# is a literal IP); the rule costs one line and removes the trap of +# breaking name resolution in a pod that later grows a container. +apiVersion: cilium.io/v2 +kind: CiliumNetworkPolicy +metadata: + name: siriusdevops-site-egress + namespace: siriusdevops +spec: + endpointSelector: + matchLabels: + app: siriusdevops-site + egress: + # Garage S3 API, on a WireGuard-overlay node, port 3900 only. + - toEntities: + - remote-node + toPorts: + - ports: + - port: "3900" + protocol: TCP + + # Cluster DNS (CoreDNS) only. + - toEndpoints: + - matchLabels: + io.kubernetes.pod.namespace: kube-system + k8s-app: kube-dns + toPorts: + - ports: + - port: "53" + protocol: UDP + - port: "53" + protocol: TCP diff --git a/apps/base/siriusdevops/networkpolicy.yaml b/apps/base/siriusdevops/networkpolicy.yaml deleted file mode 100644 index 5f13682..0000000 --- a/apps/base/siriusdevops/networkpolicy.yaml +++ /dev/null @@ -1,88 +0,0 @@ -# Tenant isolation for `siriusdevops` (audit finding F3 / A5-1, card t_fed52919). -# -# Replaces the egress-only `siriusdevops-site-egress` CiliumNetworkPolicy. That -# policy proved the mechanism but restricted one pod in one direction; this file -# adds the namespace-wide deny and keeps the two allow rules that measurement -# established: -# -# WHY THE GARAGE RULE IS `remote-node` AND NOT `ipBlock`: -# 10.10.0.1 is a CLUSTER NODE (rpi, the WireGuard hub), not a bare address. -# Cilium resolves it to `reserved:remote-node` (identity 6) in its ipcache -# (`cilium-dbg bpf ipcache list | grep 10.10.0.1` -> identity=6), and -# `ipBlock`/toCIDR rules are only evaluated for `reserved:world`. A standard -# NetworkPolicy with `ipBlock: 10.10.0.1/32` is silently inert here — measured: -# the pod's request to 10.10.0.1:3900 timed out exactly like the denied ports, -# while Prometheus (unrestricted namespace) scraped the same host fine. -# `toNodes` would name the node exactly but needs Cilium's -# `enable-node-selector-labels` flag; the port-scoped `remote-node` entity gives -# the same reach (any cluster node is on the WireGuard overlay, TCP 3900 only) -# without a cluster-wide flag change. -# -# `default-deny` (stock NetworkPolicy, podSelector {}, both directions) is the -# deny. `siriusdevops-allow` (CiliumNetworkPolicy) re-adds: -# ingress: Cilium Gateway proxy (`reserved:ingress`) for siriusdevops.com -> -# site:80 / contact:8090, plus node/health entities for kubelet probes. -# egress: cluster DNS; its own pods; `world` for the Telegram Bot API used by -# siriusdevops-contact; node IPs on 3900 for the media pull the site -# runs in its initContainer (Garage S3, http://10.10.0.1:3900). -# -# Port 5000 (the container registry on the same node) stays unreachable from -# these pods, exactly as before. -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: default-deny - namespace: siriusdevops -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress ---- -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: siriusdevops-allow - namespace: siriusdevops -spec: - description: >- - siriusdevops: gateway + kubelet ingress; egress to own namespace, cluster - DNS, the internet and Garage on node IPs (TCP 3900) only. - endpointSelector: {} - ingress: - - fromEntities: - - ingress - - host - - remote-node - - health - # Intra-namespace pod -> pod (app -> db, sidecars, the backup CronJob). - # Cilium enforces policy at BOTH ends, so this allow must exist in ingress as - # well as egress — measured on `piedmont`: with only the egress rule a pod - # could not reach its own Service (TimeoutError). - - fromEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: siriusdevops - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: siriusdevops - # Telegram Bot API (contact form delivery). - - toEntities: - - world - # Garage S3 API, on a WireGuard-overlay node, port 3900 only. - - toEntities: - - remote-node - toPorts: - - ports: - - port: "3900" - protocol: TCP diff --git a/apps/base/siriusdevops/secret-forgejo-pull.sops.yaml b/apps/base/siriusdevops/secret-forgejo-pull.sops.yaml deleted file mode 100644 index 305461a..0000000 --- a/apps/base/siriusdevops/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:FGTPqAwCijts4PwpAdGaasBaOAEreJh1JU/fRvn6SqQCPxb0rJlzl8eOVP6dqfGQkR+gct/5xTI6PfUXzD6ElgjPba9K+D/TTz2y5F2h0N9eKVewnMWywR6XaW1tGEjXazapFUDxLzGbCTG9jyEmjDbgIBHqYzCAro1OrsuMZzzFzeQjLFbxWE5HDPPXcHua/j/3LWS77gl7g4PIeWoKfvmsNwwewakRRiLyk5fJ1+4CRQMEoVcCejxiYrMcGqrONhLwIPpuvq04jRT4eo+SowTWWc9vVLf9YSTEy2MAO61yBoPGquScAN8LwQGWIH5oSOr6nWmHh7LLqXRbC+S2DH5SdessYpKv4OrBdSqXMOmLhqAOkqdcNYI1rXlA/40r,iv:a5Nv5UnfBGNlPKqiLcXGITcfU/W2yuqOv8DzG28l6M8=,tag:04HkP6cRcdkbdlPEuKcWwg==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: siriusdevops -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBuTlUwOXBacU5GbkkvUXhk - WFZ4RWtDRjJCbzhkUEwyekZ4OXBZckFETmlvCnJaTjlMVDZDWnVSNXNiM09KRE1Z - MDVsMlZROVZVKzY5enRrVHkzc2VuQVkKLS0tIEF0Z2RqaHdsdFVmcjlCWGJGdnpj - Q2JCNVNPbG9pVGpVTXBoa3o1ZjVQa0UK7ADGX0391HfrzCMRhGciJgpajKUyzJ4I - gCvkdu8SeNFyoktlaQDIqjjWjY4LVG4koUTQF9kb6aZqyJrwDB5XQw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:42Z" - mac: ENC[AES256_GCM,data:5DZxAeqDmCtX2F1SJiXVwVP4mOyWh8XfUQRwNbyYF9pguAgq8NSTC+ZwF2HpUUZa+tzSU6M/wr4hJKtEbkxAOVMN3AhKcR7xfzXsrnOYGU1nW4eNc8J4e3+m51d6gZrN27HWGCWQakM+E/tj2h0F6h7U+07sVlOfEzLnLYRn88Q=,iv:Po+2Y2CQdPkWnCcuxfsdmrUpNe1eHHkbdIqujTDjbss=,tag:vdNJzH7rPlgXe6LKMKLbVQ==,type:str] - version: 3.13.3 diff --git a/apps/base/siriusdevops/secret-garage-media-s3.sops.yaml b/apps/base/siriusdevops/secret-garage-media-s3.sops.yaml deleted file mode 100644 index 467abf8..0000000 --- a/apps/base/siriusdevops/secret-garage-media-s3.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - AWS_ACCESS_KEY_ID: ENC[AES256_GCM,data:ZFFYbez5y5eM5zYyTpWsPWz6AOuSTSRfg2cnqxiyPFxF2MNy,iv:Ii4KlCf1qmYdM/1BK5Y06MCyIS5xjBnBV+uB/pPNDc0=,tag:aS9VAusLyv+GXaoZx8fnhQ==,type:str] - AWS_SECRET_ACCESS_KEY: ENC[AES256_GCM,data:6UCRnrORf/EVtEl4ZBPpLBLzLlZ6C+sxPx9Q4WzEdW42UX9AhosImDs5YoDGiskzHksO4I55JUZeTf1xhuWbkYB/0BheWlr4pHz5b4IjMfdCYJStccXspQ==,iv:ftRq37JciHfGll1LkgpIWftFkXshv2t1HAcCegV+//0=,tag:w8vOXTFW/n19PxikdcUMeg==,type:str] -kind: Secret -metadata: - name: garage-media-s3 - namespace: siriusdevops -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBJcllHcHErb3FvaTRpTDZ6 - WHBwT2doVXJnTm1lSmtZbSs4bkIzc3JmdUdjCnFhbUNwd2R4dk1uc0Z2ZlkyME5a - RWUySFdjTHVtQVFVblc0MkZETzBuUWMKLS0tIEp0WlYrcXYzU0pqM0xHOUF4VFc2 - T210dEtmYmU0d3Q2Z3J0ZS9ia2hQV0EKXxXxfQV9XuOCewI9DDJ7WQ7F+q3jJMOl - BITWgXv2XkFBr2UeCKoYo5AayA5XXRVS16qzySL0Bihcf5do8Y4AQQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:42Z" - mac: ENC[AES256_GCM,data:hKCawRhmKuvLNdF2sLKeE4vF7ZP5UU/w99cfmbkmUqzHea1ioRvTmqUBA5e9/CiYOHDWyTvZDLj/O1jVZBzR3EU3SxU6GK2tuqg/F0vzAzPuwJo32MhuJM+RGu6xbGq5MNjsp7yKyPr00u6krQxpkWSD1RVR7UXLX2T6wvP9HMI=,iv:GY70FcdOaOtkLRLorHqx0lZfiV4/1jpwUYhJHQgqkVk=,tag:LOj61JlJzek2XpxOrKUpEg==,type:str] - version: 3.13.3 diff --git a/apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml b/apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml deleted file mode 100644 index a50bcb3..0000000 --- a/apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - TG_CHAT: ENC[AES256_GCM,data:E5cxci96oZ0NoM2iq8FrAQ==,iv:7nox/CI/oFbOQkvagBtdBDA+3WJbxDlpUlTKtjAJva0=,tag:+kOWy2KGvulk5tySAF5/cw==,type:str] - TG_TOKEN: ENC[AES256_GCM,data:AXPJu/cwUVqNerbhcQxxQ8OUSwukqeE28t+1n5hcFOJ76xlx/U6mcZ3rZDn/Pr3UgUDiiNUC5ja63Z/XRCHwLw==,iv:2MRHNh7waV5hwzsDR7Wn4RR99NiAI6CyAqiwznkAH8o=,tag:sR0OXmISsBgzMTkw3SW78g==,type:str] -kind: Secret -metadata: - name: siriusdevops-contact - namespace: siriusdevops -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBnOEJtK3FYUFlyM0lwU3hG - c2F3TUNyS3B3UjdMMUdzQjU3UjFicUM0TGxJCmZRYjVPVEhmWFhIazNNcFBzMHVS - VWFKaXU4OEZiLzQrdlNWcWJRbld2b0kKLS0tIEVOSG9YelF6aUx1dXFXS3FXbEhU - eXNKdER5ZlVsbHJETkxEZ1JaT05PcEEKR7qlnvNhIrgF6UuQXaRhvG2+z16WRkZI - F8Pw7QXDIr1m961OTupvAvswuDB0GR146y18iZefD+v/udIam9EVeQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:16:43Z" - mac: ENC[AES256_GCM,data:nSJoyIps1Xd3aNj0DPceEWypdU+y8zh2NFOsQ5A2LAkeDFblwwG93ECvThw0JeWSHL6B3X9xIi3ZqLFy72owtcKI3idOLQ/WG3OycCJ4YZ4WnfobPDIsR2nd+x54rLL7TXOw1+lE8WCh2SEv1Ytg0lFZ/jrFUzy5e7CLHe0PZyU=,iv:CGLhOySEWCnnhoPd+oURkSBYKUF/gDcL4w5A/pw0Y4k=,tag:dCHJnIZ0PJK9OiK95kMt5A==,type:str] - version: 3.13.3 diff --git a/clusters/homek8s/apps.yaml b/clusters/homek8s/apps.yaml index f99dfb1..a060326 100644 --- a/clusters/homek8s/apps.yaml +++ b/clusters/homek8s/apps.yaml @@ -13,13 +13,6 @@ spec: name: flux-system path: ./apps/home prune: true - # Secrets in apps/base/*/secret-*.sops.yaml are age-encrypted with SOPS. - # The private key is the `flux-system/sops-age` Secret (key `age.agekey`); - # it is never in git — see docs/secrets-sops.md for the escrow locations. - decryption: - provider: sops - secretRef: - name: sops-age dependsOn: - name: infrastructure # `sirius-growth` now carries an `ObjectStore` (barmancloud.cnpg.io) whose diff --git a/clusters/homek8s/cert-manager.yaml b/clusters/homek8s/cert-manager.yaml index 8db3b3d..e32ba2a 100644 --- a/clusters/homek8s/cert-manager.yaml +++ b/clusters/homek8s/cert-manager.yaml @@ -15,11 +15,4 @@ spec: # release object, and the chart's CRDs carry `helm.sh/resource-policy: keep` # so they survive. Nothing here is a bare CRD in git, hence prune: true. prune: true - # Uniform SOPS policy for every Flux Kustomization: a tree with no encrypted - # files today is exactly where a stray secret-*.sops.yaml would otherwise be - # applied as literal ENC[...] ciphertext — silently. See docs/secrets-sops.md. - decryption: - provider: sops - secretRef: - name: sops-age wait: true diff --git a/clusters/homek8s/databases.yaml b/clusters/homek8s/databases.yaml index e73e1f5..108270d 100644 --- a/clusters/homek8s/databases.yaml +++ b/clusters/homek8s/databases.yaml @@ -18,12 +18,6 @@ spec: # reasoning as gateway-api-crds. Reverting the operator Deployment args is a # git change, not a prune. prune: false - # Uniform SOPS policy; harmless with no encrypted files in this tree, and it - # removes the "which tree am I in" trap — see docs/secrets-sops.md. - decryption: - provider: sops - secretRef: - name: sops-age # The plugin's operator<->plugin mTLS pair is issued by cert-manager # (Issuer/Certificate in the vendored plugin manifest). Applying those before # the cert-manager CRDs and webhook exist just churns; wait for it. diff --git a/clusters/homek8s/flux-system/gotk-sync.yaml b/clusters/homek8s/flux-system/gotk-sync.yaml index 52f7f48..b46b999 100644 --- a/clusters/homek8s/flux-system/gotk-sync.yaml +++ b/clusters/homek8s/flux-system/gotk-sync.yaml @@ -22,15 +22,6 @@ spec: interval: 10m0s path: ./clusters/homek8s prune: true - # Added by hand on top of the generated manifest: uniform SOPS policy for every - # Flux Kustomization (see docs/secrets-sops.md). This tree holds only Flux - # manifests today; the field means a secret-*.sops.yaml dropped here fails - # loudly instead of applying as literal ENC[...] ciphertext. `flux bootstrap` - # regenerates this file and would drop the block — `make check-sops` catches that. - decryption: - provider: sops - secretRef: - name: sops-age sourceRef: kind: GitRepository name: flux-system diff --git a/clusters/homek8s/gateway-api-crds.yaml b/clusters/homek8s/gateway-api-crds.yaml index f1dfcbd..6e55b6b 100644 --- a/clusters/homek8s/gateway-api-crds.yaml +++ b/clusters/homek8s/gateway-api-crds.yaml @@ -13,10 +13,4 @@ spec: path: ./infrastructure/networking/gateway-api # CRDs must never be pruned automatically: dropping them would delete # every Gateway/HTTPRoute object in the cluster. - prune: false - # Uniform SOPS policy; harmless with no encrypted files in this tree, and it - # removes the "which tree am I in" trap — see docs/secrets-sops.md. - decryption: - provider: sops - secretRef: - name: sops-age + prune: false \ No newline at end of file diff --git a/clusters/homek8s/infrastructure.yaml b/clusters/homek8s/infrastructure.yaml index 7cd2b2b..d01d48d 100644 --- a/clusters/homek8s/infrastructure.yaml +++ b/clusters/homek8s/infrastructure.yaml @@ -12,9 +12,3 @@ spec: name: flux-system path: ./infrastructure/home prune: true - # Uniform SOPS policy; harmless with no encrypted files in this tree, and it - # removes the "which tree am I in" trap — see docs/secrets-sops.md. - decryption: - provider: sops - secretRef: - name: sops-age diff --git a/clusters/homek8s/logging.yaml b/clusters/homek8s/logging.yaml index cf4ed16..3ba94e4 100644 --- a/clusters/homek8s/logging.yaml +++ b/clusters/homek8s/logging.yaml @@ -12,12 +12,6 @@ spec: name: flux-system path: ./infrastructure/logging prune: true - # Uniform SOPS policy; harmless with no encrypted files in this tree, and it - # removes the "which tree am I in" trap — see docs/secrets-sops.md. - decryption: - provider: sops - secretRef: - name: sops-age # Namespace + local-path PVC provisioning come from infrastructure; the # ServiceMonitor/PrometheusRule CRDs come from kube-prometheus-stack via # monitoring, so nothing here is applied before its CRDs exist. diff --git a/clusters/homek8s/monitoring.yaml b/clusters/homek8s/monitoring.yaml index ede2518..a4b2e17 100644 --- a/clusters/homek8s/monitoring.yaml +++ b/clusters/homek8s/monitoring.yaml @@ -12,11 +12,5 @@ spec: name: flux-system path: ./monitoring/controllers/home 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: - name: infrastructure diff --git a/docs/arm64-runner-dind.md b/docs/arm64-runner-dind.md index ac0dfe6..32a8b3f 100644 --- a/docs/arm64-runner-dind.md +++ b/docs/arm64-runner-dind.md @@ -16,12 +16,6 @@ finished in **27 s wall inside dind vs 28 s on the Pi's host daemon** **peak RSS was 3.10 GiB**, which is 6× the 512 Mi currently requested and the first thing that must change. See §15. - -> **Namespace note (2026-11-27, card `t_2bbe34a8`):** the three runner -> Deployments, their PVCs and the prune CronJob moved from `forgejo` to -> `ci-runners` so `forgejo` can enforce Pod Security `baseline`. Commands -> below use the new namespace; the dind design and every measurement are -> unchanged. --- ## 1. What the arm64 runners depend on today @@ -628,7 +622,7 @@ difference between the two runners). `docker:27-dind` already contains the client and the plugins: ``` -$ kubectl -n ci-runners exec deploy/forgejo-runner-amd64 -c dind -- sh -c 'command -v docker; ls /usr/local/libexec/docker/cli-plugins/' +$ kubectl -n forgejo exec deploy/forgejo-runner-amd64 -c dind -- sh -c 'command -v docker; ls /usr/local/libexec/docker/cli-plugins/' /usr/local/bin/docker docker-buildx docker-compose @@ -705,7 +699,7 @@ risk of migrating a target dir that has already caused `os error 13` corruption. Pre-flight — every one is read-only and proves the next step: -1. `kubectl -n ci-runners get deploy,pvc` and `ssh rpi docker ps` — record before. +1. `kubectl -n forgejo get deploy,pvc` and `ssh rpi docker ps` — record before. 2. Confirm `onionwire`'s in-flight work: no `running` run on the `docker` label (`action_task`), or accept that the cutover kills it (see §14). 3. Publish the Pi registry on `10.10.0.1:5000` and prove @@ -717,7 +711,7 @@ Pre-flight — every one is read-only and proves the next step: Cutover — shared runner first (it owns `docker`): -6. `kubectl -n ci-runners scale deploy/forgejo-runner-arm64 --replicas=0`, then +6. `kubectl -n forgejo scale deploy/forgejo-runner-arm64 --replicas=0`, then `ssh rpi docker ps --filter name=GITEA-ACTIONS` and `docker kill`/`rm` any job containers **still running on the host daemon** (a Deployment restart does not stop them; they keep writing to the volumes we are about to abandon). @@ -744,10 +738,10 @@ Cutover — shared runner first (it owns `docker`): landed in the Pi registry (`curl -s http://10.10.0.1:5000/v2/_catalog`) and the Garage sync succeeded. 12. Prove the existing prune discovers the new pod before trusting the night: - `kubectl -n ci-runners create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)` + `kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)` and check its `dind-daemons` container log lists both new pods (label + container-name contract, §1.6) and reports `docker system df` per daemon. -13. `df -h /` on rpi before/after, `kubectl -n ci-runners get pvc` (both Bound), +13. `df -h /` on rpi before/after, `kubectl -n forgejo get pvc` (both Bound), `kubectl get deploy -n forgejo -o wide`. ## 11. Rollback @@ -766,9 +760,9 @@ Kept in place for this purpose, and none of it is deleted by the cutover: Rollback, ~5 minutes: ``` -kubectl -n ci-runners apply -f -kubectl -n ci-runners apply -f -kubectl -n ci-runners scale deploy/forgejo-runner-arm64 --replicas=1 +kubectl -n forgejo apply -f +kubectl -n forgejo apply -f +kubectl -n forgejo scale deploy/forgejo-runner-arm64 --replicas=1 ``` (down the dind deployment first, kill any job container inside dind, then apply.) @@ -932,7 +926,7 @@ The `dind` container is named exactly `dind` (§1.6 naming contract). an in-pod daemon the socket is still `unix:///var/run/docker.sock` (in `DOCKER_HOST`, the shim, and `container.options`), so the string appears 5× per Deployment. The meaningful test is **no hostPath at all**: - `kubectl -n ci-runners get deploy -o yaml | grep -c hostPath` = 0 for both, + `kubectl -n forgejo get deploy -o yaml | grep -c hostPath` = 0 for both, and every `docker.sock` reference resolves to the `emptyDir` shared by the `dind` and `runner` containers. @@ -962,7 +956,7 @@ The `dind` container is named exactly `dind` (§1.6 naming contract). PVCs bound on rpi, static, `Retain`: ``` -$ kubectl -n ci-runners get pvc -o wide | grep dind +$ kubectl -n forgejo get pvc -o wide | grep dind forgejo-runner-arm64-dind Bound forgejo-runner-arm64-dind 200Gi RWO local-static forgejo-runner-deploy-arm64-dind Bound forgejo-runner-deploy-arm64-dind 40Gi RWO local-static $ kubectl get pv forgejo-runner-arm64-dind forgejo-runner-deploy-arm64-dind @@ -975,10 +969,10 @@ Pods on rpi, two containers each, daemon `27.5.1` (the dind image — the Pi hos daemon is `29.7.2`, so a job can never be talking to it): ``` -$ kubectl -n ci-runners get deploy -o wide +$ kubectl -n forgejo get deploy -o wide forgejo-runner-arm64 1/1 dind,runner docker:27-dind,code.forgejo.org/forgejo/runner:5.0.1 forgejo-runner-deploy-arm64 1/1 dind,runner docker:27-dind,code.forgejo.org/forgejo/runner:5.0.1 -$ kubectl -n ci-runners exec -c dind -- docker version --format 'server={{.Server.Version}}' +$ kubectl -n forgejo exec -c dind -- docker version --format 'server={{.Server.Version}}' server=27.5.1 ``` @@ -1007,8 +1001,8 @@ task 1737 in 1782 s (warm); deploy runner: task 1736 (`deploy-site.yml`) green i Nightly prune reaches both new daemons (R10 proof, forced Job): ``` -$ kubectl -n ci-runners create job --from=cronjob/forgejo-runner-prune prune-manual-1793084490 -$ kubectl -n ci-runners logs job/prune-manual-1793084490 -c dind-daemons | grep -E "daemon: dind in pod/|summary:" +$ kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-1793084490 +$ kubectl -n forgejo logs job/prune-manual-1793084490 -c dind-daemons | grep -E "daemon: dind in pod/|summary:" == daemon: dind in pod/forgejo-runner-amd64-f7bb99fb-mbv5f == daemon: dind in pod/forgejo-runner-arm64-7c84998bb8-mmwqd == daemon: dind in pod/forgejo-runner-deploy-arm64-5dcbd9f7fc-6nj2g @@ -1022,7 +1016,7 @@ $ ssh rpi 'ss -lntH "sport = :5000"' LISTEN 0 4096 10.10.0.1:5000 0.0.0.0:* LISTEN 0 4096 127.0.0.1:5000 0.0.0.0:* $ ssh rpi 'curl -m5 -o /dev/null -w "%{http_code}" http://192.168.1.125:5000/v2/' → 000 (refused) -$ kubectl -n ci-runners exec -c dind -- wget -qO- http://10.10.0.1:5000/v2/ +$ kubectl -n forgejo exec -c dind -- wget -qO- http://10.10.0.1:5000/v2/ {} # from the job daemon itself ``` @@ -1066,8 +1060,8 @@ regrown inside dind — they rebuild cold by design, §4.2). ``` # 1. stop the dind pods (a job container lives inside them, so it dies with them) -kubectl -n ci-runners scale deploy/forgejo-runner-arm64 --replicas=0 -kubectl -n ci-runners scale deploy/forgejo-runner-deploy-arm64 --replicas=0 +kubectl -n forgejo scale deploy/forgejo-runner-arm64 --replicas=0 +kubectl -n forgejo scale deploy/forgejo-runner-deploy-arm64 --replicas=0 # 2. Flux owns these files: suspend the apps Kustomization, or the next # reconcile puts the dind manifests straight back flux -n flux-system suspend kustomization apps diff --git a/docs/cluster-overview.md b/docs/cluster-overview.md index 997a191..7881d65 100644 --- a/docs/cluster-overview.md +++ b/docs/cluster-overview.md @@ -355,9 +355,9 @@ Producer: the **CNPG-I Barman Cloud plugin** (`cnpg-system/barman-cloud`, | 4 | flux-system | `notification-controller-7cd6d4994b-drh8x` | siriussec | 10.244.0.125 | Flux alerts/webhooks | internal | | 5 | flux-system | `source-controller-56549698b5-2lvmc` | siriussec | 10.244.0.44 | Flux git artifact fetcher | internal | | 6 | forgejo | `forgejo-67847d596c-jpb7x` | siriussec | 10.244.0.197 | Forgejo **16.0.5** git/CI/registry UI | **public** `forgejo.siriusdevops.com` | -| 7 | ci-runners | `forgejo-runner-amd64-…` | siriussec | 10.244.0.x | Actions runner (privileged dind sidecar), labels `docker-amd64`, `amd64` | internal | -| 8 | ci-runners | `forgejo-runner-arm64-…` | rpi | 10.244.1.x | Actions runner (privileged dind sidecar), labels `docker-arm64`, `arm64`, `docker` | internal | -| 9 | ci-runners | `forgejo-runner-deploy-arm64-…` | rpi | 10.244.1.x | Actions runner (privileged dind sidecar), label **`deploy-arm64` only** (site deploys) | internal | +| 7 | forgejo | `forgejo-runner-amd64-65fdfdf884-bb88l` | siriussec | 10.244.0.17 | Actions runner (dind sidecar), labels `docker-amd64`, `amd64` | internal | +| 8 | forgejo | `forgejo-runner-arm64-7566647d9f-7q2wk` | rpi | 10.244.1.128 | Actions runner via Pi host Docker socket, labels `docker-arm64`, `arm64`, `docker` | internal | +| 9 | forgejo | `forgejo-runner-deploy-arm64-b748d7c6f-66r5j` | rpi | 10.244.1.167 | Actions runner, label **`deploy-arm64` only** (site deploys) | internal | | 10 | forgejo | `pg-1` | siriussec | 10.244.0.159 | CNPG PostgreSQL for Forgejo (1 instance) | internal | | 11 | kube-system | `cilium-cz7w6` | siriussec | 10.10.0.2 (host-net) | Cilium agent v1.20.1 | internal | | 12 | kube-system | `cilium-dswfb` | rpi | 10.10.0.1 (host-net) | Cilium agent v1.20.1 | internal | @@ -412,9 +412,9 @@ Nothing runs on `linode` except its Cilium agent. `rpi` runs only the two runner | Deployment | Node | Docker access | `runs-on` labels | Config | |---|---|---|---|---| -| `forgejo-runner-arm64` | rpi | privileged `docker:27-dind` sidecar, PVC `forgejo-runner-arm64-dind` (200 Gi static PV) | `docker-arm64`, `arm64`, **`docker`** | CM `forgejo-runner-config` key `arm64.toml`; `capacity 1`; runner uid 1000; no host socket | +| `forgejo-runner-arm64` | rpi | Pi **host** socket `/var/run/docker.sock` + host `docker-static` binary + cli-plugins | `docker-arm64`, `arm64`, **`docker`** | CM `forgejo-runner-config` key `arm64.toml`; `capacity 1`; root + privileged; pod `supplementalGroups: [984]`; **no `docker_host`** (would duplicate the socket mount) | | `forgejo-runner-amd64` | siriussec | privileged `docker:27-dind` sidecar, PVC `forgejo-runner-amd64` (20 Gi) | `docker-amd64`, `amd64` | key `amd64.toml`; `capacity 1`; `docker_host: unix:///var/run/docker.sock` | -| `forgejo-runner-deploy-arm64` | rpi | privileged `docker:27-dind` sidecar, PVC `forgejo-runner-deploy-arm64-dind` (40 Gi static PV) | **`deploy-arm64` only** | key `deploy-arm64.toml`; `capacity 1`; `timeout 30m`; state (runner.ini) on the PVC | +| `forgejo-runner-deploy-arm64` | rpi | Pi host socket, same bind mounts | **`deploy-arm64` only** | key `deploy-arm64.toml`; `capacity 1`; `timeout 30m`; state on hostPath `/opt/siriusdevops/runner-deploy/data` | Label discipline that must not be broken: @@ -424,11 +424,11 @@ Label discipline that must not be broken: Workflow labels actually present in the local checkouts *(live grep of `.forgejo/workflows`)*: `docker` (×8) and `docker-amd64` (×3) in `onionwire`; `deploy-arm64`, `docker-amd64` in `sirius-growth`; `docker-amd64` in `siriusdevops-contact`. -### 6.5 Nightly disk reclamation (`ci-runners/forgejo-runner-prune`) +### 6.5 Nightly disk reclamation (`forgejo/forgejo-runner-prune`) `apps/base/forgejo/prune-cronjob.yaml`, `17 4 * * *` **UTC** (the repo's one CronJob timezone convention), `concurrencyPolicy: Forbid`, `startingDeadlineSeconds: 1800`, `backoffLimit: 1`, `activeDeadlineSeconds: 3600`. -**Two containers, because there are two kinds of daemon.** `host-daemon` (`docker:27-cli`) mounts the Pi's `/var/run/docker.sock`; `dind-daemons` (`alpine/k8s:1.36.4`) discovers in-cluster dind daemons — pods with label `app=forgejo-runner` **that have a container named `dind`** — and runs the same prune logic inside each over the exec API. The ServiceAccount `forgejo-prune` has only `pods get,list` and `pods/exec create` in namespace `ci-runners`. No pod names are in the manifest, so the two arm64 dind daemons from the arm64 migration are picked up the first night they exist (proved by creating an unrelated `app=forgejo-runner` dind pod: the job reported `found=2 pruned=2`). +**Two containers, because there are two kinds of daemon.** `host-daemon` (`docker:27-cli`) mounts the Pi's `/var/run/docker.sock`; `dind-daemons` (`alpine/k8s:1.36.4`) discovers in-cluster dind daemons — pods with label `app=forgejo-runner` **that have a container named `dind`** — and runs the same prune logic inside each over the exec API. The ServiceAccount `forgejo-prune` has only `pods get,list` and `pods/exec create` in namespace `forgejo`. No pod names are in the manifest, so the two arm64 dind daemons from the arm64 migration are picked up the first night they exist (proved by creating an unrelated `app=forgejo-runner` dind pod: the job reported `found=2 pruned=2`). **Retention.** Exited containers > 48 h, unused **Pi-host** images > 168 h (a week of rollback for the sites). Build cache is capped at **20 GB** on the Pi host and **4 GB** per dind daemon; above the cap the script walks `--filter until=` down from 72 h to 0 s and stops as soon as the cache is under the cap, so the newest layers survive and a cold cache is the last resort. In-cluster images are **dangling-only** pruned: an `until` filter on a *pulled* image compares the upstream build date, so it would delete `node:20-bullseye` / `rust:*-bookworm` every night and make every job cold. @@ -439,9 +439,9 @@ Workflow labels actually present in the local checkouts *(live grep of `.forgejo Force a run (safe any time; it self-skips when busy): ```bash -kubectl -n ci-runners create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s) -kubectl -n ci-runners logs job/prune-manual- -c host-daemon # Pi daemon -kubectl -n ci-runners logs job/prune-manual- -c dind-daemons # every dind daemon +kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s) +kubectl -n forgejo logs job/prune-manual- -c host-daemon # Pi daemon +kubectl -n forgejo logs job/prune-manual- -c dind-daemons # every dind daemon ``` **Two premises worth writing down, because the code depends on them** (both verified 2026-10-27): @@ -931,8 +931,8 @@ All times 2026-10-26 UTC. `kubeconfig` on the Legion admin laptop → `https://1 | 9 | `kubectl -n kube-system get ds,deploy` / image tags | cilium `v1.20.1`, envoy `v1.37.5` | | 10 | `kubectl -n kube-system exec ds/cilium -- cilium-dbg status --brief` | `OK` | | 11 | `kubectl top nodes` | `error: Metrics API not available` → no metrics-server | -| 12 | `kubectl -n ci-runners get deploy -o json` | 3 runner Deployments + nodeSelectors; pod/container securityContext as documented | -| 13 | `kubectl -n ci-runners get cm forgejo-runner-config -o jsonpath` | three TOMLs: `amd64.toml`, `arm64.toml`, `deploy-arm64.toml`, all `capacity: 1` | +| 12 | `kubectl -n forgejo get deploy -o json` | 3 runner Deployments + nodeSelectors; pod/container securityContext as documented | +| 13 | `kubectl -n forgejo get cm forgejo-runner-config -o jsonpath` | three TOMLs: `amd64.toml`, `arm64.toml`, `deploy-arm64.toml`, all `capacity: 1` | | 14 | `kubectl -n forgejo exec deploy/forgejo -- forgejo --version` | `16.0.5` | | 15 | rpi: `sudo wg show` | `wg0` 3 peers (handshakes 1 min / 48 min / 6 d); `wg-remote` 1 peer, 35 s | | 16 | rpi: `sudo wg show wg0 dump \| wc -l` | `4` | diff --git a/docs/gateway-access-logging.md b/docs/gateway-access-logging.md deleted file mode 100644 index 470f3eb..0000000 --- a/docs/gateway-access-logging.md +++ /dev/null @@ -1,140 +0,0 @@ -# Gateway access logging (cilium-envoy) - -Source of truth for the HTTP access log the Cilium Gateway class emits. Closes finding F7 of the -2026-11-27 cluster netsec audit: before this, `cilium-envoy` wrote **no request-level record**, so the -design's application-layer detection (traversal / `union select` / `%00` / `.env`/`.git` probes, -high-rate 401-403 per client, scanner user agents) had no input stream. - -## What is configured, and where it lives - -| Object | File | -|---|---| -| `CiliumGatewayClassConfig kube-system/cilium` | `infrastructure/networking/gateway/gatewayclass-config.yaml` | -| `GatewayClass cilium` (+ `spec.parametersRef`) | `infrastructure/networking/gateway/gatewayclass.yaml` | - -Cilium 1.20 reads `spec.telemetry.accessLogs` from the config referenced by -`GatewayClass.spec.parametersRef`. The cilium Helm chart creates the GatewayClass but has **no values -knob for `parametersRef`**, so the object is declared in Git with the chart's spec plus the reference; -Flux (`kustomization infrastructure`) owns both. Access logging therefore applies to **every** Gateway -on the `cilium` class: `gateway-system/public` and the internal `internal/*` Gateways. - -Cilium renders the config into each Gateway listener's HTTP connection manager as an -`envoy.access_loggers.stdout` access log (`StdoutAccessLog`), i.e. one JSON line per request on the -`cilium-envoy` container's stdout. Nothing is applied by hand; `cilium upgrade` / `helm upgrade` must -not be used. - -## Fields - -`gateway, start_time, method, path, protocol, response_code, response_flags, duration_ms, -bytes_received, bytes_sent, authority, client_ip, x_forwarded_for, peer, user_agent, cf_ray, -upstream_host` - -- `client_ip` = `CF-Connecting-IP`. Envoy is hostNetwork, so the **raw peer is cloudflared on the Pi** - (`10.10.0.1`) for public traffic and the WG client address for internal traffic — `peer` and - `x_forwarded_for` are kept so a missing/forged `CF-Connecting-IP` is visible rather than trusted. - Internal/WG requests have `client_ip: null` and a real `peer`. -- `authority` is the Host (which public hostname / which `10.10.0.2:`). -- `path` is `X-ENVOY-ORIGINAL-PATH?:PATH`, so a rewrite does not hide the requested path. - -**Not logged, by construction** (the JSON map is an allowlist, not a filter): no request/response -bodies and no header dumps, so `Authorization`, `Cookie` and `Set-Cookie` never reach disk. Envoy -application log level stays `info` — no debug/trace logging. - -## Where the lines land - -1. `/var/log/pods/kube-system_cilium-envoy-_/cilium-envoy/*.log` (kubelet container log). -2. Loki automatically: the `logging` Alloy DaemonSet tails `/var/log/pods/*/*/*.log*`, so the stream - appears as `{namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}` - with the store's 192 h retention. No extra Alloy/Loki configuration was needed. - -Only **siriussec** runs envoy (`node-role.kubernetes.io/gateway=true` is a single node), so there is -exactly one container log — the "3 nodes" framing in the finding does not apply. - -## Measured volume and retention (2026-11-27) - -Window `06:35:26Z → 06:55:04Z`, 1,178 s, live public traffic: - -| Measure | Value | -|---|---| -| access lines | 11,240 | -| bytes written | 7,205,793 | -| per line | 641 B | -| line rate | 9.54/s | -| write rate | 6.1 KB/s | -| **projected** | **528 MB/day raw (504 MiB)** | -| 5-day request average (envoy `downstream_rq_total` 2,059,146 / 417,181 s = 4.94/s) | 274 MB/day | -| lines per request (594 s sub-window: +5,534 lines vs +5,492 requests) | 1.008 | - -Composition: 93.5 % `forgejo.siriusdevops.com` (about half of those are 303 login redirects to -crawlers, because the registry/UI is login-only), 4.2 % hubble UI, 1.2 % the sites, 1.1 % bare-IP -internal ports. - -**kubelet default rotation (10 MiB x 5 per container):** 10 MiB at 6.1 KB/s = **28.6 min per file**, -so the 5-file budget (50 MiB) holds **≈2.4 h** of access log at the measured rate (≈4.6 h at the 5-day -average). Hard disk cost is capped at 50 MiB — 0.023 % of siriussec's 213.5 GiB root (99 GiB free; -`/var/log/pods` is 66 MB total today). Not minutes-long, so the default is kept: Loki is the archive. -If a longer *file* window is ever wanted, `containerLogMaxSize: 50Mi` + `containerLogMaxFiles: 5` -(250 MiB/container, ≈7 h) in `/var/lib/kubelet/config.yaml` is the change — it is node-wide and needs -a kubelet restart, and at ~35 containers that is a worst case of ~8.6 GiB of logs inside 99 GiB free. - -Loki cost: `gzip -6` of the captured window shrinks 8.1 MB → 0.64 MB (**12.6x**), so 528 MB/day raw is -≈42 MB/day stored, ≈340 MB for the full 192 h inside the 8 GiB `logging/loki-data` PVC. - -## Verify - -```bash -# config accepted and bound -kubectl -n kube-system get ciliumgatewayclassconfig cilium # ACCEPTED True -kubectl get gatewayclass cilium -o jsonpath='{.spec.parametersRef}' - -# the listener really carries the access log (host, because the container has no curl) -sudo curl -s --unix-socket /var/run/cilium/envoy/sockets/admin.sock \ - http://localhost/config_dump | grep -o 'envoy.access_loggers.stdout' | head -1 - -# drive one request through the tunnel and read the line -curl -s -o /dev/null "https://siriusdevops.com/?probe=$(date +%s)" -sudo tail -1 /var/log/pods/kube-system_cilium-envoy-*/cilium-envoy/*.log* -``` - -A request that matches a Cloudflare cache HIT never reaches the origin and therefore produces no line — -add a query string when proving logging. - -Rotation happens at 10 MiB. kubelet renames the full file to `.log.` (observed -2026-11-27T07:02:56Z: `3.log` 10,528,075 B -> `3.log.20261127-020256`, new `3.log` started, 29.3 min -after the first access line — the projection was 28.6 min) and starts a new `*.log`. The `*.log*` -glob in the commands above therefore covers rotated files too; a plain `*.log` would miss them. - -## Parse - -```bash -# one line -> flat record; client_ip is the real client for tunnelled traffic -sudo grep -h '"authority"' /var/log/pods/kube-system_cilium-envoy-*/cilium-envoy/*.log* \ - | sed 's/^.* stdout F //' \ - | jq -c 'select(.gateway=="gateway-system/public") - | {ts:.start_time, host:.authority, method, path, code:.response_code, - client:(.client_ip//.peer), ua:.user_agent, ray:.cf_ray, - flags:.response_flags, ms:(.duration_ms|tonumber)}' -``` - -Example (client redacted to /24), real line from the proof request: - -```json -{"authority":"siriusdevops.com","bytes_received":0,"bytes_sent":30179,"cf_ray":"a60f1bb759b3d96c-ATL", - "client_ip":"137.118.156.0","duration_ms":1,"gateway":"gateway-system/public","method":"GET", - "path":"/?f7probe=1795761278","peer":"10.10.0.1","protocol":"HTTP/1.1","response_code":200, - "response_flags":"-","start_time":"2026-11-27T06:34:38.642Z","upstream_host":"10.244.0.60:80", - "user_agent":"curl/8.23.0","x_forwarded_for":"137.118.156.0,10.10.0.1"} -``` - -## Operational notes - -- **The change is an xDS push, not a restart.** `cilium-envoy` was not restarted and no listener was - rebound; the pod kept its original age/restart count through the change. -- **Nothing happens if the cilium-operator's gateway controller is not running.** It is the component - that reads `parametersRef` and rewrites the Gateway listeners. On 2026-11-27 it had failed to - initialise during an apiserver restart (`Required GatewayAPI resources are not found` — transient - RBAC lookup failure at 05:24Z) and stayed wedged, so a GatewayClassConfig change applied cleanly in - Git but produced no access log until `kubectl -n kube-system rollout restart deploy/cilium-operator`. - Always confirm `kubectl -n kube-system logs deploy/cilium-operator | grep Reconciling Gateway`. -- Rollback: revert the commit (or delete the `parametersRef`); the operator drops the access log on - the next Gateway reconcile. Nothing else in the chain depends on it. diff --git a/docs/grafana-persistence.md b/docs/grafana-persistence.md index 1333cfc..02c683d 100644 --- a/docs/grafana-persistence.md +++ b/docs/grafana-persistence.md @@ -53,16 +53,6 @@ So: changing `grafana-admin` alone on a populated PVC does **nothing**. That is by design (no silent password resets on redeploy), and it is exactly why the recovery path below matters. -> **Drift breaks the sidecars, not just the login.** The pod's sidecars (`grafana-sc-dashboard`, -> `grafana-sc-datasources`) carry `REQ_USERNAME`/`REQ_PASSWORD` from `grafana-admin` and POST -> `/api/admin/provisioning/{dashboards,datasources}/reload` as their "make Grafana read what I just -> wrote" step. Once the DB password has drifted from the Secret that POST returns **401**, so a -> datasource ConfigMap is written into `/etc/grafana/provisioning/datasources` and never loaded: -> the datasource is simply absent from `/api/datasources` while the file sits in the pod. Observable -> 2026-11-27 with the Loki datasource (ConfigMap live, file in the volume, no datasource in Grafana -> for 40 minutes). The DB was then reset to the Secret's value, so the seed and the DB match again -> and the reload answers **200**. Fix drift the same way before debugging a "missing" datasource. - ## Recovery: reset a lost admin password The trap with a persistent DB is that re-applying the Secret no longer helps. diff --git a/docs/hubble-event-loss.md b/docs/hubble-event-loss.md deleted file mode 100644 index 38156a8..0000000 --- a/docs/hubble-event-loss.md +++ /dev/null @@ -1,216 +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"}`, -averaged over the 30 min before the roll (old 4095 agents) against a 34 min -uptime sample after all three agents restarted onto the new config: - -| node | before (4095) | after (16383) | delta | -|---|---|---|---| -| siriussec | 330.2 MiB | 333.8 MiB | +3.6 MiB | -| linode | 309.1 MiB | 297.1 MiB | -12.0 MiB | -| rpi | 194.5 MiB | 213.1 MiB | +18.6 MiB | - -The deltas straddle zero, i.e. the 12288 extra retained events are inside the -process's own allocation noise at this event size (they are pointers plus the -payloads that were already being allocated; the ring only delays their free). -The honest statement is: **no measurable growth; the Pi, the node with the -least headroom after linode, is +18.6 MiB.** Rejected alternative: 65535 "to be -safe" is 4x this for headroom the 24 h peak does not justify. - -### 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.** - -The counter carries two different signals and the gate must not treat them -alike: `perf_event_ring_buffer` / `observer_events_queue` are real loss on the -way in, while `hubble_ring_buffer` also counts *reads* that fall outside the -ring's retained window (the artefact above). A read is not a lost event, so the -gate value is built from the two real-loss sources only, and read churn gets its -own rate-based regression guard. - -Threshold and enforcement: - -| rule | expression | meaning | -|---|---|---| -| `hubble:lost_events_increase_30m` (recorder) | `sum by (node, source) (increase(hubble_lost_events_total{source=~"perf_event_ring_buffer\|observer_events_queue"}[30m]))` | the gate value: any non-zero **real** loss → window incomplete; `source` is kept so the alert can name it | -| `hubble:ring_buffer_read_rate_15m` (recorder) | `sum by (node) (rate(hubble_lost_events_total{source="hubble_ring_buffer"}[15m]))` | read churn on the ring, events/s | -| `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 — real loss only | -| `HubbleRingBufferReadChurn` (warning) | `hubble:ring_buffer_read_rate_15m > 0.05` for 10 m | status-call storm / ring under a minute of flows; **reads, not drops** | -| `HubbleFlowLossMaterial` (critical) | `sum by (node) (hubble:lost_events_increase_30m) / flows > 0.001` for 15 m | real 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 five 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. `hubble_ring_buffer` alone is -never grounds for `incomplete`: it is a read counter. - -### Follow-up 2026-11-27: the gate as first written paged on reads - -The first version of these rules recorded -`increase(hubble_lost_events_total{source="hubble_ring_buffer"}[30m])` and alerted -at `> 0`. That reproduced the artefact the deeper ring was meant to remove and -paged on it: measured at 18:39Z, `HubbleFlowWindowIncomplete` was firing on all -three nodes with `hubble:lost_events_increase_30m` ≈ 2.01, while -`perf_event_ring_buffer` and `observer_events_queue` were 0 everywhere and the -ring-buffer counter stepped +1 twice in an hour (18:27, 18:35 — identical -timestamps on all three nodes) with the Hubble UI open from the admin laptop. A -`for: 10m` cannot fix that: two status reads an hour keep `increase() > 0` true -for the whole hour, and the same recorder fed `HubbleFlowLossMaterial`, where a -couple of extra counts out of ~7 k flows on the quiet Pi node is 0.03 %. - -Split applied: the gate recorder now covers `perf_event_ring_buffer` + -`observer_events_queue` only, `HubbleFlowWindowIncomplete` and -`HubbleFlowLossMaterial` read that (unchanged thresholds), and -`hubble_ring_buffer` gets rate-based `HubbleRingBufferReadChurn` at **0.05 -events/s over 15 m** — ~45 reads per window, versus the F10 probe storm's -~0.2/s (12/min) and the current ~0.001/s (2 reads/hour). Both firing conditions -name the source in the summary so a read is never described as a dropped flow. -`hubble.eventBufferCapacity` was not touched and the agents were not rolled. - - -## Verification (live, 2026-11-27) - -``` -# acceptance 1: 30 min window, after the last agent restart (05:19:48Z), read 05:53Z -$ promq 'sum by (node) (rate(hubble_lost_events_total{source="hubble_ring_buffer"}[30m]))' -0 node=rpi / 0 node=linode / 0 node=siriussec -$ promq 'sum by (node) (increase(hubble_lost_events_total{source="hubble_ring_buffer"}[30m]))' -0 node=rpi / 0 node=linode / 0 node=siriussec - -# counter stops climbing — flat for 30 min, with both big rings 100 % full -$ promq 'sum by (node) (hubble_lost_events_total{source="hubble_ring_buffer"})' -31 rpi / 31 linode / 30 siriussec (05:23:47Z) -31 rpi / 31 linode / 30 siriussec (05:53:47Z) - -# ...and the depth is what holds it there, not luck: -# siriussec Current/Max Flows 16,383/16,383, linode 16,383/16,383, rpi 10,685/16,383 - -# the artefact is gone: 20 status calls + 20 s idle move nothing -siriussec before: 30 after 20 status: 30 after +20s idle: 30 - -# 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. diff --git a/docs/internal-wireguard-services.md b/docs/internal-wireguard-services.md index d73de29..46842df 100644 --- a/docs/internal-wireguard-services.md +++ b/docs/internal-wireguard-services.md @@ -52,10 +52,7 @@ only". Consequences: Public traffic has no path here: the only public ingress is the cloudflared tunnel, whose ingress list is an explicit allow-list of hostnames pointing at `http://10.10.0.2:8080` (the `public` gateway). Nothing points at 8081, and -`*.lab.internal` resolves nowhere publicly. `:8080` itself is in the -`internal_gw` WG-only set as well (since 2026-11-27): the tunnel origin reaches -it from `10.10.0.1` over the mesh, so the LAN has no plain-HTTP path to the -public hostnames. +`*.lab.internal` resolves nowhere publicly. ## 2. The pieces @@ -64,7 +61,7 @@ public hostnames. | `Gateway internal/internal` | `infrastructure/networking/internal/gateway.yaml` (Flux: `infrastructure`) | listener `http-internal`, **port 8081**, `allowedRoutes: All` so any namespace can attach. **One bare-IP service only** (Grafana) — see the merge gotcha above | | `Gateway internal/hubble-ui` | `infrastructure/networking/internal/gateway-hubble-ui.yaml` | listener `http-internal`, **port 8084**, its own RouteConfiguration, so its hostname-less route cannot merge with Grafana's | | `HTTPRoute ` | the app's own tree (e.g. `monitoring/controllers/home/httproute.yaml`, `infrastructure/networking/cilium/hubble-ui-httproute.yaml`) | `parentRefs: /internal#http-internal`, **no `hostnames`** | -| `table inet internal_gw` + `internal-gw-firewall.service` | siriussec host (`/etc/nftables.d/internal-gw.nft`) | drop `:8080` (the `public` gateway — Cloudflare tunnel origin only), `:8081`, `:8084`–`:8087` from everything but `10.10.0.0/24`, `10.244.0.0/16`, `lo`; the accept rules carry `counter`s so "traffic arrived and was allowed" is provable, not inferred from a 200. `:8080` is WG-only because the only legitimate client is `cloudflared` on rpi, which connects to `10.10.0.2:8080` over the mesh — a LAN client could otherwise spoof a `Host:` header and get Forgejo and every public site over plain HTTP, bypassing Cloudflare TLS/WAF/rate limits | +| `table inet internal_gw` + `internal-gw-firewall.service` | siriussec host (`/etc/nftables.d/internal-gw.nft`) | drop `:8081`+`:8084` from everything but `10.10.0.0/24`, `10.244.0.0/16`, `lo`; the accept rules carry `counter`s so "traffic arrived and was allowed" is provable, not inferred from a 200 | | ufw rules (inserted above the LAN catch-all) | rpi host | **inert since 2026-10-27** — left in place as a belt-and-braces guard in case the Pi is ever relabelled `gateway=true`, but nothing binds those ports on rpi any more, so they just make stale `10.10.0.1:8081` clients time out instead of being refused | | `infrastructure/networking/internal/host-firewall/` | repo | the host artifacts + install/verify instructions | diff --git a/docs/kube-apiserver-audit-logging.md b/docs/kube-apiserver-audit-logging.md deleted file mode 100644 index 04b6a5c..0000000 --- a/docs/kube-apiserver-audit-logging.md +++ /dev/null @@ -1,221 +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//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` **get, list, watch** | reads: a corpus dump (`list`) or one live credential (`get`); objectRef is the whole signal, 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` **create/update/patch/delete/deletecollection**, `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. For secrets this is the **write** path only — the body is the tampering evidence | -| 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 secret reads are Metadata and secret writes are not - -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`) was therefore the first to go Metadata. - -`get` was the second half of the same problem, and it was not a volume issue. Measured on the live log -2026-11-27: of **3,527** secret events, **1,606** were `get` and **2,574** carried `.data` in -`responseObject` — the audit log was a second plaintext copy of every secret that had been read -(`kubernetes-admin`, `kustomize-controller`, `source-controller`, `sirius-growth:portal`, …). That copy -is root-only on the control-plane node, so reading it produces **no audit event**, which inverts the -purpose of the log. A `get` is fully described by `objectRef` + `user` + `sourceIPs` + `responseStatus`. - -Secret **writes** are the opposite case and keep full `request`/`response` bodies: an attacker filling -a secret with their own SSH key or rewriting a `dockerconfigjson` is exactly the record you want, and a -write body is evidence rather than a credential that was already in the cluster. Verbs are enumerated -(`create/update/patch/delete/deletecollection`) so an unrecognised verb falls through to Metadata -instead of silently acquiring a body. - -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 still holds secret material - -Secret **reads** are Metadata since 2026-11-27, so a `get`/`list`/`watch` record carries no `data`. -Secret **writes** still do: at `RequestResponse` a `create`/`update`/`patch` record carries the object in -`requestObject` (and the server's answer in `responseObject`). `/var/log/kubernetes/audit/` therefore -stays `0700 root` with the log `0600 root`, on the control-plane node only. - -Files written **before** that date also held every secret that had been *read*; they were deleted as part -of the change rather than left to age out (see "Purge" below). Treat any log shipper that touches this -path as a **secrets pipeline**: no unauthenticated sink, no plaintext off-node copy, and its own -encryption/retention story. The Loki/Alloy stack in `infrastructure/logging/` does **not** mount this -directory today (`/var/log/pods` + `/var/log/journal` only) — keep it that way unless the pipeline has an -encryption story. - -## Purge: files written before the split (2026-11-27) - -The bodies already on disk were upstream of the policy fix, so they were cut rather than left to age -out. `truncate -s 0` is wrong here — the apiserver keeps writing at its own offset and the file stays -sparse — so the live file was **moved aside while the apiserver still held its fd** (no bytes lost), -the container was restarted so the new process created a fresh `audit.log` instead of appending, and the -superseded files were then deleted: - -``` -/var/log/kubernetes/audit before: audit-2026-11-27T05-45-22.804.log.gz 39,423,475 - audit-pre-readfix-20261127T055416Z.log 15,037,570 (the moved live file) - audit.log 7,440,332 (fresh, post-change) -after: audit.log 7,440,332 age ~1 min -``` - -Summary of what those files held, extracted before deletion (the only part worth keeping): - -``` -secret events 3,527 (get 1,606, patch 899, watch 721, update 196, delete 49, list 43, create 13) -with responseObject 2,753 | with responseObject.data 2,574 -readers: kubernetes-admin, kustomize-controller, source-controller, kube-prometheus-stack-grafana, - sirius-growth:portal, cert-manager, cnpg-manager, and per-node kubelet identities -``` - -Rotation later in the run only replaces files that were written under the split, so nothing with a read -body can reappear. The `throwaway-probe` values from the write-path proof are the only secret values in -the fresh log, and that secret no longer exists. - -## 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 — **read/write split, captured 2026-11-27T05:57Z** (policy merged as `9f07d333`, apiserver -restarted to reload it, one fresh `audit.log`): - -``` -verb level secret code body -get Metadata forgejo/forgejo-pg-app 200 none — no requestObject, no responseObject, no `data` substring -create RequestResponse audit-probe/throwaway-probe 201 requestObject.data = {key} -patch RequestResponse audit-probe/throwaway-probe 200 requestObject = {"stringData":{"added":…}} (the patch document) -update RequestResponse audit-probe/throwaway-probe 200 requestObject.data = {added, key, replaced} -delete RequestResponse audit-probe/throwaway-probe 200 DeleteOptions, no object body -get Metadata audit-probe/throwaway-probe 404 objectRef + responseStatus only (post-delete read still recorded) -``` - -Whole-file check over the first 339 secret events of the fresh log: **263 read verbs (`get`/`list`/`watch`), -all `Metadata`, 0 with `responseObject`, 0 with `data`**; 76 write verbs, all `RequestResponse` carrying -`requestObject`. A merge patch's `requestObject` is the patch document itself, which is exactly the -tampering evidence (an attacker's key appears verbatim in `stringData`). - -Earlier proof, 2026-11-27T05:18Z (pre-split policy), kept for the `pods/exec` shape: - -``` -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 — PRE-SPLIT; now Metadata with no body) -rbac write kubernetes-admin create forgejo/audit-trail-probe (dryRun=All) code 201 RequestResponse -pods/exec kubernetes-admin get forgejo//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- /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). diff --git a/docs/logging.md b/docs/logging.md index cbbb092..e28ecc7 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -186,47 +186,13 @@ the audit history was then re-ingested through the fixed pipeline. ## Querying Grafana datasource `Loki` (`uid: loki`, `infrastructure/logging/datasource.yaml`, -loaded by the kube-prometheus-stack datasource sidecar) → Explore → Loki. The -saved queries live on the **Logs** dashboard (`uid: logs`, -`monitoring/controllers/home/dashboards/logs.yaml`, generated by `build.py`): - -``` -http://10.10.0.2:8081/d/logs/ -``` +loaded by the kube-prometheus-stack datasource sidecar) → Explore → Loki. From inside the cluster: `http://loki.logging.svc.cluster.local:3100`. From the Legion over WireGuard: `kubectl -n logging port-forward svc/loki 3100:3100`. No Gateway/listener is published for this — the store is not exposed outside the mesh and has no auth layer of its own. -**A new or edited datasource ConfigMap needs a provisioning reload.** Grafana -reads `provisioning/datasources` only at startup; the sidecar writes the file but -the thing that makes Grafana read it is the sidecar's own -`POST /api/admin/provisioning/datasources/reload`, authenticated with -`monitoring/grafana-admin`. If the DB password has drifted from that Secret the -POST 401s, the file is on disk and the datasource never appears — which looks -like a broken ConfigMap. Reload by hand with the Secret's credential: - -```bash -kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80 & -curl -u "admin:$GF_ADMIN_PASSWORD" -X POST \ - http://127.0.0.1:3000/api/admin/provisioning/datasources/reload # 200 -``` - -**The audit stream's field names are not the audit event's.** Alloy re-emits each -record as a flat allowlist (`infrastructure/logging/alloy/config.alloy`), so -`objectRef.resource` arrives as the **stream label** `resource` and -`user.username` as the line field `user`: - -```logql -{job="kube/apiserver-audit", resource="secrets"} | json # who touched a Secret -``` - -`{job="kube/apiserver-audit"} | json | objectRef_resource="secrets"` returns -**zero rows** — measured 2026-11-27. `resource`/`verb` are stream labels, so put -them in the selector (Loki prunes streams before parsing); `user`, `ns`, `name`, -`code`, `sourceIP` are JSON fields and need `| json`. - Useful LogQL: ```logql @@ -234,7 +200,6 @@ Useful LogQL: {namespace="kube-system", container="cilium-agent"} |= "error" {job="systemd-journal", node="siriussec"} |= "sshd" # node-level auth activity sum by (namespace) (count_over_time({job="kube/pods"}[1h])) -sum by (user) (count_over_time({job="kube/apiserver-audit", resource="secrets"} | json [5m])) ``` Label cardinality is bounded: `namespace, pod, container, node, stream, job` diff --git a/docs/monitoring-dashboards.md b/docs/monitoring-dashboards.md index efa87d7..8d2704d 100644 --- a/docs/monitoring-dashboards.md +++ b/docs/monitoring-dashboards.md @@ -1,6 +1,6 @@ # Monitoring dashboards -Four custom Grafana dashboards, all provisioned from this repo. Nothing on these +Three custom Grafana dashboards, all provisioned from this repo. Nothing on these boards is created in the UI: the `kube-prometheus-stack` Grafana sidecar watches for ConfigMaps labelled `grafana_dashboard=1` in **every** namespace (`NAMESPACE=ALL`, `LABEL_VALUE=1`, `FOLDER=/tmp/dashboards`) and reloads them, so @@ -11,7 +11,6 @@ a UI edit is overwritten on the next sidecar poll. | Forgejo Runners | `forgejo-runners` | Are the runners alive and polling, is CI queueing, how do runs end, and how full is the disk CI fills? | | CNPG Postgres | `cnpg-postgres` | Are both Postgres clusters up, how busy, how big, how much WAL, is anything erroring? | | Home lab workloads | `home-lab-workloads` | Which namespace is burning CPU/memory, what is Pending or restarting, are the nodes healthy, do the internal services answer? | -| Logs | `logs` | Who read a Secret (apiserver audit, by user), what did a pod say before it died, what did the CI runners print? | Open them (WireGuard only, no public hostname — see `docs/internal-wireguard-services.md`): @@ -20,37 +19,28 @@ Open them (WireGuard only, no public hostname — see http://10.10.0.2:8081/d/forgejo-runners/ http://10.10.0.2:8081/d/cnpg-postgres/ http://10.10.0.2:8081/d/home-lab-workloads/ -http://10.10.0.2:8081/d/logs/ ``` -`logs` is the odd one out: its panels query the **Loki** datasource (`uid: loki`, -`infrastructure/logging/datasource.yaml`) rather than Prometheus, and its two -template variables are filled from Loki's label API. The audit field names there -are the Alloy pipeline's allowlist, not the raw audit event's — `objectRef.resource` -arrives as the stream label `resource` and `user.username` as the field `user`; -`docs/logging.md` §Querying has the detail and the zero-row proof. - They land in the default **General** folder, next to the chart's own dashboards — not in a custom folder. That is a consequence of *how* they get imported: the sidecar's API-backed import POSTs to `/api/admin/provisioning/dashboards/reload` -with `GF_SECURITY_ADMIN_USER/PASSWORD`, and that call only succeeds while the live -admin password still matches `monitoring/grafana-admin`. When the two have drifted -the POST returns **401** and Grafana's own **file** provider imports -`/tmp/dashboards` on its 10 s rescan instead — that is what actually registers -these boards — and the file provider has no per-dashboard folder option. Hence no -`grafana_folder` annotation: it would only describe a path the boards do not take. -(The drift was repaired on 2026-11-27; see `docs/grafana-persistence.md`.) +with `GF_SECURITY_ADMIN_USER/PASSWORD`, and on this Grafana that returns **401** +because the live admin password is the out-of-band one set in the UI +(`docs/grafana-persistence.md`) while `monitoring/grafana-admin` is only the +first-boot seed. Grafana's own **file** provider then imports `/tmp/dashboards` +on its 10 s rescan anyway — that is what actually registers these boards — and +the file provider has no per-dashboard folder option. Hence no `grafana_folder` +annotation: it would only describe a path the boards do not take. ## Where the files live ``` monitoring/controllers/home/dashboards/ -├── build.py # source of truth: panel definitions + PromQL/LogQL +├── build.py # source of truth: panel definitions + PromQL ├── kustomization.yaml ├── forgejo-runners.yaml # GENERATED ConfigMap (JSON inside) ├── cnpg-postgres.yaml # GENERATED -├── home-lab-workloads.yaml # GENERATED -└── logs.yaml # GENERATED (Loki panels) +└── home-lab-workloads.yaml # GENERATED ``` **Edit `build.py`, then regenerate.** The generated YAML is committed so Flux @@ -167,22 +157,17 @@ throughput panels query "how many rows stopped inside the last hour" directly ## Adding a panel 1. Edit `monitoring/controllers/home/dashboards/build.py` — `ts()` for a - timeseries, `stat()` for a single number, `note()` for markdown, `logs()` for - a Loki log panel (its target must come from `loki_target()`, and the panel - needs `ds=DS_LOKI`). + timeseries, `stat()` for a single number, `note()` for markdown. 2. Regenerate (command above). -3. **Validate the query, not just the YAML.** `validate_panels.py` (next to +3. **Validate the PromQL, not just the YAML.** `validate_panels.py` (next to `build.py`) reads the dashboard JSON *out of the provisioned ConfigMap*, - extracts every target expression, substitutes the `$namespace` / `$runner_ns` - "All" cases and queries the target's own datasource — Prometheus for - PromQL panels, Loki for panels whose datasource is `loki` (a Loki panel is a - failure unless it returns rows, not just series). Anything that returns no - data is a failed panel. It needs both port-forwards: + extracts every target expression, substitutes the `$namespace` "All" case and + queries Prometheus. Anything that returns no series is a failed panel. It + needs a Prometheus port-forward (`kubectl -n monitoring port-forward + svc/kube-prometheus-stack-prometheus 9090:9090`). ```bash - kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090 & - kubectl -n logging port-forward svc/loki 3100:3100 & python3 monitoring/controllers/home/dashboards/validate_panels.py \ - monitoring/controllers/home/dashboards http://127.0.0.1:9090 http://127.0.0.1:3100 + monitoring/controllers/home/dashboards http://127.0.0.1:9090 ``` 4. Commit + push to `master`, then force the reconcile: ```bash @@ -215,11 +200,10 @@ deploying another exporter. `forgejo-runner-prune-*` CronJob pods, which are `Completed` and therefore permanently "not Ready" — that turned a not-Ready stat from 0 into 3 until the selector was narrowed to the three Deployment pod prefixes. -- **Two namespaces on one board: runner pods live in `ci-runners`, the queue lives in the `forgejo` database.** The CI capsule moved to `ci-runners` (so `forgejo` can enforce PSA `baseline` — see `docs/pod-security.md`), so every pod/PVC/Deployment target is built from `build.py`'s single `CI_RUNNERS_NS = 'ci-runners'` constant. The `cnpg_actions_*` / `cnpg_*` targets keep `namespace="forgejo"`: that label comes from the scrape of the CNPG **database** cluster, not from the runners. Never blanket-replace the namespace in either direction — a runner-pod query against `forgejo` is silently empty, and a DB query against `ci-runners` is too. Moving the capsule again should be a one-line `CI_RUNNERS_NS` change plus a regenerate. - **CNPG custom-query metrics carry `namespace`/`pod` from the scrape, not the exporter's `cluster` label.** `cnpg_collector_*` has `cluster`; the `cnpg_actions_*` and `cnpg_pg_stat_*` families do not. Filter those by - `namespace="ci-runners"` (the `cnpg_actions_*` panels keep `namespace="forgejo"`: that label is the Postgres cluster's namespace). + `namespace="forgejo"`. ## Known unknowns (deliberate, documented on the boards themselves) diff --git a/docs/network-isolation.md b/docs/network-isolation.md deleted file mode 100644 index 1c33283..0000000 --- a/docs/network-isolation.md +++ /dev/null @@ -1,94 +0,0 @@ -# Namespace network isolation - -**State since 2026-11-27 (audit finding F3 / A5-1, card `t_fed52919`).** Before that the cluster -was one flat L2/L3 domain: a pod in any namespace could reach every other namespace's services, the -API server, the internal Gateway ports on `10.10.0.2` (`:8081` Grafana, `:8084` Hubble, -`:8085` Metabase, `:8086/:8087` customer1) and the internet. - -## What is covered - -Each app namespace carries two objects in `apps/base//networkpolicy.yaml`, -applied by the `apps` Flux Kustomization: - -| namespace | default-deny | allow policy | internet egress | Garage/S3 | CI/backup SSH | API | -|---|---|---|---|---|---|---| -| `customer1` | yes | `customer1-allow` | **no** (by design) | no | no | no | -| `osint` | yes | `osint-allow` | yes | no | no | no | -| `sirius-growth` | yes | `sirius-growth-allow` | yes | 3900 | 22 | yes | -| `piedmont` | yes | `piedmont-allow` | yes | no | no | no | -| `siriusdevops` | yes | `siriusdevops-allow` | yes | 3900 | no | no | -| `forgejo` | yes | `forgejo-allow` | yes | no | 22 | yes | - -`customer1` also carries `quota.yaml`: a `ResourceQuota` + `LimitRange` sized from the declared -1-replica shape of the parked sandbox (2 CPU / 4Gi requests, 4 CPU / 10Gi limits, 45Gi storage, -`max` 1 CPU / 2Gi per container). See the comments in that file for the arithmetic. - -`metabase`, `monitoring`, `logging`, `kube-system`, `ci-runners`, `netsec` and `secops` are **not** -isolated yet — they are the next tier (monitoring/logging legitimately reach everything). - -## How the deny is expressed - -* **Deny**: `networking.k8s.io/v1 NetworkPolicy` named `default-deny`, - `podSelector: {}`, `policyTypes: [Ingress, Egress]`, no rules. A stock NetworkPolicy is - unambiguous in Cilium's k8s-policy path, and unlike a `CiliumClusterwideNetworkPolicy` with - `endpointSelector: {}` it cannot silently select `kube-system`/CoreDNS/Flux. -* **Allow**: `CiliumNetworkPolicy` per namespace with `endpointSelector: {}`. Cilium *unions* all - policies that select an endpoint, so deny + allow = the effective policy. The Cilium CRD is needed - because the permitted sources/destinations are Cilium **entities**. - -## The five rules every namespace needs - -```yaml -ingress: - - fromEntities: [ingress, host, remote-node, health] # Gateway proxy + kubelet + cilium-health - - fromEndpoints: # INTRA-NAMESPACE, see below - - matchLabels: {io.kubernetes.pod.namespace: } -egress: - - toEndpoints: kube-dns :53 (UDP+TCP) - - toEndpoints: own namespace - - toEntities: [world] # internet + LAN + VPN peers, NOT pods/nodes -``` - -Entities that matter here: - -| entity | what it is | why it appears | -|---|---|---| -| `ingress` | Cilium Gateway/listener proxy | **measured**: `hubble observe --to-namespace forgejo --to-port 3000` shows the source identity as `reserved:ingress` (identity 8), not `host`. Traffic arrives via cloudflared → hostNetwork Envoy → pod. | -| `host` | the local node IP | kubelet probes and host-network datapath | -| `remote-node` | other nodes' IPs | cross-node gateway ingress; Garage (`10.10.0.1`, `10.10.0.5`) and the Linode SSH target live here, **not** in `world` | -| `kube-apiserver` | the apiserver identity | attached to the **whole node IP** `10.10.0.2` because apiserver is host-networked — always port-scope it (see below) | -| `health` | cilium-health | inter-node health probes | - -## Gotchas that cost time (all measured 2026-11-27) - -1. **Cilium enforces at both ends.** An egress rule alone does not let a pod reach its own - Service: the destination pod's ingress policy must allow it too. Symptom: a probe pod in the - namespace gets `TimeoutError` on `own-service..svc:5432` while the public route works fine - (that one enters as `ingress`). Add the same-namespace `fromEndpoints` ingress rule as well. - Confirmed by re-running the probe after adding it: `OPEN`. -2. **`toEntities: [kube-apiserver]` without `toPorts` opens the whole gateway node.** The apiserver - is host-networked on `10.10.0.2`, and Cilium attaches the `kube-apiserver` identity to that IP, - so an unscoped rule also allowed `:8085`, `:8081`, `:9100`, `:10250`. Measured, then fixed with - `toPorts: [6443, 443]` (443 = the service port the CNPG instance manager / `kubectl` dial; - 6443 = the backend port). Re-probe: `apiserver OPEN`, `:8085/:8081/:9100/:10250 CLOSED`. -3. **`ipBlock`/`toCIDR` is inert for node IPs.** `10.10.0.1` (Garage on the Pi) resolves to - `reserved:remote-node`, and CIDR rules are only evaluated for `reserved:world`. Use - `toEntities: [remote-node]` + `toPorts`. -4. **`world` is not "the internet".** It is everything outside the cluster: public IPs **and** the - LAN (`192.168.1.0/24`) and VPN peers. Cluster pods and node IPs are *not* in `world`, which is - what makes `toEntities: [world]` a safe "internet only" rule. -5. **A deny shows up as `TimeoutError`, an empty Service as `ConnectionRefusedError`.** Useful when - reading probes: `pg.customer1.svc:5432` refusing proves the policy *permits* the path and the - namespace is simply parked at 0 replicas. - -## Adding a dependency - -1. Add the rule to that namespace's allow policy — DNS, same-namespace and the entity list are - already there; most additions are one `toEntities`/`toPorts` block. -2. Prove it both ways: the new path must go `OPEN`, and `forgejo:3000`, `metabase:3000`, - `grafana:80`, `kubernetes.default:443` (where not needed) and `10.10.0.2:8085` must stay - `CLOSED` from that namespace. -3. Watch the deny side while you test: `hubble observe --verdict DROPPED -o compact` on the - namespace you changed (`policy-verdict:...DENIED` lines name the exact port). -4. Push through a PR; Flux owns the objects. A `kubectl apply` is only for testing and will be - adopted by the next reconcile. diff --git a/docs/pod-security.md b/docs/pod-security.md deleted file mode 100644 index 75c8561..0000000 --- a/docs/pod-security.md +++ /dev/null @@ -1,262 +0,0 @@ -# Pod Security posture (2026-11-27) - -Status of Pod Security Admission (PSA) labels per namespace, why one workload -still needs `privileged`, and what is enforced where. Two namespaces now -*enforce*, not just warn: `forgejo` at `baseline` and the CI capsule -`ci-runners` at `privileged`. - -## Levels in use - -| level | namespaces | -|---|---| -| `enforce: baseline` + `warn`/`audit: restricted` | `cert-manager`, `customer1`, `forgejo`, `metabase`, `osint`, `piedmont`, `secops`, `sirius-growth`, `siriusdevops` | -| `enforce: privileged` + `warn`/`audit: privileged` | `ci-runners` (the Actions CI capsule) | -| `enforce: privileged` + `warn`/`audit: restricted` | `logging` | -| `warn`/`audit: restricted` only | `netsec`, `monitoring`, `node-io`, `internal`, `gateway-system`, `local-path-storage`, plus cluster-owned `kube-system`, `kube-public`, `kube-node-lease`, `default`, `cnpg-system`, `cilium-secrets`, `flux-system` | - -The enforced set was picked by reading the live workload templates first: every -namespace in it had zero baseline violations (no `privileged`, no -`hostNetwork`/`hostPID`/`hostIPC`, no `hostPath`, no `hostPort`, no capability -additions, no `seccompProfile: Unconfined`) on 2026-11-27. Enforcement is per -*pod creation*, so a namespace that later needs one of those shapes has to be -moved to warn/audit deliberately, with a comment in Git, instead of being -allowed by accident. - -The warn/audit-only set is the opposite list — each one hosts a workload that -baseline forbids today: - -| namespace | blocker | -|---|---| -| `kube-system` | Cilium agent/envoy (hostNetwork, hostPath, privileged init, hostPorts), static control-plane pods | -| `monitoring` | node-exporter (hostNetwork + hostPID + hostPath `/proc`,`/sys`,`/`) | -| `logging` | Alloy DaemonSet (hostPath `/var/log`, journal, machine-id) — enforced at `privileged` because the shape is expected | -| `netsec` | hubble-flow-collector (hostPath socket + log dir) | -| `node-io` | etcd-io-guard (privileged, hostPID, hostPath) | -| `local-path-storage` | provisioner helper pods are privileged (created on every PVC) | -| `internal`, `gateway-system` | reserved for hostNetwork Cilium Gateway listeners | - -`kube-system`, `kube-public`, `kube-node-lease`, `default`, `cnpg-system`, -`cilium-secrets`, `logging` and `flux-system` are not declared in this repo -(created by kubeadm/Helm/Flux), so their warn/audit labels are applied -out-of-band; re-apply them after a control-plane rebuild: - -```sh -for ns in kube-system kube-public kube-node-lease default cnpg-system cilium-secrets logging flux-system; do - kubectl label ns "$ns" --overwrite \ - pod-security.kubernetes.io/warn=restricted \ - pod-security.kubernetes.io/warn-version=latest \ - pod-security.kubernetes.io/audit=restricted \ - pod-security.kubernetes.io/audit-version=latest -done -``` - -## The Forgejo CI capsule (`ci-runners`) - -The three Actions runners (`forgejo-runner-amd64`, `forgejo-runner-arm64`, -`forgejo-runner-deploy-arm64`) each carry a docker-in-docker sidecar with -`privileged: true`, and the nightly prune CronJob mounts the Pi's host -`/var/run/docker.sock`. PSA has no per-workload exception, and baseline rejects -both shapes (`privileged`, `hostPath`) at admission. While those pods lived in -`forgejo`, that namespace could only ever be warn/audit — which is why -originally *nothing* in the cluster enforced. - -The fix is the first option that was open: the **CI capsule moved to its own -namespace**, `apps/base/forgejo/runner-namespace.yaml`, which enforces PSA at -`privileged` *on purpose*, and `forgejo` now enforces `baseline`. This is -containment, not a new grant: the dind sidecar was already privileged. What the -split buys: - -* `forgejo` (Forgejo itself, the CNPG Postgres cluster, the nightly - cluster-backup CronJob) is now protected by admission — a future privileged, - hostPath or hostNetwork pod added there is rejected instead of silently - accepted; -* the only namespace allowed to run a privileged pod is the one whose name says - so, labelled as such in Git, and it holds nothing but the CI capsule; -* the capsule's `warn`/`audit` are `privileged` as well (the operator's decision): - they emit nothing because everything there is allowed by design, and the - namespace is reviewed in Git rather than at admission. - -What is inside `ci-runners`: the three runner Deployments, their PVCs -(`forgejo-runner-amd64` on siriussec's local-path, `forgejo-runner-arm64-dind` -200 Gi and `forgejo-runner-deploy-arm64-dind` 40 Gi as static Retain PVs on -rpi), the `forgejo-runner-config` ConfigMap, the two registration-token -Secrets, and the prune ServiceAccount/Role/RoleBinding/ConfigMap/CronJob. The -capsule's Deployments use the namespace's `default` ServiceAccount, which has -**no** RBAC; only the prune Job can `get/list` pods and `create pods/exec`, and -only in this namespace. - -What was already removed from the runner shape (same change, card -`t_2bbe34a8`): - -* the runner container no longer runs as uid 0 — it uses the image's uid 1000, - and the dind socket is created `0660 root:1000` via `dockerd --group 1000` - (which also removes the old one-shot `chmod 666` race that forced root); -* CI **job** containers are no longer privileged (`container.privileged: false` - in the runner ConfigMap) — previously every job container was privileged - inside a privileged dind; -* the runners have no `hostPath`, no `hostNetwork` and no host docker socket; - the only hostPath left in the capsule is the prune Job's Pi socket. - -Residual risk, stated plainly: a privileged dind container is node root on the -node it runs on, and a CI job can reach that daemon socket by design. The -capsule therefore means "trusted CI code" rather than isolation. The one -hardening path that changes what `privileged: true` *means* is a virtualised -runtime behind a `RuntimeClass`; it was evaluated and staged on one runner — -see below. - -## `enforce: baseline` on `ci-runners` is unreachable by any runtime (measured) - -All three candidate runtimes were installed on **both** arches and exercised -against the live cluster on 2026-11-27 (v1.36.4, containerd 2.3.4/2.3.5, Cilium -native routing). Architecture was never the blocker: sysbox-ce 0.7.2 ships an -arm64 `.deb`, gVisor publishes `gvisor-aarch64`, Kata publishes -`kata-static-4.4.0-arm64`, and `/dev/kvm` exists on siriussec **and** rpi. - -The blocker is a contradiction, not a bug: - -> PSA `baseline` forbids adding any capability outside `AUDIT_WRITE, CHOWN, -> DAC_OVERRIDE, FOWNER, FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, -> SETPCAP, SETUID, SYS_CHROOT` — and every nested dockerd needs `SYS_ADMIN` -> (overlay, mounts) + `NET_ADMIN` (docker0, iptables) **in the pod spec**. - -Measured verdicts, each on a live cluster: - -| runtime | verdict | -|---|---| -| sysbox-ce 0.7.2 | The only one **admitted** at `enforce: baseline` with a clean spec (id-mapped userns, `uid_map 0 427680 65536`), but its inner dockerd cannot use the CNI-owned pod netns: `Failed to create bridge docker0 via netlink: operation not permitted`, `iptables ... Could not fetch rule set generation id: Permission denied`, and with `--bridge=none` every `docker run` dies on `failed to set into network namespace ... operation not permitted`. sysbox also bans inner `--net=host`, so there is no egress fallback. Also needs `enable_unprivileged_ports=false` + `enable_unprivileged_icmp=false` under containerd 2.x. | -| gVisor | Full CI shape works (nested run, pull, build, overlay2) **only** with `capabilities.add: ["ALL"]`; with a baseline-clean spec dockerd never starts (`failed to mount overlay: operation not permitted`). | -| Kata 4.4.0 | `privileged: false` hits the same caps wall *inside the guest*. With `privileged: true` the whole CI shape works on amd64 **and** arm64 (nested run, bridge+NAT egress, `docker build`) — but `/var/lib/docker` is virtiofs, overlayfs refuses it, and Docker falls back to `vfs`. | - -So the letter of the original audit finding (drop `privileged`, enforce -`baseline`) cannot be met by swapping a runtime; only reworking CI off -docker-in-docker could, and that rewrites every workflow. The operator's -decision (card `t_8aa4af50`) was to take the one option that changes the -*consequence* of the flag, staged to a single runner. - -## Kata microVM on the deploy runner (`forgejo-runner-deploy-arm64`, staged) - -`forgejo-runner-deploy-arm64` (rpi) now runs with -`runtimeClassName: kata-qemu`. **Read this precisely:** - -* the pod **still declares `privileged: true`** and `ci-runners` **still - enforces `privileged`**. Nothing about this namespace's PSA level changed; a - privileged pod in `forgejo` is still rejected; -* what changed is the blast radius: the dind sidecar and the job containers - live in a QEMU/KVM microVM with no host namespaces, no host kernel and only - the volumes the pod mounts. An escape from CI has to beat KVM, not just the - container runtime. On a runc runner the same flag is direct root on rpi; -* `forgejo-runner-amd64` and `forgejo-runner-arm64` are untouched (still - privileged dind under runc), so `docker-amd64` and `runs-on: docker` are - unchanged. Converting them is a separate decision, taken on the measured cost - of this one. - -How it is wired (all in `apps/base/forgejo/`): - -* `kata-runtimeclass.yaml` — `RuntimeClass` `kata-qemu`, handler `kata-qemu`; -* rpi's containerd has the handler via the drop-in - `/etc/containerd/conf.d/50-kata.toml` (`io.containerd.kata.v2`, - `privileged_without_host_devices = true` — a privileged container otherwise - receives all 218 of the node's `/dev` nodes, which is meaningless inside a VM - and makes runtime-rs fail the create with `get host path failed`), with - kata-static 4.4.0 under `/opt/kata` and - `/etc/kata-containers/configuration.toml` symlinked to the runtime-rs QEMU - config; -* the dind sidecar builds its own ext4 data-root: a 16 GiB image file at - `/data-docker/kata-ext4.img` on the existing claim, attached with - `losetup /dev/loop0` (the guest has to `mknod` the node — only - `/dev/loop-control` exists) and mounted at `/var/lib/docker`. This is what - restores `overlay2`; without it Docker silently uses `vfs`; -* the guest kernel has **no** binfmt registrations (the host's are not visible - from inside the VM), so every start mounts `binfmt_misc` and runs - `tonistiigi/binfmt --install amd64`. Without that, `deploy-site.yml`'s - `docker buildx build --platform linux/amd64` dies with `exec format error` / - `buildkit-qemu-x86_64: executable file not found`; -* the runner container waits for `/var/run/dind-ready`, which the dind sidecar - touches **after** the data-root and binfmt are set up, so a job can never - start against a half-initialised daemon. - -Rollback is one field: drop `runtimeClassName: kata-qemu` from that Deployment -(Flux) — the pod returns to runc/privileged dind on the same claim, and the -`kata-ext4.img` is an unused file until then (it is a cache; deleting it is -safe). The containerd drop-in on rpi is inert once no pod asks for the handler. - -### Measured cost of the microVM (warm cache, same content) - -| workflow | runner / runtime | run | wall clock | -|---|---|---|---| -| `deploy-site` (sirius-growth) | `deploy-arm64`, runc | 130 | 22 s | -| `deploy-site` (sirius-growth) | `deploy-arm64`, runc | 129 | 31 s | -| `deploy-site` (sirius-growth) | `deploy-arm64`, **Kata** | 133 | **48 s** | -| `deploy` (siriusdevops) | `docker-amd64`, runc (untouched) | 67 | 49 s (66: 49 s) | - -So the VM costs roughly **+25 s per deploy** on a warm image cache (boot + guest -plumbing), and pushes the amd64 site image with its own digest -(`sirius-growth-site:7e1dd4cc…`, manifest `sha256:7b2987b4…`). The untouched -amd64 runner is unchanged to the second, and `runs-on: docker` was not touched. - -Three things had to be fixed before the first real job would run — all measured, -all in the manifests now: - -1. **The dind socket must not live on virtiofs.** A disk-backed `emptyDir` is a - virtiofs share; a unix socket created there is *visible* but unconnectable - from the other containers (`runner: cannot ping the docker daemon …` while - `dind: docker version` on the same path succeeds). The socket directory is - `medium: Memory` (tmpfs in the guest) instead. -2. **No per-job `--memory` inside the VM.** The guest cgroup root is - `domain threaded` with only `cpuset cpu pids` delegated, so dockerd cannot - apply a memory limit and every job dies at `docker run` with - `cannot enter cgroupv2 "/sys/fs/cgroup/docker" with domain controllers`. - The 2Gi dind limit sizes the VM, so that is the bound now. -3. **binfmt is per-VM.** The host's qemu handlers are not visible inside the - guest, so `--platform linux/amd64` needs `tonistiigi/binfmt --install amd64` - on every pod start (the image itself is cached in the ext4 data-root). - -Operational note: the Deployment is `strategy: Recreate`, so a rollout during a -run kills the job *and* leaves the Forgejo run `running` forever (reproduced, -run 132 — there is no cancel endpoint). Land template changes while the runner -is idle. - -## Why the dind sidecar keeps `privileged` (measured, do not re-derive) - -Three independent attempts to drop the flag were measured live on 2026-11-27 -(siriussec, kernel 6.18.50-lts; rpi reproduced the procfs failure): - -1. **Explicit capability set** (`privileged: false`, - `capabilities.add: [SYS_ADMIN, NET_ADMIN]`): dockerd starts and pulls - images, but no container starts — - `runc create failed: ... mkdir /sys/fs/cgroup/docker: read-only file system`. - kubelet mounts `/sys/fs/cgroup` read-only for non-privileged pods. PSA - baseline also forbids adding `SYS_ADMIN`/`NET_ADMIN`, so this shape cannot - live in an enforced namespace at all. -2. **Rootless dind** (`docker:27-dind-rootless`, uid 1000, vpnkit network): - the daemon initialises and pulls images, but every container fails with - `error mounting "proc" to rootfs at "/proc": operation not permitted`. A - nested user namespace may only mount a fresh procfs if a fully visible - procfs already exists in the namespace (kernel `mount_too_revealing`), and - kubelet masks a number of `/proc` paths in every pod. -3. **`procMount: Unmasked`** fixes (2), but the API only accepts it with - `hostUsers: false`. In a user-namespace pod `newuidmap` cannot write a - subuid map (it is not setuid-root inside that namespace) and `mknod - /dev/net/tun` is refused, so rootless dind has neither a uid map nor the - tun device it needs for networking. - -## Verification - -```sh -# no privileged container left in the Forgejo namespace (empty output = pass) -kubectl -n forgejo get pods -o jsonpath='{..securityContext.privileged}' - -# forgejo enforces baseline; the capsule is explicitly privileged + audited -kubectl get ns forgejo ci-runners -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.metadata.labels}{"\n"}{end}' - -# admission really rejects the shape in forgejo (expect Forbidden) -kubectl -n forgejo run probe-bad --image=busybox --restart=Never \ - --overrides='{"spec":{"containers":[{"name":"p","image":"busybox","securityContext":{"privileged":true}}]}}' - -# the prune CronJob (and its RBAC) now live in the capsule -kubectl -n ci-runners get cronjob,role,rolebinding,sa -l app=forgejo-runner - -# only the deploy runner is a microVM; the other two are runc/privileged dind -kubectl -n ci-runners get pods -l app=forgejo-runner \ - -o custom-columns=NAME:.metadata.name,RUNTIME:.spec.runtimeClassName,NODE:.spec.nodeName -``` diff --git a/docs/registry-pull-auth.md b/docs/registry-pull-auth.md deleted file mode 100644 index fd04cee..0000000 --- a/docs/registry-pull-auth.md +++ /dev/null @@ -1,156 +0,0 @@ -# Registry pull authentication (Forgejo container registry) - -Status: **enforced** since 2026-11-27 (audit finding F11), re-implemented at the edge on -2026-12-02 so public repos can be browsed anonymously again. Every workload that pulls -`forgejo.siriusdevops.com/sirius/*` carries `imagePullSecrets: [forgejo-pull]`, and the -registry refuses to mint tokens for anonymous clients — now via a Cloudflare WAF rule rather -than `REQUIRE_SIGNIN_VIEW`. - -## What was wrong - -Forgejo 16 (Gitea 1.22 lineage) grants anonymous callers the **ghost user** and then treats -that ghost as `perm.AccessModeRead` on *every* package — including packages of **private** -repos. Source: `services/context/package.go::determineAccessMode` (case 3: owner visibility -`public` → `Read` for `doer == nil`), reached from -`routers/api/packages/container/*::Authenticate`, which mints a ghost token *unless* -`setting.Service.RequireSignInView` is set. - -Measured before the fix (2026-11-27T05:11Z): an unauthenticated `/v2/token` returned a JWT -with `{"UserID": -1, "Scope": ""}` and that token returned `200` for -`/v2/sirius/osint-dashboard/manifests/…`. `sirius/siriusdevops`, `sirius/websites` and -`sirius/sirius-growth` are **private** repos and their images (`siriusdevops-site`, `phs-site`, -`sirius-growth-*`, `sgs-leadgen`) were publicly pullable too — so "make the repo private" is -*not* a mitigation on this version. - -## The switch - -`apps/base/forgejo/deployment.yaml` now runs with public browsing **on**: - -```yaml -- name: FORGEJO__service__REQUIRE_SIGNIN_VIEW - value: "false" -``` - -and the registry guard moved to the edge — Cloudflare zone `siriusdevops.com`, phase -`http_request_firewall_custom`, rule **"Block anonymous Forgejo registry tokens"**: - -``` -(http.host eq "forgejo.siriusdevops.com") and (starts_with(http.request.uri.path, "/v2/token")) -and (not any(http.request.headers["authorization"][*] contains "Basic")) -``` - -Effects: - -* Anonymous `/v2/token` → `403` from Cloudflare (never reaches Forgejo, so no ghost token is - minted). `/v2/` still answers the normal `401` challenge, so registry clients keep their - auth flow. -* Authenticated callers (basic auth: username + access token) still get the two-stage flow: - `/v2/token` (returns a scoped JWT) → `Bearer ` on `/v2/...`. Verified 2026-12-02 with - the `registry-reader` credential: token minted, `manifests/` → `200`. -* Public repos (`homek8s`, `onionwire`, `osint-dashboard`, `gcloud-lab`, `netsec-agent`, …) are - browsable and clonable anonymously again; private repos still 404 for anonymous visitors. -* Package **metadata** (`/api/v1/packages/...` listing, tags) is still readable anonymously — - only token minting is blocked, so blobs stay protected. -* CI pushes are unaffected — workflows authenticate with `REGISTRY_TOKEN` (`write:package`). - -**Order matters when changing this:** the WAF rule must be live *before* (or at the same time -as) setting `REQUIRE_SIGNIN_VIEW=false`. Flipping the env var alone re-opens anonymous pulls of -every image, including those of private repos. - -## The credential - -A dedicated non-admin user, `registry-reader` (visibility `limited`, `read:package` scope). -Its token lives in the Kubernetes Secrets, and since `docs/secrets-sops.md` also as SOPS -ciphertext in git (`apps/base//secret-forgejo-pull.sops.yaml`). - -Secret `forgejo-pull` (`kubernetes.io/dockerconfigjson`) must exist in every namespace whose -pods pull from the registry. Currently: `osint`, `piedmont`, `sirius-growth`, `siriusdevops`. - -These Secrets **are** reconciled by Flux from the SOPS files above (this supersedes the earlier -"out of band" wording): a namespace recreated by a Flux prune gets its copy back on the same -reconcile, instead of losing it before the pods reschedule. The manual recipe below is now only -for **rotating** the token. - -### 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 -# 1. token (mint a fresh one; never echo it) -kubectl -n forgejo exec deploy/forgejo -- su-exec git forgejo admin user generate-access-token \ - --username registry-reader --raw --scopes read:package --token-name pull-k8s-$(date +%Y%m%d) -# (if the user itself is gone: POST /api/v1/admin/users with visibility "limited", -# then the command above; the password is only needed for interactive login and is -# never used by containerd.) - -# 2. rewrite the encrypted value in every namespace's file (no plaintext ever hits disk) -umask 077 -read -r -s -p 'token: ' RT; echo -python3 - "$RT" > /tmp/dc.json <<'PY' -import base64, json, sys -t = sys.argv[1].strip() -print(json.dumps({"auths": {"forgejo.siriusdevops.com": { - "username": "registry-reader", "password": t, - "auth": base64.b64encode(f"registry-reader:{t}".encode()).decode()}}})) -PY -for ns in osint piedmont sirius-growth siriusdevops; do - f=apps/base/$ns/secret-forgejo-pull.sops.yaml - sops decrypt --output-type json "$f" \ - | jq --rawfile dc /tmp/dc.json '.data[".dockerconfigjson"] = ($dc | rtrimstr("\n") | @base64)' \ - | sops encrypt --filename-override "$f" --input-type json --output-type yaml /dev/stdin > /tmp/new.yaml \ - && mv /tmp/new.yaml "$f" -done -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 - -Three edits, all in git: - -1. copy an existing `secret-forgejo-pull.sops.yaml` into `apps/base//` and point it at the - namespace (`sops` re-encrypts on save; `metadata.namespace` is not encrypted); -2. list it plus `secret-.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 - -Containerd is deliberately left with no registry credential -(`config_path = ""` in `/etc/containerd/config.toml`, no `/etc/containerd/certs.d/*/hosts.toml` -on any node). A node-level token would be one credential shared by every workload on every -node; `imagePullSecrets` scopes the read grant to the namespace that needs it and keeps the -audit trail per-pod. - -## Verification - -```bash -# anonymous must be refused -curl -s -o /dev/null -w '%{http_code}\n' \ - 'https://forgejo.siriusdevops.com/v2/token?service=container_registry&scope=repository:sirius/osint-dashboard:pull' # 401 -curl -s -o /dev/null -w '%{http_code}\n' \ - https://forgejo.siriusdevops.com/v2/sirius/osint-dashboard/manifests/amd64-54897b49bc57 # 401 - -# authenticated two-stage flow must work -T=$(curl -s -u "registry-reader:$RT" \ - 'https://forgejo.siriusdevops.com/v2/token?service=container_registry&scope=repository:sirius/osint-dashboard:pull' \ - | python3 -c 'import json,sys;print(json.load(sys.stdin)["token"])') -curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $T" \ - -H 'Accept: application/vnd.oci.image.index.v1+json' \ - https://forgejo.siriusdevops.com/v2/sirius/osint-dashboard/manifests/amd64-54897b49bc57 # 200 - -# no global credential on the nodes -for h in siriussec rpi; do ssh "$h" 'grep -E "^\s*config_path" /etc/containerd/config.toml; find /etc/containerd -name hosts.toml'; done -``` - -A pod that pulls without the secret now fails with -`failed to authorize: ... 401 Unauthorized` → `ErrImagePull`, which is the intended negative -control. diff --git a/docs/secrets-sops.md b/docs/secrets-sops.md deleted file mode 100644 index f20af1a..0000000 --- a/docs/secrets-sops.md +++ /dev/null @@ -1,217 +0,0 @@ -# Cluster Secrets in Git (SOPS + age) - -**Decision (2026-11-27):** every hand-made Secret consumed by a workload in this repo is -committed as a **SOPS/age-encrypted plain `Secret` manifest** — not a SealedSecret, not -`secretGenerator` from a plaintext file. One mechanism, no mixing. - -Rationale: Flux already ships the `sops` decryptor (`kustomize-controller`), so there is no -extra controller, CRD or admission webhook to run; the age private key never leaves the two -places listed below. SealedSecrets would need a controller in the cluster *and* a sealing key -escrowed somewhere anyway — the same single point of failure with more moving parts. - -## Where the key lives (this is the whole disaster-recovery story) - -| # | Location | Notes | -|---|----------|-------| -| 1 | Secret `flux-system/sops-age`, key `age.agekey` | What Flux reads at reconcile time. Created out of band (`kubectl create secret generic`), never in git. | -| 2 | `/root/sops/homek8s-age.key` on the Linode VPS (0600, root) | **Off-workstation escrow.** Reachable only over the mesh: `laptop → rpi → ssh root@10.20.0.1`. sha256 `2d1b9d82e07ea126…` (full hash in the 2026-11-27 card/handoff). | -| 3 | `~/.config/sops/age/keys.txt` on the admin workstation (0600) | Convenience only; sops' default lookup path. Losing this is survivable, losing #1 and #2 is not. | - -The key is **not** in the Obsidian vault (that tree is pushed nightly to Forgejo — a key there -would publish itself) and not on any cluster node's disk other than as the Secret above. - -Restore after losing both: nothing on the cluster can be decrypted and every encrypted file -must be re-encrypted to a new recipient. That means re-entering the values from the upstream -providers (Telegram bot tokens, Forgejo tokens, S3 keys, DB passwords). Treat #2 as the -authoritative copy and copy it into a password manager as a third location. - -Reading the key from escrow, if the workstation copy is gone: - -```bash -ssh -i ~/.ssh/lancelot_priv sirius@192.168.1.125 \ - 'ssh -i ~/.ssh/linode_admin root@10.20.0.1 cat /root/sops/homek8s-age.key' \ - > ~/.config/sops/age/keys.txt && chmod 600 ~/.config/sops/age/keys.txt -``` - -## Working with the encrypted files - -`encrypted_regex: ^(data|stringData)$` — only the values are encrypted; `metadata.name`, -`namespace` and `type` stay readable so `git grep` and code review still work. - -```bash -# edit one (opens $EDITOR, re-encrypts on save) -sops apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml - -# read key NAMES without decrypting values -sops decrypt --output-type json apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml \ - | jq -r '.data | keys[]' - -# add a new secret: capture the live object, strip server metadata, encrypt through a pipe -kubectl -n get secret -o json \ - | jq -S '{apiVersion:"v1",kind:"Secret", - metadata:{name:.metadata.name,namespace:.metadata.namespace}, - type:.type,data:.data}' \ - | sops encrypt --filename-override secret-.sops.yaml \ - --input-type yaml --output-type yaml /dev/stdin > apps/base//secret-.sops.yaml -``` - -Then list the file in that app's `kustomization.yaml` (they all end with a "Secrets, -SOPS/age-encrypted in git" block). - -**Never** commit a plaintext Secret, and never "encrypt it in a follow-up commit" — the -plaintext commit is recoverable from the object database forever, even if force-pushed. - -`sops` and `age` are packaged (`pacman -S sops age`); the recipient lives in `.sops.yaml` -at the repo root, so `sops` picks it up with no flags as long as the filename matches -`secret-*.sops.yaml`. - -## How Flux applies them - -**`decryption` is opt-in per Flux Kustomization, and the failure mode is silent.** A -`secret-*.sops.yaml` under a tree whose Kustomization lacks the block is still valid YAML: -kustomize-controller applies the Secret with the literal strings `ENC[AES256_GCM,data:…]` as its -values. The Secret exists, `kubectl get secret` is green, and the first symptom is an application -failing to authenticate — possibly days later, on a pod restart, looking nothing like a git -problem. (Same class as the registry-secret trap in `docs/registry-pull-auth.md`.) - -So **every** Flux Kustomization in `clusters/homek8s/` carries the block, not just the two that -need it today — harmless where a tree has no encrypted files, and it removes the "which tree am -I in" question entirely: - -```yaml - decryption: - provider: sops - secretRef: - name: sops-age -``` - -The eight: `apps`, `monitoring`, `infrastructure`, `logging`, `databases`, `cert-manager`, -`gateway-api-crds` and `flux-system`. Today only `apps` (`apps/base/*/`) and `monitoring` -(`monitoring/controllers/home/`) actually contain encrypted files. - -`clusters/homek8s/flux-system/gotk-sync.yaml` is generated by `flux bootstrap` and says -"DO NOT EDIT"; the `decryption` block there was added by hand and a future bootstrap would drop -it. The guard below catches that. - -Flux decrypts server-side *before* kustomize builds, so what lands in the cluster is an -ordinary Secret. `prune: true`, so deleting the file deletes the Secret — that is the -intended lifecycle. - -### Guard — `make check-sops` - -`scripts/check-sops-decryption.py` (static: no cluster, no age key, no network) reads the live -sync path out of `clusters/*/flux-system/gotk-sync.yaml`, walks each Kustomization's kustomize -resource graph, and fails when: - -1. any Flux Kustomization lacks `decryption.provider: sops` (or its `secretRef.name`); -2. a `*.sops.yaml` / `*.sops.yml` file sits under no reconciled tree, or under a tree whose - owner cannot decrypt; -3. a `*.sops.yaml` file contains no `sops:` block / `ENC[AES256_GCM…` — i.e. plaintext wearing - an encrypted file's name. - -```bash -make check-sops # exit 0 = clean, 1 = violations, 2 = could not run (never a pass) -./scripts/check-sops-decryption.py -v # same, plus each Kustomization and file→owner mapping -``` - -Run it before pushing a change that adds or moves a Secret. A violation is a config error, not a -warning: in the un-guarded case Flux applies ciphertext and reports success. - -### Reading a diff - -`.gitattributes` marks `*.sops.yaml` with `diff=sopsdiffer`. To make `git diff` show decrypted -values instead of ciphertext, enable the driver once per workstation (it needs the age key): - -```bash -git config --global diff.sopsdiffer.textconv 'sops decrypt --output-type yaml' -``` - -Ordering note: a Secret must exist before its consumer starts (CNPG `bootstrap.initdb.secret`, -`imagePullSecrets`, env refs). Kustomize sorts `Secret` before `Deployment`/`Cluster`, and all -of these live in the same app directory, so one reconcile creates both. - -## Inventory — in git (35 Secrets, 8 namespaces) - -| Namespace | Secrets | -|-----------|---------| -| `forgejo` | `forgejo-pg-app`, `forgejo-runner-amd64-token`, `forgejo-runner-deploy-arm64-token`, `cluster-backup-ssh` | -| `siriusdevops` | `siriusdevops-contact`, `garage-media-s3`, `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` | -| `osint` | `osint-admin`, `osint-db`, `forgejo-pull` | -| `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` | -| `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 -are **ours** — each Cluster's `bootstrap.initdb.secret.name` points at one of them, so CNPG reads -the password from the Secret we create rather than minting it. Without them in git a rebuild's -`initdb` has no application password and the Cluster never bootstraps. They are static (no -password-rotation policy is configured), so re-applying the same bytes is a no-op. - -`forgejo-pull` is committed even though `docs/registry-pull-auth.md` (F11) describes it as -"out of band (never in git)". That wording predates this card: once every Deployment carries -`imagePullSecrets: [forgejo-pull]`, that Secret is *the* thing whose absence stops the cluster -from starting, which is exactly what this card exists to prevent. It is a Forgejo -`read:package` token — ciphertext in git is the correct home for it. - -## Excluded on purpose (not in git, by design) - -| Secret(s) | Namespace | Why | -|-----------|-----------|-----| -| `pg-server`, `pg-replication`, `pg-ca` | `forgejo`, `metabase` | Issued and rotated by the CNPG instance manager (ownerRef `Cluster/pg`). Committing them pins stale certs the operator immediately overwrites → permanent drift. | -| `portal-server`, `portal-replication`, `portal-ca` | `sirius-growth` | Same, ownerRef `Cluster/portal`. | -| `cnpg-ca-secret`, `cnpg-webhook-cert` | `cnpg-system` | Operator's own CA + webhook serving cert, ownerRef `Deployment/cnpg-controller-manager`; regenerated on install. | -| `barman-cloud-server-tls`, `barman-cloud-client-tls`, `plugin-barman-cloud-` | `cnpg-system` | Generated by the vendored `plugin-barman-cloud` manifest (the `` is a content checksum in the object name). | -| `cert-manager-webhook-ca` | `cert-manager` | Helm-generated webhook CA. | -| `cilium-ca`, `hubble-server-certs`, `hubble-relay-client-certs` | `kube-system` | Cilium Helm chart mints these (`lookup`-reused); a stale copy wedges an upgrade — the documented failure is `HelmRelease` stalled on a cert that does not match the current `cluster.name`. | -| `sh.helm.release.v1.*` | `kube-system`, `cert-manager`, `monitoring` | Helm release records (release state, not configuration). | -| `kube-prometheus-stack-admission` | `monitoring` | Helm-generated webhook cert. | -| `prometheus-kube-prometheus-stack-prometheus`, `alertmanager-kube-prometheus-stack-alertmanager`, `*-generated`, `*-tls-assets-*`, `*-web-config`, `*-cluster-tls-config` | `monitoring` | Rendered by the prometheus-operator from the CRs on every reconcile — writing them into git creates a second, losing writer. Their *inputs* (`alertmanager-telegram`, `grafana-admin`, `grafana-secret-key`) are ours and are committed separately. | -| `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. | -| `sops-age` | `flux-system` | **The age private key.** It cannot encrypt itself and must exist before any file here can be decrypted — it is the one Secret that is by definition out of git. See "Where the key lives" above for the two escrow copies. | - -Every other live Secret is either in git as ciphertext or in the table above. Re-prove that with a -clean checkout of `master` (needs the age key in `~/.config/sops/age/keys.txt`): - -```bash -kubectl get secret -A -o json \ - | jq -r '.items[] | "\(.metadata.namespace)/\(.metadata.name)"' | sort > /tmp/live.txt -for f in apps/base/*/secret-*.sops.yaml monitoring/controllers/home/secret-*.sops.yaml; do - sops decrypt --output-type json "$f" | jq -r '"\(.metadata.namespace)/\(.metadata.name)"' -done | sort > /tmp/git.txt -comm -23 /tmp/live.txt /tmp/git.txt # live but not restorable from git: must be the table above -comm -13 /tmp/live.txt /tmp/git.txt # in git but absent live: must be empty -``` - -At the 2026-11-27 audit that printed 77 live = 35 in git + 42 excluded, all 42 accounted for above, -and nothing in git that was missing from the cluster. - -Now covered (added after the drill in the section below proved the recovery path): -`cluster-backup-ssh` (3 namespaces), `grafana-admin`, `grafana-secret-key`, `alertmanager-telegram`. - -## Delete-and-reconcile drill (2026-11-27T05:29Z) - -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. - diff --git a/images/backup/Dockerfile b/images/backup/Dockerfile deleted file mode 100644 index 66b6bd6..0000000 --- a/images/backup/Dockerfile +++ /dev/null @@ -1,49 +0,0 @@ -# Backup tooling image for the three nightly state-backup CronJobs -# (monitoring/grafana-backup, forgejo/cluster-backup, sirius-growth/leadgen-backup). -# -# Why this exists (card t_9d0428d8): every one of those jobs used to run -# `apk add --no-cache rsync openssh-client` at container start, which dialled -# dl-cdn.alpinelinux.org (Fastly anycast 151.101.x.132:443) on every run. That -# made the nightly backup depend on the public internet, tripped the -# `egress-new-dst` flow alert whenever Fastly rotated an address, and put a -# package install on the one pod that carries the Grafana PVC and an SSH key. -# The toolchain is baked in at build time instead, and the pods get an egress -# NetworkPolicy that admits DNS + the backup host only. -# -# Base image is pinned by digest (multi-arch index digest; this build is -# linux/amd64 because all three jobs are nodeSelector'd to siriussec). -FROM python:3.12-alpine@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89 - -# kubectl is needed by forgejo/cluster-backup only (CNPG `get cluster` + -# `exec` pg_dump); the cluster runs v1.36.4, so the client is pinned to the -# same minor and its release checksum is verified at build time. -ARG KUBECTL_VERSION=v1.36.4 -ARG KUBECTL_SHA256=8b8f088da2dab964f853b38464033b1be15ede2839eca751482357c45abdd05a - -LABEL org.opencontainers.image.title="backup-tools" \ - org.opencontainers.image.description="python3.12-alpine + rsync + openssh-client + bash + kubectl for the nightly state backups" \ - org.opencontainers.image.source="https://forgejo.siriusdevops.com/sirius/homek8s" - -RUN set -eux; \ - # bash: cluster-backup and leadgen-backup use arrays, `set -o pipefail` - # and `tee >(...)` process substitution, so /bin/sh (busybox ash) is not - # enough -- the CronJob entrypoints stay /bin/bash, unchanged. - apk add --no-cache rsync openssh-client bash; \ - test "${TARGETARCH:-amd64}" = "amd64" || { echo "kubectl pin is amd64-only; the backup jobs run on siriussec" >&2; exit 1; }; \ - apk add --no-cache --virtual .fetch curl ca-certificates; \ - curl -fsSL -o /usr/local/bin/kubectl \ - "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl"; \ - echo "${KUBECTL_SHA256} /usr/local/bin/kubectl" | sha256sum -c -; \ - chmod 0755 /usr/local/bin/kubectl; \ - apk del .fetch; \ - rm -rf /var/cache/apk/* - -# Build-time proof that nothing has to be installed at run time. -RUN set -eux; \ - rsync --version | head -1; \ - ssh -V; \ - bash --version | head -1; \ - python3 --version; \ - kubectl version --client - -CMD ["/bin/sh"] diff --git a/infrastructure/controllers/cert-manager/namespace.yaml b/infrastructure/controllers/cert-manager/namespace.yaml index 44cd351..c90416f 100644 --- a/infrastructure/controllers/cert-manager/namespace.yaml +++ b/infrastructure/controllers/cert-manager/namespace.yaml @@ -2,10 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: cert-manager - labels: - pod-security.kubernetes.io/enforce: baseline - pod-security.kubernetes.io/enforce-version: latest - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/infrastructure/controlplane/audit/audit-policy.yaml b/infrastructure/controlplane/audit/audit-policy.yaml deleted file mode 100644 index 945006b..0000000 --- a/infrastructure/controlplane/audit/audit-policy.yaml +++ /dev/null @@ -1,138 +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. -# -# Read/write split: secret READS (get/list/watch) are Metadata - the body is a -# credential and objectRef already answers who/which/from where. Secret WRITES -# (create/update/patch/delete) keep full request/response - the body there is the -# evidence (an attacker planting their own key), not a credential to protect. -# Measured before the split: 2,574 of 3,527 secret events carried `.data` in -# responseObject, i.e. the log was a second copy of every secret that had been read. -# Everything else - pods/exec, tokenreviews, RBAC writes, proxies - is unchanged. -# 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"] - - # ---------------------- 4a. secrets: READS (corpus + single object) = Metadata - # `list` returns EVERY secret in the namespace (measured 1.9 MiB per event, dozens - # per flux reconcile storm); `get` returns one object whose responseObject.data is - # the live credential. Neither body is evidence: objectRef + user + sourceIPs + - # responseStatus fully answers "who read which secret, when, and did it succeed". - # Keeping the body writes a second plaintext copy of every secret into a root-only - # file that no audit event covers (root can read the log without touching the API). - - level: Metadata - verbs: ["get", "list", "watch"] - resources: - - group: "" - resources: ["secrets"] - - # -------------------- 4b. secrets: WRITES = full request/response bodies - # The tampering verbs. Here the body IS the evidence: who planted which key, who - # rewrote the forgejo-pull dockerconfigjson, who deleted the SOPS age key secret. - # Verbs are enumerated so an unknown future verb falls through to Metadata (rule 6) - # rather than silently acquiring a body. - - level: RequestResponse - verbs: ["create", "update", "patch", "delete", "deletecollection"] - 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: ["*"] - - # -------------------------------- 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 diff --git a/infrastructure/controlplane/audit/install-audit.sh b/infrastructure/controlplane/audit/install-audit.sh deleted file mode 100755 index 1f9926d..0000000 --- a/infrastructure/controlplane/audit/install-audit.sh +++ /dev/null @@ -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 diff --git a/infrastructure/databases/base/upstream/cnpg-1.30.0.yaml b/infrastructure/databases/base/upstream/cnpg-1.30.0.yaml index 5d2dce0..4f7364a 100644 --- a/infrastructure/databases/base/upstream/cnpg-1.30.0.yaml +++ b/infrastructure/databases/base/upstream/cnpg-1.30.0.yaml @@ -3,14 +3,6 @@ kind: Namespace metadata: labels: app.kubernetes.io/name: cloudnative-pg - # Pod Security: warn/audit only. The operator pods are baseline-clean today, - # but this namespace is upstream-managed and we do not want a future - # operator version to be rejected on a cluster upgrade without warning; - # warn/audit makes any such pod visible first. - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest name: cnpg-system --- apiVersion: apiextensions.k8s.io/v1 diff --git a/infrastructure/garage/host/garage-firewall.nft b/infrastructure/garage/host/garage-firewall.nft index 3459135..4f8cc61 100644 --- a/infrastructure/garage/host/garage-firewall.nft +++ b/infrastructure/garage/host/garage-firewall.nft @@ -34,15 +34,6 @@ table inet garage_guard { # WireGuard only: the mesh hub link and loopback. iifname { "lo", "wg0", "wg-remote" } tcp dport { 3900, 3901, 3902, 3903 } counter accept - # Cluster pods scheduled on this node. Traffic from a local pod - # reaches 10.10.0.1 over its Cilium veth, not wg0, so the rule above - # dropped it: the Forgejo deploy runner (a pod on rpi) timed out on - # `s3 cp ... http://10.10.0.1:3900` while the same call from a pod on - # another node worked (that path arrives via wg0). The cluster is the - # documented consumer of this endpoint, so accept its pod CIDR only — - # LAN, tailscale and public sources still fall through to the drop. - ip saddr 10.244.0.0/16 tcp dport { 3900, 3901, 3902, 3903 } counter accept - # Anything else — LAN, tailscale, public, or a future interface that # nobody remembered to add above. tcp dport { 3900, 3901, 3902, 3903 } counter drop diff --git a/infrastructure/logging/namespace.yaml b/infrastructure/logging/namespace.yaml index 03b83a0..5610945 100644 --- a/infrastructure/logging/namespace.yaml +++ b/infrastructure/logging/namespace.yaml @@ -11,9 +11,3 @@ metadata: # run with a read-only root filesystem; the only real privilege is the root # UID needed to read journal files (0640 root:systemd-journal). pod-security.kubernetes.io/enforce: privileged - # enforce=privileged silences PSA entirely; warn/audit at restricted keeps - # the violations visible on every pod creation (and in the audit log). - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/infrastructure/networking/cilium/values.yaml b/infrastructure/networking/cilium/values.yaml index 19d4e16..5005c97 100644 --- a/infrastructure/networking/cilium/values.yaml +++ b/infrastructure/networking/cilium/values.yaml @@ -59,21 +59,6 @@ prometheus: trustCRDsExist: true hubble: - # Ring depth, in flows. The chart default (4095) is only ~51 s of history on - # siriussec at its ~80 flows/s, and `getFlowRate()` — called by every - # `hubble status`, by the agent's own 5 s hubble health probe and by the UI — - # walks the ring backwards over a full minute. When the ring is shorter than - # that walk it reaches the read boundary, `Ring.read()` synthesises a - # HUBBLE_RING_BUFFER lost event and bumps `hubble_lost_events_total` - # (cilium#46584, fixed upstream only on forward reads). Result: a constant - # 12 increments/min on siriussec with nothing actually dropped. - # 16383 keeps >= 60 s at the 24 h peak on every node (linode 196 flows/s -> - # 83 s, siriussec 101 flows/s -> 161 s, rpi 38 flows/s -> 431 s), so the walk - # stops on the timestamp check before it can touch the boundary. Must be - # 2^n-1 (Cilium's ring only accepts 4095/8191/16383/32767/65535). - # Cost: see docs/hubble-event-loss.md — the ring retains *Event pointers, so - # the delta is bounded and measured, not assumed. - eventBufferCapacity: "16383" # Flow/Forensics UI is reachable over WireGuard only, by bare IP on the # dedicated `internal/hubble-ui` gateway: http://10.10.0.2:8084/ (port 8084, # its own Gateway because Cilium merges hostname-less routes that share one). diff --git a/infrastructure/networking/gateway/gatewayclass-config.yaml b/infrastructure/networking/gateway/gatewayclass-config.yaml deleted file mode 100644 index 58f7230..0000000 --- a/infrastructure/networking/gateway/gatewayclass-config.yaml +++ /dev/null @@ -1,52 +0,0 @@ -# Envoy access logging for every Gateway served by the Cilium GatewayClass. -# -# Finding F7 (2026-11-27 netsec audit): cilium-envoy emitted no request-level -# record at all, so the design's HTTP attack-shape rules (§4d: traversal, -# `union select`, `%00`, .env/.git probes, high-rate 401/403 per client, -# scanner user-agents) had no input stream. -# -# Cilium 1.20 renders this into the Gateway listeners' HTTP connection manager -# and writes one JSON line per request to the cilium-envoy container's stdout, -# i.e. /var/log/pods/kube-system_cilium-envoy-*/cilium-envoy/*.log, which the -# node log store (Alloy -> Loki) already tails. -# -# Deliberately NOT logged: -# * no debug/trace Envoy application logging (disk is the constraint here); -# * no request/response headers wholesale and no bodies -- Authorization, -# Cookie and Set-Cookie therefore never reach disk. Only the named fields -# below are emitted, each an explicit command operator. -# -# `client_ip` is the real client identity: Envoy is hostNetwork, so the raw -# peer is cloudflared on the Pi (10.10.0.1). Cloudflare sets CF-Connecting-IP -# and cloudflared forwards it; `peer` and `x_forwarded_for` are kept so a -# missing/forged CF-Connecting-IP is visible rather than silently trusted. -apiVersion: cilium.io/v2alpha1 -kind: CiliumGatewayClassConfig -metadata: - name: cilium - namespace: kube-system -spec: - description: Cilium GatewayClass with HTTP access logging (netsec F7) - telemetry: - accessLogs: - - format: JSON - targets: - - HTTP - json: - gateway: "%CILIUM_GATEWAY_NAMESPACE%/%CILIUM_GATEWAY_NAME%" - start_time: "%START_TIME%" - method: "%REQUEST_HEADER(:METHOD)%" - path: "%REQUEST_HEADER(X-ENVOY-ORIGINAL-PATH?:PATH)%" - protocol: "%PROTOCOL%" - response_code: "%RESPONSE_CODE%" - response_flags: "%RESPONSE_FLAGS%" - duration_ms: "%DURATION%" - bytes_received: "%BYTES_RECEIVED%" - bytes_sent: "%BYTES_SENT%" - authority: "%REQUEST_HEADER(:AUTHORITY)%" - client_ip: "%REQUEST_HEADER(CF-CONNECTING-IP)%" - x_forwarded_for: "%REQUEST_HEADER(X-FORWARDED-FOR)%" - peer: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%" - user_agent: "%REQUEST_HEADER(USER-AGENT)%" - cf_ray: "%REQUEST_HEADER(CF-RAY)%" - upstream_host: "%UPSTREAM_HOST%" diff --git a/infrastructure/networking/gateway/gatewayclass.yaml b/infrastructure/networking/gateway/gatewayclass.yaml deleted file mode 100644 index db01b84..0000000 --- a/infrastructure/networking/gateway/gatewayclass.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# The Cilium GatewayClass, declared here so the access-log configuration is -# bound by GitOps rather than a hand patch. -# -# Why this file exists at all: the cilium Helm chart creates the GatewayClass -# (controllerName io.cilium/gateway-controller) but has no values knob for -# `spec.parametersRef`, and Cilium only reads `spec.telemetry.accessLogs` from -# the CiliumGatewayClassConfig referenced there. Owning the object here keeps -# the binding in sirius/homek8s and applied by Flux. -# -# The rendered spec is byte-for-byte the chart's GatewayClass plus parametersRef, -# so a Helm upgrade and this manifest agree on every other field. -apiVersion: gateway.networking.k8s.io/v1 -kind: GatewayClass -metadata: - name: cilium -spec: - controllerName: io.cilium/gateway-controller - description: The default Cilium GatewayClass - parametersRef: - group: cilium.io - kind: CiliumGatewayClassConfig - name: cilium - namespace: kube-system diff --git a/infrastructure/networking/gateway/kustomization.yaml b/infrastructure/networking/gateway/kustomization.yaml index ba8b4b8..a64a0c8 100644 --- a/infrastructure/networking/gateway/kustomization.yaml +++ b/infrastructure/networking/gateway/kustomization.yaml @@ -3,5 +3,3 @@ kind: Kustomization resources: - namespace.yaml - gateway.yaml - - gatewayclass.yaml - - gatewayclass-config.yaml diff --git a/infrastructure/networking/gateway/namespace.yaml b/infrastructure/networking/gateway/namespace.yaml index c9c5f66..3dbea03 100644 --- a/infrastructure/networking/gateway/namespace.yaml +++ b/infrastructure/networking/gateway/namespace.yaml @@ -2,8 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: gateway-system - labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/infrastructure/networking/internal/host-firewall/README.md b/infrastructure/networking/internal/host-firewall/README.md index fe9a001..e03fd2e 100644 --- a/infrastructure/networking/internal/host-firewall/README.md +++ b/infrastructure/networking/internal/host-firewall/README.md @@ -21,26 +21,12 @@ exactly one node. | siriussec (10.10.0.2) — **load bearing** | nftables table `inet internal_gw`, loaded by a oneshot unit (same pattern as `k8s-api-firewall.service`) | `siriussec-internal-gw.nft`, `internal-gw-firewall.service` | | rpi (10.10.0.1) — **inert guard** | ufw rules inserted above the `allow from 192.168.1.0/24` catch-all | `rpi-ufw-internal-gw.sh` | -Effective policy for `:8080` (the `public` gateway — Cloudflare tunnel origin), -`:8081` (Grafana), `:8084` (Hubble UI), `:8085` (Metabase) and `:8086`/`:8087` -(Customer 1 lab replica): +Effective policy for `:8081` (Grafana), `:8084` (Hubble UI) and `:8085` +(Metabase): **accept from 10.10.0.0/24 and 10.244.0.0/16, accept on lo, drop everything else** (LAN, tailscale, public). Envoy binds every listener on `0.0.0.0`, so a -new listener port is a LAN exposure until it is added here. - -**`:8080` is in the WG-only set too, and that is deliberate** (2026-11-27, -audit finding F2). `gateway-system/public` has no hostname restriction -(`allowedRoutes.namespaces.from: All`), so before this the LAN could -`curl -H 'Host: forgejo.siriusdevops.com' http://192.168.1.179:8080/` and get -Forgejo over plain HTTP — no Cloudflare TLS, WAF, rate limits or bot -protection, and credentials on the wire inside 192.168.1.0/24. The only -legitimate client is `cloudflared` on rpi, which connects **over the mesh** -(`ss` on siriussec shows `10.10.0.1:* -> 10.10.0.2:8080 ESTABLISHED`), so the -`10.10.0.0/24` accept covers production. Do not treat the public gateway as -LAN-reachable just because it is "public": it is public *through Cloudflare*, -and the tunnel origin is on the overlay. - -The accept rules carry `counter`s: `nft list table inet internal_gw` shows packets +new internal listener port is a LAN exposure until it is added here. The +accept rules carry `counter`s: `nft list table inet internal_gw` shows packets that reached the host and were allowed, which is the only way to tell "the firewall accepted it and Envoy answered" from "the client never got there" — rpi's ufw accept rules read 0 packets while requests to `10.10.0.1:8081` were @@ -77,17 +63,10 @@ ufw status | grep -E '8081|8084|8085' Negative test from the LAN must be a timeout (DROP), never 200: ```bash -curl -m 3 -sS -o /dev/null -w '%{http_code}\n' http://192.168.1.179:8080/ # empty/000 curl -m 3 -sS -o /dev/null -w '%{http_code}\n' http://192.168.1.179:8081/ # empty/000 curl -m 3 -sS -o /dev/null -w '%{http_code}\n' http://192.168.1.125:8081/ # empty/000 ``` -Positive test from the mesh must still be 200 (this is what cloudflared does): - -```bash -curl -m 5 -sS -o /dev/null -w '%{http_code}\n' -H 'Host: siriusdevops.com' http://10.10.0.2:8080/ -``` - When a new internal listener port is added, add it to the `tcp dport { … }` set in `siriussec-internal-gw.nft` and to `PORTS` in `rpi-ufw-internal-gw.sh` (which inserts one deny for the port plus mesh and pod-CIDR allows above the LAN diff --git a/infrastructure/networking/internal/host-firewall/internal-gw-firewall.service b/infrastructure/networking/internal/host-firewall/internal-gw-firewall.service index 9489acc..c46890b 100644 --- a/infrastructure/networking/internal/host-firewall/internal-gw-firewall.service +++ b/infrastructure/networking/internal/host-firewall/internal-gw-firewall.service @@ -4,7 +4,7 @@ # Flux-managed); the file lives in git at # infrastructure/networking/internal/host-firewall/. [Unit] -Description=Restrict the Gateway listeners (8080 public origin, 8081/8084-8087 internal) to WireGuard + pods +Description=Restrict the internal Gateway listeners (8081, 8084, 8085) to WireGuard After=network-online.target Wants=network-online.target diff --git a/infrastructure/networking/internal/host-firewall/rpi-ufw-internal-gw.sh b/infrastructure/networking/internal/host-firewall/rpi-ufw-internal-gw.sh index 186621c..f20e0f8 100644 --- a/infrastructure/networking/internal/host-firewall/rpi-ufw-internal-gw.sh +++ b/infrastructure/networking/internal/host-firewall/rpi-ufw-internal-gw.sh @@ -5,21 +5,18 @@ # to sit ABOVE it — hence `ufw insert`, not `ufw allow/deny` (which appends). # Final order per port: allow 10.10.0.0/24, allow 10.244.0.0/16, deny the rest. # -# Ports: 8080 = the `public` Gateway listener (the Cloudflare tunnel origin) — -# the tunnel's only legitimate client is cloudflared on this Pi -# reaching 10.10.0.2:8080 over the mesh, never the Pi's LAN IP, -# 8081 = Grafana (`internal` Gateway listener http-internal), +# Ports: 8081 = Grafana (`internal` Gateway listener http-internal), # 8084 = Hubble UI (`internal` Gateway listener hubble-ui), # 8085 = Metabase (`metabase` Gateway listener http-internal), # 8086 = Customer 1 lab Odoo (`customer1-odoo` Gateway), # 8087 = Customer 1 lab Metabase (`customer1-metabase` Gateway). -# Add a new listener port to PORTS; the loop is idempotent, so +# Add a new internal listener port to PORTS; the loop is idempotent, so # re-running after a port is already firewalled only adds what is missing. # # Run as root on rpi (192.168.1.125). set -euo pipefail -PORTS="${PORTS:-8080 8081 8084 8085 8086 8087}" +PORTS="${PORTS:-8081 8084 8085 8086 8087}" for port in $PORTS; do if ufw status | grep -q "${port}/tcp"; then diff --git a/infrastructure/networking/internal/host-firewall/siriussec-internal-gw.nft b/infrastructure/networking/internal/host-firewall/siriussec-internal-gw.nft index 863a9fc..6f07915 100644 --- a/infrastructure/networking/internal/host-firewall/siriussec-internal-gw.nft +++ b/infrastructure/networking/internal/host-firewall/siriussec-internal-gw.nft @@ -1,32 +1,16 @@ #!/usr/sbin/nft -f -# Gateway listener host firewall on siriussec: the listeners that must answer -# the WireGuard mesh and the pod network only, never the LAN. +# Internal (WireGuard-only) gateway listeners: TCP 8081 (Grafana), 8084 +# (Hubble UI), 8085 (Metabase) and 8086/8087 (Customer 1 lab replica: Odoo, +# Metabase). # -# Ports and who they serve: -# 8080 public — Cloudflare tunnel origin (cloudflared runs on rpi) -# 8081 internal — Grafana -# 8084 internal — Hubble UI -# 8085 internal — Metabase -# 8086 internal — Customer 1 lab Odoo -# 8087 internal — Customer 1 lab Metabase +# Cilium's hostNetwork Envoy binds every Gateway listener on 0.0.0.0, so the +# internal listeners are open on the LAN interface the moment the Gateway is +# programmed. This table makes them answer only from the WireGuard mesh and the +# pod network. DROP (not reject) so a LAN scan sees a timeout, not a port that +# tells you something is listening. # -# Cilium's hostNetwork Envoy binds every Gateway listener on 0.0.0.0, so every -# listener is open on the LAN interface the moment the Gateway is programmed. -# This table makes them answer only from the WireGuard mesh and the pod network. -# DROP (not reject) so a LAN scan sees a timeout, not a port that tells you -# something is listening. -# -# 8080 is in this set on purpose. `gateway-system/public` serves the public -# hostnames and used to answer 192.168.1.0/24 over plain HTTP; a spoofed -# `Host:` header then served Forgejo and every public site without Cloudflare's -# TLS, WAF, rate limits or bot protection, and put credentials on the wire -# inside the LAN. The only legitimate client of :8080 is the tunnel origin — -# cloudflared on rpi (10.10.0.1), which connects to 10.10.0.2:8080 over the -# WireGuard mesh — so the saddr rule below covers it. Nothing may reach :8080 -# from the LAN. -# -# Adding a listener: add its port to the set in all three rules below, -# reinstall this file, then +# Adding an internal service: add its listener port to the set in all three +# rules below, reinstall this file, then # `systemctl reload-or-restart internal-gw-firewall.service`. The same list # must also be added to the rpi ufw rules (rpi-ufw-internal-gw.sh). # @@ -39,14 +23,13 @@ table inet internal_gw { type filter hook input priority filter; policy accept; # local process / kubelet probes - tcp dport { 8080, 8081, 8084, 8085, 8086, 8087 } iifname "lo" counter accept + tcp dport { 8081, 8084, 8085, 8086, 8087 } iifname "lo" counter accept - # WireGuard mesh (Legion = 10.10.0.3, nodes, remote hub spokes; - # 10.10.0.1 = the cloudflared tunnel origin) and the pod network - # (in-cluster probes, gateway to service traffic) - tcp dport { 8080, 8081, 8084, 8085, 8086, 8087 } ip saddr { 10.10.0.0/24, 10.244.0.0/16 } counter accept + # WireGuard mesh (Legion = 10.10.0.3, nodes, remote hub spokes) + # and the pod network (in-cluster scrapers, probes) + tcp dport { 8081, 8084, 8085, 8086, 8087 } ip saddr { 10.10.0.0/24, 10.244.0.0/16 } counter accept # everything else: LAN, tailscale, public - tcp dport { 8080, 8081, 8084, 8085, 8086, 8087 } counter drop + tcp dport { 8081, 8084, 8085, 8086, 8087 } counter drop } -} +} \ No newline at end of file diff --git a/infrastructure/networking/internal/namespace.yaml b/infrastructure/networking/internal/namespace.yaml index a665930..ad62a56 100644 --- a/infrastructure/networking/internal/namespace.yaml +++ b/infrastructure/networking/internal/namespace.yaml @@ -3,8 +3,4 @@ kind: Namespace metadata: name: internal labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest istio-injection: disabled diff --git a/infrastructure/networking/rosenpass/README.md b/infrastructure/networking/rosenpass/README.md deleted file mode 100644 index 6ccc5f0..0000000 --- a/infrastructure/networking/rosenpass/README.md +++ /dev/null @@ -1,183 +0,0 @@ -# Rosenpass monitoring (host exporters for Link A and Link B) - -Rosenpass rotates the WireGuard preshared key on **Link A** (`rpi` wg0 -`10.10.0.1` ↔ `siriussec` wg0 `10.10.0.2`) and on **Link B** (`rpi` wg-remote -`10.20.0.2` ↔ `linode` wg0 `10.20.0.1`) about every two minutes. WireGuard -keeps using the last PSK it was given, so if the exchange dies the tunnel stays -**up** and silently stops being post-quantum. These files make that state -visible in Prometheus. - -They are host configuration, not cluster manifests — nothing here is reconciled -by Flux. The cluster side is `monitoring/controllers/home/rosenpass.yaml` -(PrometheusRule) plus the `prometheus-node-exporter` block in -`monitoring/controllers/home/values.yaml`, which enables the textfile -collector. - -## Why a host script instead of a collector - -`kube-prometheus-stack-prometheus-node-exporter` is distroless and ships -without `--collector.textfile.directory`; `--collector.systemd` would need dbus -plumbing the DaemonSet does not have. So one POSIX `sh` script writes a -textfile that node-exporter serves from `/metrics`. - -## Install (rpi and siriussec only — never linode) - -```sh -install -m 0755 rosenpass-metrics.sh /usr/local/sbin/rosenpass-metrics.sh -install -m 0644 rosenpass-metrics.service /etc/systemd/system/ -install -m 0644 rosenpass-metrics.timer /etc/systemd/system/ -# Shared with the node-exporter DaemonSet's hostPath. The unit's sandbox sets -# ProtectSystem=strict, so this must exist before the first run (the kubelet's -# DirectoryOrCreate would normally make it once node-exporter rolls out). -install -d -m 0755 /var/lib/node-exporter/textfile -systemctl daemon-reload -systemctl enable --now rosenpass-metrics.timer -systemctl start rosenpass-metrics.service # first sample now, not in 60 s -``` - -Requires `wg`, `sha256sum`, `systemctl` and `awk` — present on Debian (rpi) and -Arch (siriussec). - -## Series - -``` -rosenpass_unit_active{node="rpi|siriussec"} 0|1 -rosenpass_psk_rotation_age_seconds{node=...,interface="wg0|wg-remote"} -rosenpass_psk_rotation_last_change_timestamp_seconds{node=...,interface="wg0|wg-remote"} -rosenpass_upnp_mapping_present{node="rpi"} 0|1 -rosenpass_upnp_last_check_timestamp_seconds{node="rpi"} -``` - -One series set per interface: `wg0` is Link A and `wg-remote` is Link B, and an -interface absent on that host (wg-remote on siriussec, where it does not exist) -is skipped. `RosenpassPskRotationStalled` is interface-agnostic -(`max by (node, interface) ... > 900`), so a stalled Link B pages as soon as the -`wg-remote` series exists — which is why hashing only `wg0` left Link B -unobserved. Its `absent()` arms name `rpi/wg0`, `rpi/wg-remote` and -`siriussec/wg0`, so a vanished Link B series pages too while siriussec never -claims a `wg-remote` it does not have. - -`rosenpass_upnp_mapping_present` is the state `rosenpass-upnp.sh` stamped on its -last 15-minute run (`/run/rosenpass-upnp.present`, `1`/`0`), and -`rosenpass_upnp_last_check_timestamp_seconds` is that file's mtime — so a -stopped timer reads as stale rather than as a flat healthy `1`. The 60-second -metrics timer only reads the file; it never calls `upnpc`, which would poll the -router's IGD 1440 times a day. Where the state file does not exist (siriussec) -neither series is emitted. - -The script hashes the output of `wg show preshared-keys` and stores -only the SHA-256 digest plus the last-change timestamp in -`/var/lib/rosenpass-exporter/last-hash-` (root-only, one file per -interface so a Link B rotation is never recorded as a Link A one). When the -digest changes the timestamp advances; otherwise only the age metric grows. -**Key material is never printed, logged or persisted.** The timer's own journal -therefore carries no key bytes — do not "improve" the script by echoing the -listing. - -An interface unreadable (down, no `CAP_NET_ADMIN`) emits no series for that -interface rather than resetting its age; `rosenpass_unit_active` and the -`absent()` arms of the alerts cover that case, so a broken exporter still pages. - -## Verify - -```sh -systemctl list-timers rosenpass-metrics.timer -cat /var/lib/node-exporter/textfile/rosenpass.prom -``` - -Both metrics should be present and the age well under 300 s once the cluster -scrapes the file (the file exists on the host either way; Prometheus only sees -it after the `values.yaml` change is reconciled). - -## Alerts - -`RosenpassDown` (unit inactive for 5 m) and `RosenpassPskRotationStalled` -(age > 900 s for 10 m), both `severity: warning`, both with `absent()` guards -so a missing series alerts instead of reading as healthy. Both cover **Link A -and Link B**: the rotation rule keys on `(node, interface)`, and its `absent()` -arms name `rpi/wg0`, `rpi/wg-remote` and `siriussec/wg0`. - -A third rule, `RosenpassUpnpMappingLost` (`severity: warning`, 10 m), covers -Link B's single inbound path: it fires when -`rosenpass_upnp_mapping_present == 0`, when no `rosenpass-upnp` run has stamped -the state for over 30 minutes (stopped timer, hung IGD), or when the series is -absent altogether. - -## Link B (rpi wg-remote ↔ linode wg0) - -Link B is the second transport link: rpi `wg-remote` `10.20.0.2` ↔ linode `wg0` -`10.20.0.1`, the exchange on UDP 9999 across the public internet. Two facts make -it fragile in ways Link A is not: - -- **The Pi's inbound path is a UPnP mapping**, because the home router has no - accessible admin panel. `rosenpass-upnp.sh` re-asserts - `UDP 9999 -> 192.168.1.125:9999 'rosenpass-pq'` with a permanent lease every - 15 minutes, logs to `logger -t rosenpass-upnp` and exits non-zero when the - mapping cannot be restored. Install: - - ```sh - install -m 0755 rosenpass-upnp.sh /usr/local/sbin/ - install -m 0644 rosenpass-upnp.service rosenpass-upnp.timer /etc/systemd/system/ - systemctl daemon-reload && systemctl enable --now rosenpass-upnp.timer - upnpc -l | grep 9999 # 9999->192.168.1.125:9999, lease 0 - ``` - -- **The linode's peer block needs the Pi's public address, which is residential - DHCP.** Chosen strategy: a **documented static endpoint, no sync timer** — - proved from the router itself: `upnpc -s` reports the WAN connection - `Connected, uptime=…` with `Time started : Thu Sep 10 16:38:13 2026` and - `ExternalIPAddress = 137.118.156.124`, i.e. ~83 days on the address that is - configured, and three independent echo services agreed (2026-12-03). If the - address moves the exchange stops and the link keeps its last PSK — which is - what `rosenpass_psk_rotation_age_seconds{interface="wg-remote"}` catches. - Re-point by editing `endpoint = ":9999"` in the linode's - `/etc/rosenpass/config.toml` and `systemctl restart rosenpass` there (both - ends do not need restarting; the Pi dials `50.116.38.217:9999`). - -Rollout order that cannot strand the far end: this link carries the only SSH path -to the linode, so `/root/rosenpass-linkb-rollback.sh` -(`linkb-rollback-rpi.sh`, `linkb-rollback-linode.sh`) is staged on **both** hosts -and armed as a transient `systemd-run --on-active=420s` timer *before* the -linode's unit starts, self-cancelling via `/run/rosenpass-linkb-ok`. It restores -the Pi's Link A-only `/etc/rosenpass/config.toml.pre-linkb` and the static -`PresharedKey`s from the untouched `/etc/wireguard/*.conf` with `wg syncconf`. -The Linode end is restored by `wg syncconf wg0` from its own conf, so the hub's -client peers keep working. - -Verify both ends agree and the key rotates, without printing key material (run -as root on the Pi): `linkb-verify.sh` — it hashes each end's PSK, compares them, -and prints the Link A sentinel so a scoped rotation is distinguishable from an -interface-wide one. Expect a changed digest 180 s apart with `agree` on both -samples. - -## Testing the rules without merging - -`kustomize build monitoring/controllers/home` proves the rule renders; these two -prove the PromQL, before Flux ever sees it (a rule that loads but selects -nothing is the failure mode that matters here): - -```sh -# 1. syntax + expression validation. promtool wants a bare `groups:` file, so -# strip the CRD wrapper first (PyYAML; jq cannot read YAML). -python3 - <<'PY' -import yaml -d = yaml.safe_load(open('monitoring/controllers/home/rosenpass.yaml')) -yaml.safe_dump({'groups': d['spec']['groups']}, open('/tmp/rosenpass-rules.yaml', 'w')) -PY -kubectl -n monitoring run promtool-check --rm -i --restart=Never \ - --image=quay.io/prometheus/prometheus:v3.15.1-distroless \ - --command -- /bin/promtool check rules /dev/stdin < /tmp/rosenpass-rules.yaml -``` - -```sh -# 2. behaviour: promtool test rules with input_series. Mount the rule file and -# a test file (rule_files: [rosenpass-rules.yaml]) from a ConfigMap and check -# four scenarios — healthy (no alerts), one unit down (only that node), age -# over threshold plus a missing peer series, and every series missing (both -# absent() arms). Expect `SUCCESS`. Note promtool compares annotations -# exactly, so expectations have to carry the rendered text. -``` - -Keep the test file out of the repo: it duplicates the annotation strings, so any -edit to the alerts would have to re-derive it from `rosenpass.yaml`. - diff --git a/infrastructure/networking/rosenpass/linkb-rollback-linode.sh b/infrastructure/networking/rosenpass/linkb-rollback-linode.sh deleted file mode 100755 index 60aca1f..0000000 --- a/infrastructure/networking/rosenpass/linkb-rollback-linode.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash -# Self-cancelling rollback for the Link B rollout, Linode end (wg0 hub). -# -# Armed as a transient `systemd-run --on-active=420s` timer on the Linode before -# rosenpass is started there. It acts locally, because the only SSH path to this -# host runs over the tunnel a PSK mismatch would break. -# -# Cancelled by touching /run/rosenpass-linkb-ok on this host once rotation and -# the cluster are verified. -# -# What it restores: the static PresharedKeys of every peer in -# /etc/wireguard/wg0.conf, and stops/disables the rosenpass unit. It never -# brings the interface down. -set -u - -log() { logger -t rosenpass-linkb "$*"; echo "$*"; } - -# Self-cancel: the operator touches this flag after verification, so this script -# is a no-op if the run actually succeeded. -if [ -f /run/rosenpass-linkb-ok ]; then - log "watchdog fired but /run/rosenpass-linkb-ok exists - no action taken" - exit 0 -fi - -log "ROLLBACK triggered: Link B did not verify within the watchdog window" - -systemctl disable --now rosenpass.service || log "warn: disable --now rosenpass failed" - -if wg-quick strip wg0 > /run/wg0.rollback.stripped 2>/dev/null; then - if wg syncconf wg0 /run/wg0.rollback.stripped; then - log "wg0 synced from conf: static PresharedKeys restored for all peers" - else - log "ERROR: wg syncconf wg0 failed; live PSKs unchanged" - fi -else - log "ERROR: wg-quick strip wg0 failed; live PSKs unchanged" -fi -rm -f /run/wg0.rollback.stripped - -log "ROLLBACK done - verify: wg show wg0 latest-handshakes (rpi peer < 180 s)" diff --git a/infrastructure/networking/rosenpass/linkb-rollback-rpi.sh b/infrastructure/networking/rosenpass/linkb-rollback-rpi.sh deleted file mode 100755 index 31d6d44..0000000 --- a/infrastructure/networking/rosenpass/linkb-rollback-rpi.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash -# Self-cancelling rollback for the Link B rollout (rpi wg-remote <-> linode wg0). -# -# Armed as a transient `systemd-run --on-active=420s` timer before rosenpass is -# started on the Linode. It must live on THIS host and act locally: a PSK -# mismatch on Link B kills the WireGuard tunnel, and that tunnel is the only SSH -# path to the far end, so no remote rollback can be delivered over it. -# -# Cancelled by touching /run/rosenpass-linkb-ok (checked by the timer unit's -# command, not here) once rotation and the cluster are verified. -# -# What it restores: -# 1. the pre-rollout rosenpass config (Link A peer only - Link A keeps working) -# 2. the static PresharedKey on the wg-remote peer, from /etc/wireguard/wg-remote.conf -# -# Never touches wg0 (Link A) or any client peer. -set -u - -log() { logger -t rosenpass-linkb "$*"; echo "$*"; } - -# Self-cancel: the operator touches this flag after verification, so this script -# is a no-op if the run actually succeeded. -if [ -f /run/rosenpass-linkb-ok ]; then - log "watchdog fired but /run/rosenpass-linkb-ok exists - no action taken" - exit 0 -fi - -log "ROLLBACK triggered: Link B did not verify within the watchdog window" - -# 1. Stop rosenpass first, so it cannot re-inject a rotating PSK mid-restore. -systemctl disable --now rosenpass.service || log "warn: disable --now rosenpass failed" - -# 2. Put the Link A-only config back and bring Link A's rotation back up. -if [ -f /etc/rosenpass/config.toml.pre-linkb ]; then - cp -a /etc/rosenpass/config.toml.pre-linkb /etc/rosenpass/config.toml - log "restored /etc/rosenpass/config.toml from config.toml.pre-linkb" -else - log "warn: /etc/rosenpass/config.toml.pre-linkb missing; config left as-is" -fi -systemctl enable --now rosenpass.service || log "warn: restarting rosenpass failed" - -# 3. Restore the static PSK on wg-remote from the conf (the rollback floor). -if wg-quick strip wg-remote > /run/wg-remote.rollback.stripped 2>/dev/null; then - if wg syncconf wg-remote /run/wg-remote.rollback.stripped; then - log "wg-remote synced from conf: static PresharedKey restored" - else - log "ERROR: wg syncconf wg-remote failed; live PSK unchanged" - fi -else - log "ERROR: wg-quick strip wg-remote failed; live PSK unchanged" -fi -rm -f /run/wg-remote.rollback.stripped - -log "ROLLBACK done - verify: wg show wg-remote latest-handshakes (expect < 180 s)" diff --git a/infrastructure/networking/rosenpass/linkb-verify.sh b/infrastructure/networking/rosenpass/linkb-verify.sh deleted file mode 100755 index 5d8973c..0000000 --- a/infrastructure/networking/rosenpass/linkb-verify.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -# Sample Link B PSK hashes on both ends. Prints no key material: the preshared -# key line is filtered on each host and only its SHA-256 (first 16 hex) leaves. -set -u -LINKB_LINODE='/2Y0XpJYd9Vl9Al6zNAlQimEYA+xY9Y5PO6nUDkfKEA=' # linode wg0 pub (peer on the Pi) -LINKB_RPI='h1v1Rhrnq2N2kt454xQamL1Y1x0TaICa1zoKgyZHpkM=' # rpi wg-remote pub (peer on the linode) -LINKA='+e50qTPdZiyxMtYHRSdGILIrh06JflFQq5+TZRjVyic=' # siriussec (Link A sentinel) - -h() { tr -d '\n' | sha256sum | cut -c1-16; } - -ts=$(date -u +%FT%TZ) - -pi_linkb=$(wg show wg-remote preshared-keys 2>/dev/null | grep -F "$LINKB_LINODE" | awk '{print $2}' | h) -pi_linka=$(wg show wg0 preshared-keys 2>/dev/null | grep -F "$LINKA" | awk '{print $2}' | h) - -ln_linkb=$(ssh -n -i /home/sirius/.ssh/linode_admin -o BatchMode=yes -o ConnectTimeout=10 root@10.20.0.1 \ - "wg show wg0 preshared-keys | grep -F '$LINKB_RPI' | awk '{print \$2}'" | h) - -pi_hs=$(wg show wg-remote latest-handshakes 2>/dev/null | grep -F "$LINKB_LINODE" | awk '{print $2}') -ln_hs=$(ssh -n -i /home/sirius/.ssh/linode_admin -o BatchMode=yes -o ConnectTimeout=10 root@10.20.0.1 \ - "wg show wg0 latest-handshakes | grep -F '$LINKB_RPI' | awk '{print \$2}'") - -agree="MISMATCH" -[ "$pi_linkb" = "$ln_linkb" ] && agree="agree" -printf '%s linkB pi=%s linode=%s %s | linkA(pi)=%s | hs pi=%s linode=%s\n' \ - "$ts" "$pi_linkb" "$ln_linkb" "$agree" "$pi_linka" "$pi_hs" "$ln_hs" diff --git a/infrastructure/networking/rosenpass/rosenpass-metrics.service b/infrastructure/networking/rosenpass/rosenpass-metrics.service deleted file mode 100644 index 0dc0826..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-metrics.service +++ /dev/null @@ -1,23 +0,0 @@ -[Unit] -Description=Rosenpass health metrics for node-exporter (textfile collector) -Documentation=file:///usr/local/sbin/rosenpass-metrics.sh -# No Requires=/After= on rosenpass.service or wg-quick@wg0.service on purpose: -# the recorder has to keep running and keep exporting while the unit it watches -# is dead or the interface is down — a hard dependency would take the metric -# away exactly when it becomes the alert. - -[Service] -Type=oneshot -ExecStart=/usr/local/sbin/rosenpass-metrics.sh -User=root -NoNewPrivileges=yes -ProtectSystem=strict -ProtectHome=yes -PrivateTmp=yes -# /var/lib/rosenpass-exporter (hash state) is created by systemd. -StateDirectory=rosenpass-exporter -# The textfile dir is shared with the node-exporter DaemonSet (hostPath). It is -# created by the install step; the leading `-` keeps the unit startable if a -# node has lost it (the node-exporter DirectoryOrCreate recreates it), instead -# of failing the whole unit with 226/NAMESPACE. -ReadWritePaths=-/var/lib/node-exporter/textfile diff --git a/infrastructure/networking/rosenpass/rosenpass-metrics.sh b/infrastructure/networking/rosenpass/rosenpass-metrics.sh deleted file mode 100644 index 8cda18e..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-metrics.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/bin/sh -# rosenpass-metrics.sh — emit Rosenpass health metrics for node-exporter's -# textfile collector. -# -# Installed on rpi and siriussec (the two ends of Link A: rpi wg0 10.10.0.1 <-> -# siriussec wg0 10.10.0.2), run every 60 s by rosenpass-metrics.timer as root. -# See README.md in this directory. -# -# Why a host script: kube-prometheus-stack-prometheus-node-exporter is -# distroless and ships without --collector.textfile.directory (and without the -# dbus plumbing --collector.systemd needs), so nothing inside the cluster can -# observe a host systemd unit. This writes a textfile that the DaemonSet's -# textfile collector then serves on :9100/metrics. -# -# Signals: -# rosenpass_unit_active{node} -# 1 when `systemctl is-active rosenpass.service` -# says active, else 0. -# rosenpass_psk_rotation_age_seconds{node,interface} -# seconds since that interface's preshared-key set -# last changed. Rotation runs about every two minutes. -# rosenpass_psk_rotation_last_change_timestamp_seconds{node,interface} -# unix timestamp of that last observed change. -# rosenpass_upnp_mapping_present{node} -# 1/0 state that rosenpass-upnp.sh stamped on its -# last run (Link B's only inbound path on the Pi). -# Only emitted where that unit runs: no state file, -# no series, so siriussec does not advertise it. -# rosenpass_upnp_last_check_timestamp_seconds{node} -# unix mtime of that state file, so a stopped -# rosenpass-upnp.timer reads as stale rather than as -# a flat healthy 1. -# -# Interfaces are emitted independently: wg0 is Link A (rpi <-> siriussec) and -# wg-remote is Link B (rpi <-> linode, through a permanent UPnP mapping on a -# router with no admin access). Link B stalls silently if the Pi's residential -# public address moves, so it needs its own series — hashing only wg0 leaves -# Link B unobserved. -# -# The preshared key is NEVER printed, logged or stored: each interface's key -# listing is piped straight into sha256sum and only the hex digest is kept, in a -# root-only state file. Do not add an `echo` of the listing while debugging. -# -# Deliberately independent of rosenpass.service: this script must keep -# reporting (unit_active=0, age growing) while the thing it watches is dead. -set -eu - -NODE=$(hostname -s) -# Interfaces rosenpass manages on this host. One absent here is skipped, so the -# same file is correct on rpi (wg0 + wg-remote) and siriussec (wg0 only). -IFACES="wg0 wg-remote" -UNIT=rosenpass.service - -STATE_DIR=/var/lib/rosenpass-exporter -OUT_DIR=/var/lib/node-exporter/textfile -OUT_FILE=$OUT_DIR/rosenpass.prom - -# 0644 so the node-exporter container (nobody/65534) can read the file and the -# directory stays traversable. -umask 022 -mkdir -p "$STATE_DIR" "$OUT_DIR" - -now=$(date +%s) - -# --- 1. unit state ----------------------------------------------------------- -active=0 -if [ "$(systemctl is-active "$UNIT" 2>/dev/null || true)" = "active" ]; then - active=1 -fi - -# --- 2. UPnP mapping state (Link B inbound path) ----------------------------- -# rosenpass-upnp.sh stamps 1/0 into /run on each of its 15-min runs. This timer -# must NOT call upnpc itself: that would poll the IGD 1440x/day and put the -# fragile component in the hot path. No state file means this host does not run -# that unit (siriussec), so emit nothing there. -UPNP_STATE=/run/rosenpass-upnp.present -upnp="" -upnp_ts="" -if [ -r "$UPNP_STATE" ]; then - upnp=$(head -n 1 "$UPNP_STATE" 2>/dev/null | tr -d '[:space:]') - case "$upnp" in - 0 | 1) upnp_ts=$(stat -c %Y "$UPNP_STATE" 2>/dev/null || echo "$now") ;; - *) upnp="" ;; - esac -fi - -# --- 3. PSK rotation, per interface ----------------------------------------- -# `wg show ... preshared-keys` fails (and prints nothing) when the interface is -# absent; command substitution would otherwise hash an empty string, which looks -# like a change on the first poll after the interface returns. Only hash real -# output, and keep one state file per interface so a Link B rotation is never -# recorded as a Link A one. -tmp="$OUT_FILE.$$" -{ - printf '# HELP rosenpass_unit_active rosenpass.service is active (1) or not (0).\n' - printf '# TYPE rosenpass_unit_active gauge\n' - printf 'rosenpass_unit_active{node="%s"} %s\n' "$NODE" "$active" - - if [ -n "$upnp" ]; then - printf '# HELP rosenpass_upnp_mapping_present The Link B UPnP mapping (UDP 9999 -> rpi) is present (1) or missing (0), as of the last rosenpass-upnp.sh run.\n' - printf '# TYPE rosenpass_upnp_mapping_present gauge\n' - printf 'rosenpass_upnp_mapping_present{node="%s"} %s\n' "$NODE" "$upnp" - printf '# HELP rosenpass_upnp_last_check_timestamp_seconds Unix timestamp of the last rosenpass-upnp.sh run that wrote the state file.\n' - printf '# TYPE rosenpass_upnp_last_check_timestamp_seconds gauge\n' - printf 'rosenpass_upnp_last_check_timestamp_seconds{node="%s"} %s\n' "$NODE" "$upnp_ts" - fi - - printf '# HELP rosenpass_psk_rotation_age_seconds Seconds since that interface preshared-key set last changed.\n' - printf '# TYPE rosenpass_psk_rotation_age_seconds gauge\n' - printf '# HELP rosenpass_psk_rotation_last_change_timestamp_seconds Unix timestamp of the last observed preshared-key change on that interface.\n' - printf '# TYPE rosenpass_psk_rotation_last_change_timestamp_seconds gauge\n' - - for IFACE in $IFACES; do - psk_list=$(wg show "$IFACE" preshared-keys 2>/dev/null || true) - [ -n "$psk_list" ] || continue - - STATE_FILE=$STATE_DIR/last-hash-$IFACE - last_hash="" - last_change="" - if [ -f "$STATE_FILE" ]; then - last_hash=$(sed -n '1p' "$STATE_FILE") - last_change=$(sed -n '2p' "$STATE_FILE") - fi - - hash_now=$(printf '%s' "$psk_list" | sha256sum | awk '{print $1}') - if [ "$hash_now" != "$last_hash" ]; then - # First observation or an actual rotation: stamp it. - last_change=$now - printf '%s\n%s\n' "$hash_now" "$last_change" > "$STATE_FILE.tmp" - mv "$STATE_FILE.tmp" "$STATE_FILE" - fi - - [ -n "$last_change" ] || continue - age=$((now - last_change)) - [ "$age" -ge 0 ] || age=0 - printf 'rosenpass_psk_rotation_age_seconds{node="%s",interface="%s"} %s\n' "$NODE" "$IFACE" "$age" - printf 'rosenpass_psk_rotation_last_change_timestamp_seconds{node="%s",interface="%s"} %s\n' "$NODE" "$IFACE" "$last_change" - done -} > "$tmp" -chmod 0644 "$tmp" -mv "$tmp" "$OUT_FILE" diff --git a/infrastructure/networking/rosenpass/rosenpass-metrics.timer b/infrastructure/networking/rosenpass/rosenpass-metrics.timer deleted file mode 100644 index 197f9af..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-metrics.timer +++ /dev/null @@ -1,11 +0,0 @@ -[Unit] -Description=Collect Rosenpass health metrics every 60s - -[Timer] -OnBootSec=30s -OnUnitActiveSec=60s -AccuracySec=5s -Unit=rosenpass-metrics.service - -[Install] -WantedBy=timers.target diff --git a/infrastructure/networking/rosenpass/rosenpass-upnp.service b/infrastructure/networking/rosenpass/rosenpass-upnp.service deleted file mode 100644 index e1675b2..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-upnp.service +++ /dev/null @@ -1,13 +0,0 @@ -[Unit] -Description=Re-assert UPnP mapping for Rosenpass Link B (UDP 9999 -> rpi) -Documentation=https://github.com/rosenpass/rosenpass -After=network-online.target -Wants=network-online.target - -[Service] -Type=oneshot -ExecStart=/usr/local/sbin/rosenpass-upnp.sh -# A router reboot drops the mapping; retry a few times before giving up so a -# transient WAN/IGD hiccup does not page anyone. -Restart=on-failure -RestartSec=30s diff --git a/infrastructure/networking/rosenpass/rosenpass-upnp.sh b/infrastructure/networking/rosenpass/rosenpass-upnp.sh deleted file mode 100755 index b655579..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-upnp.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# rosenpass-upnp.sh - re-assert the permanent UPnP mapping that gives the -# Linode a way back to Rosenpass on the Pi (UDP 9999 -> 192.168.1.125:9999). -# -# The home router's admin panel is inaccessible, so this mapping is the ONLY -# inbound path for the Rosenpass exchange on Link B (rpi wg-remote <-> -# linode wg0). It is runtime state: a router reboot, a factory reset or a UPnP -# daemon hiccup drops it, and the failure is silent - the link keeps its last -# PSK and simply stops being post-quantum. Hence this timer. -# -# Idempotent: re-adding an identical permanent-lease mapping is a no-op, so it -# is safe to run on a schedule. Never prints key material (it handles none). -set -uo pipefail - -LAN_IP=192.168.1.125 -PORT=9999 -DESC=rosenpass-pq -# Result of this run, read by rosenpass-metrics.sh (60 s textfile collector) so -# the mapping is observable without polling the IGD from that timer. /run is -# tmpfs: on a reboot the file is gone and the metric is absent until this unit -# runs again (OnBootSec=2min), which the alert treats as "unknown", not "lost". -STATE=/run/rosenpass-upnp.present - -set_present() { - printf '%s\n' "$1" > "$STATE.tmp" && mv "$STATE.tmp" "$STATE" -} - -out=$(upnpc -e "$DESC" -a "$LAN_IP" "$PORT" "$PORT" UDP 0 2>&1) || true - -# upnpc prints the mapping as " 0 UDP 9999->192.168.1.125:9999 'rosenpass-pq'" -if ! upnpc -l 2>/dev/null | grep -q "${PORT}->${LAN_IP}:${PORT}"; then - set_present 0 - logger -t rosenpass-upnp "mapping missing after re-assert: ${out}" - exit 1 -fi - -set_present 1 diff --git a/infrastructure/networking/rosenpass/rosenpass-upnp.timer b/infrastructure/networking/rosenpass/rosenpass-upnp.timer deleted file mode 100644 index 4fbcc35..0000000 --- a/infrastructure/networking/rosenpass/rosenpass-upnp.timer +++ /dev/null @@ -1,11 +0,0 @@ -[Unit] -Description=Re-assert the Rosenpass Link B UPnP mapping every 15 minutes - -[Timer] -OnBootSec=2min -OnUnitActiveSec=15min -AccuracySec=30s -Unit=rosenpass-upnp.service - -[Install] -WantedBy=timers.target diff --git a/infrastructure/node-io/namespace.yaml b/infrastructure/node-io/namespace.yaml index ef7e7dc..f678859 100644 --- a/infrastructure/node-io/namespace.yaml +++ b/infrastructure/node-io/namespace.yaml @@ -2,8 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: node-io - labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/infrastructure/storage/local-path-storage.yaml b/infrastructure/storage/local-path-storage.yaml index c840d83..6190da7 100644 --- a/infrastructure/storage/local-path-storage.yaml +++ b/infrastructure/storage/local-path-storage.yaml @@ -2,11 +2,6 @@ apiVersion: v1 kind: Namespace metadata: name: local-path-storage - labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest --- apiVersion: v1 kind: ServiceAccount diff --git a/monitoring/controllers/home/dashboards/build.py b/monitoring/controllers/home/dashboards/build.py index 2441817..fe46072 100644 --- a/monitoring/controllers/home/dashboards/build.py +++ b/monitoring/controllers/home/dashboards/build.py @@ -17,9 +17,6 @@ OUT_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser( "~/Projects/homek8s/monitoring/controllers/home/dashboards") DS = {"type": "prometheus", "uid": "prometheus"} -# Loki is provisioned by infrastructure/logging/datasource.yaml with a pinned -# uid, so panels can reference it without a lookup. -DS_LOKI = {"type": "loki", "uid": "loki"} CLUSTER_NS = 'namespace=~"$namespace"' _next_id = [0] @@ -39,10 +36,10 @@ def target(expr, legend=None, ref="A", instant=False, fmt="time_series"): def ts(title, targets, grid, unit=None, desc="", stack=False, fill=0, overrides=None, - w=12, h=8, ds=DS): + w=12, h=8): p = { "id": pid(), "type": "timeseries", "title": title, "description": desc, - "datasource": ds, "gridPos": grid, "targets": targets, + "datasource": DS, "gridPos": grid, "targets": targets, "fieldConfig": {"defaults": {"custom": {"lineWidth": 1, "fillOpacity": fill, "showPoints": "never"}, "color": {"mode": "palette-classic"}}, @@ -59,10 +56,10 @@ def ts(title, targets, grid, unit=None, desc="", stack=False, fill=0, overrides= def stat(title, targets, grid, unit=None, desc="", text_size=32, reducer="lastNotNull", - thresholds=None, w=4, h=5, decimals=None, ds=DS): + thresholds=None, w=4, h=5, decimals=None): p = { "id": pid(), "type": "stat", "title": title, "description": desc, - "datasource": ds, "gridPos": grid, "targets": targets, + "datasource": DS, "gridPos": grid, "targets": targets, "fieldConfig": {"defaults": { "color": {"mode": "thresholds"}, "mappings": [], @@ -108,39 +105,6 @@ def row(title, y): "gridPos": {"h": 1, "w": 24, "x": 0, "y": y}, "panels": []} -# ---------------------------------------------------------------- logs -------- -# Loki targets. NOTE the field names are the audit pipeline's, not the raw -# kube-apiserver audit-event ones: infrastructure/logging/alloy/config.alloy -# re-emits each record as a flat allowlist, so `objectRef.resource` arrives as -# the stream label `resource` and `user.username` as `user`. `| json` is only -# needed to reach `user`/`ns`/`name`; the resource filter stays in the selector -# as a label matcher so Loki prunes streams before parsing anything. -AUDIT_SECRETS = '{job="kube/apiserver-audit", resource="secrets"}' -POD_LOGS = '{job="kube/pods"}' -POD_SEL = 'job="kube/pods"' -RUNNER_NS = 'namespace=~"$runner_ns"' - - -def loki_target(expr, legend=None, ref="A", instant=False): - t = {"datasource": DS_LOKI, "expr": expr, "refId": ref, - "queryType": "instant" if instant else "range", - "range": not instant, "instant": instant} - if legend: - t["legendFormat"] = legend - return t - - -def logs(title, targets, grid, desc="", sort="Descending"): - return { - "id": pid(), "type": "logs", "title": title, "description": desc, - "datasource": DS_LOKI, "gridPos": grid, "targets": targets, - "options": {"showTime": True, "showLabels": False, "showCommonLabels": False, - "wrapLogMessage": True, "prettifyLogMessage": False, - "enableLogDetails": True, "dedupStrategy": "none", - "sortOrder": sort}, - } - - def dashboard(uid, title, tags, panels, description, variables=None): return { "uid": uid, "title": title, "description": description, "tags": tags, @@ -166,51 +130,17 @@ def ns_variable(): } -def loki_ns_variable(): - # Same "All = .*" contract as ns_variable, but the option list comes from - # Loki's label API so it also contains namespaces Prometheus never scrapes - # (ci-probe, metabase, ...) and does not need kube-state-metrics. - return { - "name": "namespace", "label": "Namespace", "type": "query", - "datasource": DS_LOKI, "refresh": 2, "includeAll": True, "multi": True, - "allValue": ".*", "current": {"selected": True, "text": ["All"], "value": ["$__all"]}, - "options": [], - "query": {"query": 'label_values(%s, namespace)' % POD_LOGS, "refId": "LokiNamespace"}, - } - - -def loki_runner_ns_variable(): - # Runner namespaces are being moved by t_2bbe34a8 (forgejo -> forgejo-runners, - # with ci-runners also live), so the panels discover them instead of pinning - # one name: "All" expands to a regex that matches any *runner* namespace plus - # forgejo itself (which still runs pods the runners need to be read next to). - return { - "name": "runner_ns", "label": "Runner namespace", "type": "query", - "datasource": DS_LOKI, "refresh": 2, "includeAll": True, "multi": True, - "allValue": ".*(runner|forgejo).*", - "current": {"selected": True, "text": ["All"], "value": ["$__all"]}, - "options": [], - "query": {"query": 'label_values({job="kube/pods", namespace=~".*(runner|forgejo).*"}, ' - 'namespace)', "refId": "LokiRunnerNamespace"}, - } - - # ---------------------------------------------------------------- runners ----- -# The CI capsule moved out of `forgejo` (card t_2bbe34a8, PSA baseline there) into -# `ci-runners`; every pod/PVC/Deployment target below uses this namespace. The -# `cnpg_actions_*` queue/jobs targets keep namespace="forgejo" — that is the -# Forgejo *database*, not the runners. Do not conflate the two. -CI_RUNNERS_NS = 'ci-runners' # Only the three runner Deployments' pods. `forgejo-runner-.*` also matches the # `forgejo-runner-prune-*` CronJob pods, which are Completed and permanently # "not Ready" — that turned a 0 into a 3 on the not-Ready stat. -RUN = 'namespace="%s",pod=~"forgejo-runner-(amd64|arm64|deploy-arm64)-.*"' % CI_RUNNERS_NS +RUN = 'namespace="forgejo",pod=~"forgejo-runner-(amd64|arm64|deploy-arm64)-.*"' SIRIUSSEC_FS = 'instance="10.10.0.2:9100",mountpoint="/"' RPI_FS = 'instance="10.10.0.1:9100",mountpoint="/"' runners = [ row("Runners & queue", 0), - stat("Runner pods Ready", [target('sum(kube_deployment_status_replicas_ready{namespace="%s",deployment=~"forgejo-runner-.*"}) or vector(0)' % CI_RUNNERS_NS)], + stat("Runner pods Ready", [target('sum(kube_deployment_status_replicas_ready{namespace="forgejo",deployment=~"forgejo-runner-.*"}) or vector(0)')], {"h": 5, "w": 4, "x": 0, "y": 1}, desc="replicas_ready summed across the three runner Deployments. Expected 3.", thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 2}, {"color": "green", "value": 3}]), stat("Runner pods not Ready", [target('sum(kube_pod_status_ready{%s,condition="false"} == 1) or vector(0)' % RUN)], @@ -262,7 +192,7 @@ runners = [ ts("Runner pod network I/O", [target('sum by (pod) (rate(container_network_receive_bytes_total{%s}[5m]))' % RUN, "{{pod}} in"), target('sum by (pod) (rate(container_network_transmit_bytes_total{%s}[5m]))' % RUN, "{{pod}} out", ref="B")], {"h": 8, "w": 8, "x": 0, "y": 25}, unit="Bps", desc="Image pulls and artifact traffic through the pod interface."), - stat("dind PVC nominal size", [target('max(kube_persistentvolumeclaim_resource_requests_storage_bytes{namespace="%s",persistentvolumeclaim="forgejo-runner-amd64"})' % CI_RUNNERS_NS)], + stat("dind PVC nominal size", [target('max(kube_persistentvolumeclaim_resource_requests_storage_bytes{namespace="forgejo",persistentvolumeclaim="forgejo-runner-amd64"})')], {"h": 8, "w": 4, "x": 8, "y": 25}, unit="bytes", desc="Requested size of the forgejo-runner-amd64 PVC (docker data-root + named CI volumes). This is the ceiling, not the usage — see the note on this row."), stat("siriussec root fs used", [target('100 * (1 - node_filesystem_avail_bytes{%s} / node_filesystem_size_bytes{%s})' % (SIRIUSSEC_FS, SIRIUSSEC_FS))], @@ -449,82 +379,6 @@ workloads = [ """, {"h": 8, "w": 24, "x": 0, "y": 49}), ] -# ----------------------------------------------------------------- logs ------ -# Time-to-answer panels for an incident: who touched a Secret (apiserver audit) -# and what a pod said before it died. Both run against the Loki datasource -# (infrastructure/logging/datasource.yaml, uid `loki`). -logs_panels = [ - row("kube-apiserver audit — secret access", 0), - stat("Secret events (1h)", - [loki_target("sum(count_over_time(" + AUDIT_SECRETS + "[1h]))", instant=True)], - {"h": 5, "w": 4, "x": 0, "y": 1}, ds=DS_LOKI, - desc="Count of audit records whose object is a Secret, filtered on the stream labels " - "the Alloy audit pipeline emits. No log-line parsing involved."), - ts("Secret access by user", - [loki_target("sum by (user) (count_over_time(" + AUDIT_SECRETS + " | json [5m]))", - legend="{{user}}")], - {"h": 8, "w": 20, "x": 4, "y": 1}, ds=DS_LOKI, fill=10, stack=True, - desc="The 'who read that credential' view. `user` comes from user.username in the audit " - "record, so `| json` is needed for the grouping; the resource filter stays in the " - "selector as a label matcher."), - logs("Secret access log — verb, object, caller", - [loki_target(AUDIT_SECRETS + ' | json | line_format "{{.verb}} ' - '{{.subresource}}{{.ns}}/{{.name}} — {{.user}} ({{.code}})"')], - {"h": 10, "w": 24, "x": 0, "y": 9}, - desc="One line per audit record that touched a Secret. Secret bodies are never stored: " - "the pipeline allowlists fields and drops requestObject/responseObject."), - - row("Pod logs", 19), - logs("Errors — namespace = $namespace", - [loki_target("{" + POD_SEL + ', namespace=~"$namespace"} |= "error"')], - {"h": 9, "w": 12, "x": 0, "y": 20}, - desc="The ordinary 'what did the pod say before it died' query. Substring filter, so it " - "catches `error` anywhere in the line."), - logs("Error / exception / fatal / panic (case-insensitive)", - [loki_target("{" + POD_SEL + ', namespace=~"$namespace"} ' - '|~ "(?i)error|exception|fatal|panic"')], - {"h": 9, "w": 12, "x": 12, "y": 20}, - desc="Wider net for stacks that log `Exception`, `FATAL` or `panic:` instead of the word " - "`error`."), - - row("CI runners (forgejo / forgejo-runners)", 29), - logs("Runner pod logs", - [loki_target("{" + POD_SEL + ", " + RUNNER_NS + "}")], - {"h": 9, "w": 12, "x": 0, "y": 30}, - desc="Everything the runner pods print — job container output, dind, and the runner's own " - "poll/registration lines. The namespace comes from the `runner_ns` variable, which " - "matches any *runner* namespace (forgejo, forgejo-runners, ci-runners) so the panel " - "survives the t_2bbe34a8 move without an edit."), - ts("Runner error / fail lines per 5m", - [loki_target("sum by (namespace) (count_over_time({" + POD_SEL + ", " + RUNNER_NS + - '} |~ "(?i)error|fail" [5m]))', legend="{{namespace}}")], - {"h": 9, "w": 12, "x": 12, "y": 30}, ds=DS_LOKI, fill=10, stack=True, - desc="Coarse CI pain signal. A silent stall (a build looping on `Ign:` with no error) does " - "not show here — check the log panel above for that."), - - row("How to read these streams", 39), - note("Field names and retention", "\n".join([ - "Loki is single-binary in the `logging` namespace: **192 h (8 d)** retention on an 8Gi PVC,", - "fed by the Alloy DaemonSet. These panels only read it.", - "", - "| `job` | source | stream labels |", - "|---|---|---|", - "| `kube/pods` | every container's stdout (`/var/log/pods`) | `namespace, pod, container, node` |", - "| `kube/apiserver-audit` | `siriussec`'s `/var/log/kubernetes/audit/audit.log` | `resource, verb` |", - "| `systemd-journal` | node journals | `unit, host, level` |", - "| `docker/json` | the Pi's docker container logs | `container` |", - "", - "**The audit field names are the Alloy pipeline's allowlist, not the raw audit event's.**", - "`objectRef.resource` arrives as the stream label `resource` and `user.username` as the", - "line field `user`, so the usable query is", - "`{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json` — an `objectRef_resource` or", - "`user_username` matcher returns **zero rows**. Secret bodies are never shipped: the", - "pipeline packs an allowlist and drops `requestObject`/`responseObject`", - "(`docs/logging.md`, `infrastructure/logging/alloy/config.alloy`).", - ]), {"h": 8, "w": 24, "x": 0, "y": 40}, h=8), -] - - DOCS = { "forgejo-runners": ("Forgejo Runners", ["homelab", "forgejo", "runners"], @@ -542,26 +396,16 @@ DOCS = { "Per-namespace requests vs usage, top pods, node health and internal-service availability.", "Cluster-wide view: who is using CPU/memory, what is Pending or restarting, how full " "the nodes' disks are, and whether the WireGuard-only internal services answer."), - "logs": ("Logs", - ["homelab", "logs", "loki", "audit"], - "Loki queries worth having: who read a Secret (apiserver audit), pod errors by namespace, CI runner output.", - "Loki single-binary in the `logging` namespace (192 h retention) holds pod logs, node journals, " - "the Pi's docker logs and the kube-apiserver audit stream. The audit panels answer 'who read " - "that credential'; the pod panels answer 'what did the pod say before it died'. Field names " - "are the Alloy pipeline's allowlist, not the raw audit event's — see the note panel."), } -PANELS = {"forgejo-runners": runners, "cnpg-postgres": cnpg, "home-lab-workloads": workloads, - "logs": logs_panels} +PANELS = {"forgejo-runners": runners, "cnpg-postgres": cnpg, "home-lab-workloads": workloads} os.makedirs(OUT_DIR, exist_ok=True) for uid, panels in PANELS.items(): _next_id[0] = 0 title, tags, desc, long_desc = DOCS[uid] d = dashboard(uid, title, tags, panels, long_desc, - variables=([ns_variable()] if uid == "cnpg-postgres" - else [loki_ns_variable(), loki_runner_ns_variable()] - if uid == "logs" else None)) + variables=[ns_variable()] if uid == "cnpg-postgres" else None) doc = { "apiVersion": "v1", "kind": "ConfigMap", @@ -569,13 +413,12 @@ for uid, panels in PANELS.items(): "name": "grafana-dashboard-" + uid, "namespace": "monitoring", "labels": {"grafana_dashboard": "1", "app.kubernetes.io/part-of": "homelab-dashboards"}, - # No grafana_folder annotation: the sidecar's API-backed import would need - # the admin credential, so the dashboards are imported by Grafana's *file* - # provider, which ignores per-dashboard folder annotations and puts every - # board in General next to the chart's own 28. Verified in grafana.db. - # (Since 2026-11-27 the live admin password equals monitoring/grafana-admin - # again — the DB was reset to the Secret's value — but the sidecar still - # imports by file, so nothing here depends on that.) + # No grafana_folder annotation: the sidecar's API-backed import cannot + # authenticate (Grafana's live admin password is the out-of-band one, + # not monitoring/grafana-admin — that Secret is only the first-boot + # seed), so the dashboards are imported by Grafana's *file* provider, + # which ignores per-dashboard folder annotations and puts every board + # in General next to the chart's own 28. Verified in grafana.db. "annotations": {"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"}, }, "data": {uid + ".json": json.dumps(d, indent=2) + "\n"}, @@ -592,4 +435,4 @@ for uid, panels in PANELS.items(): f.write("data:\n %s.json: |\n" % uid) for line in doc["data"][uid + ".json"].rstrip("\n").split("\n"): f.write(" " + line + "\n") - print("wrote", path) \ No newline at end of file + print("wrote", path) diff --git a/monitoring/controllers/home/dashboards/forgejo-runners.yaml b/monitoring/controllers/home/dashboards/forgejo-runners.yaml index 638cf4d..b28732d 100644 --- a/monitoring/controllers/home/dashboards/forgejo-runners.yaml +++ b/monitoring/controllers/home/dashboards/forgejo-runners.yaml @@ -87,7 +87,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(kube_deployment_status_replicas_ready{namespace=\"ci-runners\",deployment=~\"forgejo-runner-.*\"}) or vector(0)", + "expr": "sum(kube_deployment_status_replicas_ready{namespace=\"forgejo\",deployment=~\"forgejo-runner-.*\"}) or vector(0)", "refId": "A", "editorMode": "code", "range": true, @@ -155,7 +155,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(kube_pod_status_ready{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",condition=\"false\"} == 1) or vector(0)", + "expr": "sum(kube_pod_status_ready{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",condition=\"false\"} == 1) or vector(0)", "refId": "A", "editorMode": "code", "range": true, @@ -692,7 +692,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (pod, container) (increase(kube_pod_container_status_restarts_total{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[24h]))", + "expr": "sum by (pod, container) (increase(kube_pod_container_status_restarts_total{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[24h]))", "refId": "A", "editorMode": "code", "range": true, @@ -749,7 +749,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (pod) (rate(container_cpu_usage_seconds_total{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",container!=\"\"}[5m]))", + "expr": "sum by (pod) (rate(container_cpu_usage_seconds_total{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",container!=\"\"}[5m]))", "refId": "A", "editorMode": "code", "range": true, @@ -806,7 +806,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (pod) (container_memory_working_set_bytes{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",container!=\"\"})", + "expr": "sum by (pod) (container_memory_working_set_bytes{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\",container!=\"\"})", "refId": "A", "editorMode": "code", "range": true, @@ -876,7 +876,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (pod) (rate(container_network_receive_bytes_total{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[5m]))", + "expr": "sum by (pod) (rate(container_network_receive_bytes_total{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[5m]))", "refId": "A", "editorMode": "code", "range": true, @@ -888,7 +888,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (pod) (rate(container_network_transmit_bytes_total{namespace=\"ci-runners\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[5m]))", + "expr": "sum by (pod) (rate(container_network_transmit_bytes_total{namespace=\"forgejo\",pod=~\"forgejo-runner-(amd64|arm64|deploy-arm64)-.*\"}[5m]))", "refId": "B", "editorMode": "code", "range": true, @@ -945,7 +945,7 @@ data: "type": "prometheus", "uid": "prometheus" }, - "expr": "max(kube_persistentvolumeclaim_resource_requests_storage_bytes{namespace=\"ci-runners\",persistentvolumeclaim=\"forgejo-runner-amd64\"})", + "expr": "max(kube_persistentvolumeclaim_resource_requests_storage_bytes{namespace=\"forgejo\",persistentvolumeclaim=\"forgejo-runner-amd64\"})", "refId": "A", "editorMode": "code", "range": true, diff --git a/monitoring/controllers/home/dashboards/kustomization.yaml b/monitoring/controllers/home/dashboards/kustomization.yaml index 8de37f8..7cfdc10 100644 --- a/monitoring/controllers/home/dashboards/kustomization.yaml +++ b/monitoring/controllers/home/dashboards/kustomization.yaml @@ -8,7 +8,3 @@ resources: - forgejo-runners.yaml - cnpg-postgres.yaml - home-lab-workloads.yaml - # Loki panels: secret access from the apiserver audit stream, pod errors by - # namespace, CI runner output. Datasource uid `loki` - # (infrastructure/logging/datasource.yaml). - - logs.yaml diff --git a/monitoring/controllers/home/dashboards/logs.yaml b/monitoring/controllers/home/dashboards/logs.yaml deleted file mode 100644 index df83942..0000000 --- a/monitoring/controllers/home/dashboards/logs.yaml +++ /dev/null @@ -1,523 +0,0 @@ -# GENERATED by monitoring/controllers/home/dashboards/build.py — edit the script, not this file. -# Provisioned by the kube-prometheus-stack dashboard sidecar (label grafana_dashboard=1, -# NAMESPACE=ALL), so it wins over any UI edit. Dashboard uid: logs -apiVersion: v1 -kind: ConfigMap -metadata: - name: grafana-dashboard-logs - namespace: monitoring - labels: - grafana_dashboard: "1" - app.kubernetes.io/part-of: homelab-dashboards - annotations: - homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py -data: - logs.json: | - { - "uid": "logs", - "title": "Logs", - "description": "Loki single-binary in the `logging` namespace (192 h retention) holds pod logs, node journals, the Pi's docker logs and the kube-apiserver audit stream. The audit panels answer 'who read that credential'; the pod panels answer 'what did the pod say before it died'. Field names are the Alloy pipeline's allowlist, not the raw audit event's \u2014 see the note panel.", - "tags": [ - "homelab", - "logs", - "loki", - "audit" - ], - "timezone": "browser", - "editable": true, - "graphTooltip": 1, - "schemaVersion": 39, - "version": 1, - "refresh": "30s", - "time": { - "from": "now-6h", - "to": "now" - }, - "annotations": { - "list": [ - { - "builtIn": 1, - "datasource": { - "type": "grafana", - "uid": "-- Grafana --" - }, - "enable": true, - "hide": true, - "iconColor": "rgba(0, 211, 255, 1)", - "name": "Annotations & Alerts", - "type": "dashboard" - } - ] - }, - "links": [], - "templating": { - "list": [ - { - "name": "namespace", - "label": "Namespace", - "type": "query", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "refresh": 2, - "includeAll": true, - "multi": true, - "allValue": ".*", - "current": { - "selected": true, - "text": [ - "All" - ], - "value": [ - "$__all" - ] - }, - "options": [], - "query": { - "query": "label_values({job=\"kube/pods\"}, namespace)", - "refId": "LokiNamespace" - } - }, - { - "name": "runner_ns", - "label": "Runner namespace", - "type": "query", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "refresh": 2, - "includeAll": true, - "multi": true, - "allValue": ".*(runner|forgejo).*", - "current": { - "selected": true, - "text": [ - "All" - ], - "value": [ - "$__all" - ] - }, - "options": [], - "query": { - "query": "label_values({job=\"kube/pods\", namespace=~\".*(runner|forgejo).*\"}, namespace)", - "refId": "LokiRunnerNamespace" - } - } - ] - }, - "panels": [ - { - "id": 68, - "type": "row", - "title": "kube-apiserver audit \u2014 secret access", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 0 - }, - "panels": [] - }, - { - "id": 69, - "type": "stat", - "title": "Secret events (1h)", - "description": "Count of audit records whose object is a Secret, filtered on the stream labels the Alloy audit pipeline emits. No log-line parsing involved.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 5, - "w": 4, - "x": 0, - "y": 1 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum(count_over_time({job=\"kube/apiserver-audit\", resource=\"secrets\"}[1h]))", - "refId": "A", - "queryType": "instant", - "range": false, - "instant": true - } - ], - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "red", - "value": null - }, - { - "color": "green", - "value": 1 - } - ] - } - }, - "overrides": [] - }, - "options": { - "colorMode": "value", - "graphMode": "area", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "textMode": "auto", - "justifyMode": "auto" - } - }, - { - "id": 70, - "type": "timeseries", - "title": "Secret access by user", - "description": "The 'who read that credential' view. `user` comes from user.username in the audit record, so `| json` is needed for the grouping; the resource filter stays in the selector as a label matcher.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 8, - "w": 20, - "x": 4, - "y": 1 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum by (user) (count_over_time({job=\"kube/apiserver-audit\", resource=\"secrets\"} | json [5m]))", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false, - "legendFormat": "{{user}}" - } - ], - "fieldConfig": { - "defaults": { - "custom": { - "lineWidth": 1, - "fillOpacity": 10, - "showPoints": "never", - "stacking": { - "mode": "normal" - } - }, - "color": { - "mode": "palette-classic" - } - }, - "overrides": [] - }, - "options": { - "legend": { - "displayMode": "list", - "placement": "bottom", - "calcs": [ - "lastNotNull" - ] - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - } - }, - { - "id": 71, - "type": "logs", - "title": "Secret access log \u2014 verb, object, caller", - "description": "One line per audit record that touched a Secret. Secret bodies are never stored: the pipeline allowlists fields and drops requestObject/responseObject.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 10, - "w": 24, - "x": 0, - "y": 9 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json | line_format \"{{.verb}} {{.subresource}}{{.ns}}/{{.name}} \u2014 {{.user}} ({{.code}})\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 72, - "type": "row", - "title": "Pod logs", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 19 - }, - "panels": [] - }, - { - "id": 73, - "type": "logs", - "title": "Errors \u2014 namespace = $namespace", - "description": "The ordinary 'what did the pod say before it died' query. Substring filter, so it catches `error` anywhere in the line.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 0, - "y": 20 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$namespace\"} |= \"error\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 74, - "type": "logs", - "title": "Error / exception / fatal / panic (case-insensitive)", - "description": "Wider net for stacks that log `Exception`, `FATAL` or `panic:` instead of the word `error`.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 12, - "y": 20 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$namespace\"} |~ \"(?i)error|exception|fatal|panic\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 75, - "type": "row", - "title": "CI runners (forgejo / forgejo-runners)", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 29 - }, - "panels": [] - }, - { - "id": 76, - "type": "logs", - "title": "Runner pod logs", - "description": "Everything the runner pods print \u2014 job container output, dind, and the runner's own poll/registration lines. The namespace comes from the `runner_ns` variable, which matches any *runner* namespace (forgejo, forgejo-runners, ci-runners) so the panel survives the t_2bbe34a8 move without an edit.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 0, - "y": 30 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$runner_ns\"}", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 77, - "type": "timeseries", - "title": "Runner error / fail lines per 5m", - "description": "Coarse CI pain signal. A silent stall (a build looping on `Ign:` with no error) does not show here \u2014 check the log panel above for that.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 12, - "y": 30 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum by (namespace) (count_over_time({job=\"kube/pods\", namespace=~\"$runner_ns\"} |~ \"(?i)error|fail\" [5m]))", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false, - "legendFormat": "{{namespace}}" - } - ], - "fieldConfig": { - "defaults": { - "custom": { - "lineWidth": 1, - "fillOpacity": 10, - "showPoints": "never", - "stacking": { - "mode": "normal" - } - }, - "color": { - "mode": "palette-classic" - } - }, - "overrides": [] - }, - "options": { - "legend": { - "displayMode": "list", - "placement": "bottom", - "calcs": [ - "lastNotNull" - ] - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - } - }, - { - "id": 78, - "type": "row", - "title": "How to read these streams", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 39 - }, - "panels": [] - }, - { - "id": 79, - "type": "text", - "title": "Field names and retention", - "gridPos": { - "h": 8, - "w": 24, - "x": 0, - "y": 40 - }, - "options": { - "mode": "markdown", - "code": { - "language": "plaintext", - "showLineNumbers": false, - "showMiniMap": false - }, - "content": "Loki is single-binary in the `logging` namespace: **192 h (8 d)** retention on an 8Gi PVC,\nfed by the Alloy DaemonSet. These panels only read it.\n\n| `job` | source | stream labels |\n|---|---|---|\n| `kube/pods` | every container's stdout (`/var/log/pods`) | `namespace, pod, container, node` |\n| `kube/apiserver-audit` | `siriussec`'s `/var/log/kubernetes/audit/audit.log` | `resource, verb` |\n| `systemd-journal` | node journals | `unit, host, level` |\n| `docker/json` | the Pi's docker container logs | `container` |\n\n**The audit field names are the Alloy pipeline's allowlist, not the raw audit event's.**\n`objectRef.resource` arrives as the stream label `resource` and `user.username` as the\nline field `user`, so the usable query is\n`{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json` \u2014 an `objectRef_resource` or\n`user_username` matcher returns **zero rows**. Secret bodies are never shipped: the\npipeline packs an allowlist and drops `requestObject`/`responseObject`\n(`docs/logging.md`, `infrastructure/logging/alloy/config.alloy`)." - } - } - ] - } diff --git a/monitoring/controllers/home/dashboards/validate_panels.py b/monitoring/controllers/home/dashboards/validate_panels.py index 317d2c7..b9ca788 100755 --- a/monitoring/controllers/home/dashboards/validate_panels.py +++ b/monitoring/controllers/home/dashboards/validate_panels.py @@ -1,20 +1,15 @@ #!/usr/bin/env python3 -"""Verify every panel on the custom dashboards returns real data. +"""Verify every panel on the three custom dashboards returns real data. Reads the dashboard JSON out of the provisioned ConfigMap YAML (i.e. exactly what -Grafana loaded), extracts every PromQL/LogQL expression, queries the matching -datasource's HTTP API and prints panel title -> query -> series count -> sample. +Grafana loaded), extracts every PromQL expression, queries the Prometheus HTTP API +and prints panel title -> PromQL -> series count -> sample. -Prometheus panels go to PROM; panels whose datasource is `loki` go to LOKI. A -Loki panel is reported as OK only if its result is non-empty, which for a logs -panel means at least one entry (the series count alone is not enough). - -Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL] [LOKI_URL] +Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL] """ import json import os import sys -import time import urllib.parse import urllib.request @@ -23,12 +18,10 @@ import yaml DASH_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser( "~/Projects/homek8s/monitoring/controllers/home/dashboards") PROM = sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:9090" -LOKI = sys.argv[3] if len(sys.argv) > 3 else "http://127.0.0.1:3100" # Grafana template variable substitution for the "All" case, so the query the # script runs is the query Grafana runs. -SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*", - "$runner_ns": ".*(runner|forgejo).*", "${runner_ns}": ".*(runner|forgejo).*"} +SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*"} def substitute(expr): @@ -46,39 +39,6 @@ def query(expr): return body["data"]["result"], None -def query_loki(expr, instant=False): - if instant: - url = "%s/loki/api/v1/query?%s" % (LOKI, urllib.parse.urlencode( - {"query": expr, "time": "%d000000000" % time.time()})) - else: - now = int(time.time()) - url = "%s/loki/api/v1/query_range?%s" % (LOKI, urllib.parse.urlencode( - {"query": expr, "start": "%d000000000" % (now - 21600), - "end": "%d000000000" % now, "limit": 1000})) - with urllib.request.urlopen(url, timeout=30) as r: - body = json.load(r) - if body.get("status") != "success": - return None, 0, body.get("error") or body - result = body["data"]["result"] or [] - # Range/metric queries return {metric|stream, values:[[ts,line],...]}; an - # instant query returns {metric, value:[ts,val]} (singular). Count both, so a - # stat panel's single sample is "1 row" rather than looking empty. - rows = 0 - for x in result: - if "values" in x: - rows += len(x.get("values") or []) - elif "value" in x: - rows += 1 - return result, rows, None - - -def ds_type(panel, target): - ds = target.get("datasource") or panel.get("datasource") - if isinstance(ds, dict): - return ds.get("type") - return None - - def panels_of(dash): out = [] for p in dash.get("panels", []): @@ -106,20 +66,6 @@ for fn in sorted(os.listdir(DASH_DIR)): if not expr: continue total += 1 - if ds_type(p, t) == "loki": - result, rows, err = query_loki(expr, instant=bool(t.get("instant"))) - if err: - bad += 1 - print(" FAIL %-46s %s\n ERROR: %s" - % (p["title"][:46], expr.replace("\n", " ")[:110], err)) - continue - if not result or not rows: - bad += 1 - print(" EMPTY %-46s %s" % (p["title"][:46], expr.replace("\n", " ")[:110])) - continue - print(" OK %-46s %-3d series %-6d rows (loki)" - % (p["title"][:46], len(result), rows)) - continue result, err = query(expr) if err: bad += 1 diff --git a/monitoring/controllers/home/grafana-backup-networkpolicy.yaml b/monitoring/controllers/home/grafana-backup-networkpolicy.yaml deleted file mode 100644 index a2a427b..0000000 --- a/monitoring/controllers/home/grafana-backup-networkpolicy.yaml +++ /dev/null @@ -1,54 +0,0 @@ -# Egress lockdown for the nightly Grafana sqlite snapshot (card t_9d0428d8). -# -# Why: grafana-backup used to run `apk add --no-cache rsync openssh-client` at -# container start, so every night it dialled the Alpine CDN -# (dl-cdn.alpinelinux.org -> Fastly 151.101.x.132:443) and kept firing the -# `egress-new-dst` flow alert whenever that anycast address rotated. The -# toolchain is now baked into the image (images/backup/Dockerfile) and this -# policy makes any future runtime fetch fail loudly instead of silently -# reaching the internet. -# -# `monitoring` has no namespace-wide default-deny, so selecting the backup pod -# here isolates it on its own: the rules below are the complete egress allow -# list and everything else (including `world`) is dropped. `egressDeny` is -# stated explicitly so the intent survives a future namespace-wide allow being -# added — Cilium deny always beats allow. -# -# Needs: cluster DNS (the script resolves nothing itself, but the image and any -# `ssh` target lookup would), and root@10.10.0.5:22 — that is the Linode node's -# InternalIP, so Cilium classifies it `remote-node`, not `world`. The registry -# pull and the Grafana PVC access are not pod traffic and are unaffected. -apiVersion: cilium.io/v2 -kind: CiliumNetworkPolicy -metadata: - name: grafana-backup-egress - namespace: monitoring - labels: - app: grafana-backup -spec: - description: >- - grafana-backup pod: cluster DNS + SSH to the backup host (10.10.0.5:22) - only; no internet egress at run time. - endpointSelector: - matchLabels: - app: grafana-backup - egress: - - toEndpoints: - - matchLabels: - io.kubernetes.pod.namespace: kube-system - k8s-app: kube-dns - toPorts: - - ports: - - port: "53" - protocol: UDP - - port: "53" - protocol: TCP - - toEntities: - - remote-node - toPorts: - - ports: - - port: "22" - protocol: TCP - egressDeny: - - toEntities: - - world diff --git a/monitoring/controllers/home/grafana-backup.yaml b/monitoring/controllers/home/grafana-backup.yaml index bf233b3..2da83fb 100644 --- a/monitoring/controllers/home/grafana-backup.yaml +++ b/monitoring/controllers/home/grafana-backup.yaml @@ -27,10 +27,10 @@ data: # T480's root filesystem, the only local file is a ~3 MB copy in /tmp. set -eu - # No package install here on purpose: rsync/openssh-client/python3 are - # baked into the pinned image (images/backup/Dockerfile) and this pod's - # egress policy admits DNS + 10.10.0.5:22 only, so a runtime fetch would - # fail rather than silently dial the Alpine CDN (card t_9d0428d8). + if ! command -v rsync >/dev/null || ! command -v ssh >/dev/null; then + echo "== installing rsync + openssh-client" + apk add --no-cache rsync openssh-client >/dev/null + fi BACKUP_HOST=${BACKUP_HOST:-root@10.10.0.5} BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} @@ -128,22 +128,15 @@ spec: app: grafana-backup spec: restartPolicy: Never - # Pulled from the in-cluster Forgejo registry (which requires auth); - # monitoring had no registry pull secret before this job needed one. - imagePullSecrets: - - name: forgejo-pull # The grafana PVC is local-path on siriussec; RWO still allows a # second pod on the same node. nodeSelector: kubernetes.io/hostname: siriussec containers: - name: backup - # python3.12-alpine + rsync + openssh-client, baked at build time - # and pinned by digest (images/backup/Dockerfile, CI workflow - # .forgejo/workflows/backup-image.yml). The sqlite backup API is - # the only consistent way to copy a live database without a shell - # inside Grafana. Nothing is installed at run time. - image: forgejo.siriusdevops.com/sirius/backup-tools@sha256:cc8dc1645111b3a80b7c4d5168f6bce3002cae7417b3725683c057976f6e379a + # python3 alpine: the sqlite backup API is the only consistent + # way to copy a live database without a shell inside Grafana. + image: python:3.12-alpine imagePullPolicy: IfNotPresent command: ["/bin/sh", "/scripts/backup.sh"] env: diff --git a/monitoring/controllers/home/hubble-loss-gate.yaml b/monitoring/controllers/home/hubble-loss-gate.yaml deleted file mode 100644 index 7e2c200..0000000 --- a/monitoring/controllers/home/hubble-loss-gate.yaml +++ /dev/null @@ -1,160 +0,0 @@ -# Hubble flow-loss gate (audit F10). -# -# The flow stream is the sensor input for every flow-shaped detector -# (first-seen egress, beaconing shape, east-west novelty). If the agent's ring -# buffer drops events, a "quiet" window is indistinguishable from a lossy one, -# and a detector built on it will happily report "all clear" from an incomplete -# sample. These rules make the loss visible and define the gate: a window whose -# lost-event count is non-zero is NOT clean and must not be reported as such. -# -# Two very different things share the `hubble_lost_events_total` counter and they -# must not share a threshold: -# -# perf_event_ring_buffer / observer_events_queue -# Real loss on the way in — the BPF perf ring dropped an event, or the -# metrics exporter fell behind. Steady state is 0 on every node. Any -# increase over the window taints that window. -# -# hubble_ring_buffer -# NOT a drop. `Ring.read()` synthesises a LostEvent and bumps this counter -# whenever a read falls outside the ring's retained window, which the -# agent's own 5 s health probe and every `hubble status` / Hubble UI status -# request do on a ring holding < 60 s of flows (cilium#46584, still open in -# the deployed 1.20.1). A couple of UI reads per hour is ~0.001 events/s and -# means nothing; the 12/min probe storm measured in F10 was ~0.2 events/s. -# So this source is alerted on a *rate*, never on `increase() > 0`. -# -# Recorders: -# hubble:lost_events_increase_30m real loss only, per (node, source), so the -# alert can name which source lost events. -# hubble:ring_buffer_read_rate_15m read churn on the ring, events/s per node. -# hubble:flows_processed_increase_30m denominator for the material ratio. -# The detector contract (docs/hubble-event-loss.md §"Gate") is: read -# `hubble:lost_events_increase_30m` with the same window as the traffic it is -# judging; if it is > 0, label the window incomplete instead of clean. -apiVersion: monitoring.coreos.com/v1 -kind: PrometheusRule -metadata: - name: hubble-event-loss - namespace: monitoring - labels: - release: kube-prometheus-stack -spec: - groups: - - name: hubble-event-loss - rules: - # One number for the gate, from the two sources that mean real loss. - # `increase()` absorbs the counter reset that an agent restart causes, - # so a rolled DaemonSet does not look like loss. Empty source filter out - # of scope: a source that starts reporting is a loss, not a read. - - record: hubble:lost_events_increase_30m - expr: | - sum by (node, source) ( - increase(hubble_lost_events_total{source=~"perf_event_ring_buffer|observer_events_queue"}[30m]) - ) - # Ring-buffer read churn, kept separate and rate-based. 0.05 events/s = - # 45 reads per 15 min; the F10 probe storm was ~0.2/s, two UI reads an - # hour is ~0.001/s. - - record: hubble:ring_buffer_read_rate_15m - expr: | - sum by (node) (rate(hubble_lost_events_total{source="hubble_ring_buffer"}[15m])) - # Denominator for the material-loss ratio. Trace is the total flow - # counter; L7/Drop/PolicyVerdict are subsets of it and would - # double-count. - - record: hubble:flows_processed_increase_30m - expr: | - sum by (node) (increase(hubble_flows_processed_total{type="Trace"}[30m])) - - - alert: HubbleFlowWindowIncomplete - # The gate from F10: any event lost on the way in during the window - # means a flow-shaped detector may have missed something, so the window - # must not be reported as clean. Steady state is 0 on all three nodes. - # Ring-buffer read artefacts are deliberately NOT in this expression — - # they are not loss and are covered by HubbleRingBufferReadChurn. - expr: hubble:lost_events_increase_30m > 0 - for: 10m - labels: - severity: warning - component: hubble - annotations: - summary: "Hubble lost flow events on {{ $labels.node }} (source: {{ $labels.source }}) — flow windows are not clean" - description: | - hubble_lost_events_total{source="{{ $labels.source }}"} on {{ $labels.node }} - increased by {{ $value | printf "%.0f" }} events over the last 30 min. - That source is real loss: `perf_event_ring_buffer` means the BPF perf - ring dropped an event on the way in, `observer_events_queue` means the - metrics exporter fell behind. A flow-based detector cannot claim - "no anomalous traffic" for this window. - Check the agent's flow rate against hubble.eventBufferCapacity in - infrastructure/networking/cilium/values.yaml, and look for an - overloaded node. - - - alert: HubbleRingBufferReadChurn - # Regression guard for the artefact described in F10, not evidence of - # loss. The 5 s health probe / `hubble status` / Hubble UI status walk - # the ring backwards over a full minute; on a ring holding < 60 s of - # flows each walk increments hubble_lost_events_total - # {source="hubble_ring_buffer"} by 1. A handful of reads is normal; the - # old probe storm (12/min = 0.2/s) and an agent whose ring no longer - # holds a minute of flows are not. Rate, not increase: `increase() > 0` - # fires forever on two UI reads an hour. - expr: hubble:ring_buffer_read_rate_15m > 0.05 - for: 10m - labels: - severity: warning - component: hubble - annotations: - summary: "Hubble ring-buffer read churn on {{ $labels.node }} (source: hubble_ring_buffer) — reads, not dropped flows" - description: | - hubble_lost_events_total{source="hubble_ring_buffer"} is increasing at - {{ $value | printf "%.3f" }}/s on {{ $labels.node }} (threshold 0.05/s, - 15 min rate, sustained 10 min). This counter also counts reads that - fall outside the ring's retained window (cilium#46584), so a burst of - `hubble status` / Hubble UI / relay calls can move it without anything - being dropped. A sustained rate this high means either a status-call - storm or a ring holding less than one minute of flows — check - `hubble status` (Current/Max Flows) against the agent's flow rate and - hubble.eventBufferCapacity in infrastructure/networking/cilium/values.yaml. - Confirm whether it is real loss by checking - HubbleFlowWindowIncomplete (perf/observer sources), which stays 0 for - read churn alone. - - - alert: HubbleFlowLossMaterial - # Escalation: real loss that is large relative to the traffic, not a - # boundary artefact. 0.1 % of 30 min of flows on siriussec (~180 k - # events) is ~180 events — small enough to catch a real gap, large - # enough that a handful of stray increments do not page. Uses the - # real-loss recorder only; ring-buffer reads never make this ratio. - expr: | - ( - sum by (node) (hubble:lost_events_increase_30m) - / - (hubble:flows_processed_increase_30m > 0) - ) > 0.001 - for: 15m - labels: - severity: critical - component: hubble - annotations: - summary: "Hubble is losing a material share of flows on {{ $labels.node }}" - description: | - {{ $labels.node }} has lost more than 0.1% of the flows it processed - over the last 30 min (ratio {{ $value | humanizePercentage }}), from the - real-loss sources (`perf_event_ring_buffer` / `observer_events_queue`). - Treat every flow-based conclusion for this node as partial until - `hubble:lost_events_increase_30m` returns to 0. - - - alert: HubbleFlowSensorMissing - # No series at all is worse than loss: the detector has no input and - # the gate cannot even evaluate. `absent()` on the recording rule. - expr: absent(hubble:flows_processed_increase_30m) - for: 15m - labels: - severity: critical - component: hubble - annotations: - summary: "No Hubble flow counters are being scraped" - description: | - No `hubble_flows_processed_total` series exist for 15 min. Either the - `hubble-metrics` scrape targets are down or the Cilium DaemonSet is not - running; flow-based detection is blind. diff --git a/monitoring/controllers/home/kustomization.yaml b/monitoring/controllers/home/kustomization.yaml index b994dba..0d2b035 100644 --- a/monitoring/controllers/home/kustomization.yaml +++ b/monitoring/controllers/home/kustomization.yaml @@ -9,32 +9,9 @@ resources: - gateway-probe.yaml - garage.yaml - prune-alerts.yaml - # Flow-loss gate + material-loss alerts for the Hubble sensor (audit F10). - - hubble-loss-gate.yaml - # Rosenpass unit-state + PSK-rotation alerts for Link A (rpi <-> siriussec). - # Series come from a host textfile exporter (infrastructure/networking/rosenpass/), - # so silently missing data is itself an alert. - - rosenpass.yaml - # Analyst freshness: OsintAnalystStale + OsintIngestAliveButNoBrief, built on - # the osint-analyst-exporter timestamps (card t_22334588). - - osint-analyst.yaml # Nightly consistent sqlite snapshot of Grafana's dashboards/alerts/users. - grafana-backup.yaml - # Egress lockdown for that backup pod: DNS + the backup host only, so no - # run-time package fetch (card t_9d0428d8). - - grafana-backup-networkpolicy.yaml - 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 - # Registry pull credential for this namespace. Added because grafana-backup - # now runs an image from the in-cluster Forgejo registry instead of - # python:3.12-alpine from Docker Hub (card t_9d0428d8). - - secret-forgejo-pull.sops.yaml - configMapGenerator: - name: kube-prometheus-stack-values files: diff --git a/monitoring/controllers/home/namespace.yaml b/monitoring/controllers/home/namespace.yaml index 693b0af..d325236 100644 --- a/monitoring/controllers/home/namespace.yaml +++ b/monitoring/controllers/home/namespace.yaml @@ -2,8 +2,3 @@ apiVersion: v1 kind: Namespace metadata: name: monitoring - labels: - pod-security.kubernetes.io/warn: restricted - pod-security.kubernetes.io/warn-version: latest - pod-security.kubernetes.io/audit: restricted - pod-security.kubernetes.io/audit-version: latest diff --git a/monitoring/controllers/home/osint-analyst.yaml b/monitoring/controllers/home/osint-analyst.yaml deleted file mode 100644 index 6c144d3..0000000 --- a/monitoring/controllers/home/osint-analyst.yaml +++ /dev/null @@ -1,87 +0,0 @@ -# osint analyst freshness -> Prometheus (card t_22334588) -# -# On 2026-11-25 the analyst (deploy/osint-news-summarizer) silently stopped -# writing article_summaries and stayed dead for nine days. The scraper kept -# ingesting normally (61.5k rows in articles, newest within minutes), the pod -# stayed Running with restarts 0, and the log carried nothing but INFO batch -# lines and 404s at INFO level -- so every signal the cluster already had said -# "healthy". These two rules are built on the timestamps the exporter in -# apps/base/osint/analyst-exporter.yaml reads straight out of Postgres -# (SeriesMonitor osint-analyst-exporter, ns osint, :9187/metrics): -# -# osint_analyst_last_success_timestamp_seconds max(article_summaries.batch_timestamp) -# osint_ingest_last_article_timestamp_seconds max(articles.timestamp) -# osint_analyst_exporter_up 1 when the last DB read worked -# -# OsintAnalystStale is the general "no brief in over an hour" gate; the -# summarizer loops every 15 min, so an hour of silence cannot be a slow batch. -# OsintIngestAliveButNoBrief is the sharper one: a fresh article row plus a -# summary table frozen for two hours names the exact failure -- ingest fine, -# analyst dark -- without waiting for the read path or the API to be down. -# -# The absent() arm on OsintAnalystStale is deliberate: if the exporter, its -# ServiceMonitor or its scrape disappears, the series vanishes and "no data" -# would otherwise read as "no problem", which is the same invisible-failure -# shape this card exists to kill. Routes through the default Alertmanager -# receiver (Telegram @Siriusdevops_alert_bot). -apiVersion: monitoring.coreos.com/v1 -kind: PrometheusRule -metadata: - name: osint-analyst - namespace: monitoring - labels: - release: kube-prometheus-stack -spec: - groups: - - name: osint-analyst - rules: - - alert: OsintAnalystStale - expr: | - ( - time() - osint_analyst_last_success_timestamp_seconds > 3600 - ) - or - absent(osint_analyst_last_success_timestamp_seconds) - for: 30m - labels: - severity: warning - annotations: - summary: >- - osint analyst has written no brief for over an hour - description: >- - The newest article_summaries.batch_timestamp is more than an hour - old (the summarizer loops every 15 minutes), or the freshness - series is missing entirely. The container can still be Running - with restarts 0: a wedged analyst looks exactly like an idle one. - Check `kubectl -n osint logs deploy/osint-news-summarizer --tail=50` - for the interval rc, confirm the exporter target is UP in - Prometheus (job osint-analyst-exporter), and test the analyst - query directly: - `kubectl -n osint exec deploy/osint-db -- psql -U osint -d osint_data -c "select max(batch_timestamp), count(*) from article_summaries"`. - A silently dead model/API key is the usual cause. - - alert: OsintIngestAliveButNoBrief - expr: | - ( - time() - osint_analyst_last_success_timestamp_seconds > 7200 - ) - and - ( - time() - osint_ingest_last_article_timestamp_seconds < 7200 - ) - for: 10m - labels: - severity: warning - annotations: - summary: >- - osint scraper is ingesting but the analyst has written no brief for 2h - description: >- - `articles` has a row younger than two hours while - `article_summaries` has nothing newer than two hours. Ingest fine - + analyst dark is the shape of the 2026-11-25..12-04 outage, where - the pipeline looked healthy for nine days because only the ingest - side was moving. Confirm the scraper is genuinely alive - (`kubectl -n osint logs deploy/osint-news-scraper --tail=20`) and - then debug the analyst side: summarizer logs, NEWS_SUMMARIZE_* - env, the resolved SUMMARY_MODEL and the Nous API key/inference - endpoint (a dead model or a 404 on every map call writes zero - rows while the loop keeps logging rc=0). diff --git a/monitoring/controllers/home/prune-alerts.yaml b/monitoring/controllers/home/prune-alerts.yaml index 2d68f0a..9d683d8 100644 --- a/monitoring/controllers/home/prune-alerts.yaml +++ b/monitoring/controllers/home/prune-alerts.yaml @@ -1,6 +1,6 @@ # Alerts for the disk-reclamation job and the daemons it prunes. # -# Context: `ci-runners/forgejo-runner-prune` reclaims build cache nightly. Its +# Context: `forgejo/forgejo-runner-prune` reclaims build cache nightly. Its # own success/failure is invisible unless kube-state-metrics is watched, and # the failure mode it exists to prevent (a full disk on siriussec → DiskPressure # → Forgejo + Postgres evicted, public 503) shows up in node_exporter first. @@ -53,10 +53,10 @@ spec: # never having succeeded at all. expr: | ( - time() - kube_cronjob_status_last_successful_time{namespace="ci-runners", cronjob="forgejo-runner-prune"} > 26 * 3600 + time() - kube_cronjob_status_last_successful_time{namespace="forgejo", cronjob="forgejo-runner-prune"} > 26 * 3600 ) or - absent(kube_cronjob_status_last_successful_time{namespace="ci-runners", cronjob="forgejo-runner-prune"}) + absent(kube_cronjob_status_last_successful_time{namespace="forgejo", cronjob="forgejo-runner-prune"}) for: 10m labels: severity: warning @@ -66,10 +66,10 @@ spec: description: >- Build cache, exited containers and unused images are not being reclaimed on the Pi host daemon or on the dind daemons. Check - `kubectl -n ci-runners get jobs -l role=prune` and the pod logs of + `kubectl -n forgejo get jobs -l role=prune` and the pod logs of the newest Job; the job skips (exit 0) when a build is live, but a *stale* success means it has not run at all. Force one run: - kubectl -n ci-runners create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s) + kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s) - alert: ForgejoPruneJobFailed # kube_job_failed was removed from kube-state-metrics; the supported # series is kube_job_status_failed (0 for a successful job, >0 when a @@ -77,7 +77,7 @@ spec: # transient failure ages out on its own after the history limit. expr: | max by (job_name) ( - kube_job_status_failed{namespace="ci-runners", job_name=~"forgejo-runner-prune-.*"} + kube_job_status_failed{namespace="forgejo", job_name=~"forgejo-runner-prune-.*"} ) > 0 for: 5m labels: @@ -86,7 +86,7 @@ spec: summary: forgejo-runner-prune Job {{ $labels.job_name }} has a failed pod description: >- A prune run failed (or its dind discovery/exec container did). - Read `kubectl -n ci-runners logs job/{{ $labels.job_name }} -c + Read `kubectl -n forgejo logs job/{{ $labels.job_name }} -c dind-daemons` — a failure there means a running dind daemon was not reachable over the exec API, so that daemon is growing unpruned. One retry is allowed by backoffLimit; persistent @@ -121,7 +121,7 @@ spec: ) and on (nodename) label_replace( - max by (node) (kube_pod_info{namespace="ci-runners", pod=~"forgejo-runner-.*"}), + max by (node) (kube_pod_info{namespace="forgejo", pod=~"forgejo-runner-.*"}), "nodename", "$1", "node", "(.+)" ) ) > 0.80 @@ -141,9 +141,9 @@ spec: Prometheus. Per-PVC bytes cannot be measured here — kubelet 1.34+ no longer exports kubelet_volume_stats_* and /metrics/volumes is 404 — so this node-level rule is the guard. Inspect the offenders: - `kubectl -n ci-runners exec -c dind -- docker system df -v` + `kubectl -n forgejo exec -c dind -- docker system df -v` and `du -sh /opt/local-path-provisioner/pvc-*` on the node, then let - the nightly prune reclaim (or force it: kubectl -n ci-runners create job + the nightly prune reclaim (or force it: kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)). - alert: RunnerDindDiskCritical expr: | @@ -159,7 +159,7 @@ spec: ) and on (nodename) label_replace( - max by (node) (kube_pod_info{namespace="ci-runners", pod=~"forgejo-runner-.*"}), + max by (node) (kube_pod_info{namespace="forgejo", pod=~"forgejo-runner-.*"}), "nodename", "$1", "node", "(.+)" ) ) > 0.90 @@ -174,7 +174,7 @@ spec: DiskPressure is imminent on a node running CI: kubelet starts evicting (Forgejo + pg-1 went Pending on siriussec this way) and dind builds fail with "no space left on device". Act now: scale the - runner to 0 (`kubectl -n ci-runners scale deploy/ --replicas=0`), + runner to 0 (`kubectl -n forgejo scale deploy/ --replicas=0`), force the prune, and only then clear the dind data-root by hand (`/opt/local-path-provisioner/pvc-*_forgejo_forgejo-runner-*/` on the node) — never wipe it while the runner pod is up. The 20Gi PVC @@ -212,10 +212,10 @@ spec: 200Gi and forgejo-runner-deploy-arm64-dind 40Gi) share rpi's only filesystem with the kubelet. Nothing enforces those claim sizes. Attribute the growth with - `kubectl -n ci-runners exec -c dind -- docker system df -v` + `kubectl -n forgejo exec -c dind -- docker system df -v` (the nightly prune job prints this for every daemon and never deletes named volumes), then reclaim with - `kubectl -n ci-runners create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)`. + `kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)`. See docs/arm64-runner-dind.md §4.4. - name: disk-capacity rules: @@ -238,7 +238,7 @@ spec: annotations: summary: "{{ $labels.nodename }} root filesystem is {{ $value | humanizePercentage }} full" description: >- - Reclaim with `kubectl -n ci-runners create job + Reclaim with `kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)` (it prunes the Pi host daemon and every dind daemon), and read that job's `docker system df -v` output for the volumes that are diff --git a/monitoring/controllers/home/rosenpass.yaml b/monitoring/controllers/home/rosenpass.yaml deleted file mode 100644 index e05b185..0000000 --- a/monitoring/controllers/home/rosenpass.yaml +++ /dev/null @@ -1,139 +0,0 @@ -# Rosenpass (post-quantum PSK rotation) -> Prometheus -# -# Link A (rpi wg0 10.10.0.1 <-> siriussec wg0 10.10.0.2) runs rosenpass 0.2.3 -# as a host systemd unit on both ends, rotating that WireGuard peer's -# preshared key roughly every two minutes. Nothing about the *tunnel* depends -# on it working: WireGuard keeps using the last PSK it received, so a dead or -# stalled exchange leaves the link up and silently non-post-quantum. These two -# alerts are the only thing that notices. -# -# Why a host script and not a collector: the -# kube-prometheus-stack-prometheus-node-exporter DaemonSet is distroless and -# has no --collector.textfile.directory (only /host/proc, /host/sys and -# /host/root are mounted), while --collector.systemd needs dbus plumbing it -# does not have. So /usr/local/sbin/rosenpass-metrics.sh on rpi and siriussec -# (committed under infrastructure/networking/rosenpass/, driven by -# rosenpass-metrics.timer every 60 s) writes the textfile, and the -# prometheus-node-exporter block in values.yaml turns the collector on. -# -# Series, emitted per host, never containing key material (the PSK set is only -# SHA-256 hashed, in a root-only state file): -# rosenpass_unit_active{node="rpi|siriussec"} 0|1 -# rosenpass_psk_rotation_age_seconds{node=...,interface="wg0|wg-remote"} -# rosenpass_psk_rotation_last_change_timestamp_seconds{node=...,interface="wg0|wg-remote"} -# rosenpass_upnp_mapping_present{node="rpi"} 0|1 -# rosenpass_upnp_last_check_timestamp_seconds{node="rpi"} -# -# Both rotation rules carry an absent() arm deliberately: a metric that simply -# stops arriving (timer disabled, script broken, node-exporter down, scrape lost) -# must alert, because "nothing happened" is exactly what a healthy rotation -# looks like from Prometheus' side. The absent arms name the hosts and -# interfaces that actually run the timer — rpi wg0 + wg-remote (Link A + Link B), -# siriussec wg0 (Link A only; it has no wg-remote) — so linode, which has -# node-exporter but no rosenpass, and an interface absent from a host do not -# page. -# -# Link B's inbound path is a permanent UPnP mapping on the Pi's router (which -# has no accessible admin panel). rosenpass-upnp.sh re-asserts it every 15 min -# and stamps 1/0 into /run, which rosenpass-metrics.sh turns into the series -# below. Without that mapping the exchange cannot be dialled, the link keeps its -# last PSK and silently stops being post-quantum. -apiVersion: monitoring.coreos.com/v1 -kind: PrometheusRule -metadata: - name: rosenpass - namespace: monitoring - labels: - release: kube-prometheus-stack -spec: - groups: - - name: rosenpass - rules: - - alert: RosenpassDown - expr: | - ( - max by (node) (rosenpass_unit_active) == 0 - ) - or - ( - absent(rosenpass_unit_active{node="rpi"}) - or - absent(rosenpass_unit_active{node="siriussec"}) - ) - for: 5m - labels: - severity: warning - annotations: - summary: "Rosenpass is not active on {{ $labels.node }}" - description: >- - The unit on {{ $labels.node }} is not reporting active, or the - series is missing entirely (timer, script or scrape gone). - WireGuard on Link A keeps working on the last preshared key, so - traffic gives no hint — the tunnel has silently stopped being - post-quantum until this is fixed. On that host check - `systemctl status rosenpass` and - `systemctl list-timers rosenpass-metrics.timer`, then - `cat /var/lib/node-exporter/textfile/rosenpass.prom`. Do not - restart rosenpass on only one end: a one-sided restart leaves the - pair disagreeing until the next rekey. - - alert: RosenpassPskRotationStalled - expr: | - ( - max by (node, interface) (rosenpass_psk_rotation_age_seconds) > 900 - ) - or - ( - absent(rosenpass_psk_rotation_age_seconds{node="rpi", interface="wg0"}) - or - absent(rosenpass_psk_rotation_age_seconds{node="rpi", interface="wg-remote"}) - or - absent(rosenpass_psk_rotation_age_seconds{node="siriussec", interface="wg0"}) - ) - for: 10m - labels: - severity: warning - annotations: - summary: >- - No rosenpass PSK rotation on {{ $labels.node }} {{ $labels.interface }} - for over 15 minutes - description: >- - Rotation runs about every two minutes, so a preshared-key set that - has not changed in 15 minutes means the exchange has stalled - (peer unreachable, unit wedged) or the metric has gone missing. - The link still passes traffic on the last key, which is why this - is otherwise invisible. Check `systemctl status rosenpass` and - `journalctl -u rosenpass -n 30` on both rpi and siriussec, and - confirm the Pi still admits 9999/udp from 192.168.1.179 - (`sudo ufw status | grep 9999`). - - alert: RosenpassUpnpMappingLost - expr: | - ( - max by (node) (rosenpass_upnp_mapping_present) == 0 - ) - or - ( - time() - max by (node) (rosenpass_upnp_last_check_timestamp_seconds) > 1800 - ) - or - absent(rosenpass_upnp_mapping_present{node="rpi"}) - for: 10m - labels: - severity: warning - annotations: - summary: >- - Link B UPnP mapping missing or unverified on {{ $labels.node }} - description: >- - Link B (rpi wg-remote 10.20.0.2 <-> linode wg0 10.20.0.1) can only - be dialled inbound through a permanent UPnP mapping - UDP 9999 -> 192.168.1.125:9999 on the Pi's router, and - rosenpass-upnp.timer re-asserts it every 15 minutes. Either the - last run reported the mapping missing (value 0), no run has - updated the state for over 30 minutes (timer or router IGD gone), - or the series is absent entirely (state file cleared by a reboot, - metrics timer dead). The link keeps passing traffic on its last - preshared key, so this is invisible from the tunnel. On rpi check - `systemctl status rosenpass-upnp.timer`, - `journalctl -t rosenpass-upnp -n 20` and `upnpc -l | grep 9999`; - re-assert by hand with - `sudo systemctl start rosenpass-upnp.service`. If the router - rebooted, the mapping comes back on the next timer run. diff --git a/monitoring/controllers/home/secret-alertmanager-telegram.sops.yaml b/monitoring/controllers/home/secret-alertmanager-telegram.sops.yaml deleted file mode 100644 index ea9b1ac..0000000 --- a/monitoring/controllers/home/secret-alertmanager-telegram.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - bot_token: ENC[AES256_GCM,data:krgPsL9rFCr1eiUgFzv+G4aN+9ub9RqMc3RBVJ/E6/RhUEv7FDiPsL3SVxYuwwFFo+emmEewI/uVvgqRqZJWOg==,iv:eJwG7Hwl1cPGN+6PqZ/tiBVh2yyMKQ2tgV5Kdhcvcd8=,tag:mU/F79zBCR4BcDKcNUXKAw==,type:str] -kind: Secret -metadata: - name: alertmanager-telegram - namespace: monitoring -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBWVXZseUg3WTdFNHg1WnI2 - RDkwZmhkV09MaXVaNEEzNG9wVmJyVUFPWFhRCmJXMGJBY0puWTI1ZlI0Y2wwWDV3 - aGJMbGNpZzBXS2ZSekt5QnNBUUpkSEEKLS0tIGY1Sy94clNhMDBqOTFPRnVJbng3 - WWZodVhKMWNkQ3pYNStnejVrTTVnaU0KHzb+ZiC5b64mWMoX7qSZ/WcSVINn8dAL - m1/+7RHmRd6OOu3k5ZVVfmiik+hxc8B99nlHI0owdkvO8OeQ4FkPsQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:29:50Z" - mac: ENC[AES256_GCM,data:C+fu2rY3tT2m33LP+lY3sH2ye6aDCczk7CSTxr3+bsjrxlNgyJ3EEKHwVuM4ySdH7rxP6hW6GksHUEAVzoRRs73tKdaf/q7IGsOM+sIMfohhOW/SICUXIF/jyQpH64rchKT0XlqYuZcwu42FUc63W/3uZHKaIy/6rfd/wYPayy8=,iv:6sEQInnCbA1QKpiZOOFc/GgkGR0lvXkaqA0k5tBaQFI=,tag:+x7v4ImO/sTZQe+O9nxSDQ==,type:str] - version: 3.13.3 diff --git a/monitoring/controllers/home/secret-cluster-backup-ssh.sops.yaml b/monitoring/controllers/home/secret-cluster-backup-ssh.sops.yaml deleted file mode 100644 index ff02496..0000000 --- a/monitoring/controllers/home/secret-cluster-backup-ssh.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - id_ed25519: ENC[AES256_GCM,data:CXpIHiPVXDTycl1lvrs703IBQpQ3mdHB4GN/JfCCHte2kOJ/9YHpML8RpGjMY18hrAWdKrau72a7XC6DhbQwJZtxk8/NndQSk+V3J7R3eWFm/i/RGszGSZ6A0ySzg7h/xvUp6ZqAqOXznU7YOPN+BgMIHm74egtq2bto4CNBQ14OP/1J4XSAfGST7NPDRKIGzvgHFEpLq+buVY4hf38KAV8/5evAhy2utyLmnYl+mnYbpXR3cA4ddiNfn6n11XdlkUdWad4i2YLRRXg97DT/h4U6nBvpJh2l8yNEPogT7r/81qblsz2U1X0AF9DxL9FtmIs4cJrUqzHTH2kfeoJXzFp3xKfBW6FJ3f8CBJXJ56ZTVZA6H6PhFFrBJeSF6vqYowfLleDPu7t5B4YvJin7DdkEaTfM/LFPHrScBXzuLU2qGmyte9EWWr3XJuOcXznkW1xgEBV131rjLYWStAd2FBoznfVVdCS5CsEMiuoQR8qY0vdlwLiXuVpI3I8cQczKTahdU9eBDBmHQwJsX5wSU9FpsjhE52Kj06zRFQCL15EeNjLmBvkVC9g5pQm+StOX90UJrsmsf1GbT4MF6wSCyxNcsrOcoIN1FbBBgYc2WGtndGL3zXTOJV5LDDC8ahCkp4gWnCY+Rk91tUiGipljDpdDOtK/agMpykh8ODVwxNHg5yeQSYrEhr62hx74C4UwvFJyUwdmeazM/cxWEo6zcceYElIeuEDz5JiPLgHOwGg=,iv:dv72rAoHKb0UThiOh8FQZY+vH6V30NoFNmOQWB2+7b0=,tag:Nx7bJQyc2KeD7HCpypOneQ==,type:str] - known_hosts: ENC[AES256_GCM,data:OtOu2+COTM408URZUfgKhfHe38wjSatSBwF9kDZjjog+euG1PKU75aFzEEGYSSnviLoKAe/mTY4D83yijFdEJFYzSsZh88ay8WG4CbQBSJ7eN/BiQzU+stHOVBgZDonpJGiBVaYfKesTmsSm+46nQOuNA64NJUQpYpCDYQ==,iv:bZKONWjfDSKo7OSA2NxO9PYGASzp7uQCH2LL/Wowogo=,tag:o9+V5+uqjHHL1Tpb+5Gqww==,type:str] -kind: Secret -metadata: - name: cluster-backup-ssh - namespace: monitoring -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBUWWF6SVZHb1hjajJzQ3JU - bVlvVHhXRlAxR2tjL01RUmtpaGhQeVZTWVRZClV1NmNJZlcrejFVMU5QTUt5QW9y - MTlUeHdYWXJvWGFHVzlVQTBobDAwWGcKLS0tIDJ1OXAvcDFwQlJ3WE90UWNadGNY - ekFNekJ4QU4rY1pqTC84ZGM3N1JIUFUKAy8PNqANmqmX8akXP6vBod4kk3ga9QN1 - o/2G3hmT47KPwdwsQ732aNe6ULgKtMcyu1xr2+TbyyTpvyEkSTAlOQ== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:29:50Z" - mac: ENC[AES256_GCM,data:3RAT6a3Std/Ik1qxG1Si6QuV4nX4P7NU/L0tOGHAJvirIpKrGTioQM9AjHXt9K/CJ5wTcds/KClLRXVMPMnh3k+ogd5mHni/vOb6zXIQgLlp4jQnw2eiVxhQaYrfX57lEwCCNv8YmJ5fBjio6DZvmSm7vx8OG0I4l/RhanulAOw=,iv:sGChD/uz7ftbuEF9PnzMCjR8GfaafcDkSs2JAyOO8WE=,tag:FcVeot08lg3DqzkV4xphdg==,type:str] - version: 3.13.3 diff --git a/monitoring/controllers/home/secret-forgejo-pull.sops.yaml b/monitoring/controllers/home/secret-forgejo-pull.sops.yaml deleted file mode 100644 index f70f79e..0000000 --- a/monitoring/controllers/home/secret-forgejo-pull.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - .dockerconfigjson: ENC[AES256_GCM,data:c7NwYAKS00RAzkEW3z1IA2XP24cdIJgQAaBjg7+WcsxLMEs2h42cg/fdtW6UYrrsQtq7X/T4wgfpzUjHq8aMI2lyiVhJa9vxHknpK32i2mP63YQ7o2axI2p5eGPQpB+uuLPr3e1A6I939co6LQCBrY1ueK9+9atCcSEflv/wJyXwrwvlV5EL20PTLTM/y8gGN9cXXfgk6aYV7F5mowQCcUIUDvCbj7cHIonumMfCANQgGjQHrACf0+2ko853nBwLQK1AtIP+U/NS1wDSbFmxqyO6OstF10Sq5t+8dY8baIt73RWN0BqB/7i08TsMpnNUXH4XJcP6WhP0FM+X3M5goJr80DNy2uG3fxTHwRSAeWGzIo2GuuK9qlMtIjjnU97K,iv:xPgSzx6+EEJRnTGYG+QZWJ7G3MUf6Ajd+CXpl8+XIxs=,tag:alsSmEFhXW46SeoVzdqyFA==,type:str] -kind: Secret -metadata: - name: forgejo-pull - namespace: monitoring -type: kubernetes.io/dockerconfigjson -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA1eU8ydkR5SmF2UG9ZQWNY - TWdKTFJkdjFlWWtBSW4wdmFDWXA0akNSSFI4CmVpL3dMKy91b1JTUTRyV1QyRXlI - YnlQZVJhL0hNRENNdlM1cDZKZmRUN0kKLS0tIEZOVHBLOUsvbFp6VjJXbW1tVmhK - Y1M4a2VyL0Z2MDhLeGJZUCtHRnQ2cmMKU9Q4m7ZuZDYbNQgsvOXEAKBE1hW1pa7m - 7/pmRAP43OjXfsjWUbnPmORcHSrVDtRrBxQZ2d1svVdwd6vMUPPjqw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-12-04T05:16:30Z" - mac: ENC[AES256_GCM,data:yYt1AWNi+Ts4c/p3OwrknVVPMPf9PEeYvgz/LckFqsJweSq36b6gzinMcLxJGnenmCokftUA4RvMMF2f0Lcpo3+RqmpPGnCzpAVQ0ypuS2+n+bET7tF/tu9icuwZaTu0sNW+/j8VK5T5nlrrw+aLf3O9yIuP7XVLXyjodJqbH7c=,iv:jSMmP96DHN6qLmpHoisVQu1DYlMVehxdXNWkzh5GZwk=,tag:b98z963bBjpM5gGZnKHqBg==,type:str] - version: 3.13.3 diff --git a/monitoring/controllers/home/secret-grafana-admin.sops.yaml b/monitoring/controllers/home/secret-grafana-admin.sops.yaml deleted file mode 100644 index a970419..0000000 --- a/monitoring/controllers/home/secret-grafana-admin.sops.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -data: - admin-password: ENC[AES256_GCM,data:1irLPlJfmkjAO4iJoeKP/NLf2KAmWL4bl3z1ZCSL3JRZyzc9fcef8tr3DIM2pX+CP2JzszgCdrA=,iv:BB6rXJ+PQSeioEUzvzldqu7ezyImTPhowy5lps9ug+Y=,tag:8Ix+zc/nmF9MizKtfEY5hQ==,type:str] - admin-user: ENC[AES256_GCM,data:JL8j1pOmUw0=,iv:vnIujGcvcotq1OE6LkZN3gu7az0osMUAVtCuLCbBFnQ=,tag:AWXPw7+PuEvc1LdEEmLULg==,type:str] -kind: Secret -metadata: - name: grafana-admin - namespace: monitoring -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBHZ1MyS0JnVWUyeVl5WlE1 - WlJwNG5wRTlKVWhVT25vc0t4VUJTc2ZEQnlVCjU0RTVURHc0T1dtcXFOaFpQVWpV - QnU2dWFTaTRrR1ovMzJxK3ZqaDRoL3MKLS0tIFFhVjFMM2ZieXlHc2x4ZERoRXBT - TkFFSllJSDRaWUJ0K3o0cVBIN3ltMzAKhP5ZPtpGFUr2DF/WOBUWeEW0G/3BAM15 - s+AT1mxwvs+NEclDOcKQH35zuxHHHI7sKrGqkEgz3anK2lxNUYmtfw== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:29:50Z" - mac: ENC[AES256_GCM,data:Q9hrSbIztIrgWxWFc2WkJFwJzEi00TZkbgjzFiCOBvyP15MsW1ZAIvg18U0EKI4EOnLPMVWIbbaS2WLjO/O2Xc1QeWgrWedZ867K6k5SJf9YmVgh41D7vfMCMGFQM6kHyK+GU08U2HSnh/nk33EaFvFCEQcqGrfA5RFXw0kD6j8=,iv:cA1HzpT72oUGhE7ndGtah0lsjpb3Bo43yYXfbi27QqE=,tag:oKKP6gIuZOVWcETl8aqc4g==,type:str] - version: 3.13.3 diff --git a/monitoring/controllers/home/secret-grafana-secret-key.sops.yaml b/monitoring/controllers/home/secret-grafana-secret-key.sops.yaml deleted file mode 100644 index 0788f2f..0000000 --- a/monitoring/controllers/home/secret-grafana-secret-key.sops.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: v1 -data: - secret_key: ENC[AES256_GCM,data:/l09rZDgsZ8l/oGlUbeQDRnDx9RZWI0Nkc0+jFu4B3aUQmceiQgfjXjFvU/remMGZ0Y4bsFiZyN03jhEttaUTx6ZpaUIQAcHhbA62EYVvqYUxMlV,iv:3VsWm1uozD5dVrLdvUUJGUlfz0WH3rMmBa9PrsQZRns=,tag:34Ts1/Vkmg6mM2V2TOZ7Rg==,type:str] -kind: Secret -metadata: - name: grafana-secret-key - namespace: monitoring -type: Opaque -sops: - age: - - enc: | - -----BEGIN AGE ENCRYPTED FILE----- - YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSB5bEhRSURIKzRsaVNFampy - VG05YU9DaGZYRlVBTzFRYWtmbUR3bVlmblRrCmFsc3cwanhkTWR2NmQxTW1FbnZ2 - QzFjeHBabXYxTzVqWkZHcVh4cXpwUGMKLS0tIHUxYTN4OGM5cDBQODdaQlRXQ2pw - QjhYVVZuUVpUd2hBZnI4b3J5TitXL2sK6yKlt1GedoQF6aG7MRlBFIEJP9IdJcyK - QI2LHwqIeMo5tIl7kFhRLhCB+/Esh+rmV/GLS1dBpUvo94sb1lsVmg== - -----END AGE ENCRYPTED FILE----- - recipient: age12zdn7x72zrgu9cdv8wdj7xfx42nz09nrwpc2g09cwx5fwdm0ry6qp5h4jp - encrypted_regex: ^(data|stringData)$ - lastmodified: "2026-11-27T05:29:50Z" - mac: ENC[AES256_GCM,data:JXq1AQruG30s5MEFv8iAGW325rmje7HIe2kxJhWqH/WOSMNDwDqcoBSkFZJrEDhZ6ImBWDun+8zgfYbbdpLH4G9+DBtkAOq+SwreX3IMnFSueQOixJQa7mONKfSFFZ8LRehf/wr9qu+bdeGet9BodI84WKx4EUMaVCLkEqXERZ8=,iv:AGlilDpIWzicA6DM7YRxRv4Em6xLrD2mvefAqTfO1HA=,tag:BAffhK1RGmdlqsJPs6g7Hg==,type:str] - version: 3.13.3 diff --git a/monitoring/controllers/home/values.yaml b/monitoring/controllers/home/values.yaml index 5a03778..1dae79c 100644 --- a/monitoring/controllers/home/values.yaml +++ b/monitoring/controllers/home/values.yaml @@ -5,82 +5,9 @@ # Prometheus is capped twice (time AND bytes) so a metrics burst can never # repeat the ephemeral-storage / DiskPressure incident (see docs/cluster-overview.md). -# --- Alertmanager: ON. It is the cluster's only alert sink; without it the -# 33 PrometheusRules evaluate into nothing (finding F5). The receiver is the -# dedicated alert bot @Siriusdevops_alert_bot (chat 7528130947) — the same bot -# the public contact forms use and deliberately NOT the Hermes gateway bot the -# agent/netsec waker runs on, so a cluster alert can never loop back into the -# agent. The bot token is NOT in git: it lives in Secret -# monitoring/alertmanager-telegram (created out of band) and the operator -# mounts it at /etc/alertmanager/secrets/alertmanager-telegram/bot_token. -# -# Routing: default -> telegram. Watchdog (fires forever by design, the -# dead-man's switch) and the InfoInhibitor meta-alert go to the 'null' -# blackhole receiver so neither ever pages; info-severity noise (e.g. -# CPUThrottlingHigh) stays in Prometheus/Grafana without paging. That route is -# the durable silence — unlike an Alertmanager API silence it lives in git and -# survives a pod reschedule. The inhibit_rules are the chart defaults (critical -# inhibits warning/info, warning inhibits info) and are kept as-is. +# --- Alertmanager: off. No receivers in this card; alerts fire to nowhere on purpose. alertmanager: - enabled: true - apiVersion: v2 - alertmanagerSpec: - nodeSelector: - kubernetes.io/hostname: siriussec - resources: - requests: - cpu: 20m - memory: 32Mi - limits: - cpu: 200m - memory: 128Mi - # Mounts Secret monitoring/alertmanager-telegram into the pod at - # /etc/alertmanager/secrets/alertmanager-telegram/ (bot_token key). - secrets: - - alertmanager-telegram - config: - global: - resolve_timeout: 5m - route: - group_by: ['namespace'] - group_wait: 30s - group_interval: 5m - repeat_interval: 12h - receiver: 'telegram' - routes: - - matchers: ['alertname = "Watchdog"'] - receiver: 'null' - - matchers: ['alertname = "InfoInhibitor"'] - receiver: 'null' - - matchers: ['severity = "info"'] - receiver: 'null' - inhibit_rules: - - source_matchers: ['severity = "critical"'] - target_matchers: ['severity =~ "warning|info"'] - equal: ['namespace', 'alertname'] - - source_matchers: ['severity = "warning"'] - target_matchers: ['severity = "info"'] - equal: ['namespace', 'alertname'] - - source_matchers: ['alertname = "InfoInhibitor"'] - target_matchers: ['severity = "info"'] - equal: ['namespace'] - - target_matchers: ['alertname = "InfoInhibitor"'] - receivers: - - name: 'null' - - name: 'telegram' - telegram_configs: - - bot_token_file: /etc/alertmanager/secrets/alertmanager-telegram/bot_token - chat_id: 7528130947 - send_resolved: true - parse_mode: HTML - message: |- - {{ range .Alerts -}} - {{ if eq .Status "firing" }}FIRING{{ else }}RESOLVED{{ end }} [{{ .Labels.severity }}] {{ .Labels.alertname }} - {{ .Annotations.summary }} - {{ .Annotations.description }} - {{ end }} - templates: - - '/etc/alertmanager/config/*.tmpl' + enabled: false defaultRules: create: true @@ -255,33 +182,6 @@ prometheus-node-exporter: # to linode. node-exporter is a read-only host-metrics DaemonSet (hostPath # /proc + /sys, host network); it adds ~700 series per node, well inside the # 8GB retentionSize cap, and rpi's PreferNoSchedule taint does not exclude it. - # - # Textfile collector: rosenpass-metrics.sh on rpi/siriussec writes - # /var/lib/node-exporter/textfile/rosenpass.prom and the DaemonSet serves it - # from /metrics (alerts: monitoring/controllers/home/rosenpass.yaml, host - # units: infrastructure/networking/rosenpass/). The image is distroless with - # no collector enabled, so the flag below is what turns it on. - # - # extraArgs REPLACES the subchart default list — Helm replaces lists, it does - # not merge them. The two filesystem exclusions are copied verbatim from - # prometheus-node-exporter 4.60.1 (the subchart pinned by kube-prometheus-stack - # 92.14.0); dropping them would add every container mountpoint to - # node_filesystem_* and change the disk alerts. - extraArgs: - - --collector.textfile.directory=/host/textfile - - --collector.filesystem.mount-points-exclude=^/(dev|proc|sys|run/containerd/.+|var/lib/docker/.+|var/lib/kubelet/.+)($|/) - - --collector.filesystem.fs-types-exclude=^(autofs|binfmt_misc|bpf|cgroup2?|configfs|debugfs|devpts|devtmpfs|fusectl|hugetlbfs|iso9660|mqueue|nsfs|overlay|proc|procfs|pstore|rpc_pipefs|securityfs|selinuxfs|squashfs|sysfs|tracefs|erofs)$ - extraVolumes: - - name: textfile - hostPath: - path: /var/lib/node-exporter/textfile - # DirectoryOrCreate: nodes with no rosenpass timer (linode) still get a - # mountable empty directory instead of a CreateContainerConfigError. - type: DirectoryOrCreate - extraVolumeMounts: - - name: textfile - mountPath: /host/textfile - readOnly: true resources: requests: cpu: 20m diff --git a/scripts/check-sops-decryption.py b/scripts/check-sops-decryption.py deleted file mode 100755 index cf32e70..0000000 --- a/scripts/check-sops-decryption.py +++ /dev/null @@ -1,238 +0,0 @@ -#!/usr/bin/env python3 -"""Fail if a SOPS-encrypted manifest sits in a tree its Flux Kustomization cannot decrypt. - -Why this exists ---------------- -`spec.decryption` is opt-in per Flux Kustomization. A `secret-*.sops.yaml` dropped under a -tree that lacks the block is still valid YAML, so kustomize-controller applies the Secret with -literal `ENC[AES256_GCM,...]` values: the object exists, is wrong, and the first symptom is an -application failing to authenticate — possibly days later, looking nothing like a git problem. -See `docs/secrets-sops.md`. - -What it checks (static: no cluster, no age key, no network) ----------------------------------------------------------- -1. Every Flux `Kustomization` under the live sync path (discovered from - `clusters/*/flux-system/gotk-sync.yaml`) carries `decryption.provider: sops` and a - `secretRef.name`. -2. Every `*.sops.yaml` / `*.sops.yml` file in the repo lives inside the kustomize resource - graph of at least one such Kustomization, and *all* of its owning Kustomizations decrypt. -3. Every such file actually contains SOPS ciphertext (`sops:` metadata + `ENC[AES256_GCM`). - -Usage ------ - scripts/check-sops-decryption.py [-v] # or: make check-sops - -Exit codes: 0 clean, 1 violations found, 2 the check could not run (never treat as a pass). -""" - -from __future__ import annotations - -import os -import sys -from pathlib import Path - -try: - import yaml -except ImportError: # pragma: no cover - environment problem, not a repo problem - sys.stderr.write( - "check-sops-decryption: PyYAML is required (pacman -S python-yaml / pip install pyyaml)\n" - ) - raise SystemExit(2) - -REPO = Path(__file__).resolve().parents[1] -SKIP_DIRS = {".git", ".worktrees", "node_modules"} -SOPS_SECRET = "sops-age" -KUSTOMIZATION_FILES = ("kustomization.yaml", "kustomization.yml", "Kustomization") - -violations: list[str] = [] -notes: list[str] = [] - - -def fail(msg: str) -> None: - violations.append(msg) - - -def load_docs(path: Path): - try: - with path.open("r", encoding="utf-8") as fh: - return [d for d in yaml.safe_load_all(fh) if isinstance(d, dict)] - except (OSError, yaml.YAMLError) as exc: - fail(f"{path.relative_to(REPO)}: cannot parse YAML: {exc}") - return [] - - -def is_flux_kustomization(doc) -> bool: - return ( - doc.get("kind") == "Kustomization" - and str(doc.get("apiVersion", "")).startswith("kustomize.toolkit.fluxcd.io/") - ) - - -def live_manifest_dirs() -> list[Path]: - """Directories Flux actually reconciles, read from the bootstrapped sync manifests.""" - dirs: list[Path] = [] - for gotk in sorted(REPO.glob("clusters/*/flux-system/gotk-sync.yaml")): - for doc in load_docs(gotk): - if is_flux_kustomization(doc) and doc.get("metadata", {}).get("name") == "flux-system": - rel = (doc.get("spec") or {}).get("path", "./") - dirs.append((REPO / rel).resolve()) - return [d for d in dirs if d.is_dir()] - - -def kustomize_build_dirs(start: Path) -> set[Path]: - """Every directory reachable from `start` through kustomize `resources`/`bases`/`components`.""" - seen: dict[Path, None] = {} - stack = [start] - while stack: - current = stack.pop() - if current in seen or not current.is_dir() or current.name in SKIP_DIRS: - continue - seen[current] = None - kfile = next((current / n for n in KUSTOMIZATION_FILES if (current / n).is_file()), None) - if kfile is None: - continue - for doc in load_docs(kfile): - entries = [] - for key in ("resources", "bases", "components"): - value = doc.get(key) or [] - if isinstance(value, list): - entries.extend(v for v in value if isinstance(v, str)) - for entry in entries: - target = Path(os.path.normpath(current / entry)) - if target.is_dir(): - stack.append(target) - return set(seen) - - -class FluxKustomization: - def __init__(self, source: Path, doc) -> None: - self.source = source - self.name = doc.get("metadata", {}).get("name") or source.stem - spec = doc.get("spec") or {} - self.path = (REPO / str(spec.get("path", "./"))).resolve() - decryption = spec.get("decryption") or {} - self.provider = decryption.get("provider") - self.secret = (decryption.get("secretRef") or {}).get("name") - self.dirs = kustomize_build_dirs(self.path) if self.path.is_dir() else set() - - @property - def decrypts(self) -> bool: - return self.provider == "sops" and bool(self.secret) - - def describe(self) -> str: - return f"{self.source.relative_to(REPO)}: {self.name}" - - -def main() -> int: - verbose = "-v" in sys.argv[1:] or "--verbose" in sys.argv[1:] - - manifest_dirs = live_manifest_dirs() - if not manifest_dirs: - sys.stderr.write( - "check-sops-decryption: no clusters/*/flux-system/gotk-sync.yaml with a flux-system\n" - "Kustomization found — refusing to report a pass I cannot prove.\n" - ) - return 2 - - flux_ks: list[FluxKustomization] = [] - for directory in manifest_dirs: - for path in sorted(directory.rglob("*")): - if path.suffix not in (".yaml", ".yml") or not path.is_file(): - continue - if any(part in SKIP_DIRS for part in path.relative_to(REPO).parts): - continue - for doc in load_docs(path): - if is_flux_kustomization(doc): - flux_ks.append(FluxKustomization(path, doc)) - - if not flux_ks: - sys.stderr.write("check-sops-decryption: no Flux Kustomizations found — refusing a pass.\n") - return 2 - - # 1. Every reconciling Kustomization must be able to decrypt. - for k in flux_ks: - if k.provider != "sops": - fail( - f"{k.describe()}: decryption.provider is {k.provider!r}, expected 'sops'\n" - f" any *.sops.yaml under {k.path.relative_to(REPO)}/ would apply as ENC[...] ciphertext" - ) - elif not k.secret: - fail(f"{k.describe()}: decryption.provider is sops but secretRef.name is missing") - - secrets_used = sorted({k.secret for k in flux_ks if k.secret}) - for name in secrets_used: - if name != SOPS_SECRET: - notes.append( - f"note: {name!r} is used as the SOPS key instead of {SOPS_SECRET!r} — make sure it exists" - ) - - # 2./3. Every encrypted file must sit in a tree that decrypts, and be encrypted. - sops_files: list[Path] = [] - for pattern in ("*.sops.yaml", "*.sops.yml"): - for path in sorted(REPO.rglob(pattern)): - rel = path.relative_to(REPO) - if any(part in SKIP_DIRS for part in rel.parts): - continue - if path.name in (".sops.yaml", ".sops.yml"): - continue # the sops creation_rules config, not a manifest - sops_files.append(path) - - for path in sops_files: - rel = path.relative_to(REPO) - owners = [k for k in flux_ks if path.parent in k.dirs] - if not owners: - fail( - f"{rel}: not under any live Flux Kustomization tree\n" - " it is never applied (dead file) — move it into a reconciled tree or delete it" - ) - continue - for owner in owners: - if not owner.decrypts: - fail( - f"{rel}: owned by {owner.describe()} which does not decrypt\n" - f" add decryption: {{provider: sops, secretRef: {{name: {SOPS_SECRET}}}}} to that Kustomization" - ) - try: - text = path.read_text(encoding="utf-8") - except OSError as exc: - fail(f"{rel}: cannot read: {exc}") - continue - if "ENC[AES256_GCM" not in text: - fail(f"{rel}: no SOPS ciphertext (ENC[AES256_GCM...) — is the value plaintext?") - if not any("sops:" in line for line in text.splitlines()): - fail(f"{rel}: missing the `sops:` metadata block — not a SOPS file") - - if verbose: - for k in flux_ks: - print( - f" {k.name:<20} path={k.path.relative_to(REPO)}/" - f" decryption={'sops:' + (k.secret or '') if k.decrypts else 'NONE'}" - ) - for path in sops_files: - owners = ",".join(k.name for k in flux_ks if path.parent in k.dirs) or "-" - print(f" {path.relative_to(REPO)} owner={owners}") - - for note in notes: - print(note, file=sys.stderr) - - decrypting = sum(1 for k in flux_ks if k.provider == "sops") - if violations: - for violation in violations: - print(f"FAIL {violation}", file=sys.stderr) - print( - f"FAIL: {len(violations)} problem(s) across {len(flux_ks)} Flux Kustomizations " - f"({decrypting} decrypt with sops) and {len(sops_files)} SOPS file(s).", - file=sys.stderr, - ) - return 1 - - print( - f"OK: {len(flux_ks)} Flux Kustomizations, {decrypting}/{len(flux_ks)} decrypt with " - f"provider=sops (secret {', '.join(secrets_used) or 'none'}); " - f"{len(sops_files)} SOPS file(s), all inside decrypting trees and genuinely encrypted." - ) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main())