Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(docker): allow a non-root start and pin the openwa uid
Yudhi Armyndharis7f5f33f99821
diff --git a/Dockerfile b/Dockerfileindex 48e3585e0..a0b864791 100644--- a/Dockerfile+++ b/Dockerfile@@ -170,8 +170,10 @@ http://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" > /etc/apt/sources.l# Set Puppeteer to skip automatic download during npm install (we download it explicitly below)ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true-# Create app user for security-RUN groupadd -r openwa && useradd -r -g openwa openwa+# Create app user for security. The ids are pinned (997 is what `-r` assigned on both arches) so a+# Kubernetes runAsUser/fsGroup or a `docker run --user` can name the runtime user; the root start+# re-owns /app/data by name either way.+RUN groupadd -r -g 997 openwa && useradd -r -u 997 -g openwa openwaWORKDIR /app@@ -306,6 +308,8 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \# `exec gosu openwa "$@"`, after it chowns /app/data and the Chromium XDG# dirs. Adding `USER openwa` here would run the entrypoint as openwa and break# the chown-before-drop pattern that makes named-volume mounts work on first-# boot (#254, #259).+# boot (#254, #259). Starting it as a non-root uid on purpose (`--user 997:997`,+# a Kubernetes runAsUser) is supported: the entrypoint skips the chown and the+# drop, and needs /app/data to be writable by that uid.ENTRYPOINT ["dumb-init", "--", "/usr/local/bin/docker-entrypoint.sh"]CMD ["node", "dist/main"]diff --git a/README.md b/README.mdindex 16a28a919..1cff21d40 100644--- a/README.md+++ b/README.md@@ -251,6 +251,8 @@ dumb-init (PID 1)Named volumes (e.g. `openwa-data`) get their ownership corrected automatically on every start, so no manual `chown` step is needed after volume creation.+The image can also start as the `openwa` user directly (uid/gid 997: `--user 997:997`, or the Helm chart's `podSecurityContext`). The entrypoint then skips the `chown` and the `gosu` drop and needs no added capabilities, provided `/app/data` is writable by that uid.+---## π Production Deploymentdiff --git a/charts/openwa/templates/statefulset.yaml b/charts/openwa/templates/statefulset.yamlindex 80978627c..abb99e3f7 100644--- a/charts/openwa/templates/statefulset.yaml+++ b/charts/openwa/templates/statefulset.yaml@@ -28,6 +28,10 @@ spec:serviceAccountName: {{ include "openwa.serviceAccountName" . }}# The app never calls the Kubernetes API β don't mount a token it can't use.automountServiceAccountToken: false+ {{- with .Values.podSecurityContext }}+ securityContext:+ {{- toYaml . | nindent 8 }}+ {{- end }}{{- with .Values.imagePullSecrets }}imagePullSecrets:{{- toYaml . | nindent 8 }}diff --git a/charts/openwa/values.yaml b/charts/openwa/values.yamlindex 17bf37ea3..e64c01a35 100644--- a/charts/openwa/values.yaml+++ b/charts/openwa/values.yaml@@ -77,9 +77,41 @@ resources:# teardown can exceed the 30s k8s default.terminationGracePeriodSeconds: 45-# Parity with docker-compose hardening. The image entrypoint STARTS AS ROOT to-# chown /app/data + the XDG dirs, then drops to the openwa user via gosu β so do-# NOT add runAsNonRoot here; it breaks that pattern.+# Pod-level securityContext, empty by default. The default image start is as+# root: the entrypoint re-owns /app/data and the XDG dirs, then drops to the+# openwa user (uid/gid 997) via gosu, which needs the capabilities added below.+#+# To run as non-root from the first instruction instead (Pod Security Standard+# "restricted"), set:+#+# podSecurityContext:+# runAsNonRoot: true+# runAsUser: 997+# runAsGroup: 997+# fsGroup: 997+# fsGroupChangePolicy: OnRootMismatch+# seccompProfile:+# type: RuntimeDefault+# containerSecurityContext:+# readOnlyRootFilesystem: true+# allowPrivilegeEscalation: false+# capabilities:+# drop: [ALL]+# add: null+#+# The entrypoint then skips its chown and privilege drop and runs as that uid;+# fsGroup is what makes a fresh volume writable by it. OnRootMismatch makes the+# kubelet re-own the volume only when its root has the wrong group or mode,+# instead of touching every file on every mount. `add: null` removes the+# default list below; Helm merges maps, so leaving it out keeps all five.+# The RuntimeDefault seccomp profile is opt-in (it can also be set alone,+# under either context) until a whatsapp-web.js session start under it has+# been confirmed on arm64, where the image uses Debian's Chromium.+podSecurityContext: {}++# Parity with docker-compose hardening. The five added capabilities are used+# only by the root entrypoint (chown, then the gosu drop); see+# podSecurityContext above for the non-root alternative.containerSecurityContext:readOnlyRootFilesystem: trueallowPrivilegeEscalation: falsediff --git a/docker-entrypoint.sh b/docker-entrypoint.shindex 8322336f8..dd302ee14 100644--- a/docker-entrypoint.sh+++ b/docker-entrypoint.sh@@ -1,8 +1,23 @@#!/bin/sh-# Runs as root (via dumb-init). Fixes named-volume ownership then drops to the-# openwa user via gosu so the Node process never holds root privileges.+# Runs as root (via dumb-init) by default: fixes named-volume ownership, then drops to the+# openwa user via gosu so the Node process never holds root privileges. Started as any other+# uid (`docker run --user`, compose `user:`, a Kubernetes runAsUser) it cannot chown or switch+# users, so it skips both and runs the command as that uid.set -e+# A non-root start needs a data volume its uid can already write. Say so here, naming the fix,+# rather than failing on a chown or on the first write inside Node.+if [ "$(id -u)" != 0 ]; then+ for dir in /app/data /app/data/sessions /app/data/media /app/data/plugins; do+ if [ -e "$dir" ] && [ ! -w "$dir" ]; then+ echo "FATAL: $dir is not writable by uid $(id -u), gid $(id -g)." >&2+ echo " A non-root start needs a data volume that user can write: in Kubernetes set" >&2+ echo " podSecurityContext.fsGroup to its gid; with Docker, chown the volume to it, or start as root." >&2+ exit 1+ fi+ done+fi+mkdir -p /app/data/sessions /app/data/media /app/data/plugins# Chromium leaves SingletonLock/SingletonSocket/SingletonCookie in each session profile and does@@ -11,6 +26,22 @@ mkdir -p /app/data/sessions /app/data/media /app/data/plugins# so clearing them lets sessions re-launch after a crash/restart. (#259)rm -f /app/data/sessions/*/Singleton* 2>/dev/null || true+# Chromium resolves its home from the passwd entry (no /home/openwa exists), so it hard-crashes at+# launch unless its config/cache dirs exist and are writable. XDG_CONFIG_HOME/XDG_CACHE_HOME (set in+# the image) point here; create them owned by openwa. On a read_only rootfs these live on tmpfs /tmp,+# which is mounted fresh each start, so they must be (re)created at runtime, not at build. (#254)+if ! mkdir -p "${XDG_CONFIG_HOME:-/tmp/.config}" "${XDG_CACHE_HOME:-/tmp/.cache}"; then+ echo "FATAL: cannot create Chromium config/cache dirs (${XDG_CONFIG_HOME:-/tmp/.config}, ${XDG_CACHE_HOME:-/tmp/.cache})." >&2+ echo " On a read_only rootfs, mount a writable tmpfs/emptyDir at /tmp (compose: 'tmpfs: [/tmp]'; k8s: an emptyDir at /tmp)." >&2+ echo " Without it Chromium cannot launch and sessions will fail (#254)." >&2+ exit 1+fi++# Nothing below can run without root: the chowns need CAP_CHOWN and gosu needs CAP_SETUID.+if [ "$(id -u)" != 0 ]; then+ exec "$@"+fi+# Re-own every path under /app/data that is not already openwa:openwa, except symlinks. Some bind# mounts (Docker Desktop's file sharing) refuse to change a symlink's owner, which a link never# needs, so a `chown -R` that met any link (a Chromium lock under a custom SESSION_DATA_PATH, a@@ -24,16 +55,7 @@ rm -f /app/data/sessions/*/Singleton* 2>/dev/null || true# chown failure still stops the script.find /app/data ! -type l \( ! -user openwa -o ! -group openwa \) -exec chown -h openwa:openwa {} +-# Chromium resolves its home from the passwd entry (no /home/openwa exists), so it hard-crashes at-# launch unless its config/cache dirs exist and are writable. XDG_CONFIG_HOME/XDG_CACHE_HOME (set in-# the image) point here; create them owned by openwa. On a read_only rootfs these live on tmpfs /tmp,-# which is mounted fresh each start β so they must be (re)created at runtime, not at build. (#254)-if ! mkdir -p "${XDG_CONFIG_HOME:-/tmp/.config}" "${XDG_CACHE_HOME:-/tmp/.cache}"; then- echo "FATAL: cannot create Chromium config/cache dirs (${XDG_CONFIG_HOME:-/tmp/.config}, ${XDG_CACHE_HOME:-/tmp/.cache})." >&2- echo " On a read_only rootfs, mount a writable tmpfs/emptyDir at /tmp (compose: 'tmpfs: [/tmp]'; k8s: an emptyDir at /tmp)." >&2- echo " Without it Chromium cannot launch and sessions will fail (#254)." >&2- exit 1-fi+# The Chromium config/cache dirs created above, as root.chown openwa:openwa "${XDG_CONFIG_HOME:-/tmp/.config}" "${XDG_CACHE_HOME:-/tmp/.cache}"# "$@" = CMD from Dockerfile (default: node dist/main).diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex da9dbb00a..16458ac15 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -108,8 +108,9 @@ COPY --from=builder /app/dist ./dist# every production dependency (issue #1045: ~35 minutes on a small VPS), and the container itself# is the Chromium confinement boundary (cap_drop ALL, read_only rootfs). Instead the image starts# as root, the entrypoint chowns ONLY the writable ./data volume and then drops privileges via-# `exec gosu openwa node dist/main.js` (no-new-privileges blocks any setuid path back up).-RUN groupadd -r openwa && useradd -r -g openwa openwa+# `exec gosu openwa node dist/main.js` (no-new-privileges blocks any setuid path back up). The ids+# are pinned so the image can also be started as openwa directly (`--user 997:997`, runAsUser 997).+RUN groupadd -r -g 997 openwa && useradd -r -u 997 -g openwa openwa# Expose portEXPOSE 2785diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.mdindex 60b350f89..1401a15d3 100644--- a/docs/11-operational-runbooks.md+++ b/docs/11-operational-runbooks.md@@ -758,7 +758,9 @@ curl -s -X POST -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth>> ```bash> # Compose: the entrypoint override runs the script as root, which can read the archive and write-> # the volume; the next start hands the restored files back to the app user. The image sets+> # the volume; on the default root start, the next start hands the restored files back to the app+> # user. A service with `user:` set runs the script as that uid instead, which then needs to read+> # the archive and write ./backups, and owns what it restores. The image sets> # HOME=/app/data, and the script refuses a data dir that is the home directory, so HOME is moved> # off it here for a compose file that does not already set it.> docker compose run --rm --no-deps --entrypoint /app/scripts/restore.sh \@@ -776,10 +778,19 @@ curl -s -X POST -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth> name: openwa-restore> spec:> restartPolicy: Never+> securityContext:+> runAsNonRoot: true+> runAsUser: 997+> runAsGroup: 997+> fsGroup: 997+> seccompProfile: { type: RuntimeDefault }> containers:> - name: restore> image: ghcr.io/rmyndharis/openwa:<version>> command: ['sleep', 'infinity']+> securityContext:+> allowPrivilegeEscalation: false+> capabilities: { drop: [ALL] }> envFrom:> - configMapRef:> name: openwa@@ -798,6 +809,8 @@ curl -s -X POST -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth> # HOME is moved off the data dir here too, as in the compose command.> kubectl exec openwa-restore -- env HOME=/tmp OPENWA_RESTORE_SNAPSHOT_DIR=/restore TMPDIR=/restore \> ./scripts/restore.sh /restore/backup.tar.gz --force+> # The helper runs as the app user (uid 997), so what the script restores is already owned by it,+> # and the pod meets Pod Security "restricted" for a release that runs non-root.> # The emptyDir goes away with the pod: copy off every snapshot the script named first.> kubectl cp openwa-restore:/restore/data.pre-restore-<ts> ./backups/data.pre-restore-<ts>> kubectl delete pod openwa-restorediff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 0569cf5c5..be5cfec9c 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1149,14 +1149,18 @@ npm run migration:run:main**Solutions:**-The entrypoint starts as root, re-owns `/app/data` to the `openwa` user on every start, and then-drops privileges with `gosu`. Keep that path intact:+By default the entrypoint starts as root, re-owns `/app/data` to the `openwa` user (uid/gid 997) on+every start, and then drops privileges with `gosu`. Keep that path intact:-- Do not set `user:` on `openwa-api` (or `--user` on `docker run`). The entrypoint then cannot- `chown` or drop privileges, exits, and the container restarts in a loop.- Keep the `CHOWN`, `DAC_OVERRIDE`, `FOWNER`, `SETGID` and `SETUID` entries under `cap_add` in`docker-compose.yml`; the `chown` and the `gosu` drop need them.-- A `chown` of the host directory is not a fix: the entrypoint re-owns `/app/data` at the next start.+- Setting `user:` on `openwa-api` (or `--user` on `docker run`) starts the entrypoint as that uid+ instead. It then skips the `chown` and the drop, so `/app/data` must already be writable by that+ uid: `user: "997:997"` works on a volume a root start has already re-owned, and the `cap_add` list+ can then be removed. Any other uid needs the volume chowned to it first. When the volume is not+ writable the container stops with `FATAL: /app/data is not writable by uid ...`.+- On the default root start, a `chown` of the host directory is not a fix: the entrypoint re-owns+ `/app/data` at the next start. A non-root start (above) is the case that needs one.- If the error persists on a bind mount, the host filesystem is refusing the `chown` (NFS with`root_squash`, some rootless or SMB setups) or SELinux is denying access (add `:z` to the mount).Use the named volume from the shipped `docker-compose.yml` instead.diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex 9110d3e0f..15fc63b30 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -405,10 +405,15 @@ spec:# grants by default, so a plugin that abuses Node built-ins (fs, net) can read host files / open raw# sockets outside the capability model. The shipped compose file runs the image read-only +# cap_drop:ALL, and the node process runs as the non-root openwa user; the manifest below mirrors- # that so a k8s deploy is not silently weaker. Do NOT add runAsNonRoot: the entrypoint starts as- # root to chown /app/data, then drops to openwa via gosu (same as charts/openwa/values.yaml).+ # that so a k8s deploy is not silently weaker. By default the entrypoint starts as root to chown+ # /app/data, then drops to openwa (uid/gid 997) via gosu. To run non-root from the start instead,+ # add runAsNonRoot: true, runAsUser: 997 and runAsGroup: 997 here and remove the capabilities `add`+ # list below; the entrypoint then skips the chown and the drop (see podSecurityContext in+ # charts/openwa/values.yaml). fsGroup makes the volume writable by openwa in either mode;+ # OnRootMismatch re-owns it only when its root is wrong, not every file on every mount.securityContext:- fsGroup: 1000+ fsGroup: 997+ fsGroupChangePolicy: OnRootMismatchcontainers:- name: openwaimage: ghcr.io/rmyndharis/openwa:latestdiff --git a/docs/30-plugin-sandboxing.md b/docs/30-plugin-sandboxing.mdindex 44e043a31..b857ae346 100644--- a/docs/30-plugin-sandboxing.md+++ b/docs/30-plugin-sandboxing.md@@ -79,9 +79,10 @@ The bundled compose stack adds **OS-level containment** as defence in depth. Itprocess can do to the host; it does not confine a plugin away from anything that process can reach:- **Run OpenWA in a container.** The image's entrypoint already drops to the non-root `openwa` user- (via `gosu`, after fixing volume ownership). The rest of the confinement comes from the bundled- `docker-compose.yml`, not from the image: `read_only: true` rootfs with a tmpfs `/tmp`,- `no-new-privileges`, and `cap_drop: ALL` with a minimal re-add+ (via `gosu`, after fixing volume ownership), or can be started as that user (uid/gid 997) from the+ first instruction, with no capabilities added (the chart's `podSecurityContext`). The rest of the+ confinement comes from the bundled `docker-compose.yml`, not from the image: `read_only: true`+ rootfs with a tmpfs `/tmp`, `no-new-privileges`, and `cap_drop: ALL` with a minimal re-add(`CHOWN`/`DAC_OVERRIDE`/`FOWNER`/`SETGID`/`SETUID`) that only the root entrypoint uses β once `gosu`setuids, the Node process keeps no effective capabilities. A plain `docker run` of the image getsnone of the compose-level settings, so replicate them yourself if you deploy that way.diff --git a/scripts/check-chart-behaviour.mjs b/scripts/check-chart-behaviour.mjsindex f8f8ecbc8..7dd6d9f90 100644--- a/scripts/check-chart-behaviour.mjs+++ b/scripts/check-chart-behaviour.mjs@@ -177,6 +177,37 @@ const check = (id, ok, detail) => results.push({ id, ok, detail }););}+// The image also starts as a non-root uid, which is the only way to meet Pod Security "restricted".+// That needs a pod-level securityContext (fsGroup is what makes a fresh volume writable by the uid)+// and a way to drop the capability list the root entrypoint needs, while the default stays as it is.+// The profile rendered is the one values.yaml documents, so the comment cannot drift from what works.+{+ const podContext = out => {+ const sts = byKind(out, 'StatefulSet')[0] ?? '';+ return /^ {6}securityContext:\n((?: {8}.*\n)+)/m.exec(sts)?.[1] ?? '';+ };+ const addsCaps = out => /^ {14}add:/m.test(byKind(out, 'StatefulSet')[0] ?? '');+ const byDefault = render();+ const values = readFileSync(`${CHARTS}/openwa/values.yaml`, 'utf8');+ const profile = /^# {3}podSecurityContext:\n(?:# {3}.*\n)+/m.exec(values)?.[0] ?? '';+ const nonRoot = renderValues(profile.replace(/^# {3}/gm, ''));+ const pod = podContext(nonRoot);+ const problems = [+ podContext(byDefault) && 'the default render sets a pod securityContext',+ !addsCaps(byDefault) && 'the default render lost the capabilities the root entrypoint needs',+ !/runAsNonRoot: true/.test(pod) && 'podSecurityContext.runAsNonRoot does not reach the pod spec',+ !/fsGroup: 997/.test(pod) && 'podSecurityContext.fsGroup does not reach the pod spec',+ // Without it the kubelet re-owns every file on the volume on every mount before the pod starts.+ !/fsGroupChangePolicy: OnRootMismatch/.test(pod) && 'podSecurityContext.fsGroupChangePolicy is not OnRootMismatch',+ addsCaps(nonRoot) && 'containerSecurityContext.capabilities.add: null still renders an add list',+ ].filter(Boolean);+ check(+ 'non-root-profile-renders',+ problems.length === 0,+ problems.length ? problems.join('; ') : 'the default is unchanged, and podSecurityContext plus add: null render a non-root pod',+ );+}+// One scrape target per pod per endpoint. Prometheus Operator yields a target for every address of// every Service matching the selector and de-duplicates nothing by pod, so a selector matching N// Services produces N series sets separated only by the `service` label.diff --git a/scripts/smoke-test-non-root.sh b/scripts/smoke-test-non-root.shindex f1e60910d..79e04524f 100755--- a/scripts/smoke-test-non-root.sh+++ b/scripts/smoke-test-non-root.sh@@ -32,6 +32,8 @@ cleanup() {docker rmi "$IMAGE_TAG" > /dev/null 2>&1 || truefi}+# Every exit, set -e aborts included, so a failed step never leaves the volume or image behind.+trap cleanup EXITecho ""echo "==> Checking process user inside container..."@@ -41,7 +43,6 @@ echo " $USER_OUTPUT"if echo "$USER_OUTPUT" | grep -q "uid=0(root)"; thenecho "FAIL: process is running as root!" >&2- cleanupexit 1fi@@ -49,7 +50,6 @@ if echo "$USER_OUTPUT" | grep -q "openwa"; thenecho "PASS: process runs as openwa (non-root)"elseecho "FAIL: process is not running as the openwa user" >&2- cleanupexit 1fi@@ -62,7 +62,6 @@ if echo "$PID1" | grep -q "dumb-init"; thenelse# Without it as PID 1 nothing reaps Chromium's exited children or forwards signals past Node.echo "FAIL: PID 1 is '$PID1' (expected dumb-init), check the ENTRYPOINT chain" >&2- cleanupexit 1fi@@ -79,7 +78,6 @@ if [ "$OWNERS" = "openwa:openwa root:root " ]; thenecho "PASS: a root-owned file is re-owned and a symlink target is left alone"elseecho "FAIL: expected 'openwa:openwa root:root', got '$OWNERS'" >&2- cleanupexit 1fi# A chown is a metadata write even when the owner is unchanged, so it moves ctime. A start that@@ -91,10 +89,42 @@ if [ "$CTIME_BEFORE" = "$CTIME_AFTER" ]; thenecho "PASS: a start leaves already-owned files untouched"elseecho "FAIL: a start re-owned an already-owned file (ctime $CTIME_BEFORE -> $CTIME_AFTER)" >&2- cleanupexit 1fi-cleanup+echo ""+echo "==> Checking a start as the openwa uid itself..."+# runAsUser/fsGroup and --user name a number, so the image must guarantee it.+PINNED=$(docker run --rm --entrypoint id "$IMAGE_TAG" openwa)+echo " $PINNED"+case "$PINNED" in+ "uid=997(openwa) gid=997(openwa)"*) echo "PASS: openwa is uid/gid 997" ;;+ *) echo "FAIL: expected openwa to be uid=997 gid=997, got '$PINNED'" >&2; exit 1 ;;+esac+# The Pod Security "restricted" shape: no capabilities at all, read-only rootfs, and the volume a+# root start has already re-owned. The entrypoint must skip its chown and gosu drop, not fail on them.+if ! NONROOT=$(docker run --rm --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \+ --user 997:997 -v "$VOL":/app/data "$IMAGE_TAG" id -u 2>&1); then+ echo "FAIL: a start as 997:997 with no capabilities exited non-zero: $NONROOT" >&2+ exit 1+fi+if [ "$NONROOT" = "997" ]; then+ echo "PASS: a start as 997:997 with no capabilities runs the command as 997"+else+ echo "FAIL: a start as 997:997 printed '$NONROOT'" >&2+ exit 1+fi+# Any other uid cannot write the image's /app/data; it must stop with the cause, not a chown error.+if OTHER=$(docker run --rm --user 12345:12345 "$IMAGE_TAG" id -u 2>&1); then+ echo "FAIL: a start as 12345 with an unwritable /app/data succeeded: $OTHER" >&2+ exit 1+fi+if echo "$OTHER" | grep -q "FATAL: /app/data is not writable by uid 12345"; then+ echo "PASS: a start as an unrelated uid stops and names the unwritable volume"+else+ echo "FAIL: a start as 12345 failed without the expected message: $OTHER" >&2+ exit 1+fi+echo ""echo "All smoke tests passed!"diff --git a/src/common/ci-privilege-gate.spec.ts b/src/common/ci-privilege-gate.spec.tsindex 189b7b365..dcf8eede6 100644--- a/src/common/ci-privilege-gate.spec.ts+++ b/src/common/ci-privilege-gate.spec.ts@@ -81,6 +81,29 @@ describe('the non-root drop is enforced, not merely documented', () => {expect(entrypoint).toMatch(/exec\s+gosu\s+openwa/);});+ // A start as any other uid (runAsUser, `--user`) holds no CAP_CHOWN or CAP_SETUID, so it must leave+ // before the first chown and the gosu drop: under `set -e` either one exits, and the container+ // restarts in a loop. It must also refuse a data volume it cannot write, naming the cause.+ it('lets a non-root start skip every chown and the gosu drop', () => {+ const entrypoint = fs.readFileSync(path.join(__dirname, '..', '..', 'docker-entrypoint.sh'), 'utf8');+ const exit = entrypoint.search(/^if \[ "\$\(id -u\)" != 0 \]; then\n\s+exec "\$@"\nfi$/m);+ const firstChown = entrypoint.search(/^\s*(?:chown|find\b.*-exec chown)\b/m);+ expect(exit).toBeGreaterThan(-1);+ expect(firstChown).toBeGreaterThan(exit);+ expect(entrypoint.search(/^exec gosu openwa/m)).toBeGreaterThan(exit);+ expect(entrypoint).toMatch(/FATAL: \$dir is not writable by uid/);+ });++ // runAsUser, fsGroup and `--user` name a number, so the image has to guarantee it rather than take+ // whatever `useradd -r` finds free after the apt layers.+ it('pins the openwa uid and gid that the chart and docs name', () => {+ const dockerfile = fs.readFileSync(path.join(__dirname, '..', '..', 'Dockerfile'), 'utf8');+ const values = fs.readFileSync(path.join(__dirname, '..', '..', 'charts', 'openwa', 'values.yaml'), 'utf8');+ expect(dockerfile).toMatch(/^RUN groupadd -r -g 997 openwa && useradd -r -u 997 -g openwa openwa$/m);+ expect(values).toMatch(/runAsUser: 997/);+ expect(values).toMatch(/fsGroup: 997/);+ });+// The Dockerfile explains the missing USER directive by pointing at the entrypoint. A line number// goes stale on the next entrypoint edit and sends the reader to the wrong statement.it('does not cite entrypoint line numbers from the Dockerfile', () => {@@ -271,6 +294,35 @@ describe('deployment docs describe what the entrypoint, probes and backup scriptconst root = path.join(__dirname, '..', '..');const read = (file: string): string => fs.readFileSync(path.join(root, file), 'utf8');+ // A non-root start leaves before the re-own, so there a host chown is the fix, not a no-op.+ it('scopes "a host chown is not a fix" to the root start', () => {+ const bullet = read('docs/12-troubleshooting-faq.md')+ .split('\n')+ .find(line => line.includes('of the host directory is not a fix'));+ expect(bullet).toMatch(/root start/);+ });++ // A non-root start never re-owns what the restore writes, and a root helper pod is refused in a+ // namespace enforcing Pod Security "restricted". The helper runs as the app user, so both hold.+ it('runs the Helm restore helper as the app user, and scopes the compose re-own to the root start', () => {+ const doc = read('docs/11-operational-runbooks.md');+ const helper = doc.slice(+ doc.indexOf(' name: openwa-restore'),+ doc.indexOf('> EOF', doc.indexOf(' name: openwa-restore')),+ );+ expect(helper).toMatch(/runAsNonRoot: true/);+ expect(helper).toMatch(/runAsUser: 997/);+ expect(helper).toMatch(/fsGroup: 997/);+ expect(helper).toMatch(/seccompProfile: \{ type: RuntimeDefault \}/);+ expect(helper).toMatch(/allowPrivilegeEscalation: false/);+ expect(helper).toMatch(/capabilities: \{ drop: \[ALL\] \}/);+ const handBack = doc+ .replace(/\n> # /g, ' ')+ .split(/[.;] /)+ .find(sentence => sentence.includes('hands the restored files back'));+ expect(handBack).toMatch(/root start/);+ });+// Session auto-start is detached: boot does not wait for it, so no probe covers it.it('does not claim the startupProbe covers session restore', () => {expect(read('docs/13-horizontal-scaling.md')).not.toMatch(/off during boot \([^)]*session/);