Skip to content

Conversation

@dani-garcia
Copy link
Member

@dani-garcia dani-garcia commented Jan 19, 2026

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-29492

📔 Objective

Add support for API middleware for the autogenerated API crates. This would allow us to add middlewares that inspect and modify the request and response, or that retry the requests. It seems very flexible and I think it should cover all our use cases. Note that the version of reqwest-middleware is not the latest, as it needs to match with a specific reqwest version, and the next major reqwest version requires some rework around rustls-platform-verifier.

Note that this is doesn't add any middleware yet, but here's an example of how one would look:

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl reqwest_middleware::Middleware for MiddlewareTest {
    async fn handle(&self, mut req: Request, _: &mut Extensions, next: Next<'_>) -> Result<Response> {
        // We can dynamically insert headers to all the requests here
        // For example, the generated code could notify us that some 
        // requests need auth so we can inject the correct token.
        if req.extensions().get::<RequiresAuth>().is_some() {
            req.headers_mut().insert(header::AUTHORIZATION, self.get_token().await);
        }

        // We can implement retry logic here as well
        let mut response = loop {
            // This example retry loop will retry any requests that have an expired token from the 
            // load balancer in front of the server. Note that not all requests are cloneable, like
            //  when they have a streamed body. Those should be a very small minority of requests, 
            // so in that case we just don't retry those.
            if self.should_send_load_balancer_token().await && let Some(req) = req.try_clone() {
                let response = next.clone().run(req, extensions).await?;

                if response.status().is_redirection() {
                    self.refresh_load_balancer_token().await?;
                    continue;
                }
                break response;
            } else {
                break next.run(req, extensions).await?
            }
        };

        // We can also modify the response before returning it
        response.headers_mut().insert("X-Custom-Response-Header", HeaderValue::from_static("Value"));

        Ok(response)
    }
}

🚨 Breaking Changes

⏰ Reminders before review

  • Contributor guidelines followed
  • All formatters and local linters executed and passed
  • Written new unit and / or integration tests where applicable
  • Protected functional changes with optionality (feature flags)
  • Used internationalization (i18n) for all UI strings
  • CI builds passed
  • Communicated to DevOps any deployment requirements
  • Updated any necessary documentation (Confluence, contributing docs) or informed the documentation
    team

🦮 Reviewer guidelines

  • 👍 (:+1:) or similar for great changes
  • 📝 (:memo:) or ℹ️ (:information_source:) for notes or general info
  • ❓ (:question:) for questions
  • 🤔 (:thinking:) or 💭 (:thought_balloon:) for more open inquiry that's not quite a confirmed
    issue and could potentially benefit from discussion
  • 🎨 (:art:) for suggestions / improvements
  • ❌ (:x:) or ⚠️ (:warning:) for more significant problems or concerns needing attention
  • 🌱 (:seedling:) or ♻️ (:recycle:) for future improvements or indications of technical debt
  • ⛏ (:pick:) for minor or nitpick changes

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Logo
Checkmarx One – Scan Summary & Detailsb24a5404-53fd-48d5-90d5-176150707752

Great job! No new security vulnerabilities introduced in this pull request

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

🔍 SDK Breaking Change Detection Results

SDK Version: ps/PM-29492-api-middleware-support (4ac30a8)
Completed: 2026-01-20 18:23:10 UTC
Total Time: 215s

Client Status Details
typescript ✅ No breaking changes detected TypeScript compilation passed with new SDK version - View Details

Breaking change detection completed. View SDK workflow

@codecov
Copy link

codecov bot commented Jan 19, 2026

Codecov Report

❌ Patch coverage is 42.85714% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.40%. Comparing base (c830ffa) to head (4ac30a8).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...rden-auth/src/send_access/access_token_response.rs 0.00% 3 Missing ⚠️
crates/bitwarden-core/src/error.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #699   +/-   ##
=======================================
  Coverage   79.40%   79.40%           
=======================================
  Files         293      293           
  Lines       32390    32395    +5     
=======================================
+ Hits        25718    25722    +4     
- Misses       6672     6673    +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dani-garcia dani-garcia marked this pull request as ready for review January 19, 2026 16:53
@dani-garcia dani-garcia requested review from a team as code owners January 19, 2026 16:53
quexten
quexten previously approved these changes Jan 19, 2026
Copy link
Contributor

@quexten quexten left a comment

Choose a reason for hiding this comment

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

Approving for KM-owned code.

coroiu
coroiu previously approved these changes Jan 20, 2026
Copy link
Contributor

@coroiu coroiu left a comment

Choose a reason for hiding this comment

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

Nice to see that we were able to use an existing solution!

@dani-garcia dani-garcia dismissed stale reviews from quexten and coroiu via 4ac30a8 January 20, 2026 18:12
@dani-garcia
Copy link
Member Author

Had to fix conflicts on the scripts due to #660

@dani-garcia dani-garcia requested review from coroiu and quexten January 20, 2026 18:30
@dani-garcia dani-garcia merged commit b3e4ea2 into main Jan 21, 2026
60 checks passed
@dani-garcia dani-garcia deleted the ps/PM-29492-api-middleware-support branch January 21, 2026 10:07
bw-ghapp bot pushed a commit to bitwarden/sdk-swift that referenced this pull request Jan 21, 2026
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.

4 participants