Repository navigation
test: capability matrix as a contract + mitmproxy addon tests - #2
ThanhNguyxn07 wants to merge 3 commits into
Conversation
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
|
|
||
| /// A transport-level fault. | ||
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | ||
| #[serde(rename_all = "snake_case", tag = "kind", content = "value")] |
There was a problem hiding this comment.
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 👍 / 👎.
| .filter_map(|event| match event { | ||
| mobitether_network::bridge::TrafficEvent::Flow(entry) => Some(entry.clone()), | ||
| _ => None, | ||
| }) |
There was a problem hiding this comment.
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 👍 / 👎.
| ctx.sleep(seconds) # mitmproxy >= 9: non-blocking sleep | ||
| except AttributeError: |
There was a problem hiding this comment.
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 👍 / 👎.
| loop { | ||
| tokio::time::sleep(tokio::time::Duration::from_millis(250)).await; | ||
| let events = mobitether_network::bridge::read_events(sidecar.events_path()).await?; |
There was a problem hiding this comment.
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 👍 / 👎.
| /// 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}") |
There was a problem hiding this comment.
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 👍 / 👎.
| let issues = mobitether_network::validate_rule_set(&rules) | ||
| .map_err(|error| format!("rule set refused: {error}"))?; |
There was a problem hiding this comment.
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 👍 / 👎.
| "response": { | ||
| "status": entry.status_code, | ||
| "statusText": "", | ||
| "httpVersion": if entry.tls { "HTTP/2" } else { "HTTP/1.1" }, |
There was a problem hiding this comment.
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.
272c6c8 to
36cc508
Compare
There was a problem hiding this comment.
💡 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): |
There was a problem hiding this comment.
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 👍 / 👎.
36cc508 to
0d379f1
Compare
There was a problem hiding this comment.
💡 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): |
There was a problem hiding this comment.
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.
0d379f1 to
f646dff
Compare
💡 Codex ReviewWhen this test runs, ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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,
mainlanded its own Phase 3 Network & Chaos Lab (mitmproxy sidecar, honest TLSpinning 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
mainand does not collide with it.1. Capability matrix: 3 hand-picked assertions → 11 invariants over 36 combinations
docs/02promises the UI never claims a capability the device does not have. That promisewas carried by three assertions someone happened to write.
Unsupportedeverywhere, with a reasonRemoteMacRequired; one documented libimobiledevice carve-outMissingToolchain, notUnsupportedrun-as/provisioning are build propertiesPlus a 36-line golden snapshot (
capability_goldenexample) diffed in CI — a diff there isa behaviour change, not a formatting change.
Bug the tests caught: iOS Simulator storage inspection claimed
Supportedwithoutdistinguishing 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
tflowfixtures, so theyexercise the objects the addon really sees in production.
Covers: mock application, method/pattern scoping, disabled rules, drop-connection reporting,
the
tls_pinnedhonesty hook, event-stream shape, live rule reload, corrupt rules file.Crash bug found and fixed: a hand-edited rules file containing invalid JSON raised
JSONDecodeErrorout of_reload_rules_if_changed, which only caughtOSError— taking thewhole sidecar down over a typo. It now runs with no rules instead.
Two behaviours pinned as explicit decisions, not fixed here:
url_patternmatches the whole URL, so a bareexample.comalso matchescdn.example.com. Scoping to one host requires the host in the pattern.delay_msrule sleeps inside therequesthook, so while one delay runs everyconcurrent 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) andrender_poc_markdown_report's eight positional inputs moved into aReportInputstruct,which also clears the last clippy warning. No behaviour change.
Verification
CI gains
fmt,clippy -D warnings, a golden-matrix diff, and asidecarsjob that installsmitmproxy and runs the addon tests.
Note
This is not the Network & Chaos Lab from the first version of this branch — that one
duplicated what
mainnow ships. If you would rather have my rule-engine design (validatedrule sets, ambiguity detection, deterministic priority) folded into the implementation that
landed on
maininstead of sitting beside it, say so and I will rework it as a refactor ofthat crate rather than as a separate file.