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

TT-13271, fix for token metadata not being cached #6689

Merged
merged 5 commits into from
Nov 1, 2024

Conversation

andrei-tyk
Copy link
Contributor

@andrei-tyk andrei-tyk commented Nov 1, 2024

User description

Currently when the token is cached into redis we are not cacheing the extra metadata so only the initial request gets populated with the requiered fields.

TT-13271
Summary Add support for custom OAuth server response fields
Type Story Story
Status Ready for Testing
Points N/A
Labels -

Description

Related Issue

Motivation and Context

How This Has Been Tested

Screenshots (if appropriate)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date
  • I explained why this PR updates go.mod in detail with reasoning why it's required
  • I would like a code coverage CI quality gate exception and have explained why

PR Type

enhancement, bug fix


Description

  • Introduced a new TokenData struct to encapsulate token and extra metadata, improving the structure and readability of the code.
  • Added functions createTokenDataBytes and unmarshalTokenData to handle JSON marshaling and unmarshaling of token data, enhancing the robustness of data handling.
  • Modified the caching mechanism to store both token and metadata, ensuring that metadata is preserved and accessible when retrieving tokens from the cache.
  • Improved the handling of extra metadata by using a map, allowing for more flexible and efficient metadata management.

Changes walkthrough 📝

Relevant files
Enhancement
mw_oauth2_auth.go
Improve token caching and metadata handling in OAuth2       

gateway/mw_oauth2_auth.go

  • Introduced a new TokenData struct to handle token and metadata.
  • Added functions to marshal and unmarshal token data.
  • Modified caching logic to store and retrieve token data with metadata.
  • Enhanced metadata handling by using a map for extra metadata.
  • +85/-17 

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    @buger
    Copy link
    Member

    buger commented Nov 1, 2024

    Knock Knock! 🔍

    Just thought I'd let you know that your PR title and story title look quite different. PR titles that closely resemble the story title make it easier for reviewers to understand the context of the PR.

    An easy-to-understand PR title a day makes the reviewer review away! 😛⚡️
    Story Title Add support for custom OAuth server response fields
    PR Title TT-13271, fix for token metadata not being cached

    Check out this guide to learn more about PR best-practices.

    Copy link
    Contributor

    github-actions bot commented Nov 1, 2024

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Redundant Check
    The check for non-empty tokenData is repeated unnecessarily, which could be simplified to improve code readability and performance.

    Error Handling
    The error from 'retryGetKeyAndLock' function is not handled immediately after the function call, which might lead to handling errors that are not related to the key retrieval.

    Potential Bug
    The function 'setExtraMetadata' modifies the request context directly, which could lead to race conditions or unexpected behavior in concurrent environments.

    Copy link
    Contributor

    github-actions bot commented Nov 1, 2024

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Enhancement
    Remove redundant condition checks to simplify the code logic

    Remove the redundant inner check for tokenData != "" as it is already checked by the
    outer condition.

    gateway/mw_oauth2_auth.go [66-67]

     if tokenData != "" {
    -    if tokenData != "" {
    -        tokenContents, err := unmarshalTokenData(tokenData)
    -        ...
    +    tokenContents, err := unmarshalTokenData(tokenData)
    +    ...
    Suggestion importance[1-10]: 8

    Why: The suggestion correctly identifies and removes a redundant inner check for tokenData != "", simplifying the code logic without altering functionality.

    8
    Add detailed error handling for token retrieval to enhance debugging and error tracking

    Ensure error handling is added after obtaining the token data to handle possible
    failures in retryGetKeyAndLock.

    gateway/mw_oauth2_auth.go [61-63]

     tokenData, err := retryGetKeyAndLock(cacheKey, &cache.RedisCluster)
     if err != nil {
    -    return "", err
    +    return "", fmt.Errorf("error retrieving token data: %w", err)
     }
    Suggestion importance[1-10]: 7

    Why: The suggestion enhances error handling by providing a more descriptive error message, which can aid in debugging and tracking issues related to token retrieval.

    7
    Possible bug
    Add nil check for byte slice to prevent potential runtime errors

    Validate tokenDataBytes for nil before converting to string to prevent potential
    runtime panics.

    gateway/mw_oauth2_auth.go [84-85]

     tokenDataBytes, err := createTokenDataBytes(encryptedToken, token, OAuthSpec.Spec.UpstreamAuth.OAuth.PasswordAuthentication.ExtraMetadata)
     if err != nil {
         return "", err
     }
    +if tokenDataBytes == nil {
    +    return "", fmt.Errorf("token data bytes are nil")
    +}
    Suggestion importance[1-10]: 6

    Why: The suggestion adds a nil check for tokenDataBytes, which could prevent potential runtime errors, although the likelihood of createTokenDataBytes returning nil should be assessed.

    6

    Copy link
    Contributor

    github-actions bot commented Nov 1, 2024

    API Changes

    --- prev.txt	2024-11-01 11:44:59.856077740 +0000
    +++ current.txt	2024-11-01 11:44:53.239953337 +0000
    @@ -11374,6 +11374,11 @@
     	Form    map[string]string
     }
     
    +type TokenData struct {
    +	Token         string                 `json:"token"`
    +	ExtraMetadata map[string]interface{} `json:"extra_metadata"`
    +}
    +
     type TraceMiddleware struct {
     	TykMiddleware
     }

    Copy link

    sonarcloud bot commented Nov 1, 2024

    Quality Gate Failed Quality Gate failed

    Failed conditions
    0.0% Coverage on New Code (required ≥ 80%)

    See analysis details on SonarCloud

    @andrei-tyk andrei-tyk merged commit 85e8a94 into master Nov 1, 2024
    34 of 40 checks passed
    @andrei-tyk andrei-tyk deleted the TT-13271-fix-for-cacheing branch November 1, 2024 12:09
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants