|
| 1 | +package manager |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "net" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/golang-jwt/jwt/v5" |
| 11 | + "github.com/redis-developer/go-redis-entraid/shared" |
| 12 | + "github.com/redis-developer/go-redis-entraid/token" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + DefaultExpirationRefreshRatio = 0.7 |
| 17 | + DefaultRetryOptionsMaxAttempts = 3 |
| 18 | + DefaultRetryOptionsInitialDelayMs = 1000 |
| 19 | + DefaultRetryOptionsBackoffMultiplier = 2.0 |
| 20 | + DefaultRetryOptionsMaxDelayMs = 10000 |
| 21 | +) |
| 22 | + |
| 23 | +// defaultIsRetryable is a function that checks if the error is retriable. |
| 24 | +// It takes an error as an argument and returns a boolean value. |
| 25 | +// The function checks if the error is a net.Error and if it is a timeout or temporary error. |
| 26 | +// Returns true for nil errors. |
| 27 | +var defaultIsRetryable = func(err error) bool { |
| 28 | + if err == nil { |
| 29 | + return true |
| 30 | + } |
| 31 | + |
| 32 | + var netErr net.Error |
| 33 | + if errors.As(err, &netErr) { |
| 34 | + // Check for timeout first as it's more specific |
| 35 | + if netErr.Timeout() { |
| 36 | + return true |
| 37 | + } |
| 38 | + // For temporary errors, we'll use a more modern approach |
| 39 | + var tempErr interface{ Temporary() bool } |
| 40 | + if errors.As(err, &tempErr) { |
| 41 | + return tempErr.Temporary() |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return errors.Is(err, os.ErrDeadlineExceeded) |
| 46 | +} |
| 47 | + |
| 48 | +// defaultRetryOptionsOr returns the default retry options if the provided options are not set. |
| 49 | +// It sets the maximum number of attempts, initial delay, maximum delay, and backoff multiplier. |
| 50 | +// The default values are 3 attempts, 1000 ms initial delay, 10000 ms maximum delay, and 2.0 backoff multiplier. |
| 51 | +// The values can be overridden by the user. |
| 52 | +func defaultRetryOptionsOr(retryOptions RetryOptions) RetryOptions { |
| 53 | + if retryOptions.IsRetryable == nil { |
| 54 | + retryOptions.IsRetryable = defaultIsRetryable |
| 55 | + } |
| 56 | + |
| 57 | + if retryOptions.MaxAttempts <= 0 { |
| 58 | + retryOptions.MaxAttempts = DefaultRetryOptionsMaxAttempts |
| 59 | + } |
| 60 | + if retryOptions.InitialDelayMs == 0 { |
| 61 | + retryOptions.InitialDelayMs = DefaultRetryOptionsInitialDelayMs |
| 62 | + } |
| 63 | + if retryOptions.BackoffMultiplier == 0 { |
| 64 | + retryOptions.BackoffMultiplier = DefaultRetryOptionsBackoffMultiplier |
| 65 | + } |
| 66 | + if retryOptions.MaxDelayMs == 0 { |
| 67 | + retryOptions.MaxDelayMs = DefaultRetryOptionsMaxDelayMs |
| 68 | + } |
| 69 | + return retryOptions |
| 70 | +} |
| 71 | + |
| 72 | +// defaultIdentityProviderResponseParserOr returns the default token parser if the provided token parser is not set. |
| 73 | +// It sets the default token parser to the defaultIdentityProviderResponseParser function. |
| 74 | +// The default token parser is used to parse the raw token and return a Token object. |
| 75 | +func defaultIdentityProviderResponseParserOr(idpResponseParser shared.IdentityProviderResponseParser) shared.IdentityProviderResponseParser { |
| 76 | + if idpResponseParser == nil { |
| 77 | + return &defaultIdentityProviderResponseParser{} |
| 78 | + } |
| 79 | + return idpResponseParser |
| 80 | +} |
| 81 | + |
| 82 | +func defaultTokenManagerOptionsOr(options TokenManagerOptions) TokenManagerOptions { |
| 83 | + options.RetryOptions = defaultRetryOptionsOr(options.RetryOptions) |
| 84 | + options.IdentityProviderResponseParser = defaultIdentityProviderResponseParserOr(options.IdentityProviderResponseParser) |
| 85 | + if options.ExpirationRefreshRatio == 0 { |
| 86 | + options.ExpirationRefreshRatio = DefaultExpirationRefreshRatio |
| 87 | + } |
| 88 | + return options |
| 89 | +} |
| 90 | + |
| 91 | +type defaultIdentityProviderResponseParser struct{} |
| 92 | + |
| 93 | +// ParseResponse parses the response from the identity provider and extracts the token. |
| 94 | +// It takes an IdentityProviderResponse as an argument and returns a Token and an error if any. |
| 95 | +// The IdentityProviderResponse contains the raw token and the expiration time. |
| 96 | +func (*defaultIdentityProviderResponseParser) ParseResponse(response shared.IdentityProviderResponse) (*token.Token, error) { |
| 97 | + if response == nil { |
| 98 | + return nil, fmt.Errorf("identity provider response cannot be nil") |
| 99 | + } |
| 100 | + |
| 101 | + var username, password, rawToken string |
| 102 | + var expiresOn time.Time |
| 103 | + now := time.Now().UTC() |
| 104 | + |
| 105 | + switch response.Type() { |
| 106 | + case shared.ResponseTypeAuthResult: |
| 107 | + authResult := response.AuthResult() |
| 108 | + if authResult.ExpiresOn.IsZero() { |
| 109 | + return nil, fmt.Errorf("auth result expiration time is not set") |
| 110 | + } |
| 111 | + if authResult.IDToken.Oid == "" { |
| 112 | + return nil, fmt.Errorf("auth result OID is empty") |
| 113 | + } |
| 114 | + rawToken = authResult.IDToken.RawToken |
| 115 | + username = authResult.IDToken.Oid |
| 116 | + password = rawToken |
| 117 | + expiresOn = authResult.ExpiresOn.UTC() |
| 118 | + |
| 119 | + case shared.ResponseTypeRawToken, shared.ResponseTypeAccessToken: |
| 120 | + tokenStr := response.RawToken() |
| 121 | + |
| 122 | + if response.Type() == shared.ResponseTypeAccessToken { |
| 123 | + accessToken := response.AccessToken() |
| 124 | + if accessToken.Token == "" { |
| 125 | + return nil, fmt.Errorf("access token value is empty") |
| 126 | + } |
| 127 | + tokenStr = accessToken.Token |
| 128 | + expiresOn = accessToken.ExpiresOn.UTC() |
| 129 | + } |
| 130 | + |
| 131 | + if tokenStr == "" { |
| 132 | + return nil, fmt.Errorf("raw token is empty") |
| 133 | + } |
| 134 | + |
| 135 | + claims := struct { |
| 136 | + jwt.RegisteredClaims |
| 137 | + Oid string `json:"oid,omitempty"` |
| 138 | + }{} |
| 139 | + |
| 140 | + // Parse the token to extract claims, but note that signature verification |
| 141 | + // should be handled by the identity provider |
| 142 | + _, _, err := jwt.NewParser().ParseUnverified(tokenStr, &claims) |
| 143 | + if err != nil { |
| 144 | + return nil, fmt.Errorf("failed to parse JWT token: %w", err) |
| 145 | + } |
| 146 | + |
| 147 | + if claims.Oid == "" { |
| 148 | + return nil, fmt.Errorf("JWT token does not contain OID claim") |
| 149 | + } |
| 150 | + |
| 151 | + rawToken = tokenStr |
| 152 | + username = claims.Oid |
| 153 | + password = rawToken |
| 154 | + |
| 155 | + if expiresOn.IsZero() && claims.ExpiresAt != nil { |
| 156 | + expiresOn = claims.ExpiresAt.UTC() |
| 157 | + } |
| 158 | + |
| 159 | + default: |
| 160 | + return nil, fmt.Errorf("unsupported response type: %s", response.Type()) |
| 161 | + } |
| 162 | + |
| 163 | + if expiresOn.IsZero() { |
| 164 | + return nil, fmt.Errorf("token expiration time is not set") |
| 165 | + } |
| 166 | + |
| 167 | + if expiresOn.Before(now) { |
| 168 | + return nil, fmt.Errorf("token has expired at %s (current time: %s)", expiresOn, now) |
| 169 | + } |
| 170 | + |
| 171 | + // Create the token with consistent time reference |
| 172 | + return token.New( |
| 173 | + username, |
| 174 | + password, |
| 175 | + rawToken, |
| 176 | + expiresOn, |
| 177 | + now, |
| 178 | + int64(time.Until(expiresOn).Seconds()), |
| 179 | + ), nil |
| 180 | +} |
0 commit comments