costroid 0.4.0

Local-first, FOCUS-native cost and limit visibility for your AI coding tools, right in your terminal.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Offline guarantee — static proof (re-scoped for the connections subsystem, T7).
//!
//! Costroid's **default, local-only build reads local logs only and must make no
//! network call and emit no telemetry, ever.** The strongest guarantee is
//! structural: assert that the *resolved* dependency graph of Costroid's own crates
//! contains no HTTP/TLS/socket client and no telemetry SDK, so there is nothing in
//! the shipped binary that *could* phone home.
//!
//! Network code is allowed in exactly one place — the feature-gated `costroid-connect`
//! crate (PRODUCT-PLAN §2c / Step 4), **off by default**. So the guarantee is now
//! two-tier:
//!
//! * **Default build (`connect` off)** — forbids *everything* that can reach the
//!   network or emit telemetry, including the sanctioned trio (`ureq`/`rustls`/
//!   `keyring`). `costroid-connect` must not even be linked. This is the local-only
//!   product that ships today.
//! * **`--features connect`** — admits **only** the sanctioned trio that the
//!   connections subsystem will use; async runtimes, non-rustls TLS (OpenSSL), other
//!   HTTP clients, and *all* telemetry stay forbidden in this build too.
//!
//! Why the *resolved* graph and not `cargo metadata`'s `packages` array: `packages`
//! is a feature-independent superset (it lists optional dependencies whether or not
//! their feature is on), so it cannot tell the default build apart from the
//! `connect` build. Walking the resolved graph for an explicit feature set is what
//! makes the distinction real — a crate gated behind `connect` is absent here when
//! the feature is off and present when it is on.
//!
//! The dynamic counterpart — running every command under network isolation and
//! proving no outbound connection is attempted — lives in
//! `scripts/offline_acceptance.sh`. Together they make "no network, no telemetry"
//! airtight.

use std::collections::{BTreeSet, VecDeque};
use std::process::Command;

/// Crates that grant the ability to make outbound network calls or emit telemetry
/// and are **never** permitted in any Costroid build — not even inside
/// `costroid-connect`. They encode the project's standing choices: blocking `ureq`
/// (so no async runtime), `rustls` (so no OpenSSL), and zero telemetry.
const ALWAYS_FORBIDDEN_CRATES: &[&str] = &[
    // HTTP / networking clients & servers other than the sanctioned `ureq`
    "reqwest",
    "hyper",
    "hyper-util",
    "h2",
    "isahc",
    "surf",
    "attohttpc",
    "curl",
    "curl-sys",
    "tiny_http",
    "actix-web",
    "axum",
    "warp",
    "rouille",
    "minreq",
    // websocket / ssh clients — outbound channels no Costroid build may carry.
    // (Raw socket primitives like `socket2`/`mio` are deliberately NOT listed: `mio`
    // is in the legitimate tree via crossterm, and a primitive alone is not egress.)
    "tungstenite",
    "tokio-tungstenite",
    "websocket",
    "ssh2",
    "libssh2-sys",
    "russh",
    // async runtimes that pull in network I/O (Costroid's HTTP is blocking `ureq`)
    "tokio",
    "async-std",
    "smol",
    "async-io",
    // TLS stacks other than `rustls`
    "openssl",
    "openssl-sys",
    "native-tls",
    // DNS resolvers
    "trust-dns-resolver",
    "hickory-resolver",
    // telemetry / analytics / crash reporting
    "sentry",
    "sentry-core",
    "opentelemetry",
    "tracing-opentelemetry",
    "posthog",
    "posthog-rs",
    "segment",
    "amplitude",
    "mixpanel",
    "datadog-apm",
    "metrics-exporter-prometheus",
];

/// The sanctioned trio the connections subsystem (`costroid-connect`) is permitted
/// to link — and **only** it, **only** when the `connect` feature is on: `ureq`
/// (blocking HTTP), `rustls` (its TLS), and `keyring` (the OS keychain). Forbidden
/// in the default/local-only build; permitted once `connect` is enabled.
///
/// (T8 added `keyring` — the credential store; T9a added `ureq` + `rustls` — the
/// generic authorized-host HTTP client. The full trio is now present in the
/// `connect` build and asserted so below; the default-build test must continue to
/// NOT see any of it.)
const CONNECT_GATED_CRATES: &[&str] = &["ureq", "rustls", "keyring"];

