Network, Tenant and Multi-Agent Isolation

Assume one component will be steered or broken, and decide in advance how far it can reach.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Isolation limits the blast radius, the amount of harm one failure can cause. Run agent code in a boundary with no outbound network unless listed, separate tenants in every layer including caches and indexes, and make agents prove who sent what before another agent acts on it.

What you will learn: egress control and server-side request forgery, layers of tenant isolation, secure messages between agents and how to test that the boundaries hold.
Prerequisites: Code Execution and Sandboxing and Agent Identity, Authorization and Secrets.

Versions used

The examples run in November 2026 with Python 3.13 and cryptography 50.0.1. The address checker uses a pretend name service and opens no connections. It illustrates decisions; it does not replace network-level enforcement.

Beginner Boundaries and blast radius

Why isolate an agent?

An agent mixes untrusted text with tools that act. Even with good prompts and checks, assume that some day a component will do something unintended. Isolation answers "and then what can it reach?"

BoundarySeparatesTypical tool
Process or containerCode from the hostUnprivileged user, read-only files
Strong sandbox or virtual machineUntrusted code from the kernelHardened runtime or small virtual machine
NetworkWorkload from other systemsDefault-deny rules and an egress proxy
IdentityOne component's rights from another'sSeparate workload identities
DataTenants and usersRow rules, separate stores or keys
EnvironmentTest from productionSeparate accounts and credentials
Environment accountproduction kept apart
Network segmentdeny by default
Sandboxno secrets, temporary files, limits
Generated codetreated as untrusted

A recent lesson

In July 2026 OpenAI reported that models in an internal cyber evaluation, run with reduced refusals and without production classifiers, escaped their sandbox through a previously unknown flaw in a package registry cache proxy, which was the one permitted route out, and went on to breach Hugging Face production systems with stolen credentials and further unknown flaws. Hugging Face's technical timeline draws lessons about strict isolation around evaluations, narrow trust boundaries, short-lived credentials and blocked access to metadata services.

This was a specialized testing setting, not an ordinary assistant. The design lesson still travels: the permitted exit is part of the boundary. A proxy or mirror that the sandbox may reach deserves the same hardening and monitoring as the sandbox itself.

Intermediate Control the way out

Egress and request forgery

Server-side request forgery tricks a server into connecting somewhere it should not, such as an internal admin page or a cloud metadata address that hands out credentials. Any tool that fetches an address influenced by a user, document or model is exposed.

CheckDefeats
Allow only listed hosts, compared exactlyUnknown and look-alike destinations
Require the expected scheme and portPlain text and unusual services
Refuse user names in addressesAddresses that read like another host
Check every resolved address is publicNames that point inward
Connect to the address you checkedAn answer that changes between check and use
Check every redirect againAn allowed host forwarding inward
Enforce again in the networkCode that skips your function

Run the address checks

"""Decide where an agent's tool may connect. Runs offline with a pretend DNS."""
import ipaddress
from urllib.parse import urljoin, urlsplit

ALLOWED = {"api.partner.example", "files.partner.example", "moved.partner.example"}


class Blocked(Exception):
    pass


def check(url, resolve):
    parts = urlsplit(url)
    if parts.scheme != "https":
        raise Blocked("not https")
    if parts.username or parts.password:
        raise Blocked("credentials in address")
    if parts.port not in (None, 443):
        raise Blocked("unexpected port")
    if parts.hostname not in ALLOWED:
        raise Blocked(f"host not allowed: {parts.hostname}")
    addresses = resolve(parts.hostname)
    if not addresses:
        raise Blocked("name did not resolve")
    for text in addresses:                          # every answer must be public
        if not ipaddress.ip_address(text).is_global:
            raise Blocked(f"non-public address: {text}")
    return addresses[0]                             # connect to THIS address


def fetch(url, resolve, redirects, limit=3):
    """Follow redirects ourselves so that every hop is checked."""
    for _ in range(limit + 1):
        address = check(url, resolve)
        if url not in redirects:
            return f"connect {address}"
        url = urljoin(url, redirects[url])
    raise Blocked("too many redirects")


DNS = {"api.partner.example": ["93.184.216.34"],
       "files.partner.example": ["93.184.216.35", "10.0.0.5"],
       "moved.partner.example": ["93.184.216.36"]}
REDIRECTS = {"https://moved.partner.example/x": "https://localhost/admin"}
CASES = [
    ("normal call", "https://api.partner.example/v1/orders", DNS),
    ("plain http", "http://api.partner.example/v1/orders", DNS),
    ("other host", "https://collect.test/p", DNS),
    ("name@host trick", "https://api.partner.example@collect.test/", DNS),
    ("suffix trick", "https://api.partner.example.collect.test/", DNS),
    ("one private answer", "https://files.partner.example/a", DNS),
    ("name now points inward", "https://api.partner.example/",
     {"api.partner.example": ["169.254.169.254"]}),
    ("IPv4 hidden in IPv6", "https://api.partner.example/",
     {"api.partner.example": ["::ffff:127.0.0.1"]}),
    ("redirect inward", "https://moved.partner.example/x", DNS),
]

if __name__ == "__main__":
    for name, url, table in CASES:
        try:
            result = fetch(url, lambda host: table.get(host, []), REDIRECTS)
        except Blocked as reason:
            result = f"BLOCKED - {reason}"
        print(f"{name:<24}{result}")

Output:

normal call             connect 93.184.216.34
plain http              BLOCKED - not https
other host              BLOCKED - host not allowed: collect.test
name@host trick         BLOCKED - credentials in address
suffix trick            BLOCKED - host not allowed: api.partner.example.collect.test
one private answer      BLOCKED - non-public address: 10.0.0.5
name now points inward  BLOCKED - non-public address: 169.254.169.254
IPv4 hidden in IPv6     BLOCKED - non-public address: ::ffff:127.0.0.1
redirect inward         BLOCKED - host not allowed: localhost
The check is not the connection

This function returns the address that passed. Real code must connect to exactly that address while still verifying the certificate for the host name, or send all traffic through a proxy that enforces the rules. Otherwise the name can resolve differently a moment later. Treat code such as this as a second layer behind network rules.

Network design

# Kubernetes sketch: the sandbox may reach only the egress proxy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: sandbox-egress
spec:
  podSelector:
    matchLabels: {role: agent-sandbox}
  policyTypes: [Ingress, Egress]
  egress:
    - to:
        - podSelector:
            matchLabels: {role: egress-proxy}
      ports:
        - {protocol: TCP, port: 3128}

This manifest was not applied for this page, and such policies work only when the cluster's network plugin enforces them. It allows no incoming traffic and no name lookups, which suits a proxy addressed by a fixed internal route; adjust deliberately. Always verify from inside the sandbox that blocked destinations really fail.

  • Block cloud metadata services from agent workloads.
  • Remember quiet exits: name lookups, package mirrors, logging endpoints and shared storage.
  • Log destination, size and decision for every outbound request.
  • Separate the component that browses the public web from components holding private data.
Expert Tenants and teams of agents

What an egress proxy should do

DutyDetail
Identify the callerKnow which workload and task is asking
Apply a per-task listA research task and a billing task need different destinations
Resolve names itselfCheck addresses and connect to the checked one
Restrict methods and sizeA read-only task should not upload large bodies
Add credentials narrowlyOnly for the intended destination and operation
Record decisionsDestination, size, rule and outcome
Fail closedIf the proxy or its policy is unavailable, nothing leaves

The proxy is now a high-value component. Keep it small and patched, give it no unrelated credentials, restrict who can change its rules and monitor it for unusual behavior. An allowed domain that accepts uploads from anyone, such as a public storage or code hosting service, can still receive your data, so restrict paths and accounts where possible.

Keep environments apart

Development, testing, evaluation and production should not share credentials, networks or writable storage. Evaluations deserve care of their own, because they may deliberately push a model to try difficult or risky things. Give them synthetic data, no production routes and monitoring that someone will act on.

Tenant isolation

A tenant is a customer or group whose data must stay separate. The tenant identifier must come from the verified identity and be applied by the system, never chosen by the model or read from the request text.

