How to Configure Credential Injection to Protect API Keys from Sandbox Access
CubeSandbox protects secret API keys by injecting them server-side into outbound HTTPS requests that match specific host/SNI rules, ensuring the sandbox process never has direct access to the credential.
CubeSandbox provides a secure isolation mechanism that prevents sandboxed code from accessing sensitive API keys while still allowing authenticated outbound requests. By configuring credential injection in the network.rules section of your sandbox creation request, you can authorize specific HTTPS endpoints to receive injected headers without exposing secrets to the container environment. This security model ensures that even if the sandbox is compromised, the API keys remain inaccessible to the attacker.
How Credential Injection Works in CubeSandbox
The injection mechanism operates entirely outside the sandbox namespace through the CubeEgress proxy. According to the TencentCloud/CubeSandbox source code, the network-agent receives egress rules as EgressRuleInject structs (defined in network-agent/internal/service/types.go at lines 55-60) and performs header injection only when the outbound request's TLS SNI matches the configured rule.
Server-Side Rule Matching
The Match clause specifies the target host, path, and HTTP method. This evaluation happens server-side in the CubeEgress proxy, not within the sandbox. As implemented in sdk/go/policy.go (lines 27-33) and sdk/python/cubesandbox/_policy.py (lines 58-66), the Match struct defines which outbound connections qualify for credential injection.
Allow-Only Action Requirement
For injection to occur, the rule must set allow: true in the Action configuration. If allow is false, the request is rejected with HTTP 403 and any configured inject entries are ignored. This requirement is enforced in both the Go SDK (sdk/go/policy.go, lines 44-50) and Python SDK (sdk/python/cubesandbox/_policy.py, lines 80-92).
Header Injection Format
The Inject entry specifies which HTTP header to add and what secret value to insert. The optional format field defaults to ${SECRET} and supports templates like Bearer ${SECRET} to accommodate standard authentication schemes. The proxy adds this header immediately before the request leaves the sandbox environment.
Step-by-Step Configuration Guide
Follow these steps to configure credential injection for your sandbox:
- Define the Match criteria – Specify the target host (SNI) in the
Matchstruct to identify which outbound connections should receive the secret. - Set the Allow flag – Ensure the
Actionhasallow: true; otherwise, injection is disabled. - Configure the Inject entry – Define the header name and secret value. Reference secrets stored in CubeEgress or provide literal values.
- Optional: Customize the format – Use the
formatfield to wrap the secret (e.g.,Bearer ${SECRET}) for standard authentication patterns. - Submit the sandbox request – Populate the
network.rulesfield in yourCreateSandboxRequestto serialize the rules into the wire format.
Implementation Examples
Go SDK Example
The Go SDK defines credential injection through the cubesandbox.Inject struct in sdk/go/policy.go. Below is a complete example that injects an API key into requests to api.example.com:
import (
"context"
"github.com/TencentCloud/CubeSandbox/sdk/go"
)
func createSandboxWithInject() (*cubesandbox.Sandbox, error) {
// Define the match – host = api.example.com
match := cubesandbox.Match{
Host: "api.example.com",
}
// Define the injection – header + secret
inject := cubesandbox.Inject{
Header: "X-Api-Key",
Secret: "MY_SUPER_SECRET",
// Format defaults to "${SECRET}"
}
// Assemble the action with allow: true
action := cubesandbox.Action{
Allow: true,
Inject: []cubesandbox.Inject{inject},
}
// Assemble the rule
rule := cubesandbox.Rule{
Name: "inject-api-key",
Match: match,
Action: action,
}
// Create the sandbox request with the network rule
req := cubesandbox.CreateSandboxRequest{
// ... other required fields ...
Network: cubesandbox.Network{
Rules: []cubesandbox.Rule{rule},
},
}
return client.CreateSandbox(context.Background(), &req)
}
Python SDK Example
The Python SDK provides equivalent functionality through cubesandbox._policy.Inject (defined in sdk/python/cubesandbox/_policy.py):
from cubesandbox import Sandbox, Network, Rule, Match, Action, Inject
# Match on the target host
match = Match(host="api.example.com")
# Define the injection with header and secret
inject = Inject(header="X-Api-Key", secret="MY_SUPER_SECRET")
# Action allowing the request and attaching the injection
action = Action(allow=True, inject=[inject])
# Assemble the complete rule
rule = Rule(name="inject-api-key", match=match, action=action)
# Build the sandbox creation payload
sandbox = Sandbox(
# ... other required fields ...
network=Network(rules=[rule])
)
# Create the sandbox
sandbox_id = sandbox.create()
print(f"Sandbox created: {sandbox_id}")
Key Source Files
Understanding the implementation requires referencing these specific files in the TencentCloud/CubeSandbox repository:
sdk/go/policy.go– Defines theMatch,Inject,Action, andRulestructs used by the Go SDK for policy configuration.sdk/python/cubesandbox/_policy.py– Provides equivalent Python dataclasses for credential injection configuration.network-agent/internal/service/types.go– Contains the internalEgressRuleInjectstruct that the proxy uses to perform server-side credential injection.
Summary
- Credential injection in CubeSandbox protects API keys by injecting them server-side into matching HTTPS requests.
- Rules must specify a Match criteria (host/SNI) and set Allow: true for injection to occur.
- The Inject struct defines the header name, secret value, and optional format template (e.g.,
Bearer ${SECRET}). - Implementation differs between Go (
cubesandbox.Inject) and Python (cubesandbox._policy.Inject) but follows the same security model. - Secrets never enter the sandbox environment, filesystem, or process memory, preventing extraction even if the container is compromised.
Frequently Asked Questions
Can the sandbox process read the injected API key?
No. The matching and injection occur server-side in the CubeEgress proxy outside the sandbox namespace. The sandbox process only sees the outgoing request after the header has been added by the trusted proxy.
What happens if I set allow: false but include inject rules?
The request is rejected with HTTP 403 status, and the injection rules are ignored. The allow: true setting is a strict prerequisite for credential injection as implemented in the network-agent.
Can I inject multiple headers or secrets into a single request?
Yes. The Inject field accepts an array of injection entries, allowing you to add multiple headers (e.g., API key and bearer token) to outbound requests that match the rule criteria.
How do I reference secrets stored in CubeEgress instead of hardcoding them?
While the examples show literal secrets, you can reference CubeEgress-managed secrets by using the appropriate secret reference syntax in the Secret field, ensuring credentials are centrally managed and rotated without code changes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →