Skip to content

API Reference

outbound_guard

Modules:

  • addresses –
  • aiohttp –
  • destinations –
  • guard –
  • smtp –
  • ssh –

Classes:

  • ConnectionCheck –

    Approves the addresses of one connection to host:port.

  • OutboundDenied –

    Raised when a destination resolves only to addresses that are neither public nor allowed.

  • OutboundGuard –

    Decides which addresses outbound connections may use.

Functions:

  • is_public_address –

    Whether an IP address is public. Raises ValueError if address is not an IP address.

  • normalize_host –

    Canonical form of a host name or IP address.

  • parse_destination –

    Parse an allowlist entry: host, host:port, IP, IP:port or [IPv6]:port.

ConnectionCheck

ConnectionCheck(guard: OutboundGuard, host: str, port: int | None)

Approves the addresses of one connection to host:port.

Methods:

  • filter_approved –

    Keep the results whose address is approved. Raises OutboundDenied if there were results but none is.

Source code in outbound_guard/guard.py
104
105
106
107
108
def __init__(self, guard: OutboundGuard, host: str, port: int | None) -> None:
    self.guard = guard
    self.host = host
    self.port = port
    self.allowed: frozenset[Destination] | None = None

filter_approved async

filter_approved[T](
    results: Iterable[T], get_address: Callable[[T], str]
) -> list[T]

Keep the results whose address is approved. Raises OutboundDenied if there were results but none is.

Source code in outbound_guard/guard.py
127
128
129
130
131
132
133
134
135
136
137
138
139
async def filter_approved[T](self, results: Iterable[T], get_address: Callable[[T], str]) -> list[T]:
    """Keep the results whose address is approved. Raises OutboundDenied if there were results but none is."""
    approved, denied = [], {}
    for result in results:
        address = get_address(result)
        if reason := await self.denial_reason(address):
            denied[address] = reason
        else:
            approved.append(result)
    if denied and not approved:
        reasons = ", ".join(dict.fromkeys(denied.values()))
        raise self.guard.deny(self.host, self.port, ", ".join(denied), reasons)
    return approved

OutboundDenied

OutboundDenied(host: str, port: int | None, reason: str)

              flowchart TD
              outbound_guard.OutboundDenied[OutboundDenied]

              

              click outbound_guard.OutboundDenied href "" "outbound_guard.OutboundDenied"
            

Raised when a destination resolves only to addresses that are neither public nor allowed.

Source code in outbound_guard/guard.py
25
26
27
28
29
def __init__(self, host: str, port: int | None, reason: str) -> None:
    super().__init__(errno.EACCES, f"Connections to {host}:{port} are not allowed: {reason}")
    self.host = host
    self.port = port
    self.reason = reason

OutboundGuard

OutboundGuard(
    allowed_hosts: Iterable[str] | AllowedHostsProvider = (), *, denial_hint: str = ""
)

Decides which addresses outbound connections may use.

Public addresses are always allowed. Other addresses are allowed only if the requested host or the address itself, with or without the port, is in allowed_hosts: a collection of entries (see parse_destination), or an async function returning one, so changes apply to the next connection. If the function fails or returns invalid entries, nothing internal is allowed.

denial_hint is appended to denial log messages (not to exceptions), e.g. to say where the allowlist is configured.

Methods:

  • connect –

    Open a TCP connection to host:port through approved addresses only, for protocols other than HTTP.

  • resolve –

    Resolve host for a TCP connection, keeping only the approved addresses. Raises OutboundDenied if none are.

Source code in outbound_guard/guard.py
56
57
58
59
60
61
62
63
def __init__(self, allowed_hosts: Iterable[str] | AllowedHostsProvider = (), *, denial_hint: str = "") -> None:
    self._provider: AllowedHostsProvider | None = None
    self._allowed: frozenset[Destination] = frozenset()
    if callable(allowed_hosts):
        self._provider = allowed_hosts
    else:
        self._allowed = parse_allowlist(allowed_hosts)
    self.denial_hint = denial_hint

connect async

connect(host: str, port: int, timeout: float) -> socket

Open a TCP connection to host:port through approved addresses only, for protocols other than HTTP.

Returns a connected blocking socket, which the caller owns. Raises OutboundDenied if no address is approved, TimeoutError or another OSError if connecting fails within timeout seconds.

Source code in outbound_guard/guard.py
90
91
92
93
94
95
96
97
98
async def connect(self, host: str, port: int, timeout: float) -> socket.socket:
    """Open a TCP connection to host:port through approved addresses only, for protocols other than HTTP.

    Returns a connected blocking socket, which the caller owns. Raises OutboundDenied if no address is approved,
    TimeoutError or another OSError if connecting fails within timeout seconds.
    """
    deadline = asyncio.get_running_loop().time() + timeout
    async with asyncio.timeout_at(deadline):
        return await connect_to_any(await self.resolve(host, port), deadline)

