Skip to main content
Inject credentials into outbound HTTP without ever exposing the real value to the guest. The guest only ever sees a placeholder; microsandbox’s TLS proxy swaps in the real secret on connections to allowed hosts and blocks everything else. See Secrets for how placeholder substitution works and usage examples.

Typical flow

use microsandbox::Sandbox;

let sb = Sandbox::builder("agent")
    .image("python")
    .secret(|s| s
        .env("OPENAI_API_KEY")             // guest sees $MSB_OPENAI_API_KEY
        .value(std::env::var("OPENAI_API_KEY")?)
        .allow_host("api.openai.com"))     // real value only reaches this host
    .create()
    .await?;

// In the guest, the placeholder is swapped for the real key
// only on TLS connections to api.openai.com.
let out = sb.exec("python", ["agent.py"]).await?;

Static methods

SecretBuilder::new()

fn new() -> SecretBuilder
use microsandbox::sandbox::SecretBuilder;

let entry = SecretBuilder::new()
    .env("STRIPE_KEY")
    .value(stripe_key)
    .allow_host("api.stripe.com")
    .build();
Start building a secret with defaults: no env var, no value, no allowed hosts, the default SecretInjection (headers and Basic Auth on, query and body off), no per-secret violation override, and require_tls_identity = true. You rarely call this yourself: SandboxBuilder::secret(|s| s...) hands you a fresh builder and calls build() for you. SecretBuilder::default() is equivalent.

Returns

A builder with default injection scopes.

SecretBuilder

Builder for one secret’s placeholder, allowed hosts, and injection scopes. Obtained through SandboxBuilder::secret(|s| s...) or SecretBuilder::new(); each secret maps an environment variable to a real value that is only revealed when traffic reaches an allowed host through the TLS proxy. Every setter returns Self, so calls chain. env(), value(), and at least one allowed host are required; build() panics otherwise. Import path: microsandbox::sandbox::SecretBuilder. Adding any secret automatically enables TLS interception.

.env()

fn env(self, var: impl Into<String>) -> Self
Set the environment variable name that holds the placeholder inside the guest. The guest sees $MSB_<var> (or a custom placeholder), never the real value. Names must be non-empty and cannot contain = or NUL; shell-identifier syntax is not required since Linux only requires a NAME=value shape. Required.

Parameters

varimpl Into<String>
Environment variable name (non-empty, no = or NUL).

.value()

fn value(self, value: impl Into<String>) -> Self
Set the real secret value. This is the string that replaces the placeholder when a request reaches an allowed host. It never enters the guest VM. Required.

Parameters

valueimpl Into<String>
The actual credential or token.

.placeholder()

fn placeholder(self, placeholder: impl Into<String>) -> Self
Override the auto-generated placeholder string. By default microsandbox generates $MSB_<env_var>. Use this when you need a specific format or when the placeholder must match a particular byte length. Placeholders must be non-empty, at most 1024 bytes (MAX_SECRET_PLACEHOLDER_BYTES), and cannot contain NUL, CR, or LF.

Parameters

placeholderimpl Into<String>
Custom placeholder string: non-empty, up to 1024 bytes, no NUL/CR/LF.

.allow_host()

fn allow_host(self, host: impl Into<String>) -> Self
.secret(|s| s
    .env("STRIPE_KEY")
    .value(stripe_key)
    .allow_host("api.stripe.com")
    .allow_host("files.stripe.com"))
Add an exact host allowed to receive the real secret value. The proxy checks the host against the connection’s verified TLS identity and observed DNS history. Can be called multiple times to allow several hosts. At least one allowed host (exact, pattern, or any) is required.

Parameters

hostimpl Into<String>
Exact hostname, e.g. “api.example.com”. Becomes a HostPattern::Exact.

.allow_host_pattern()

fn allow_host_pattern(self, pattern: impl Into<String>) -> Self
Add a wildcard host pattern. A *.suffix pattern matches the suffix itself and any single- or multi-label subdomain of it.

Parameters

patternimpl Into<String>
Wildcard pattern, e.g. “*.googleapis.com”. Becomes a HostPattern::Wildcard.

.allow_any_host_dangerous()

fn allow_any_host_dangerous(self, i_understand_the_risk: bool) -> Self
Allow substitution on any host. Every server the guest connects to can then receive the real secret, which effectively disables host-based protection. The call is a no-op unless i_understand_the_risk is true. Only use this when the secret is not sensitive or the sandbox network is fully locked down. Adds a HostPattern::Any to the allow list, the one pattern that skips DNS and TLS-identity pinning.

