fix(aws): port mappings reach [::1]-only servers, never fail silently; clearer silent-agent error
Secret Scan / scan (push) Successful in 13s
Build App (Preview) / compute-version (pull_request) Successful in 8s
Secret Scan / scan (pull_request) Successful in 9s
Build App (Preview) / create-release (pull_request) Successful in 12s
Build App (Preview) / build-macos (pull_request) Successful in 7m30s
Build App (Preview) / test (pull_request) Successful in 11m4s
Build App (Preview) / build-windows (pull_request) Successful in 14m12s
Build App (Preview) / build-linux (pull_request) Successful in 15m52s
Build App (Preview) / prune-previews (pull_request) Successful in 5s
Secret Scan / scan (push) Successful in 13s
Build App (Preview) / compute-version (pull_request) Successful in 8s
Secret Scan / scan (pull_request) Successful in 9s
Build App (Preview) / create-release (pull_request) Successful in 12s
Build App (Preview) / build-macos (pull_request) Successful in 7m30s
Build App (Preview) / test (pull_request) Successful in 11m4s
Build App (Preview) / build-windows (pull_request) Successful in 14m12s
Build App (Preview) / build-linux (pull_request) Successful in 15m52s
Build App (Preview) / prune-previews (pull_request) Successful in 5s
Port mappings (AWS):
- In the workspace each connection now picks 127.0.0.1 or [::1] from
/proc/net/tcp{,6} (tunnel::mapping_command): a server bound to ::1 only
(Vite, Node `localhost`) was unreachable through a mapping. No probe
connection is made; nothing found falls back to 127.0.0.1.
- The first socat "Connection refused" per mapping is a `ports`
workspace-warning: "nothing is listening on port N in the workspace
(127.0.0.1 or ::1)".
- open_for_project warns instead of returning None when a Running project's
mappings can't be opened (no tunnel, or the tunnel changed under the open).
- Info/warn logs at each step (mappings read, each opened/failed, set closed
and why) so the next report shows where it stopped.
- Tests: start-path sequence (mapping saved while stopped, tunnel, Running,
open) with IPv4 and ::1 clients; refusal reported once; never-silent cases;
an ignored live test against a real agent container (0.0.0.0, [::1] and
nothing-listening servers).
Silent agent: the error now says the image (named, escaped) may predate the
app's AWS support, that :latest moves only on a release, and to set
Settings → Docker → Custom image to ghcr.io/shadowdao/triple-c-sandbox:edge.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
73eb507cfe
commit
ff872f34a1
7 files changed
+483
-47
No files matched your search
@@ -310,7 +310,11 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
|
||||
that would be refused is skipped with a warning at connect. Opens are serialised per project and
|
||||
re-read the stored mappings under that lock; unchanged forwards are kept with their connections.
|
||||
Opened after every connect and on a save while connected; closed by every `tunnels::close*`
|
||||
path. A failing mapping is a `workspace-warning` (`topic: "ports"`). An idle listener makes no
|
||||
path. A failing mapping is a `workspace-warning` (`topic: "ports"`), and so is a Running project
|
||||
whose mappings could not be opened at all (no tunnel / tunnel replaced) — never silent. In the
|
||||
workspace each connection picks `127.0.0.1` or `[::1]` from `/proc/net/tcp{,6}`
|
||||
(`tunnel::mapping_command`; no probe connection), and the first socat "Connection refused" per
|
||||
mapping is a `ports` warning ("nothing is listening on port N"). An idle listener makes no
|
||||
agent request; a connection carrying traffic is activity (keeps the workspace from idling).
|
||||
`agent.rs` reuses `docker/exec.rs`'s `OneshotOutput`, host-file reader and uid probe so the two
|
||||
variants cannot drift; an `Agent` target's token never appears in `Debug` or error text.
|
||||
|
||||
@@ -54,6 +54,8 @@
|
||||
//! ([`IDLE_TIMEOUT`]).
|
||||
|
||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::host::{AttachedExec, ContainerTarget, ExecChunk};
|
||||
@@ -158,19 +160,25 @@ impl PortForward {
|
||||
container_port: u16,
|
||||
family: PortFamily,
|
||||
) -> Result<Self, std::io::Error> {
|
||||
Self::bind_with(container, host_port, container_port, family, Gate::SignInCallback).await
|
||||
Self::bind_with(container, host_port, container_port, family, Gate::SignInCallback, None).await
|
||||
}
|
||||
|
||||
/// As [`bind`](Self::bind), for a project's port mapping on a host with
|
||||
/// no Docker port publishing (AWS): every connection is carried as is
|
||||
/// (see [`Gate::None`]).
|
||||
///
|
||||
/// Inside the workspace each connection goes to whichever loopback
|
||||
/// family has a listener on `container_port` ([`mapping_command`]), so a
|
||||
/// server bound to `[::1]` only is reached as well as one on
|
||||
/// `127.0.0.1`/`0.0.0.0`. `on_refused` is called (once per forward) the
|
||||
/// first time a connection finds nothing listening there.
|
||||
pub async fn bind_mapping(
|
||||
container: ContainerTarget,
|
||||
host_port: u16,
|
||||
container_port: u16,
|
||||
family: PortFamily,
|
||||
on_refused: Option<RefusedNotice>,
|
||||
) -> Result<Self, std::io::Error> {
|
||||
Self::bind_with(container, host_port, container_port, family, Gate::None).await
|
||||
Self::bind_with(container, host_port, container_port, PortFamily::Dual, Gate::None, on_refused).await
|
||||
}
|
||||
|
||||
async fn bind_with(
|
||||
@@ -179,6 +187,7 @@ impl PortForward {
|
||||
container_port: u16,
|
||||
family: PortFamily,
|
||||
gate: Gate,
|
||||
on_refused: Option<RefusedNotice>,
|
||||
) -> Result<Self, std::io::Error> {
|
||||
// SECURITY BOUNDARY: the host side binds loopback ONLY — 127.0.0.1 and
|
||||
// ::1, never 0.0.0.0 / ::. Everything reachable through this socket is
|
||||
@@ -222,8 +231,12 @@ impl PortForward {
|
||||
}
|
||||
};
|
||||
|
||||
let target = family.socat_target(container_port);
|
||||
let task = tokio::spawn(accept_loop(container, port, target, v4, v6, gate));
|
||||
let cmd = match gate {
|
||||
Gate::SignInCallback => socat_command(&family.socat_target(container_port)),
|
||||
Gate::None => mapping_command(container_port),
|
||||
};
|
||||
let refused = on_refused.map(|f| Arc::new(RefusedOnce { notice: f, fired: AtomicBool::new(false) }));
|
||||
let task = tokio::spawn(accept_loop(container, port, cmd, v4, v6, gate, refused));
|
||||
|
||||
Ok(Self {
|
||||
port,
|
||||
@@ -273,10 +286,11 @@ impl Gate {
|
||||
async fn accept_loop(
|
||||
container: ContainerTarget,
|
||||
port: u16,
|
||||
target: String,
|
||||
cmd: Vec<String>,
|
||||
v4: TcpListener,
|
||||
v6: Option<TcpListener>,
|
||||
gate: Gate,
|
||||
refused: Option<Arc<RefusedOnce>>,
|
||||
) {
|
||||
let mut conns: JoinSet<()> = JoinSet::new();
|
||||
|
||||
@@ -313,17 +327,18 @@ async fn accept_loop(
|
||||
match gate {
|
||||
Gate::SignInCallback => conns.spawn(tunnel_connection(
|
||||
container.clone(),
|
||||
target.clone(),
|
||||
cmd.clone(),
|
||||
stream,
|
||||
port,
|
||||
)),
|
||||
Gate::None => conns.spawn(tunnel_labelled(
|
||||
gate.label(),
|
||||
container.clone(),
|
||||
target.clone(),
|
||||
cmd.clone(),
|
||||
stream,
|
||||
port,
|
||||
Vec::new(),
|
||||
refused.clone(),
|
||||
)),
|
||||
};
|
||||
}
|
||||
@@ -353,7 +368,7 @@ async fn accept_optional(
|
||||
/// reaches the container at all — not even a `docker exec`.
|
||||
async fn tunnel_connection(
|
||||
container: ContainerTarget,
|
||||
target: String,
|
||||
cmd: Vec<String>,
|
||||
mut stream: TcpStream,
|
||||
port: u16,
|
||||
) {
|
||||
@@ -387,7 +402,7 @@ async fn tunnel_connection(
|
||||
}
|
||||
|
||||
// The bytes already off the socket go back on the wire first, byte-exact.
|
||||
tunnel_connection_with_prelude(container, target, stream, port, head.into_buffer()).await
|
||||
tunnel_labelled("Auth bridge", container, cmd, stream, port, head.into_buffer(), None).await
|
||||
}
|
||||
|
||||
/// What the first bytes of an accepted connection turned out to be.
|
||||
@@ -586,19 +601,20 @@ pub async fn tunnel_connection_with_prelude(
|
||||
port: u16,
|
||||
prelude: Vec<u8>,
|
||||
) {
|
||||
tunnel_labelled("Auth bridge", container, target, stream, port, prelude).await
|
||||
tunnel_labelled("Auth bridge", container, socat_command(&target), stream, port, prelude, None).await
|
||||
}
|
||||
|
||||
/// [`tunnel_connection_with_prelude`], logging under `label`.
|
||||
async fn tunnel_labelled(
|
||||
label: &'static str,
|
||||
container: ContainerTarget,
|
||||
target: String,
|
||||
cmd: Vec<String>,
|
||||
stream: TcpStream,
|
||||
port: u16,
|
||||
prelude: Vec<u8>,
|
||||
refused: Option<Arc<RefusedOnce>>,
|
||||
) {
|
||||
let cmd = vec!["socat".to_string(), "-".to_string(), target.clone()];
|
||||
let target = cmd.last().cloned().unwrap_or_default();
|
||||
|
||||
let AttachedExec {
|
||||
mut output,
|
||||
@@ -673,6 +689,12 @@ async fn tunnel_labelled(
|
||||
}
|
||||
}
|
||||
Ok(ExecChunk::StdErr(message)) => {
|
||||
if let Some(r) = &refused {
|
||||
if is_connection_refused(&message) {
|
||||
log::warn!("{}: host port {}: nothing is listening in the workspace", label, port);
|
||||
r.fire();
|
||||
}
|
||||
}
|
||||
log::debug!(
|
||||
"{}: socat stderr for port {}: {}", label,
|
||||
port,
|
||||
@@ -692,10 +714,113 @@ async fn tunnel_labelled(
|
||||
drop(upstream);
|
||||
}
|
||||
|
||||
/// Called the first time a port mapping's connection finds nothing
|
||||
/// listening on its workspace port.
|
||||
pub type RefusedNotice = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// A [`RefusedNotice`] that fires once per forward.
|
||||
struct RefusedOnce {
|
||||
notice: RefusedNotice,
|
||||
fired: AtomicBool,
|
||||
}
|
||||
|
||||
impl RefusedOnce {
|
||||
fn fire(&self) {
|
||||
if !self.fired.swap(true, Ordering::SeqCst) {
|
||||
(self.notice)();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `socat` relaying stdio to `target`.
|
||||
fn socat_command(target: &str) -> Vec<String> {
|
||||
vec!["socat".to_string(), "-".to_string(), target.to_string()]
|
||||
}
|
||||
|
||||
/// Whether socat's stderr says the connect was refused (nothing listening).
|
||||
fn is_connection_refused(stderr: &[u8]) -> bool {
|
||||
String::from_utf8_lossy(stderr).contains("Connection refused")
|
||||
}
|
||||
|
||||
/// The in-workspace command of one port-mapping connection.
|
||||
///
|
||||
/// Docker publishes to the container's interface; a mapping reaches its
|
||||
/// loopback instead, where a server may listen on either family (Vite, or
|
||||
/// Node's `localhost` where it resolves to `::1`, listen on `[::1]` only).
|
||||
/// So the command picks, from `/proc/net/tcp{,6}` (the image has no `ss`),
|
||||
/// the family with a listener on `port`: `127.0.0.1` when one listens on
|
||||
/// `127.0.0.1` or `0.0.0.0`, else `[::1]` when one listens on `::1` or `::`.
|
||||
/// Nothing found: `127.0.0.1` anyway, and socat's "Connection refused" is
|
||||
/// what tells the host nothing listens. Reading `/proc` rather than trying
|
||||
/// a connect first means a server never sees a probe connection.
|
||||
pub(crate) fn mapping_command(port: u16) -> Vec<String> {
|
||||
// `port` is a u16: interpolating it into the script is safe.
|
||||
let script = format!(
|
||||
"h=$(printf ':%04X' {port}); \
|
||||
l() {{ awk -v a=\"$2$h\" -v b=\"$3$h\" '$4==\"0A\" && ($2==a || $2==b) {{f=1}} END {{exit !f}}' \"$1\" 2>/dev/null; }}; \
|
||||
if l /proc/net/tcp 0100007F 00000000; then exec socat - TCP:127.0.0.1:{port}; fi; \
|
||||
if l /proc/net/tcp6 00000000000000000000000001000000 00000000000000000000000000000000; \
|
||||
then exec socat - TCP6:[::1]:{port}; fi; \
|
||||
exec socat - TCP:127.0.0.1:{port}"
|
||||
);
|
||||
vec!["sh".to_string(), "-c".to_string(), script]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_mapping_command_names_only_its_port_and_both_loopbacks() {
|
||||
let cmd = mapping_command(8080);
|
||||
assert_eq!(&cmd[..2], ["sh", "-c"]);
|
||||
let s = &cmd[2];
|
||||
assert!(s.contains("printf ':%04X' 8080"), "{s}");
|
||||
assert!(s.contains("TCP:127.0.0.1:8080") && s.contains("TCP6:[::1]:8080"), "{s}");
|
||||
// v4 first; the last resort is v4 too.
|
||||
assert!(s.find("TCP:127.0.0.1").unwrap() < s.find("TCP6:[::1]").unwrap());
|
||||
assert!(s.trim_end().ends_with("exec socat - TCP:127.0.0.1:8080"), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socats_refusal_is_recognised() {
|
||||
assert!(is_connection_refused(
|
||||
b"2026/11/17 10:00:00 socat[42] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused\n"
|
||||
));
|
||||
assert!(!is_connection_refused(b"socat[42] N exiting with status 0"));
|
||||
}
|
||||
|
||||
/// The command picks the family from `/proc/net/tcp{,6}`: run it against
|
||||
/// real listeners where `sh`, `awk` and `socat` exist (skipped elsewhere).
|
||||
#[tokio::test]
|
||||
async fn a_mapping_command_reaches_a_v4_or_a_v6_only_listener() {
|
||||
let have = |b: &str| std::process::Command::new("sh").args(["-c", &format!("command -v {b}")]).output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !(have("awk") && have("socat") && std::path::Path::new("/proc/net/tcp").exists()) {
|
||||
eprintln!("skipped: needs sh, awk, socat and /proc/net");
|
||||
return;
|
||||
}
|
||||
for addr in ["127.0.0.1:0", "[::1]:0"] {
|
||||
let Ok(l) = TcpListener::bind(addr).await else { continue };
|
||||
let port = l.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
if let Ok((mut s, _)) = l.accept().await {
|
||||
let _ = s.write_all(b"hello").await;
|
||||
}
|
||||
});
|
||||
let cmd = mapping_command(port);
|
||||
let out = tokio::process::Command::new(&cmd[0]).args(&cmd[1..])
|
||||
.stdin(std::process::Stdio::null()).output().await.unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout), "hello", "{addr}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
// Nothing listening: refused, in socat's words.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let cmd = mapping_command(port);
|
||||
let out = tokio::process::Command::new(&cmd[0]).args(&cmd[1..])
|
||||
.stdin(std::process::Stdio::null()).output().await.unwrap();
|
||||
assert!(is_connection_refused(&out.stderr), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn head(lines: &[&str]) -> String {
|
||||
format!("{}\r\n\r\n", lines.join("\r\n"))
|
||||
}
|
||||
|
||||
@@ -1159,7 +1159,8 @@ pub async fn update_project(
|
||||
// AWS (Q6): a connected workspace's forwards follow the saved mappings
|
||||
// now — there is no container to recreate. Nothing when not connected.
|
||||
if saved.is_aws() && mappings_changed {
|
||||
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &saved.id).await {
|
||||
let warn = ports_warner(&app_handle, &saved.id, &saved.name);
|
||||
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &saved.id, Some(warn)).await {
|
||||
emit_ports_warning(&app_handle, &saved.id, &saved.name, &detail);
|
||||
}
|
||||
}
|
||||
@@ -1551,7 +1552,8 @@ async fn start_project_container_locked(
|
||||
// AWS (Q6): the project's port mappings become loopback forwards into
|
||||
// the workspace; a mapping that can't open is a warning, the rest work.
|
||||
if project.is_aws() {
|
||||
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &project_id).await {
|
||||
let warn = ports_warner(&app_handle, &project_id, &project.name);
|
||||
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &project_id, Some(warn)).await {
|
||||
emit_ports_warning(&app_handle, &project_id, &project.name, &detail);
|
||||
}
|
||||
}
|
||||
@@ -1628,12 +1630,23 @@ fn connect_warning_payload(project_id: &str, name: &str, detail: &str) -> serde_
|
||||
/// Port mappings that could not be forwarded to a connected AWS workspace
|
||||
/// (Q6): a busy host port, a host port mapped twice. Same `workspace-warning`
|
||||
/// event, with its own `topic` so it does not replace the other warnings.
|
||||
/// Where a port mapping's later notices ("nothing is listening") go: the
|
||||
/// same `ports` warning toast.
|
||||
fn ports_warner(app_handle: &tauri::AppHandle, project_id: &str, name: &str) -> crate::host::port_forwards::PortsWarn {
|
||||
let (handle, id, name) = (app_handle.clone(), project_id.to_string(), name.to_string());
|
||||
std::sync::Arc::new(move |detail: String| emit_ports_warning(&handle, &id, &name, &detail))
|
||||
}
|
||||
|
||||
fn emit_ports_warning(app_handle: &tauri::AppHandle, project_id: &str, name: &str, detail: &str) {
|
||||
let _ = app_handle.emit(
|
||||
"workspace-warning",
|
||||
serde_json::json!({
|
||||
"project_id": project_id,
|
||||
"message": format!("“{name}”: some port mappings could not be opened"),
|
||||
"message": if detail.contains("nothing is listening") {
|
||||
format!("“{name}”: a port mapping found nothing listening in the workspace")
|
||||
} else {
|
||||
format!("“{name}”: some port mappings could not be opened")
|
||||
},
|
||||
"detail": detail,
|
||||
"topic": "ports",
|
||||
}),
|
||||
@@ -3344,20 +3357,21 @@ mod tests {
|
||||
let start = fn_body(src, "start_project_container_locked");
|
||||
let running = start.find("update_status(&project_id, ProjectStatus::Running)").unwrap();
|
||||
let open = start
|
||||
.find("port_forwards::open_for_project(&state.projects_store, &project_id)")
|
||||
.find("port_forwards::open_for_project(&state.projects_store, &project_id, Some(warn))")
|
||||
.expect("the start opens them");
|
||||
assert!(open > running);
|
||||
let guard = start[..open].rfind("if project.is_aws() {").expect("AWS-only");
|
||||
assert!(start[guard..open].lines().count() <= 2);
|
||||
assert!(start[guard..open].lines().count() <= 3);
|
||||
assert!(start[guard..open].contains("let warn = ports_warner(&app_handle, &project_id, &project.name);"));
|
||||
assert!(start[open..].lines().nth(1).unwrap().contains("emit_ports_warning("));
|
||||
let update = fn_body(src, "update_project");
|
||||
assert!(update.contains("port_forwards::open_for_project(&state.projects_store, &saved.id)"));
|
||||
assert!(update.contains("port_forwards::open_for_project(&state.projects_store, &saved.id, Some(warn))"));
|
||||
let reconcile = fn_body(src, "reconcile_aws_projects");
|
||||
assert!(reconcile.contains("on_ports_warning,"));
|
||||
assert!(reconcile.contains("emit_ports_warning(&ports_handle, &ports_id, &ports_name, &detail)"));
|
||||
let aws_host = include_str!("../host/aws_host.rs");
|
||||
let reattached = aws_host.find("Ok(true) => {").unwrap();
|
||||
let opened = aws_host.find("port_forwards::open_for_project(&store, &project.id)").unwrap();
|
||||
let opened = aws_host.find("port_forwards::open_for_project(&store, &project.id, Some(warn.clone()))").unwrap();
|
||||
let pushed = aws_host[reattached..].find("connect::apply_connect(").unwrap() + reattached;
|
||||
assert!(reattached < opened && opened < pushed);
|
||||
}
|
||||
|
||||
@@ -374,6 +374,25 @@ fn refusal_message(e: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge image: what `main` builds, ahead of `:latest` between releases.
|
||||
const EDGE_IMAGE: &str = "ghcr.io/shadowdao/triple-c-sandbox:edge";
|
||||
|
||||
/// What the user is told when the agent never answers through the tunnel.
|
||||
/// The usual cause is an image whose entrypoint predates AWS mode and never
|
||||
/// starts the agent: the registry's `:latest` moves only on a release.
|
||||
/// `image` is the one the task ran, when the caller knows it.
|
||||
fn agent_silent_message(image: Option<&str>) -> String {
|
||||
let which = match image {
|
||||
Some(i) => format!("The image \"{}\"", i.escape_debug()),
|
||||
None => "The workspace's image".to_string(),
|
||||
};
|
||||
format!(
|
||||
"The workspace's agent did not answer through the tunnel. {which} may be older than this \
|
||||
app's AWS support: the registry's :latest moves only when a release is cut. Until then, \
|
||||
set Settings → Docker → Custom image to {EDGE_IMAGE}, then start the project again."
|
||||
)
|
||||
}
|
||||
|
||||
/// Wait for the agent behind `ep` to answer. A refusal (wrong token) is
|
||||
/// final; silence is retried until [`HEALTH_TIMEOUT`].
|
||||
async fn wait_healthy(ep: &AgentEndpoint) -> Result<(), String> {
|
||||
@@ -385,11 +404,7 @@ async fn wait_healthy(ep: &AgentEndpoint) -> Result<(), String> {
|
||||
Err(e) => return Err(refusal_message(&e)),
|
||||
}
|
||||
if tokio::time::Instant::now() + HEALTH_INTERVAL > deadline {
|
||||
return Err(
|
||||
"The workspace's agent did not answer through the tunnel. Check that the image \
|
||||
includes triple-c-agent, then start the project again."
|
||||
.into(),
|
||||
);
|
||||
return Err(agent_silent_message(None));
|
||||
}
|
||||
tokio::time::sleep(HEALTH_INTERVAL).await;
|
||||
}
|
||||
@@ -967,7 +982,8 @@ pub async fn start_core<T: TaskApi, W: WorkspaceApi, R: RuntimeApi, C: Connector
|
||||
if created && stop_created(tasks, &task_cluster(&env, &task.arn), &task.arn).await {
|
||||
(inp.on_task)(None);
|
||||
}
|
||||
Err(e)
|
||||
// Name the image this start ran (the connector doesn't know it).
|
||||
Err(if e == agent_silent_message(None) { agent_silent_message(Some(inp.image)) } else { e })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1621,7 +1637,7 @@ pub async fn reconcile(
|
||||
settings: &AppSettings,
|
||||
store: Arc<ProjectsStore>,
|
||||
on_connect_warning: impl FnOnce(String) + Send + 'static,
|
||||
on_ports_warning: impl FnOnce(String) + Send + 'static,
|
||||
on_ports_warning: impl Fn(String) + Send + Sync + 'static,
|
||||
on_interrupted_warning: impl FnOnce(String) + Send + 'static,
|
||||
) {
|
||||
let (connection_id, region, sdk) = match project_sdk(project, settings).await {
|
||||
@@ -1652,8 +1668,11 @@ pub async fn reconcile(
|
||||
Ok(true) => {
|
||||
// Q6: the port mappings' forwards, before the
|
||||
// (slower) credential copy.
|
||||
if let Some(detail) = super::port_forwards::open_for_project(&store, &project.id).await {
|
||||
on_ports_warning(detail);
|
||||
let warn: super::port_forwards::PortsWarn = Arc::new(on_ports_warning);
|
||||
if let Some(detail) =
|
||||
super::port_forwards::open_for_project(&store, &project.id, Some(warn.clone())).await
|
||||
{
|
||||
warn(detail);
|
||||
}
|
||||
if let Err(e) = connect::apply_connect(&project, &settings).await {
|
||||
log::warn!("Project {}: could not copy the credentials in: {e}", project.id);
|
||||
|
||||
@@ -93,6 +93,8 @@ struct Fake {
|
||||
logs: Vec<String>,
|
||||
role: Option<Knowable>,
|
||||
connect_fails: bool,
|
||||
/// The connector times out waiting for the agent (an image without it).
|
||||
agent_silent: bool,
|
||||
connect_tokens: Mutex<Vec<String>>,
|
||||
secret_json: Mutex<Option<String>>,
|
||||
/// A losing start rotates the secret's token while this one connects.
|
||||
@@ -309,6 +311,9 @@ impl Connector for Fake {
|
||||
v["TRIPLEC_AGENT_TOKEN"] = "the-losers-token".into();
|
||||
*j = Some(v.to_string());
|
||||
}
|
||||
if self.agent_silent {
|
||||
return Err(agent_silent_message(None));
|
||||
}
|
||||
if self.connect_fails {
|
||||
return Err("session-manager-plugin was not found".into());
|
||||
}
|
||||
@@ -586,6 +591,25 @@ async fn a_tunnel_failure_stops_a_task_this_start_ran_but_never_an_attached_one(
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_silent_agent_names_the_image_and_the_edge_tag() {
|
||||
let p = aws_project(StorageMode::Ephemeral);
|
||||
let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), agent_silent: true, ..Default::default() };
|
||||
let e = start(&fake, &p).await.0.err().unwrap();
|
||||
assert!(e.contains(&format!("\"{REGISTRY_IMAGE}\"")), "{e}");
|
||||
assert!(e.contains("older than this app's AWS support"), "{e}");
|
||||
assert!(e.contains(":latest moves only when a release is cut"), "{e}");
|
||||
assert!(e.contains("Settings → Docker → Custom image to ghcr.io/shadowdao/triple-c-sandbox:edge"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_silent_agent_message_escapes_the_image_name() {
|
||||
let m = agent_silent_message(Some("evil\"\nimage"));
|
||||
assert!(m.contains(r#""evil\"\nimage""#), "{m}");
|
||||
assert!(!m.contains('\n'));
|
||||
assert!(agent_silent_message(None).contains("The workspace's image may be older"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_user_who_has_not_joined_is_told_before_anything_is_written() {
|
||||
let p = aws_project(StorageMode::Hybrid);
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
//! ## Two differences from Docker, both deliberate
|
||||
//!
|
||||
//! * **It reaches the workspace's loopback, not its network interface**
|
||||
//! (`socat … TCP:127.0.0.1:<port>` inside the task). So a mapping can
|
||||
//! (`socat` to `127.0.0.1:<port>`, or `[::1]:<port>` when only an IPv6
|
||||
//! loopback/wildcard socket listens there — see
|
||||
//! [`crate::auth_bridge::tunnel::mapping_command`]). So a mapping can
|
||||
//! reach a service that bound loopback precisely to be private — which is
|
||||
//! why the agent's port, the browser view's range and (when the project
|
||||
//! runs it) the gateway sidecar's [`GATEWAY_SIDECAR_PORT`] are refused.
|
||||
@@ -46,7 +48,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::auth_bridge::proc_net::PortFamily;
|
||||
use crate::auth_bridge::tunnel::PortForward;
|
||||
use crate::auth_bridge::{RESERVED_CONTAINER_PORTS, RESERVED_HOST_PORTS};
|
||||
use crate::models::PortMapping;
|
||||
@@ -54,6 +55,18 @@ use crate::storage::projects_store::ProjectsStore;
|
||||
|
||||
use super::ContainerTarget;
|
||||
|
||||
/// Where a warning about a mapping goes after the open has returned: the
|
||||
/// first connection that finds nothing listening in the workspace.
|
||||
pub type PortsWarn = Arc<dyn Fn(String) + Send + Sync>;
|
||||
|
||||
/// What the user is told when a mapping's workspace port has no listener.
|
||||
pub fn nothing_listening(host_port: u16, container_port: u16) -> String {
|
||||
format!(
|
||||
"localhost:{host_port}: nothing is listening on port {container_port} in the workspace \
|
||||
(127.0.0.1 or ::1)"
|
||||
)
|
||||
}
|
||||
|
||||
/// What became of one mapping: `error` is `None` when its forward is open.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PortForwardResult {
|
||||
@@ -215,7 +228,7 @@ pub async fn open_for(
|
||||
mappings: &[PortMapping],
|
||||
) -> Vec<PortForwardResult> {
|
||||
let mappings = mappings.to_vec();
|
||||
open_latest(project_id, target, move || Some((mappings, false))).await
|
||||
open_latest(project_id, target, None, move || Some((mappings, false))).await
|
||||
}
|
||||
|
||||
/// Open the project's mappings into `target`, replacing the set it had.
|
||||
@@ -232,14 +245,22 @@ pub async fn open_for(
|
||||
pub async fn open_latest(
|
||||
project_id: &str,
|
||||
target: &ContainerTarget,
|
||||
warn: Option<PortsWarn>,
|
||||
read: impl FnOnce() -> Option<(Vec<PortMapping>, bool)> + Send,
|
||||
) -> Vec<PortForwardResult> {
|
||||
let plock = project_lock(project_id);
|
||||
let _held = plock.lock().await;
|
||||
let Some((mappings, gateway_sidecar)) = read() else {
|
||||
log::info!("Project {project_id}: no longer an AWS project; closing its port forwards");
|
||||
close_unlocked(project_id).await;
|
||||
return Vec::new();
|
||||
};
|
||||
log::info!(
|
||||
"Project {project_id}: opening port mappings into {} ({} stored, {} incomplete)",
|
||||
target.id(),
|
||||
mappings.len(),
|
||||
mappings.iter().filter(|m| incomplete(m)).count()
|
||||
);
|
||||
|
||||
// What can be forwarded, in order; the first row wins a host port.
|
||||
let mut results: Vec<PortForwardResult> = Vec::new();
|
||||
@@ -284,7 +305,12 @@ pub async fn open_latest(
|
||||
opened.push(f);
|
||||
continue;
|
||||
}
|
||||
match PortForward::bind_mapping(target.clone(), host_port, container_port, PortFamily::V4).await {
|
||||
let on_refused = warn.clone().map(|w| {
|
||||
let notice: crate::auth_bridge::tunnel::RefusedNotice =
|
||||
Arc::new(move || w(nothing_listening(host_port, container_port)));
|
||||
notice
|
||||
});
|
||||
match PortForward::bind_mapping(target.clone(), host_port, container_port, on_refused).await {
|
||||
Ok(fwd) => {
|
||||
if let Some(w) = &fwd.ipv6_warning {
|
||||
log::warn!("Project {project_id}: port mapping {host_port}: {w}");
|
||||
@@ -313,11 +339,25 @@ pub async fn open_latest(
|
||||
// Checked *after* the set is registered: a tunnel close that ran before
|
||||
// this sees it gone here; one that runs after removes it itself.
|
||||
if !still_connected(project_id, target) {
|
||||
log::warn!(
|
||||
"Project {project_id}: the workspace's tunnel is no longer {} — closing the port forwards just opened",
|
||||
target.id()
|
||||
);
|
||||
close_unlocked(project_id).await;
|
||||
for r in results.iter_mut().filter(|r| r.error.is_none()) {
|
||||
r.error = Some("the workspace disconnected".into());
|
||||
}
|
||||
}
|
||||
for r in &results {
|
||||
match &r.error {
|
||||
None => log::info!(
|
||||
"Project {project_id}: port mapping localhost:{} → workspace port {} is open",
|
||||
r.mapping.host_port,
|
||||
r.mapping.container_port
|
||||
),
|
||||
Some(e) => log::warn!("Project {project_id}: port mapping not open: {e}"),
|
||||
}
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
@@ -337,6 +377,9 @@ pub async fn close(project_id: &str) {
|
||||
async fn close_unlocked(project_id: &str) {
|
||||
let set = lock().remove(project_id);
|
||||
if let Some(set) = set {
|
||||
if !set.forwards.is_empty() {
|
||||
log::info!("Project {project_id}: closing {} port forward(s)", set.forwards.len());
|
||||
}
|
||||
shutdown_all(set.forwards).await;
|
||||
}
|
||||
}
|
||||
@@ -352,20 +395,38 @@ pub async fn close_all() {
|
||||
/// After a connect (or a save of the mappings while connected): open an
|
||||
/// AWS project's mappings, **as stored when the open runs**, into its
|
||||
/// connected workspace. The warning detail for the mappings that failed, if
|
||||
/// any did; `None` as well for a local project (Docker publishes its own) or
|
||||
/// a workspace that is not (or no longer) connected.
|
||||
pub async fn open_for_project(store: &ProjectsStore, project_id: &str) -> Option<String> {
|
||||
/// any did; `None` for a local project (Docker publishes its own), and for a
|
||||
/// workspace that is not (or no longer) connected **unless the project is
|
||||
/// Running** — mappings that should be open and aren't are never silent.
|
||||
/// `warn` receives the later "nothing is listening" notices.
|
||||
pub async fn open_for_project(
|
||||
store: &ProjectsStore,
|
||||
project_id: &str,
|
||||
warn: Option<PortsWarn>,
|
||||
) -> Option<String> {
|
||||
let project = store.get(project_id).filter(|p| p.is_aws())?;
|
||||
let target = ContainerTarget::Agent(super::tunnels::get_endpoint(&project.id)?);
|
||||
let results = open_latest(project_id, &target, || {
|
||||
let wanted = project.port_mappings.iter().filter(|m| !incomplete(m)).count();
|
||||
let running = || {
|
||||
store.get(project_id).is_some_and(|p| p.status == crate::models::ProjectStatus::Running)
|
||||
};
|
||||
let Some(endpoint) = super::tunnels::get_endpoint(&project.id) else {
|
||||
log::info!("Project {project_id}: no tunnel to the workspace; {wanted} port mapping(s) not opened");
|
||||
return (wanted > 0 && running()).then(|| {
|
||||
"The workspace is not connected, so its port mappings were not opened. Start the \
|
||||
project again."
|
||||
.to_string()
|
||||
});
|
||||
};
|
||||
let target = ContainerTarget::Agent(endpoint);
|
||||
let results = open_latest(project_id, &target, warn, || {
|
||||
store.get(project_id).filter(|p| p.is_aws()).map(|p| {
|
||||
let gateway = p.aws.as_ref().is_some_and(|a| a.gateway_sidecar);
|
||||
(p.port_mappings, gateway)
|
||||
})
|
||||
})
|
||||
.await;
|
||||
if !still_connected(project_id, &target) {
|
||||
return None;
|
||||
if !still_connected(project_id, &target) && !running() {
|
||||
return None; // a Stop raced the open: nothing to say
|
||||
}
|
||||
failure_detail(&results)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ struct Fake {
|
||||
requests: AtomicUsize,
|
||||
/// The command of each attach.
|
||||
cmds: std::sync::Mutex<Vec<Vec<String>>>,
|
||||
/// Answer every attach as socat finding nothing listening.
|
||||
refuse: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
async fn attach_ws(State(f): State<Arc<Fake>>, ws: WebSocketUpgrade) -> Response {
|
||||
@@ -41,6 +43,14 @@ async fn echo(f: Arc<Fake>, mut ws: WebSocket) {
|
||||
.collect();
|
||||
f.cmds.lock().unwrap().push(cmd);
|
||||
let _ = ws.send(WsMessage::Text(r#"{"type":"started","exec_id":"a1"}"#.into())).await;
|
||||
if f.refuse.load(Ordering::SeqCst) {
|
||||
let mut err = vec![2u8];
|
||||
err.extend_from_slice(b"socat[7] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused\n");
|
||||
let _ = ws.send(WsMessage::Binary(err.into())).await;
|
||||
let _ = ws.send(WsMessage::Text(r#"{"type":"exit","code":1}"#.into())).await;
|
||||
let _ = ws.close().await;
|
||||
return;
|
||||
}
|
||||
while let Some(Ok(msg)) = ws.recv().await {
|
||||
match msg {
|
||||
WsMessage::Binary(b) => {
|
||||
@@ -129,7 +139,7 @@ async fn a_busy_host_port_fails_its_mapping_alone_and_the_other_forwards() {
|
||||
assert_eq!(round_trip(free, b"ping").await, b"ping");
|
||||
assert_eq!(
|
||||
fake.cmds.lock().unwrap().as_slice(),
|
||||
[vec!["socat".to_string(), "-".into(), "TCP:127.0.0.1:5432".into()]]
|
||||
[crate::auth_bridge::tunnel::mapping_command(5432)]
|
||||
);
|
||||
|
||||
// Stop / Remove / task death all close the tunnel: the mappings go too.
|
||||
@@ -310,7 +320,7 @@ async fn overlapping_opens_converge_on_the_last_stored_set_without_false_errors(
|
||||
let mine = sets[i % sets.len()].clone();
|
||||
opens.push(tokio::spawn(async move {
|
||||
go2.wait().await;
|
||||
open_latest(&p2, &t2, move || {
|
||||
open_latest(&p2, &t2, None, move || {
|
||||
let mut s = s2.lock().unwrap();
|
||||
*s = mine; // this save lands, then its open reads the store
|
||||
Some((s.clone(), false))
|
||||
@@ -352,7 +362,7 @@ async fn a_save_keeps_unchanged_forwards_and_their_live_connections() {
|
||||
let r = open_for(&p, &target, &[tcp(a, 9090)]).await;
|
||||
assert!(r[0].error.is_none(), "{:?}", r[0].error);
|
||||
assert_eq!(round_trip(a, b"x").await, b"x");
|
||||
assert_eq!(fake.cmds.lock().unwrap().last().unwrap()[2], "TCP:127.0.0.1:9090");
|
||||
assert_eq!(fake.cmds.lock().unwrap().last().unwrap(), &crate::auth_bridge::tunnel::mapping_command(9090));
|
||||
assert!(port_is_free(b));
|
||||
tunnels::close(&p).await;
|
||||
}
|
||||
@@ -371,9 +381,9 @@ async fn a_stored_project_is_read_when_the_open_runs() {
|
||||
let busy_port = busy.local_addr().unwrap().port();
|
||||
project.port_mappings = vec![tcp(port, 8080), tcp(busy_port, 8081)];
|
||||
let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![project]);
|
||||
assert_eq!(open_for_project(&store, &p).await, None, "not connected: nothing, no warning");
|
||||
assert_eq!(open_for_project(&store, &p, None).await, None, "not connected: nothing, no warning");
|
||||
let (_target, _, _) = connected_agent(&p).await;
|
||||
let warning = open_for_project(&store, &p).await.expect("the busy port is reported");
|
||||
let warning = open_for_project(&store, &p, None).await.expect("the busy port is reported");
|
||||
assert!(warning.contains(&busy_port.to_string()) && warning.contains("already in use"), "{warning}");
|
||||
assert_eq!(open_ports(&p), vec![port]);
|
||||
tunnels::close(&p).await;
|
||||
@@ -386,7 +396,7 @@ async fn the_auth_bridges_forward_still_waits_for_a_client_to_speak() {
|
||||
let p = pid("bridge");
|
||||
let (target, fake, _) = connected_agent(&p).await;
|
||||
let port = free_port();
|
||||
let mut fwd = PortForward::bind(target, port, port, PortFamily::V4).await.unwrap();
|
||||
let mut fwd = PortForward::bind(target, port, port, crate::auth_bridge::proc_net::PortFamily::V4).await.unwrap();
|
||||
assert_eq!((fwd.port, fwd.container_port), (port, port));
|
||||
let _client = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
@@ -394,3 +404,182 @@ async fn the_auth_bridges_forward_still_waits_for_a_client_to_speak() {
|
||||
fwd.shutdown().await;
|
||||
tunnels::close(&p).await;
|
||||
}
|
||||
|
||||
fn aws_project_in_store(p: &str, status: crate::models::ProjectStatus, mappings: Vec<PortMapping>) -> (tempfile::TempDir, ProjectsStore) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut project = crate::models::Project::new("x".into(), vec![]);
|
||||
project.id = p.to_string();
|
||||
project.host_id = Some("h1".into());
|
||||
project.aws_placement =
|
||||
Some(crate::models::AwsPlacement { region: "us-west-2".into(), environment: "dev".into() });
|
||||
project.aws = Some(Default::default());
|
||||
project.status = status;
|
||||
project.port_mappings = mappings;
|
||||
let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![project]);
|
||||
(dir, store)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_running_project_whose_mappings_cannot_open_is_never_silent() {
|
||||
use crate::models::ProjectStatus;
|
||||
let p = pid("silent");
|
||||
// Stopped (a save while stopped): nothing to open, nothing to say.
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(free_port(), 8080)]);
|
||||
assert_eq!(open_for_project(&store, &p, None).await, None);
|
||||
// Running with no tunnel: the mappings should be open and are not.
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(free_port(), 8080)]);
|
||||
let w = open_for_project(&store, &p, None).await.expect("a warning");
|
||||
assert!(w.contains("not connected"), "{w}");
|
||||
// Only incomplete rows: nothing to say.
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(0, 8080)]);
|
||||
assert_eq!(open_for_project(&store, &p, None).await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_start_opens_a_listener_for_a_mapping_saved_before_it() {
|
||||
use crate::models::ProjectStatus;
|
||||
// The reported case: 8080 → 8080 saved while stopped, then a start
|
||||
// registers the tunnel, sets Running and opens the mappings.
|
||||
let p = pid("start");
|
||||
let port = free_port();
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(port, 8080)]);
|
||||
let (_target, fake, _) = connected_agent(&p).await;
|
||||
store.update_status(&p, ProjectStatus::Running).unwrap();
|
||||
assert_eq!(open_for_project(&store, &p, None).await, None);
|
||||
assert_eq!(open_ports(&p), vec![port]);
|
||||
assert_eq!(round_trip(port, b"ping").await, b"ping");
|
||||
// Over IPv6 loopback too (`localhost` may resolve to ::1 first).
|
||||
if let Ok(mut c) = TcpStream::connect(("::1", port)).await {
|
||||
c.write_all(b"six").await.unwrap();
|
||||
let mut buf = [0u8; 3];
|
||||
c.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"six");
|
||||
}
|
||||
assert_eq!(fake.cmds.lock().unwrap()[0], crate::auth_bridge::tunnel::mapping_command(8080));
|
||||
tunnels::close(&p).await;
|
||||
assert!(port_is_free(port));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_listening_in_the_workspace_is_reported_once_per_mapping() {
|
||||
use crate::models::ProjectStatus;
|
||||
let p = pid("refused");
|
||||
let port = free_port();
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(port, 8080)]);
|
||||
let (_target, fake, _) = connected_agent(&p).await;
|
||||
fake.refuse.store(true, Ordering::SeqCst);
|
||||
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let s2 = seen.clone();
|
||||
let warn: PortsWarn = Arc::new(move |d| s2.lock().unwrap().push(d));
|
||||
assert_eq!(open_for_project(&store, &p, Some(warn)).await, None);
|
||||
for _ in 0..3 {
|
||||
let mut c = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let mut buf = Vec::new();
|
||||
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), c.read_to_end(&mut buf)).await;
|
||||
}
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
assert_eq!(seen, vec![nothing_listening(port, 8080)]);
|
||||
assert!(seen[0].contains("nothing is listening on port 8080 in the workspace (127.0.0.1 or ::1)"));
|
||||
tunnels::close(&p).await;
|
||||
}
|
||||
|
||||
/// The reported case end to end against a **real** agent in a real
|
||||
/// container (no SSM; the tunnel is registered by hand): a mapping saved
|
||||
/// before the start, a Python server on `0.0.0.0:8080` (the user's), one on
|
||||
/// `[::1]` only, and a port nothing listens on. Needs Docker and an image
|
||||
/// whose entrypoint starts the agent (`TRIPLEC_AGENT_E2E_IMAGE`, default
|
||||
/// `ghcr.io/shadowdao/triple-c-sandbox:edge`).
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a Docker daemon and an image whose entrypoint starts triple-c-agent"]
|
||||
async fn live_a_mapping_reaches_v4_and_v6_servers_in_a_real_workspace() {
|
||||
use crate::models::ProjectStatus;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
let docker = |args: &[&str]| -> String {
|
||||
let out = Command::new("docker").args(args).output().expect("docker cli");
|
||||
assert!(out.status.success(), "docker {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
};
|
||||
let image = std::env::var("TRIPLEC_AGENT_E2E_IMAGE")
|
||||
.unwrap_or_else(|_| "ghcr.io/shadowdao/triple-c-sandbox:edge".into());
|
||||
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
|
||||
let name = format!("tc-ports-e2e-{}", uuid::Uuid::new_v4().simple());
|
||||
docker(&[
|
||||
"run", "-d", "--name", &name, "-w", "/workspace",
|
||||
"-e", &format!("TRIPLEC_AGENT_TOKEN={token}"),
|
||||
"-e", "TRIPLEC_AGENT_ADDR=0.0.0.0:47900",
|
||||
"-p", "127.0.0.1::47900",
|
||||
&image,
|
||||
]);
|
||||
let p = pid("live");
|
||||
let outcome = async {
|
||||
let mapped = docker(&["port", &name, "47900/tcp"]);
|
||||
let lport: u16 = mapped.lines().next().and_then(|l| l.rsplit(':').next()).and_then(|x| x.parse().ok()).unwrap();
|
||||
let ip = docker(&["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", &name]);
|
||||
let mut candidates = vec![AgentEndpoint::loopback(lport, token.clone())];
|
||||
for a in ip.split_whitespace() {
|
||||
candidates.push(AgentEndpoint::new(url::Url::parse(&format!("http://{a}:47900/")).unwrap(), token.clone()).unwrap());
|
||||
}
|
||||
let mut ep = None;
|
||||
'wait: for _ in 0..240 {
|
||||
for c in &candidates {
|
||||
if ContainerTarget::Agent(c.clone()).is_running().await.unwrap_or(false) {
|
||||
ep = Some(c.clone());
|
||||
break 'wait;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
let ep = ep.ok_or("agent never answered")?;
|
||||
docker(&["exec", "-d", "-u", "claude", &name, "python3", "-m", "http.server", "8080", "--bind", "0.0.0.0"]);
|
||||
docker(&["exec", "-d", "-u", "claude", &name, "python3", "-m", "http.server", "8081", "--bind", "::1"]);
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
|
||||
let (h80, h81, h82) = (free_port(), free_port(), free_port());
|
||||
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(h80, 8080), tcp(h81, 8081), tcp(h82, 8082)]);
|
||||
// The start: tunnel registered, Running, then the open.
|
||||
let mut t = tunnels::tests::fake_tunnel(lport, Arc::new(AtomicUsize::new(0)));
|
||||
t.endpoint = ep;
|
||||
tunnels::register(&p, t);
|
||||
store.update_status(&p, ProjectStatus::Running).unwrap();
|
||||
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let s2 = seen.clone();
|
||||
let warn: PortsWarn = Arc::new(move |d| s2.lock().unwrap().push(d));
|
||||
if let Some(w) = open_for_project(&store, &p, Some(warn)).await {
|
||||
return Err(format!("open warned: {w}"));
|
||||
}
|
||||
async fn get(addr: (&str, u16)) -> Result<String, String> {
|
||||
let mut c = TcpStream::connect(addr).await.map_err(|e| format!("{addr:?}: {e}"))?;
|
||||
c.write_all(b"GET / HTTP/1.0\r\nHost: localhost\r\n\r\n").await.map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
tokio::time::timeout(Duration::from_secs(20), c.read_to_end(&mut buf)).await.map_err(|_| "timeout".to_string())?.map_err(|e| e.to_string())?;
|
||||
Ok(String::from_utf8_lossy(&buf).into_owned())
|
||||
}
|
||||
for (port, what) in [(h80, "0.0.0.0:8080"), (h81, "[::1]:8081")] {
|
||||
for host in ["127.0.0.1", "::1"] {
|
||||
let r = get((host, port)).await?;
|
||||
if !r.starts_with("HTTP/1.0 200") {
|
||||
return Err(format!("{what} via {host}:{port}: {r:?}"));
|
||||
}
|
||||
eprintln!("{what} via {host}:{port}: 200");
|
||||
}
|
||||
}
|
||||
let r = get(("127.0.0.1", h82)).await?;
|
||||
if !r.is_empty() {
|
||||
return Err(format!("nothing listens on 8082, yet: {r:?}"));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
if seen != vec![nothing_listening(h82, 8082)] {
|
||||
return Err(format!("warnings: {seen:?}"));
|
||||
}
|
||||
Ok::<(), String>(())
|
||||
}
|
||||
.await;
|
||||
tunnels::close(&p).await;
|
||||
let logs = Command::new("docker").args(["logs", "--tail", "20", &name]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
|
||||
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
|
||||
if let Err(e) = outcome {
|
||||
panic!("{e}\n--- container log tail ---\n{logs}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user