diff --git a/docs/adrs/20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md b/docs/adrs/20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md new file mode 100644 index 0000000000..a39dced118 --- /dev/null +++ b/docs/adrs/20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md @@ -0,0 +1,226 @@ +--- +semantic-links: + skill-links: + - create-adr + related-artifacts: + - docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md + - docs/adrs/20261007082938_bound_protocol_agnostic_values_by_the_tightest_delivery_protocol.md + - docs/adrs/20260723184019_separate_configuration_value_invariants_from_consistency_validation.md + - docs/adrs/20260721100000_use_newtypes_for_constrained_configuration_field_types.md + - docs/adrs/20260527175600_keep_protocol_and_domain_types_decoupled.md + - docs/adrs/20260727000000_events_are_objective_facts.md + - docs/adrs/20260617093046_reject_wildcard_external_ip.md + - docs/adrs/20261005124222_cap_scrape_info_hashes_per_protocol.md + - docs/adrs/20260716000000_accept_only_ip_addresses_in_http_announce_ip_param.md + - packages/http-protocol/src/v1/requests/announce.rs + - packages/udp-protocol/src/request.rs + - packages/primitives/src/peer.rs +--- + + + +# Reject Malformed Inbound Protocol Values Unless Real Clients Need the Tolerance + +## Scope + +Repository-level. The decision applies to every delivery protocol that receives client requests +(`udp-protocol`, `udp-server`, `http-protocol`, `axum-http-server`) and to the domain types in +`primitives` that those protocols feed, so it belongs in `docs/adrs/`. + +## Description + +BitTorrent is decentralized and has no conformance authority. Implementations that accept the +widest range of client behavior interoperate with the most clients ("be liberal in what you +accept"). A tracker that is liberal everywhere, however, hides client bugs, lets different delivery +protocols disagree about the same value, and pushes values into the domain that its code never +considered. + +The first case found is the announce `left` field. BEP 15 encodes it as a signed 64-bit integer, +and the UDP announce accepts a negative value. The HTTP announce parses `left` as `u64` and rejects +it. `Peer::is_seeder` (`packages/primitives/src/peer.rs`) treats `left <= 0` as a seeder, so a +negative value from a UDP client counts as a completed download, while the same value over HTTP is +an error. Nobody decided this; it follows from the parsers being written independently. + +The existing ADRs cover the other direction. [Bound protocol-agnostic values by the tightest +delivery protocol](20261007082938_bound_protocol_agnostic_values_by_the_tightest_delivery_protocol.md) +is about values the tracker sends. The [value-invariant +ADR](20260723184019_separate_configuration_value_invariants_from_consistency_validation.md) and the +[newtype ADR](20260721100000_use_newtypes_for_constrained_configuration_field_types.md) say how to +reject a bad configuration value. None of them says what to do with a value a client sends. + +## Agreement + +1. **Strict by default.** A value a client sends that its protocol specification does not allow is + rejected with the protocol's normal error response (a BEP 15 error packet over UDP, a bencoded + `failure reason` over HTTP). It is not clamped, defaulted, or silently ignored. + +2. **Judge each field on its own.** A value that looks unusual may be legitimate: BEP 15 + `num_want = -1` means "use the default", and `left`, `downloaded` and `uploaded` are 64-bit + integers in BEP 15, and the sources do not document why they are signed. The question for each field is what its + specification allows, not whether the value is negative or large. "Reject all negatives" is + not the rule. + +3. **Tolerate only with recorded evidence.** The tracker tolerates a malformed value only when + there is evidence that a meaningful share of real clients relies on it. Evidence is one of: a + named client and version that sends the value (an issue report, a packet capture, or the + client's source), or the rejection metric described in point 5. A tolerance without evidence is + not added, and a "might break some client" argument alone is not evidence. + +4. **Record every tolerance in code and in this ADR.** A tolerance is one row in the register + below, and its code carries a comment that links to this ADR. The row says the field, the + protocols, the tolerated values, what they are normalized to, the evidence, the metric, and + when to reconsider it. Adding or removing a row is an amendment to this ADR and goes through a + PR like any other change. + +5. **Make the decision measurable.** The tracker counts every request rejected for a malformed + inbound value, labeled by delivery protocol, field and a bounded client family, so the number + of affected real clients can be read before a tolerance is added. Every tolerance has its own + counter, emitted as an objective event per [Events Are Objective Facts](20260727000000_events_are_objective_facts.md) (or, where a metric is not feasible, a rate-limited log) so the register can be + reviewed with data and a tolerance that no client uses is removed. + +6. **Implement the public specification strictly; refuse at the first project-owned type.** + Following a public protocol specification faithfully has priority over failing fast. A type + that mirrors a BEP keeps the shape the BEP gives it and is not narrowed, because the + specification is not our decision and its reasons may be unknown. The wire parser therefore + accepts what the BEP type allows. A value the specification allows but the domain does not is + refused at the first conversion into a type the project owns (application or domain layer), + as the fallible conversion in `udp-core` does for a negative `left`. The malformed value + never reaches `primitives` or `tracker-core`. A tolerance normalizes to a value the domain + already accepts. Domain types protect their invariants with newtypes and constructors (for + example a non-negative number of bytes) and carry no special cases for malformed input. See + [Keep protocol and domain types decoupled](20260527175600_keep_protocol_and_domain_types_decoupled.md). + +7. **The protocols agree on the verdict for a value both wire formats can express.** UDP and + HTTP must not disagree about whether such a value is accepted. A range that only one wire + format can express follows that protocol's own specification: the protocols may differ at the + wire level and are equal in the domain, as in [Cap scrape info hashes per + protocol](20261005124222_cap_scrape_info_hashes_per_protocol.md). Rejecting a malformed value + is not by itself a reason to ban the client; banning stays with the rules of the UDP ban + service. Each field has a parity test that exercises both parsers with the same values. + +8. **Validate each kind of rule in the layer that owns it, as early as possible.** Syntax is + validated in the delivery layer (the wire parser), application invariants in the service, and + domain invariants in the domain. Public protocol packages follow + [Package Conventions](../packages.md#package-conventions), principle 2: `*-protocol` + packages strictly implement BEP specifications. + +9. **Protect invariants with constructors or newtypes, not standalone validation functions.** A + value that must hold an invariant has a type whose constructor enforces it, so a valid value + cannot be bypassed and the check is not repeated by every caller. + +### First application: byte counts + +Announce `left`, `downloaded` and `uploaded` apply the rules above. This records the intended +design; the code changes are tracked in their own issues. + +- Domain `NumberOfBytes` (in `primitives`) is a private `u64` with no upper bound. +- UDP wire type `NumberOfBytes(I64)` and `Request::parse_bytes` stay unchanged. A negative value + is refused in a fallible `peer_builder::from_request` in `udp-core`; its error is wrapped by + `UdpAnnounceError`. This replaces the validation function added by #2839. +- The HTTP protocol type becomes a private `u64` and its `i64::MAX` limit + (`NumberOfBytesOverflow`) is removed, because the limit only existed to fit the old shared + `i64` type. HTTP then accepts `0..=u64::MAX` and UDP `0..=i64::MAX`; the domain is the same for + both. +- REST resource fields for byte counts are `u64`. + +Research behind the signed UDP fields: BEP 15 and the XBT Tracker document say only "64-bit +integer" for these fields, never signed or unsigned. The libtorrent document (cited by BEP 15 as +an existing implementation) uses `int64_t` for the byte counts, but `uint32_t` for `ip` and `key` +and `uint16_t` for `port`, so unsigned types exist in the format. BEP 3 says only "encoded in +base ten ascii". No document says why the counts are signed or what a tracker must do with a +negative value. The "Evidence on real clients and other trackers" section of the #2838 +specification (PR #2839) shows that, before the metadata is known, libtorrent sends `left = 16384` +and Transmission sends `left = i64::MAX`; neither sends a negative value. + +### Register of tolerances + +| Field | Protocols | Tolerated values | Normalized to | Evidence | Metric | Reconsider when | +| ----- | --------- | ---------------- | ------------- | -------- | ------ | --------------- | +| _None yet_ | | | | | | | + +### Existing leniencies (inventory, not yet applied to this rule) + +These were found while writing this ADR. They predate it, so none has recorded evidence or a +metric. Each is to be kept (and registered with its evidence), changed to reject, or aligned across +protocols in its own issue; this ADR does not change any of them. + +| Field | UDP | HTTP | Note | +| ----- | --- | ---- | ---- | +| Announce `left`, `downloaded`, `uploaded` | accepts negative (signed 64-bit) | rejects negative (its `i64::MAX` limit exists only to fit the old shared type) | First application: bug #2838, fixed in PR #2839 (UDP now rejects it) | +| Announce `port` = 0 | rejected by the parser | no zero check found in the parser (to verify) | Possible disagreement. BEP 15 does not forbid port 0, so under rule 6 this parser check deserves a review. The event check (`0..=3`) mirrors BEP 15 | +| Announce `num_want` / `numwant` | any `i32`; tracker ignores it | `u32` only; `-1` rejected | `-1` is legitimate for UDP (BEP 15 default); HTTP `-1` is unspecified | +| Announce event outside the defined set | rejected | rejected | Consistent | +| Announce `ip` that is not an IP address | field ignored always | ignored; connection IP used | Recorded in [the `ip` ADR](20260716000000_accept_only_ip_addresses_in_http_announce_ip_param.md); no metric | +| Scrape above the info-hash cap | extra hashes dropped | extra hashes dropped | Recorded in [the scrape cap ADR](20261005124222_cap_scrape_info_hashes_per_protocol.md); no metric | + +## Alternatives Considered + +### Tolerant by default + +Accept and normalize anything that can be interpreted. Rejected: it maximizes compatibility but +hides client bugs, discourages good implementations, and has already produced a protocol +disagreement and a domain type that must handle values it should never receive. + +### Strict by default with no exceptions + +Rejected. A widely deployed client that cannot be fixed would be locked out of a tracker, which +defeats a tracker's purpose. The evidence rule keeps the choice open without making tolerance the +default. + +### Per-protocol policy + +Let each delivery protocol decide its own tolerance. Rejected: it is how the `left` disagreement +arose, and one swarm served over several protocols should not depend on which one a client used. + +### Make tolerance a configuration option + +Rejected for now. An operator switch multiplies the combinations to test and does not produce the +evidence this ADR asks for. It can be reconsidered for one specific tolerance if the evidence +shows operators disagree. + +### Normalize in the domain instead of the parser + +Rejected. It spreads protocol knowledge into `primitives`, against [Keep protocol and domain types +decoupled](20260527175600_keep_protocol_and_domain_types_decoupled.md), and the same value would +need handling in every consumer. + +## Consequences + +- **Positive**: one explicit, reviewable rule for every inbound field; UDP and HTTP stop + disagreeing by accident. +- **Positive**: the domain can rely on valid values, so `is_seeder` and similar code stay simple. +- **Positive**: tolerance decisions are driven by data (the rejection counters) and can be undone. +- **Negative**: a client with a malformed value is rejected until someone shows evidence and a + tolerance is registered, so the maintainers will occasionally get a compatibility bug report. +- **Negative**: the rejection counter and per-tolerance metrics are new work, and the client-family + label needs a bounded cardinality. +- **Negative**: the existing leniencies in the inventory are inconsistent with the rule until each + is handled. + +## Affected Code + +- [`packages/http-protocol/src/v1/requests/announce.rs`](../../packages/http-protocol/src/v1/requests/announce.rs): + HTTP announce parsing. +- [`packages/udp-protocol/src/request.rs`](../../packages/udp-protocol/src/request.rs): UDP request + parsing. +- [`packages/primitives/src/peer.rs`](../../packages/primitives/src/peer.rs): `Peer::is_seeder`. + +This ADR changes no code. Follow-up issues apply it field by field. + +## Date + +2026-11-11 + +## References + +- [Issue #2842](https://github.com/torrust/torrust-tracker/issues/2842) — this ADR +- [EPIC #1347](https://github.com/torrust/torrust-tracker/issues/1347) — package testing overhaul, where the `left` finding came up +- [BEP 3: The BitTorrent Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +- [BEP 15: UDP Tracker Protocol](https://www.bittorrent.org/beps/bep_0015.html) +- [Issue #2838](https://github.com/torrust/torrust-tracker/issues/2838) and [PR #2839](https://github.com/torrust/torrust-tracker/pull/2839) — first application: reject a negative `left`, `uploaded` or `downloaded` in a UDP announce +- [Events Are Objective Facts](20260727000000_events_are_objective_facts.md) — how rejections and tolerances are reported +- [Reject wildcard IPs as invalid `external_ip` values](20260617093046_reject_wildcard_external_ip.md) — the same fail-fast stance for configuration +- [Use Exact IP Counters for UDP Banning](../../packages/udp-core/docs/adrs/20260829204258_use_exact_ip_counters_for_udp_banning.md) — ban rules, independent of this decision +- [Bound protocol-agnostic values by the tightest delivery protocol](20261007082938_bound_protocol_agnostic_values_by_the_tightest_delivery_protocol.md) +- [Separate Configuration Value Invariants from Consistency Validation](20260723184019_separate_configuration_value_invariants_from_consistency_validation.md) +- [Use Newtypes for Domain-Constrained Configuration Field Types](20260721100000_use_newtypes_for_constrained_configuration_field_types.md) diff --git a/docs/adrs/index.md b/docs/adrs/index.md index ff3fe2c840..6c393b4738 100644 --- a/docs/adrs/index.md +++ b/docs/adrs/index.md @@ -62,6 +62,7 @@ supersession rules. | [20261105132341](20261105132341_define_the_stats_and_metrics_endpoints_and_require_help_and_type_in_prometheus_output.md) | 2026-11-05 | Define the stats and metrics endpoints and require HELP and TYPE in Prometheus output | `/stats` is not deprecated and serves the aggregated statistics, `/metrics` serves the extendable labelled metrics, and every exported Prometheus text must carry `# HELP` and `# TYPE` (legacy `/stats` text aligned by #2734, amended 2026-11-06). | | [20261106102632](20261106102632_scope_the_cli_output_contract_and_keep_exit_codes_to_zero_one_two.md) | 2026-11-06 | Scope the CLI output contract and keep exit codes to 0, 1 and 2 | The contract covers operator binaries and the AI-agent and CI tools, not developer diagnostics; commands use only exit codes 0/1/2, and a distinct outcome is a `kind`: a result with exit 0 when it is the answer asked for, a stderr diagnostic with exit 1 when the command could not answer. | | [20261111095222](20261111095222_close_idle_connections_without_a_408_response.md) | 2026-11-11 | Close idle connections without a 408 response | A connection that sends no complete first request is closed silently after the first-request timeout; no `408 Request Timeout` is sent. | +| [20261111170611](20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md) | 2026-11-11 | Reject malformed inbound protocol values unless real clients need the tolerance | Clients that send values the protocol does not allow are rejected by default; a tolerance needs recorded evidence, a register entry and a metric, and applies the same over UDP and HTTP. | ## ADR Lifecycle diff --git a/docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md b/docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md new file mode 100644 index 0000000000..e8e773f270 --- /dev/null +++ b/docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md @@ -0,0 +1,150 @@ +--- +schema-version: 1 +doc-type: issue +issue-type: task +status: planned +priority: p2 +epic: null +github-issue: 2842 +spec-path: docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md +branch: "2842-inbound-tolerance-adr" +related-pr: null +last-updated-utc: "2026-11-11 17:10" +semantic-links: + skill-links: + - create-issue + - create-adr + related-artifacts: + - .github/skills/dev/planning/create-issue/SKILL.md + - .github/skills/dev/planning/create-adr/SKILL.md + - docs/adrs/20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md +--- + + + +# Issue #2842 - ADR: reject malformed inbound protocol values unless real clients need the tolerance + +## Goal + +Record a repository-level ADR that says when the tracker tolerates a non-conforming client request +and when it rejects it, so UDP and HTTP stop disagreeing by accident. + +## Background + +Found while writing the `primitives` tests for EPIC #1347. The UDP announce accepts a negative +`left` (signed 64-bit on the wire), while HTTP rejects it, and `Peer::is_seeder` treats a negative +`left` as a seeder. Bug #2838 (PR #2839) fixes that case; it needs a rule to +apply. No ADR covers inbound values: the existing +[tightest-protocol ADR](../../../adrs/20261007082938_bound_protocol_agnostic_values_by_the_tightest_delivery_protocol.md) +covers values the tracker sends. + +Maintainer position (2026-11-11): tolerant implementations accept the widest range of clients, +but the maintainer prefers strictness to encourage good implementations, unless a meaningful +share of real clients relies on the tolerant behavior. + +## Scope + +### In Scope + +- One ADR in `docs/adrs/` with the rule, a register of tolerances (empty), and an inventory of the + existing inbound leniencies found in `http-protocol`, `udp-protocol` and `udp-server`. +- The row in `docs/adrs/index.md`. + +### Out of Scope + +- Any production-code change, including the `left` fix, the rejection metrics, and aligning the + other inventory items. Each becomes its own issue after the ADR is merged. + +## Architectural Decisions + +- Related ADRs: the tightest-protocol, value-invariant, newtype, protocol/domain decoupling, + scrape-cap and announce-`ip` ADRs (linked from the ADR). +- ADRs to create: `20261111170611_reject_malformed_inbound_protocol_values_unless_clients_need_tolerance.md`. + +## Design and Ownership Review + +Not applicable. + +## Bug-Fix Process + +Not applicable. + +## Regression Test Strategy + +Not applicable. + +## Implementation Plan + +| ID | Status | Task | Notes / Expected Output | +| --- | ------ | -------------------------------------------- | ------------------------------------------------- | +| T1 | DONE | Draft the ADR and inventory | ADR file written, inventory checked against code | +| T2 | TODO | Maintainer review and decisions | Open questions in the PR resolved | +| T3 | TODO | Index row, `linter all`, PR | Docs-only PR, `Closes #` | +| T4 | TODO | Propose follow-up issues from the inventory | One issue per leniency to apply the rule | + +## Commit Points + +| Task | Coherent change set | Commit policy | +| ---- | ------------------------------------ | ---------------------------------------------------- | +| T1 | ADR file plus index row | Commit after `linter all`. | +| T3 | Issue spec moved to `docs/issues/open/` | Commit after `linter all`. | + +## Progress Tracking + +### Workflow Checkpoints + +- [x] Folder-style spec drafted in `docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md` +- [x] Spec reviewed and approved by user/maintainer +- [x] GitHub issue created and issue number added to this spec +- [ ] Implementation completed +- [ ] Automatic verification completed (`linter all`) +- [ ] Acceptance criteria reviewed after implementation and updated with evidence +- [ ] Issue closed and spec moved from `docs/issues/open/` to `docs/issues/closed/` + +### Progress Log + +- 2026-11-11 17:10 UTC - Claude Code (Claude Sonnet 5.5) - Drafted spec and ADR. +- 2026-11-12 14:00 UTC - Claude Code (Claude Sonnet 5.5) - Maintainer approved the spec; issue #2842 created. + +## Acceptance Criteria + +- [ ] AC1: The ADR states the rule (strict by default, evidence-based tolerance, recorded in code + and ADR, measurable, same over every delivery protocol, decided per field). +- [ ] AC2: The ADR cites bug #2838 (PR #2839) as the first application and the existing + related ADRs. +- [ ] AC3: The inventory matches the current code (each row verified or marked "to verify"). +- [ ] AC4: No production code changes. +- [ ] `linter all` exits with code `0` + +## Verification Plan + +### Automatic Checks + +- `linter all` (markdown, cspell, links) + +### Manual Verification Scenarios + +Not applicable: documentation-only change, no behavior to exercise. + +### Acceptance Verification + +| AC ID | Status | Evidence | +| ----- | ------ | -------- | +| AC1 | TODO | ADR PR | +| AC2 | TODO | ADR PR | +| AC3 | TODO | ADR PR | +| AC4 | TODO | PR diff | + +## Risks and Trade-offs + +- The inventory can go stale; it is labeled as a snapshot and each row links to its follow-up. +- The rule commits the project to adding a rejection metric; that work is tracked separately. + +## Implementation Completion Review + +- Retrospective: `Not yet assessed` + +## References + +- Related issues: #1347 (EPIC), #2838 (fixed by PR #2839) +- Related ADRs: `docs/adrs/20261007082938_bound_protocol_agnostic_values_by_the_tightest_delivery_protocol.md`