diff --git a/cmd/zapret-autotune/managed_monitor_cli_test.go b/cmd/zapret-autotune/managed_monitor_cli_test.go index 06fc8f4..5377d34 100644 --- a/cmd/zapret-autotune/managed_monitor_cli_test.go +++ b/cmd/zapret-autotune/managed_monitor_cli_test.go @@ -215,9 +215,8 @@ func TestManagedEntrypointSupervision(t *testing.T) { return path } log := filepath.Join(root, "log") - write("secret", strings.Repeat("a", 32)) write("awk", "#!/bin/sh\ncase \"$*\" in */proc/net/tcp*) until grep -q ready-ss-server \"$LOG\" && grep -q ready-ss-local \"$LOG\"; do sleep 0.02; done;; esac\nexit 0\n") - child := "#!/bin/sh\ntrap 'echo stopped-$0 >> \"$LOG\"; exit 0' TERM INT\necho ready-$(basename \"$0\") >> \"$LOG\"\nwhile :; do sleep 0.1 & wait $!; done\n" + child := "#!/bin/sh\n[ -z \"${SS_PASSWORD+x}\" ] || exit 88\ntrap 'echo stopped-$0 >> \"$LOG\"; exit 0' TERM INT\necho ready-$(basename \"$0\") >> \"$LOG\"\nwhile :; do sleep 0.1 & wait $!; done\n" write("ss-server", child) write("ss-local", child) zapret := write("zapret", "#!/bin/sh\necho zapret-$1 >> \"$LOG\"\n") @@ -226,12 +225,12 @@ func TestManagedEntrypointSupervision(t *testing.T) { if err != nil { t.Fatal(err) } - text := strings.NewReplacer("/run/secrets/ss_password", filepath.Join(root, "secret"), "/run/zapret-autotune-ss", config, "/usr/local/bin/zapret-autotune", monitor, managedZapretScript, zapret).Replace(string(data)) + text := strings.NewReplacer("/run/zapret-autotune-ss", config, "/usr/local/bin/zapret-autotune", monitor, managedZapretScript, zapret).Replace(string(data)) entry := write("entrypoint", text) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "/bin/sh", entry) - cmd.Env = append(os.Environ(), "PATH="+root+":"+os.Getenv("PATH"), "LOG="+log, "MODE="+mode, "ZAPRET_CONFIG="+filepath.Join(root, "config")) + cmd.Env = append(os.Environ(), "PATH="+root+":"+os.Getenv("PATH"), "LOG="+log, "MODE="+mode, "ZAPRET_CONFIG="+filepath.Join(root, "config"), "SS_PASSWORD="+strings.Repeat("a", 32)) cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} var output bytes.Buffer cmd.Stdout, cmd.Stderr = &output, &output diff --git a/deploy/managed-target/README.md b/deploy/managed-target/README.md index 8d4749d..4f348c3 100644 --- a/deploy/managed-target/README.md +++ b/deploy/managed-target/README.md @@ -1,86 +1,70 @@ -# Isolated managed-test definition — deployment deferred +# Isolated managed-test target -This definition is **not autonomous acceptance-ready**: `managed monitor` and -entrypoint recovery integration exist in code but are not live verified. Do not build/pull/start it as part of this -change. Existing containers, production and Xray configuration are out of scope. +This Compose project provisions a new, isolated target. It does not attach to, +reconfigure, or stop the existing `zapret2-ss-autotune` container. The target +starts from a disabled managed baseline; `managed monitor` bootstraps the +frontend/API strategy, then discovers and applies an exact-host GGC strategy. -For a later approved deployment, from this directory: +## Provisioning -1. Copy `.env.example` to `.env` and restrict it to `0600`; it sets only the - host loopback SOCKS port. Generate a **new independent** secret locally: - `(umask 077; set -C; openssl rand -hex 32 > ss_password)`. - This refuses to overwrite an existing file. Never copy existing secrets or - put the password in `.env`, environment variables or command arguments. - `ss_password`, `.env` and state are gitignored and excluded from the build - context. Do not commit the secret file. Compose mounts it read-only at - `/run/secrets/ss_password`; keep the host file owned by the invoking user - with mode `0600` (no deploy-time chown or world-readable permissions). - Use only this newly generated regular file at `./ss_password`, not a symlink - or a reused secret. Do not mount its parent directory or other host secrets. -2. Provision a **new empty** `./target-state`, owned by host UID 0 (runtime - user), mode `0700`. Rootless/user-remapped Docker needs the mapped owner. - Never reuse mounts/state. Compose refuses a missing bind source. Retain - state for recreation; deletion loses identity, journal, backups and DB. -3. Orchestrator may validate without deploying: - `docker compose --env-file .env -f compose.yaml config --quiet`. - Rendered Compose config contains only the secret file path, not its value. Build/run require - separate approval and runtime validation gates. +From this directory, create a private `.env` with a fresh independent password +and the configured host SOCKS port: + +```sh +(umask 077; set -C; printf 'SS_PASSWORD=%s\nZAPRET_AUTOTUNE_HOST_SOCKS_PORT=11080\n' "$(openssl rand -hex 32)" > .env) +``` + +This refuses to overwrite an existing `.env`; do not print it or commit it. +Compose passes `SS_PASSWORD` as a container environment variable. It is removed +from the entrypoint environment before Shadowsocks children start and is never +placed in argv or logs. Docker administrators/root can still read container +environment and runtime config, so use this only for the isolated test target. + +Create a **new empty** `./target-state`, owned by host UID 0 (runtime user), +mode `0700`; rootless/user-remapped Docker needs the mapped owner. Never reuse +state. Compose refuses a missing bind source. Retain state for recreation; +deletion loses transaction identity, journal, backups and candidate DB. + +Validate without printing interpolated values: +`docker compose --env-file .env -f compose.yaml config --quiet`. +Then build and start only this Compose project. The rendered configuration +contains the environment password, so never use plain `docker compose config` +in logs or shared terminals. Offline static guard (from repository root): -`python3 deploy/managed-target/check_static.py`. It pins the capability allowlist -and single-secret/single-state mount shape; it does not prove runtime readability. +`python3 deploy/managed-target/check_static.py`. + +## Isolation and runtime contract Only SOCKS TCP/UDP is published on host -`127.0.0.1:${ZAPRET_AUTOTUNE_HOST_SOCKS_PORT:-11080}` for same-host Xray; -no Xray edits are supplied. SS port `8388` is internal, never published. -The server binds `0.0.0.0:8388` only inside the dedicated bridge namespace; -ss-local binds `0.0.0.0:1080`. Startup requires a hex-only secret of at least -32 characters and writes JSON configs to the dedicated target-owned tmpfs -`/run/zapret-autotune-ss` (directory `0700`, files `0600`). Both Shadowsocks -processes receive only `-c `, never a password in argv or env. -Docker administrators/root can still read mounted secrets and runtime configs; -file-backed Compose secrets are not encrypted storage. +`127.0.0.1:${ZAPRET_AUTOTUNE_HOST_SOCKS_PORT:-11080}` for optional same-host +Xray use; no Xray edits are supplied. SS port `8388` is internal and never +published. The server binds `0.0.0.0:8388` only inside the dedicated bridge +namespace; ss-local binds `0.0.0.0:1080`. Startup validates a hex-only password +of at least 32 characters, writes JSON configs to target-owned tmpfs +`/run/zapret-autotune-ss` (directory `0700`, files `0600`), then unsets the +password before starting child processes. + The dedicated bridge is not shared with existing services. No host networking, Docker socket, existing mounts, host Lua/fakes or privileged mode; all -capabilities are dropped except `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID` -and `DAC_OVERRIDE`. +capabilities are dropped except `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID`. `NET_ADMIN` covers nft/NFQUEUE; `NET_RAW` covers nfqws2 raw sends. Zapret2's -`nfqws2 --user=tpws` needs `SETUID`/`SETGID` for UID/GID switching, then retains -only `CAP_NET_RAW` and `CAP_NET_ADMIN`. `DAC_OVERRIDE` lets the root entrypoint -read the invoking user's mode-`0600` file-backed secret despite its different -host UID; it does not make the host file world-readable or writable through -the read-only secret mount. This capability is container-wide, not restricted -to one pathname: its safe scope depends on exposing only -`./ss_password` → `/run/secrets/ss_password` (read-only) and the fresh -`./target-state` → `/var/lib/zapret-autotune/target` bind, plus dedicated runtime -tmpfs. Never add host directories, other secrets or existing state to this -container. No default-all capability set is used. Rootless/user-remapped Docker -must validate secret readability separately; this does not bypass user-namespace -or host filesystem restrictions. +`nfqws2 --user=tpws` needs `SETUID`/`SETGID` for UID/GID switching. -Go builder matches `Dockerfile`; runtime digest is pinned and image-owned -Lua/fakes retained. Startup: ss-server/ss-local → internal listener 1080 -(30-second bound) → guarded managed init on fresh state (status on recreation) -→ zapret2 start using target config → one installed managed monitor child. Drift/pending state refuses startup; -no automatic adoption of unknown state. SIGTERM/SIGINT cancels and waits the monitor -before stopping target-local zapret and the entrypoint's Shadowsocks children. -Monitor fatal exits stop the entrypoint; no restart policy hides fail-closed exits. -Monitor probes Player API via owned loopback SOCKS; unresolved GGC is not playback health. +Startup order: ss-server/ss-local → listener 1080 → guarded managed init on +fresh state (status on recreation) → target-local `zapret2 start` → supervised +managed monitor. Drift/pending state refuses startup; unknown state is never +adopted. SIGTERM/SIGINT cancels and waits for the monitor before stopping +target-local zapret and Shadowsocks children. Monitor fatal exits stop the +entrypoint. Monitor health is YouTube Player API status through the owned SOCKS, +not video playback/SABR; GGC candidates are scoped to the exact discovered +hostname. -Inside target, `zapret-autotune health youtube` uses -`socks5://127.0.0.1:1080`, never the host port. It is one-shot Player API health, -not playback or scheduling. - -The supplied remote read-only inspection verified shadowsocks-libev 3.3.5 -and `ss-server -h` supports `-c `; runtime JSON loading remains -unverified. Before deployment acceptance, validate Lua/fakes, -`ZAPRET_CONFIG` binding and full zapret start/stop/restart with only -the explicit `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID`, `DAC_OVERRIDE` capability set (including -the `tpws` user drop). Prove target-local routing, -NFQUEUE activation/rollback, signal cleanup and persistent recreation on the -new target only. Compose syntax, build and runtime integration are unverified -by this producer. Do not widen capabilities or reuse existing config/network -as a workaround. Autonomous acceptance also needs tests/build and live verification -of monitor/recovery and crash reconciliation, including shutdown grace sufficient -for bounded restoration (which may exceed the defined 45s). Docker configuration -has not been changed by this code integration increment. +The deployment has not yet passed live runtime acceptance. Validate the pinned +image's JSON config loading, Lua/fakes, `ZAPRET_CONFIG` binding, target-local +routing, NFQUEUE activation/rollback, signal cleanup and persistent recreation +on this new target only. Do not widen capabilities or reuse existing config or +network as a workaround. Verify the complete unattended path: empty profile → +frontend/API candidate scan and apply → exact-host GGC candidate scan and apply +→ ongoing probes → saved-first recovery, falling back to scan only when saved +scenarios validly fail. diff --git a/deploy/managed-target/check_static.py b/deploy/managed-target/check_static.py index 8965d8e..4db9b6f 100644 --- a/deploy/managed-target/check_static.py +++ b/deploy/managed-target/check_static.py @@ -9,20 +9,20 @@ entrypoint = (directory.parents[1] / "managed-target-entrypoint.sh").read_text() readme = (directory / "README.md").read_text() # ponytail: checks the committed Compose shape, not arbitrary YAML; use a YAML -# parser if this definition grows beyond its single service and single secret. +# parser if this definition grows beyond its single target service. assert " privileged: false\n" in compose assert " cap_drop: [ALL]\n" in compose -assert " cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, DAC_OVERRIDE]\n" in compose +assert " cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID]\n" in compose assert compose.count(" - type: bind\n") == 1 assert " source: ./target-state\n" in compose assert " target: /var/lib/zapret-autotune/target\n" in compose assert " create_host_path: false\n" in compose -assert " secrets: [ss_password]\n" in compose -assert compose.endswith("secrets:\n ss_password:\n file: ./ss_password\n") -assert "SS_PASSWORD" not in compose -assert "ss_password=$(cat /run/secrets/ss_password) || exit 1" in entrypoint +assert "SS_PASSWORD: ${SS_PASSWORD:?Set SS_PASSWORD in the deployment environment}" in compose +assert "secrets:" not in compose +assert "ss_password=${SS_PASSWORD-}" in entrypoint +assert "unset SS_PASSWORD" in entrypoint assert "export ss_password" not in entrypoint assert "export SS_PASSWORD" not in entrypoint -assert "container-wide, not restricted" in readme -assert "mode `0600`" in readme -assert "not a symlink" in readme +assert "Docker administrators/root can still read container" in readme +assert "removed\nfrom the entrypoint environment" in readme +assert "No host networking" in readme diff --git a/deploy/managed-target/compose.yaml b/deploy/managed-target/compose.yaml index b2ea3b7..0dbe085 100644 --- a/deploy/managed-target/compose.yaml +++ b/deploy/managed-target/compose.yaml @@ -8,10 +8,9 @@ services: privileged: false cap_drop: [ALL] # nft/NFQUEUE, nfqws2 raw sends, and --user=tpws UID/GID switching. - # DAC_OVERRIDE lets root read the invoking user's 0600 read-only secret bind. - # It is container-wide; expose only this secret and the fresh target-state bind. - cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID, DAC_OVERRIDE] + cap_add: [NET_ADMIN, NET_RAW, SETUID, SETGID] environment: + SS_PASSWORD: ${SS_PASSWORD:?Set SS_PASSWORD in the deployment environment} SOCKS_PORT: "1080" ZAPRET_AUTOTUNE_TARGET_ROLE: managed-test ZAPRET_AUTOTUNE_TARGET_ID: zapret-autotune-managed-v1 @@ -28,7 +27,6 @@ services: target: /var/lib/zapret-autotune/target bind: create_host_path: false - secrets: [ss_password] tmpfs: - /run/zapret-autotune-ss:rw,noexec,nosuid,nodev,size=1m,mode=0700,uid=0,gid=0 networks: [target] @@ -36,6 +34,3 @@ services: networks: target: driver: bridge -secrets: - ss_password: - file: ./ss_password diff --git a/managed-target-entrypoint.sh b/managed-target-entrypoint.sh index 7331a7a..f8c8418 100644 --- a/managed-target-entrypoint.sh +++ b/managed-target-entrypoint.sh @@ -1,11 +1,12 @@ #!/bin/sh set -eu umask 077 -unset SS_PASSWORD ss_password [ "$#" -eq 0 ] || { echo 'error: target entrypoint accepts no arguments' >&2; exit 1; } -# Credentials never enter exported variables or Shadowsocks command arguments. -ss_password=$(cat /run/secrets/ss_password) || exit 1 +# Credentials never enter argv or logs. Docker supplies SS_PASSWORD via env; +# clear the exported value before starting any child processes. +ss_password=${SS_PASSWORD-} +unset SS_PASSWORD case "$ss_password" in ''|*[!0123456789abcdefABCDEF]*) echo 'error: target secret must contain only hexadecimal characters' >&2; exit 1 ;;