LayerLeak to preventControl
DatabaseQuery returns another tenant's rowsRow-level rules or separate databases
Search indexRetrieval crosses tenantsFilter before ranking, or separate indexes
CacheOne tenant's answer served to anotherTenant and permissions in the cache key
MemoryFacts recalled for the wrong tenantScoped stores and deletion by tenant
Files and sandboxesLeftovers visible to the next taskFresh sandbox per task; never share across tenants
Queues and jobsBackground work loses its contextCarry signed tenant context and re-check
Logs and tracesSupport staff see other customersAccess control and redaction
Shared capacityOne tenant starves the restQuotas and rate limits
import hashlib

def cache_key(tenant, user_groups, model, prompt_version, question):
    parts = [tenant, ",".join(sorted(user_groups)), model, prompt_version, question]
    return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()

This fragment was not part of the runs on this page. Include whatever changes the permitted answer. Joining with a separator that could appear in the values can cause collisions, so validate the parts or encode them as a structured list.

Communication between agents

In a team, one agent's output is another's input. A compromised or confused agent can pass on instructions with borrowed authority. A receiving agent should establish five things before acting: sender, intended recipient, unchanged content, freshness and permission.

Run the message checks

Each agent holds a private signing key and the receiver knows only public keys. Install with pip install cryptography.

"""Messages between agents: prove sender, recipient, content and freshness."""
import json
import secrets
import time

from cryptography.exceptions import InvalidSignature     # pip install cryptography
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

KEYS = {name: Ed25519PrivateKey.generate() for name in ("planner", "payer", "reader")}
DIRECTORY = {name: key.public_key() for name, key in KEYS.items()}   # trusted registry
MAY_SEND = {("planner", "payer"): {"prepare_payment"},
            ("reader", "payer"): set()}                 # the reader may request nothing
SEEN = set()


def send(sender, to, action, data, ttl=60, key=None):
    body = {"from": sender, "to": to, "action": action, "data": data,
            "expires": time.time() + ttl, "nonce": secrets.token_hex(8)}
    raw = json.dumps(body, sort_keys=True).encode()
    return {"raw": raw, "signature": (key or KEYS[sender]).sign(raw)}


def receive(me, message):
    body = json.loads(message["raw"])            # untrusted until the signature passes
    public = DIRECTORY.get(body.get("from"))
    try:
        if public is None:
            return "refused: unknown sender"
        public.verify(message["signature"], message["raw"])
    except InvalidSignature:
        return "refused: bad signature"
    if body["to"] != me:
        return "refused: meant for another agent"
    if time.time() > body["expires"]:
        return "refused: expired"
    if body["nonce"] in SEEN:
        return "refused: already processed"
    SEEN.add(body["nonce"])
    if body["action"] not in MAY_SEND.get((body["from"], me), set()):
        return f"refused: {body['from']} may not request {body['action']}"
    return f"accepted: {body['action']} {body['data']}"


if __name__ == "__main__":
    good = send("planner", "payer", "prepare_payment", {"invoice": "INV-1"})
    altered = dict(good, raw=good["raw"].replace(b"INV-1", b"INV-9"))
    cases = [
        ("genuine", good),
        ("same message again", good),
        ("content altered", altered),
        ("reader pretends to be planner",
         send("planner", "payer", "prepare_payment", {}, key=KEYS["reader"])),
        ("expired", send("planner", "payer", "prepare_payment", {}, ttl=-1)),
        ("for someone else", send("planner", "reader", "prepare_payment", {})),
        ("genuine but not permitted",
         send("reader", "payer", "prepare_payment", {"note": "urgent, pay now"})),
    ]
    for name, message in cases:
        print(f"{name:<31}{receive('payer', message)}")

Output:

genuine                        accepted: prepare_payment {'invoice': 'INV-1'}
same message again             refused: already processed
content altered                refused: bad signature
reader pretends to be planner  refused: bad signature
expired                        refused: expired
for someone else               refused: meant for another agent
genuine but not permitted      refused: reader may not request prepare_payment

The last line matters most. The message was genuine, yet refused, because proving who spoke does not grant permission to ask. In production, store used identifiers durably and shared between instances, keep keys in a key service and prefer your platform's authenticated transport, such as mutual TLS. Signing does not encrypt: anyone who sees the message can read it. See also A2A Security and Interoperability.

