Skip to content

v4.2.14#85

Merged
Power2All merged 4 commits into
masterfrom
v4.2.14
Jun 7, 2026
Merged

v4.2.14#85
Power2All merged 4 commits into
masterfrom
v4.2.14

Conversation

@Power2All

@Power2All Power2All commented Jun 7, 2026

Copy link
Copy Markdown
Owner
  • Hotfix in regard to database handling
  • A full audit and security scan of the code, shown some possible vulnerabilities
  • Small little performance tweaks
  • Adding a better token usage by recommending a header bearer, legacy still works

Summary by CodeRabbit

  • New Features

    • API Authentication now accepts Authorization header with Bearer token (preferred) alongside legacy token query parameter
    • Database commit chunk size configurable via DATABASE__CHUNK_SIZE env var
  • Bug Fixes

    • Enforced size limits on RTC-related fields and capped number of info_hash entries in scrape requests
  • Documentation

    • Added docs for API authentication, database chunking, and updated changelog
  • Chores

    • Version bumped to 4.2.14; removed unused async-std dependency

Power2All added 3 commits June 7, 2026 01:42
* A full audit and security scan of the code, shown some possible vulnerabilities
* Small little performance tweaks
* Adding a better token usage by recommending a header bearer, legacy still works
@Power2All Power2All self-assigned this Jun 7, 2026
@Power2All Power2All added bug Something isn't working enhancement New feature or request labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1020938b-ce78-444a-8172-1d4b5170acc1

📥 Commits

Reviewing files that changed from the base of the PR and between 621e405 and 2040d53.

📒 Files selected for processing (2)
  • src/api/api.rs
  • src/http/http.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/http/http.rs
  • src/api/api.rs

📝 Walkthrough

Walkthrough

Version 4.2.14: bump manifests, remove async-std and migrate sleeps/timeouts to tokio; centralize API token extraction (Authorization header Bearer, fallback token query); add configurable database transaction chunking; tighten announce/scrape validation and update docs.

Changes

Release v4.2.14

Layer / File(s) Summary
Version updates and dependency cleanup
Cargo.toml, docker/Dockerfile, docker/build.bat, torrust-actix.desktop
Version bumped to 4.2.14 and async-std = "1.13.2" removed.
async-std → tokio migration
src/main.rs, src/common/common.rs
Replaced async-std sleep/timeout calls with tokio::time equivalents and removed async-std imports.
API token extraction refactor
src/api/api.rs
Added api_extract_token() (Authorization Bearer header or token query fallback); api_service_token now accepts &HttpRequest and extracts token internally; CORS allows Authorization.
Update API handlers for centralized auth
src/api/* modules
Removed per-handler QueryToken parsing and call api_service_token(&request, config) across blacklist, certificate, key, stats, torrent, user, and whitelist endpoints.
Database chunk_size config
src/config/*
Add DatabaseConfig.chunk_size with serde default, default_chunk_size() helper, set default in Configuration::init(), and support DATABASE__CHUNK_SIZE env override.
MySQL chunked commits
src/database/impls/database_connector_mysql.rs
save_torrents/save_users now perform periodic commits via new commit_chunk helper and chunk counter.
Postgres chunked commits
src/database/impls/database_connector_pgsql.rs
Add per-iteration chunking and async commit_chunk helper to rotate/commit transactions.
SQLite chunked commits
src/database/impls/database_connector_sqlite.rs
Introduce commit_chunk helper and per-loop chunking for save_torrents/save_users.
HTTP and tracker validation
src/http/http.rs, src/tracker/impls/torrent_tracker_handlers.rs, src/websocket/websocket.rs
http_service_check_user_key_validation returns Result<UserId, HttpResponse>; RTC field size limits and scrape hash count cap added; handle_scrape accepts borrowed reference and callers updated.
Documentation and release notes
README.md
Document DATABASE__CHUNK_SIZE, Database commit chunk size, API Authentication, add changelog v4.2.14 entry, and typo fixes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through headers, tokens in paw,

Bearer first, query next—no flaw,
Async-std gone, tokio takes the lead,
Commits in chunks for steadier speed,
A rabbit cheers v4.2.14 with a gnaw! 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.28% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'v4.2.14' is a version string only and does not describe the actual changes or improvements made in the pull request. Replace the title with a clear, descriptive summary of the main changes, such as 'Improve API token handling and add database chunking' or 'Security audit fixes and token authentication improvements'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch v4.2.14

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Actionable comments posted: 3

🧹 Nitpick comments (6)
README.md (5)

88-88: ⚡ Quick win

Improve the phrasing to avoid repetition.

The phrase "using --help argument for using in your environment" repeats "using" awkwardly. Consider rephrasing for clarity.

✍️ Suggested rephrasing
-Run the code using `--help` argument for using in your environment:
+Run the code with the `--help` argument to see all available options:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` at line 88, The sentence in README.md repeats "using" awkwardly;
replace "Run the code using `--help` argument for using in your environment:"
with a clearer phrasing such as "Run the code with the `--help` flag to see
usage for your environment:" to remove duplication and improve readability.

277-277: ⚡ Quick win

Remove extra spaces inside the code span.

The code span has unnecessary spaces around the text.

🔧 Suggested fix
-   The `Bearer ` prefix is optional; a bare `Authorization: <api_key>` is also accepted.
+   The `Bearer` prefix is optional; a bare `Authorization: <api_key>` is also accepted.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` at line 277, Remove the extra spaces inside the inline code span
so the text reads exactly `Bearer` (no trailing space) in the clause that
currently shows `Bearer `; update the code span around the Authorization header
to be precise (e.g., keep `Authorization: <api_key>` as-is) so the sentence
becomes "The `Bearer` prefix is optional; a bare `Authorization: <api_key>` is
also accepted."

Source: Linters/SAST tools


613-618: ⚡ Quick win

Improve changelog phrasing and grammar.

The changelog entry has several minor issues:

  • "in regard to" is wordy (use "regarding" or "for")
  • "shown some possible vulnerabilities" is grammatically awkward (use "identified")
  • "Small little" is redundant (use "Small" or "Minor")
  • "header bearer" should be "Bearer header" (proper HTTP terminology)
✍️ Suggested improvements
 #### v4.2.14
-* Hotfix in regard to database handling
-* A full audit and security scan of the code, shown some possible vulnerabilities
-* Small little performance tweaks
-* Adding a better token usage by recommending a header bearer, legacy still works
+* Hotfix for database handling
+* Full audit and security scan of the code identified some possible vulnerabilities
+* Minor performance tweaks
+* Improved token usage by recommending an Authorization Bearer header; legacy token parameter still supported
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 613 - 618, Revise the v4.2.14 changelog entry
(heading "#### v4.2.14") to improve phrasing: replace "Hotfix in regard to
database handling" with "Hotfix regarding database handling" or "Hotfix for
database handling", change "A full audit and security scan of the code, shown
some possible vulnerabilities" to "A full audit and security scan of the code
identified some potential vulnerabilities", change "Small little performance
tweaks" to "Minor performance tweaks", and change "Adding a better token usage
by recommending a header bearer, legacy still works" to "Recommend using the
Bearer header for token usage (legacy method still supported)" so the grammar
and HTTP terminology are correct.

Source: Linters/SAST tools


273-276: ⚡ Quick win

Specify language for the fenced code block.

The fenced code block should have a language identifier for proper syntax highlighting.

📝 Suggested fix
-   ```
+   ```http
    Authorization: Bearer <api_key>
    ```
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 273 - 276, The fenced code block containing the
Authorization header lacks a language specifier; update the triple-backtick
fence for the block that includes "Authorization: Bearer <api_key>" to include a
language identifier (e.g., http) so the snippet is rendered with proper syntax
highlighting.

Source: Linters/SAST tools


281-283: ⚡ Quick win

Specify language for the fenced code block.

The fenced code block should have a language identifier for proper syntax highlighting.

📝 Suggested fix
-   ```
+   ```http
    GET /api/torrents?token=<api_key>
    ```
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 281 - 283, The fenced code block showing the API
request lacks a language identifier for syntax highlighting; update the block
around the GET /api/torrents?token=<api_key> example by adding an appropriate
language tag (e.g., use "http" or "bash") after the opening backticks so it
reads like ```http and preserves the existing contents and formatting of the
request line.

Source: Linters/SAST tools

src/api/api.rs (1)

294-298: 💤 Low value

Consider case-insensitive Bearer prefix handling.

Per RFC 7235, auth-scheme tokens are case-insensitive. The current implementation only handles "Bearer " and "bearer ", so "BEARER " or mixed-case variants would be treated as bare tokens. Given the README states the prefix is optional, this works but could cause minor confusion.

Optional: Use case-insensitive prefix stripping
     if let Some(value) = request.headers().get(http::header::AUTHORIZATION).and_then(|h| h.to_str().ok()) {
-        let token = value
-            .strip_prefix("Bearer ")
-            .or_else(|| value.strip_prefix("bearer "))
-            .unwrap_or(value)
-            .trim();
+        let token = if value.len() >= 7 && value[..7].eq_ignore_ascii_case("bearer ") {
+            &value[7..]
+        } else {
+            value
+        }.trim();
         if !token.is_empty() {
             return Some(token.to_string());
         }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/api.rs` around lines 294 - 298, The current Authorization header
handling (request.headers().get(http::header::AUTHORIZATION) ... ) only strips
"Bearer " and "bearer " prefixes, missing other case variants; make the
Bearer-prefix stripping case-insensitive by comparing the header value's leading
scheme in a case-insensitive way (e.g., examine the first N chars via
to_ascii_lowercase or use a case-insensitive starts_with) and then strip that
prefix before assigning token so token contains the raw credential regardless of
"Bearer" casing while preserving existing behavior when no prefix is present.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/api.rs`:
- Around line 292-307: The CORS setup is missing the Authorization header so
browser clients fail preflight; update the api_service_cors() CORS builder to
allow the Authorization header by adding http::header::AUTHORIZATION via
allowed_header(...) (and, if present, ensure credentials/expose_headers settings
remain correct) so api_extract_token can receive Bearer tokens from cross-origin
requests; locate api_service_cors and add
allowed_header(http::header::AUTHORIZATION) to its configuration.

In `@src/http/http.rs`:
- Around line 281-287: When tracker_config.users_enabled is true and a user_key
is present in the path, do not silently fall through on validation failure: call
http_service_check_user_key_validation(path.clone().1) and if it returns Err
(invalid key) return an appropriate HTTP error response instead of calling
http_service_announce_handler with None; only call http_service_announce_handler
with Some(user_id) on Ok(user_id) and with None when no user_key was supplied at
all. Update the logic around tracker_config.users_enabled, path,
http_service_check_user_key_validation, and http_service_announce_handler to
short-circuit and return the error when validation fails.
- Around line 254-260: The current code calls
http_service_check_user_key_validation(...) and discards Err(HttpResponse),
causing invalid user keys to fall through; change the logic to match the Result
returned: when tracker_config.users_enabled && !tracker_config.keys_enabled call
http_service_check_user_key_validation(...).await and if it returns Ok(user_id)
call and return http_service_announce_handler(..., Some(user_id), ...).await,
but if it returns Err(resp) immediately return that HttpResponse; otherwise (no
user check) continue to call http_service_announce_handler(..., None,
...).await. Ensure you use the same function names
(http_service_check_user_key_validation and http_service_announce_handler) and
preserve awaits.

---

Nitpick comments:
In `@README.md`:
- Line 88: The sentence in README.md repeats "using" awkwardly; replace "Run the
code using `--help` argument for using in your environment:" with a clearer
phrasing such as "Run the code with the `--help` flag to see usage for your
environment:" to remove duplication and improve readability.
- Line 277: Remove the extra spaces inside the inline code span so the text
reads exactly `Bearer` (no trailing space) in the clause that currently shows
`Bearer `; update the code span around the Authorization header to be precise
(e.g., keep `Authorization: <api_key>` as-is) so the sentence becomes "The
`Bearer` prefix is optional; a bare `Authorization: <api_key>` is also
accepted."
- Around line 613-618: Revise the v4.2.14 changelog entry (heading "####
v4.2.14") to improve phrasing: replace "Hotfix in regard to database handling"
with "Hotfix regarding database handling" or "Hotfix for database handling",
change "A full audit and security scan of the code, shown some possible
vulnerabilities" to "A full audit and security scan of the code identified some
potential vulnerabilities", change "Small little performance tweaks" to "Minor
performance tweaks", and change "Adding a better token usage by recommending a
header bearer, legacy still works" to "Recommend using the Bearer header for
token usage (legacy method still supported)" so the grammar and HTTP terminology
are correct.
- Around line 273-276: The fenced code block containing the Authorization header
lacks a language specifier; update the triple-backtick fence for the block that
includes "Authorization: Bearer <api_key>" to include a language identifier
(e.g., http) so the snippet is rendered with proper syntax highlighting.
- Around line 281-283: The fenced code block showing the API request lacks a
language identifier for syntax highlighting; update the block around the GET
/api/torrents?token=<api_key> example by adding an appropriate language tag
(e.g., use "http" or "bash") after the opening backticks so it reads like
```http and preserves the existing contents and formatting of the request line.

In `@src/api/api.rs`:
- Around line 294-298: The current Authorization header handling
(request.headers().get(http::header::AUTHORIZATION) ... ) only strips "Bearer "
and "bearer " prefixes, missing other case variants; make the Bearer-prefix
stripping case-insensitive by comparing the header value's leading scheme in a
case-insensitive way (e.g., examine the first N chars via to_ascii_lowercase or
use a case-insensitive starts_with) and then strip that prefix before assigning
token so token contains the raw credential regardless of "Bearer" casing while
preserving existing behavior when no prefix is present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9750ff93-e20c-4822-9276-4e4ce9197419

📥 Commits

Reviewing files that changed from the base of the PR and between e27eea1 and 621e405.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (24)
  • Cargo.toml
  • README.md
  • docker/Dockerfile
  • docker/build.bat
  • src/api/api.rs
  • src/api/api_blacklists.rs
  • src/api/api_certificate.rs
  • src/api/api_keys.rs
  • src/api/api_stats.rs
  • src/api/api_torrents.rs
  • src/api/api_users.rs
  • src/api/api_whitelists.rs
  • src/common/common.rs
  • src/config/config.rs
  • src/config/impls/configuration.rs
  • src/config/structs/database_config.rs
  • src/database/impls/database_connector_mysql.rs
  • src/database/impls/database_connector_pgsql.rs
  • src/database/impls/database_connector_sqlite.rs
  • src/http/http.rs
  • src/main.rs
  • src/tracker/impls/torrent_tracker_handlers.rs
  • src/websocket/websocket.rs
  • torrust-actix.desktop

Comment thread src/api/api.rs
Comment thread src/http/http.rs
Comment thread src/http/http.rs
@Power2All Power2All merged commit e1ce34e into master Jun 7, 2026
2 checks passed
@Power2All Power2All deleted the v4.2.14 branch June 7, 2026 18:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant