|
| 1 | +package jd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/hmac" |
| 6 | + "crypto/sha256" |
| 7 | + "encoding/base64" |
| 8 | + |
| 9 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 10 | + "github.com/aws/aws-sdk-go-v2/config" |
| 11 | + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" |
| 12 | + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" |
| 13 | + "golang.org/x/oauth2" |
| 14 | +) |
| 15 | + |
| 16 | +// CognitoClient defines the interface for Cognito Identity Provider operations. |
| 17 | +// This interface allows for mocking the AWS Cognito client in unit tests. |
| 18 | +type CognitoClient interface { |
| 19 | + InitiateAuth( |
| 20 | + ctx context.Context, |
| 21 | + params *cognitoidentityprovider.InitiateAuthInput, |
| 22 | + optFns ...func(*cognitoidentityprovider.Options), |
| 23 | + ) (*cognitoidentityprovider.InitiateAuthOutput, error) |
| 24 | +} |
| 25 | + |
| 26 | +// CognitoTokenSource provides a oath2 token that is used to authenticate with the Job Distributor. |
| 27 | +type CognitoTokenSource struct { |
| 28 | + // The Cognito authentication information |
| 29 | + auth CognitoAuth |
| 30 | + |
| 31 | + // The cached authentication result from Cognito |
| 32 | + authResult *types.AuthenticationResultType |
| 33 | + |
| 34 | + // The Cognito client interface for making API calls |
| 35 | + client CognitoClient |
| 36 | +} |
| 37 | + |
| 38 | +// CognitoAuth contains the Cognito authentication information required to generate a token from |
| 39 | +// Cognito. |
| 40 | +type CognitoAuth struct { |
| 41 | + AWSRegion string |
| 42 | + CognitoAppClientID string |
| 43 | + CognitoAppClientSecret string |
| 44 | + Username string |
| 45 | + Password string |
| 46 | +} |
| 47 | + |
| 48 | +// NewCognitoTokenSource creates a new CognitoTokenSource with the given CognitoAuth configuration. |
| 49 | +// If client is nil, a real AWS Cognito client will be created when Authenticate is called. |
| 50 | +func NewCognitoTokenSource(auth CognitoAuth) *CognitoTokenSource { |
| 51 | + return &CognitoTokenSource{ |
| 52 | + auth: auth, |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// Authenticate performs user authentication against AWS Cognito using the USER_PASSWORD_AUTH flow. |
| 57 | +// |
| 58 | +// Authentication results are cached in the authResult field and used by the Token() method |
| 59 | +// to provide OAuth2 access tokens without re-authenticating. |
| 60 | +func (c *CognitoTokenSource) Authenticate(ctx context.Context) error { |
| 61 | + // Create client if not already set (for production use) |
| 62 | + if c.client == nil { |
| 63 | + sdkConfig, err := config.LoadDefaultConfig(ctx, |
| 64 | + config.WithRegion(c.auth.AWSRegion), |
| 65 | + ) |
| 66 | + if err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + c.client = cognitoidentityprovider.NewFromConfig(sdkConfig) |
| 70 | + } |
| 71 | + |
| 72 | + // Authenticate the user |
| 73 | + input := &cognitoidentityprovider.InitiateAuthInput{ |
| 74 | + AuthFlow: types.AuthFlowTypeUserPasswordAuth, |
| 75 | + ClientId: aws.String(c.auth.CognitoAppClientID), |
| 76 | + AuthParameters: map[string]string{ |
| 77 | + "USERNAME": c.auth.Username, |
| 78 | + "PASSWORD": c.auth.Password, |
| 79 | + "SECRET_HASH": c.secretHash(), |
| 80 | + }, |
| 81 | + } |
| 82 | + |
| 83 | + output, err := c.client.InitiateAuth(ctx, input) |
| 84 | + if err != nil { |
| 85 | + return err |
| 86 | + } |
| 87 | + |
| 88 | + c.authResult = output.AuthenticationResult |
| 89 | + |
| 90 | + return nil |
| 91 | +} |
| 92 | + |
| 93 | +// Token retrieves an OAuth2 access token for authenticating with the Job Distributor service. |
| 94 | +// |
| 95 | +// This method implements a lazy loading pattern: |
| 96 | +// 1. If an authentication result is already cached, it returns the cached access token |
| 97 | +// 2. If no cached result exists, it automatically authenticates with AWS Cognito first |
| 98 | +// 3. Returns the access token wrapped in an oauth2.Token struct |
| 99 | +// |
| 100 | +// The method implements the oauth2.TokenSource interface, making it compatible with |
| 101 | +// standard OAuth2 client libraries and HTTP clients that support token sources. |
| 102 | +// |
| 103 | +// Note: This method uses context.Background() for authentication if no cached token exists. |
| 104 | +// For more control over authentication context and timeout behavior, consider calling |
| 105 | +// Authenticate() explicitly before calling Token(). |
| 106 | +// |
| 107 | +// Returns an OAuth2 token containing the Cognito access token |
| 108 | +func (c *CognitoTokenSource) Token() (*oauth2.Token, error) { |
| 109 | + if c.authResult == nil { |
| 110 | + if err := c.Authenticate(context.Background()); err != nil { |
| 111 | + return nil, err |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + return &oauth2.Token{ |
| 116 | + AccessToken: aws.ToString(c.authResult.AccessToken), |
| 117 | + }, nil |
| 118 | +} |
| 119 | + |
| 120 | +// secretHash computes the AWS Cognito secret hash required for authentication with app clients that have a client secret. |
| 121 | +// |
| 122 | +// The secret hash is calculated using HMAC-SHA256 with the following formula: |
| 123 | +// |
| 124 | +// HMAC-SHA256(ClientSecret, Username + ClientId) |
| 125 | +// |
| 126 | +// This method: |
| 127 | +// 1. Creates an HMAC-SHA256 hash using the Cognito app client secret as the key |
| 128 | +// 2. Constructs the message by concatenating the username and client ID |
| 129 | +// 3. Computes the HMAC hash of the message |
| 130 | +// 4. Returns the hash encoded as a base64 string |
| 131 | +// |
| 132 | +// The secret hash is required by AWS Cognito when the app client is configured with a client secret. |
| 133 | +// It provides an additional layer of security by ensuring that only clients with the correct secret |
| 134 | +// can authenticate users. |
| 135 | +// |
| 136 | +// Returns the computed secret hash as a base64-encoded string. |
| 137 | +func (c *CognitoTokenSource) secretHash() string { |
| 138 | + hmac := hmac.New(sha256.New, []byte(c.auth.CognitoAppClientSecret)) |
| 139 | + message := []byte(c.auth.Username + c.auth.CognitoAppClientID) |
| 140 | + hmac.Write(message) |
| 141 | + dataHmac := hmac.Sum(nil) |
| 142 | + |
| 143 | + return base64.StdEncoding.EncodeToString(dataHmac) |
| 144 | +} |
0 commit comments