resolve async

resolve(host: str, port: int) -> list[AddrInfo]

Resolve host for a TCP connection, keeping only the approved addresses. Raises OutboundDenied if none are.

Source code in outbound_guard/guard.py
85
86
87
88
async def resolve(self, host: str, port: int) -> list[AddrInfo]:
    """Resolve host for a TCP connection, keeping only the approved addresses. Raises OutboundDenied if none are."""
    addr_infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM)
    return await ConnectionCheck(self, host, port).filter_approved(addr_infos, get_address)

is_public_address

is_public_address(address: str) -> bool

Whether an IP address is public. Raises ValueError if address is not an IP address.

Source code in outbound_guard/addresses.py
4
5
6
7
8
def is_public_address(address: str) -> bool:
    """Whether an IP address is public. Raises ValueError if address is not an IP address."""
    ip = ipaddress.ip_address(address)
    is_site_local = isinstance(ip, ipaddress.IPv6Address) and ip.is_site_local
    return ip.is_global and not (ip.is_multicast or ip.is_reserved or is_site_local)

normalize_host

normalize_host(host: str) -> str

Canonical form of a host name or IP address.

Source code in outbound_guard/destinations.py
27
28
29
def normalize_host(host: str) -> str:
    """Canonical form of a host name or IP address."""
    return str(ipaddress.ip_address(host)) if is_ip_address(host) else host.lower().removesuffix(".")

parse_destination

parse_destination(entry: str) -> Destination

Parse an allowlist entry: host, host:port, IP, IP:port or [IPv6]:port.

Raises ValueError for anything else, like URLs, CIDR ranges, wildcards, credentials or paths.

Source code in outbound_guard/destinations.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def parse_destination(entry: str) -> Destination:
    """Parse an allowlist entry: host, host:port, IP, IP:port or [IPv6]:port.

    Raises ValueError for anything else, like URLs, CIDR ranges, wildcards, credentials or paths.
    """
    error = ValueError(f"{entry!r} is not a host or host:port")
    if not isinstance(entry, str):
        raise error
    if is_ip_address(entry):
        return Destination(normalize_host(entry), None)
    try:
        url = urlsplit(f"//{entry}")
        port = url.port
    except ValueError:
        raise error from None
    host = normalize_host(url.hostname or "")
    is_valid = is_ip_address(host) or is_host_name(host)
    if not is_valid or url.netloc != entry or url.username is not None or entry.endswith(":"):
        raise error
    return Destination(host, port)

aiohttp

Classes:

  • GuardedConnector –

    A TCPConnector that connects only to addresses the guard approves and refuses proxies.

Functions:

  • limited_response_class –

    A ClientResponse class whose read(), text() and json() raise ClientPayloadError past max_size bytes.

  • session –

    Create an aiohttp session for URLs that users or other servers control.

GuardedConnector

GuardedConnector(guard: OutboundGuard, **kwargs: Any)

              flowchart TD
              outbound_guard.aiohttp.GuardedConnector[GuardedConnector]

              

              click outbound_guard.aiohttp.GuardedConnector href "" "outbound_guard.aiohttp.GuardedConnector"
            

A TCPConnector that connects only to addresses the guard approves and refuses proxies.

Other arguments are passed to TCPConnector.

Source code in outbound_guard/aiohttp.py
22
23
24
def __init__(self, guard: OutboundGuard, **kwargs: Any) -> None:
    super().__init__(**kwargs)
    self.guard = guard

limited_response_class cached

limited_response_class(max_size: int) -> type[ClientResponse]

A ClientResponse class whose read(), text() and json() raise ClientPayloadError past max_size bytes.

Source code in outbound_guard/aiohttp.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@functools.lru_cache
def limited_response_class(max_size: int) -> type[ClientResponse]:
    """A ClientResponse class whose read(), text() and json() raise ClientPayloadError past max_size bytes."""

    class LimitedResponse(ClientResponse):
        async def read(self) -> bytes:
            if self._body is None:
                try:
                    if (self.content_length or 0) > max_size and not self.content.at_eof():
                        raise ClientPayloadError(f"Response is larger than {max_size} bytes")
                    body = bytearray()
                    async for chunk in self.content.iter_any():
                        body += chunk
                        if len(body) > max_size:
                            raise ClientPayloadError(f"Response is larger than {max_size} bytes")
                    self._body = bytes(body)
                    for trace in self._traces:
                        await trace.send_response_chunk_received(self.method, self.url, self._body)
                except BaseException:
                    self.close()
                    raise
            return await super().read()

    return LimitedResponse

session

session(
    guard: OutboundGuard,
    *,
    timeout: ClientTimeout = DEFAULT_TIMEOUT,
    max_response_size: int = MAX_RESPONSE_SIZE,
    **kwargs: Any,
) -> ClientSession

Create an aiohttp session for URLs that users or other servers control.

Connections go only to addresses the guard approves, otherwise aiohttp.ClientOSError is raised. Proxies are not used. Reading a response with read(), text() or json() raises aiohttp.ClientPayloadError past max_response_size bytes; iterating response.content directly is not limited. Other arguments are passed to aiohttp.ClientSession, except connector, response_class and trust_env.

Source code in outbound_guard/aiohttp.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def session(
    guard: OutboundGuard,
    *,
    timeout: ClientTimeout = DEFAULT_TIMEOUT,
    max_response_size: int = MAX_RESPONSE_SIZE,
    **kwargs: Any,
) -> ClientSession:
    """Create an aiohttp session for URLs that users or other servers control.

    Connections go only to addresses the guard approves, otherwise aiohttp.ClientOSError is raised. Proxies are not
    used. Reading a response with read(), text() or json() raises aiohttp.ClientPayloadError past max_response_size
    bytes; iterating response.content directly is not limited. Other arguments are passed to aiohttp.ClientSession,
    except connector, response_class and trust_env.
    """
    return ClientSession(
        connector=GuardedConnector(guard),
        trust_env=False,
        timeout=timeout,
        response_class=limited_response_class(max_response_size),
        **kwargs,
    )

smtp

Functions:

  • connect_smtp –

    Create an aiosmtplib.SMTP client connected to hostname:port through an address the guard approves.

connect_smtp async

connect_smtp(
    guard: OutboundGuard,
    hostname: str,
    port: int,
    *,
    timeout: float = 10,
    **kwargs: Any,
) -> SMTP

Create an aiosmtplib.SMTP client connected to hostname:port through an address the guard approves.

The hostname is kept for TLS. timeout limits connecting and each SMTP command. Other arguments are passed to aiosmtplib.SMTP, e.g. username, password, use_tls or start_tls. The caller closes the client, e.g. with async with await connect_smtp(...) as client:.

Source code in outbound_guard/smtp.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
async def connect_smtp(
    guard: OutboundGuard, hostname: str, port: int, *, timeout: float = 10, **kwargs: Any
) -> aiosmtplib.SMTP:
    """Create an aiosmtplib.SMTP client connected to hostname:port through an address the guard approves.

    The hostname is kept for TLS. timeout limits connecting and each SMTP command. Other arguments are passed to
    aiosmtplib.SMTP, e.g. username, password, use_tls or start_tls. The caller closes the client, e.g. with
    `async with await connect_smtp(...) as client:`.
    """
    client = aiosmtplib.SMTP(hostname=hostname, timeout=timeout, **kwargs)
    sock = await guard.connect(hostname, port, timeout)
    try:
        await client.connect(sock=sock)
    except BaseException:
        client.close()
        sock.close()
        raise
    return client

ssh

Functions:

  • connect_ssh –

    Connect a paramiko.SSHClient to hostname:port through an address the guard approves.

connect_ssh async

connect_ssh(
    guard: OutboundGuard,
    client: SSHClient,
    hostname: str,
    port: int = 22,
    *,
    timeout: float = 10,
    **kwargs: Any,
) -> None

Connect a paramiko.SSHClient to hostname:port through an address the guard approves.

The hostname is kept for host key checks. timeout limits connecting and the key exchange. Other arguments are passed to SSHClient.connect, e.g. username, password, banner_timeout or auth_timeout.

Source code in outbound_guard/ssh.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
async def connect_ssh(
    guard: OutboundGuard, client: paramiko.SSHClient, hostname: str, port: int = 22, *, timeout: float = 10, **kwargs: Any
) -> None:
    """Connect a paramiko.SSHClient to hostname:port through an address the guard approves.

    The hostname is kept for host key checks. timeout limits connecting and the key exchange. Other arguments are
    passed to SSHClient.connect, e.g. username, password, banner_timeout or auth_timeout.
    """
    sock = await guard.connect(hostname, port, timeout)
    try:
        await asyncio.to_thread(client.connect, hostname, port, sock=sock, timeout=timeout, **kwargs)
    except BaseException:
        client.close()
        sock.close()
        raise