fix(managed): guard experimental authorization and startup requests

Reject explicit candidate-ID and inherited-policy CLI bypasses of the guarded native-circular operator path. Validate empty private runtime-owned request inodes without following links before state mutation, atomically claim and sync them before apply, retain failed claims, and never delete replacement requests. Keep internal journal reconciliation and legacy qualification unchanged.

Co-authored-by: GPT-6 <gpt-6@openai.com>
This commit is contained in:
ZeusinaandGPT-6 Bot committed 2026-10-12 07:14:20 +03:00
1 parent 371382c2c4
commit f88c8e9c45
6 files changed
+294 -13

No files matched your search

+9 -4
View File
@@ -409,10 +409,15 @@ rendered bytes and qualification gates are unchanged. Unknown policies fail clos
For PID-1-controlled application, while this dedicated target is stopped and For PID-1-controlled application, while this dedicated target is stopped and
after taking a complete private state backup, create a private empty file named after taking a complete private state backup, create a private empty file named
`.autotune-experimental-suffix-request` in its owned state directory. Startup `.autotune-experimental-suffix-request` in its owned state directory. It must be
reconciles/starts the known deployment, performs the command before launching an empty regular 0600 file owned by the runtime UID, with no symlink/hardlink.
the monitor, and consumes the request only on success. Failure exits closed; Startup validates it before init/reconcile, then atomically claims the validated
retain artifacts and use the matched whole-state/image rollback procedure above. inode before guarded apply (before launching the monitor). Only a successful
apply removes that claim; a replacement request is never deleted. Failure exits
closed and retains the private `.autotune-experimental-request-claim-*` artifact;
do not blindly retry it. Use the matched whole-state/image rollback above.
Candidate-ID CLI apply cannot select/inherit the experimental policy; explicit
native-circular authorization is required. Internal journal recovery is unchanged.
Resource probes still run. This policy remains `DEGRADED`/GGC-unresolved even Resource probes still run. This policy remains `DEGRADED`/GGC-unresolved even
when a bounded media check succeeds: neither playback READY nor family when a bounded media check succeeds: neither playback READY nor family
+32 -4
View File
@@ -60,7 +60,7 @@ func managedArguments(args []string) (string, []int64, error) {
if len(args) == 2 && args[0] == "status" && args[1] == "--assets" { if len(args) == 2 && args[0] == "status" && args[1] == "--assets" {
return "status", nil, nil return "status", nil, nil
} }
if len(args) == 1 && (args[0] == "init" || args[0] == "reconcile" || args[0] == "status" || args[0] == "active-ids") { if len(args) == 1 && (args[0] == "init" || args[0] == "reconcile" || args[0] == "status" || args[0] == "active-ids" || args[0] == "experimental-request-check") {
return args[0], nil, nil return args[0], nil, nil
} }
if len(args) < 3 || len(args)%2 != 1 || args[0] != "apply" { if len(args) < 3 || len(args)%2 != 1 || args[0] != "apply" {
@@ -70,9 +70,17 @@ func managedArguments(args []string) (string, []int64, error) {
seen := map[int64]bool{} seen := map[int64]bool{}
scopeSeen := false scopeSeen := false
experiment := false experiment := false
request := false
var scope GooglevideoScope var scope GooglevideoScope
for i := 1; i < len(args); i += 2 { for i := 1; i < len(args); i += 2 {
key := args[i] key := args[i]
if key == "--googlevideo-request" {
if request || args[i+1] != "startup" {
return "", nil, invalid
}
request = true
continue
}
if key == "--googlevideo-experiment" { if key == "--googlevideo-experiment" {
if experiment || args[i+1] != "native-circular" { if experiment || args[i+1] != "native-circular" {
return "", nil, invalid return "", nil, invalid
@@ -117,6 +125,9 @@ func managedArguments(args []string) (string, []int64, error) {
} }
return "experiment", nil, nil return "experiment", nil, nil
} }
if request || scope == GooglevideoScopeExperimental {
return "", nil, invalid
}
for _, key := range []string{"--frontend-candidate", "--googlevideo-candidate", "--asset-candidate"} { for _, key := range []string{"--frontend-candidate", "--googlevideo-candidate", "--asset-candidate"} {
ids = append(ids, selected[key]...) ids = append(ids, selected[key]...)
} }
@@ -381,7 +392,9 @@ func managedCLI(args []string, stdout, stderr io.Writer, d managedDeps) int {
return 1 return 1
} }
m := &managedTransaction{Dir: dir, Name: "config", Reload: func() error { return d.run(d.script, "restart") }, Health: func() (string, error) { return "", fmt.Errorf("health not configured") }} m := &managedTransaction{Dir: dir, Name: "config", Reload: func() error { return d.run(d.script, "restart") }, Health: func() (string, error) { return "", fmt.Errorf("health not configured") }}
if command == "init" { if command == "experimental-request-check" {
err = managedExperimentalRequest(dir, false, nil)
} else if command == "init" {
err = managedInitialize(m) err = managedInitialize(m)
} else if err = managedCheckIdentity(m); err == nil { } else if err = managedCheckIdentity(m); err == nil {
if command == "reconcile" { if command == "reconcile" {
@@ -389,7 +402,15 @@ func managedCLI(args []string, stdout, stderr io.Writer, d managedDeps) int {
} else if command == "status" || command == "active-ids" { } else if command == "status" || command == "active-ids" {
err = managedReport(m, stdout, d.openDB, command == "active-ids", len(args) == 2 && args[1] == "--assets") err = managedReport(m, stdout, d.openDB, command == "active-ids", len(args) == 2 && args[1] == "--assets")
} else if command == "experiment" { } else if command == "experiment" {
err = managedExperimentalSuffix(m, d) startup := false
for i := 1; i < len(args); i += 2 {
startup = startup || args[i] == "--googlevideo-request"
}
if startup {
err = managedExperimentalRequest(dir, true, func() error { return managedExperimentalSuffix(m, d) })
} else {
err = managedExperimentalSuffix(m, d)
}
} else { } else {
expected := map[int64]string{} expected := map[int64]string{}
var scopes []GooglevideoScope var scopes []GooglevideoScope
@@ -407,7 +428,14 @@ func managedCLI(args []string, stdout, stderr io.Writer, d managedDeps) int {
expected[id] = group expected[id] = group
} }
} }
err = managedActivate(m, d, ids, expected, scopes...) journal, loadErr := m.load()
if loadErr != nil {
err = loadErr
} else if journal.Scope == GooglevideoScopeExperimental && len(scopes) == 0 {
err = fmt.Errorf("experimental CLI apply requires explicit guarded operator path")
} else {
err = managedActivate(m, d, ids, expected, scopes...)
}
} }
} }
if err != nil { if err != nil {
@@ -2,10 +2,87 @@ package main
import ( import (
"crypto/sha256" "crypto/sha256"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath"
"syscall"
) )
const managedExperimentalRequestName = ".autotune-experimental-suffix-request"
func validExperimentalRequestStat(stat *syscall.Stat_t) bool {
return stat != nil && stat.Mode&(syscall.S_IFMT|07777) == syscall.S_IFREG|0600 && stat.Uid == uint32(os.Geteuid()) && stat.Nlink == 1 && stat.Size == 0
}
// A private directory excludes untrusted renames. Claim the validated inode
// before apply so no later cleanup can delete a replacement operator request.
// Failed claims stay private for diagnosis; never overwrite/retry them silently.
func managedExperimentalRequest(dir string, consume bool, apply func() error) error {
if err := managedDirectory(dir); err != nil {
return err
}
path := filepath.Join(dir, managedExperimentalRequestName)
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
if errors.Is(err, syscall.ENOENT) {
return nil
}
invalid := fmt.Errorf("unsafe experimental startup request")
if err != nil {
return invalid
}
f := os.NewFile(uintptr(fd), "experimental request")
defer f.Close()
info, err := f.Stat()
if err != nil {
return invalid
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || !validExperimentalRequestStat(stat) {
return invalid
}
if !consume {
return nil
}
if apply == nil {
return invalid
}
claim, err := os.CreateTemp(dir, ".autotune-experimental-request-claim-*")
if err != nil {
return err
}
claimPath := claim.Name()
if err := claim.Close(); err != nil {
return err
}
if err := os.Rename(path, claimPath); err != nil {
return err
}
claimed, err := os.Lstat(claimPath)
if err != nil || !os.SameFile(info, claimed) {
return invalid
}
claimedStat, ok := claimed.Sys().(*syscall.Stat_t)
if !ok || !validExperimentalRequestStat(claimedStat) {
return invalid
}
transaction := &managedTransaction{Dir: dir}
if err := transaction.syncDir(); err != nil {
return err
}
if err := apply(); err != nil {
return err
}
claimed, err = os.Lstat(claimPath)
if err != nil || !os.SameFile(info, claimed) {
return invalid
}
if err := os.Remove(claimPath); err != nil {
return err
}
return transaction.syncDir()
}
// Runs before the PID-1-owned monitor starts; never races a recovery worker. // Runs before the PID-1-owned monitor starts; never races a recovery worker.
// A real Player-discovered identity is saved WITHOUT cold/adaptive evidence. // A real Player-discovered identity is saved WITHOUT cold/adaptive evidence.
func managedExperimentalSuffix(m *managedTransaction, d managedDeps) error { func managedExperimentalSuffix(m *managedTransaction, d managedDeps) error {
@@ -5,8 +5,13 @@ import (
"context" "context"
"database/sql" "database/sql"
"errors" "errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect" "reflect"
"strings" "strings"
"syscall"
"testing" "testing"
) )
@@ -114,6 +119,9 @@ func TestExperimentalSuffixCLIExplicit(t *testing.T) {
{"apply", "--googlevideo-experiment", "native-circular"}, {"apply", "--googlevideo-experiment", "native-circular"},
{"apply", "--googlevideo-experiment", "native-circular", "--googlevideo-scope", "suffix"}, {"apply", "--googlevideo-experiment", "native-circular", "--googlevideo-scope", "suffix"},
{"apply", "--googlevideo-experiment", "unknown", "--googlevideo-scope", string(GooglevideoScopeExperimental)}, {"apply", "--googlevideo-experiment", "unknown", "--googlevideo-scope", string(GooglevideoScopeExperimental)},
{"apply", "--googlevideo-candidate", "3", "--googlevideo-scope", string(GooglevideoScopeExperimental)},
{"apply", "--frontend-candidate", "1", "--googlevideo-candidate", "3", "--asset-candidate", "2", "--googlevideo-scope", string(GooglevideoScopeExperimental)},
{"apply", "--googlevideo-request", "startup", "--googlevideo-candidate", "3"},
} { } {
if _, _, err := managedArguments(args); err == nil { if _, _, err := managedArguments(args); err == nil {
t.Fatal("implicit experiment", args) t.Fatal("implicit experiment", args)
@@ -121,6 +129,167 @@ func TestExperimentalSuffixCLIExplicit(t *testing.T) {
} }
} }
func TestExperimentalSuffixCLIRejectsBypassBeforeWork(t *testing.T) {
d, _, _ := managedCLIFixture(t)
d.lookup = func(string) (string, bool) { t.Fatal("bypass reached runtime work"); return "", false }
d.player = func(context.Context, []string, io.Writer, io.Writer) error {
t.Fatal("bypass requested Player")
return nil
}
code, _, _ := callManaged(t, d, "apply", "--googlevideo-candidate", "3", "--googlevideo-scope", string(GooglevideoScopeExperimental))
if code != 2 {
t.Fatal(code)
}
}
func TestExperimentalRequestValidationAndConsumption(t *testing.T) {
for _, kind := range []string{"valid", "content", "mode", "directory", "symlink", "dangling", "hardlink", "fifo", "owner", "apply-failure", "replacement"} {
t.Run(kind, func(t *testing.T) {
dir := t.TempDir()
if err := os.Chmod(dir, 0700); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, managedExperimentalRequestName)
if err := os.WriteFile(path, nil, 0600); err != nil {
t.Fatal(err)
}
switch kind {
case "content":
if err := os.WriteFile(path, []byte("not empty"), 0600); err != nil {
t.Fatal(err)
}
case "mode":
if err := os.Chmod(path, 0640); err != nil {
t.Fatal(err)
}
case "directory":
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(path, 0700); err != nil {
t.Fatal(err)
}
case "symlink", "dangling":
target := filepath.Join(dir, "operator-file")
if err := os.Rename(path, target); err != nil {
t.Fatal(err)
}
if kind == "dangling" {
target += "-missing"
}
if err := os.Symlink(target, path); err != nil {
t.Fatal(err)
}
case "hardlink":
if err := os.Link(path, filepath.Join(dir, "operator-file")); err != nil {
t.Fatal(err)
}
case "fifo":
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(path, 0600); err != nil {
t.Fatal(err)
}
case "owner":
if os.Geteuid() != 0 {
t.Skip("real wrong-UID fixture requires root; fstat owner unit check runs separately")
}
if err := os.Chown(path, 1, -1); err != nil {
t.Fatal(err)
}
}
before, err := os.Lstat(path)
if err != nil {
t.Fatal(err)
}
calls := 0
apply := func() error {
calls++
if kind == "replacement" {
return os.WriteFile(path, []byte("new request: retain"), 0600)
}
if kind == "apply-failure" {
return errors.New("apply failed")
}
return nil
}
if kind != "valid" && kind != "apply-failure" && kind != "replacement" {
if err := managedExperimentalRequest(dir, false, nil); err == nil {
t.Fatal("unsafe preflight accepted")
}
if err := managedExperimentalRequest(dir, true, apply); err == nil || calls != 0 {
t.Fatal("unsafe request applied", calls, err)
}
after, err := os.Lstat(path)
if err != nil || !os.SameFile(before, after) {
t.Fatal("unsafe operator file removed/replaced", err)
}
return
}
if err := managedExperimentalRequest(dir, false, nil); err != nil {
t.Fatal(err)
}
err = managedExperimentalRequest(dir, true, apply)
if kind == "apply-failure" {
if err == nil || calls != 1 {
t.Fatal("failure lost", calls, err)
}
claims, err := filepath.Glob(filepath.Join(dir, ".autotune-experimental-request-claim-*"))
if err != nil || len(claims) != 1 {
t.Fatal("failed claim lost", claims, err)
}
return
}
if err != nil || calls != 1 {
t.Fatal(calls, err)
}
if kind == "replacement" {
body, err := os.ReadFile(path)
if err != nil || string(body) != "new request: retain" {
t.Fatal("replacement deleted", err)
}
return
}
if err := managedExperimentalRequest(dir, true, apply); err != nil || calls != 1 {
t.Fatal("request repeated", calls, err)
}
})
}
}
func TestExperimentalRequestWrongOwnerStat(t *testing.T) {
stat := syscall.Stat_t{Mode: syscall.S_IFREG | 0600, Uid: uint32(os.Geteuid()), Nlink: 1}
if !validExperimentalRequestStat(&stat) {
t.Fatal("valid runtime-owned stat rejected")
}
stat.Uid++
if validExperimentalRequestStat(&stat) {
t.Fatal("foreign owner accepted")
}
}
func TestExperimentalSuffixCLIRejectsInheritedPolicy(t *testing.T) {
d, _, _ := managedCLIFixture(t)
initManagedCLI(t, d)
db := testStore(t)
front := managedCandidateFixture(t, db, "frontend", "www.youtube.com", "--lua-desync=fake", true)
asset := unitAssetCandidate(t, db, "i.ytimg.com", "--lua-desync=fake", true)
id := managedCandidateFixture(t, db, "googlevideo", "rr1---sn-alpha.googlevideo.com", managedGooglevideoArgs, false)
m := &managedTransaction{Dir: d.directory, Name: "config", Reload: func() error { return nil }, Health: func() (string, error) { return "OK", nil }}
if err := m.Apply(db, []int64{front, asset, id}, GooglevideoScopeExperimental); err != nil {
t.Fatal(err)
}
d.player = func(context.Context, []string, io.Writer, io.Writer) error {
t.Fatal("inherited bypass requested Player")
return nil
}
code, _, diagnostic := callManaged(t, d, "apply", "--googlevideo-candidate", fmt.Sprint(id))
if code != 1 || !strings.Contains(diagnostic, "explicit guarded operator path") {
t.Fatal(code, diagnostic)
}
}
func TestExperimentalSuffixPreparedRollback(t *testing.T) { func TestExperimentalSuffixPreparedRollback(t *testing.T) {
db := testStore(t) db := testStore(t)
front := managedCandidateFixture(t, db, "frontend", "www.youtube.com", "--lua-desync=fake", true) front := managedCandidateFixture(t, db, "frontend", "www.youtube.com", "--lua-desync=fake", true)
+3 -2
View File
@@ -57,7 +57,8 @@ for command, seconds in (("/usr/local/bin/zapret-autotune managed init", 45),
("/opt/zapret2/init.d/sysv/zapret2 start", 30)): ("/opt/zapret2/init.d/sysv/zapret2 start", 30)):
assert f"timeout -k 5 {seconds} {command} || exit 78" in entrypoint assert f"timeout -k 5 {seconds} {command} || exit 78" in entrypoint
assert entrypoint.index("managed reconcile || exit 78") < entrypoint.index("zapret2 start || exit 78") assert entrypoint.index("managed reconcile || exit 78") < entrypoint.index("zapret2 start || exit 78")
experimental = 'managed apply --googlevideo-experiment native-circular --googlevideo-scope experimental_googlevideo_suffix || exit 78' experimental = 'managed apply --googlevideo-experiment native-circular --googlevideo-scope experimental_googlevideo_suffix --googlevideo-request startup || exit 78'
assert entrypoint.index('zapret2 start || exit 78') < entrypoint.index(experimental) assert entrypoint.index('zapret2 start || exit 78') < entrypoint.index(experimental)
assert entrypoint.index(experimental) < entrypoint.index('setsid /bin/sh /opt/managed-target-supervision.sh --monitor') assert entrypoint.index(experimental) < entrypoint.index('setsid /bin/sh /opt/managed-target-supervision.sh --monitor')
assert entrypoint.index(experimental) < entrypoint.index('rm "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request"') assert entrypoint.index('managed experimental-request-check || exit 78') < entrypoint.index('managed init || exit 78')
assert 'rm "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request"' not in entrypoint
+4 -3
View File
@@ -181,6 +181,8 @@ until awk '$2 == "00000000:0438" && $4 == "0A" { found=1 } END { exit !found }'
[ "$attempt" -lt 30 ] || { echo 'error: target SOCKS listener timeout' >&2; return 75; } [ "$attempt" -lt 30 ] || { echo 'error: target SOCKS listener timeout' >&2; return 75; }
pause 1 pause 1
done done
# Reject unsafe operator requests before init/reconcile can mutate owned state.
timeout -k 5 45 /usr/local/bin/zapret-autotune managed experimental-request-check || exit 78
if [ ! -e "$ZAPRET_CONFIG" ]; then if [ ! -e "$ZAPRET_CONFIG" ]; then
timeout -k 5 45 /usr/local/bin/zapret-autotune managed init || exit 78 timeout -k 5 45 /usr/local/bin/zapret-autotune managed init || exit 78
fi fi
@@ -192,9 +194,8 @@ timeout -k 5 30 /opt/zapret2/init.d/sysv/zapret2 start || exit 78
# Private operator request, consumed only after a successful guarded transaction. # Private operator request, consumed only after a successful guarded transaction.
# Never suppress qualification gates globally or race the owned monitor. # Never suppress qualification gates globally or race the owned monitor.
if [ -e "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request" ]; then if [ -e "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request" ] || [ -L "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request" ]; then
timeout -k 5 120 /usr/local/bin/zapret-autotune managed apply --googlevideo-experiment native-circular --googlevideo-scope experimental_googlevideo_suffix || exit 78 timeout -k 5 120 /usr/local/bin/zapret-autotune managed apply --googlevideo-experiment native-circular --googlevideo-scope experimental_googlevideo_suffix --googlevideo-request startup || exit 78
rm "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request"
fi fi
# A replacement SS child can fail during reconciliation/activation. Do not # A replacement SS child can fail during reconciliation/activation. Do not