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
Original file line number Diff line number Diff line change
@@ -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
---

<!-- skill-link: create-adr -->

# 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Minor][F4] The ADR credits BEP 15 with the signedness, but it comes from the codec.

BEP 15's request table gives field widths ("64-bit integer") but not signedness. The I64 reading comes from this repository's codec (packages/udp-protocol/src/common.rs:58, NumberOfBytes(pub I64)). That same codec reads port as unsigned (Port(pub U16), line 91), so the claim on line 59 that "the format has no unsigned type" does not hold for the codec either. Rule 2 decides each field by what its specification allows, so the ADR should say which text it relies on. (I read the BEP text from memory because it could not be fetched offline.)

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Minor][F12] A negative left makes the peer a seeder. It does not count as a completed download.

is_seeder is left <= 0 and not stopped (packages/primitives/src/peer.rs:269-270). A role change moves the peer into complete, the seeder count (packages/swarm-coordination-registry/src/swarm/coordinator.rs:231-234). The downloads counter goes up only when the event is completed (lines 241-243; is_completed at peer.rs:279-280). Suggested wording: "counts as a seeder (complete)". The previous round checked is_seeder but did not catch this wording.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Minor][F10] Rule 6 cites a fallible conversion in udp-core that the code does not have.

At this head, and on develop 388faf59a, peer_builder::from_request (packages/udp-core/src/peer_builder.rs:16) returns a peer::Peer, not a Result. Line 25 copies a negative bytes_left straight into the domain left. The conversion is what the First application plans (lines 117-119), and issue #2850 lists it as work still to do. This is the F3 slip again, now in the rule itself. Suggested wording: "as the First application below plans for a negative left".

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Nit][F11] "The code changes are tracked in their own issues" names no issue.

Issue #2850 ("Make the number of bytes non-negative by construction") now covers every change listed below as a single issue, and it cross-references this PR. Link it here, and write "its own issue" if it stays a single issue. The spec still says the follow-ups become issues after the ADR is merged (docs/issues/open/2842-inbound-tolerance-adr/ISSUE.md lines 55-56), which is part of F6.


- 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`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Minor][F13] A reader of this tree cannot open the client evidence.

Lines 131-133 rest both client values (left = 16384 and left = i64::MAX before the metadata is known) on a section of "the #2838 specification (PR #2839)". No ref here carries a 2838 spec: not this head, not develop 388faf59a, and no commit touches such a path. Issue #2850 calls PR #2839 superseded and unmerged, so the section will never land through it. The sentence also gives no path, link, client version or source location. Rule 3 asks evidence for "a named client and version" with its source. Suggested fix: cite each client's source directly (repository, tag, file and line), or carry the evidence section in this PR's spec, and drop the dependency on #2839.

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 |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major][F2] The UDP num_want row says the tracker ignores the value. It does not, and the row misses a disagreement between UDP and HTTP.

packages/udp-core/src/services/announce.rs:115 passes the value to PeersWanted::from_client_request (packages/tracker-core/src/announce_handler.rs:262-267): 0 or less means "as many as possible", and a positive value caps the list. HTTP maps numwant through PeersWanted::only (packages/http-core/src/services/announce.rs:325), so numwant=0 over HTTP returns no peers while num_want = 0 over UDP returns the maximum. That is exactly the kind of per-field disagreement rule 7 is about. Suggested UDP column: "any i32; 0 or less = as many as possible, above 0 caps the list". Also add the 0 divergence to the Note.

| 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 |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major][F1] The HTTP ip row says a non-IP value is ignored, but the code rejects it.

packages/http-core/src/services/announce.rs:289-290 maps PeerIp::DnsName and PeerIp::Invalid to PeerIpDnsNameUnsupported and PeerIpInvalid, and these go back to the client as a bencoded failure reason (lines 425-428). Malformed percent-encoding already fails parsing at packages/http-protocol/src/v1/requests/announce.rs:113. A literal ip is also rejected when use_ip_from_query_string is off (http-core lines 285-286). The cited ip ADR still says "silently ignored", so it is out of date and does not record what the code does now. As written, this row would send a follow-up issue to change behaviour that already rejects the value. Suggested HTTP column: "rejected with a failure reason (DNS name, invalid literal, malformed encoding; a literal when the override is off)". Suggested Note: "consistent with rule 1; the ip ADR text is stale".

| 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Minor][F7] The link between the ADR and the affected code only goes one way, and the list is incomplete.

create-adr Step 3.5 asks for module-level doc comments in the affected files that point back to the ADR, and none are added. A doc comment is not a behaviour change, so AC4 allows it; otherwise, record why it waits for the follow-ups. Scope (line 27) and Affected Code also leave out http-core and udp-core. That is where the ip rejection and the num_want mapping live, and where rule 6 puts the left fix.


## 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)
1 change: 1 addition & 0 deletions docs/adrs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading