Skip to content

test: capability matrix as a contract + mitmproxy addon tests - #2

Open
ThanhNguyxn07 wants to merge 3 commits into
mainfrom
feat/network-chaos-lab
Open

ThanhNguyxn07 wants to merge 3 commits into
mainfrom
feat/network-chaos-lab

Conversation

@ThanhNguyxn07

@ThanhNguyxn07 ThanhNguyxn07 commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Make the capability matrix a tested contract + tests for the mitmproxy addon

This PR replaces an earlier version of the same branch. Between my first push and
now, main landed its own Phase 3 Network & Chaos Lab (mitmproxy sidecar, honest TLS
pinning detection, mocks/chaos, HAR 1.2 export, CLI/MCP/desktop UI) and a Phase 4 QA
Intelligence
update. My original PR carried a second, parallel implementation of the
same thing — duplicate crates, a duplicate addon, duplicate CLI commands. That is gone.

What remains is the part that did not exist on main and does not collide with it.


1. Capability matrix: 3 hand-picked assertions → 11 invariants over 36 combinations

docs/02 promises the UI never claims a capability the device does not have. That promise
was carried by three assertions someone happened to write.

Invariant Why it exists
Every cell carries a non-empty reason A bare "unsupported" is a support ticket
Every non-supported cell offers an actionable remedy A dead end with no next step is unusable
Android+Simulator / iOS+Emulator Unsupported everywhere, with a reason Category errors must not half-work
iOS without a Mac → RemoteMacRequired; one documented libimobiledevice carve-out Phase 3's whole premise, enforced
Connecting a remote Mac never reduces a capability The tether is additive, never subtractive
HTTPS capture never claimed unconditionally Certificate pinning defeats any proxy
Removing a tool only degrades the matrix, never upgrades it A rule that "improves" when a tool is missing is a bug
Missing tool reads as MissingToolchain, not Unsupported "You can fix this" ≠ "never works"
Sandbox inspection needs a debug build or a Mac-side container run-as/provisioning are build properties

Plus a 36-line golden snapshot (capability_golden example) diffed in CI — a diff there is
a behaviour change, not a formatting change.

Bug the tests caught: iOS Simulator storage inspection claimed Supported without
distinguishing a local Mac from a tethered one, even though every other iOS arm makes
that distinction. That is exactly the kind of claim this matrix exists to prevent.

2. mitmproxy addon: 0 tests → 13 tests against a real mitmproxy

Main's addon had no tests at all. These use mitmproxy's own tflow fixtures, so they
exercise the objects the addon really sees in production.

Covers: mock application, method/pattern scoping, disabled rules, drop-connection reporting,
the tls_pinned honesty hook, event-stream shape, live rule reload, corrupt rules file.

Crash bug found and fixed: a hand-edited rules file containing invalid JSON raised
JSONDecodeError out of _reload_rules_if_changed, which only caught OSError — taking the
whole sidecar down over a typo. It now runs with no rules instead.

Two behaviours pinned as explicit decisions, not fixed here:

  • url_pattern matches the whole URL, so a bare example.com also matches
    cdn.example.com. Scoping to one host requires the host in the pattern.
  • a delay_ms rule sleeps inside the request hook, so while one delay runs every
    concurrent flow stalls
    — a "slow network" rule currently slows the whole proxy, not just
    its target host. This is the one I would fix next.

3. Hygiene

cargo fmt --all (the workspace had never been formatted — 11 files drifted) and
render_poc_markdown_report's eight positional inputs moved into a ReportInput struct,
which also clears the last clippy warning. No behaviour change.


Verification

cargo fmt --all --check                                    # pass
cargo clippy --workspace --all-targets -- -D warnings     # pass (was 1 warning)
cargo test --workspace                                     # 29 pass (was 14)
python sidecars/mitmproxy-addon/test_addon.py             # 13 pass (was 0)

CI gains fmt, clippy -D warnings, a golden-matrix diff, and a sidecars job that installs
mitmproxy and runs the addon tests.

Note

This is not the Network & Chaos Lab from the first version of this branch — that one
duplicated what main now ships. If you would rather have my rule-engine design (validated
rule sets, ambiguity detection, deterministic priority) folded into the implementation that
landed on main instead of sitting beside it, say so and I will rework it as a refactor of
that crate rather than as a separate file.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 143c76d1-f8f9-4bd4-bcc0-4c1189e908d9
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T16:11:06.788836Z f646dff New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 272c6c82fd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mobitether-domain/src/network.rs Outdated

/// A transport-level fault.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "value")]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Serialize chaos kinds in the format the addon reads

When the CLI writes rules, this adjacently tagged enum serializes as an object such as {"kind":"latency_ms"}, but the addon compares rule.get("kind") with strings like "latency_ms" and "offline". Consequently, chaos rules in Rust-generated rule files are silently ignored during capture; make the serialized shape match what the addon consumes, or update the addon to decode the tagged object.

Useful? React with 👍 / 👎.

Comment thread crates/mobitether-cli/src/main.rs Outdated
Comment on lines +577 to +580
.filter_map(|event| match event {
mobitether_network::bridge::TrafficEvent::Flow(entry) => Some(entry.clone()),
_ => None,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Include TLS-blocked events in the capture result

When mitmproxy reports a TLS handshake failure, the addon emits TrafficEvent::TlsBlocked, not Flow. This filter discards that event, so the final summary can report zero unintercepted flows and both capture HAR export and network har omit the TLS failure, even though it appeared in the live output and NDJSON stream. Preserve TlsBlocked events in the summary and export.

Useful? React with 👍 / 👎.

Comment on lines +288 to +289
ctx.sleep(seconds) # mitmproxy >= 9: non-blocking sleep
except AttributeError:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Import the mitmproxy context before calling sleep

When a latency, jitter, or timeout rule reaches _sleep with a positive delay, ctx is undefined in this module, so the call raises NameError; the fallback catches only AttributeError. Those delays therefore fail instead of being applied, and bandwidth_kbps can fail before its response event is emitted. Import or otherwise define the context used here, or use a working fallback.

Useful? React with 👍 / 👎.

Comment thread crates/mobitether-cli/src/main.rs Outdated
Comment on lines +557 to +559
loop {
tokio::time::sleep(tokio::time::Duration::from_millis(250)).await;
let events = mobitether_network::bridge::read_events(sidecar.events_path()).await?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle Ctrl-C as a normal capture stop

When --duration is omitted, the command is documented to run until Ctrl-C, but this loop does not handle that signal. Ctrl-C terminates the process instead of breaking the loop, so sidecar.stop(), the final summary, and the requested --har export after the loop do not run. Handle Ctrl-C as a graceful loop exit.

Useful? React with 👍 / 👎.

Comment thread crates/mobitether-network/src/har.rs Outdated
/// timestamp is attached by the core when the event is recorded. Placeholder
/// keeps the document valid for importers that require the field.
fn iso_stub(id: u64) -> String {
format!("1970-01-01T00:00:00.000Z#{id}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Emit a valid HAR timestamp

Appending #id after Z makes startedDateTime values such as 1970-01-01T00:00:00.000Z#1 invalid RFC3339 timestamps. Every exported HAR entry uses this value, so standard HAR readers may reject the file; _mobitetherId already preserves the entry ID separately.

Useful? React with 👍 / 👎.

Comment thread crates/mobitether-cli/src/main.rs Outdated
Comment on lines +503 to +504
let issues = mobitether_network::validate_rule_set(&rules)
.map_err(|error| format!("rule set refused: {error}"))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the full rule validation in rules-check

validate_rule_set does not check mock override statuses or reject mocks that override nothing, while NetworkRuleSet::validate does and is used by capture. As a result, rules-check can report such a file as OK even though network capture rejects it; use the same comprehensive validation path for both commands.

Useful? React with 👍 / 👎.

Comment thread crates/mobitether-network/src/har.rs Outdated
"response": {
"status": entry.status_code,
"statusText": "",
"httpVersion": if entry.tls { "HTTP/2" } else { "HTTP/1.1" },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not infer HTTP/2 from TLS

A tls flag indicates encryption, not the negotiated HTTP version. This labels every captured TLS flow as HTTP/2, including HTTPS requests served over HTTP/1.1, so exported HAR metadata can mislead downstream debugging tools. Capture the actual protocol version or avoid asserting HTTP/2 from TLS alone.

Useful? React with 👍 / 👎.

Two independent hygiene fixes, kept together because CI is being taught to
enforce both.

- `cargo fmt --all` — the workspace had never been formatted; 11 files drift.
- `render_poc_markdown_report` takes eight positional inputs. They now travel in
  a `ReportInput` struct, which also clears the last clippy warning
  (too_many_arguments) and makes the call site readable.

No behaviour change.
@ThanhNguyxn07
ThanhNguyxn07 force-pushed the feat/network-chaos-lab branch from 272c6c8 to 36cc508 Compare December 2, 2026 15:52
@ThanhNguyxn07 ThanhNguyxn07 changed the title feat(phase-4): Network & Chaos Lab + capability matrix as a tested contract test: capability matrix as a contract + mitmproxy addon tests Dec 2, 2026
Comment thread .github/workflows/ci.yml Fixed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 36cc50825e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

self._rules = data if isinstance(data, list) else []
self._rules_mtime = st.st_mtime
except OSError:
except (OSError, ValueError):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface malformed rule files before disabling chaos

When rules.json contains invalid JSON, this catches the parse error and clears _rules without emitting a diagnostic; spawn_mitmdump discards mitmdump's stdout and stderr, so capture continues with chaos and mock rules silently disabled. A fault-injection test can then record a misleading clean result. Surface the parse failure to the capture user before falling back.

Useful? React with 👍 / 👎.

@ThanhNguyxn07
ThanhNguyxn07 force-pushed the feat/network-chaos-lab branch from 36cc508 to 0d379f1 Compare December 2, 2026 15:56

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0d379f17be

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

self._rules = data if isinstance(data, list) else []
self._rules_mtime = st.st_mtime
except OSError:
except (OSError, ValueError):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report invalid rules before disabling fault injection

This commit newly catches ValueError here and clears _rules without reporting the parse failure. If rules.json is malformed, mitmproxy stays up but all mock and chaos rules are disabled; because spawn_mitmdump discards its output, a fault-injection capture can look clean without warning. Emit a visible error before falling back.

Useful? React with 👍 / 👎.

…amples

docs/02 promises the UI never claims a capability the device does not have. That
promise was carried by three hand-picked assertions.

Adds 11 invariants over all 36 host x platform x device x tether combinations, plus
a 36-line golden snapshot generated by a new `capability_golden` example and
diffed in CI. Highlights:

- Android+Simulator and iOS+Emulator are `Unsupported` everywhere, and say why
- iOS without a Mac requires a remote Mac; the only `Partial` exception for a
  physical device is the documented libimobiledevice carve-out
- connecting a remote Mac never *reduces* a capability
- HTTPS capture is never claimed unconditionally, because pinning defeats any proxy
- removing a tool can only degrade the matrix, never upgrade it

The tests caught one real inconsistency: iOS Simulator storage inspection claimed
`Supported` without distinguishing a local Mac from a tethered one, even though
every other iOS arm makes that distinction. Fixed in capability.rs.

CI caught a second one: the golden comparison used raw bytes, so a CRLF checkout
of the snapshot on Windows failed the test while the matrix was identical. Line
endings are now normalised on both sides, and `.gitattributes` pins the fixture
to LF so git stops rewriting it.
13 tests against a real mitmproxy install, using mitmproxy's own `tflow` fixtures,
so they exercise the objects the addon actually sees in production rather than a
hand-written double.

Covered: mock application, method and pattern scoping, disabled rules,
drop-connection reporting, the `tls_pinned` honesty hook, event-stream shape, live
rule reload, and a corrupt rules file.

Two behaviours are pinned deliberately, because both look like bugs and should be
an explicit decision rather than a surprise:

- `url_pattern` matches the whole URL, so a bare `example.com` also matches
  `cdn.example.com`. Scoping to one host requires the host in the pattern.
- a `delay_ms` rule sleeps inside the `request` hook, so while one delay runs
  every concurrent flow stalls. Documented, not fixed here.

Also fixes a crash the tests found: a hand-edited rules file containing invalid
JSON raised `JSONDecodeError` out of `_reload_rules_if_changed`, which only caught
`OSError` -- taking the whole sidecar down over a typo. It now runs with no rules
instead.

CodeQL drove three more changes here: `tempfile.mktemp` (deprecated and
race-prone) replaced with `mkdtemp`, the URL assertion rewritten to compare the
reported host explicitly instead of searching a URL for a substring, and the
workflows given an explicit `permissions: contents: read`.

CI gains a `sidecars` job that installs mitmproxy and runs these tests.
@ThanhNguyxn07
ThanhNguyxn07 force-pushed the feat/network-chaos-lab branch from 0d379f1 to f646dff Compare December 2, 2026 16:04
@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

assert flow.response is None or True # `flow.kill()` is a no-op on a fixture

P2 Badge Verify the drop hook actually kills the flow

When this test runs, flow.response is None or True is always true, so removing flow.kill() would still pass as long as the chaos event is emitted. Spy on flow.kill() or assert against a fixture with an observable kill state so CI catches regressions in connection dropping.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants