ARTEX/server/isolation.go
BaaRai e3a54ef3ea sec(p0): fail-closed startup, atomic secret rotation, scoped target-gate backfill, and kernel kill-switch
- Startup fail-closed: LockDownKeyDir explicitly chmods 0700 an existing key
  dir (counteracting host bind mounts) and 0600 existing key files; adds keys/
  itself alongside jwt.key, secret.key, and config.json to IsolationSelfTest;
  makes IsolationSelfTest fatal unless ARTEX_ALLOW_UNISOLATED=1 is set.
- Secret rotation: adds db.RotateSecretKey (single atomic transaction
  re-encrypting all sealed columns/settings and bumping auth.password_version),
  cmd/artex -rotate-secrets, scripts/rotate-secrets.sh, and OPS/SECURITY docs.
- Scoped defaults, backfill & posture warnings: TargetGate defaults ON for
  tasks with CompanyIDs or InterceptRules (explicit opt-out persisted in
  tasks.target_gate_opt_out); migration 0022_target_gate_backfill.sql backfills
  existing active scoped tasks that did not explicitly opt out; egress-guard
  defaults to EGRESS_MODE=enforce when scope lists exist; loud startup warning
  when target gate or egress enforcement is off.
- Kernel-backed local kill-switch: enables PR_SET_CHILD_SUBREAPER and scans
  /proc (without trusting agent-writable state) on Engine.Pause/BeginDelete to
  kill escaped setsid, nohup, and nested double-fork daemons (plus all
  execPriv.UID processes in isolated mode) within <= 5s with zero post-pause
  egress.
2026-11-30 17:41:46 +01:00

170 lines
7 KiB
Go

package server
import (
"fmt"
"log"
"os"
"strings"
)
// Startup self-test of agent isolation. Before the stores open, the server checks
// that what an agent can run really is isolated from it: IsolationSelfTest
// (isolation_unix.go) starts a probe through the Bash shim, the way the agent's Bash
// starts, and checks from inside it that it runs as the executor, cannot read the
// server's secrets or its process, sees only the allowlisted environment and cannot
// open a database session without the server's password; it also checks that the
// file tools cannot read the secrets. EnforceIsolation then decides the start:
//
// - The self-test passes: the server starts isolated.
// - Linux with the privilege drop on (the server is root, as in the Docker image):
// isolation is expected there and the self-test shows it is broken, so the start
// stops. The development escape -dev-insecure-no-isolation, off by default, lets
// it go on degraded.
// - Anywhere else (not Linux, the server is not root, or -exec-uid=-1): isolation
// cannot be built on that host, so the server starts degraded without any flag.
// The systemd unit (non-root), dev.sh, Windows and macOS start as before.
//
// A degraded start logs a warning banner that says what is exposed, and reports the
// state in GET /api/health to a signed-in caller, which the web UI shows as a
// banner on every page.
// DevNoIsolationFlag is the legacy command-line flag alias of the development escape.
const DevNoIsolationFlag = "dev-insecure-no-isolation"
// AllowUnisolatedEnv is the explicit environment opt-out that lets ARTEX start
// when IsolationSelfTest fails. Must be set to "1" to bypass fail-closed startup.
const AllowUnisolatedEnv = "ARTEX_ALLOW_UNISOLATED"
// AllowUnisolatedFromEnv reports whether ARTEX_ALLOW_UNISOLATED=1 is set.
func AllowUnisolatedFromEnv() bool {
return strings.TrimSpace(os.Getenv(AllowUnisolatedEnv)) == "1"
}
// The isolation modes the server reports.
const (
IsolationIsolated = "isolated"
IsolationDegraded = "degraded"
)
// IsolationStatus is the agent isolation the server runs with.
type IsolationStatus struct {
Mode string `json:"mode"`
// Reason is the self-test failure of a degraded start.
Reason string `json:"reason,omitempty"`
}
// WithIsolationStatus records the result of EnforceIsolation for GET /api/health.
func WithIsolationStatus(st IsolationStatus) Option {
return func(s *Server) { s.isolation = st }
}
// IsolationTargets are the server's paths and database the self-test checks the
// executor cannot reach.
type IsolationTargets struct {
DataDir string
KeyDir string
ConfigPath string
SkillDir string
// DSN is the server's database DSN; only its hosts, ports, user and database
// name reach the probe, never its password.
DSN string
}
// EnforceIsolation decides the start from the self-test result. Startup is
// fail-closed on every platform and privilege mode: a failed self-test stops
// the server unless ARTEX_ALLOW_UNISOLATED=1 (or -dev-insecure-no-isolation)
// is explicitly set.
func EnforceIsolation(goos string, p ExecPrivilege, selfTest error, allowUnisolated bool) (IsolationStatus, error) {
if selfTest == nil {
log.Printf("[isolation] self-test passed: agent processes and file tools run as the executor and cannot reach the server's secrets")
if allowUnisolated {
log.Printf("[isolation] %s=1 / -%s is set and not needed: the self-test passed", AllowUnisolatedEnv, DevNoIsolationFlag)
}
return IsolationStatus{Mode: IsolationIsolated}, nil
}
if !allowUnisolated {
return IsolationStatus{}, fmt.Errorf("agent isolation self-test failed: %v. Startup is fail-closed: fix the isolation error above, or set %s=1 (or pass -%s) for explicit development-only opt-out", selfTest, AllowUnisolatedEnv, DevNoIsolationFlag)
}
logDegradedBanner(selfTest, isolationRequired(goos, p))
return IsolationStatus{Mode: IsolationDegraded, Reason: selfTest.Error()}, nil
}
// isolationRequired reports whether the host can isolate agents, so that a failed
// self-test means broken isolation: Linux, with the privilege drop on (root).
func isolationRequired(goos string, p ExecPrivilege) bool {
return goos == "linux" && p.Enabled
}
// degradedBanner is the warning a degraded start logs when ARTEX_ALLOW_UNISOLATED=1
// (or -dev-insecure-no-isolation) explicitly overrides fail-closed startup.
func degradedBanner(cause error, canIsolate bool) []string {
bar := strings.Repeat("!", 78)
why := "!! " + AllowUnisolatedEnv + "=1 is set (host cannot isolate agents without Linux root + -exec-uid). DEVELOPMENT ONLY."
if canIsolate {
why = "!! " + AllowUnisolatedEnv + "=1 / -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY."
}
lines := []string{bar, "!! AGENT ISOLATION IS DEGRADED."}
lines = append(lines, strings.Split(why, "\n")...)
return append(lines,
"!! Self-test failure: "+cause.Error(),
"!! Agent shells, custom tools, MCP stdio servers and the file tools may read the",
"!! server's keys (JWT signing key, secret key), its config, its database",
"!! credentials and its process, and may change skills and tools on disk.",
"!! Do not use this mode on a server that holds real targets or credentials.",
bar,
)
}
func logDegradedBanner(cause error, escaped bool) {
for _, line := range degradedBanner(cause, escaped) {
log.Print("[isolation] " + line)
}
}
// SecurityPostureCheck describes startup posture warnings for target gating and egress enforcement.
type SecurityPostureCheck struct {
EgressMode string
UngatedActiveTasks int
TargetGateOptedOut bool
}
// SecurityStartupWarnings builds loud operator warnings when egress enforcement
// or target gating is disabled. Returns nil when both protections are active.
func SecurityStartupWarnings(c SecurityPostureCheck) []string {
var warnings []string
mode := strings.ToLower(strings.TrimSpace(c.EgressMode))
if mode != "enforce" {
if mode == "" {
mode = "unset/off"
}
warnings = append(warnings,
fmt.Sprintf("EGRESS ENFORCEMENT IS OFF (EGRESS_MODE=%s): outbound connections from agent commands are not restricted by egress-guard. Enable docker-compose.egress.yml with EGRESS_MODE=enforce and populate egress-guard/lists/scope-domains.txt.", mode),
)
}
if c.TargetGateOptedOut {
warnings = append(warnings,
"TARGET GATE IS OFF BY OPT-OUT: agent commands may contact unapproved hosts without operator confirmation.",
)
}
if c.UngatedActiveTasks > 0 {
warnings = append(warnings,
fmt.Sprintf("TARGET GATE IS OFF ON %d ACTIVE TASK(S): those tasks can contact arbitrary hosts without target-gate approval. Enable target_gate on scoped tasks.", c.UngatedActiveTasks),
)
}
return warnings
}
// LogSecurityStartupWarnings logs a prominent warning banner for each active posture gap.
func LogSecurityStartupWarnings(c SecurityPostureCheck) {
warnings := SecurityStartupWarnings(c)
if len(warnings) == 0 {
return
}
bar := strings.Repeat("!", 78)
log.Print("[security] " + bar)
log.Print("[security] !! SECURITY POSTURE WARNING")
for _, w := range warnings {
log.Print("[security] !! " + w)
}
log.Print("[security] " + bar)
}