/// The designated network/credential home: excluded as a graph *root* (it is the
/// thing being gated), but still reached as a *dependency* when `connect` is on.
const CONNECT_CRATE: &str = "costroid-connect";

/// Every crate `--features connect` legitimately adds to the resolved graph over the
/// default build, unioned across all shipped targets (`costroid-connect` itself excluded
/// — it is the gated home). This is an **allowlist**, not a denylist: the `connect` test
/// asserts the *real* connect-delta is a **subset** of it, so a future dependency bump
/// that pulls a NEW crate (a socket/TLS/telemetry crate under an unlisted name, say) fails
/// the gate until a human reviews it and adds it here. That converts "we ban the network
/// crates we thought of" into "nothing new reaches the network-on build unreviewed".
///
/// It includes the zbus / async-`secret-service` ecosystem because the per-target metadata
/// union reaches it (via dev/build deps + the cross-target union); only `dbus-secret-service`
/// (the **sync** backend) actually links into the shipped binary (`cargo tree -e normal`),
/// and the async *runtimes* (`tokio`/`async-io`/`async-std`/`smol`) stay independently and
/// unconditionally banned by [`ALWAYS_FORBIDDEN_CRATES`] above — so allowlisting the async
/// *plumbing* here cannot let a runtime slip in. Regenerate after a deliberate dependency
/// change with the `#[ignore]` `print_connect_delta` test:
/// `cargo test -p costroid --test offline print_connect_delta -- --ignored --nocapture`.
const CONNECT_ALLOWED: &[&str] = &[
    "aes",
    "async-broadcast",
    "async-trait",
    "block-padding",
    "byteorder",
    "cbc",
    "cc",
    "cipher",
    "concurrent-queue",
    "core-foundation",
    "crossbeam-utils",
    "dbus",
    "dbus-secret-service",
    "endi",
    "enumflags2",
    "enumflags2_derive",
    "event-listener",
    "event-listener-strategy",
    "find-msvc-tools",
    "futures-core",
    "futures-macro",
    "futures-sink",
    "futures-task",
    "futures-util",
    "hkdf",
    "hmac",
    "http",
    "httparse",
    "inout",
    "keyring",
    "libdbus-sys",
    "num",
    "num-bigint",
    "num-complex",
    "num-integer",
    "num-iter",
    "num-rational",
    "openssl-probe",
    "ordered-stream",
    "parking",
    "percent-encoding",
    "pin-project-lite",
    "pkg-config",
    "ring",
    "rpassword",
    "rtoolbox",
    "rustls",
    "rustls-native-certs",
    "rustls-pki-types",
    "rustls-webpki",
    "schannel",
    "secrecy",
    "secret-service",
    "security-framework",
    "security-framework-sys",
    "serde_repr",
    "sha1",
    "shlex",
    "slab",
    "tracing",
    "tracing-attributes",
    "tracing-core",
    "untrusted",
    "ureq",
    "ureq-proto",
    "utf8-zero",
    "windows-targets",
    "windows_x86_64_msvc",
    "xdg-home",
    "zbus",
    "zbus_macros",
    "zbus_names",
    "zeroize",
    "zeroize_derive",
    "zvariant",
    "zvariant_derive",
    "zvariant_utils",
];

/// The target triples Costroid ships (mirrors `deny.toml` `[graph].targets`). The
/// reachable graph is resolved once **per target** and unioned (see
/// [`reachable_crate_names`]).
const SHIPPED_TARGETS: &[&str] = &[
    "x86_64-unknown-linux-gnu",
    "aarch64-unknown-linux-gnu",
    "x86_64-unknown-linux-musl",
    "x86_64-apple-darwin",
    "aarch64-apple-darwin",
    "x86_64-pc-windows-msvc",
];

