Skip to content

fix(tracker-core): [#3051] return an error when a random key duration overflows the clock - #3064

Merged
josecelano merged 5 commits into
torrust:developfrom
josecelano-bot:3051-random-expiring-key-duration-overflow-panic
Nov 26, 2026
Merged

josecelano merged 5 commits into
torrust:developfrom
josecelano-bot:3051-random-expiring-key-duration-overflow-panic

Conversation

@josecelano-bot

@josecelano-bot josecelano-bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #3051

Summary

Creating a random expiring authentication key with a seconds_valid that overflows the clock no longer panics. key::generate_key returned the key and unwrapped the clock addition, so POST /api/v1/keys (random key) and POST /api/v1/key/{seconds} with 18446744073709551615 dropped the connection and logged a panic at key/mod.rs:111. They now answer 400 "invalid auth key duration", as the pre-generated key path already did. The design is the one the maintainer decided on the spec PR (#3054): fix at the seam, with a dedicated key::DurationOverflow type converted into PeerKeyError::DurationOverflow.

Breaking public API change (torrust-tracker-core, allowed before 4.0.0)

  • authentication::key::generate_key(lifetime) -> Result<PeerKey, key::DurationOverflow> (was PeerKey).
  • KeysHandler::generate_expiring_peer_key(lifetime) -> Result<PeerKey, PeerKeyError> (was Result<PeerKey, databases::error::Error>); the pub(crate) generate_permanent_peer_key changes the same way.
  • New key::DurationOverflow { seconds_valid: u64 } and impl From<DurationOverflow> for PeerKeyError.

All callers in the workspace are updated: tracker-core, http-core tests, the REST adapter, the REST handler and the persistence benchmark binary.

Files

  • packages/tracker-core/src/authentication/key/mod.rs, handler.rs and error.rs: the fix and its unit tests.
  • packages/rest-api-runtime-adapter/src/v1/adapters/auth_key.rs: the generate-key adapter reuses map_peer_key_error.
  • packages/axum-rest-api-server/src/v1/context/auth_key/handlers.rs and its contract tests: a DurationOverflow arm in generate_auth_key_handler; the existing test of the other errors is renamed.
  • packages/http-core (tests) and packages/persistence-benchmark: callers.
  • docs/issues/open/3051-random-expiring-key-duration-overflow-panic/: spec progress, manual-verification-evidence.md (red before the fix, green after, real-tracker recheck) and test-design-review.md.

Validation

  • The regression tests were committed first and failed for the bug (evidence V2b); they pass with the fix (V2c). The new generate_key unit test fails when the old unwrap() is restored.
  • linter all exits 0; the tests of tracker-core, axum-rest-api-server, http-core, axum-http-server, rest-api-runtime-adapter and persistence-benchmark pass, and so do the workspace doc tests.
  • Real tracker recheck (V3): requests 2 and 4 answer 400 instead of an empty reply, the control answers 200, and the log holds no panic.
  • Not changed: an expiry above i64::MAX seconds that still fits the clock returns a 500 from the stores, tracked in Key duration above i64::MAX seconds returns 500 instead of a duration error #3055; PeerKeyError is not split or renamed.

Summary by CodeRabbit

  • Bug Fixes

    • Expiring-key requests with durations beyond the supported range now return a clear invalid-duration error instead of triggering a panic.
    • This validation applies to both current and deprecated key-generation endpoints, including requests to add randomly generated keys.
    • Permanent key generation remains unaffected.
  • Tests

    • Added regression coverage for duration overflow handling and API responses, including verification that the tracker records no panic.

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Key generation now returns a duration-overflow error instead of panicking. Tracker and REST layers propagate that error, and REST endpoints return a bad-request response for overflowing durations.

Changes: Authentication key duration overflow handling

Layer / File(s) Summary
Key generation contract and call-site updates
packages/tracker-core/src/authentication/key/mod.rs, packages/http-core/src/container.rs, packages/http-core/src/services/announce.rs, packages/http-core/src/services/scrape.rs, packages/persistence-benchmark/.../operations/keys.rs
generate_key returns a Result and reports lifetime overflow with DurationOverflow. Key-generation callers and tests now handle the result.
Tracker error propagation
packages/tracker-core/src/error.rs, packages/tracker-core/src/authentication/handler.rs, packages/rest-api-runtime-adapter/src/v1/adapters/auth_key.rs
Tracker methods preserve generation errors. Database-add failures are mapped to PeerKeyError::DatabaseError.
REST response and verification
packages/axum-rest-api-server/src/v1/context/auth_key/handlers.rs, packages/axum-rest-api-server/tests/server/v1/contract/context/auth_key.rs, docs/issues/open/3051-random-expiring-key-duration-overflow-panic/*
REST handlers map duration overflow to the invalid-duration response. Tests cover both endpoints. Issue records include test-design and verification results.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AuthKeyHandler
  participant TrackerAuthKeyAdapter
  participant KeysHandler
  participant KeyGenerator
  Client->>AuthKeyHandler: Submit key request with duration
  AuthKeyHandler->>TrackerAuthKeyAdapter: Generate key
  TrackerAuthKeyAdapter->>KeysHandler: Add random key
  KeysHandler->>KeyGenerator: Generate key with lifetime
  KeyGenerator-->>KeysHandler: Return DurationOverflow
  KeysHandler-->>TrackerAuthKeyAdapter: Propagate PeerKeyError
  TrackerAuthKeyAdapter-->>AuthKeyHandler: Map peer-key error
  AuthKeyHandler-->>Client: Return invalid-duration response
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers: josecelano, da2ce7

Merge Risk: Minimal · up to ff5ae

Random expiring key requests with an overflowing duration now return a 400 error instead of panicking. The change is covered by tests at several layers and no merge-blocking risk was found. The public API change in tracker-core is intentional and allowed before 4.0.0.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: random expiring key generation now returns an error when the requested duration overflows the clock, instead of panicking. It also names the affected crate (tracker-co…
Linked Issues check Passed Issue #3051 is the only directly linked active issue, so its coding requirements apply. (1) key::generate_key now returns Result<PeerKey, key::DurationOverflow>. The overflow path returns an error…
Out of Scope Changes check Passed All changed areas connect to #3051. The generate_key signature change, the DurationOverflow type, and the PeerKeyError conversion implement the seam fix. The REST adapter, the handler arm, and t…
Full details: Title check

Explanation

The title names the main change: random expiring key generation now returns an error when the requested duration overflows the clock, instead of panicking. It also names the affected crate (tracker-core) and the issue number. The title matches the changeset summary, the PR objectives, and the linked issue #3051.

Full details: Linked Issues check

Explanation

Issue #3051 is the only directly linked active issue, so its coding requirements apply. (1) key::generate_key now returns Result&lt;PeerKey, key::DurationOverflow&gt;. The overflow path returns an error instead of calling unwrap() on the clock addition, so the panic is removed. This matches the issue decision. (2) key::DurationOverflow { seconds_valid: u64 } is a new public type, as the issue requires. (3) KeysHandler::generate_expiring_peer_key and generate_permanent_peer_key return Result&lt;PeerKey, PeerKeyError&gt;. From&lt;DurationOverflow&gt; for PeerKeyError is added in tracker-core/src/error.rs. (4) generate_auth_key_handler in the axum REST server maps AuthKeyError::DurationOverflow to invalid_auth_key_duration_response (HTTP 400). The REST adapter generate_key path maps the error through map_peer_key_error, which preserves the overflow variant. (5) Unit tests cover the overflow case in key/mod.rs, the handler, and the contract tests for POST /api/v1/keys and the generate-key endpoint. The issue's coding requirements are implemented in the reviewed code. The real-tracker recheck and the test runs are author-reported. I did not rerun them.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to #3051. The generate_key signature change, the DurationOverflow type, and the PeerKeyError conversion implement the seam fix. The REST adapter, the handler arm, and the contract tests implement the 400 mapping on both endpoints. The unwrap() edits in http-core test helpers and the error propagation in persistence-benchmark are caller updates required by the new return type. The docs/issues/open/3051-... files record the process evidence and add no runtime behavior. The previous concern about manual path parsing in generate_auth_key_handler is resolved. The base-to-head diff of handlers.rs shows only the new DurationOverflow arm, its new test, and the test rename. The parse::&lt;u64&gt;() path handling is unchanged from the merge base, so it is not part of this PR's changes. No unrelated change was found.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • 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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0934ea6f-4242-455f-93d1-37dfba01613c
Commits

Reviewing files that changed from the base of the PR and between 40a1ae0 and ff5ae2c.

Files selected for processing: 3

  • docs/issues/open/3051-random-expiring-key-duration-overflow-panic/manual-verification-evidence.md
  • packages/tracker-core/src/authentication/handler.rs
  • packages/tracker-core/src/authentication/key/mod.rs
Files skipped from review as they are similar to previous changes: 1

  • docs/issues/open/3051-random-expiring-key-duration-overflow-panic/manual-verification-evidence.md

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

josecelano-bot and others added 5 commits November 25, 2026 19:21
…he random key duration overflow

Four tests fail for the reported bug: a KeysHandler test, a
generate_auth_key_handler test and two REST contract tests. The red
runs are recorded in the evidence file (V2b). No production change yet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…uration overflows the clock

key::generate_key returns Result<PeerKey, key::DurationOverflow> instead of
unwrapping the clock addition, so an overflowing seconds_valid no longer
panics. KeysHandler::generate_expiring_peer_key and the pub(crate)
generate_permanent_peer_key return PeerKeyError, with a From conversion
from DurationOverflow. The REST generate-key adapter reuses
map_peer_key_error and generate_auth_key_handler answers 400 for an
overflow, like the add-key endpoint.

Breaking public API (allowed before tracker-core 4.0.0): generate_key and
generate_expiring_peer_key change their return type.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…e_key returning a Result

The tests added by torrust#3056 call generate_key, whose return type changes in
this branch. The evidence notes the rerun after the rebase.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@josecelano-bot
josecelano-bot force-pushed the 3051-random-expiring-key-duration-overflow-panic branch from 40a1ae0 to ff5ae2c Compare November 25, 2026 19:26
@josecelano josecelano self-assigned this Nov 25, 2026
@josecelano
josecelano requested a review from da2ce7 November 25, 2026 19:29
@josecelano

Copy link
Copy Markdown
Member

ACK ff5ae2c

@da2ce7 da2ce7 left a comment

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.

Reviewed at ff5ae2c4ca9235296774fe47e9abdf25b3752cb0. Recomputed from the bytes at this head, against the merge base 082ad2452; git merge-tree against develop a94c3ced8 writes a clean tree: develop gained only documentation and agent-tooling changes since the merge base, none in a file this change touches.

Process: a bug fix, governed by fix-bug (red then green regression tests, a real-tracker recheck after the last production change, commits cited by subject), write-unit-test (test-design-review.md) and commit-changes with open-pull-request. The spec from #3054 is an ancestor of the merge base.

The change against its claim: generate_key returns Result<PeerKey, DurationOverflow> instead of unwrapping now_add; generate_expiring_peer_key and generate_permanent_peer_key return PeerKeyError, with database failures mapped as before; the adapter's generate path reuses map_peer_key_error, whose Database text is unchanged; the deprecated handler answers the add endpoint's 400 body. Every caller in the workspace is updated or already unwraps. Recomputed: the merge-base panic site is key/mod.rs:111:79, the unwrap(); the control key's valid_until 1795637631 is 19:13:51 UTC plus 3600 s; the changes from #3056 sit in test modules only, so the claim that the rebase left the production code unchanged holds. With the fix reverted, the contract tests and the handler test fail.

Consistency: no links added; the in-folder issue-spec keys match the clarification now on develop; no dictionary words added; nothing moved or renamed.

Hygiene: Conventional subjects carry [#3051]; author equals committer on all five commits; git diff --check is clean; the commit-id check prints nothing; only the body's Closes #3051 matches the closing-keyword pattern. Each commit carries an AI attribution footer; no rule in the tree forbids it.

Findings

  • Minor: the tracker-core tests do not compile at 0e44bc9, 085687e or 5c2100e; ff5ae2c repairs them.
  • Minor: the new overflow tests depend on the stopped clock's default not being the epoch.
  • Nit: the doc comment of generate_auth_key_handler still lists only 200 and 500.

Checked, no finding: DurationOverflow's message equals PeerKeyError::DurationOverflow's; the doctest overflows under the working clock; the benchmark callers; the renamed handler test; the spec checkboxes and AC table against the evidence; frontmatter.

Checks

On the loop's compute node at this head, against the merge base 082ad2452: the repository's pre-commit gate and lint roster exit 0; cargo test --workspace passes 4860 tests with 0 failed and 5 ignored across 140 binaries with default features; and cargo clippy --workspace --all-targets --all-features -- -D warnings exits 0 (2026-11-26). Checked against the bytes at posting: the doc comment of generate_auth_key_handler (lines 53 to 58) still lists only the 200 and 500 responses. The head was confirmed with git ls-remote before posting. GitHub checks at this head at posting time: "Publish (Development): completed/skipped; Publish (Release): completed/skipped; Context: completed/success; Package Coverage Regression: completed/success; Package Coverage (torrust-tracker-persistence-benchmark): completed/success; Package Coverage (torrust-tracker-http-core): completed/success; Package Coverage (torrust-tracker-core): completed/success; Package Coverage (torrust-tracker-rest-api-runtime-adapter): completed/success; Package Coverage (torrust-tracker-axum-rest-api-server): completed/success; Docker E2E: completed/skipped; Layer Boundary Bans: completed/success; Source Locations: completed/success; Unit (nightly): completed/success; Unit (stable): completed/success; Documented Clippy Allows: completed/success; Workspace Packaging: completed/success; Shipped Features: completed/success; Docs Lint: completed/success; Build on macos-latest (stable): completed/success; Build on ubuntu-latest (nightly): completed/success; Build on windows-latest (nightly): completed/success; Build on windows-latest (stable): completed/success; Build on ubuntu-latest (stable): completed/success; Build on macos-latest (nightly): completed/success; Test (Docker) (release): completed/success; Database Compatibility PostgreSQL (16): completed/success; Database Compatibility PostgreSQL (14): completed/success; Database Compatibility MySQL (8.0): completed/success; Database Compatibility PostgreSQL (15): completed/success; Database Compatibility PostgreSQL (17): completed/success; Database Compatibility MySQL (8.4): completed/success; Persistence Benchmark PostgreSQL: completed/success; Persistence Benchmark MySQL: completed/success; Persistence Benchmark SQLite3: completed/success; Generate Coverage Report: completed/success; Discover Package Coverage: completed/success; CodeRabbit: completed/success". At posting, develop is b32179f23.

async fn it_should_keep_the_key_in_memory_when_removing_it_from_the_database_fails() {
// Arrange
let peer_key = generate_key(None);
let peer_key = generate_key(None).unwrap();

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] The tracker-core tests do not compile at three commits of this branch.

0e44bc9 changes generate_key to return a Result. The tests that #3056 added still bind its value as a PeerKey at 0e44bc9, 085687e and 5c2100e: here, at lines 850, 880 and 881, and at key/mod.rs lines 419 and 456. This commit repairs them. AGENTS.md requires linter all to pass before every commit, and the merge keeps the branch's commits, so a bisect on develop would stop on a build error at those three commits. Moving the caller update into the fix commit during the rebase that brought in #3056 keeps every change and leaves each commit buildable. If the history stays as it is, a line in the PR body saying so would help a later reader.


#[test]
fn it_should_return_an_error_with_the_requested_seconds_instead_of_panicking() {
let result = generate_key(Some(Duration::from_secs(u64::MAX)));

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] This test arranges no clock, yet the overflow it asserts depends on the clock.

u64::MAX seconds overflow only when the current time is past the epoch: Duration::ZERO plus Duration::from_secs(u64::MAX) fits, so at a zero clock generate_key returns Ok and unwrap_err panics. The test passes because the stopped clock's default in this crate's tests is not the epoch, as the recorded red run's panic at now_add shows. The write-unit-test skill states that Stopped::now() defaults to Duration::ZERO, so a reader following it would expect this test to fail. The same holds for the new KeysHandler test at handler.rs:418, which at a zero clock would reach the store instead. test-design-review.md:15 calls u64::MAX seconds a lifetime "which no clock can add", but a clock at the epoch can. Pinning the clock first, as it_should_generate_a_key_that_expires_at_now_plus_its_lifetime does with clock::Stopped::local_set(&Duration::from_secs(1_000)), makes the causal state visible and the test independent of the default.

};
match auth_key_service.generate_key(seconds_valid).await {
Ok(auth_key) => auth_key_response(&auth_key),
Err(AuthKeyError::DurationOverflow { seconds_valid }) => invalid_auth_key_duration_response(seconds_valid),

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] The doc comment of generate_auth_key_handler no longer lists every response.

With this arm the deprecated endpoint answers 400 for an overflowing duration, but the comment (lines 53 to 58) still says it returns two types of responses, 200 and 500. The 400 for a segment that is not a number was already missing. Listing the 400 cases, as the comment of add_auth_key_handler does, would keep it accurate.

@da2ce7

da2ce7 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

ACK ff5ae2c — verified that a random key whose duration overflows the clock now returns DurationOverflow and a 400 on both REST endpoints, with every caller updated and the merge into develop clean.

@josecelano
josecelano merged commit d581356 into torrust:develop Nov 26, 2026
37 checks passed
josecelano added a commit that referenced this pull request Nov 26, 2026
…ssues/closed

0ac4829 docs(pr-reviews): [#3051] record the replies to review 6079505913 in the PR 3072 audit (josecelano-bot)
70a3f89 docs(pr-reviews): [#3051] record review 6079505913 in the PR 3072 audit (josecelano-bot)
0196ad3 docs(pr-reviews): [#3051] record the replies to review 6078748782 in the PR 3072 audit (josecelano-bot)
828414b docs(pr-reviews): [#3051] record review 6078748782 in the PR 3072 audit (josecelano-bot)
4a84d47 docs(issues): [#3051] leave the remaining criteria for a reviewer to tick (josecelano-bot)
9a1b9aa docs(pr-reviews): [#3051] record the replies to review 6077711472 in the PR 3072 audit (josecelano-bot)
ac62b23 docs(pr-reviews): [#3051] record review 6077711472 in the PR 3072 audit (josecelano-bot)
157aff7 docs(issues): [#3051] leave the acceptance criteria for a reviewer to tick (josecelano-bot)
119ee6b docs(pr-reviews): [#3051] record the replies to review 6075748165 in the PR 3072 audit (josecelano-bot)
65f43b0 docs(pr-reviews): [#3051] add the PR 3072 review audit (josecelano-bot)
eb5671e docs(issues): [#3051] make the archived spec agree with its record (josecelano-bot)
6a6fbb9 chore(issues): archive closed issue #3051 spec to docs/issues/closed (josecelano-bot)

Pull request description:

  Related to #3051

  ## Summary

  Archives the spec of issue #3051, which is closed: its spec PR (#3054) and fix PR (#3064) are merged. The folder moves from `docs/issues/open/` to `docs/issues/closed/` as the `cleanup-completed-issues` skill describes. The ISSUE.md frontmatter now has `status: done`, the new `spec-path` and `related-pr: 3064`; the checkpoints the merged work satisfies are ticked and the progress log records the archival. The branch also carries the audit record of the reviews of this pull request.

  ## Files

  - `docs/issues/closed/3051-random-expiring-key-duration-overflow-panic/` (moved from `open/`: `ISSUE.md`, `manual-verification-evidence.md`, `test-design-review.md`, `evidence/`).
  - `docs/pr-reviews/pr-3072-review/PR-REVIEW.md` (the audit record of the reviews of this pull request).

  ## Validation

  `linter markdown` and `linter cspell` pass, `git diff --cached --check` is clean, and a search for the folder name finds no live reference to the old path (the PR 3054 audit record keeps the path that existed at the time). No code is changed. The checkpoint "Reviewer validated acceptance criteria" is left unticked on purpose.

ACKs for top commit:
  da2ce7:
    ACK 0ac4829 — the #3051 spec archived to docs/issues/closed with its references repaired, and an audit record that answers every review finding and passes its validator
  josecelano:
    ACK 0ac4829

Tree-SHA512: a8367619601e0db1162b6b85c85d92535fd90bd10b26623abee55aee6f7cd71c2abffa2a701846d7769e9d4d0f9a3b035b8bb71c9fa1766cf01a2b43b3f8ba2c

This branch was previously deployed

1 inactive deployment
coverage — ff5ae2c4 Deployed Nov 25, 2026 by josecelano-bot via Generate Coverage Report #3558
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.

Panic when a random expiring authentication key duration overflows the clock

3 participants