Skip to content

Handle token generation failures in auth flow#151

Merged
chipp merged 1 commit intomainfrom
address-jwt-issues
Feb 18, 2026
Merged

Handle token generation failures in auth flow#151
chipp merged 1 commit intomainfrom
address-jwt-issues

Conversation

@chipp
Copy link
Owner

@chipp chipp commented Feb 18, 2026

No description provided.

@chipp chipp enabled auto-merge February 18, 2026 08:37
@gemini-code-assist
Copy link

Summary of Changes

Hello @chipp, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness and reliability of the authentication flow by implementing comprehensive error handling for token generation and URL parsing. It ensures that the system can gracefully recover from failures, provide meaningful error responses to clients, and prevent unexpected crashes, thereby improving the overall stability of the web service.

Highlights

  • Robust Error Handling for Token Generation: Introduced a new TokenError enum to explicitly manage various failure scenarios during token creation and encoding, replacing previous .unwrap() calls with Result types for better error propagation.
  • Enhanced Authentication Flow Resilience: Modified the authorize and issue_token handlers to gracefully handle token generation failures, returning appropriate HTTP status codes (e.g., 400 Bad Request, 500 Internal Server Error) and logging detailed error messages.
  • Improved Token Expiration Logic: Adjusted the token validity check to use a strict greater-than comparison (>) for expiration timestamps, ensuring tokens are considered invalid precisely at their expiration time.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • bin/alisa/src/web_service/auth/authorize.rs
    • Imported error from log and TokenError from super::token.
    • Updated get_redirect_url_from_params to return a Result type.
    • Implemented error handling for get_redirect_url_from_params in the authorize function, returning BAD_REQUEST or INTERNAL_SERVER_ERROR on failure.
  • bin/alisa/src/web_service/auth/issue_token.rs
    • Imported error from log and TokenError from super::token.
    • Modified Response::success to return a Result<Response, TokenError>.
    • Added error handling for token issuance within the issue_token function, returning INTERNAL_SERVER_ERROR on token generation failures.
  • bin/alisa/src/web_service/auth/token.rs
    • Defined a new TokenError enum with InvalidExpiration and Encoding variants.
    • Implemented Display and std::error::Error traits for TokenError.
    • Changed the return type of create_token_with_expiration_in and related functions from String to Result<String, TokenError>.
    • Replaced .unwrap() calls with ? operator or .map_err() for error propagation during token creation.
    • Modified token expiration check from >= to > to ensure strict validity.
    • Added log::debug for token decoding failures.
    • Introduced a new test case to verify error handling for invalid token expiration.
    • Updated existing test cases to .unwrap() the create_token_with_expiration_in_with_secret_at calls.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request significantly enhances the robustness of the authentication service by replacing panics with proper Result-based error handling in the token generation flow. However, a high-severity Open Redirect vulnerability was identified in the authorize endpoint, where the redirect_uri provided by the user is not validated against an allow-list. This could lead to the leakage of authorization codes and must be addressed. Additionally, while the changes are consistently applied and tests updated, consider making the error handling even more idiomatic using the From trait to simplify error propagation.

Comment on lines +38 to +41
let mut url = match Url::parse(auth.redirect_uri.as_ref()) {
Ok(url) => url,
Err(_) => return Ok(None),
};

Choose a reason for hiding this comment

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

security-high high

The redirect_uri parameter is parsed and used as the base for a redirect without validation against an allow-list of trusted domains. This constitutes an Open Redirect vulnerability. An attacker can craft a malicious link that, once the user authenticates, redirects them to an attacker-controlled site, potentially leaking the authorization code and state parameters.

To remediate this, you should validate the redirect_uri against a list of allowed URIs, similar to the check performed in issue_token.rs.

Suggested change
let mut url = match Url::parse(auth.redirect_uri.as_ref()) {
Ok(url) => url,
Err(_) => return Ok(None),
};
let mut url = match Url::parse(auth.redirect_uri.as_ref()) {
Ok(url) if url.as_str() == "https://social.yandex.net/broker/redirect" => url,
_ => return Ok(None),
};

Comment on lines +20 to +35
#[derive(Debug)]
pub enum TokenError {
InvalidExpiration,
Encoding(jsonwebtoken::errors::Error),
}

impl fmt::Display for TokenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidExpiration => write!(f, "invalid token expiration"),
Self::Encoding(err) => write!(f, "token encoding failed: {err}"),
}
}
}

impl std::error::Error for TokenError {}

Choose a reason for hiding this comment

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

medium

For more idiomatic error handling, you can implement the From trait for jsonwebtoken::errors::Error. This will allow you to use the ? operator to automatically convert the error type at call sites.

After applying this suggestion, you can simplify the code at lines 129-134 to:

    encode(
        &header,
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )?
#[derive(Debug)]
pub enum TokenError {
    InvalidExpiration,
    Encoding(jsonwebtoken::errors::Error),
}

impl From<jsonwebtoken::errors::Error> for TokenError {
    fn from(err: jsonwebtoken::errors::Error) -> Self {
        Self::Encoding(err)
    }
}

impl fmt::Display for TokenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidExpiration => write!(f, "invalid token expiration"),
            Self::Encoding(err) => write!(f, "token encoding failed: {err}"),
        }
    }
}

impl std::error::Error for TokenError {}

@chipp chipp merged commit 4656392 into main Feb 18, 2026
6 checks passed
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.

1 participant