-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathrelay.rs
More file actions
412 lines (382 loc) · 14.3 KB
/
relay.rs
File metadata and controls
412 lines (382 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Protocol-aware bidirectional relay with L7 inspection.
//!
//! Replaces `copy_bidirectional` for endpoints with L7 configuration.
//! Parses each request within the tunnel, evaluates it against OPA policy,
//! and either forwards or denies the request.
use crate::l7::provider::{L7Provider, RelayOutcome};
use crate::l7::{EnforcementMode, L7EndpointConfig, L7Protocol, L7RequestInfo};
use crate::secrets::{self, SecretResolver};
use miette::{IntoDiagnostic, Result, miette};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use tracing::{debug, info, warn};
/// Context for L7 request policy evaluation.
pub struct L7EvalContext {
/// Host from the CONNECT request.
pub host: String,
/// Port from the CONNECT request.
pub port: u16,
/// Matched policy name from L4 evaluation.
pub policy_name: String,
/// Binary path (for cross-layer Rego evaluation).
pub binary_path: String,
/// Ancestor paths.
pub ancestors: Vec<String>,
/// Cmdline paths.
pub cmdline_paths: Vec<String>,
/// Supervisor-only placeholder resolver for outbound headers.
pub(crate) secret_resolver: Option<Arc<SecretResolver>>,
}
/// Run protocol-aware L7 inspection on a tunnel.
///
/// This replaces `copy_bidirectional` for L7-enabled endpoints.
/// Protocol detection (peek) is the caller's responsibility — this function
/// assumes the streams are already proven to carry the expected protocol.
/// For TLS-terminated connections, ALPN proves HTTP; for plaintext, the
/// caller peeks on the raw `TcpStream` before calling this.
pub async fn relay_with_inspection<C, U>(
config: &L7EndpointConfig,
engine: Mutex<regorus::Engine>,
client: &mut C,
upstream: &mut U,
ctx: &L7EvalContext,
) -> Result<()>
where
C: AsyncRead + AsyncWrite + Unpin + Send,
U: AsyncRead + AsyncWrite + Unpin + Send,
{
match config.protocol {
L7Protocol::Rest => relay_rest(config, &engine, client, upstream, ctx).await,
L7Protocol::Sql => {
// SQL provider is Phase 3 — fall through to passthrough with warning
warn!(
host = %ctx.host,
port = ctx.port,
"SQL L7 provider not yet implemented, falling back to passthrough"
);
tokio::io::copy_bidirectional(client, upstream)
.await
.into_diagnostic()?;
Ok(())
}
}
}
/// Handle an upgraded connection (101 Switching Protocols).
///
/// Forwards any overflow bytes from the upgrade response to the client, then
/// switches to raw bidirectional TCP copy for the upgraded protocol (WebSocket,
/// HTTP/2, etc.). L7 policy enforcement does not apply after the upgrade —
/// the initial HTTP request was already evaluated.
async fn handle_upgrade<C, U>(
client: &mut C,
upstream: &mut U,
overflow: Vec<u8>,
host: &str,
port: u16,
) -> Result<()>
where
C: AsyncRead + AsyncWrite + Unpin + Send,
U: AsyncRead + AsyncWrite + Unpin + Send,
{
info!(
host = %host,
port = port,
overflow_bytes = overflow.len(),
"101 Switching Protocols — switching to raw bidirectional relay \
(L7 enforcement no longer active)"
);
if !overflow.is_empty() {
client.write_all(&overflow).await.into_diagnostic()?;
client.flush().await.into_diagnostic()?;
}
tokio::io::copy_bidirectional(client, upstream)
.await
.into_diagnostic()?;
Ok(())
}
/// REST relay loop: parse request -> evaluate -> allow/deny -> relay response -> repeat.
async fn relay_rest<C, U>(
config: &L7EndpointConfig,
engine: &Mutex<regorus::Engine>,
client: &mut C,
upstream: &mut U,
ctx: &L7EvalContext,
) -> Result<()>
where
C: AsyncRead + AsyncWrite + Unpin + Send,
U: AsyncRead + AsyncWrite + Unpin + Send,
{
loop {
// Parse one HTTP request from client
let req = match crate::l7::rest::RestProvider.parse_request(client).await {
Ok(Some(req)) => req,
Ok(None) => return Ok(()), // Client closed connection
Err(e) => {
if is_benign_connection_error(&e) {
debug!(
host = %ctx.host,
port = ctx.port,
error = %e,
"L7 connection closed"
);
} else {
warn!(
host = %ctx.host,
port = ctx.port,
error = %e,
"HTTP parse error in L7 relay"
);
}
return Ok(()); // Close connection on parse error
}
};
// Rewrite credential placeholders in the request target BEFORE OPA
// evaluation. OPA sees the redacted path; the resolved path goes only
// to the upstream write.
let (eval_target, redacted_target) = if let Some(ref resolver) = ctx.secret_resolver {
match secrets::rewrite_target_for_eval(&req.target, resolver) {
Ok(result) => (result.resolved, result.redacted),
Err(e) => {
warn!(
host = %ctx.host,
port = ctx.port,
error = %e,
"credential resolution failed in request target, rejecting"
);
let response = b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
client.write_all(response).await.into_diagnostic()?;
client.flush().await.into_diagnostic()?;
return Ok(());
}
}
} else {
(req.target.clone(), req.target.clone())
};
let request_info = L7RequestInfo {
action: req.action.clone(),
target: redacted_target.clone(),
query_params: req.query_params.clone(),
};
// Evaluate L7 policy via Rego (using redacted target)
let (allowed, reason) = evaluate_l7_request(engine, ctx, &request_info)?;
// Check if this is an upgrade request for logging purposes.
let header_end = req
.raw_header
.windows(4)
.position(|w| w == b"\r\n\r\n")
.map_or(req.raw_header.len(), |p| p + 4);
let is_upgrade_request = {
let h = String::from_utf8_lossy(&req.raw_header[..header_end]);
h.lines()
.skip(1)
.any(|l| l.to_ascii_lowercase().starts_with("upgrade:"))
};
let decision_str = match (allowed, config.enforcement, is_upgrade_request) {
(true, _, true) => "allow_upgrade",
(true, _, false) => "allow",
(false, EnforcementMode::Audit, _) => "audit",
(false, EnforcementMode::Enforce, _) => "deny",
};
// Log every L7 decision (using redacted target — never log real secrets)
info!(
dst_host = %ctx.host,
dst_port = ctx.port,
policy = %ctx.policy_name,
l7_protocol = "rest",
l7_action = %request_info.action,
l7_target = %redacted_target,
l7_query_params = ?request_info.query_params,
l7_decision = decision_str,
l7_deny_reason = %reason,
"L7_REQUEST",
);
// Store the resolved target for the deny response redaction
let _ = &eval_target;
if allowed || config.enforcement == EnforcementMode::Audit {
// Forward request to upstream and relay response
let outcome = crate::l7::rest::relay_http_request_with_resolver(
&req,
client,
upstream,
ctx.secret_resolver.as_deref(),
)
.await?;
match outcome {
RelayOutcome::Reusable => {} // continue loop
RelayOutcome::Consumed => {
debug!(
host = %ctx.host,
port = ctx.port,
"Upstream connection not reusable, closing L7 relay"
);
return Ok(());
}
RelayOutcome::Upgraded { overflow } => {
return handle_upgrade(client, upstream, overflow, &ctx.host, ctx.port).await;
}
}
} else {
// Enforce mode: deny with 403 and close connection (use redacted target)
crate::l7::rest::RestProvider
.deny_with_redacted_target(
&req,
&ctx.policy_name,
&reason,
client,
Some(&redacted_target),
)
.await?;
return Ok(());
}
}
}
/// Check if a miette error represents a benign connection close.
///
/// TLS handshake EOF, missing `close_notify`, connection resets, and broken
/// pipes are all normal lifecycle events for proxied connections — not worth
/// a WARN that interrupts the user's terminal.
fn is_benign_connection_error(err: &miette::Report) -> bool {
const BENIGN: &[&str] = &[
"close_notify",
"tls handshake eof",
"connection reset",
"broken pipe",
"unexpected eof",
"client disconnected mid-request",
];
let msg = err.to_string().to_ascii_lowercase();
BENIGN.iter().any(|pat| msg.contains(pat))
}
/// Evaluate an L7 request against the OPA engine.
///
/// Returns `(allowed, deny_reason)`.
pub fn evaluate_l7_request(
engine: &Mutex<regorus::Engine>,
ctx: &L7EvalContext,
request: &L7RequestInfo,
) -> Result<(bool, String)> {
let input_json = serde_json::json!({
"network": {
"host": ctx.host,
"port": ctx.port,
},
"exec": {
"path": ctx.binary_path,
"ancestors": ctx.ancestors,
"cmdline_paths": ctx.cmdline_paths,
},
"request": {
"method": request.action,
"path": request.target,
"query_params": request.query_params.clone(),
}
});
let mut engine = engine
.lock()
.map_err(|_| miette!("OPA engine lock poisoned"))?;
engine
.set_input_json(&input_json.to_string())
.map_err(|e| miette!("{e}"))?;
let allowed = engine
.eval_rule("data.openshell.sandbox.allow_request".into())
.map_err(|e| miette!("{e}"))?;
let allowed = allowed == regorus::Value::from(true);
let reason = if allowed {
String::new()
} else {
let val = engine
.eval_rule("data.openshell.sandbox.request_deny_reason".into())
.map_err(|e| miette!("{e}"))?;
match val {
regorus::Value::String(s) => s.to_string(),
regorus::Value::Undefined => "request denied by policy".to_string(),
other => other.to_string(),
}
};
Ok((allowed, reason))
}
/// Relay HTTP traffic with credential injection only (no L7 OPA evaluation).
///
/// Used when TLS is auto-terminated but no L7 policy (`protocol` + `access`/`rules`)
/// is configured. Parses HTTP requests minimally to rewrite credential
/// placeholders and log requests for observability, then forwards everything.
pub async fn relay_passthrough_with_credentials<C, U>(
client: &mut C,
upstream: &mut U,
ctx: &L7EvalContext,
) -> Result<()>
where
C: AsyncRead + AsyncWrite + Unpin + Send,
U: AsyncRead + AsyncWrite + Unpin + Send,
{
let provider = crate::l7::rest::RestProvider;
let mut request_count: u64 = 0;
let resolver = ctx.secret_resolver.as_deref();
loop {
// Read next request from client.
let req = match provider.parse_request(client).await {
Ok(Some(req)) => req,
Ok(None) => break, // Client closed connection.
Err(e) => {
if is_benign_connection_error(&e) {
break;
}
return Err(e);
}
};
request_count += 1;
// Resolve and redact the target for logging.
let redacted_target = if let Some(ref res) = ctx.secret_resolver {
match secrets::rewrite_target_for_eval(&req.target, res) {
Ok(result) => result.redacted,
Err(e) => {
warn!(
host = %ctx.host,
port = ctx.port,
error = %e,
"credential resolution failed in request target, rejecting"
);
let response = b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
client.write_all(response).await.into_diagnostic()?;
client.flush().await.into_diagnostic()?;
return Ok(());
}
}
} else {
req.target.clone()
};
// Log for observability (using redacted target — never log real secrets).
let has_creds = resolver.is_some();
info!(
host = %ctx.host,
port = ctx.port,
method = %req.action,
path = %redacted_target,
credentials_injected = has_creds,
request_num = request_count,
"HTTP_REQUEST",
);
// Forward request with credential rewriting and relay the response.
// relay_http_request_with_resolver handles both directions: it sends
// the request upstream and reads the response back to the client.
let outcome =
crate::l7::rest::relay_http_request_with_resolver(&req, client, upstream, resolver)
.await?;
match outcome {
RelayOutcome::Reusable => {} // continue loop
RelayOutcome::Consumed => break,
RelayOutcome::Upgraded { overflow } => {
return handle_upgrade(client, upstream, overflow, &ctx.host, ctx.port).await;
}
}
}
debug!(
host = %ctx.host,
port = ctx.port,
total_requests = request_count,
"Credential injection relay completed"
);
Ok(())
}