/// Names of every crate reachable in the **resolved** dependency graph from Costroid's
/// own crates — every workspace member except `costroid-connect` — under the given
/// extra cargo args (e.g. `--features connect`), unioned across every shipped target.
///
/// Resolving **per target** (`--filter-platform`) rather than via one unfiltered
/// `cargo metadata` is deliberate: the unfiltered resolve is an all-targets *superset*
/// that reports phantom optional dependencies a feature would prune — e.g. keyring's
/// unused `async-secret-service` path (`zbus`/`async-io`), which the sync
/// `dbus-secret-service` backend we select never links (confirmed with `cargo tree`).
/// Per-target resolution applies real feature+target pruning, so a phantom `async-io`
/// can't trip the ban; unioning all six triples still catches a network dependency
/// gated to any single platform. `--locked` ties the check to the committed
/// `Cargo.lock`, so it is fully offline and deterministic.
fn reachable_crate_names(extra_args: &[&str]) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    for target in SHIPPED_TARGETS {
        names.extend(reachable_for_target(target, extra_args));
    }
    names
}

/// The resolved reachable set for a single target triple (see [`reachable_crate_names`]).
fn reachable_for_target(target: &str, extra_args: &[&str]) -> BTreeSet<String> {
    let mut args = vec![
        "metadata",
        "--format-version",
        "1",
        "--locked",
        "--filter-platform",
        target,
    ];
    args.extend_from_slice(extra_args);

    let output = match Command::new(env!("CARGO")).args(&args).output() {
        Ok(output) => output,
        Err(err) => panic!(
            "failed to run `cargo metadata --filter-platform {target} {extra_args:?}`: {err}"
        ),
    };
    assert!(
        output.status.success(),
        "`cargo metadata --filter-platform {target} {extra_args:?}` failed:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );

    let meta: serde_json::Value = match serde_json::from_slice(&output.stdout) {
        Ok(value) => value,
        Err(err) => panic!("`cargo metadata` emitted invalid JSON: {err}"),
    };

    let packages = match meta["packages"].as_array() {
        Some(packages) => packages,
        None => panic!("`cargo metadata` output had no `packages` array"),
    };
    let id_to_name: std::collections::HashMap<&str, &str> = packages
        .iter()
        .filter_map(|pkg| Some((pkg["id"].as_str()?, pkg["name"].as_str()?)))
        .collect();

    let resolve = &meta["resolve"];
    let nodes = match resolve["nodes"].as_array() {
        Some(nodes) => nodes,
        None => panic!("`cargo metadata` output had no `resolve.nodes` array"),
    };
    // id -> resolved dependency ids (feature-pruned by the current selection).
    let mut edges: std::collections::HashMap<&str, Vec<&str>> = std::collections::HashMap::new();
    for node in nodes {
        let Some(id) = node["id"].as_str() else {
            continue;
        };
        let deps: Vec<&str> = node["deps"]
            .as_array()
            .map(|deps| deps.iter().filter_map(|d| d["pkg"].as_str()).collect())
            .unwrap_or_default();
        edges.insert(id, deps);
    }

    // Roots: every workspace member except the gated network home.
    let members = match meta["workspace_members"].as_array() {
        Some(members) => members,
        None => panic!("`cargo metadata` output had no `workspace_members` array"),
    };
    let mut queue: VecDeque<&str> = VecDeque::new();
    let mut visited: BTreeSet<&str> = BTreeSet::new();
    for member in members {
        let Some(id) = member.as_str() else {
            continue;
        };
        if id_to_name.get(id).copied() != Some(CONNECT_CRATE) && visited.insert(id) {
            queue.push_back(id);
        }
    }

    // Breadth-first over the resolved edges (all kinds: normal, build, and dev — so
    // a test-only network dependency would be caught too).
    while let Some(id) = queue.pop_front() {
        if let Some(deps) = edges.get(id) {
            for &dep in deps {
                if visited.insert(dep) {
                    queue.push_back(dep);
                }
            }
        }
    }

    visited
        .iter()
        .filter_map(|id| id_to_name.get(id).map(|name| name.to_string()))
        .collect()
}

/// Maintenance helper (not run in CI) — prints the exact crates `--features connect` adds
/// over the default build, unioned across all shipped targets. Run it to regenerate
/// [`CONNECT_ALLOWED`] after a deliberate dependency change:
/// `cargo test -p costroid --test offline print_connect_delta -- --ignored --nocapture`.
#[test]
#[ignore]
fn print_connect_delta() {
    let default = reachable_crate_names(&[]);
    let connect = reachable_crate_names(&["--features", "connect"]);
    let delta: Vec<&String> = connect.difference(&default).collect();
    println!("CONNECT_DELTA ({} crates):", delta.len());
    for name in &delta {
        println!("  {name}");
    }
}

/// Default/local-only build: the gate is **off**, so `costroid-connect` must not be
/// linked and the graph must contain no networking, TLS, or telemetry crate at all
/// (the sanctioned trio included).
#[test]
fn default_build_links_no_network_tls_or_telemetry_crate() {
    let names = reachable_crate_names(&[]);

    assert!(
        !names.contains(CONNECT_CRATE),
        "the default build must not link `{CONNECT_CRATE}` — the `connect` feature \
         must be off by default so the local-only build links no network/keychain code."
    );

    let hits: Vec<&str> = ALWAYS_FORBIDDEN_CRATES
        .iter()
        .chain(CONNECT_GATED_CRATES.iter())
        .copied()
        .filter(|crate_name| names.contains(*crate_name))
        .collect();
    assert!(
        hits.is_empty(),
        "the default/local-only build forbids networking/TLS/telemetry dependencies, \
         but the resolved graph contains: {hits:?}.\n\
         Costroid must read local logs only and make no network call. Network code \
         belongs solely in `costroid-connect`, behind the off-by-default `connect` \
         feature — if a crate must move there, update CONNECT_GATED_CRATES, deny.toml, \
         and the `connect`-build test together."
    );
}

/// `--features connect`: the connections subsystem is linked, so the sanctioned trio
/// (`ureq`/`rustls`/`keyring`) is permitted — but async runtimes, OpenSSL, other HTTP
/// clients, and *all* telemetry stay forbidden even here.
#[test]
fn connect_feature_admits_only_the_sanctioned_trio() {
    let names = reachable_crate_names(&["--features", "connect"]);

    assert!(
        names.contains(CONNECT_CRATE),
        "`--features connect` must link `{CONNECT_CRATE}` — otherwise the gate is not \
         actually wired to the connections subsystem."
    );

    let hits: Vec<&str> = ALWAYS_FORBIDDEN_CRATES
        .iter()
        .copied()
        .filter(|crate_name| names.contains(*crate_name))
        .collect();
    assert!(
        hits.is_empty(),
        "even with `connect` on, Costroid forbids async runtimes, non-rustls TLS \
         (OpenSSL), other HTTP clients, and all telemetry, but the resolved graph \
         contains: {hits:?}.\n\
         The connections subsystem uses only `ureq` + `rustls` + `keyring`."
    );
    // T8 landed the keychain (`keyring`) and T9a the HTTP client (`ureq` + `rustls`):
    // assert the whole sanctioned trio is now actually linked under `connect` — the
    // gate must really pull in the OS-keychain backend the credential store uses and
    // the blocking HTTP/TLS stack the authorized-host client uses.
    for gated in CONNECT_GATED_CRATES {
        assert!(
            names.contains(*gated),
            "`--features connect` must link `{gated}` — the connections subsystem \
             (T8 credential store, T9a authorized-host HTTP client) depends on the \
             full `ureq`/`rustls`/`keyring` trio, so the gate has to pull it in."
        );
    }

    // Subset-allowlist: bound exactly what `connect` *adds* over the default build, so a
    // future dependency bump that introduces a NEW crate (a socket/TLS/telemetry path, or
    // anything else) trips this gate for a human to review — rather than silently slipping
    // past the name-denylist above. `CONNECT_ALLOWED` is the reviewed connect-delta.
    let default = reachable_crate_names(&[]);
    let allowed: BTreeSet<&str> = CONNECT_ALLOWED.iter().copied().collect();
    let unexpected: Vec<&str> = names
        .difference(&default)
        .map(String::as_str)
        .filter(|name| *name != CONNECT_CRATE && !allowed.contains(name))
        .collect();
    assert!(
        unexpected.is_empty(),
        "`--features connect` introduced crate(s) not in the reviewed allowlist: \
         {unexpected:?}.\n\
         Every crate the connect-on graph adds must be reviewed (is it a network / TLS / \
         telemetry path?) and, if legitimate, added to CONNECT_ALLOWED. Regenerate the \
         expected delta with: \
         `cargo test -p costroid --test offline print_connect_delta -- --ignored --nocapture`."
    );
}