Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validity time option to the API (DIS-2749) #299

Merged
merged 9 commits into from
Oct 12, 2024

Conversation

paulgb
Copy link
Member

@paulgb paulgb commented Oct 2, 2024

Adds valid_for_seconds to the auth body request. We weren't actually parsing the request body before, so we do that now.

Introduces a newtype to avoid mixing up the current time and expiration times.

Closes #309

Copy link

vercel bot commented Oct 2, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
y-sweet-debugger ⬜️ Ignored (Inspect) Visit Preview Oct 9, 2024 4:40pm
y-sweet-demos ⬜️ Ignored (Inspect) Visit Preview Oct 9, 2024 4:40pm
y-sweet-gendocs ⬜️ Ignored (Inspect) Visit Preview Oct 9, 2024 4:40pm

@paulgb paulgb changed the title Add validity time option to the API Add validity time option to the API (DIS-2749) Oct 7, 2024
@paulgb paulgb mentioned this pull request Oct 8, 2024
@paulgb paulgb force-pushed the paulgb/add-validity-time-option-to-api branch from de27c86 to bc4f3e1 Compare October 9, 2024 15:48
Copy link
Contributor

coderabbitai bot commented Oct 9, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several changes across multiple files in the y-sweet codebase. It primarily focuses on enhancing the AuthDocRequest struct by adding an optional field, valid_for_seconds, which allows for specifying token validity time. A default implementation for this struct is also provided. In the auth.rs file, a new struct ExpirationTimeEpochMillis is introduced to improve type safety regarding expiration times, and existing methods are updated to utilize this new type. The lib.rs file imports the new types and modifies the auth_doc function to incorporate the optional valid_for_seconds. The Server struct in server.rs is updated to reflect these changes, allowing for default values when the field is not specified. Additionally, the DocumentManager class in the JavaScript SDK is updated to accept the AuthDocRequest parameter in several methods, enhancing the authorization handling. New type definitions for Authorization and AuthDocRequest are also added in the TypeScript definitions.

Assessment against linked issues

Objective Addressed Explanation
Allow the token validity time to be specified (##309)
Make y-sweet session duration configurable in auth endpoint (DIS-2749)

Possibly related PRs

Suggested reviewers

  • rolyatmax

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7384018 and da062ff.

📒 Files selected for processing (2)
  • crates/y-sweet-worker/src/lib.rs (3 hunks)
  • crates/y-sweet/src/server.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/y-sweet/src/server.rs
🧰 Additional context used
🔇 Additional comments (4)
crates/y-sweet-worker/src/lib.rs (4)

11-14: LGTM: New imports align with PR objectives

The addition of AuthDocRequest, ExpirationTimeEpochMillis, and DEFAULT_EXPIRATION_SECONDS imports from the y_sweet_core crate aligns well with the PR objectives. These new types will support the implementation of the validity time option for authentication tokens.


194-194: LGTM: Mutable request parameter

The addition of the mut keyword to the req parameter is appropriate. It allows for the parsing of the request body as JSON, which is necessary for extracting the valid_for_seconds field from the AuthDocRequest.


210-219: LGTM: Implementation of validity time option

The changes successfully implement the new validity time option for authentication tokens. The code correctly parses the AuthDocRequest, uses the valid_for_seconds field if provided, and falls back to a default value otherwise. The expiration time calculation is also implemented correctly.

Consider adding validation for valid_for_seconds

While the implementation handles cases where valid_for_seconds is not provided, it doesn't validate the value when it is present. Consider adding a check to ensure that valid_for_seconds is within an acceptable range to prevent potential security issues with extremely long-lived tokens or negative values.

Here's a suggested implementation:

const MAX_VALIDITY_SECONDS: u64 = 86400; // Example: 24 hours max

let valid_time_seconds = body.valid_for_seconds.unwrap_or(DEFAULT_EXPIRATION_SECONDS);
if valid_time_seconds == 0 || valid_time_seconds > MAX_VALIDITY_SECONDS {
    return Err(Error::InvalidTokenValidityPeriod);
}

Verify error handling for request body parsing

A previous review comment suggested explicit error handling for request body parsing. The current implementation addresses this by using map_err(|_| Error::BadRequest)? instead of unwrap_or_default(). This change appropriately handles parsing errors by returning a BadRequest error.


223-223: LGTM: Updated token generation

The token generation has been correctly updated to use the new expiration_time calculated from the valid_for_seconds parameter or the default value.


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

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: 10

🧹 Outside diff range and nitpick comments (5)
js-pkg/sdk/src/types.ts (1)

34-46: LGTM: Well-structured AuthDocRequest type with a minor suggestion.

The AuthDocRequest type is well-defined and aligns perfectly with the PR objectives. It includes the crucial validForSeconds property for specifying token validity time, and the optional nature of all properties provides great flexibility.

Consider improving type safety for the metadata property:

metadata?: Record<string, unknown>;

This change ensures that any value can be stored in the metadata while maintaining type safety.

crates/y-sweet-core/src/api_types.rs (1)

37-39: LGTM! Consider adding documentation for the new field.

The addition of the valid_for_seconds field aligns well with the PR objective of allowing specification of token validity time. The use of Option<u64> and the serde annotations are appropriate.

Consider adding a doc comment to explain the purpose and expected format of the valid_for_seconds field. For example:

/// The duration in seconds for which the authentication token should be valid.
/// If not specified, a default value will be used.
#[serde(skip_serializing_if = "Option::is_none", rename = "validForSeconds")]
pub valid_for_seconds: Option<u64>,
crates/y-sweet/src/server.rs (2)

654-658: Ensure consistent naming and remove debug print

The implementation for handling the valid_for_seconds parameter looks good. However, there are a couple of suggestions:

  1. Consider renaming valid_for_seconds to expiration_time_seconds for consistency with the ExpirationTimeEpochMillis type.
  2. Remove the debug print statement on line 655, as it's not necessary for production code.

Here's a suggested improvement:

-let valid_for_seconds = body.valid_for_seconds.unwrap_or(DEFAULT_EXPIRATION_MILLIS);
-println!("valid_for_seconds {}", valid_for_seconds);
-let expiration_time =
-    ExpirationTimeEpochMillis(current_time_epoch_millis() + valid_for_seconds * 1000);
+let expiration_time_seconds = body.valid_for_seconds.unwrap_or(DEFAULT_EXPIRATION_MILLIS);
+let expiration_time = ExpirationTimeEpochMillis(
+    current_time_epoch_millis() + expiration_time_seconds * 1000
+);

756-756: LGTM: Test case for default behavior

Passing None instead of a Json<AuthDocRequest> is a good test for the default behavior when no request body is provided. This helps ensure backward compatibility.

Consider adding an additional test case that explicitly sets a custom valid_for_seconds value to ensure that the expiration time is calculated correctly.

crates/y-sweet-core/src/auth.rs (1)

13-13: Typo in documentation comment

There's a typo in the comment on line 13: "intentonally" should be "intentionally".

Apply this diff to correct the typo:

-/// We introduce this to intentonally break callers to `gen_doc_token` that do not explicitly
+/// We introduce this to intentionally break callers to `gen_doc_token` that do not explicitly
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9a8c0f6 and 211e576.

📒 Files selected for processing (7)
  • crates/y-sweet-core/src/api_types.rs (1 hunks)
  • crates/y-sweet-core/src/auth.rs (10 hunks)
  • crates/y-sweet-worker/src/lib.rs (3 hunks)
  • crates/y-sweet/src/server.rs (4 hunks)
  • js-pkg/sdk/src/main.ts (6 hunks)
  • js-pkg/sdk/src/types.ts (1 hunks)
  • tests/src/index.test.ts (2 hunks)
🧰 Additional context used
🪛 Biome
tests/src/index.test.ts

[error] 299-299: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

🔇 Additional comments (17)
js-pkg/sdk/src/types.ts (2)

32-32: LGTM: Clear and concise Authorization type definition.

The Authorization type is well-defined as a union of 'full' and 'read-only'. This aligns with the PR objectives of enhancing token management flexibility.


31-46: Summary: New type definitions align well with PR objectives.

The additions of Authorization and AuthDocRequest types are well-implemented and directly support the PR's goal of enhancing token management flexibility. The validForSeconds property in AuthDocRequest addresses the main objective of allowing specification of token validity time. These changes provide a solid foundation for implementing the new features described in the PR objectives.

crates/y-sweet-core/src/api_types.rs (1)

41-49: LGTM! Verify the default authorization level.

The Default implementation for AuthDocRequest is well-structured and includes all fields, including the new valid_for_seconds field.

Please confirm that Authorization::Full is the intended default authorization level. If it's correct, consider adding a comment explaining why full authorization is the default. If not, adjust accordingly.

To verify the usage of Authorization::Full across the codebase, you can run the following script:

This will help ensure consistency in the default authorization level across the project.

crates/y-sweet/src/server.rs (4)

35-35: LGTM: Appropriate imports added

The addition of ExpirationTimeEpochMillis and DEFAULT_EXPIRATION_MILLIS to the imports is consistent with their usage in the updated auth_doc function. This change follows good practices by importing specific items.


644-644: LGTM: Improved function signature for backward compatibility

The updated function signature now accepts an optional Json<AuthDocRequest>, which is then unwrapped with a default value. This change allows for backward compatibility while introducing the new functionality to specify token validity time.

Also applies to: 648-649


718-723: LGTM: Updated test case for new functionality

The test case has been appropriately updated to include the new valid_for_seconds field in the AuthDocRequest. This ensures that the new functionality is being tested.


Line range hint 1-765: Overall assessment: Well-implemented feature with minor suggestions

The changes successfully implement the new feature to allow specifying token validity time while maintaining backward compatibility. The code is well-structured and the test cases have been appropriately updated. Here's a summary of the suggestions:

  1. Consider renaming valid_for_seconds to expiration_time_seconds for consistency.
  2. Remove the debug print statement in the auth_doc function.
  3. Add an additional test case that explicitly sets a custom valid_for_seconds value.

These minor improvements will enhance the code quality and test coverage. Great work overall!

crates/y-sweet-worker/src/lib.rs (3)

11-14: Imports updated correctly

The necessary types and constants have been successfully imported to support the new functionality.


194-194: Function signature updated appropriately

The auth_doc function now accepts mutable req and ctx, which is necessary for parsing the request body and modifying the context.


220-220: Ensure correct usage of gen_doc_token with updated expiration time

auth.gen_doc_token is now called with expiration_time, ensuring tokens are generated with the specified validity period.

tests/src/index.test.ts (1)

2-2: Importing YSweetError for error handling

The addition of YSweetError in the import statement is appropriate, as it facilitates proper error handling in the new test cases.

crates/y-sweet-core/src/auth.rs (6)

9-10: Renaming and exposing DEFAULT_EXPIRATION_MILLIS improves clarity and accessibility

Renaming EXPIRATION_MILLIS to DEFAULT_EXPIRATION_MILLIS clarifies its purpose as the default expiration time for tokens. Making it pub allows other modules to access this constant as needed, aligning with the PR objectives of enhancing token management flexibility.


20-24: ExpirationTimeEpochMillis::max() provides a clear way to represent infinite expiration

Implementing the max() method enhances usability by offering a straightforward way to represent tokens with no specific expiration time.


102-102: Updating expiration_millis to use ExpirationTimeEpochMillis enhances type safety

Changing the expiration_millis field to Option<ExpirationTimeEpochMillis> ensures that expiration times are explicitly and safely handled, reducing the risk of errors associated with raw u64 values.


159-162: Payload::new_with_expiration now requires ExpirationTimeEpochMillis for clarity

By accepting ExpirationTimeEpochMillis, the constructor enforces explicit specification of expiration times, enhancing readability and reducing potential misuse.


277-283: Properly handling token expiration using ExpirationTimeEpochMillis

The updated logic correctly checks token expiration by comparing the expiration time with the current time, accounting for tokens without a set expiration by defaulting to ExpirationTimeEpochMillis::max().


316-322: gen_doc_token now requires explicit expiration time

Requiring an ExpirationTimeEpochMillis parameter for gen_doc_token enforces that callers explicitly specify the token's expiration, improving security and aligning with the PR's goals to make token validity configurable.

Comment on lines +75 to +78
public async getClientToken(
docId: string | DocCreationResult,
authDocRequest?: AuthDocRequest,
): Promise<ClientToken> {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update JSDoc comments to include the 'authDocRequest' parameter

The getClientToken method now accepts an optional authDocRequest parameter, but the JSDoc comments above the method do not reflect this change. Please update the documentation to include a description of authDocRequest and its purpose.

js-pkg/sdk/src/main.ts Show resolved Hide resolved
Comment on lines +129 to +132
public async getDocConnection(
docId: string | DocCreationResult,
authDocRequest?: AuthDocRequest,
): Promise<DocConnection> {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add documentation for the new 'authDocRequest' parameter

The getDocConnection method signature now includes an optional authDocRequest parameter, but the accompanying JSDoc comments have not been updated. Please provide a description of authDocRequest in the documentation to clarify its function.

js-pkg/sdk/src/main.ts Show resolved Hide resolved
js-pkg/sdk/src/main.ts Show resolved Hide resolved
crates/y-sweet-worker/src/lib.rs Outdated Show resolved Hide resolved
crates/y-sweet-worker/src/lib.rs Outdated Show resolved Hide resolved
tests/src/index.test.ts Outdated Show resolved Hide resolved
tests/src/index.test.ts Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
js-pkg/sdk/src/main.ts (1)

131-135: Update JSDoc for getDocConnection method.

The getDocConnection method has been correctly updated to include the authDocRequest parameter and pass it to getClientToken. However, the JSDoc comments for this method have not been updated to reflect this change.

Please update the JSDoc to include a description of the authDocRequest parameter, similar to the other methods.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d726e52 and d101f7a.

📒 Files selected for processing (1)
  • js-pkg/sdk/src/main.ts (5 hunks)
🧰 Additional context used
🔇 Additional comments (6)
js-pkg/sdk/src/main.ts (6)

4-4: LGTM: Import statement updated correctly.

The import statement has been properly updated to include the AuthDocRequest type, which is necessary for the new parameter added to various methods.


73-79: LGTM: getClientToken method updated correctly.

The getClientToken method has been properly updated:

  1. The method signature now includes the optional authDocRequest parameter.
  2. The JSDoc has been updated to describe the new parameter, addressing the previous review comment.
  3. The request body in the implementation now correctly uses the authDocRequest parameter.

These changes improve the flexibility of the authentication process as intended.

Also applies to: 84-84


98-104: LGTM: getOrCreateDocAndToken method updated correctly.

The getOrCreateDocAndToken method has been properly updated:

  1. The method signature now includes the optional authDocRequest parameter.
  2. The JSDoc has been updated to describe the new parameter, addressing the previous review comment.
  3. The implementation now correctly passes the authDocRequest to the getClientToken method.

These changes ensure that the authentication request options are properly propagated.

Also applies to: 106-106


146-146: LGTM: getOrCreateDocAndToken function updated correctly.

The getOrCreateDocAndToken function has been properly updated:

  1. The function signature now includes the optional authDocRequest parameter.
  2. The JSDoc has been updated to describe the new parameter, addressing the previous review comment.
  3. The implementation now correctly passes the authDocRequest to the DocumentManager.getOrCreateDocAndToken method.

These changes ensure that the authentication request options are properly propagated through the convenience function.

Also applies to: 152-152, 155-155


163-163: LGTM: getClientToken function updated correctly.

The getClientToken function has been properly updated:

  1. The function signature now includes the optional authDocRequest parameter.
  2. The JSDoc has been updated to describe the new parameter, addressing the previous review comment.
  3. The implementation now correctly passes the authDocRequest to the DocumentManager.getClientToken method.

These changes ensure that the authentication request options are properly propagated through the convenience function.

Also applies to: 169-169, 172-172


Line range hint 1-189: Overall changes align well with PR objectives.

The changes in this file successfully implement the new feature allowing specification of validity time for authentication tokens through the authDocRequest parameter. The modifications are consistent across different methods and functions, ensuring that the new parameter is properly propagated throughout the authentication process.

Key points:

  1. The AuthDocRequest type is correctly imported and used.
  2. All relevant methods and functions (getClientToken, getOrCreateDocAndToken, getDocConnection) have been updated to include the new parameter.
  3. JSDoc comments have been updated in most places to reflect the changes (except for getDocConnection, which has been addressed in a previous comment).
  4. The changes align well with the PR objectives and the AI-generated summary.

These updates enhance the flexibility of token management as intended, allowing users to define how long a token remains valid.

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 and nitpick comments (5)
crates/y-sweet-core/src/auth.rs (5)

9-10: LGTM! Consider adding a doc comment.

The introduction of DEFAULT_EXPIRATION_SECONDS as a public constant is a good change. It aligns with the PR objective of making token validity time configurable and uses a more intuitive time unit (seconds).

Consider adding a doc comment to explain the purpose and usage of this constant, especially since it's now public. For example:

/// Default expiration time for authentication tokens in seconds.
/// This value is used when no specific expiration time is provided.
pub const DEFAULT_EXPIRATION_SECONDS: u64 = 60 * 60; // 60 minutes

11-18: LGTM! Consider implementing additional traits.

The introduction of ExpirationTimeEpochMillis is a good change that improves type safety and prevents potential misuse of the gen_doc_token function. The derived traits and the explanatory comment are appropriate.

Consider implementing additional traits that might be useful for this type:

use std::ops::Deref;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct ExpirationTimeEpochMillis(pub u64);

impl Deref for ExpirationTimeEpochMillis {
    type Target = u64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

This would allow for easier comparison and dereferencing to the underlying u64 value when needed.


20-24: LGTM! Consider adding a doc comment.

The max() method is a good addition, providing a convenient way to represent an "infinite" expiration time.

Consider adding a doc comment to explain the purpose and usage of this method:

impl ExpirationTimeEpochMillis {
    /// Returns the maximum possible expiration time, effectively representing "never expires".
    pub fn max() -> Self {
        Self(u64::MAX)
    }
}

316-322: LGTM! Consider adding a default expiration option.

The changes to gen_doc_token correctly incorporate the new ExpirationTimeEpochMillis type, improving type safety and preventing accidental misuse with raw u64 values.

Consider adding an overloaded method or a default parameter to allow users to generate tokens with the default expiration time easily:

impl Authenticator {
    // ... existing methods ...

    pub fn gen_doc_token_with_default_expiration(&self, doc_id: &str) -> String {
        self.gen_doc_token(doc_id, ExpirationTimeEpochMillis(DEFAULT_EXPIRATION_SECONDS * 1000))
    }
}

This would provide a convenient way for users to generate tokens without specifying an expiration time, while still allowing custom expiration times when needed.


389-392: LGTM! Consider adding more test cases.

The updates to the test cases correctly incorporate the new ExpirationTimeEpochMillis type and make use of the DEFAULT_EXPIRATION_SECONDS constant. These changes ensure that the tests remain consistent with the main code and improve maintainability.

Consider adding more test cases to cover different scenarios:

  1. Test with a custom expiration time that's neither 0 nor the default.
  2. Test the behavior when the current time is exactly at the expiration time.
  3. Test with ExpirationTimeEpochMillis::max() to ensure "never expires" behavior works as expected.

For example:

#[test]
fn test_custom_expiration_time() {
    let authenticator = Authenticator::gen_key().unwrap();
    let custom_expiration = 3600; // 1 hour
    let token = authenticator.gen_doc_token("doc123", ExpirationTimeEpochMillis(custom_expiration * 1000));
    assert_eq!(authenticator.verify_doc_token(&token, "doc123", 0), Ok(()));
    assert_eq!(authenticator.verify_doc_token(&token, "doc123", custom_expiration * 1000), Ok(()));
    assert_eq!(
        authenticator.verify_doc_token(&token, "doc123", (custom_expiration + 1) * 1000),
        Err(AuthError::Expired)
    );
}

#[test]
fn test_never_expires() {
    let authenticator = Authenticator::gen_key().unwrap();
    let token = authenticator.gen_doc_token("doc123", ExpirationTimeEpochMillis::max());
    assert_eq!(authenticator.verify_doc_token(&token, "doc123", u64::MAX), Ok(()));
}

These additional test cases would help ensure the robustness of the expiration time handling.

Also applies to: 406-406, 441-441, 455-455, 466-466

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d101f7a and 7384018.

📒 Files selected for processing (3)
  • crates/y-sweet-core/src/auth.rs (10 hunks)
  • crates/y-sweet-worker/src/lib.rs (3 hunks)
  • crates/y-sweet/src/server.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/y-sweet/src/server.rs
🧰 Additional context used
🔇 Additional comments (6)
crates/y-sweet-worker/src/lib.rs (4)

11-14: LGTM: New imports are consistent with functionality changes

The new imports for AuthDocRequest, ExpirationTimeEpochMillis, and DEFAULT_EXPIRATION_SECONDS align well with the changes in the auth_doc function, supporting the new token validity time feature.


213-215: LGTM: Expiration time calculation looks good

The expiration time calculation correctly uses the valid_for_seconds from the request body or falls back to DEFAULT_EXPIRATION_SECONDS. The use of ExpirationTimeEpochMillis type improves type safety for expiration time handling.


220-220: LGTM: Token generation with configurable expiration time

The token generation now correctly uses the calculated expiration time, which can be specified in the request or defaults to a predefined value. This change successfully implements the feature of configurable token validity times.


Line range hint 194-220: Summary: Successfully implemented configurable token validity times

The changes in the auth_doc function effectively implement the feature of allowing token validity time to be specified through the API, as outlined in the PR objectives and linked issues. The use of ExpirationTimeEpochMillis enhances type safety, and the fallback to DEFAULT_EXPIRATION_SECONDS ensures backward compatibility.

However, there's room for improvement in error handling during request parsing. Consider addressing this to provide better feedback to API consumers in case of malformed requests.

Overall, these changes align well with the PR's goals and enhance the flexibility of token management in the system.

crates/y-sweet-core/src/auth.rs (2)

102-102: LGTM! Consistent use of the new type.

The change in the Payload struct to use Option<ExpirationTimeEpochMillis> for the expiration_millis field is consistent with the introduction of the new type. This maintains the optional nature of the expiration time while improving type safety.


277-283: LGTM! Improved expiration check.

The changes to the verify method correctly incorporate the new ExpirationTimeEpochMillis type. The use of unwrap_or(ExpirationTimeEpochMillis::max()) is a clean and effective way to handle cases where no expiration time is specified.

crates/y-sweet-worker/src/lib.rs Outdated Show resolved Hide resolved
@@ -34,6 +34,19 @@ pub struct AuthDocRequest {
pub user_id: Option<String>,
#[serde(default)]
pub metadata: HashMap<String, Value>,
#[serde(skip_serializing_if = "Option::is_none", rename = "validForSeconds")]
pub valid_for_seconds: Option<u64>,
Copy link
Member

Choose a reason for hiding this comment

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

Even though this value doesn't exactly make sense in a Jamsocket context, I suppose we should at least allow it to be a part of the request body (and probably log if we see it, too)

Copy link
Member Author

Choose a reason for hiding this comment

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

If we expose the same parameter in Plane, we could make it work there, too. Plane has an equivalent internally.

Copy link
Member

Choose a reason for hiding this comment

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

@paulgb paulgb merged commit c3ab7a1 into main Oct 12, 2024
12 checks passed
@paulgb paulgb deleted the paulgb/add-validity-time-option-to-api branch October 12, 2024 13:25
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.

Allow the token validity time to be specified
2 participants