One function call. Zero dependencies. No infrastructure changes.
API · Cookbook · Compatibility · Security
tethered checks every connection made through Python's socket layer against your allow list, from inside the process, before the connection is opened. activate() sets the ceiling for the whole process; scope() narrows a single code path.
import tethered
tethered.activate(allow=["*.stripe.com", "db.internal"])
import urllib.request
urllib.request.urlopen("https://api.stripe.com/v1/charges") # allowed: matches *.stripe.com
urllib.request.urlopen("https://evil.test/exfil") # raises tethered.EgressBlockedYour code, your dependencies and AI-generated code share one Python process, and any of them can open an outbound connection you never intended. Firewalls, network policies and proxies can stop that, but they take a platform team, a separate service or admin rights. tethered takes one line of Python. It complements those controls and does not replace them.
| Supply-chain defense | AI agent guardrails | Least privilege |
|---|---|---|
| A dependency that phones home or exfiltrates data through Python's networking is stopped: it reaches the hosts you listed and nothing else. | Code an agent wrote runs under the same allow list as the rest of the process, in production and in your test suite. | scope() holds a request handler, a background job or a library call to the destinations it needs. |
The check adds about 25 µs to a connect, and tethered looks each allowed host name up a second time, which costs one more DNS round trip where no cache answers it (measurements).
uv add tetheredOr pip install tethered. Python 3.11+ on Linux, macOS and Windows, with no runtime dependencies. Wheels are prebuilt; a source install needs a C compiler.
Upgrading from 0.5.x? 1.0 refuses to run where 0.5.x went on without enforcing, so a deployment can stop at start-up after the upgrade. Read the migration guide first.
# main.py, wsgi.py, manage.py: your entry point
import tethered
tethered.activate(allow=["*.stripe.com:443", "db.internal:5432"])
from myapp import create_app # import the application afterwards
app = create_app()Activate first, before your application and its dependencies are imported. Connections that are already open keep working, and processes started earlier are not reached, multiprocessing's fork server included: the workers it forks afterwards hold no policy either.
import httpx
import tethered
@tethered.scope(allow=["*.stripe.com:443"])
def charge(amount: int, token: str) -> dict:
# this function, and everything it calls, reaches *.stripe.com:443 only
return httpx.post("https://api.stripe.com/v1/charges", ...).json()A scope is a decorator or a with block, for sync and async code, and it works without activate(). With both in place a connection must be allowed by both: a scope narrows the policy and never widens it.
Writing a library? Use tethered in your tests, and leave both activate() and scope() to the application, which owns the process (guide for package authors).
Python children started with the same interpreter inherit the policy as they start: multiprocessing and ProcessPoolExecutor workers, gunicorn and uvicorn workers, subprocess.run([sys.executable, ...]). A child launched through subprocess inside a scope inherits the scope too.
Every other launch (curl, another interpreter, python -S) is external: logged by default, refused with external_subprocess_policy="block". The rules are on the subprocess page.
tethered.activate(
allow=["api.stripe.com:443", "db.internal:5432"],
locked=True, # replacing or switching off the policy takes the token
lock_token=object(), # ... and nobody keeps it
fail_closed=True, # an error inside the check blocks instead of allowing
external_subprocess_policy="block", # no shelling out to a program that does the egress
)Under a lock, monkey-patching tethered's functions or classes, or swapping its active policy, is detected and fails closed, and a Python child that cannot establish the locked policy refuses to start. Activate before importing third-party code: whatever runs earlier is not covered.
"block" also stops the helper programs libraries run, such as file for platform.architecture(), and code that expects OSError there fails (details). Locked mode is not a sandbox: the security model lists what it checks and what it does not stop.
- Check the environment.
python -m tethered check, run where the application runs, lists what tethered would refuse there, what it would not see and what needs configuration. It changes nothing (the check). - Enforce in your tests. Activate the policy, locked, from a session fixture in
conftest.py(example). A test that reaches a host you did not list fails, and production is not touched. - Observe in production with
log_only=True: every connection the policy would refuse is logged, and none is refused. The audit hook is installed all the same, each allowed host name is looked up a second time, and Python children inherit the policy. What tethered does not see is not logged (log-only mode). - Enforce once the log shows nothing the application needs: drop
log_only. - Lock it (above).
| Rule | Matches |
|---|---|
"api.stripe.com" |
That host, on any port |
"*.stripe.com" |
Any subdomain, a.b.stripe.com included; not stripe.com itself |
"api.stripe.com:443" |
That host on port 443 only |
"198.51.100.1", "10.0.0.0/8" |
An IPv4 address; a CIDR range |
"10.0.0.0/8:5432" |
A CIDR range on one port |
"[2001:db8::1]:443", "[2001:db8::]/32" |
IPv6, in brackets where a port or a prefix follows |
Wildcards follow Python's fnmatch and match text, not address ranges: 10.* also allows 10.attacker.example, so use CIDR for ranges. Localhost is allowed unless you pass allow_localhost=False. A malformed rule raises ValueError when the policy is set. The full syntax is in the API reference.
- A guardrail, not a sandbox. tethered works at Python's audit-event layer. Code that goes below it (
ctypes,cffi, a C extension making its own system calls) is not stopped, with or without locked mode. Where you need a guarantee, combine tethered with a control below Python: an egress proxy or a network policy that names the allowed hosts, containers, seccomp, network namespaces. The security model has the full threat model. - Libraries that connect in C are not seen. tethered sees what goes through Python's
socketmodule: requests, httpx, urllib3, aiohttp and the pure-Python database and broker clients. A library that resolves and connects inside its own C code (psycopg2, pycurl, grpcio) is not checked. The compatibility page says what was measured, server by server and library by library. - Under asyncio, the selector event loop only. A uvloop event loop raises no audit events, so tethered refuses to enforce a policy next to it, and uvicorn picks uvloop whenever it is installed. Name the loop (
uvicorn main:app --loop asyncio) or activate in a launcher script before the server is imported (server setup). - On Windows, run asyncio on
asyncio.SelectorEventLoop. The defaultProactorEventLoopconnects through calls that raise no audit event, so only DNS-time hostname checks apply there. - Free-threaded Python runs with the GIL once a policy is active. tethered's C extension does not declare free-threading support, so Python turns the GIL back on when it is loaded: by
activate(), and in a child process that inherits a policy or a scope. Importing tethered and entering ascope()do not load it.
The documentation is at tethered.shcherbak.ai, with an index for language models and coding agents at llms.txt.
- API reference:
activate,scope,deactivate, the exceptions, locked and log-only mode, the preflight check - Cookbook: what each server, task queue and pool needs; handling a blocked connection in Django, FastAPI and Celery; scopes in an application; tethered in a library's tests
- Compatibility: what is enforced, what needs configuration and what is not seen, measured under real servers, task queues and client libraries
- Subprocess control: how a policy and a scope reach child processes, and
external_subprocess_policy - Architecture: the audit hook, scopes, the C guardian, measured overhead
- Security model: the threat model, what tethered does and does not protect against, what locked mode adds
- Migrating to 1.0: upgrading from 0.5.x, with the breaking changes by what a deployment uses and what to do about each
- Changelog: what changed in each release
- Examples: twelve runnable scripts, one for each feature
- Contributing: development setup and guidelines
Questions or collaboration ideas? Reach out on LinkedIn or X. Built with ❤️ in Oslo, Norway.