Skip to content

Conversation

@kubkon
Copy link
Contributor

@kubkon kubkon commented Jun 4, 2025

Mirroring tlsnotary/tlsn#817, this PR makes it possible to configure user-defined JWT claims at runtime config (from either config.toml or env vars). So instead of having the expected claims hard-coded in the binary, we are now able to define them in the config file and have the authorisation middleware validate them at runtime.

TOML

[auth.jwt]
public_key = "..."
algorithm = "rs256"

[[auth.jwt.claims]]
name = "sub"

[[auth.jwt.claims]]
name = "environment"
values = ["test"]

Env vars

$ VLAYER_AUTH__JWT__CLAIMS="sub environment:test" ./call_server

Both of the examples above yield the same end result, namely, the server:

  • expects sub claim with any values - existence check
  • expects environment with exactly one value test - precise match

TODO

Before we can merge this PR, we need to make a tweak to the gas-meter logic since now we forward the JWT token in its entirety to the gas-meter rather than extracting anything in particular from the JWT claims. This is a necessary requirement since now knowledge of required JWT claims is deferred to runtime, therefore we cannot know uprfont what to expect in the extraction logic in the prover server. As such, it seems more natural to simply forward the JWT to the gas-meter which knows what to expect and can perform any relevant claim extraction on its own:

  • accept JWT token in the gas-meter
  • extract sub claim from the input JWT

Summary by CodeRabbit

  • New Features

    • Added support for user-defined JWT claims in configuration files and environment variables.
    • New environment variable (VLAYER_AUTH__JWT__CLAIMS) allows specifying required JWT claims for authentication.
  • Bug Fixes

    • Improved JWT claim validation, providing clearer error messages for missing or invalid claims.
  • Documentation

    • Updated documentation to describe how to configure custom JWT claims and the new environment variable.
  • Refactor

    • Simplified JWT handling and validation logic across services.
    • Streamlined test setup for JWT authentication, removing reliance on custom helpers and abstractions.
    • Replaced complex JWT claim structures with simplified claim representations and centralized validation logic.
    • Updated token extraction and validation to use a unified token extractor and configuration-based validation.
    • Consolidated JWT configuration and validation into a dedicated module with enhanced claim checking.
    • Removed deprecated JWT claim types and test helpers to reduce complexity.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 4, 2025

"""

Walkthrough

This change introduces support for user-defined JWT claims across the prover and call_server components. It adds configuration options for specifying JWT claims in YAML and TOML, updates environment variable handling, refactors JWT claim structures in Rust, and simplifies authentication logic and testing to validate claims against user-specified requirements.

Changes

Files/Groups Change Summary
ansible/host_vars/nightly_fake_prover.yml, ansible/host_vars/stable_fake_prover.yml, ansible/host_vars/stable_prod_prover.yml Added vlayer_jwt_claims configuration entries for JWT claims.
ansible/roles/prover/templates/vlayer.service.j2 Added VLAYER_AUTH__JWT__CLAIMS environment variable using joined claim values.
book/src/appendix/architecture/prover.md Documented user-defined JWT claims in configuration and environment variable table.
book/src/appendix/contributing/extension.md, book/src/appendix/contributing/rust.md Updated server run commands to remove --proof fake argument.
rust/cli/Cargo.toml Added derive_builder dependency; enabled derive feature for strum.
rust/cli/src/commands/jwt.rs Replaced imported JWT claim types with new local Claims and Environment definitions using builder pattern.
rust/jwt/Cargo.toml Removed derive_builder dependency.
rust/jwt/src/lib.rs Replaced Environment/Claims with new Claim struct and parsing logic; removed builder and test helpers.
rust/server_utils/src/jwt.rs Added config module; reduced re-exports; removed test helpers.
rust/server_utils/src/jwt/axum.rs Refactored to extract and validate JWT tokens using new Config and TokenExtractor; removed generic claims extraction.
rust/server_utils/src/jwt/cli.rs Switched to importing Config from config module; updated constructor usage.
rust/server_utils/src/jwt/config.rs New module: defines Config struct for claim validation, error types, and logic for checking claims in JWTs.
rust/services/call/server/src/main.rs Allowed destructuring of JwtOptions to ignore extra fields.
rust/services/call/server_lib/src/cli.rs Added support for parsing auth.jwt.claims from environment variables.
rust/services/call/server_lib/src/config.rs Added claims field to JwtOptions; defined JwtClaimOrString enum and conversion logic; updated TOML parsing and tests.
rust/services/call/server_lib/src/gas_meter.rs, rust/services/call/server_lib/src/handlers.rs Switched to importing Token from server_utils::jwt::axum.
rust/services/call/server_lib/src/jwt.rs Removed environment validation logic and related error handling; simplified config extraction.
rust/services/call/server_lib/src/lib.rs Removed pub mod token; declaration.
rust/services/call/server_lib/src/server.rs Replaced claims extraction and validation with token extraction; streamlined authentication logic.
rust/services/call/server_lib/src/token.rs Deleted: removed Token struct definition.
rust/services/call/server_lib/tests/integration_tests.rs Refactored JWT tests to use explicit claims and config; removed builder/test helpers.
rust/services/call/server_lib/tests/test_helpers/mod.rs Updated import path for JwtConfig.
rust/services/dns/server/src/config.rs, rust/services/dns/server/src/main.rs Updated import path for JwtConfig.
rust/services/dns/server/src/server.rs Replaced default JWT config helper with explicit config construction in tests.
rust/services/dns/server/src/server/handlers/dns_query.rs Switched to TokenExtractor; refactored tests to use direct JWT encoding.
rust/services/dns/server/src/server/jwt.rs Updated to use JwtConfig for state conversion.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Service (call_server/prover)
    participant JWT Config
    participant JWT Validator

    User->>Service: Sends request with JWT token
    Service->>JWT Config: Loads expected claims from config/env
    Service->>JWT Validator: Passes JWT token and expected claims
    JWT Validator->>JWT Validator: Decodes and validates claims
    JWT Validator->>Service: Returns validation result
    Service->>User: Processes request or rejects (401) based on result
Loading

Possibly related PRs

  • vlayer-xyz/vlayer#2445: The main PR adds support for user-defined JWT claims configuration and environment variable integration in the call server, while the retrieved PR introduces a new config file parsing system for the call server including TOML config and environment variable overrides; both PRs modify the call server configuration approach and related files but focus on different aspects—JWT claims handling versus overall config file parsing—thus they are related but address distinct configuration features.
  • vlayer-xyz/vlayer#2130: The main PR introduces new JWT claim configuration support and environment variable integration, while the retrieved PR focuses on removing the JWT feature gating to always build with JWT enabled; these changes are related as both involve JWT functionality but address different aspects—configuration and feature gating respectively.

Suggested reviewers

  • rzadp
  • wgromniak2
  • pociej

Poem

In the warren of code, a new claim appears,
JWTs now checked for names we hold dear.
Configs grow stronger, with claims you define,
Tokens validated—no need to opine!
🐇 With a hop and a skip, security’s in line,
Our burrow’s protected, and all works just fine.
Hooray for the claims, and this code so divine!
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0fb7bec and 4590512.

📒 Files selected for processing (2)
  • rust/jwt/src/lib.rs (3 hunks)
  • rust/services/call/server_lib/src/config.rs (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Build binaries
  • GitHub Check: Test Rust
  • GitHub Check: Test vlayer
  • GitHub Check: Build binaries
  • GitHub Check: Build examples
  • GitHub Check: Lint TS
  • GitHub Check: Rust incremental compilation performance
🔇 Additional comments (8)
rust/jwt/src/lib.rs (3)

81-86: Well-designed simplified claim structure.

The new Claim struct effectively replaces the complex previous JWT structures with a clean, flexible design that supports the runtime configuration of claims as described in the PR objectives.


88-103: Robust parsing implementation with proper validation.

The FromStr implementation correctly handles the colon-separated format and includes necessary validation for empty strings and empty claim names, addressing previous review feedback.


105-140: Comprehensive test coverage for the new claim parsing logic.

The tests effectively cover both successful parsing scenarios and error conditions, ensuring the FromStr implementation works correctly with various input formats.

rust/services/call/server_lib/src/config.rs (5)

16-19: Proper import updates for the refactored JWT module.

The import changes correctly reflect the new structure where JwtClaim comes from the main jwt crate and JwtConfig has been moved to the config module.


80-96: Flexible design for JWT claim configuration.

The JwtClaimOrString enum with its TryFrom implementation provides excellent flexibility, allowing users to specify claims either as structured objects or simple strings in configuration files.


227-231: Correct implementation of claims conversion logic.

The conversion from JwtClaimOrString to JwtClaim using TryInto with collect::<Result<_, _>>() is an idiomatic Rust pattern that properly handles error propagation during the conversion process.


697-745: Excellent test coverage for the new JWT claims functionality.

The new test comprehensively validates the TOML parsing of custom JWT claims, covering both claims without values (like "sub") and claims with specific values (like "environment"), which aligns perfectly with the examples in the PR objectives.


541-565: Good test organization with nested modules.

The reorganization into focused test modules (rpc_url_from_str, parse_config_file) improves maintainability and follows Rust testing best practices.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the Ops label Jun 4, 2025
@github-actions
Copy link

github-actions bot commented Jun 4, 2025

The preview of the vlayer book is available at: https://vlayer-book-f5vb2i8lj-vlayer.vercel.app

@github-actions
Copy link

github-actions bot commented Jun 4, 2025

🐢 Incremental Compilation Time: 0:27.94.
View the HTML report here

@github-actions
Copy link

github-actions bot commented Jun 4, 2025

The preview of the vlayer book is available at: https://vlayer-book-qrngmuwbe-vlayer.vercel.app

@kubkon kubkon force-pushed the kubkon+adam/call_server-jwt-claims-config branch from 2dc23de to 1e9cbf9 Compare June 4, 2025 21:41
@github-actions
Copy link

github-actions bot commented Jun 4, 2025

The preview of the vlayer book is available at: https://vlayer-book-rmsfr10na-vlayer.vercel.app

@github-actions
Copy link

github-actions bot commented Jun 4, 2025

The preview of the vlayer book is available at: https://vlayer-book-az67m6dlr-vlayer.vercel.app

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
rust/services/call/server_lib/src/gas_meter.rs (1)

88-101: 💡 Verification agent

🧩 Analysis chain

Verify gas-meter logic aligns with PR objectives.

The PR objectives mention a TODO about updating gas-meter logic to accept the full JWT token and extract claims like sub internally, since required claims are now defined at runtime. Please ensure this implementation properly handles the new dynamic claims structure.


🏁 Script executed:

#!/bin/bash
# Description: Check if gas-meter logic properly handles dynamic JWT claims extraction
# Expected: Find evidence of JWT claims extraction or validation logic

# Search for JWT claim extraction or validation in gas meter related files
rg -A 10 -B 5 "extract.*claim|validate.*claim|jwt.*claim" --type rust

# Look for any TODO comments related to gas-meter and JWT
rg -A 5 -B 2 "TODO.*gas.?meter|gas.?meter.*TODO" --type rust

# Check if there are any references to 'sub' claim extraction
rg -A 5 -B 2 "sub.*claim|claim.*sub" --type rust

Length of output: 17141


Fix gas-meter JWT handling to extract and validate dynamic claims

The gas_meter.rs implementation currently only stores an Option<Token> but never decodes or validates the JWT or extracts runtime‐defined claims (e.g. "sub"). To align with the PR’s objectives, you need to:

  • In rust/services/call/server_lib/src/gas_meter.rs (around RpcClient::new), decode the full JWT using the existing JWT middleware utilities (e.g. server_utils::jwt::axum::decode) and your JwtConfig.
  • Call into Config::validate(&token_data.claims) to enforce runtime claims.
  • Extract required claim values (like sub) from token_data.claims (using .pointer("/sub") or similar) and propagate them into your gas-meter logic.

Without this, the gas meter never enforces or uses the dynamically configured claims. Please add the decode→validate→extract sequence so that the new dynamic‐claims feature is fully wired through the gas-meter.

🧹 Nitpick comments (1)
rust/services/dns/server/src/server.rs (1)

64-64: Consider using a more descriptive test secret.

While "deadbeef" is acceptable for testing, consider using a more descriptive value like "test-jwt-secret" to improve code readability.

-    pub const JWT_SECRET: &[u8] = b"deadbeef";
+    pub const JWT_SECRET: &[u8] = b"test-jwt-secret";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c9dae53 and d550992.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (31)
  • ansible/host_vars/nightly_fake_prover.yml (1 hunks)
  • ansible/host_vars/stable_fake_prover.yml (1 hunks)
  • ansible/host_vars/stable_prod_prover.yml (1 hunks)
  • ansible/roles/prover/templates/vlayer.service.j2 (1 hunks)
  • book/src/appendix/architecture/prover.md (2 hunks)
  • book/src/appendix/contributing/extension.md (1 hunks)
  • book/src/appendix/contributing/rust.md (1 hunks)
  • rust/cli/Cargo.toml (2 hunks)
  • rust/cli/src/commands/jwt.rs (2 hunks)
  • rust/jwt/Cargo.toml (0 hunks)
  • rust/jwt/src/lib.rs (3 hunks)
  • rust/server_utils/src/jwt.rs (1 hunks)
  • rust/server_utils/src/jwt/axum.rs (3 hunks)
  • rust/server_utils/src/jwt/cli.rs (2 hunks)
  • rust/server_utils/src/jwt/config.rs (1 hunks)
  • rust/services/call/server/src/main.rs (1 hunks)
  • rust/services/call/server_lib/src/cli.rs (1 hunks)
  • rust/services/call/server_lib/src/config.rs (5 hunks)
  • rust/services/call/server_lib/src/gas_meter.rs (1 hunks)
  • rust/services/call/server_lib/src/handlers.rs (1 hunks)
  • rust/services/call/server_lib/src/jwt.rs (1 hunks)
  • rust/services/call/server_lib/src/lib.rs (0 hunks)
  • rust/services/call/server_lib/src/server.rs (2 hunks)
  • rust/services/call/server_lib/src/token.rs (0 hunks)
  • rust/services/call/server_lib/tests/integration_tests.rs (5 hunks)
  • rust/services/call/server_lib/tests/test_helpers/mod.rs (1 hunks)
  • rust/services/dns/server/src/config.rs (1 hunks)
  • rust/services/dns/server/src/main.rs (1 hunks)
  • rust/services/dns/server/src/server.rs (1 hunks)
  • rust/services/dns/server/src/server/handlers/dns_query.rs (5 hunks)
  • rust/services/dns/server/src/server/jwt.rs (1 hunks)
💤 Files with no reviewable changes (3)
  • rust/jwt/Cargo.toml
  • rust/services/call/server_lib/src/lib.rs
  • rust/services/call/server_lib/src/token.rs
🧰 Additional context used
🧬 Code Graph Analysis (1)
rust/services/call/server_lib/src/jwt.rs (3)
rust/services/call/server_lib/src/server.rs (1)
  • server (62-79)
rust/services/call/server_lib/tests/test_helpers/mod.rs (1)
  • server (95-112)
rust/services/dns/server/src/server/jwt.rs (1)
  • from_ref (8-14)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build binaries
  • GitHub Check: Build binaries
🔇 Additional comments (52)
rust/cli/Cargo.toml (2)

15-15: Workspace dependency derive_builder added
The derive_builder crate is now included to support builder-pattern generation for the new JWT claims struct.


26-26: Enable derive feature on strum crate
Including the derive feature flag for strum allows procedural derivation of the Environment enum used in dynamic claim validation.

rust/services/dns/server/src/config.rs (1)

3-3: Update JWT config import path
Switching from server_utils::jwt::cli::Config to server_utils::jwt::config::Config ensures we reference the relocated configuration type.

book/src/appendix/contributing/extension.md (1)

62-62: Remove --proof fake argument from server run command
The CLI invocation no longer requires the --proof fake flag, reflecting the streamlined default proof mode and runtime-configurable JWT claims.

rust/services/call/server_lib/tests/test_helpers/mod.rs (1)

11-11: Align JWT config import in test helpers
Updated the import to use server_utils::jwt::config::Config so tests reference the new centralized JWT configuration struct.

rust/services/dns/server/src/main.rs (1)

10-10: Use centralized JwtConfig from server_utils::jwt::config
Ensures the DNS server reads its JWT settings from the newly refactored configuration module.

rust/services/call/server/src/main.rs (1)

60-60: LGTM! Wildcard pattern correctly handles struct extension.

The addition of .. in the destructuring pattern appropriately handles the new claims field added to JwtOptions while maintaining the existing logging functionality for public_key and algorithm.

rust/services/call/server_lib/src/handlers.rs (2)

8-8: LGTM! Import change aligns with JWT refactoring.

The migration from local token::Token to server_utils::jwt::axum::Token correctly reflects the refactoring to shared JWT utilities, supporting the new configurable claims functionality.


13-13: LGTM! Clean removal of local token import.

Removing the local token import is appropriate since token handling has been moved to shared utilities in server_utils.

rust/services/call/server_lib/src/cli.rs (1)

38-38: LGTM! Environment variable parsing for JWT claims correctly implemented.

The addition of "auth.jwt.claims" as a list parse key enables parsing JWT claims from environment variables like VLAYER_AUTH__JWT__CLAIMS="sub environment:test" as described in the PR objectives.

ansible/host_vars/stable_fake_prover.yml (1)

8-10: LGTM! JWT claims configuration correctly implemented.

The vlayer_jwt_claims configuration with "sub" and "environment:test" values aligns perfectly with the PR objectives, requiring the sub claim to exist and the environment claim to match "test" exactly. This is appropriate for the stable fake prover environment.

ansible/host_vars/stable_prod_prover.yml (1)

9-11: LGTM - JWT claims configuration for production environment.

The configuration correctly specifies the required JWT claims for the production environment, with sub requiring existence and environment requiring exact match to "production".

rust/services/call/server_lib/src/gas_meter.rs (1)

9-12: Import reorganization looks good.

The consolidation of JWT-related imports from server_utils is appropriate and aligns with removing the local Token struct.

ansible/host_vars/nightly_fake_prover.yml (1)

8-10: LGTM - JWT claims configuration for test environment.

The configuration correctly specifies the required JWT claims for the test environment, appropriately using "environment:test" to distinguish from production.

ansible/roles/prover/templates/vlayer.service.j2 (1)

44-44: Environment variable setup is correct.

The template properly sets up the VLAYER_AUTH__JWT__CLAIMS environment variable by joining the claims list with spaces, which matches the format specified in the PR objectives.

book/src/appendix/contributing/rust.md (1)

122-123: LGTM! Command simplification improves usability.

Removing the --proof fake argument aligns with the broader configuration changes and simplifies the profiling workflow.

rust/services/dns/server/src/server.rs (2)

59-59: Import changes align with JWT refactoring.

The explicit imports of DecodingKey and JwtConfig are consistent with the broader refactoring that centralizes JWT configuration handling.


73-75: Manual JWT configuration provides better test control.

The explicit construction of JWT configuration with empty claims list is more transparent than using a default helper and aligns well with the new user-defined claims support.

rust/server_utils/src/jwt/cli.rs (2)

9-9: Import change aligns with JWT config module refactoring.

Moving from local Config to super::config::Config is consistent with centralizing JWT configuration logic into a dedicated module.


49-49: Empty claims vector supports new JWT claims feature.

Adding Vec::new() as the third parameter correctly initializes the JWT configuration with an empty claims list, which aligns with the new user-defined JWT claims support.

book/src/appendix/architecture/prover.md (2)

84-90: Excellent documentation for JWT claims configuration.

The documentation clearly explains both claim existence validation (name only) and value-specific validation with practical examples. This will help users understand how to configure custom JWT claims effectively.


129-129: Environment variable table properly updated.

Adding VLAYER_AUTH__JWT__CLAIMS to the environment variables table with correct type (list) and empty default maintains consistency with the configuration documentation.

rust/services/dns/server/src/server/jwt.rs (2)

2-2: LGTM: Import update aligns with JWT config refactoring.

The import change from JwtState to JwtConfig is consistent with the centralized JWT configuration approach introduced in this PR.


6-15: LGTM: Clean implementation of FromRef trait.

The implementation correctly extracts and clones the JWT configuration from the application state. The expect message provides clear guidance for configuration requirements.

rust/services/call/server_lib/src/server.rs (2)

14-14: LGTM: Updated import reflects new token extraction approach.

The change from ClaimsExtractor to TokenExtractor aligns with the centralized JWT validation strategy where claims validation is handled by the JwtConfig.


46-54: LGTM: Simplified authentication handler.

The refactored handle_with_auth function is much cleaner by:

  • Using TokenExtractor instead of ClaimsExtractor
  • Removing environment validation logic (now handled centrally)
  • Directly passing the token to Params::new

This aligns with the PR objective of centralizing JWT claims validation in the configuration layer.

rust/server_utils/src/jwt.rs (2)

3-3: LGTM: New config module supports centralized JWT validation.

The addition of the config submodule aligns with the PR objective of centralizing JWT claims configuration and validation logic.


5-5: LGTM: Simplified exports reflect architectural changes.

The updated exports with the simplified Claim struct instead of complex claim types support the streamlined JWT handling approach.

rust/services/call/server_lib/src/jwt.rs (2)

1-5: LGTM: Updated imports reflect JWT config centralization.

The import changes from various JWT-related modules to the simplified jwt::config::Config align with the centralized JWT configuration approach.


7-16: LGTM: Simplified FromRef implementation aligns with architectural goals.

The refactored implementation:

  • Consistently returns JwtConfig instead of JwtState
  • Removes complex validation logic in favor of centralized config-based validation
  • Follows the same pattern as the DNS server implementation

This simplification supports the PR objective of centralizing JWT claims validation in the configuration layer, where the JwtConfig now handles claims validation internally.

rust/services/dns/server/src/server/handlers/dns_query.rs (1)

34-40: LGTM!

The simplified token extraction aligns well with the new dynamic JWT claims configuration approach.

rust/cli/src/commands/jwt.rs (1)

97-109: Well-structured Claims definition

The local Claims struct with builder pattern is a good design choice for the CLI's specific needs, allowing flexible JWT generation for testing while keeping the core jwt library generic.

rust/services/call/server_lib/tests/integration_tests.rs (7)

498-501: LGTM: Import changes align with JWT refactoring.

The new imports replace previous abstractions with explicit JWT utilities, providing better control over token creation in tests.


506-506: LGTM: Hardcoded secret appropriate for tests.

Using a fixed secret in test code ensures deterministic behavior and is a common testing pattern.


508-522: LGTM: Token creation function is well-implemented.

The explicit JSON claims approach improves test clarity compared to previous abstractions. The timestamp calculation and JWT encoding logic are correct.


524-540: LGTM: JWT configuration correctly matches test tokens.

The explicit claims configuration (sub with any value, environment must be "test") aligns with the tokens created by the token() function.


586-595: LGTM: Tampered token test correctly validates signature verification.

The test properly uses a different secret key to ensure signature validation fails, maintaining security.


624-647: LGTM: Environment mismatch test validates claims correctly.

The test properly verifies that tokens with incorrect environment claims are rejected with descriptive error messages, ensuring robust claim validation.


649-700: LGTM: Gas meter authentication test correctly uses full token.

The test properly validates JWT authentication flow with gas meter integration, using the full token string for bearer authentication as intended.

rust/server_utils/src/jwt/config.rs (6)

1-12: LGTM: Clean error handling and appropriate imports.

The ValidationError type with descriptive messages will help with debugging JWT validation issues.


13-19: LGTM: Well-designed Config struct with security considerations.

Skipping the public key in debug output is a good security practice to prevent accidental key exposure in logs.


21-52: LGTM: Robust and secure JWT claims validation logic.

The implementation correctly handles:

  • Nested claims via JSON pointer syntax
  • Type safety (strings only for claim values)
  • Value validation against allowlists
  • Descriptive error messages for debugging

The validation approach is both secure and flexible for user-defined claims.


61-72: LGTM: Test correctly validates claim presence requirement.

The test uses a realistic JWT structure and properly validates that required claims must exist.


74-87: LGTM: Excellent test coverage for nested claims validation.

This test validates the crucial JSON pointer functionality, ensuring claims like custom.host correctly map to nested JSON structures like {"custom": {"host": "..."}}.


99-146: LGTM: Comprehensive error condition testing.

The tests cover all major failure scenarios with detailed error message validation:

  • Missing required claims
  • Invalid claim values
  • Unsupported claim types (non-strings)

This ensures robust error handling and good debugging experience.

rust/services/call/server_lib/src/config.rs (4)

16-16: LGTM: Import updates align with JWT refactoring.

The alias Claim as JwtClaim prevents naming conflicts, and the updated import path reflects the relocated Config struct.

Also applies to: 19-19


75-78: LGTM: Flexible claims configuration with backward compatibility.

The optional claims field with #[serde(default)] maintains backward compatibility while enabling user-defined JWT claims configuration.


80-96: LGTM: Flexible claim specification with proper error handling.

The untagged enum design allows users to specify claims as either simple strings or structured objects, with proper error propagation for invalid string formats.


221-231: LGTM: Proper conversion from configuration to JWT validation config.

The logic correctly converts flexible configuration claims to structured JWT claims with appropriate error propagation and passes them to the validation config.

rust/server_utils/src/jwt/axum.rs (3)

21-22: LGTM: Clean Token newtype with appropriate derives.

The Token wrapper provides type safety for JWT tokens while remaining simple and efficient with appropriate trait derives.


24-37: LGTM: API simplification with proper error handling.

Moving from generic ClaimsExtractor<T> to concrete TokenExtractor simplifies the API while maintaining type safety. The Validation error variant properly handles claim validation failures.


41-71: LGTM: Robust token extraction with flexible claim validation.

The implementation correctly:

  • Validates JWT header and signature
  • Decodes claims as generic JSON for flexibility with user-defined claims
  • Delegates validation to the Config's validate method
  • Returns the raw token string for downstream use

This design supports the user-defined claims feature while maintaining security.

@github-actions
Copy link

github-actions bot commented Jun 5, 2025

The preview of the vlayer book is available at: https://vlayer-book-entxopnm9-vlayer.vercel.app

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
rust/jwt/src/lib.rs (1)

88-103: Excellent implementation that addresses previous feedback!

The FromStr implementation correctly handles the parsing requirements and appropriately addresses the empty claim name validation that was flagged in previous reviews. The use of EmptyName error (instead of EmptyString) is semantically better than the originally suggested fix.

The parsing logic correctly handles the colon-separated format mentioned in the PR objectives (e.g., "sub environment:test").

🧹 Nitpick comments (1)
rust/jwt/src/lib.rs (1)

81-86: Consider adding documentation for the simplified Claim struct.

The struct design is clean and appropriate for the new dynamic claim configuration approach. However, it would benefit from documentation explaining the purpose and usage of the name and values fields.

+/// Represents a JWT claim with a name and optional allowed values.
+/// 
+/// When `values` is empty, the claim only needs to exist in the JWT.
+/// When `values` contains items, the claim must match one of the specified values.
 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
 pub struct Claim {
+    /// The name of the JWT claim (e.g., "sub", "environment")
     pub name: String,
+    /// Optional list of allowed values. Empty means any value is accepted.
     #[serde(default)]
     pub values: Vec<String>,
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d550992 and 0fb7bec.

📒 Files selected for processing (1)
  • rust/jwt/src/lib.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build binaries
  • GitHub Check: Test vlayer
  • GitHub Check: Test Rust
  • GitHub Check: Build binaries
  • GitHub Check: Build examples
  • GitHub Check: Lint TS
  • GitHub Check: Lint Rust
  • GitHub Check: Rust incremental compilation performance
🔇 Additional comments (2)
rust/jwt/src/lib.rs (2)

1-4: LGTM! Import additions support the new parsing functionality.

The addition of std::str::FromStr correctly supports the new string parsing capability for JWT claims.


16-19: LGTM! Well-defined error variants for claim parsing.

The new error variants EmptyString and EmptyName provide clear, specific error messages for different parsing failure scenarios.

@github-actions
Copy link

github-actions bot commented Jun 5, 2025

The preview of the vlayer book is available at: https://vlayer-book-ri2ubtnhg-vlayer.vercel.app

Copy link
Contributor

@Chmarusso Chmarusso left a comment

Choose a reason for hiding this comment

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

book part LGTM

@kubkon kubkon added this pull request to the merge queue Jun 5, 2025
Merged via the queue into main with commit c80916b Jun 5, 2025
62 checks passed
@kubkon kubkon deleted the kubkon+adam/call_server-jwt-claims-config branch June 5, 2025 11:35
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.

5 participants