Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(docker): enhance worker container Docker access configuration
Dmitry Ng131694b8aa1c
diff --git a/.env.example b/.env.exampleindex 1d8ff699..9057c8e2 100644--- a/.env.example+++ b/.env.example@@ -262,6 +262,18 @@ DOCKER_CERT_PATH=DOCKER_INSIDE=false # enable to use docker socket (see security note above; default false)DOCKER_NET_ADMIN=true # enable to use net_admin capabilityDOCKER_SOCKET=/var/run/docker.sock # path on host machine++## Docker daemon the WORKER CONTAINER itself talks to (only used when DOCKER_INSIDE=true).+## Injected into the sandbox as DOCKER_HOST / DOCKER_TLS_VERIFY / DOCKER_CERT_PATH.+## Setting DOCKER_INSIDE_HOST also stops auto-detecting and mounting the host socket,+## so an agent reaches only the daemon you designate — unless DOCKER_SOCKET is set+## explicitly, which still takes precedence and is mounted as before.+## DOCKER_INSIDE_CERT_PATH is resolved on the WORKER NODE and bind-mounted read-only+## at the same path inside the container.+DOCKER_INSIDE_HOST=+DOCKER_INSIDE_TLS_VERIFY=+DOCKER_INSIDE_CERT_PATH=+DOCKER_NETWORK=DOCKER_WORK_DIR=DOCKER_PUBLIC_IP=0.0.0.0 # public ip of host machinediff --git a/README.md b/README.mdindex f9b315d9..b352fb0f 100644--- a/README.md+++ b/README.md@@ -21,6 +21,8 @@- [Architecture](#architecture)- [Agent Supervision](#advanced-agent-supervision)- [Quick Start](#quick-start)+ - [Agent Docker Access](#giving-agents-docker-without-giving-away-the-host)+ - [Running Several Instances](#running-several-instances-tenant_id)- [How to Use PentAGI After Login](#how-to-use-pentagi-after-login)- [API Access](#api-access)- [LLM Provider Configuration](#custom-llm-provider-configuration)@@ -671,6 +673,53 @@ The two-node setup provides:- **Security Boundaries**: Docker-in-Docker with TLS authentication- **OOB Attack Support**: Dedicated port ranges for out-of-band techniques+#### Giving Agents Docker Without Giving Away the Host++Many pentest workflows need `docker` inside the agent's sandbox. There are two ways to provide it, and they differ sharply in risk.++**Recommended — point sandboxes at a hardened dind daemon over TLS.** Set `DOCKER_INSIDE=true`, leave `DOCKER_SOCKET` empty, and configure the daemon the sandbox may talk to:++```bash+DOCKER_INSIDE=true+DOCKER_SOCKET= # mount no socket+DOCKER_INSIDE_HOST=tcp://10.0.0.5:3376 # hardened dind endpoint+DOCKER_INSIDE_TLS_VERIFY=1+DOCKER_INSIDE_CERT_PATH=/etc/docker/dind/certs/client # path on the worker node+```++PentAGI injects these into every worker container as `DOCKER_HOST`, `DOCKER_TLS_VERIFY` and `DOCKER_CERT_PATH` (the `_INSIDE_` segment is dropped) and bind-mounts the certificate directory read-only at the same path, so `docker` works inside the sandbox with no further setup.++**Not recommended — bind-mounting a Docker socket (`DOCKER_SOCKET`).** This has two failure modes:++- **Boot-order race**: a bind-mount source that does not exist yet is created by Docker as a *directory*. After a worker-node reboot, a worker container can start before dind has recreated its socket — Docker then puts a directory where the socket belongs, and dind cannot start until it is removed by hand.+- **Blast radius**: the race is only reliably avoided when the mounted socket is the **host** daemon's, since that one always exists first. But that grants an autonomous agent the host Docker API: it can start a privileged container, mount `/`, and compromise the entire node — PentAGI included.++Use `DOCKER_SOCKET` only on single-node development setups where the host daemon is already trusted.++**See**: [Worker Node Setup](examples/guides/worker_node.md) for the full dind hardening and TLS configuration, and [Worker Docker Access](backend/docs/docker.md#worker-docker-access) for the exact resolution algorithm.++#### Running Several Instances (`TENANT_ID`)++A single PentAGI installation needs none of this — leave `TENANT_ID` empty (the default) and nothing changes.++Set it when several PentAGI installations share external resources: one PostgreSQL server, one worker node, one Neo4j/Graphiti, one Langfuse. The typical case is a management backend per server with a common worker node and database. Because every instance numbers its flows from `1`, they would otherwise collide on container names, database rows, knowledge-graph namespaces and session cookies. `TENANT_ID` namespaces all of it:++| Area | Effect when `TENANT_ID=acme` |+| ---- | ---------------------------- |+| PostgreSQL | The instance creates and works inside schema `acme` instead of `public`; extensions stay shared in `public` |+| Worker containers | `acme-pentagi-terminal-<flow>` instead of `pentagi-terminal-<flow>`; volumes and hostnames follow, and both carry a `pentagi.tenant` label |+| Knowledge graph | Graphiti/Neo4j group ids become `acme-flow-<id>` |+| Auth | Cookie and API token keys are derived from `COOKIE_SIGNING_SALT` **plus** the tenant, and the session cookie is renamed |+| Telemetry | Langfuse traces carry the tenant as their `environment` and a `tenant:acme` tag; OTel resources gain `tenant_id` |++The value must match `^[a-z][a-z0-9_]{0,31}$` — an invalid one aborts startup rather than being silently normalised.++Some things stay yours to set per instance, because they are host resources rather than names: `DATA_DIR` (two instances sharing it **will** overwrite each other's flow data), `DOCKER_PORTS_BASE`, the published ports, and `INSTALLATION_ID`. The effective values are printed at startup under `Instance identity`.++The installer provisions one instance per server. Running several on one server is possible — for example behind a shared nginx — but the stock `docker-compose.yml` uses fixed container and network names, so it has to be adapted to your own network layout first.++**See**: [Multi-Instance Deployment](backend/docs/config.md#multi-instance-deployment-tenant_id) for validation rules, upgrade notes and the full list of operator responsibilities.+### Manual Installation1. Create a working directory or clone the repository:@@ -779,6 +828,7 @@ ASSISTANT_USE_AGENTS=false # Default value for agent usage when creating- `COOKIE_SIGNING_SALT` - Salt for cookie signing, change to random value- `PUBLIC_URL` - Public URL of your server (eg. `https://pentagi.example.com`)- `SERVER_SSL_CRT` and `SERVER_SSL_KEY` - Custom paths to your existing SSL certificate and key for HTTPS (these paths should be used in the docker-compose.yml file to mount as volumes)+- `TENANT_ID` - Leave empty unless this instance shares external resources with another PentAGI installation. When set, it is mixed into the cookie and API token signing keys and renames the session cookie, so a session minted by one instance is rejected by the others even though they share the same `COOKIE_SIGNING_SALT`. See [Running Several Instances](#running-several-instances-tenant_id)### Scraper Access- `SCRAPER_PUBLIC_URL` - Public URL for scraper if you want to use different scraper server for public URLsdiff --git a/backend/cmd/installer/wizard/controller/controller.go b/backend/cmd/installer/wizard/controller/controller.goindex 1db0e088..03c3ce51 100644--- a/backend/cmd/installer/wizard/controller/controller.go+++ b/backend/cmd/installer/wizard/controller/controller.go@@ -1862,6 +1862,13 @@ type DockerConfig struct {DockerTLSVerify loader.EnvVar // DOCKER_TLS_VERIFYHostDockerCertPath loader.EnvVar // PENTAGI_DOCKER_CERT_PATH+ // Daemon endpoint exposed to worker containers when DOCKER_INSIDE is enabled.+ // These mirror the trio above but describe the sandbox's view, and their paths+ // resolve on the worker node rather than on the machine running the installer.+ DockerInsideHost loader.EnvVar // DOCKER_INSIDE_HOST+ DockerInsideTLSVerify loader.EnvVar // DOCKER_INSIDE_TLS_VERIFY+ DockerInsideCertPath loader.EnvVar // DOCKER_INSIDE_CERT_PATH+// computed fields (not directly mapped to env vars)Configured bool}@@ -1880,6 +1887,9 @@ func (c *controller) GetDockerConfig() *DockerConfig {"DOCKER_HOST","DOCKER_TLS_VERIFY","PENTAGI_DOCKER_CERT_PATH",+ "DOCKER_INSIDE_HOST",+ "DOCKER_INSIDE_TLS_VERIFY",+ "DOCKER_INSIDE_CERT_PATH",})config := &DockerConfig{@@ -1894,6 +1904,9 @@ func (c *controller) GetDockerConfig() *DockerConfig {DockerHost: vars["DOCKER_HOST"],DockerTLSVerify: vars["DOCKER_TLS_VERIFY"],HostDockerCertPath: vars["PENTAGI_DOCKER_CERT_PATH"],+ DockerInsideHost: vars["DOCKER_INSIDE_HOST"],+ DockerInsideTLSVerify: vars["DOCKER_INSIDE_TLS_VERIFY"],+ DockerInsideCertPath: vars["DOCKER_INSIDE_CERT_PATH"],}// patch docker host default value@@ -1924,6 +1937,9 @@ func (c *controller) UpdateDockerConfig(config *DockerConfig) error {"DOCKER_HOST": config.DockerHost.Value,"DOCKER_TLS_VERIFY": config.DockerTLSVerify.Value,"PENTAGI_DOCKER_CERT_PATH": config.HostDockerCertPath.Value,+ "DOCKER_INSIDE_HOST": config.DockerInsideHost.Value,+ "DOCKER_INSIDE_TLS_VERIFY": config.DockerInsideTLSVerify.Value,+ "DOCKER_INSIDE_CERT_PATH": config.DockerInsideCertPath.Value,}dockerHost := config.DockerHost.Value@@ -1962,6 +1978,9 @@ func (c *controller) ResetDockerConfig() *DockerConfig {"DOCKER_HOST","DOCKER_TLS_VERIFY","DOCKER_CERT_PATH",+ "DOCKER_INSIDE_HOST",+ "DOCKER_INSIDE_TLS_VERIFY",+ "DOCKER_INSIDE_CERT_PATH",// Volume mapping for docker socket"PENTAGI_DOCKER_SOCKET","PENTAGI_DOCKER_CERT_PATH",@@ -2355,6 +2374,9 @@ func (c *controller) getVariableDescription(varName string) string {"DOCKER_HOST": locale.EnvDesc_DOCKER_HOST,"DOCKER_TLS_VERIFY": locale.EnvDesc_DOCKER_TLS_VERIFY,"DOCKER_CERT_PATH": locale.EnvDesc_DOCKER_CERT_PATH,+ "DOCKER_INSIDE_HOST": locale.EnvDesc_DOCKER_INSIDE_HOST,+ "DOCKER_INSIDE_TLS_VERIFY": locale.EnvDesc_DOCKER_INSIDE_TLS_VERIFY,+ "DOCKER_INSIDE_CERT_PATH": locale.EnvDesc_DOCKER_INSIDE_CERT_PATH,"TENANT_ID": locale.EnvDesc_TENANT_ID,"LICENSE_KEY": locale.EnvDesc_LICENSE_KEY,@@ -2566,6 +2588,9 @@ var criticalVariables = map[string]bool{"DOCKER_HOST": true,"DOCKER_TLS_VERIFY": true,"DOCKER_CERT_PATH": true,+ "DOCKER_INSIDE_HOST": true,+ "DOCKER_INSIDE_TLS_VERIFY": true,+ "DOCKER_INSIDE_CERT_PATH": true,"PENTAGI_DOCKER_SOCKET": true,// observability changesdiff --git a/backend/cmd/installer/wizard/locale/locale.go b/backend/cmd/installer/wizard/locale/locale.goindex 83363148..34bda841 100644--- a/backend/cmd/installer/wizard/locale/locale.go+++ b/backend/cmd/installer/wizard/locale/locale.go@@ -1209,6 +1209,44 @@ const (ServerSettingsLicenseKey = "License Key"ServerSettingsLicenseKeyDesc = "PentAGI License Key in format of XXXX-XXXX-XXXX-XXXX"+ ToolsDockerInsideHost = "Worker Docker Daemon Host"+ ToolsDockerInsideHostDesc = "Daemon endpoint given to worker containers (e.g., tcp://dind:2376); empty keeps socket mounting"++ ToolsDockerInsideTLSVerify = "Worker Docker TLS Verify"+ ToolsDockerInsideTLSVerifyDesc = "Enable TLS verification for the worker container's Docker connection"++ ToolsDockerInsideCertPath = "Worker Docker Certificate Path"+ ToolsDockerInsideCertPathDesc = "TLS certificate directory on the WORKER NODE, mounted read-only into worker containers"++ ToolsDockerInsideHostHelp = `Docker daemon endpoint handed to worker containers when Docker Access is enabled.++It is injected into each sandbox as DOCKER_HOST, so the Docker CLI inside the container talks to this daemon.++Setting it also STOPS the host socket from being auto-detected and bind-mounted into sandboxes: an agent then reaches only the daemon you designated, not the one running PentAGI itself. An explicitly configured Docker Socket still takes precedence and is mounted as before.++Leave empty to keep the historical behaviour (auto-detected socket mount).++Examples:+• tcp://dind:2376+• tcp://10.0.0.5:2375+• unix:///var/run/docker.sock`++ ToolsDockerInsideTLSVerifyHelp = `Enables TLS verification for the worker container's connection to the Docker daemon.++Injected into each sandbox as DOCKER_TLS_VERIFY. Use it together with Worker Docker Daemon Host and Worker Docker Certificate Path when the daemon requires mutual TLS.++Leave disabled for a plain (non-TLS) endpoint.`++ ToolsDockerInsideCertPathHelp = `Directory holding the TLS client material (ca.pem, cert.pem, key.pem) used by worker containers.++Injected into each sandbox as DOCKER_CERT_PATH and bind-mounted read-only at the SAME path, so the value resolves identically inside the container.++IMPORTANT: this path is resolved on the WORKER NODE — the machine whose Docker daemon creates sandbox containers — not on the machine running this installer. It is therefore not validated here; make sure it exists on the worker node.++Examples:+• /etc/docker/certs+• /opt/pentagi/docker/ssl`+ServerSettingsTenantID = "Tenant ID"ServerSettingsTenantIDDesc = "Optional namespace for multi-instance deployment on one host (e.g., acme, team_alpha)"@@ -2360,6 +2398,9 @@ const (EnvDesc_DOCKER_HOST = "Docker Host"EnvDesc_DOCKER_TLS_VERIFY = "Docker TLS Verify"EnvDesc_DOCKER_CERT_PATH = "Docker Certificate Path"+ EnvDesc_DOCKER_INSIDE_HOST = "Worker Docker Daemon Host"+ EnvDesc_DOCKER_INSIDE_TLS_VERIFY = "Worker Docker TLS Verify"+ EnvDesc_DOCKER_INSIDE_CERT_PATH = "Worker Docker Certificate Path"EnvDesc_TENANT_ID = "PentAGI Tenant ID"EnvDesc_LICENSE_KEY = "PentAGI License Key"diff --git a/backend/cmd/installer/wizard/models/docker_form.go b/backend/cmd/installer/wizard/models/docker_form.goindex 0e1b3c75..29cb7ab2 100644--- a/backend/cmd/installer/wizard/models/docker_form.go+++ b/backend/cmd/installer/wizard/models/docker_form.go@@ -115,6 +115,28 @@ func (m *DockerFormModel) BuildForm() tea.Cmd {false,))+ // Daemon endpoint exposed to worker containers (only used when Docker Access+ // is enabled). Mirrors the trio above, but describes the sandbox's view.+ fields = append(fields, m.createTextField("docker_inside_host",+ locale.ToolsDockerInsideHost,+ locale.ToolsDockerInsideHostDesc,+ config.DockerInsideHost,+ false,+ ))++ fields = append(fields, m.createBooleanField("docker_inside_tls_verify",+ locale.ToolsDockerInsideTLSVerify,+ locale.ToolsDockerInsideTLSVerifyDesc,+ config.DockerInsideTLSVerify,+ ))++ fields = append(fields, m.createTextField("docker_inside_cert_path",+ locale.ToolsDockerInsideCertPath,+ locale.ToolsDockerInsideCertPathDesc,+ config.DockerInsideCertPath,+ false,+ ))+m.SetFormFields(fields)return nil}@@ -251,6 +273,17 @@ func (m *DockerFormModel) GetCurrentConfiguration() string {m.GetStyles().Success.Render(locale.StatusConfigured)))}+ // Worker daemon endpoint — only meaningful when Docker Access is enabled.+ if dockerInside == "true" {+ if config.DockerInsideHost.Value != "" {+ sections = append(sections, fmt.Sprintf("• Worker Docker Daemon: %s",+ m.GetStyles().Success.Render(locale.StatusConfigured)))+ } else {+ sections = append(sections, fmt.Sprintf("• Worker Docker Daemon: %s",+ m.GetStyles().Warning.Render(locale.StatusNotConfigured)))+ }+ }+sections = append(sections, "")if config.Configured {sections = append(sections, m.GetStyles().Success.Render(locale.MessageDockerConfigured))@@ -305,6 +338,12 @@ func (m *DockerFormModel) GetHelpContent() string {sections = append(sections, locale.ToolsDockerTLSVerifyHelp)case "docker_cert_path":sections = append(sections, locale.ToolsDockerCertPathHelp)+ case "docker_inside_host":+ sections = append(sections, locale.ToolsDockerInsideHostHelp)+ case "docker_inside_tls_verify":+ sections = append(sections, locale.ToolsDockerInsideTLSVerifyHelp)+ case "docker_inside_cert_path":+ sections = append(sections, locale.ToolsDockerInsideCertPathHelp)default:sections = append(sections, locale.ToolsDockerFormOverview)}@@ -331,6 +370,9 @@ func (m *DockerFormModel) HandleSave() error {DockerHost: config.DockerHost,DockerTLSVerify: config.DockerTLSVerify,HostDockerCertPath: config.HostDockerCertPath,+ DockerInsideHost: config.DockerInsideHost,+ DockerInsideTLSVerify: config.DockerInsideTLSVerify,+ DockerInsideCertPath: config.DockerInsideCertPath,}// update field values based on form input@@ -392,6 +434,30 @@ func (m *DockerFormModel) HandleSave() error {}}newConfig.HostDockerCertPath.Value = value+ case "docker_inside_host":+ // Accept any daemon endpoint scheme docker understands; an unreachable+ // endpoint is an operational matter, not a form-level error.+ if value != "" && !strings.Contains(value, "://") {+ return fmt.Errorf("invalid worker docker host: %s (expected a scheme, e.g. tcp://host:2376 or unix:///var/run/docker.sock)", value)+ }+ newConfig.DockerInsideHost.Value = value+ case "docker_inside_tls_verify":+ if value != "" && value != "true" && value != "false" && value != "1" && value != "0" {+ return fmt.Errorf("invalid boolean value for Worker Docker TLS Verify: %s (must be 'true', 'false', '1', or '0')", value)+ }+ // normalize to docker's own convention: "1" enables, empty disables+ switch value {+ case "true":+ value = "1"+ case "false":+ value = ""+ }+ newConfig.DockerInsideTLSVerify.Value = value+ case "docker_inside_cert_path":+ // Deliberately NOT stat'd: this path is resolved on the worker node+ // whose daemon creates sandboxes, which may be a different machine from+ // the one running this installer.+ newConfig.DockerInsideCertPath.Value = value}}diff --git a/backend/docs/config.md b/backend/docs/config.mdindex f2e8b808..5e82ff8f 100644--- a/backend/docs/config.md+++ b/backend/docs/config.md@@ -13,6 +13,7 @@ This document serves as a comprehensive guide to the configuration system in Pen- [Multi-Instance Deployment (`TENANT_ID`)](#multi-instance-deployment-tenant_id)- [Usage Details](#usage-details)- [Docker Settings](#docker-settings)+ - [Worker Docker Access (DOCKER_INSIDE_*)](#worker-docker-access-docker_inside_)- [Usage Details](#usage-details-1)- [Server Settings](#server-settings)- [Usage Details](#usage-details-2)@@ -148,27 +149,15 @@ These settings control basic application behavior and are foundational for the s### Multi-Instance Deployment (`TENANT_ID`)-`TENANT_ID` namespaces the artifacts a PentAGI instance creates in **shared external-services**, so that several independent installations can use one PostgreSQL server,-one worker node (Docker daemon), one Neo4j/Graphiti and one Langfuse without-colliding.+`TENANT_ID` namespaces the artifacts a PentAGI instance creates in **shared external services**, so that several independent installations can use one PostgreSQL server, one worker node (Docker daemon), one Neo4j/Graphiti and one Langfuse without colliding.-**Primary use case: several management instances, shared resources.** The typical-deployment puts each PentAGI management backend on its own server, while the heavy-shared resources — the worker node where sandbox containers run, and the database —-are common. `TENANT_ID` is what keeps those instances from writing over each other.+**Primary use case: several management instances, shared resources.** The typical deployment puts each PentAGI management backend on its own server, while the heavy shared resources — the worker node where sandbox containers run, and the database — are common. `TENANT_ID` is what keeps those instances from writing over each other.-Running several management instances on **one** server is also possible (for example-behind an nginx reverse proxy), but that is not what the installer or the stock-`docker-compose.yml` are built for — see *Deployment topologies* below.+Running several management instances on **one** server is also possible (for example behind an nginx reverse proxy), but that is not what the installer or the stock `docker-compose.yml` are built for — see *Deployment topologies* below.-**When empty (the default) nothing changes.** Every helper degrades to an identity-function: container names stay `pentagi-terminal-<id>`, the database schema stays-`public`, Graphiti group ids stay `flow-<id>`, and the session cookie stays `auth`.-This is enforced in one place (`backend/pkg/config/tenant.go`) and covered by tests.+**When empty (the default) nothing changes.** Every helper degrades to an identity function: container names stay `pentagi-terminal-<id>`, the database schema stays `public`, Graphiti group ids stay `flow-<id>`, and the session cookie stays `auth`. This is enforced in one place (`backend/pkg/config/tenant.go`) and covered by tests.-**Validation.** `TENANT_ID` must match `^[a-z][a-z0-9_]{0,31}$` — the intersection of-the constraints imposed by every consumer:+**Validation.** `TENANT_ID` must match `^[a-z][a-z0-9_]{0,31}$` — the intersection of the constraints imposed by every consumer:| Consumer | Constraint || --- | --- |@@ -176,10 +165,7 @@ the constraints imposed by every consumer:| PostgreSQL identifier | ≤ 63 bytes; unquoted-safe as `[a-z_][a-z0-9_]*` || Graphiti / Neo4j group id | parsed on a hyphen boundary, so no hyphens |-Hyphens are excluded deliberately: they separate the tenant from the rest of a group-id or object name. An invalid value **aborts startup** rather than being normalised,-because collapsing two distinct tenants onto one namespace is exactly the collision-tenancy exists to prevent.+Hyphens are excluded deliberately: they separate the tenant from the rest of a group id or object name. An invalid value **aborts startup** rather than being normalised, because collapsing two distinct tenants onto one namespace is exactly the collision tenancy exists to prevent.#### What the application namespaces automatically@@ -194,8 +180,7 @@ tenancy exists to prevent.#### What stays the operator's responsibility-`TENANT_ID` does **not** rewrite infrastructure-level settings. The following must be-given distinct values per instance by whoever provisions it:+`TENANT_ID` does **not** rewrite infrastructure-level settings. The following must be given distinct values per instance by whoever provisions it:| Setting | Why it is not derived from `TENANT_ID` || --- | --- |@@ -205,9 +190,7 @@ given distinct values per instance by whoever provisions it:| `INSTALLATION_ID` | Unique per installation, or left empty to be generated once and cached in `DATA_DIR`. || Database privileges | The configured user needs `CREATE SCHEMA`, and on first boot `CREATE EXTENSION` — unless an administrator pre-installed `vector` and `pg_trgm` into `public`. |-The values actually in effect are written to the startup log under-`Instance identity` (`tenant_id`, `data_dir`, `schema`, `installation_id`), which is-the quickest way to confirm two instances are not sharing something they should not.+The values actually in effect are written to the startup log under `Instance identity` (`tenant_id`, `data_dir`, `schema`, `installation_id`), which is the quickest way to confirm two instances are not sharing something they should not.`DOCKER_INSIDE` is orthogonal to tenancy and may be enabled alongside it.@@ -218,16 +201,9 @@ the quickest way to confirm two instances are not sharing something they should| One instance per server, shared PostgreSQL and/or worker node | The installer and the stock `docker-compose.yml`, with `TENANT_ID` set per server. This is the intended setup. || Several instances on one server | Manual configuration only. The stock `docker-compose.yml` uses fixed `container_name` and network names, so copying it verbatim will not start a second stack. Adapt it to your network and infrastructure — for example, distinct container names behind a shared nginx — and give each instance its own `DATA_DIR` and ports. |-The installer provisions **one** instance per server; it does not manage several-side by side. Note that it does scope the sandbox resources it cleans up — worker-containers and volumes are matched by the tenant prefix — so a purge run for one-management instance will not remove another's sandboxes from a shared worker node.+The installer provisions **one** instance per server; it does not manage several side by side. Note that it does scope the sandbox resources it cleans up — worker containers and volumes are matched by the tenant prefix — so a purge run for one management instance will not remove another's sandboxes from a shared worker node.-**Upgrading an existing deployment.** Leave `TENANT_ID` empty. The instance keeps-using `public` and its current data directory; no migration is required. Setting-`TENANT_ID` on an existing installation points it at a **new, empty schema** — the-data in `public` is not migrated and will appear to be gone. Do not point an existing-`public` deployment at a `search_path` that lists another tenant's schema.+**Upgrading an existing deployment.** Leave `TENANT_ID` empty. The instance keeps using `public` and its current data directory; no migration is required. Setting `TENANT_ID` on an existing installation points it at a **new, empty schema** — the data in `public` is not migrated and will appear to be gone. Do not point an existing `public` deployment at a `search_path` that lists another tenant's schema.### Usage Details@@ -325,6 +301,9 @@ These settings control how PentAGI interacts with Docker, which is used for term| DockerInside | `DOCKER_INSIDE` | `false` | Set to `true` if PentAGI runs inside Docker and needs to access the host Docker daemon. || DockerNetAdmin | `DOCKER_NET_ADMIN` | `false` | Set to `true` to grant the primary container NET_ADMIN capability for advanced networking. || DockerSocket | `DOCKER_SOCKET` | *(none)* | Path to Docker socket for container management |+| DockerInsideHost | `DOCKER_INSIDE_HOST` | *(none)* | Docker daemon endpoint given to worker containers; also disables host-socket autodetection. See [Worker Docker Access](#worker-docker-access-docker_inside_) |+| DockerInsideTLSVerify | `DOCKER_INSIDE_TLS_VERIFY` | *(none)* | TLS verification for the worker container's Docker connection |+| DockerInsideCertPath | `DOCKER_INSIDE_CERT_PATH` | *(none)* | TLS certificate directory **on the worker node**, mounted read-only into worker containers || DockerNetwork | `DOCKER_NETWORK` | *(none)* | Docker network name for bridge mode, or `host` for host network mode. See network modes below. || DockerPublicIP | `DOCKER_PUBLIC_IP` | `0.0.0.0` | Public IP address for Docker containers' port bindings (bridge mode only) || DockerWorkDir | `DOCKER_WORK_DIR` | *(none)* | Custom working directory inside Docker containers |@@ -332,6 +311,43 @@ These settings control how PentAGI interacts with Docker, which is used for term| DockerDefaultImageForPentest | `DOCKER_DEFAULT_IMAGE_FOR_PENTEST` | `vxcontrol/kali-linux` | Default Docker image for penetration testing tasks || TerminalToolTimeout | `TERMINAL_TOOL_TIMEOUT` | `1200` | Default execution timeout in seconds applied when an agent requests `timeout=0` or a negative value. Accepted range: `1`–`10800` (3 hours). Values `<= 0` or above `10800` are clamped to the 3-hour maximum. Negative values are treated identically to `0`. |+### Worker Docker Access (`DOCKER_INSIDE_*`)++`DOCKER_HOST`, `DOCKER_TLS_VERIFY` and `DOCKER_CERT_PATH` tell **PentAGI itself** which daemon to create worker containers on. The `DOCKER_INSIDE_*` trio is the mirror image: it tells a **worker container** which daemon *it* may talk to. Both sets are independent — sandboxes can be pointed at a different daemon than the one that spawned them.++They are read only when `DOCKER_INSIDE=true`; with it disabled the sandbox gets no Docker access and no Docker configuration whatsoever.++**How the socket is chosen.** With `DOCKER_INSIDE=true`:++| `DOCKER_SOCKET` | `DOCKER_INSIDE_HOST` | Result |+| --- | --- | --- |+| set | any | That socket is bind-mounted at `/var/run/docker.sock` — historical behaviour, an explicit socket always wins. |+| empty | set | **Nothing is mounted.** The sandbox reaches Docker over `DOCKER_INSIDE_HOST` instead. |+| empty | empty | The host socket is autodetected and mounted — historical behaviour. |++The middle row is the point of the feature: mounting the host socket into a sandbox gives an autonomous agent control of the daemon running PentAGI itself, including every other flow's containers. Designating a separate endpoint — a DinD sidecar, a remote daemon, a socket proxy — keeps that authority out of the sandbox.++**What is injected.** Every non-empty `DOCKER_INSIDE_*` value is passed into the container as an environment variable with the `_INSIDE_` segment removed, so the Docker CLI inside picks it up with no extra configuration:++| Configured | Seen inside the worker container |+| --- | --- |+| `DOCKER_INSIDE_HOST=tcp://dind:2376` | `DOCKER_HOST=tcp://dind:2376` |+| `DOCKER_INSIDE_TLS_VERIFY=1` | `DOCKER_TLS_VERIFY=1` |+| `DOCKER_INSIDE_CERT_PATH=/certs/client` | `DOCKER_CERT_PATH=/certs/client` |++Empty values are omitted rather than injected blank.++When `DOCKER_INSIDE_CERT_PATH` is set, that directory is additionally bind-mounted **read-only at the same path** inside the container, so the injected `DOCKER_CERT_PATH` resolves unchanged. The path is resolved on the **worker node** — the machine whose daemon creates sandboxes — which may not be the machine running PentAGI or the installer. For that reason the installer does not verify it exists.++**Example — sandboxes use a DinD sidecar over mutual TLS:**++```bash+DOCKER_INSIDE=true+DOCKER_SOCKET= # leave empty so the host socket is not mounted+DOCKER_INSIDE_HOST=tcp://dind:2376+DOCKER_INSIDE_TLS_VERIFY=1+DOCKER_INSIDE_CERT_PATH=/certs/client+```### Usage Detailsdiff --git a/backend/docs/docker.md b/backend/docs/docker.mdindex 7c4cbb19..bbdb4c6b 100644--- a/backend/docs/docker.md+++ b/backend/docs/docker.md@@ -5,6 +5,7 @@- [Overview](#overview)- [Architecture](#architecture)- [Configuration](#configuration)+ - [Worker Docker Access](#worker-docker-access)- [Core Interfaces](#core-interfaces)- [Container Lifecycle Management](#container-lifecycle-management)- [Security and Isolation](#security-and-isolation)@@ -53,12 +54,15 @@ backend/pkg/docker/### Key Constants and Configuration```go-const WorkFolderPathInContainer = "/work" // Standard working directory in containers-const BaseContainerPortsNumber = 28000 // Starting port number for dynamic allocation-const defaultImage = "debian:latest" // Fallback image if custom image fails-const containerPortsNumber = 2 // Number of ports allocated per container-const limitContainerPortsNumber = 2000 // Maximum port range for allocation-const containerListWorkers = 20 // Parallel stat workers for directory listing+const WorkFolderPathInContainer = "/work" // Standard working directory in containers+const WorkerVolumeNameSuffix = "-data" // Suffix of the per-flow named volume+const BaseContainerPortsNumber = 28000 // Default base for dynamic port allocation++const defaultImage = "debian:latest" // Fallback image if custom image fails+const defaultDockerSocketPath = "/var/run/docker.sock" // Mount point of a bound socket+const containerPortsNumber = 2 // Number of ports allocated per container+const limitContainerPortsNumber = 2000 // Port window size per instance+const containerListWorkers = 20 // Parallel stat workers for directory listing```### Port Allocation Strategy@@ -66,11 +70,14 @@ const containerListWorkers = 20 // Parallel stat workers fPentAGI uses a deterministic port allocation algorithm to ensure each flow gets unique, predictable ports:```go-func GetPrimaryContainerPorts(flowID int64) []int {+func GetPrimaryContainerPorts(portsBase int, flowID int64) []int {+ if portsBase <= 0 || portsBase > (65535-limitContainerPortsNumber) {+ portsBase = BaseContainerPortsNumber+ }ports := make([]int, containerPortsNumber)- for i := 0; i < containerPortsNumber; i++ {+ for i := range containerPortsNumber {delta := (int(flowID)*containerPortsNumber + i) % limitContainerPortsNumber- ports[i] = BaseContainerPortsNumber + delta+ ports[i] = portsBase + delta}return ports}@@ -79,7 +86,9 @@ func GetPrimaryContainerPorts(flowID int64) []int {This ensures that:- Each flow gets consistent port numbers across restarts- Port conflicts are avoided between different flows-- Ports are within a controlled range (28000-30000)+- Ports stay inside a 2000-wide window starting at `DOCKER_PORTS_BASE` (default `28000`, so `28000-30000`)++The base is configurable because flow ids restart at `1` in every PentAGI instance: two instances sharing one worker node would otherwise request identical host ports for their respective flow `1`. Give each instance a disjoint window (`28000`, `30000`, …). An out-of-range base silently falls back to `28000` rather than producing unbindable ports.## Configuration@@ -92,7 +101,11 @@ The Docker client is configured through several environment variables defined in| `DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker daemon connection || `DOCKER_INSIDE` | `false` | Whether PentAGI communicates with host Docker daemon from containers || `DOCKER_NET_ADMIN` | `false` | Whether PentAGI grants the primary container NET_ADMIN capability for advanced networking. |-| `DOCKER_SOCKET` | `/var/run/docker.sock` | Path to Docker socket on host |+| `DOCKER_SOCKET` | | Explicit socket path on the worker node to bind into worker containers. Empty enables autodetection — see [Worker Docker Access](#worker-docker-access) |+| `DOCKER_INSIDE_HOST` | | Docker daemon endpoint given **to worker containers**; also disables socket autodetection |+| `DOCKER_INSIDE_TLS_VERIFY` | | TLS verification for the worker container's Docker connection |+| `DOCKER_INSIDE_CERT_PATH` | | TLS certificate directory **on the worker node**, mounted read-only into worker containers |+| `DOCKER_PORTS_BASE` | `28000` | First host port of this instance's per-flow allocation window || `DOCKER_NETWORK` | | Docker network for container communication (bridge mode) or `host` for host network mode || `DOCKER_PUBLIC_IP` | `0.0.0.0` | Public IP for port binding (bridge mode only) || `DOCKER_WORK_DIR` | | Custom work directory path on host |@@ -105,18 +118,27 @@ The Docker client is configured through several environment variables defined in```gotype Config struct {// Docker (terminal) settings- DockerInside bool `env:"DOCKER_INSIDE" envDefault:"false"`- DockerNetAdmin bool `env:"DOCKER_NET_ADMIN" envDefault:"false"`- DockerSocket string `env:"DOCKER_SOCKET"`+ DockerInside bool `env:"DOCKER_INSIDE" envDefault:"false"`+ DockerNetAdmin bool `env:"DOCKER_NET_ADMIN" envDefault:"false"`+ DockerSocket string `env:"DOCKER_SOCKET"`++ // How a worker container reaches a Docker daemon (see Worker Docker Access)+ DockerInsideHost string `env:"DOCKER_INSIDE_HOST"`+ DockerInsideTLSVerify string `env:"DOCKER_INSIDE_TLS_VERIFY"`+ DockerInsideCertPath string `env:"DOCKER_INSIDE_CERT_PATH"`+DockerNetwork string `env:"DOCKER_NETWORK"`DockerPublicIP string `env:"DOCKER_PUBLIC_IP" envDefault:"0.0.0.0"`DockerWorkDir string `env:"DOCKER_WORK_DIR"`+ DockerPortsBase int `env:"DOCKER_PORTS_BASE" envDefault:"28000"`DockerDefaultImage string `env:"DOCKER_DEFAULT_IMAGE" envDefault:"debian:latest"`DockerDefaultImageForPentest string `env:"DOCKER_DEFAULT_IMAGE_FOR_PENTEST" envDefault:"vxcontrol/kali-linux"`DataDir string `env:"DATA_DIR" envDefault:"./data"`}```+The three `DOCKER_INSIDE_*` values are consumed through helpers on `*config.Config` (`WorkerDockerSocket`, `WorkerDockerEnv`, `WorkerDockerCertPath`) so the decision logic lives in one place and the Docker client stays a thin consumer.+### NET_ADMIN Capability ConfigurationThe `DOCKER_NET_ADMIN` option controls whether PentAGI containers are granted the `NET_ADMIN` Linux capability, which provides advanced networking permissions essential for many penetration testing operations.@@ -165,12 +187,67 @@ hostConfig := &container.HostConfig{}```-### Docker-in-Docker Support+### Worker Docker Access++Two independent questions are often confused, and PentAGI answers them with two separate sets of variables:++| Question | Variables | Consumer |+|---|---|---|+| Which daemon does **PentAGI** create worker containers on? | `DOCKER_HOST`, `DOCKER_TLS_VERIFY`, `DOCKER_CERT_PATH` | Docker SDK inside the PentAGI process |+| Which daemon may a **worker container** talk to? | `DOCKER_INSIDE`, `DOCKER_SOCKET`, `DOCKER_INSIDE_HOST`, `DOCKER_INSIDE_TLS_VERIFY`, `DOCKER_INSIDE_CERT_PATH` | The agent's sandbox |++`DOCKER_INSIDE` is the master switch for the second row. With it disabled a sandbox gets no Docker access and no Docker configuration at all.++#### Socket selection algorithm++With `DOCKER_INSIDE=true`, `NewDockerClient` resolves the socket once at startup:++```go+socket, autodetectSocket := cfg.WorkerDockerSocket()+if autodetectSocket {+ socket = getHostDockerSocket(ctx, cli)+}+```++| `DOCKER_SOCKET` | `DOCKER_INSIDE_HOST` | Result |+|---|---|---|+| set | any | That socket is bind-mounted at `/var/run/docker.sock` inside every worker |+| empty | set | **Nothing is mounted**; autodetection is skipped entirely |+| empty | empty | Host socket is autodetected and mounted (historical behaviour) |-PentAGI supports running inside Docker containers while still managing other containers. This is controlled by the `DOCKER_INSIDE` setting:+#### Environment injection-- **`DOCKER_INSIDE=false`**: PentAGI runs on host, manages containers directly-- **`DOCKER_INSIDE=true`**: PentAGI runs in container, mounts Docker socket to manage sibling containers+Every non-empty `DOCKER_INSIDE_*` value is injected into the worker container with the `_INSIDE_` segment removed, so the Docker CLI inside picks it up unmodified:++| Configured on PentAGI | Seen inside the worker container |+|---|---|+| `DOCKER_INSIDE_HOST=tcp://10.0.0.5:3376` | `DOCKER_HOST=tcp://10.0.0.5:3376` |+| `DOCKER_INSIDE_TLS_VERIFY=1` | `DOCKER_TLS_VERIFY=1` |+| `DOCKER_INSIDE_CERT_PATH=/etc/docker/dind-client` | `DOCKER_CERT_PATH=/etc/docker/dind-client` |++Empty values are omitted rather than injected blank. When `DOCKER_INSIDE_CERT_PATH` is set, that directory is additionally bind-mounted **read-only at the identical path**, so the injected `DOCKER_CERT_PATH` resolves unchanged inside the container. The path is resolved on the **worker node** — the machine whose daemon creates sandboxes — which is frequently not the machine running PentAGI.++```go+if dc.inside {+ if dc.socket != "" {+ hostConfig.Binds = append(hostConfig.Binds, dc.socket+":"+defaultDockerSocketPath)+ }+ config.Env = append(config.Env, dc.insideEnv...)+ if dc.insideCertPath != "" {+ hostConfig.Binds = append(hostConfig.Binds, dc.insideCertPath+":"+dc.insideCertPath+":ro")+ }+}+```++#### Why the TCP endpoint is preferred over a bound socket++Bind-mounting a socket into worker containers has two distinct problems.++**Ordering fragility.** A bind-mount source that does not exist yet is created by Docker as a **directory**. If the worker node reboots and a worker container with `restart: on-failure` starts before the dind daemon has recreated its socket, Docker materialises a directory at `/var/run/docker-dind/docker.sock` — and dind then cannot bind its own socket at that path. The sandbox gets a useless mount and dind fails to start until the directory is removed by hand.++**Blast radius.** A socket bind-mount only avoids that race reliably when it is the **host** daemon's socket, since that one exists before anything else starts. But handing an autonomous agent the host daemon means handing it the host: it can start a privileged container, mount `/`, and take over the node — including PentAGI itself and every other flow's containers.++Pointing sandboxes at a hardened dind daemon over TLS avoids both. There is no mount to race on, and the authorization policy on that daemon constrains what the agent may create. See [Worker Node Setup](../../examples/guides/worker_node.md) for a complete configuration.### Network Configuration@@ -230,16 +307,21 @@ type DockerClient interface {```gotype dockerClient struct {- db database.Querier // Database for container state management- logger *logrus.Logger // Structured logging- dataDir string // Local data directory- hostDir string // Host-mapped data directory- client *client.Client // Docker SDK client- inside bool // Running inside Docker- defImage string // Default fallback image- socket string // Docker socket path- network string // Docker network name- publicIP string // Public IP for port binding+ db database.Querier // Database for container state management+ logger *logrus.Logger // Structured logging+ dataDir string // Local data directory+ hostDir string // Host-mapped data directory+ client *client.Client // Docker SDK client+ inside bool // Worker containers may reach a Docker daemon+ defImage string // Default fallback image+ socket string // Socket to bind into workers ("" = none)+ network string // Docker network name+ publicIP string // Public IP for port binding+ portsBase int // First host port of this instance's window+ labels map[string]string // Tenant ownership labels (nil without a tenant)++ insideEnv []string // DOCKER_* injected into worker containers+ insideCertPath string // TLS dir mounted read-only into workers}```@@ -268,7 +350,7 @@ The `RunContainer` method handles the complete container creation workflow:4. **Storage Setup**:- Creates dedicated volume or bind mount- Mounts work directory to `/work` in container- - Optionally mounts Docker socket for Docker-in-Docker+ - When `DOCKER_INSIDE=true`: optionally mounts a Docker socket, injects the `DOCKER_*` environment derived from `DOCKER_INSIDE_*`, and mounts the TLS certificate directory read-only — see [Worker Docker Access](#worker-docker-access)5. **Network and Ports**:- **Bridge Mode**: Assigns flow-specific ports using deterministic algorithm, binds to public IP@@ -302,7 +384,9 @@ hostConfig := &container.HostConfig{},Binds: []string{"/host/data/flow-123:/work", // Work directory mount- "/var/run/docker.sock:/var/run/docker.sock", // Docker socket (if inside Docker)+ // Only when DOCKER_INSIDE=true and a socket was selected; with+ // DOCKER_INSIDE_HOST set instead, no socket is mounted at all.+ "/var/run/docker.sock:/var/run/docker.sock",},PortBindings: nat.PortMap{"28000/tcp": []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: "28000"}},@@ -326,8 +410,8 @@ PentAGI tracks container states in the database:Containers follow a specific naming pattern for easy identification:```go-func PrimaryTerminalName(flowID int64) string {- return fmt.Sprintf("pentagi-terminal-%d", flowID)+func PrimaryTerminalName(tenantPrefix string, flowID int64) string {+ return fmt.Sprintf("%s%s%d", tenantPrefix, PrimaryTerminalNamePrefix, flowID)}```@@ -336,6 +420,8 @@ This creates names like `pentagi-terminal-123` for flow ID 123, making it easy t- Perform flow-based cleanup operations- Debug container-related issues+When `TENANT_ID` is set the tenant leads the name — `acme-pentagi-terminal-123` — so that several PentAGI instances can share one worker node. The prefix goes in front deliberately: sweeps that match `pentagi-terminal-*` then reach only their own instance's containers. The per-flow volume (`<container name>-data`) and the container hostname derive from this name, so both inherit the scoping. Containers and volumes additionally carry a `pentagi.tenant` label for filter-based cleanup.+### Cleanup OperationsThe `Cleanup` method performs comprehensive cleanup:@@ -496,7 +582,7 @@ if err != nil {}// Create container for a flow-containerName := docker.PrimaryTerminalName(flowID)+containerName := tools.PrimaryTerminalName(cfg.TenantPrefix(), flowID)container, err := dockerClient.RunContainer(ctx,containerName,diff --git a/backend/pkg/config/config.go b/backend/pkg/config/config.goindex 9f695afe..d96f27db 100644--- a/backend/pkg/config/config.go+++ b/backend/pkg/config/config.go@@ -32,9 +32,24 @@ type Config struct {LicenseKey string `env:"LICENSE_KEY"`// === Container Runtime Configuration ===- DockerInside bool `env:"DOCKER_INSIDE" envDefault:"false"`- DockerNetAdmin bool `env:"DOCKER_NET_ADMIN" envDefault:"false"`- DockerSocket string `env:"DOCKER_SOCKET"`+ DockerInside bool `env:"DOCKER_INSIDE" envDefault:"false"`+ DockerNetAdmin bool `env:"DOCKER_NET_ADMIN" envDefault:"false"`+ DockerSocket string `env:"DOCKER_SOCKET"`++ // DOCKER_INSIDE_* describe how a worker container reaches a Docker daemon when+ // DOCKER_INSIDE is enabled. They mirror the DOCKER_HOST / DOCKER_TLS_VERIFY /+ // DOCKER_CERT_PATH trio that this process itself uses, but apply to the+ // sandbox rather than to PentAGI, and are injected into it with the _INSIDE+ // segment stripped from the name.+ //+ // Setting DockerInsideHost points sandboxes at a dedicated daemon endpoint+ // instead of a bind-mounted host socket, which is the safer arrangement: an+ // agent then talks to whichever daemon the operator designated rather than the+ // one running PentAGI itself. All three are ignored when DOCKER_INSIDE is off.+ DockerInsideHost string `env:"DOCKER_INSIDE_HOST"`+ DockerInsideTLSVerify string `env:"DOCKER_INSIDE_TLS_VERIFY"`+ DockerInsideCertPath string `env:"DOCKER_INSIDE_CERT_PATH"`+DockerNetwork string `env:"DOCKER_NETWORK"`DockerPublicIP string `env:"DOCKER_PUBLIC_IP" envDefault:"0.0.0.0"`DockerWorkDir string `env:"DOCKER_WORK_DIR"`@@ -339,6 +354,66 @@ func (c *Config) WorkerPublicIP() string {return c.DockerPublicIP}+// WorkerDockerEnv returns the DOCKER_* environment entries to inject into a+// worker container so that the Docker CLI inside it talks to the daemon the+// operator designated. Each DOCKER_INSIDE_* value is passed through with the+// _INSIDE segment removed; empty values are omitted entirely.+//+// Returns nil when DOCKER_INSIDE is disabled, so a sandbox that is not meant to+// reach Docker at all receives no Docker configuration.+func (c *Config) WorkerDockerEnv() []string {+ if c == nil || !c.DockerInside {+ return nil+ }++ var env []string+ for _, kv := range []struct{ name, value string }{+ {"DOCKER_HOST", c.DockerInsideHost},+ {"DOCKER_TLS_VERIFY", c.DockerInsideTLSVerify},+ {"DOCKER_CERT_PATH", c.DockerInsideCertPath},+ } {+ if kv.value != "" {+ env = append(env, kv.name+"="+kv.value)+ }+ }++ return env+}++// WorkerDockerCertPath returns the TLS certificate directory that must be made+// visible inside a worker container, or "" when there is nothing to mount. The+// path is identical on both sides so that the injected DOCKER_CERT_PATH resolves+// unchanged within the sandbox.+func (c *Config) WorkerDockerCertPath() string {+ if c == nil || !c.DockerInside {+ return ""+ }+ return c.DockerInsideCertPath+}++// WorkerDockerSocket decides which host socket, if any, is bind-mounted into a+// worker container.+//+// - An explicit DOCKER_SOCKET always wins and is mounted as before.+// - Otherwise, if DOCKER_INSIDE_HOST is set, nothing is mounted: the sandbox+// reaches Docker over that endpoint, and exposing the host socket as well+// would hand it control of the daemon running PentAGI itself.+// - Otherwise the caller falls back to autodetecting the host socket, which is+// the historical behaviour; this is signalled by returning autodetect=true.+func (c *Config) WorkerDockerSocket() (socket string, autodetect bool) {+ if c == nil {+ return "", true+ }+ switch {+ case c.DockerSocket != "":+ return c.DockerSocket, false+ case c.DockerInsideHost != "":+ return "", false+ default:+ return "", true+ }+}+// WorkerNetwork returns the network for the worker containerfunc (c *Config) WorkerNetwork() string {if c == nil {diff --git a/backend/pkg/config/config_test.go b/backend/pkg/config/config_test.goindex 972b0c06..bf805753 100644--- a/backend/pkg/config/config_test.go+++ b/backend/pkg/config/config_test.go@@ -3,6 +3,7 @@ package configimport ("os""path/filepath"+ "reflect""testing""github.com/google/uuid"@@ -272,6 +273,7 @@ func clearConfigEnv(t *testing.T) {envVars := []string{"DATABASE_URL", "DEBUG", "DATA_DIR", "ASK_USER", "TENANT_ID", "INSTALLATION_ID", "LICENSE_KEY","DOCKER_INSIDE", "DOCKER_NET_ADMIN", "DOCKER_SOCKET", "DOCKER_NETWORK",+ "DOCKER_INSIDE_HOST", "DOCKER_INSIDE_TLS_VERIFY", "DOCKER_INSIDE_CERT_PATH","DOCKER_PUBLIC_IP", "DOCKER_WORK_DIR", "DOCKER_DEFAULT_IMAGE", "DOCKER_DEFAULT_IMAGE_FOR_PENTEST", "TERMINAL_TOOL_TIMEOUT","SERVER_PORT", "SERVER_HOST", "SERVER_USE_SSL", "SERVER_SSL_KEY", "SERVER_SSL_CRT","STATIC_URL", "STATIC_DIR", "CORS_ORIGINS", "COOKIE_SIGNING_SALT",@@ -616,3 +618,151 @@ func TestNewConfig_AgentSupervisionOverride(t *testing.T) {assert.Equal(t, 30, config.MaxLimitedAgentToolCalls)assert.Equal(t, true, config.AgentPlanningStepEnabled)}++// TestWorkerDockerEnvDisabled pins the first rule: with DOCKER_INSIDE off, a+// worker container receives no Docker configuration at all, even if the+// DOCKER_INSIDE_* values happen to be populated.+func TestWorkerDockerEnvDisabled(t *testing.T) {+ c := &Config{+ DockerInside: false,+ DockerInsideHost: "tcp://dind:2376",+ DockerInsideTLSVerify: "1",+ DockerInsideCertPath: "/certs",+ }++ if env := c.WorkerDockerEnv(); env != nil {+ t.Errorf("WorkerDockerEnv() = %v, want nil when DOCKER_INSIDE is disabled", env)+ }+ if p := c.WorkerDockerCertPath(); p != "" {+ t.Errorf("WorkerDockerCertPath() = %q, want %q when DOCKER_INSIDE is disabled", p, "")+ }+}++func TestWorkerDockerEnvStripsInsideSegment(t *testing.T) {+ tests := []struct {+ name string+ cfg *Config+ want []string+ }{+ {+ name: "all three set",+ cfg: &Config{+ DockerInside: true,+ DockerInsideHost: "tcp://dind:2376",+ DockerInsideTLSVerify: "1",+ DockerInsideCertPath: "/certs/client",+ },+ want: []string{+ "DOCKER_HOST=tcp://dind:2376",+ "DOCKER_TLS_VERIFY=1",+ "DOCKER_CERT_PATH=/certs/client",+ },+ },+ {+ name: "host only — empty values are omitted, not passed as blanks",+ cfg: &Config{+ DockerInside: true,+ DockerInsideHost: "tcp://dind:2375",+ },+ want: []string{"DOCKER_HOST=tcp://dind:2375"},+ },+ {+ name: "nothing configured",+ cfg: &Config{DockerInside: true},+ want: nil,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.cfg.WorkerDockerEnv(); !reflect.DeepEqual(got, tt.want) {+ t.Errorf("WorkerDockerEnv() = %v, want %v", got, tt.want)+ }+ })+ }+}++// TestWorkerDockerSocket covers the socket-selection rule, which is the part+// with security consequences: autodetection of the host socket must stop as soon+// as a dedicated daemon endpoint is designated for sandboxes.+func TestWorkerDockerSocket(t *testing.T) {+ tests := []struct {+ name string+ cfg *Config+ wantSocket string+ wantAutodetect bool+ }{+ {+ name: "nothing configured — historical autodetect",+ cfg: &Config{},+ wantSocket: "",+ wantAutodetect: true,+ },+ {+ name: "explicit socket wins",+ cfg: &Config{DockerSocket: "/var/run/docker.sock"},+ wantSocket: "/var/run/docker.sock",+ wantAutodetect: false,+ },+ {+ name: "inside host set — no socket, no autodetect",+ cfg: &Config{DockerInsideHost: "tcp://dind:2376"},+ wantSocket: "",+ wantAutodetect: false,+ },+ {+ name: "explicit socket still wins over inside host",+ cfg: &Config{+ DockerSocket: "/run/custom.sock",+ DockerInsideHost: "tcp://dind:2376",+ },+ wantSocket: "/run/custom.sock",+ wantAutodetect: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ socket, autodetect := tt.cfg.WorkerDockerSocket()+ if socket != tt.wantSocket || autodetect != tt.wantAutodetect {+ t.Errorf("WorkerDockerSocket() = (%q, %v), want (%q, %v)",+ socket, autodetect, tt.wantSocket, tt.wantAutodetect)+ }+ })+ }+}++// TestWorkerDockerBackwardCompatibility guards the untouched path: an+// installation that never sets a DOCKER_INSIDE_* value must behave exactly as it+// did before the feature existed — autodetect the host socket, inject nothing.+func TestWorkerDockerBackwardCompatibility(t *testing.T) {+ for _, inside := range []bool{false, true} {+ c := &Config{DockerInside: inside}++ socket, autodetect := c.WorkerDockerSocket()+ if socket != "" || !autodetect {+ t.Errorf("DOCKER_INSIDE=%v: WorkerDockerSocket() = (%q, %v), want (\"\", true)",+ inside, socket, autodetect)+ }+ if env := c.WorkerDockerEnv(); env != nil {+ t.Errorf("DOCKER_INSIDE=%v: WorkerDockerEnv() = %v, want nil", inside, env)+ }+ if p := c.WorkerDockerCertPath(); p != "" {+ t.Errorf("DOCKER_INSIDE=%v: WorkerDockerCertPath() = %q, want \"\"", inside, p)+ }+ }+}++func TestWorkerDockerHelpersNilSafe(t *testing.T) {+ var c *Config++ if env := c.WorkerDockerEnv(); env != nil {+ t.Errorf("WorkerDockerEnv() = %v, want nil", env)+ }+ if p := c.WorkerDockerCertPath(); p != "" {+ t.Errorf("WorkerDockerCertPath() = %q, want \"\"", p)+ }+ if socket, autodetect := c.WorkerDockerSocket(); socket != "" || !autodetect {+ t.Errorf("WorkerDockerSocket() = (%q, %v), want (\"\", true)", socket, autodetect)+ }+}diff --git a/backend/pkg/docker/client.go b/backend/pkg/docker/client.goindex 43f6d12b..92080668 100644--- a/backend/pkg/docker/client.go+++ b/backend/pkg/docker/client.go@@ -55,18 +55,20 @@ const ()type dockerClient struct {- db database.Querier- logger *logrus.Logger- dataDir string- hostDir string- client *client.Client- inside bool- defImage string- socket string- network string- publicIP string- portsBase int- labels map[string]string+ db database.Querier+ logger *logrus.Logger+ dataDir string+ hostDir string+ client *client.Client+ inside bool+ defImage string+ socket string+ network string+ publicIP string+ portsBase int+ labels map[string]string+ insideEnv []string+ insideCertPath string}type DockerClient interface {@@ -112,10 +114,12 @@ func NewDockerClient(ctx context.Context, db database.Querier, cfg *config.Confireturn nil, fmt.Errorf("failed to get docker info: %w", err)}- var socket string- if cfg.DockerSocket != "" {- socket = cfg.DockerSocket- } else {+ // Resolve which host socket (if any) gets bind-mounted into worker containers.+ // Autodetection is skipped when DOCKER_INSIDE_HOST designates a daemon+ // endpoint for sandboxes: mounting the host socket alongside it would grant an+ // agent control of the daemon running PentAGI itself.+ socket, autodetectSocket := cfg.WorkerDockerSocket()+ if autodetectSocket {socket = getHostDockerSocket(ctx, cli)}inside := cfg.DockerInside@@ -151,30 +155,33 @@ func NewDockerClient(ctx context.Context, db database.Querier, cfg *config.Confilogger := logrus.StandardLogger()logger.WithFields(logrus.Fields{- "docker_name": info.Name,- "docker_arch": info.Architecture,- "docker_version": info.ServerVersion,- "client_version": cli.ClientVersion(),- "data_dir": dataDir,- "host_dir": hostDir,- "docker_inside": inside,- "docker_socket": socket,- "public_ip": publicIP,+ "docker_name": info.Name,+ "docker_arch": info.Architecture,+ "docker_version": info.ServerVersion,+ "client_version": cli.ClientVersion(),+ "data_dir": dataDir,+ "host_dir": hostDir,+ "docker_inside": inside,+ "docker_socket": socket,+ "docker_inside_host": cfg.DockerInsideHost,+ "public_ip": publicIP,}).Debug("Docker client initialized")return &dockerClient{- db: db,- client: cli,- dataDir: dataDir,- hostDir: hostDir,- logger: logger,- inside: inside,- defImage: defImage,- socket: socket,- network: netName,- publicIP: publicIP,- portsBase: cfg.DockerPortsBase,- labels: cfg.TenantLabels(),+ db: db,+ client: cli,+ dataDir: dataDir,+ hostDir: hostDir,+ logger: logger,+ inside: inside,+ defImage: defImage,+ socket: socket,+ network: netName,+ publicIP: publicIP,+ portsBase: cfg.DockerPortsBase,+ labels: cfg.TenantLabels(),+ insideEnv: cfg.WorkerDockerEnv(),+ insideCertPath: cfg.WorkerDockerCertPath(),}, nil}@@ -302,7 +309,21 @@ func (dc *dockerClient) RunContainer(hostConfig.Binds = append(hostConfig.Binds, fmt.Sprintf("%s:%s", hostDir, WorkFolderPathInContainer))if dc.inside {- hostConfig.Binds = append(hostConfig.Binds, fmt.Sprintf("%s:%s", dc.socket, defaultDockerSocketPath))+ // The socket is empty when DOCKER_INSIDE_HOST designates a daemon endpoint+ // instead; binding "" would produce a malformed mount spec.+ if dc.socket != "" {+ hostConfig.Binds = append(hostConfig.Binds, fmt.Sprintf("%s:%s", dc.socket, defaultDockerSocketPath))+ }++ // Point the sandbox's Docker CLI at the designated daemon.+ config.Env = append(config.Env, dc.insideEnv...)++ // TLS material is mounted read-only at the same path on both sides so the+ // injected DOCKER_CERT_PATH resolves unchanged inside the container.+ if dc.insideCertPath != "" {+ hostConfig.Binds = append(hostConfig.Binds,+ fmt.Sprintf("%s:%s:ro", dc.insideCertPath, dc.insideCertPath))+ }}// Defense-in-depth: block setuid/setgid and file-capability escalationdiff --git a/docker-compose.yml b/docker-compose.ymlindex 5f72976d..0fbeda6a 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -178,6 +178,9 @@ services:- DOCKER_INSIDE=${DOCKER_INSIDE:-false}- DOCKER_NET_ADMIN=${DOCKER_NET_ADMIN:-false}- DOCKER_SOCKET=${DOCKER_SOCKET:-}+ - DOCKER_INSIDE_HOST=${DOCKER_INSIDE_HOST:-}+ - DOCKER_INSIDE_TLS_VERIFY=${DOCKER_INSIDE_TLS_VERIFY:-}+ - DOCKER_INSIDE_CERT_PATH=${DOCKER_INSIDE_CERT_PATH:-}- DOCKER_NETWORK=${DOCKER_NETWORK:-}- DOCKER_PUBLIC_IP=${DOCKER_PUBLIC_IP:-}- DOCKER_WORK_DIR=${DOCKER_WORK_DIR:-}