Skip to content

Conversation

@quexten
Copy link
Contributor

@quexten quexten commented Nov 12, 2025

🎟️ Tracking

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

📔 Objective

Enables tracing, but does not yet remove the old logging (follow-up). It adds tracing to the most important crypto paths. Follow-up tickets may add more tracing.

Example log output:

ERROR log{cipher_id=Some(CipherId(18c99ec6-af2b-407a-a5d0-b39201386413))}:decrypt: bitwarden_crypto::traits::decryptable: Function returned error error=The cipher's MAC doesn't match the expected value

__wbg_error_a7f8fbb0523dae15 @ bitwarden_wasm_internal_bg.js:4508
$func7041 @ 43dc2d8abaf76eb338eb.module.wasm:0x2c3395
$func3785 @ 43dc2d8abaf76eb338eb.module.wasm:0x297ed0
$func232 @ 43dc2d8abaf76eb338eb.module.wasm:0xa3c75
$func6915 @ 43dc2d8abaf76eb338eb.module.wasm:0x2c23e3
$func2456 @ 43dc2d8abaf76eb338eb.module.wasm:0x2687b1
$func817 @ 43dc2d8abaf76eb338eb.module.wasm:0x1b8e06
$func192 @ 43dc2d8abaf76eb338eb.module.wasm:0x5ce74
$func2995 @ 43dc2d8abaf76eb338eb.module.wasm:0x27f181
...

⏰ 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

@quexten quexten changed the title Km/tracing Add crypto tracing logs Nov 12, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Nov 12, 2025

Logo
Checkmarx One – Scan Summary & Detailsc329b946-6fd2-4afb-a314-d47954d06c3b

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

@quexten quexten changed the title Add crypto tracing logs [POC] Add crypto tracing logs Nov 12, 2025
@codecov
Copy link

codecov bot commented Nov 12, 2025

Codecov Report

❌ Patch coverage is 30.00000% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.53%. Comparing base (afb991b) to head (ddee1bb).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
crates/bitwarden-wasm-internal/src/init.rs 0.00% 6 Missing ⚠️
crates/bitwarden-core/src/key_management/crypto.rs 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #555      +/-   ##
==========================================
- Coverage   79.71%   79.53%   -0.18%     
==========================================
  Files         300      300              
  Lines       32238    32068     -170     
==========================================
- Hits        25697    25505     -192     
- Misses       6541     6563      +22     

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

@quexten quexten changed the title [POC] Add crypto tracing logs [POC|PM-28135] Add crypto tracing logs Nov 13, 2025
@quexten quexten marked this pull request as ready for review November 13, 2025 14:36
@quexten quexten requested review from a team as code owners November 13, 2025 14:36
@quexten quexten requested a review from a team as a code owner November 13, 2025 14:36
@quexten
Copy link
Contributor Author

quexten commented Nov 13, 2025

Note: This has some overlap with #550, as this also enables tracing. The linked PR enables tracing and removes log.

Copy link
Member

@dani-garcia dani-garcia left a comment

Choose a reason for hiding this comment

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

Looks pretty reasonable to me, just got some small comments.

@Hinton
Copy link
Member

Hinton commented Nov 13, 2025

Do we have any concerns about runtime performance? I think tracing negatively impacts performance but they have ways to indicate some should be compiled out, https://docs.rs/tracing/latest/tracing/level_filters/index.html#compile-time-filters.

(I suspect tracing performance to be a drop in the bucket for the crypto operations but I think this is a worthwhile discussion to have)

@claude
Copy link

claude bot commented Nov 13, 2025

Claude finished @quexten's task —— View job


Code Review Complete

Todo List

  • Review PR title and description quality
  • Examine git diff to understand all changes
  • Read modified files for implementation details
  • Check resolution of previous review comments
  • Identify new issues or improvements
  • Post comprehensive review feedback

Summary of Changes Since Last Review

The PR has evolved significantly with 25 commits. Recent changes include:

  • Setting release_max_level_info to prevent trace/debug logs in release builds
  • Using skip_all for #[instrument] attributes per dani-garcia's feedback
  • Adding tracing to key crypto paths including cipher decryption, user crypto initialization, and org key setup

Critical Issues

Finding 1: The WASM initialization code can panic on subsequent calls to init_sdk()

In crates/bitwarden-wasm-internal/src/init.rs:38, calling .init() on the tracing subscriber will panic if init_sdk() is called multiple times. This is problematic for WASM environments where reinitialization might occur.

tracing_subscriber::registry().with(fmt_layer).init();

Recommendation: Use try_init() instead and handle the error gracefully:

if let Err(_) = tracing_subscriber::registry().with(fmt_layer).try_init() {
    // Already initialized, which is fine
}

Good Practices Observed

  • Appropriate use of release_max_level_info to prevent debug/trace logs in production
  • Strategic placement of tracing spans at critical crypto boundaries (cipher decrypt, user crypto init)
  • Proper use of skip_all to avoid leaking sensitive parameters in logs
  • Consistent use of #[instrument(err)] to capture error paths

Suggested Improvements

Finding 2: Consider explicit `attributes` feature declaration

In Cargo.toml:79, while the attributes feature is default-enabled for tracing, explicit feature declarations are considered best practice for library crates to prevent breakage if defaults change:

tracing = { version = "0.1.41", features = ["release_max_level_info", "attributes"] }

This is a minor improvement for defensive coding.

Finding 3: The span creation pattern could be simplified

In crates/bitwarden-core/src/client/internal.rs:305 and line 171 in crypto.rs, the span creation uses:

let _span_guard = tracing::info_span!("...", ...).entered();

However, this creates two variable bindings. The .entered() method returns an Entered guard that takes ownership of the span, so you can simplify to:

let _span = tracing::info_span!("...", ...).entered();

This was actually suggested by dani-garcia in a previous review comment and appears to have been partially addressed but not in all locations.

Finding 4: Add TODO comment for temporary dual-logging system

In crates/bitwarden-wasm-internal/src/init.rs:41-44, the code maintains both tracing and the old console_log system. Adding a TODO comment would help track the migration:

// TODO(PM-28135): Remove old logging system once tracing migration is complete
let log_level = convert_level(log_level.unwrap_or(LogLevel::Info));
if let Err(_e) = console_log::init_with_level(log_level) {
    set_max_level(log_level.to_level_filter())
}

Previous Review Items

Resolved:

  • ✅ dani-garcia's suggestion to use skip_all has been addressed (commit d366d05)
  • ✅ Hinton's performance concerns addressed by setting release_max_level_info (commit ce93f3b)

Partially Resolved:

  • ⚠️ The .entered() pattern suggested by dani-garcia is used in some places but the double binding pattern still exists in others

Still Outstanding:

  • ❌ My previous comment about using try_init() in WASM initialization (Finding 1 above)
  • ❌ My previous comment about explicit attributes feature (Finding 2 above)
  • ❌ My suggestion to add a TODO comment for dual-logging (Finding 4 above)

Test Coverage

Codecov reports 30% patch coverage with 7 lines missing in the tracing initialization code. Given that this is initialization and logging infrastructure, this is acceptable. The core crypto paths being traced are well-tested through existing tests.

Security Considerations

  • ✅ No sensitive data logged (proper use of skip_all)
  • ✅ Error messages don't leak crypto material
  • ✅ Tracing fields use safe identifiers (cipher_id, org_id, user_id) not actual values

Action Items for Author

  1. Critical: Fix the panic risk in WASM init_sdk() by using try_init() (Finding 1)
  2. Optional: Add explicit attributes feature to tracing dependency (Finding 2)
  3. Optional: Simplify span guard pattern in remaining locations (Finding 3)
  4. Optional: Add TODO comment for dual-logging system (Finding 4)

Overall Assessment

This is a solid implementation of tracing infrastructure for the crypto paths. The placement of tracing spans is appropriate and follows best practices. The main concern is the WASM initialization panic risk, which should be addressed before merging.

The PR achieves its stated objective of enabling tracing without removing the old logging system, setting the stage for future migration work.

@quexten
Copy link
Contributor Author

quexten commented Nov 14, 2025

@Hinton My biggest concern would be if tracing somehow is blocking with respect to the subscribers, and we would log a lot (possibly having to go to JS every time via the hooking to console it uses), though a quick check suggests that it just appends to a buffer that then gets flushed, and actual logs should not be that frequent with the current implementation.

Is there specific things that you'd like to see measured here? Vault unlock times for large vaults? Actual logs should only be emitted for errors / rare info events, but obviously the context is still stored into a buffer somewhere.

@Hinton
Copy link
Member

Hinton commented Nov 14, 2025

@quexten Comparing calling decrypt 100'000 times with tracing to 100'000 without in a test maybe? I think it's a drop in the bucket. But I feel like it's probably not necessary to be honest.

I do think it's good to decide if we want any of the release_max_level_ enabled since they would change behaviour. And anything lower than the value would be excluded from release builds and probably safe to use in abundance.

@quexten
Copy link
Contributor Author

quexten commented Nov 17, 2025

@Hinton Okay, I've not further benchmarked it since I agree that it's most likely negligible. I've set the max log level to release_max_level_info, since I don't think anyone would expect trace / debug to be emitted in release.

In case we do want logging in an operation that gets called millions of times, we should consider using debug/trace to have it compiled out in release.

@github-actions
Copy link
Contributor

github-actions bot commented Nov 17, 2025

🔍 SDK Breaking Change Detection Results

SDK Version: km/tracing (ddee1bb)
Completed: 2025-11-17 10:11:41 UTC
Total Time: 245s

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

Breaking change detection completed. View SDK workflow

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