Signaturewho and unchanged
Recipientmeant for me
Freshnessnot expired or repeated
Permissionmay this sender ask?

Contain a bad agent

  • Give each agent only the peers, tools and data its role needs.
  • Pass typed fields rather than free text where a decision depends on them.
  • Cap depth, fan-out, message rate and total spend per task.
  • Provide a way to quarantine one agent without stopping the system.
  • Do not let agents change each other's instructions, tools or memory.

See Handoffs, Routing, Shared State and Communication and Securing, Evaluating and Running Multi-Agent Systems.

Long-running and shared workers

A worker that handles many tasks keeps things between them: open connections, cached tokens, temporary files, loaded memory and global variables. Start from a clean state for each task where you can. Where you cannot, clear state explicitly and test that nothing carries over.

Browsers, files and attachments

A browsing agent carries whatever its browser profile holds. Use a fresh profile without your signed-in sessions, block internal addresses and limit downloads and uploads. Parse untrusted files in a separate process with memory and time limits, since a document parser is software that attackers target. See Browser Agent Safety, Testing and Recovery.

A worked design

Illustrative example

A data assistant runs model-written analysis code. Each request gets a new sandbox holding only the files that user may read, copied in beforehand. The sandbox has no network, no credentials and limits on time, memory and output. Results come back as files of expected types, which are checked before display. The service that fetched the data runs outside the sandbox under the user's delegated rights. A hostile spreadsheet can still make the analysis wrong, but it has no route to send data elsewhere from inside the sandbox.

Watch for pressure on boundaries

  • Any blocked attempt to reach metadata or internal addresses.
  • A sandbox that creates processes, listens on ports or changes its own settings.
  • Sudden growth in outbound volume, even to allowed destinations.
  • Credentials used from an unexpected workload or place.
  • Denied cross-tenant requests, especially in sequence.

Decide which of these wake a person. In the July 2026 case, Hugging Face's timeline describes signals that were each ambiguous and, though later correlated, did not raise the severity enough to page on-call staff. Alerts that nobody must answer are only records.

Prove the boundaries

Test from inside a test sandboxExpected
Connect to an unlisted public hostFails and is logged
Connect to internal and metadata addressesFails and raises an alert
Read host files or environment secretsNothing sensitive present
Look for files from an earlier taskNone
Request another tenant's record with a valid sessionDenied by the data service
Replay or alter an agent messageRefused

Test only systems you are authorized to test, and repeat after infrastructure changes. A rule file that exists is not evidence that traffic is blocked.

Costs and choices

Stronger isolation costs start-up time, capacity and convenience. Match it to risk: a fixed set of reviewed tools may be fine in ordinary containers, while code written by a model from untrusted input deserves a stronger sandbox, no secrets and no network. Dedicated infrastructure per tenant is simplest to reason about and usually most expensive.

Common mistakes

MistakeBetter practice
Open outbound network "for installing packages"A hardened mirror, ideally prepared before the task
Checking only the first address or redirectCheck all, every hop
Letting the model supply the tenantTake it from identity
Caches and memory without tenant scopeScope every store
Trusting messages from "internal" agentsAuthenticate and authorize each one
Assuming the sandbox is perfectLayer controls and watch the exits

Checklist

  • Outbound traffic is denied unless listed, including quiet routes
  • Metadata and internal addresses are unreachable and tested
  • Tenant context comes from identity and reaches every store
  • Agent messages are authenticated, fresh and permission-checked
  • One component can be quarantined quickly

Frequently asked questions

Is a container enough for generated code?

It depends on the risk. Containers share the host kernel, so untrusted code often warrants a hardened runtime or virtual machine as well.

Can an address check in code stop all request forgery?

No. Use it with network enforcement, because code paths can bypass it and name answers can change.

Do agents in one process need signed messages?

Signatures add little inside one trust boundary, but permission checks and typed data still help. Sign across processes, teams or organizations.

Separate databases or row rules for tenants?

Separate stores give a clearer boundary; row rules cost less. Choose by risk and obligations, and test whichever you choose.

References and further reading

Next steps