Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add opt-in JSON diagnostics for TCP tunnels (#50131)

richardopenai8d44977aa2fb
diff --git a/codex-rs/tcp-tunnel/README.md b/codex-rs/tcp-tunnel/README.md
index 0e49499f05..a15406566a 100644
--- a/codex-rs/tcp-tunnel/README.md
+++ b/codex-rs/tcp-tunnel/README.md
@@ -5,3 +5,21 @@ The ordinary Codex binary includes the hidden `codex tcp-tunnel` command. It for
The initial bearer must be provided as a single line on standard input (`--auth-token-stdin`). With `--auth-token-updates-stdin`, later lines replace the bearer for new connections, emit `AUTH_UPDATED`, and closure of the controlling pipe stops the tunnel. With `--connect-headers-stdin`, the first line is instead a JSON list of `["x-name","value"]` pairs; token lines follow. Only non-forwarding `x-` extension headers are accepted. No header values or credentials belong in the command arguments.
The process emits `LISTENING 127.0.0.1:<port>` after connecting to the proxy. A proxy handshake does not authorize the target; each local connection makes its own authenticated CONNECT. The listener survives transport reconnects, but TCP streams are never replayed.
+
+`--diagnostics-json` opts into newline-delimited JSON on stderr. Version 1 contains
+`v`, `phase` (`startup`, `connect`, `transport`, or `control`), `code` (`failed`,
+`timeout`, `rejected`, `closed`, `draining`, or `invalid_input`), and `terminal`.
+A rejected CONNECT may also include a numeric `http_status` (100–599, excluding
+2xx). Records contain no credentials, addresses, headers, or raw error messages
+and are less than 256 bytes. Stdout readiness and credential acknowledgments are
+unchanged. A terminal record is flushed before an unsuccessful return; closing
+the controlling pipe normally emits no failure. The CLI may append a generic
+error line after the terminal record. Nonterminal events may concern
+one TCP stream or a reconnecting shared transport and do not identify the cause
+of a later child-process failure. Consumers must ignore records with unknown versions or fields and keep a generic
+fallback for helpers without this flag.
+
+Version 1 terminal combinations are `startup/{failed,timeout}`,
+`control/{failed,invalid_input}`, and `transport/failed`. Nonterminal combinations
+are `connect/{failed,rejected}` and `transport/{failed,timeout,closed,draining}`.
+Other combinations are unknown records and must use the generic fallback.
diff --git a/codex-rs/tcp-tunnel/src/diagnostics.rs b/codex-rs/tcp-tunnel/src/diagnostics.rs
new file mode 100644
index 0000000000..2b865b7bef
--- /dev/null
+++ b/codex-rs/tcp-tunnel/src/diagnostics.rs
@@ -0,0 +1,139 @@
+//! Opt-in, bounded diagnostics contain only classifications, never error-chain or wire values.
+//! Nonterminal records describe one stream or a recoverable shared-transport event.
+use std::fmt;
+use std::io::Write;
+
+use anyhow::Result;
+use anyhow::anyhow;
+use http::StatusCode;
+
+#[derive(Clone, Copy)]
+pub(super) enum Diagnostics {
+ Human,
+ Json,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub(super) enum Phase {
+ Startup,
+ Connect,
+ Transport,
+ Control,
+}
+
+impl fmt::Display for Phase {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::Startup => "startup",
+ Self::Connect => "connect",
+ Self::Transport => "transport",
+ Self::Control => "control",
+ })
+ }
+}
+
+#[derive(Debug)]
+pub(super) enum Code {
+ Failed,
+ Timeout,
+ HandshakeTimeout,
+ Rejected(StatusCode),
+ Closed,
+ Draining,
+ InvalidInput,
+}
+
+impl fmt::Display for Code {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Failed => f.write_str("failed"),
+ Self::HandshakeTimeout => {
+ f.write_str("QUIC handshake failed: QUIC handshake timed out")
+ }
+ Self::Timeout => f.write_str("connecting to MASQUE proxy timed out"),
+ Self::Rejected(status) => {
+ write!(f, "MASQUE CONNECT rejected with status {}", status.as_u16())
+ }
+ Self::Closed => f.write_str("closed"),
+ Self::Draining => f.write_str("draining"),
+ Self::InvalidInput => f.write_str("invalid control input"),
+ }
+ }
+}
+
+impl std::error::Error for Code {}
+
+impl Diagnostics {
+ pub(super) fn with_phase<T>(self, result: Result<T>, phase: Phase) -> Result<T> {
+ match self {
+ Self::Human => result,
+ Self::Json => result.map_err(|error| error.context(phase)),
+ }
+ }
+
+ pub(super) fn finish(
+ self,
+ result: Result<()>,
+ phase: Phase,
+ output: &mut impl Write,
+ ) -> Result<()> {
+ match (self, result) {
+ (Self::Json, Err(error)) => {
+ Self::write(output, phase, &error, /*terminal*/ true);
+ // The CLI formats returned errors. Do not let its top-level handler print the raw chain.
+ Err(anyhow!("TCP tunnel failed"))
+ }
+ (_, result) => result,
+ }
+ }
+
+ pub(super) fn report(self, phase: Phase, error: &anyhow::Error, human: fmt::Arguments<'_>) {
+ match self {
+ Self::Human => eprintln!("{human}"),
+ Self::Json => Self::write(
+ &mut std::io::stderr().lock(),
+ phase,
+ error,
+ /*terminal*/ false,
+ ),
+ }
+ }
+
+ fn write(output: &mut impl Write, phase: Phase, error: &anyhow::Error, terminal: bool) {
+ let phase = error.downcast_ref::<Phase>().copied().unwrap_or(phase);
+ let fallback = if matches!(phase, Phase::Control)
+ && error.downcast_ref::<std::io::Error>().is_none()
+ {
+ Code::InvalidInput
+ } else {
+ Code::Failed
+ };
+ let code = error.downcast_ref::<Code>().unwrap_or(&fallback);
+ let mut record = serde_json::json!({
+ "v": 1,
+ "phase": phase.to_string(),
+ "code": match code {
+ Code::Failed => "failed",
+ Code::Timeout | Code::HandshakeTimeout => "timeout",
+ Code::Rejected(_) => "rejected",
+ Code::Closed => "closed",
+ Code::Draining => "draining",
+ Code::InvalidInput => "invalid_input",
+ },
+ "terminal": terminal,
+ });
+ if let (Phase::Connect, Code::Rejected(status)) = (phase, code)
+ && (100..600).contains(&status.as_u16())
+ && !status.is_success()
+ {
+ record["http_status"] = status.as_u16().into();
+ }
+ // All fields are bounded enums or numbers; one locked, flushed line precedes process exit.
+ let _ = writeln!(output, "{record}");
+ let _ = output.flush();
+ }
+}
+
+#[cfg(test)]
+#[path = "diagnostics_tests.rs"]
+mod tests;
diff --git a/codex-rs/tcp-tunnel/src/diagnostics_tests.rs b/codex-rs/tcp-tunnel/src/diagnostics_tests.rs
new file mode 100644
index 0000000000..7e9b862094
--- /dev/null
+++ b/codex-rs/tcp-tunnel/src/diagnostics_tests.rs
@@ -0,0 +1,132 @@
+use super::Code;
+use super::Diagnostics;
+use super::Phase;
+use anyhow::Context;
+use anyhow::anyhow;
+use http::StatusCode;
+use pretty_assertions::assert_eq;
+use serde_json::json;
+
+#[test]
+fn fatal_diagnostic_drops_untrusted_error_chain_and_flushes_one_record() {
+ #[derive(Default)]
+ struct Output {
+ bytes: Vec<u8>,
+ flushes: usize,
+ }
+ impl std::io::Write for Output {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.bytes.extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ self.flushes += 1;
+ Ok(())
+ }
+ }
+ let mut output = Output::default();
+ let error = Diagnostics::Json
+ .finish(
+ Err(anyhow!(
+ "Bearer secret; x-route: private; https://private.example/path"
+ ))
+ .context(Code::Timeout),
+ Phase::Startup,
+ &mut output,
+ )
+ .unwrap_err();
+ assert_eq!(format!("{error:#}"), "TCP tunnel failed");
+ assert_eq!(output.flushes, 1);
+ assert!(output.bytes.len() < 256);
+ assert_eq!(
+ output.bytes.iter().filter(|&&byte| byte == b'\n').count(),
+ 1
+ );
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&output.bytes).unwrap(),
+ json!({
+ "v": 1, "phase": "startup", "code": "timeout", "terminal": true,
+ })
+ );
+}
+
+#[test]
+fn control_io_failure_and_invalid_input_have_distinct_safe_codes() {
+ for (error, code) in [
+ (anyhow!("invalid private bearer"), "invalid_input"),
+ (
+ anyhow!(std::io::Error::other("private input failure")),
+ "failed",
+ ),
+ ] {
+ let mut output = Vec::new();
+ Diagnostics::Json
+ .finish(
+ Err(error).context(Phase::Control),
+ Phase::Startup,
+ &mut output,
+ )
+ .unwrap_err();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&output).unwrap(),
+ json!({
+ "v": 1, "phase": "control", "code": code, "terminal": true,
+ })
+ );
+ }
+}
+
+#[test]
+fn connect_rejection_is_nonterminal_and_contains_only_valid_status() {
+ for status in [403, 407, 503, 999] {
+ let mut output = Vec::new();
+ let error = anyhow!("private proxy response body")
+ .context(Code::Rejected(StatusCode::from_u16(status).unwrap()));
+ Diagnostics::write(&mut output, Phase::Connect, &error, /*terminal*/ false);
+ let mut expected =
+ json!({"v": 1, "phase": "connect", "code": "rejected", "terminal": false});
+ if status < 600 {
+ expected["http_status"] = status.into();
+ }
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&output).unwrap(),
+ expected
+ );
+ }
+}
+
+#[test]
+fn legacy_errors_and_successful_shutdown_produce_no_json() {
+ let mut output = Vec::new();
+ let result = Diagnostics::Human.with_phase(Err(anyhow!("legacy error")), Phase::Transport);
+ let error = Diagnostics::Human
+ .finish(result, Phase::Startup, &mut output)
+ .unwrap_err();
+ assert_eq!(format!("{error:#}"), "legacy error");
+ Diagnostics::Json
+ .finish(Ok(()), Phase::Control, &mut output)
+ .unwrap();
+ assert!(output.is_empty());
+}
+
+#[test]
+fn handshake_timeout_preserves_legacy_debug_output() {
+ let error = anyhow!(Code::HandshakeTimeout);
+ assert_eq!(
+ format!("{error:?}"),
+ "QUIC handshake failed: QUIC handshake timed out"
+ );
+ let mut output = Vec::new();
+ Diagnostics::write(
+ &mut output,
+ Phase::Transport,
+ &error,
+ /*terminal*/ false,
+ );
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&output).unwrap(),
+ json!({
+ "v": 1, "phase": "transport", "code": "timeout", "terminal": false,
+ })
+ );
+}
diff --git a/codex-rs/tcp-tunnel/src/lib.rs b/codex-rs/tcp-tunnel/src/lib.rs
index 2908a504fd..b907363864 100644
--- a/codex-rs/tcp-tunnel/src/lib.rs
+++ b/codex-rs/tcp-tunnel/src/lib.rs
@@ -36,6 +36,11 @@ use url::Host;
use url::Url;
mod control;
+mod diagnostics;
+
+use diagnostics::Code;
+use diagnostics::Diagnostics;
+use diagnostics::Phase;
use control::read_auth_token;
use control::read_connect_headers;
@@ -64,6 +69,9 @@ pub struct Args {
/// Read a JSON list of extension-header name/value pairs before the first bearer.
#[arg(long, requires = "auth_token_stdin")]
connect_headers_stdin: bool,
+ /// Emit credential-safe JSON diagnostics on stderr instead of human-readable errors.
+ #[arg(long)]
+ diagnostics_json: bool,
}
#[derive(Debug, PartialEq, Eq)]
@@ -156,68 +164,83 @@ fn parse_trusted_origins(origins: &str) -> Result<Vec<String>> {
mod tests;
pub async fn run(args: Args) -> Result<()> {
- ensure!(args.auth_token_stdin, "--auth-token-stdin is required");
- ensure!(
- args.listen_addr.ip().is_loopback(),
- "listener must be loopback"
- );
- let origins = std::fs::read_to_string(&args.proxy_origins_file)
- .context("reading trusted proxy origins")?;
- let trusted_origins = parse_trusted_origins(&origins)?;
- let target = ProxyTarget::parse(&args.proxy_url, &trusted_origins, &args.target)?;
- let (metadata, mut tokens) = control_input(
- std::io::BufReader::new(std::io::stdin()),
- args.connect_headers_stdin,
- )?;
- let connect = metadata.await.context("CONNECT metadata input closed")??;
- let initial_auth = tokens
- .recv()
- .await
- .context("MASQUE credential input closed")??
- .context("empty MASQUE token")?;
- let (updates, auth) = watch::channel(initial_auth);
- let headers = TunnelHeaders { auth, connect };
-
- let listener = TcpListener::bind(args.listen_addr)
- .await
- .context("binding loopback listener")?;
- let native = rustls_native_certs::load_native_certs();
- let mut roots = rustls::RootCertStore::empty();
- roots.add_parsable_certificates(native.certs);
- ensure!(
- !roots.is_empty(),
- "no native TLS roots: {:?}",
- native.errors
- );
- let mut tls = rustls::ClientConfig::builder_with_provider(Arc::new(
- rustls::crypto::ring::default_provider(),
- ))
- .with_safe_default_protocol_versions()?
- .with_root_certificates(roots)
- .with_no_client_auth();
- tls.alpn_protocols = vec![b"h3".to_vec()];
- let mut config = quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls)?));
- let mut transport = quinn::TransportConfig::default();
- transport.max_idle_timeout(Some(Duration::from_secs(30).try_into()?));
- transport.keep_alive_interval(Some(Duration::from_secs(10)));
- config.transport_config(Arc::new(transport));
- let (ready, readiness) = oneshot::channel();
- let tunnel = async move {
- let connected = ProxyConnection::connect(&target, &config).await?;
- // The line is the caller readiness contract, including the assigned port.
- writeln!(std::io::stdout(), "LISTENING {}", listener.local_addr()?)?;
- std::io::stdout().flush()?;
- let _ = ready.send(());
- serve(listener, target, config, headers, connected).await
+ let diagnostics = if args.diagnostics_json {
+ Diagnostics::Json
+ } else {
+ Diagnostics::Human
};
- if args.auth_token_updates_stdin {
- tokio::select! {
- result = tunnel => result,
- result = update_auth_tokens(&mut tokens, updates, readiness, std::io::stdout()) => result,
+ let mut phase = Phase::Startup;
+ let result = async {
+ ensure!(args.auth_token_stdin, "--auth-token-stdin is required");
+ ensure!(
+ args.listen_addr.ip().is_loopback(),
+ "listener must be loopback"
+ );
+ let origins = std::fs::read_to_string(&args.proxy_origins_file)
+ .context("reading trusted proxy origins")?;
+ let trusted_origins = parse_trusted_origins(&origins)?;
+ let target = ProxyTarget::parse(&args.proxy_url, &trusted_origins, &args.target)?;
+ phase = Phase::Control;
+ let (metadata, mut tokens) = control_input(
+ std::io::BufReader::new(std::io::stdin()),
+ args.connect_headers_stdin,
+ )?;
+ let connect = metadata.await.context("CONNECT metadata input closed")??;
+ let initial_auth = tokens
+ .recv()
+ .await
+ .context("MASQUE credential input closed")??
+ .context("empty MASQUE token")?;
+ phase = Phase::Startup;
+ let (updates, auth) = watch::channel(initial_auth);
+ let headers = TunnelHeaders { auth, connect };
+
+ let listener = TcpListener::bind(args.listen_addr)
+ .await
+ .context("binding loopback listener")?;
+ let native = rustls_native_certs::load_native_certs();
+ let mut roots = rustls::RootCertStore::empty();
+ roots.add_parsable_certificates(native.certs);
+ ensure!(
+ !roots.is_empty(),
+ "no native TLS roots: {:?}",
+ native.errors
+ );
+ let mut tls = rustls::ClientConfig::builder_with_provider(Arc::new(
+ rustls::crypto::ring::default_provider(),
+ ))
+ .with_safe_default_protocol_versions()?
+ .with_root_certificates(roots)
+ .with_no_client_auth();
+ tls.alpn_protocols = vec![b"h3".to_vec()];
+ let mut config = quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls)?));
+ let mut transport = quinn::TransportConfig::default();
+ transport.max_idle_timeout(Some(Duration::from_secs(30).try_into()?));
+ transport.keep_alive_interval(Some(Duration::from_secs(10)));
+ config.transport_config(Arc::new(transport));
+ let (ready, readiness) = oneshot::channel();
+ let tunnel = async move {
+ let connected = ProxyConnection::connect(&target, &config).await?;
+ // The line is the caller readiness contract, including the assigned port.
+ writeln!(std::io::stdout(), "LISTENING {}", listener.local_addr()?)?;
+ std::io::stdout().flush()?;
+ let _ = ready.send(());
+ diagnostics.with_phase(
+ serve(listener, target, config, headers, connected, diagnostics).await,
+ Phase::Transport,
+ )
+ };
+ if args.auth_token_updates_stdin {
+ tokio::select! {
+ result = tunnel => result,
+ result = update_auth_tokens(&mut tokens, updates, readiness, std::io::stdout()) => diagnostics.with_phase(result, Phase::Control),
+ }
+ } else {
+ tunnel.await
}
- } else {
- tunnel.await
}
+ .await;
+ diagnostics.finish(result, phase, &mut std::io::stderr().lock())
}
type TokenStream = mpsc::Receiver<Result<Option<HeaderValue>>>;
@@ -278,7 +301,7 @@ fn control_input(
impl ProxyConnection {
async fn connect(target: &ProxyTarget, config: &quinn::ClientConfig) -> Result<Self> {
tokio::time::timeout(PROXY_CONNECT_TIMEOUT, async {
- let mut last_error = "MASQUE proxy resolved to no addresses".to_owned();
+ let mut last_error = anyhow!("MASQUE proxy resolved to no addresses");
for peer in tokio::net::lookup_host((target.host.as_str(), target.port)).await? {
let bind = match peer.ip() {
IpAddr::V4(_) => "0.0.0.0:0",
@@ -287,7 +310,7 @@ impl ProxyConnection {
let mut endpoint = match quinn::Endpoint::client(bind.parse()?) {
Ok(endpoint) => endpoint,
Err(error) => {
- last_error = error.to_string();
+ last_error = anyhow!(error.to_string());
continue;
}
};
@@ -295,18 +318,18 @@ impl ProxyConnection {
let connecting = match endpoint.connect(peer, &target.host) {
Ok(connecting) => connecting,
Err(error) => {
- last_error = error.to_string();
+ last_error = anyhow!(error.to_string());
continue;
}
};
let quic = match tokio::time::timeout(Duration::from_secs(5), connecting).await {
Ok(Ok(quic)) => quic,
Ok(Err(error)) => {
- last_error = error.to_string();
+ last_error = anyhow!(error.to_string());
continue;
}
Err(_) => {
- last_error = "QUIC handshake timed out".to_owned();
+ last_error = Code::HandshakeTimeout.into();
continue;
}
};
@@ -317,7 +340,7 @@ impl ProxyConnection {
{
Ok(connection) => connection,
Err(error) => {
- last_error = error.to_string();
+ last_error = anyhow!(error.to_string());
continue;
}
};
@@ -328,10 +351,17 @@ impl ProxyConnection {
sender,
});
}
- bail!("QUIC handshake failed: {last_error}");
+ if matches!(
+ last_error.downcast_ref::<Code>(),
+ Some(Code::HandshakeTimeout)
+ ) {
+ Err(last_error)
+ } else {
+ bail!("QUIC handshake failed: {last_error}")
+ }
})
.await
- .context("connecting to MASQUE proxy timed out")?
+ .context(Code::Timeout)?
}
}
@@ -341,6 +371,7 @@ async fn serve(
config: quinn::ClientConfig,
headers: TunnelHeaders,
mut connected: ProxyConnection,
+ diagnostics: Diagnostics,
) -> Result<()> {
loop {
let ProxyConnection {
@@ -364,7 +395,11 @@ async fn serve(
request.headers_mut().insert(header::AUTHORIZATION, headers.auth.borrow().clone());
tokio::spawn(async move {
if let Err(error) = bridge(socket, &mut sender, request, draining).await {
- eprintln!("MASQUE TCP connection failed: {error:#}");
+ diagnostics.report(
+ Phase::Connect,
+ &error,
+ format_args!("MASQUE TCP connection failed: {error:#}"),
+ );
}
});
}
@@ -379,7 +414,11 @@ async fn serve(
drop(sender);
match failure {
ProxyClosure::Draining => {
- eprintln!("MASQUE HTTP/3 proxy is draining; reconnecting");
+ diagnostics.report(
+ Phase::Transport,
+ &Code::Draining.into(),
+ format_args!("MASQUE HTTP/3 proxy is draining; reconnecting"),
+ );
// A refused new CONNECT is not replayed. Accepted streams keep their old transport.
tokio::spawn(async move {
tokio::select! {
@@ -393,7 +432,11 @@ async fn serve(
driver.abort();
quic.close(/*error_code*/ 0_u8.into(), b"reconnecting");
drop(endpoint);
- eprintln!("MASQUE proxy connection lost; reconnecting: {error:#}");
+ diagnostics.report(
+ Phase::Transport,
+ &Code::Closed.into(),
+ format_args!("MASQUE proxy connection lost; reconnecting: {error:#}"),
+ );
}
}
@@ -422,7 +465,11 @@ async fn serve(
break;
}
Err(error) => {
- eprintln!("MASQUE proxy reconnect failed: {error:#}");
+ diagnostics.report(
+ Phase::Transport,
+ &error,
+ format_args!("MASQUE proxy reconnect failed: {error:#}"),
+ );
retry_delay = (retry_delay * 2).min(Duration::from_secs(15));
}
}
@@ -451,7 +498,7 @@ async fn bridge(
.context("receiving CONNECT response")?
.status();
if !status.is_success() {
- bail!("MASQUE CONNECT rejected with status {}", status.as_u16());
+ return Err(Code::Rejected(status).into());
}
let (mut send, mut recv) = stream.split();
let (mut local_read, mut local_write) = socket.split();
diff --git a/codex-rs/tcp-tunnel/src/lib_tests.rs b/codex-rs/tcp-tunnel/src/lib_tests.rs
index 1a3d83699a..6af4fffec9 100644
--- a/codex-rs/tcp-tunnel/src/lib_tests.rs
+++ b/codex-rs/tcp-tunnel/src/lib_tests.rs
@@ -31,6 +31,7 @@ use super::control::MAX_CONNECT_METADATA_BYTES;
use super::control::MAX_TOKEN_BYTES;
use super::control::read_connect_headers;
use super::control_input;
+use super::diagnostics::Diagnostics;
use super::parse_trusted_origins;
use super::serve;
use super::update_auth_tokens;
@@ -272,6 +273,14 @@ async fn transport_reconnect_keeps_listener_and_does_not_replay_old_tcp_streams(
request.headers()["x-test-route"].clone(),
))
.unwrap();
+ if request.headers()[http::header::AUTHORIZATION] == "Bearer rejected-test" {
+ stream
+ .send_response(Response::builder().status(403).body(()).unwrap())
+ .await
+ .unwrap();
+ stream.finish().await.unwrap();
+ continue;
+ }
request_count.fetch_add(1, Ordering::SeqCst);
tokio::spawn(async move {
if stream
@@ -306,7 +315,14 @@ async fn transport_reconnect_keeps_listener_and_does_not_replay_old_tcp_streams(
connect: read_connect_headers(&mut &b"[[\"x-test-route\",\"custom-route\"]]\n"[..])?,
};
let initial = ProxyConnection::connect(&target, &config).await?;
- let client = tokio::spawn(serve(listener, target, config, headers, initial));
+ let client = tokio::spawn(serve(
+ listener,
+ target,
+ config,
+ headers,
+ initial,
+ Diagnostics::Json,
+ ));
let (first_connection, _) = timeout(Duration::from_secs(5), connections.recv())
.await?
.unwrap();
@@ -319,6 +335,17 @@ async fn transport_reconnect_keeps_listener_and_does_not_replay_old_tcp_streams(
("Bearer local-test".parse()?, "custom-route".parse()?)
);
+ updates.send_replace("Bearer rejected-test".parse()?);
+ let mut rejected = TcpStream::connect(address).await?;
+ assert_eq!(
+ timeout(Duration::from_secs(5), rejected.read(&mut data)).await??,
+ 0
+ );
+ assert_eq!(
+ tokens.recv().await.unwrap(),
+ ("Bearer rejected-test".parse()?, "custom-route".parse()?)
+ );
+
updates.send_replace("Bearer replacement-test".parse()?);
let mut refreshed = TcpStream::connect(address).await?;
timeout(Duration::from_secs(5), refreshed.read_exact(&mut data)).await??;
@@ -377,3 +404,37 @@ async fn transport_reconnect_keeps_listener_and_does_not_replay_old_tcp_streams(
server.abort();
Ok(())
}
+
+#[test]
+fn diagnostics_flag_is_optional_and_advertised() {
+ #[derive(clap::Parser)]
+ struct Cli {
+ #[command(flatten)]
+ args: super::Args,
+ }
+ use clap::CommandFactory;
+ use clap::Parser;
+ let args = [
+ "tcp-tunnel",
+ "--proxy-url",
+ "https://proxy.example",
+ "--proxy-origins-file",
+ "origins",
+ "--target",
+ "target:22",
+ "--auth-token-stdin",
+ ];
+ assert!(!Cli::try_parse_from(args).unwrap().args.diagnostics_json);
+ assert!(
+ Cli::try_parse_from(args.into_iter().chain(["--diagnostics-json"]))
+ .unwrap()
+ .args
+ .diagnostics_json
+ );
+ assert!(
+ Cli::command()
+ .render_help()
+ .to_string()
+ .contains("--diagnostics-json")
+ );
+}