Parameters

i_understand_the_riskbool
Must be true to take effect.

.on_violation()

fn on_violation(
    self,
    f: impl FnOnce(ViolationActionBuilder) -> ViolationActionBuilder,
) -> Self
.secret(|s| s
    .env("API_KEY")
    .value(api_key)
    .allow_host("api.github.com")
    .on_violation(|v| v
        .block_and_log()
        .passthrough_host("api.anthropic.com")))
Configure violation behavior for this secret. Overrides the sandbox-wide secret violation policy and can let selected hosts receive the placeholder unchanged. See ViolationActionBuilder for the full set of block_* and passthrough_* methods. Passthrough hosts do not receive the real secret value; substitution still only happens for hosts configured with allow_host() or allow_host_pattern(). When a per-secret passthrough policy does not match the request host, microsandbox falls back to the sandbox-wide secret violation action.

Parameters

Configure the per-secret violation action.

.require_tls_identity()

fn require_tls_identity(self, enabled: bool) -> Self
When true, the secret is only substituted on TLS-intercepted connections where the proxy has verified it is performing MITM and the SNI matches an allowed host. Bypassed TLS is opaque and never receives substitution. Disable only when you know the traffic path is safe and explicitly supports non-TLS substitution. Default: true.

Parameters

enabledbool
Require verified TLS identity. Default: true.

.inject_headers()

fn inject_headers(self, enabled: bool) -> Self
Control whether the placeholder is replaced anywhere in HTTP headers. This is the most common injection scope, covering Authorization: Bearer $MSB_... and similar patterns. Default: true.

Parameters

enabledbool
Substitute in headers. Default: true.

.inject_basic_auth()

fn inject_basic_auth(self, enabled: bool) -> Self
Control whether Authorization: Basic <base64> credentials are decoded, substituted in the decoded user:password, then re-encoded. Orthogonal to inject_headers: this flag handles the encoded-credentials case for the Basic scheme; inject_headers handles literal substitution in any header line, including non-Basic Authorization schemes (Bearer, Digest). Default: true.

Parameters

enabledbool
Substitute inside Basic Auth credentials. Default: true.

.inject_query()

fn inject_query(self, enabled: bool) -> Self
Control whether the placeholder is replaced in the URL query string (the ?key=value portion of the request line). Default: false.

Parameters

enabledbool
Substitute in query parameters. Default: false.

.inject_body()

fn inject_body(self, enabled: bool) -> Self
Control whether the placeholder is replaced in HTTP/1 request bodies. Fixed-length bodies up to 16 MiB are substituted and their Content-Length updated; larger fixed-length bodies are blocked. Chunked bodies are decoded and re-encoded with fresh chunk sizes. Encoded bodies pass through unchanged. HTTP/2 DATA-frame substitution is not supported, so matching body placeholders are blocked rather than leaked. Default: false.

Parameters

enabledbool
Substitute in request bodies. Default: false.

.build()

fn build(self) -> SecretEntry
Materialize the SecretEntry. Called for you by SandboxBuilder::secret, so you rarely call it directly. If placeholder was not set, it defaults to $MSB_<env_var>.

Returns

The materialized secret entry.

Panics

Panics if env or value was not set, or if the allow list is empty. Use allow_any_host_dangerous(true) for an explicit any-host secret.

Shorthand

Two convenience methods on SandboxBuilder for the common cases, so you don’t have to spell out a SecretBuilder closure. Both automatically enable TLS interception.

.secret_env()

fn secret_env(
    self,
    env_var: impl Into<String>,
    value: impl Into<String>,
    allowed_host: impl Into<String>,
) -> Self
let sb = Sandbox::builder("agent")
    .image("python")
    .secret_env("OPENAI_API_KEY", api_key, "api.openai.com")
    .create()
    .await?;
Equivalent to .secret(|s| s.env(env_var).value(value).allow_host(allowed_host)). The placeholder is auto-generated as $MSB_<env_var> and the default injection scopes apply (headers and Basic Auth enabled, query and body disabled).

Parameters

env_varimpl Into<String>
Environment variable name (non-empty, no = or NUL).
valueimpl Into<String>
Secret value.
allowed_hostimpl Into<String>
Allowed destination host (exact match).

.secret_entry()

fn secret_entry(self, entry: SecretEntry) -> Self
use microsandbox::sandbox::SecretBuilder;

let entry = SecretBuilder::new()
    .env("STRIPE_KEY")
    .value(stripe_key)
    .allow_host("api.stripe.com")
    .build();

let sb = Sandbox::builder("billing")
    .image("python")
    .secret_entry(entry)
    .create()
    .await?;
Add a pre-built SecretEntry directly. This is the escape hatch when you already have a materialized entry, for example one produced by SecretBuilder::build(), loaded from configuration, or constructed by hand for full control over the serialized shape. Both secret() and secret_env() funnel through this method. The entry is validated when the sandbox is built; an invalid one surfaces as a config error rather than a panic.

Parameters

A materialized secret entry.

Types

HostPattern

used by SecretEntry · allow_host() · allow_host_pattern() · ViolationAction

Matches a destination host anywhere a secret policy needs one. Allow-list patterns decide where the real value may be substituted; passthrough patterns (on ViolationAction) decide where the placeholder may be forwarded unchanged. Passthrough patterns never make a secret eligible for substitution. Exact and wildcard allow-list entries are pinned to observed DNS answers and TLS identity; Any is the only allow-list pattern that skips this pinning.
VariantBuilder methodsMatches
Exact(String)allow_host(), passthrough_host()That exact host, ASCII case-insensitive
Wildcard(String)allow_host_pattern(), passthrough_host_pattern()The suffix and its subdomains, e.g. *.example.com
Anyallow_any_host_dangerous(true), passthrough_all_hosts(true)Every host
MethodSignatureDescription
matchesfn matches(&self, hostname: &str) -> boolWhether hostname matches this pattern (ASCII case-insensitive).

SecretEntry

returned by SecretBuilder::build() · used by secret_entry()

The materialized, serializable form of a secret that is handed to the network engine. The real value is redacted from the Debug output. Built for you by SecretBuilder; construct it directly only when you need full control over the serialized shape, then pass it to secret_entry().
FieldTypeDescription
env_varStringEnvironment variable holding the placeholder. Non-empty, no = or NUL.
valueStringThe real secret value (never enters the guest).
placeholderStringWhat the guest sees. Non-empty, at most 1024 bytes, no NUL/CR/LF.
allowed_hostsVec<HostPattern>Hosts allowed to receive the real value.
injectionSecretInjectionWhere in the request the value may be substituted.
on_violationOption<ViolationAction>Per-secret violation override. None falls back to the sandbox-wide action.
require_tls_identityboolRequire verified TLS identity before substituting. Default: true.
MethodSignatureDescription
validatefn validate(&self, secret_index: usize) -> Result<(), SecretConfigError>Validate this entry’s env var, allowed hosts, and placeholder.

SecretInjection

used by SecretEntry

Which parts of an outbound HTTP request the placeholder may be substituted in. Set through the inject_* methods on SecretBuilder.
FieldTypeDefaultDescription
headersbooltrueSubstitute anywhere in HTTP headers.
basic_authbooltrueSubstitute inside decoded Authorization: Basic credentials.
query_paramsboolfalseSubstitute in the URL query string.
bodyboolfalseSubstitute in HTTP/1 request bodies (see inject_body() for limits).

ViolationAction

used by SecretEntry · on_violation() · ViolationActionBuilder

What happens when the guest sends a request containing a secret placeholder to a host that is not in the secret’s substitution allow list. Built through ViolationActionBuilder, set globally via NetworkBuilder::on_secret_violation() or per secret via SecretBuilder::on_violation(). Also documented on the Networking page.
VariantDescription
BlockSilently drop the request. The guest sees a connection reset.
BlockAndLogDrop the request and emit a warning log on the host side. This is the default.
BlockAndTerminateDrop the request, log an error, and shut down the entire sandbox.
Passthrough(Vec<HostPattern>)Forward matching hosts with the placeholder unchanged. Non-matching hosts fall back to the default secret violation action.

SecretConfigError

returned by SecretEntry::validate()

Why a secret entry failed validation. Each variant carries the offending secret_index. The placeholder ceiling is the public constant MAX_SECRET_PLACEHOLDER_BYTES = 1024.
VariantDescription
EmptyEnvVarThe environment variable name is empty.
EnvVarContainsEqualsThe environment variable name contains =.
EnvVarContainsNulThe environment variable name contains NUL.
MissingAllowedHostsNo allowed hosts were configured.
EmptyPlaceholderThe placeholder is empty.
PlaceholderTooLongThe placeholder exceeds MAX_SECRET_PLACEHOLDER_BYTES (carries actual_bytes, max_bytes).
PlaceholderContainsNulThe placeholder contains NUL.
PlaceholderContainsLineBreakThe placeholder contains CR or LF.