Closed andrei-tyk closed 4 days ago
Here are some key observations to aid the review process:
โฑ๏ธ Estimated effort to review: 4 ๐ต๐ต๐ต๐ตโช |
๐งช PR contains tests |
๐ Security concerns Sensitive information exposure: The implementation includes direct handling of passwords which are sensitive data. Ensure that passwords are not logged or exposed in error messages. Consider implementing additional security measures such as encryption or secure storage mechanisms. |
โก Recommended focus areas for review Security Concern The implementation of password-based OAuth should ensure that sensitive data such as passwords are securely handled. The current implementation exposes the password in the source code, which could lead to security vulnerabilities. Data Exposure Passwords are included in the configuration struct which might get logged or exposed through debugging. Ensure that sensitive fields are omitted from logs and error messages. |
Explore these optional code suggestions:
Category | Suggestion | Score |
Possible bug |
Improve error handling in encryption and decryption to enhance robustness___ **Add error handling for potential failures in theencrypt and decrypt functions to prevent runtime panics.** [gateway/mw_oauth2_auth.go [64-73]](https://github.com/TykTechnologies/tyk/pull/6649/files#diff-a90347c3ad28f06a7bd1c5554ce63448774cb486cf4e9961af2323423ce8209dR64-R73) ```diff -decryptedToken := decrypt(getPaddedSecret(OAuthSpec.Gw), tokenString) -encryptedToken := encrypt(getPaddedSecret(OAuthSpec.Gw), token.AccessToken) +decryptedToken, err := decrypt(getPaddedSecret(OAuthSpec.Gw), tokenString) +if err != nil { + return "", err +} +encryptedToken, err := encrypt(getPaddedSecret(OAuthSpec.Gw), token.AccessToken) +if err != nil { + return "", err +} ``` Suggestion importance[1-10]: 9Why: Adding error handling for the encrypt and decrypt functions is a significant improvement. It prevents potential runtime panics and ensures that any issues during these operations are properly managed, enhancing the overall reliability of the code. | 9 |
Validate token expiry to prevent caching invalid tokens___ **Validate thetoken.Expiry to ensure it is a future timestamp before setting the TTL for the cache.** [gateway/mw_oauth2_auth.go [75-77]](https://github.com/TykTechnologies/tyk/pull/6649/files#diff-a90347c3ad28f06a7bd1c5554ce63448774cb486cf4e9961af2323423ce8209dR75-R77) ```diff +if token.Expiry.Before(time.Now()) { + return "", fmt.Errorf("invalid token expiry") +} ttl := time.Until(token.Expiry) if err := setTokenInCache(cacheKey, encryptedToken, ttl, &cache.RedisCluster); err != nil { return "", err } ``` Suggestion importance[1-10]: 8Why: This suggestion addresses a potential bug by ensuring that only tokens with a valid future expiry are cached. This prevents caching expired tokens, which could lead to authentication failures, thus improving the robustness of the token handling logic. | 8 | |
Performance |
Prevent excessive token requests by implementing rate limiting or caching___ **Implement rate limiting or caching mechanisms to avoid excessive token generationrequests, potentially leading to service abuse.** [gateway/mw_oauth2_auth.go [86]](https://github.com/TykTechnologies/tyk/pull/6649/files#diff-a90347c3ad28f06a7bd1c5554ce63448774cb486cf4e9961af2323423ce8209dR86-R86) ```diff -token, err := cfg.PasswordCredentialsToken(ctx, OAuthSpec.Spec.UpstreamAuth.OAuth.PasswordAuthentication.Username, OAuthSpec.Spec.UpstreamAuth.OAuth.PasswordAuthentication.Password) +// Implement rate limiting or use an existing token from cache if valid +token, err := checkCachedOrGenerateNewToken(ctx, cfg, OAuthSpec) ``` Suggestion importance[1-10]: 7Why: The suggestion to implement rate limiting or caching mechanisms is relevant for preventing service abuse and improving performance. However, the suggestion lacks specific implementation details, which slightly reduces its immediate applicability. | 7 |
API Changes
--- prev.txt 2024-10-24 08:03:14.636853821 +0000
+++ current.txt 2024-10-24 08:03:08.544815718 +0000
@@ -886,6 +886,9 @@
"client_credentials": {
"type": "object",
"properties": {
+ "enabled": {
+ "type": "boolean"
+ },
"client_id": {
"type": "string"
},
@@ -897,11 +900,41 @@
},
"scopes":{
"type": ["array", "null"]
- }
+ },
+ "header_name": {
+ "type": "string"
+ }
}
},
- "header_name": {
- "type": "string"
+ "password_authentication": {
+ "type": "object",
+ "properties": {
+ "enabled": {
+ "type": "boolean"
+ },
+ "client_id": {
+ "type": "string"
+ },
+ "client_secret": {
+ "type": "string"
+ },
+ "username": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ },
+ "token_url": {
+ "type": "string"
+ },
+ "scopes": {
+ "type": ["array", "null"]
+ },
+ "header_name": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -1218,11 +1251,16 @@
type ClientCredentials struct {
ClientAuthData
+ // Enabled activates upstream OAuth2 client credentials authentication.
+ Enabled bool `bson:"enabled" json:"enabled"`
// TokenURL is the resource server's token endpoint
// URL. This is a constant specific to each server.
TokenURL string `bson:"token_url" json:"token_url"`
// Scopes specifies optional requested permissions.
Scopes []string `bson:"scopes" json:"scopes,omitempty"`
+ // HeaderName is the custom header name to be used for OAuth client credential flow authentication.
+ // Defaults to `Authorization`.
+ HeaderName string `bson:"header_name" json:"header_name"`
// TokenProvider is the OAuth2 token provider for internal use.
TokenProvider oauth2.TokenSource `bson:"-" json:"-"`
@@ -1720,6 +1758,29 @@
SegregateByClient bool `bson:"segregate_by_client" json:"segregate_by_client"`
}
+type PasswordAuthentication struct {
+ ClientAuthData
+ // Enabled activates upstream OAuth2 password authentication.
+ Enabled bool `bson:"enabled" json:"enabled"`
+ // Username is the username to be used for upstream OAuth2 password authentication.
+ Username string `bson:"username" json:"username"`
+ // Password is the password to be used for upstream OAuth2 password authentication.
+ Password string `bson:"password" json:"password"`
+ // TokenURL is the resource server's token endpoint
+ // URL. This is a constant specific to each server.
+ TokenURL string `bson:"token_url" json:"token_url"`
+ // Scopes specifies optional requested permissions.
+ Scopes []string `bson:"scopes" json:"scopes,omitempty"`
+ // HeaderName is the custom header name to be used for OAuth password authentication flow.
+ // Defaults to `Authorization`.
+ HeaderName string `bson:"header_name" json:"header_name"`
+
+ // TokenProvider is the OAuth2 password authentication flow token for internal use.
+ Token *oauth2.Token `bson:"-" json:"-"`
+}
+ PasswordAuthentication holds the configuration for upstream OAuth2 password
+ authentication flow.
+
type PersistGraphQLMeta struct {
Path string `bson:"path" json:"path"`
Method string `bson:"method" json:"method"`
@@ -2082,9 +2143,8 @@
Enabled bool `bson:"enabled" json:"enabled"`
// ClientCredentials holds the client credentials for upstream OAuth2 authentication.
ClientCredentials ClientCredentials `bson:"client_credentials" json:"client_credentials"`
- // HeaderName is the custom header name to be used for upstream basic authentication.
- // Defaults to `Authorization`.
- HeaderName string `bson:"header_name" json:"header_name,omitempty"`
+ // PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
+ PasswordAuthentication PasswordAuthentication `bson:"password_authentication,omitempty" json:"passwordAuthentication,omitempty"`
}
UpstreamOAuth holds upstream OAuth2 authentication configuration.
@@ -3108,6 +3168,14 @@
func (cb *CircuitBreaker) Fill(circuitBreaker apidef.CircuitBreakerMeta)
Fill fills *CircuitBreaker from apidef.CircuitBreakerMeta.
+type ClientAuthData struct {
+ // ClientID is the application's ID.
+ ClientID string `bson:"clientId" json:"clientId"`
+ // ClientSecret is the application's secret.
+ ClientSecret string `bson:"clientSecret" json:"clientSecret"`
+}
+ ClientAuthData holds the client ID and secret for OAuth2 authentication.
+
type ClientCertificates struct {
// Enabled activates static mTLS for the API.
Enabled bool `bson:"enabled" json:"enabled"`
@@ -3124,15 +3192,17 @@
Fill fills *ClientCertificates from apidef.APIDefinition.
type ClientCredentials struct {
- // ClientID is the application's ID.
- ClientID string `bson:"clientID" json:"clientID"`
- // ClientSecret is the application's secret.
- ClientSecret string `bson:"clientSecret" json:"clientSecret"`
+ ClientAuthData
+ // Enabled activates upstream OAuth2 client credentials authentication.
+ Enabled bool `bson:"enabled" json:"enabled"`
// TokenURL is the resource server's token endpoint
// URL. This is a constant specific to each server.
TokenURL string `bson:"tokenURL" json:"tokenURL"`
// Scopes specifies optional requested permissions.
Scopes []string `bson:"scopes,omitempty" json:"scopes,omitempty"`
+ // HeaderName is the custom header name to be used for OAuth client credential flow authentication.
+ // Defaults to `Authorization`.
+ HeaderName string `bson:"headerName" json:"headerName"`
}
ClientCredentials holds the configuration for OAuth2 Client Credentials
flow.
@@ -4037,6 +4107,30 @@
type Operations map[string]*Operation
Operations holds Operation definitions.
+type PasswordAuthentication struct {
+ ClientAuthData
+ // Enabled activates upstream OAuth2 password authentication.
+ Enabled bool `bson:"enabled" json:"enabled"`
+ // Username is the username to be used for upstream OAuth2 password authentication.
+ Username string `bson:"username" json:"username"`
+ // Password is the password to be used for upstream OAuth2 password authentication.
+ Password string `bson:"password" json:"password"`
+ // TokenURL is the resource server's token endpoint
+ // URL. This is a constant specific to each server.
+ TokenURL string `bson:"tokenURL" json:"tokenURL"`
+ // Scopes specifies optional requested permissions.
+ Scopes []string `bson:"scopes" json:"scopes,omitempty"`
+ // HeaderName is the custom header name to be used for OAuth password authentication flow.
+ // Defaults to `Authorization`.
+ HeaderName string `bson:"headerName" json:"headerName"`
+}
+ PasswordAuthentication holds the configuration for upstream OAuth2 password
+ authentication flow.
+
+func (p *PasswordAuthentication) ExtractTo(api *apidef.PasswordAuthentication)
+
+func (p *PasswordAuthentication) Fill(api apidef.PasswordAuthentication)
+
type Path struct {
// Delete holds plugin configuration for DELETE requests.
Delete *Plugins `bson:"DELETE,omitempty" json:"DELETE,omitempty"`
@@ -4892,9 +4986,8 @@
Enabled bool `bson:"enabled" json:"enabled"`
// ClientCredentials holds the configuration for OAuth2 Client Credentials flow.
ClientCredentials *ClientCredentials `bson:"clientCredentials,omitempty" json:"clientCredentials,omitempty"`
- // HeaderName is the custom header name to be used for upstream basic authentication.
- // Defaults to `Authorization`.
- HeaderName string `bson:"headerName" json:"headerName"`
+ // PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
+ PasswordAuthentication *PasswordAuthentication `bson:"passwordAuthentication,omitempty" json:"passwordAuthentication,omitempty"`
}
UpstreamOAuth holds the configuration for OAuth2 Client Credentials flow.
@@ -9912,6 +10005,8 @@
func (k *OrganizationMonitor) SetOrgSentinel(orgChan chan bool, orgId string)
+type PasswordOAuthProvider struct{}
+
type PerAPIClientCredentialsOAuthProvider struct{}
type PersistGraphQLOperationMiddleware struct {
Issues
0 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code
User description
Ticket link: https://tyktech.atlassian.net/browse/TT-13185
Description
This PR implements an OAuth 2.0 authentication mechanism within the Tyk API Gateway, using the Password Flow to securely authenticate and authorize requests forwarded to the Upstream server. It involves configuring the Gateway to obtain, manage, and refresh access tokens, ensuring secure communication between the Gateway and the Upstream services.
Related Issue
This PR is related to the issue of enhancing security for the API Gateway, which previously forwarded requests directly to the Upstream server without authenticating itself. This introduces an OAuth 2.0 mechanism to address the security concerns. A Jira ticket has been created to track this issue.
Motivation and Context
The change is necessary to ensure that only authenticated requests reach the Upstream server. By implementing OAuth 2.0 Password Flow, the API Gateway will now authenticate itself before forwarding requests, securing communication between the Gateway and the Upstream server. This solves the problem of unauthorized requests being forwarded and strengthens overall security.
How This Has Been Tested
Unit tests have been written to verify the OAuth token retrieval, caching, and refresh mechanisms. The API Gateway was tested in an environment using a mock Upstream server protected by OAuth (using Keycloak). Simulated token expiration scenarios were tested to ensure the Gateway properly handles token refreshes and retries the request. Error handling scenarios were tested for cases such as invalid credentials or network failures. The Redis store was checked to verify that tokens are hashed (RSA256 - FIPS compliant) before being stored, and no token appears in the logs.
Screenshots (if appropriate)
Types of changes
Checklist
PR Type
Enhancement, Tests
Description
PasswordAuthentication
struct to configure OAuth2 password flow, including username, password, and token URL.PasswordOAuthProvider
to manage token retrieval and caching for password flow.Changes walkthrough ๐
api_definitions.go
Add OAuth2 Password Flow Configuration to API Definitions
apidef/api_definitions.go
PasswordAuthentication
struct for OAuth2 password flowconfiguration.
PasswordAuthentication
inUpstreamOAuth
.upstream.go
Extend Upstream OAuth to Support Password Authentication
apidef/oas/upstream.go
PasswordAuthentication
struct and methods.UpstreamOAuth
to support password authentication.mw_oauth2_auth.go
Implement OAuth2 Password Flow in Middleware
gateway/mw_oauth2_auth.go
PasswordOAuthProvider
for handling password flow.mw_oauth2_auth_test.go
Add Tests for OAuth2 Password Flow Implementation
gateway/mw_oauth2_auth_test.go