yaml Copy code
# High-Level Architecture: Policy-Driven Secrets Access Broker
# ========================================================
# - **Proxy Layer**: Envoy with chained WebAssembly (Wasm) filters for extensibility, zero-trust enforcement.
# - **Policy Engine**: Policies in Rego (OPA-compatible), compiled/injected into Wasm context or fetched via shared data.
# - **Secrets Backend**: HashiCorp Vault (or AWS Secrets Manager) for storage.
# - **Auditing**: Logs to Kafka/ELK stack.
# - **DR Drills**: Fault injection via Wasm (e.g., 1% request denial for chaos testing).
# - **Deployment**: Kubernetes with Envoy as sidecar or gateway.
#
# Flow:
# Client Request -> Envoy (Wasm: Eval Policy -> Audit Request) -> Vault -> Envoy (Wasm: Redact -> Audit Response -> DR Drill) -> Client
#
# Text Diagram:
# Client ──► [Envoy Proxy + Wasm Filters] ──► Vault Backend
# │
# ├── Request Eval Filter (Policy Check/ABAC)
# ├── Audit Filter (Log Ingress)
# │
# ◄── Response ── Redact Filter (Dynamic Masking)
# │ Audit Filter (Log Egress)
# └── DR Drill Filter (Fault Injection)
1. Envoy Configuration (envoy.yaml)
Deploy as Kubernetes ConfigMap or Helm chart. Uses envoyproxy/proxy-wasm SDK.
yaml Copy code
static_resources:
listeners:
- name: secrets_broker_listener
address:
socket_address: { address: 0.0.0.0, port_value: 8080 }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: secrets_broker
codec_type: AUTO
route_config:
name: local_route
virtual_hosts:
- name: secrets_broker
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: vault_backend }
http_filters:
- name: envoy.filters.http.wasm
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
config:
vm_config:
runtime: "envoy.wasm.runtime.v8" # Or wasmtime
code:
local:
filename: "/wasm/request_evaluation.wasm" # Policy eval
configuration:
"@type": type.googleapis.com/google.protobuf.StringValue
value: "policy:strict" # Shared config
- name: envoy.filters.http.wasm # Audit (request)
typed_config: ... # Similar, filename: "/wasm/auditing.wasm"
- name: envoy.filters.http.router # To backend
clusters:
- name: vault_backend
connect_timeout: 5s
type: STRICT_DNS
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: vault_backend
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address: { address: vault.secrets.svc.cluster.local, port_value: 8200 }
# Response filters (via Lua/Wasm on egress or post-backend)
# Chain additional Wasm on http_filters for response processing.
Kubernetes Deployment Snippet (for Envoy DaemonSet/Sidecar):
yaml Copy code
apiVersion: apps/v1
kind: Deployment
metadata:
name: secrets-broker
spec:
template:
spec:
containers:
- name: envoy
image: envoyproxy/envoy:v1.29-latest
volumeMounts:
- name: wasm-filters
mountPath: /wasm
volumeMounts:
- name: envoy-config
mountPath: /etc/envoy
volumes:
- name: wasm-filters
configMap:
name: wasm-modules # Contains .wasm files
2. Policy Definition (Rego for ABAC)
Store in Kubernetes ConfigMap or etcd, fetched by Wasm via Envoy SharedData.
rego Copy code
# policies.rego (loaded into Wasm context)
package secrets_access
default allow = false
allow {
input.method == "GET"
input.headers["x-user-id"][_] == user_id
user_role[user_id][_]
resource := split(input.path, "/")[1] # e.g., /api/prod/db-pass
permitted_resources[user_role[_]][resource]
}
user_role["alice"]["admin"]
permitted_resources["admin"]["*"] = true
# Redaction policy
redact_fields["password"] { input.context == "prod" }
3. WebAssembly Filters (Rust + proxy-wasm)
Compile with cargo wasm + proxy-wasm. Use wasmtime or Envoy's V8 runtime.
a. Request Evaluation Filter (request_evaluation.rs)
Evaluates policy; denies unauthorized requests.
rust Copy code
use proxy_wasm::traits::*;
use proxy_wasm::types::*;
use serde_json::Value;
proxy_wasm::main! {{
proxy_wasm::set_log_level(LogLevel::Info);
dispatcher! { SecretsEvalFilter }
}}
struct SecretsEvalFilter;
impl Context for SecretsEvalFilter {}
impl HttpContext for SecretsEvalFilter {
fn on_http_request_headers(&mut self, _num_headers: usize, _end_of_stream: bool) -> Action {
let headers = self.get_http_request_headers();
let path = self.get_http_request_path().unwrap_or_default();
let user_id = headers.iter().find(|h| h.0 == "x-user-id").map(|h| h.1.clone()).unwrap_or_default();
// Fetch policy from SharedData or compile Rego (use wasi-opa crate for runtime eval)
let policy_json = r#"{"method":"GET","headers":{"x-user-id":["alice"]},"path":"/prod/db"}"#;
let input: Value = serde_json::from_str(policy_json).unwrap();
// Pseudo-OPA eval (integrate proxy-wasm-opa or embed Rego compiler)
let allow = true; // Replace with rego::eval(input, policies)
if !allow {
self.send_http_response(403, vec![("x-deny-reason".to_string(), "Policy violation".to_string())], vec![]);
return Action::Pause;
}
Action::Continue
}
}
Build : cargo build --target wasm32-unknown-unknown --release, optimize with wasm-opt.
b. Dynamic Redaction Filter (dynamic_redaction.rs)
Redacts response body based on policy/context (e.g., mask passwords in non-prod).
rust Copy code
impl HttpContext for SecretsRedactFilter {
fn on_http_response_body(&mut self, body: &[u_byte], end_of_stream: bool) -> StreamInfo {
if !end_of_stream { return StreamInfo::Continue; }
let body_str = String::from_utf8_lossy(body);
let parsed: Value = serde_json::from_str(&body_str).unwrap_or_default();
// Policy-driven redaction
if parsed["context"] == "prod" {
if let Some(mut secret) = parsed.get_mut("data") {
secret["password"] = json!("***REDACTED***".into());
}
}
let redacted_body = serde_json::to_vec(&parsed).unwrap();
self.set_http_response_body(&redacted_body);
StreamInfo::Continue
}
}
c. Auditing Filter (auditing.rs)
Logs to stdout (sidecar to ELK) or Kafka via Wasm host calls.
rust Copy code
impl HttpContext for AuditFilter {
fn on_http_request_headers(&mut self, _num_headers: usize, _end_of_stream: bool) -> Action {
let log_entry = format!("REQ: {} {} user={:?}", self.get_http_method().unwrap(), self.get_http_path().unwrap(), get_user_id());
proxy_wasm::hostcalls::log(LogLevel::Info, &log_entry); // Or Kafka producer via Wasm extension
Action::Continue
}
fn on_http_response_headers(&mut self, _num_headers: usize) -> HttpHeadersAction {
// Similar for response audit
proxy_wasm::hostcalls::log(LogLevel::Info, &format!("RESP: {} status={}", self.get_http_path().unwrap(), self.get_http_response_status()));
HttpHeadersAction::Continue
}
}
d. Disaster Recovery Drills Filter (dr_drills.rs)
Injects faults (e.g., 0.5% denial, latency) for chaos testing. Toggle via config.
rust Copy code
impl HttpContext for DRDrillFilter {
fn on_http_request_headers(&mut self, _num_headers: usize, _end_of_stream: bool) -> Action {
let drill_rate: f64 = self.get_config_metadata("dr_rate").unwrap_or(0.005); // From Envoy config
if rand::random::<f64>() < drill_rate {
match rand::random::<u8>() % 3 {
0 => { self.send_http_response(503, vec![("x-drill".to_string(), "service-down".to_string())], vec![]); Action::Pause }
1 => { self.set_http_request_delay(5000); } // Latency injection
_ => {} // Partial failure
}
}
Action::Continue
}
}
Dependencies (Cargo.toml):
toml Copy code
[dependencies]
proxy-wasm = "0.2"
serde_json = "1.0"
rand = "0.8"
# wasi-opa = "0.1" # For Rego in Wasm
4. Deployment & Testing
Build Wasm :
code Copy code
for filter in eval redact audit dr; do
cd $filter && cargo build --target=wasm32-unknown-unknown --release && wasm-opt -O3 target/wasm32-unknown-unknown/release/$filter.wasm -o $filter.wasm
done
kubectl create configmap wasm-modules --from-file=/path/to/*.wasm
Policy Injection : Use Envoy ADS (xDS) to push Rego via SharedData API.
Testing :
bash Copy code
# Curl test
curl -H "x-user-id: alice" http://broker:8080/prod/db # Should succeed, redacted
curl -H "x-user-id: bob" http://broker:8080/prod/db # 403
# DR Drill verification (tail logs for 503s)
for i in {1..1000}; do curl ...; done | grep "x-drill"
Scaling/Monitoring :
Prometheus for Envoy metrics (wasm.vm.*).
Istio integration for mTLS.
Rollout: Blue-green with ArgoCD.
This broker enforces policies at the edge with sub-ms Wasm overhead, scales horizontally, and supports DR without downtime. Source code repo skeleton available on request. Questions, Holmes?