mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 04:14:15 +00:00
Norma writes transcripts and noa archives with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation. LockDownPrivateDataDirs walks <data>/transcripts and <data>/noa under an os.Root at the data directory: each directory keeps at most 0700 and each regular file at most 0600, a narrower mode is kept, and every change goes through the descriptor that was checked. A symlink, a hard-linked file, any other entry and a directory not owned by the server are refused and left as they are. cmd/artex runs it with the key directory lockdown, so a refusal or a failed chmod fails the start unless ARTEX_ALLOW_UNISOLATED=1 is set; NewManager runs it too and only logs. Norma's Grep runs an unpinned npm install of @vscode/ripgrep when rg is missing unless NORMA_RIPGREP_NO_INSTALL is non-empty. NewManager now always sets it to 1, so an empty value cannot re-enable the install.
470 lines
18 KiB
Go
470 lines
18 KiB
Go
// Command artex runs the ARTEX backend: the dual PostgreSQL graph stores,
|
|
// the event-driven exploration engine, and the JSON HTTP API consumed by the
|
|
// shadcn/ui frontend.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/Autumn-27/artex/agent"
|
|
"github.com/Autumn-27/artex/config"
|
|
"github.com/Autumn-27/artex/db"
|
|
"github.com/Autumn-27/artex/egress"
|
|
"github.com/Autumn-27/artex/sandbox"
|
|
"github.com/Autumn-27/artex/server"
|
|
)
|
|
|
|
// configSnapshot is the single startup log line describing the effective
|
|
// configuration. It carries no credential material: the DSN is passed through
|
|
// config.Redact, and no key or token value is ever included.
|
|
type configSnapshot struct {
|
|
Version string `json:"version"`
|
|
ConfigFile string `json:"config_file"`
|
|
ConfigFileFound bool `json:"config_file_found"`
|
|
PGDSN string `json:"pg_dsn"`
|
|
PGDSNSource string `json:"pg_dsn_source"`
|
|
DataDir string `json:"data_dir"`
|
|
SkillDir string `json:"skill_dir"`
|
|
KeyDir string `json:"key_dir"`
|
|
Addr string `json:"addr"`
|
|
Proxy string `json:"proxy"`
|
|
NoiseProfile string `json:"noise_profile"`
|
|
UntrustedBoundary bool `json:"untrusted_boundary"`
|
|
TrustedProxies []string `json:"trusted_proxies"`
|
|
}
|
|
|
|
// logConfigSnapshot emits one structured line so an operator can reproduce the
|
|
// exact configuration of a run from the logs. A serialization failure is
|
|
// reported but never aborts startup.
|
|
func logConfigSnapshot(s configSnapshot) {
|
|
b, err := json.Marshal(s)
|
|
if err != nil {
|
|
slog.Warn("[config] snapshot unavailable", "err", err)
|
|
return
|
|
}
|
|
slog.Info("[config] snapshot " + string(b))
|
|
}
|
|
|
|
// version is the build version, injected at release time via
|
|
// -ldflags "-X main.version=<tag>". Defaults to "dev" for local builds.
|
|
var version = "dev"
|
|
|
|
// revision is the full source commit, injected via
|
|
// -ldflags "-X main.revision=<sha>". Empty when the build had no git context.
|
|
var revision = ""
|
|
|
|
const banner = `
|
|
_ ____ _____ _______ __
|
|
/ \ | _ \_ _| ____\ \/ /
|
|
/ _ \ | |_) || | | _| \ /
|
|
/ ___ \| _ < | | | |___ / \
|
|
/_/ \_\_| \_\|_| |_____/_/\_\
|
|
`
|
|
|
|
// printBanner writes the startup banner + version/runtime info to stdout.
|
|
func printBanner(addr string) {
|
|
fmt.Print(banner)
|
|
fmt.Println(" AI autonomous penetration testing system")
|
|
fmt.Printf(" version %s · %s/%s · %s · listening on %s\n\n",
|
|
version, runtime.GOOS, runtime.GOARCH, runtime.Version(), addr)
|
|
}
|
|
|
|
// main maps run's result onto the process exit code. The body lives in a
|
|
// function that can *return* rather than os.Exit, so its own defers still run.
|
|
func main() {
|
|
// Started as the Bash shim or as an MCP drop command: drop the identity and exec
|
|
// the real program. It returns only for an ordinary start.
|
|
server.RunExecShimIfRequested(os.Args)
|
|
// Before any listener or child exists: keep the secrets out of /proc/<pid>/environ.
|
|
server.SealProcessEnv()
|
|
os.Exit(run())
|
|
}
|
|
|
|
// flagWasSet reports whether the operator passed the named flag.
|
|
func flagWasSet(name string) bool {
|
|
set := false
|
|
flag.Visit(func(f *flag.Flag) {
|
|
if f.Name == name {
|
|
set = true
|
|
}
|
|
})
|
|
return set
|
|
}
|
|
|
|
func run() int {
|
|
var (
|
|
addr = flag.String("addr", "127.0.0.1:8787", "HTTP listen address")
|
|
dataDir = flag.String("data", filepath.Join(config.BaseDir(), "data"), "runtime data directory: traffic index, task files, transcripts (default: data/ next to the executable)")
|
|
proxy = flag.String("proxy", "127.0.0.1:8788", "traffic recording proxy address (empty to disable)")
|
|
// Identity of every agent process (Bash, the shell, custom tools, MCP stdio).
|
|
// A negative uid turns the drop off; 0 (root) is refused.
|
|
execUID = flag.Int("exec-uid", server.DefaultExecUID, "uid that agent processes run as (Bash, shell, custom tools, MCP stdio); -1 turns the drop off")
|
|
execGID = flag.Int("exec-gid", server.DefaultExecGID, "gid that agent processes run as")
|
|
// Opt-in shared Chromium for live view and operator take-over in the web UI.
|
|
// Disabled by default so each agent run keeps its own private headless browser.
|
|
sharedBrowser = flag.Bool("shared-browser", envBool("ARTEX_SHARED_BROWSER", false), "opt-in: run a shared browser with live view and operator take-over in the web UI; default false gives each agent run a private headless browser (env ARTEX_SHARED_BROWSER)")
|
|
sharedBrowserLockTimeout = flag.Duration("shared-browser-lock-timeout", envDuration("ARTEX_SHARED_BROWSER_LOCK_TIMEOUT", server.DefaultSharedBrowserLockTimeout), "how long an idle operator take-over or ask_operator hold keeps the shared browser before automatically expiring (env ARTEX_SHARED_BROWSER_LOCK_TIMEOUT)")
|
|
// Development escape of the isolation self-test, off by default (prefer ARTEX_ALLOW_UNISOLATED=1).
|
|
devNoIsolation = flag.Bool(server.DevNoIsolationFlag, false, "DEVELOPMENT ONLY: start even when the agent isolation self-test fails (legacy alias for ARTEX_ALLOW_UNISOLATED=1); agent processes and file tools may then read the server's keys, config and database credentials")
|
|
// Offline/atomic secret rotation helper invoked by scripts/rotate-secrets.sh.
|
|
rotateSecrets = flag.Bool("rotate-secrets", false, "re-encrypt database secrets from -rotate-old-secret-file to -rotate-new-secret-file, invalidate active JWT sessions, and exit")
|
|
rotateOldSecretFile = flag.String("rotate-old-secret-file", "", "path to current secret.key (used with -rotate-secrets)")
|
|
rotateNewSecretFile = flag.String("rotate-new-secret-file", "", "path to staged new secret.key (used with -rotate-secrets)")
|
|
// Scope export for the optional egress-guard overlay, invoked by egress-guard/export-scope.sh.
|
|
exportEgressGuardScope = flag.Bool("export-egress-guard-scope", false, "print the operator-approved task scope in the form egress-guard/export-scope.sh reads, and exit")
|
|
exportEgressGuardTasks = flag.String("export-egress-guard-tasks", "", "comma-separated task ids for -export-egress-guard-scope (default: every task that is not finished)")
|
|
)
|
|
flag.Parse()
|
|
|
|
if *rotateSecrets {
|
|
return runRotateSecrets(*rotateOldSecretFile, *rotateNewSecretFile)
|
|
}
|
|
if *exportEgressGuardScope {
|
|
return runExportEgressGuardScope(*exportEgressGuardTasks, os.Stdout)
|
|
}
|
|
|
|
// hand the build version and source revision to the server package so
|
|
// GET /api/health can report them to the frontend top bar.
|
|
server.BuildVersion = version
|
|
server.BuildCommit = revision
|
|
|
|
printBanner(*addr)
|
|
|
|
// capture backend logs into the in-memory sink (still to stderr) so the /logs
|
|
// page can show a live log stream. Do this first, to catch startup logs too.
|
|
server.StartLogCapture()
|
|
|
|
// Resolve every effective setting before starting the stores, then emit a
|
|
// single structured snapshot line. The old code logged the same facts in
|
|
// five scattered lines, which made a run hard to reproduce from logs.
|
|
cfgPath := config.Path() // absolute, so `go run`'s relative CWD is unambiguous
|
|
if abs, e := filepath.Abs(cfgPath); e == nil {
|
|
cfgPath = abs
|
|
}
|
|
_, statErr := os.Stat(cfgPath)
|
|
cfgFound := statErr == nil
|
|
|
|
skillDir, err := config.SkillDir()
|
|
if err != nil {
|
|
slog.Error("[config] skill directory unavailable", "err", err)
|
|
return 1
|
|
}
|
|
if abs, e := filepath.Abs(skillDir); e == nil {
|
|
skillDir = abs
|
|
}
|
|
// JWT signing key directory (also holds secret.key, see server.NewManager).
|
|
keyDir := config.KeyDir()
|
|
// Proxies whose X-Forwarded-For the login rate limit reads; empty trusts none.
|
|
trusted, err := server.ParseTrustedProxies(os.Getenv("ARTEX_TRUSTED_PROXIES"))
|
|
if err != nil {
|
|
slog.Error("[config] invalid ARTEX_TRUSTED_PROXIES", "err", err)
|
|
return 1
|
|
}
|
|
trustedAddrs := make([]string, 0, len(trusted))
|
|
for _, p := range trusted {
|
|
trustedAddrs = append(trustedAddrs, p.String())
|
|
}
|
|
|
|
// NewManager resolves the DSN too, but does so internally. Calling
|
|
// PostgresDSN here is idempotent (no connection, no side effects) and lets
|
|
// the snapshot show the source and a redacted view even on a failed start.
|
|
dsn, dsnSource, dsnErr := config.PostgresDSN()
|
|
if dsnErr != nil {
|
|
dsn, dsnSource = "", "unavailable"
|
|
}
|
|
logConfigSnapshot(configSnapshot{
|
|
Version: version,
|
|
ConfigFile: cfgPath,
|
|
ConfigFileFound: cfgFound,
|
|
PGDSN: config.Redact(dsn),
|
|
PGDSNSource: dsnSource,
|
|
DataDir: *dataDir,
|
|
SkillDir: skillDir,
|
|
KeyDir: keyDir,
|
|
Addr: *addr,
|
|
Proxy: *proxy,
|
|
NoiseProfile: egress.ProfileFromEnv().Name,
|
|
UntrustedBoundary: agent.UntrustedBoundaryEnabled(),
|
|
TrustedProxies: trustedAddrs,
|
|
})
|
|
|
|
// Agent processes run as the executor identity, never as the server's root (see
|
|
// server/execpriv.go). An explicit option that cannot be applied stops the start.
|
|
priv, err := server.ResolveExecPrivilege(*execUID, *execGID, flagWasSet("exec-uid") || flagWasSet("exec-gid"))
|
|
if err != nil {
|
|
slog.Error("[config] resolve exec privilege failed", "err", err)
|
|
return 1
|
|
}
|
|
if err := server.PrepareExecPrivilege(&priv, *dataDir, config.KeyDir(), config.Path()); err != nil {
|
|
slog.Error("[config] prepare exec privilege failed", "err", err)
|
|
return 1
|
|
}
|
|
if err := server.InstallBashShim(priv); err != nil {
|
|
slog.Error("[config] install bash shim failed", "err", err)
|
|
return 1
|
|
}
|
|
// Tighten an existing key directory before running the isolation self-test:
|
|
// a host bind mount (typically 0755) masks the image's 0700.
|
|
// The transcripts and noa archives (whole conversations) too: Norma leaves
|
|
// them 0755/0644, readable by the executor.
|
|
keyLockErr := errors.Join(server.LockDownKeyDir(keyDir), server.LockDownCAKey(*dataDir), server.LockDownPrivateDataDirs(*dataDir))
|
|
// Before the stores open and any agent runs: check that the isolation above holds
|
|
// (server/isolation.go). Startup is fail-closed unless ARTEX_ALLOW_UNISOLATED=1
|
|
// (or -dev-insecure-no-isolation) is explicitly set.
|
|
selfTest := server.IsolationSelfTest(priv, server.IsolationTargets{
|
|
DataDir: *dataDir, KeyDir: keyDir, ConfigPath: cfgPath, SkillDir: skillDir, DSN: dsn,
|
|
})
|
|
if keyLockErr != nil {
|
|
selfTest = errors.Join(keyLockErr, selfTest)
|
|
}
|
|
allowUnisolated := server.AllowUnisolatedFromEnv() || *devNoIsolation
|
|
isolation, err := server.EnforceIsolation(runtime.GOOS, priv, selfTest, allowUnisolated)
|
|
if err != nil {
|
|
slog.Error("[config] enforce isolation failed", "err", err)
|
|
return 1
|
|
}
|
|
|
|
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
ctx, shutdown := shutdownContext(sigCtx)
|
|
defer shutdown(agent.AbortShutdown)
|
|
|
|
mgr, err := server.NewManager(*dataDir, *proxy)
|
|
if err != nil {
|
|
log.Fatalf("open stores: %v", err)
|
|
}
|
|
defer mgr.Close()
|
|
|
|
// This log is a startup snapshot. The operator UI reads current posture through
|
|
// the authenticated API, so later task changes never rely on this old count.
|
|
postureCheck := server.SecurityPostureCheck{EgressMode: os.Getenv("EGRESS_MODE")}
|
|
postureCtx, cancelPostureRead := context.WithTimeout(ctx, 5*time.Second)
|
|
posture, postureErr := mgr.PG().GetTargetGatePosture(postureCtx)
|
|
cancelPostureRead()
|
|
if postureErr != nil {
|
|
postureCheck.TargetGatePostureUnavailable = true
|
|
} else {
|
|
postureCheck.UngatedActiveTasks = posture.UngatedUnfinishedTasks
|
|
postureCheck.TargetGateOptedOut = posture.ExplicitOptOutTasks > 0
|
|
}
|
|
server.LogSecurityStartupWarnings(postureCheck)
|
|
|
|
sandboxCfg, err := sandbox.PanelConfigFromEnv()
|
|
if err != nil {
|
|
slog.Error("[sandbox] invalid configuration", "err", err)
|
|
return 1
|
|
}
|
|
var sandboxClient server.SandboxClient
|
|
if sandboxCfg.Mode == sandbox.ModeRequired {
|
|
sandboxClient = sandbox.NewClient(sandboxCfg.RunnerURL, sandboxCfg.RunnerToken)
|
|
hctx, hcancel := context.WithTimeout(ctx, 5*time.Second)
|
|
h, herr := sandboxClient.Health(hctx)
|
|
hcancel()
|
|
if herr != nil || !h.OK || !h.Docker {
|
|
slog.Warn("[sandbox] ARTEX_SANDBOX=required: runner is currently unavailable; tasks will be refused until artex-runner is healthy", "runner_url", sandboxCfg.RunnerURL, "err", herr)
|
|
} else {
|
|
slog.Info("[sandbox] ARTEX_SANDBOX=required: connected to artex-runner", "runner_url", sandboxCfg.RunnerURL, "workers", h.Workers, "version", h.Version)
|
|
}
|
|
} else {
|
|
server.LogSandboxOffBanner()
|
|
}
|
|
|
|
srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout), server.WithSandbox(sandboxClient, sandboxCfg.Mode))
|
|
// ReadTimeout bounds how long the request headers and body may take to arrive.
|
|
// It does not limit how long a handler runs, so an event stream stays open.
|
|
// WriteTimeout is left unset: a write deadline would cut that stream.
|
|
httpSrv := &http.Server{
|
|
Addr: *addr,
|
|
Handler: srv.Handler(),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
ReadTimeout: 30 * time.Minute,
|
|
IdleTimeout: 2 * time.Minute,
|
|
}
|
|
|
|
go func() {
|
|
slog.Info("ARTEX backend listening", "version", version, "addr", *addr, "data", *dataDir, "workers", mgr.Workers())
|
|
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("serve: %v", err)
|
|
}
|
|
}()
|
|
|
|
// Wait for a stop signal.
|
|
<-ctx.Done()
|
|
|
|
slog.Info("shutting down")
|
|
// Close the listener before draining. Otherwise a request accepted during
|
|
// the drain can start a detached run, and mgr.Close runs while that run
|
|
// is still writing.
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
httpErr := httpSrv.Shutdown(shutdownCtx)
|
|
cancel()
|
|
if httpErr != nil {
|
|
slog.Error("http shutdown failed", "err", httpErr)
|
|
}
|
|
drainCtx, drainCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
drainErr := srv.Wait(drainCtx)
|
|
drainCancel()
|
|
if drainErr != nil {
|
|
slog.Error("task drain failed", "err", drainErr)
|
|
}
|
|
// The health writer flushes on ctx.Done(). Wait for it before the deferred
|
|
// store close, so the last cooling window is not written at a closed database.
|
|
srv.FlushLLMHealth()
|
|
if httpErr != nil || drainErr != nil {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// shutdownContext deliberately does not derive from signalCtx. If it did, the
|
|
// parent's plain context.Canceled could win the race before AbortShutdown was
|
|
// attached to the child, losing the diagnostic cause in every running Agent.
|
|
func shutdownContext(signalCtx context.Context) (context.Context, context.CancelCauseFunc) {
|
|
ctx, shutdown := context.WithCancelCause(context.Background())
|
|
go func() {
|
|
select {
|
|
case <-signalCtx.Done():
|
|
shutdown(agent.AbortShutdown)
|
|
case <-ctx.Done():
|
|
}
|
|
}()
|
|
return ctx, shutdown
|
|
}
|
|
|
|
// envBool reads a boolean environment variable, or def when it is unset or not a
|
|
// boolean.
|
|
func envBool(name string, def bool) bool {
|
|
v, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(name)))
|
|
if err != nil {
|
|
return def
|
|
}
|
|
return v
|
|
}
|
|
|
|
// runExportEgressGuardScope prints the egress-guard allowlist derived from the
|
|
// operator-approved task scope. Nothing is written to out unless the whole
|
|
// export succeeded, so a failed run cannot hand the caller a partial list.
|
|
func runExportEgressGuardScope(tasksCSV string, out io.Writer) int {
|
|
var taskIDs []int64
|
|
for _, part := range strings.Split(tasksCSV, ",") {
|
|
part = strings.TrimSpace(part)
|
|
if part == "" {
|
|
continue
|
|
}
|
|
id, err := strconv.ParseInt(part, 10, 64)
|
|
if err != nil || id <= 0 {
|
|
slog.Error("[egress-guard-export] invalid task id in -export-egress-guard-tasks", "value", part)
|
|
return 2
|
|
}
|
|
taskIDs = append(taskIDs, id)
|
|
}
|
|
if strings.TrimSpace(tasksCSV) != "" && len(taskIDs) == 0 {
|
|
slog.Error("[egress-guard-export] -export-egress-guard-tasks names no task")
|
|
return 2
|
|
}
|
|
dsn, _, err := config.PostgresDSN()
|
|
if err != nil {
|
|
slog.Error("[egress-guard-export] database DSN unavailable", "err", err)
|
|
return 1
|
|
}
|
|
pg, err := db.Open(dsn)
|
|
if err != nil {
|
|
slog.Error("[egress-guard-export] open database failed", "err", err)
|
|
return 1
|
|
}
|
|
defer pg.Close()
|
|
|
|
scope, err := server.ExportEgressGuardScope(pg, taskIDs)
|
|
if err != nil {
|
|
slog.Error("[egress-guard-export] export failed, nothing written", "err", err)
|
|
return 1
|
|
}
|
|
if err := scope.Render(out); err != nil {
|
|
slog.Error("[egress-guard-export] write failed", "err", err)
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// runRotateSecrets atomically re-encrypts database secrets from oldPath to
|
|
// newPath and increments auth.password_version to invalidate active sessions.
|
|
func runRotateSecrets(oldPath, newPath string) int {
|
|
if strings.TrimSpace(oldPath) == "" || strings.TrimSpace(newPath) == "" {
|
|
slog.Error("[rotate-secrets] both -rotate-old-secret-file and -rotate-new-secret-file are required")
|
|
return 2
|
|
}
|
|
oldRaw, err := os.ReadFile(oldPath)
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] read old secret key failed", "path", oldPath, "err", err)
|
|
return 1
|
|
}
|
|
newRaw, err := os.ReadFile(newPath)
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] read new secret key failed", "path", newPath, "err", err)
|
|
return 1
|
|
}
|
|
oldKey, err := db.ParseSecretKey(string(oldRaw))
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] invalid old secret key", "err", err)
|
|
return 1
|
|
}
|
|
newKey, err := db.ParseSecretKey(string(newRaw))
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] invalid new secret key", "err", err)
|
|
return 1
|
|
}
|
|
dsn, _, err := config.PostgresDSN()
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] database DSN unavailable", "err", err)
|
|
return 1
|
|
}
|
|
pg, err := db.Open(dsn)
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] open database failed", "err", err)
|
|
return 1
|
|
}
|
|
defer pg.Close()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
rotated, pwdVer, err := pg.RotateSecretKey(ctx, oldKey, newKey, true)
|
|
if err != nil {
|
|
slog.Error("[rotate-secrets] database secret rotation failed", "err", err)
|
|
return 1
|
|
}
|
|
slog.Info("[rotate-secrets] completed", "rotated_values", rotated, "auth_password_version", pwdVer)
|
|
return 0
|
|
}
|
|
|
|
// envDuration reads a Go duration environment variable (or integer seconds),
|
|
// returning def when unset or invalid.
|
|
func envDuration(name string, def time.Duration) time.Duration {
|
|
raw := strings.TrimSpace(os.Getenv(name))
|
|
if raw == "" {
|
|
return def
|
|
}
|
|
if d, err := time.ParseDuration(raw); err == nil && d > 0 {
|
|
return d
|
|
}
|
|
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
|
|
return time.Duration(secs) * time.Second
|
|
}
|
|
return def
|
|
}
|