Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/minimal-tui/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@ fn policy_lines(model: &Model, key: &SessionKey) -> Vec<Line<'static>> {
.join(", ")
))),
}
policy_list(&mut lines, "deny subnets", &egress.deny_subnets);
}
}
lines.push(Line::styled(
Expand Down
36 changes: 36 additions & 0 deletions crates/minimal-tui/tests/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ fn detail_pane_with_policy() {
allow_subnets: Some(vec!["10.0.0.0/8".to_string()]),
allow_dns_hosts: None,
allow_protocols: None,
deny_subnets: Some(vec!["10.0.0.0/24".to_string()]),
}),
Some(sessions::IngressPolicy {
port_mappings: vec![sessions::PortMapping {
Expand All @@ -229,6 +230,41 @@ fn detail_pane_with_policy() {
insta::assert_snapshot!(render(&mut model));
}

/// The policy section renders the `deny_subnets` field as part of the
/// effective egress rules.
#[test]
fn policy_lines_show_deny_subnets() {
let mut model = fixed_model(vec![provider(
"host",
vec![entry(1, Some("api-staging"), "/src/api")],
)]);
let key = SessionKey {
provider: "host".to_string(),
id: id(1),
};
model.details.insert(
key,
Detail {
record: Some(record(Some("api-staging"), NetworkMode::OwnIp)),
policy: Some(sessions::SessionPolicy::new(
Some(sessions::EgressPolicy {
allow_subnets: None,
allow_dns_hosts: None,
allow_protocols: None,
deny_subnets: Some(vec!["192.168.1.0/24".to_string()]),
}),
None,
)),
},
);
model.cursor = 1;
let rendered = render(&mut model);
assert!(
rendered.contains("deny subnets 192.168.1.0/24"),
"deny_subnets must appear in the policy section:\n{rendered}"
);
}

/// Git info from the list RPC renders: the branch in the sidebar row
/// (TestBackend text — the glyph is what matters) and the repo root,
/// tagged as a worktree, in the detail Info section.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
source: crates/minimal-tui/tests/snapshots.rs
assertion_line: 230
expression: render(&mut model)
---
"┌──────────────────────────────┐┌ api-staging · 00000000 ──────────────────────────────────────────┐"
Expand All @@ -12,6 +13,7 @@ expression: render(&mut model)
"│ ││ subnets 10.0.0.0/8 │"
"│ ││ dns hosts allow all │"
"│ ││ protocols allow all │"
"│ ││ deny subnets 10.0.0.0/24 │"
"│ ││ ingress │"
"│ ││ tcp :8080 → :80 │"
"│ ││ ─ Preview (live screen snapshot) ─────────────────────────────── │"
Expand All @@ -29,6 +31,5 @@ expression: render(&mut model)
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────┘└──────────────────────────────────────────────────────────────────┘"
" ↑↓ move · / filter · enter attach · d destroy · r rename · n new · q quit "
19 changes: 18 additions & 1 deletion crates/minimal/src/cmd/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,13 +839,29 @@ pub(crate) fn exit_code_of(status: std::process::ExitStatus) -> i32 {
.unwrap_or(1)
}

/// Print the effective networking policy for a session as JSON.
/// Print the effective networking policy for a session as JSON.
pub async fn cmd_session_policy(
global: &GlobalArgs,
args: PolicyArgs,
) -> Result<(), anyhow::Error> {
ensure_daemon(global)?;
let mut out = tokio::io::stdout();
format_session_policy(&mut out, &args, global).await?;
Ok(())
}

/// Fetch a session's effective networking policy from the daemon and write it
/// as JSON to `out`. Split from [`cmd_session_policy`] so tests can verify the
/// emitted JSON without capturing the process stdout.
pub async fn format_session_policy<W>(
out: &mut W,
args: &PolicyArgs,
global: &GlobalArgs,
) -> Result<(), anyhow::Error>
where
W: tokio::io::AsyncWrite + Unpin,
{
let mut client = connect_daemon(global).await?;

use minimald_rpc::{GetSessionPolicy, GetSessionPolicyRequest};
Expand All @@ -860,7 +876,8 @@ pub async fn cmd_session_policy(
minimald_rpc::Errorable::Ok(policy) => {
let json =
serde_json_lenient::to_string(&policy).context("Failed to serialize policy")?;
println!("{json}");
out.write_all(json.as_bytes()).await?;
out.write_all(b"\n").await?;
Ok(())
}
minimald_rpc::Errorable::Err { error } => {
Expand Down
24 changes: 19 additions & 5 deletions crates/minimal/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,11 @@ impl std::io::Write for DashLog {
/// Whether the command's stdout is a data contract that tracing must not
/// pollute, so its logs go to stderr instead. The `completions` handlers emit a
/// shell shim on stdout, `session exec` carries only the exec'd
/// command's output, and `task run` / `session run` stream the task's stdout —
/// a log line in any of them would be read as content. A bare `min` (no subcommand) is
/// one too: its non-TTY twin promises an empty stdout to pipelines, and its
/// interactive activate path prints only the session id there.
/// command's output, `task run` / `session run` stream the task's stdout, and
/// `session policy` emits JSON on stdout — a log line in any of them would be
/// read as content. A bare `min` (no subcommand) is one too: its non-TTY twin
/// promises pipelines an empty stdout, and its interactive activate path prints
/// only the session id there.
fn stdout_is_data_contract(command: &Option<minimal::Command>) -> bool {
matches!(
command,
Expand All @@ -139,7 +140,8 @@ fn stdout_is_data_contract(command: &Option<minimal::Command>) -> bool {
| minimal::Command::Completions(_)
| minimal::Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Exec(ExecArgs { .. })
| minimal::SessionCommand::Run(_),
| minimal::SessionCommand::Run(_)
| minimal::SessionCommand::Policy(_),
})
| minimal::Command::Task(minimal::TaskArgs {
command: minimal::TaskCommand::Run(_),
Expand Down Expand Up @@ -186,4 +188,16 @@ mod tests {
}));
assert!(stdout_is_data_contract(&cmd));
}

/// `min session policy` emits JSON on stdout, so tracing must route to
/// stderr to keep the output parseable.
#[test]
fn session_policy_is_a_stdout_contract() {
let cmd = Some(Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Policy(minimal::PolicyArgs {
session: "web".to_string(),
}),
}));
assert!(stdout_is_data_contract(&cmd));
}
}
134 changes: 134 additions & 0 deletions crates/minimal/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,8 +781,142 @@ async fn session_policy_succeeds() {
.unwrap();
}

/// NET-061: `min session policy` prints the effective egress rules, including
/// all four fields, for both own-address and host-address boxes.
#[tokio::test]
async fn policy_shows_effective_egress() {
let (daemon, _args) = setup().await;

let egress = sessions::EgressPolicy {
allow_subnets: Some(vec!["10.0.0.0/8".to_string()]),
allow_dns_hosts: Some(vec!["github.com".to_string()]),
allow_protocols: Some(vec![minimald_rpc::IpProto::Tcp]),
deny_subnets: Some(vec!["10.0.0.0/24".to_string()]),
};

for (name, network) in [
("own-ip-policy-cli", sessions::NetworkMode::OwnIp),
("host-ip-policy-cli", sessions::NetworkMode::HostNet),
] {
let session_id =
create_session_with_policy(&daemon, name, network, Some(egress.clone())).await;

let args = daemon.global_args();
let json = run_session_policy(&args, session_id).await;
let parsed: serde_json_lenient::Value = serde_json_lenient::from_str(&json)
.unwrap_or_else(|_| panic!("policy output must be valid JSON: {json}"));
let egress_json = parsed
.get("egress")
.unwrap_or_else(|| panic!("policy output must contain egress: {json}"));
assert_eq!(
egress_json.get("allow_subnets").and_then(|v| v.as_array()),
Some(&vec![serde_json_lenient::json!("10.0.0.0/8")]),
"allow_subnets must round-trip for {network:?}"
);
assert_eq!(
egress_json
.get("allow_dns_hosts")
.and_then(|v| v.as_array()),
Some(&vec![serde_json_lenient::json!("github.com")]),
"allow_dns_hosts must round-trip for {network:?}"
);
assert_eq!(
egress_json
.get("allow_protocols")
.and_then(|v| v.as_array()),
Some(&vec![serde_json_lenient::json!("tcp")]),
"allow_protocols must round-trip for {network:?}"
);
assert_eq!(
egress_json.get("deny_subnets").and_then(|v| v.as_array()),
Some(&vec![serde_json_lenient::json!("10.0.0.0/24")]),
"deny_subnets must round-trip for {network:?}"
);
}
}

async fn run_session_policy(args: &GlobalArgs, session_id: SessionId) -> String {
let mut buf = Vec::new();
minimal::format_session_policy(
&mut buf,
&minimal::PolicyArgs {
session: session_id.to_string(),
},
args,
)
.await
.unwrap();
String::from_utf8(buf).unwrap()
}

// --- helpers ---

/// Like [`create_session_at`], but sets an explicit network mode and policy.
async fn create_session_with_policy(
daemon: &common::TestDaemon,
name: &str,
network: sessions::NetworkMode,
egress: Option<sessions::EgressPolicy>,
) -> SessionId {
let mut client = daemon.server.connect().await;
let project_path = paths::HostAbsPath::try_new(
camino::Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap()).unwrap(),
)
.unwrap();

let policy = sessions::SessionPolicy {
egress,
ingress: None,
};
let config = minimald_rpc::SessionConfig {
name: Some(name.to_string()),
project_path,
network,
policy,
hooks_enabled: true,
attrs: Default::default(),
};

use minimald_rpc::{
ConfigureLoadout, ConfigureLoadoutRequest, CreateSession, CreateSessionRequest,
FinalizeSession, FinalizeSessionRequest,
};
let id = match client
.call::<CreateSession>(&CreateSessionRequest {
config,
must_match_version: None,
})
.await
{
minimald_rpc::Errorable::Ok(r) => r.id,
minimald_rpc::Errorable::Err { error } => {
panic!("CreateSession failed: {error}")
}
};
match client
.call::<ConfigureLoadout>(&ConfigureLoadoutRequest {
session_id: id,
contribution: Default::default(),
})
.await
{
minimald_rpc::Errorable::Ok(r) => unwrap_ready(r),
minimald_rpc::Errorable::Err { error } => {
panic!("ConfigureLoadout failed: {error}")
}
}
match client
.call::<FinalizeSession>(&FinalizeSessionRequest { session_id: id })
.await
{
minimald_rpc::Errorable::Ok(_) => {}
minimald_rpc::Errorable::Err { error } => {
panic!("FinalizeSession failed: {error}")
}
}
id
}

/// Creates a session whose workspace mfile declares a `[session.vars]`
/// entry, which the daemon must route back to the client for gating — so
/// configuring its loadout returns `Pending` and the session actor parks in
Expand Down
Loading
Loading