organize for inclusion

This commit is contained in:
jay brown
2025-04-01 15:34:35 -07:00
parent 11222646a5
commit 704c565d4d
4 changed files with 469 additions and 310 deletions
@@ -0,0 +1,327 @@
package main
// PKCE specific types and functions
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/labstack/echo/v4"
)
// CognitoTokenResponse represents the response from the token endpoint
// Returned by Cognito when exchanging an authorization code for tokens
type CognitoTokenResponse struct {
IDToken string `json:"id_token"` // OpenID Connect ID token containing user claims
AccessToken string `json:"access_token"` // OAuth2 access token for accessing resources
RefreshToken string `json:"refresh_token"` // Token used to get new access tokens without re-authentication
ExpiresIn int `json:"expires_in"` // Token validity period in seconds
TokenType string `json:"token_type"` // Type of token, typically "Bearer"
}
// PKCESession stores PKCE code verifier for verification
// We need to store the code verifier temporarily to use during token exchange
type PKCESession struct {
CodeVerifier string
CreatedAt time.Time
ExpiresAt time.Time
}
// Global map to store PKCE sessions by state parameter
// In a production environment, this should be replaced with a proper session store
var pkceSessionMap = struct {
sync.RWMutex
sessions map[string]*PKCESession
}{
sessions: make(map[string]*PKCESession),
}
// initiateLoginWithPKCE generates PKCE code challenge and redirects to Cognito
// This function starts the OAuth authorization flow with PKCE
func initiateLoginWithPKCE(c echo.Context, config *CognitoConfig, logger *slog.Logger) error {
// Generate random state parameter to prevent CSRF
state, err := generateRandomString(32)
if err != nil {
logger.Error("Failed to generate state parameter", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Authentication initialization failed"})
}
// Generate code verifier (random string between 43-128 chars)
codeVerifier, err := generateRandomString(64)
if err != nil {
logger.Error("Failed to generate code verifier", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Authentication initialization failed"})
}
// Create code challenge from verifier (SHA256 + Base64URL without padding)
codeChallenge := createCodeChallenge(codeVerifier)
// Store in session for later verification (with expiration time)
storePKCESession(state, codeVerifier, logger)
// Build authorization URL with PKCE parameters
params := url.Values{}
params.Set("client_id", config.ClientID)
params.Set("response_type", "code")
params.Set("redirect_uri", config.RedirectURI)
params.Set("scope", "openid email profile")
params.Set("state", state)
params.Set("code_challenge", codeChallenge)
params.Set("code_challenge_method", "S256")
authURL := fmt.Sprintf("%s?%s", config.AuthURL, params.Encode())
if os.Getenv("DEBUG") == "true" {
logger.Debug("Initiating login with PKCE",
"code_verifier", codeVerifier,
"code_challenge", codeChallenge,
"state", state,
"redirect_uri", config.RedirectURI)
}
// Redirect user to Cognito login page
return c.Redirect(http.StatusFound, authURL)
}
// createCodeChallenge creates a code challenge from a code verifier
// Implements S256 code challenge method as specified in PKCE RFC 7636
func createCodeChallenge(verifier string) string {
// Create SHA256 hash of the verifier
hash := sha256.Sum256([]byte(verifier))
// Base64URL encode the hash without padding
challenge := base64.RawURLEncoding.EncodeToString(hash[:])
return challenge
}
// generateRandomString creates a cryptographically secure random string
// Used for generating state parameter and code verifier
func generateRandomString(length int) (string, error) {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b)[:length], nil
}
// storePKCESession stores the PKCE session for later verification
// In a production environment, this should be replaced with a proper session store
func storePKCESession(state, codeVerifier string, logger *slog.Logger) {
pkceSessionMap.Lock()
defer pkceSessionMap.Unlock()
// Create new session with expiration (5 minutes is common)
session := &PKCESession{
CodeVerifier: codeVerifier,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(5 * time.Minute),
}
pkceSessionMap.sessions[state] = session
// Clean up expired sessions
for k, v := range pkceSessionMap.sessions {
if time.Now().After(v.ExpiresAt) {
logger.Debug("Cleaning up expired PKCE session", "state", k)
delete(pkceSessionMap.sessions, k)
}
}
}
// getCodeVerifier retrieves and validates the code verifier for a state
func getCodeVerifier(state string, logger *slog.Logger) (string, error) {
pkceSessionMap.RLock()
defer pkceSessionMap.RUnlock()
session, ok := pkceSessionMap.sessions[state]
if !ok {
return "", errors.New("no session found for state")
}
if time.Now().After(session.ExpiresAt) {
return "", errors.New("session expired")
}
return session.CodeVerifier, nil
}
// exchangeCodeForTokensWithPKCE exchanges the authorization code for tokens using PKCE
// Called during the OAuth callback flow to get tokens from the authorization code
// Makes an HTTP request to Cognito's token endpoint to perform this exchange
func exchangeCodeForTokensWithPKCE(authCode, codeVerifier string, config CognitoConfig, logger *slog.Logger) (*CognitoTokenResponse, error) {
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("client_id", config.ClientID)
data.Set("code", authCode)
data.Set("redirect_uri", config.RedirectURI)
data.Set("code_verifier", codeVerifier) // Include code verifier for PKCE
logger.Debug("Token request details",
"url", config.TokenURL,
"client_id", config.ClientID,
"redirect_uri", config.RedirectURI)
req, err := http.NewRequest("POST", config.TokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// Add Authorization header if client secret is provided
if config.ClientSecret != "" {
req.SetBasicAuth(config.ClientID, config.ClientSecret)
logger.Debug("Using Basic Auth authentication")
} else {
logger.Debug("Using public client authentication (no secret)")
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token endpoint returned status %d: %s", resp.StatusCode, string(body))
}
var tokenResponse CognitoTokenResponse
if err := json.Unmarshal(body, &tokenResponse); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResponse, nil
}
// handleOAuthCallback handles the OAuth 2.0 authorization code flow callback with PKCE
// Called when Cognito redirects back to our application with an authorization code
// Exchanges the code for tokens, verifies them, and redirects to home page with token in cookie
func handleOAuthCallback(c echo.Context, config *CognitoConfig, routePermissions map[string][]string, logger *slog.Logger) error {
// Extract the authorization code and state
code := c.QueryParam("code")
if code == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Missing code parameter"})
}
state := c.QueryParam("state")
if state == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Missing state parameter"})
}
// Check for OAuth errors
errorMsg := c.QueryParam("error")
if errorMsg != "" {
errorDesc := c.QueryParam("error_description")
return c.JSON(http.StatusBadRequest, map[string]string{
"error": errorMsg,
"error_description": errorDesc,
})
}
// Retrieve stored code verifier
codeVerifier, err := getCodeVerifier(state, logger)
if err != nil {
logger.Error("Failed to retrieve code verifier", "error", err, "state", state)
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid or expired session"})
}
// Exchange the code for tokens using PKCE
tokens, err := exchangeCodeForTokensWithPKCE(code, codeVerifier, *config, logger)
if err != nil {
logger.Error("Failed to exchange code for tokens", "error", err)
return c.JSON(http.StatusUnauthorized, map[string]string{"error": err.Error()})
}
// Get the JWKS for token verification
keySet, err := GetJWKS(config.JwksURL, logger)
if err != nil {
logger.Error("Failed to fetch JWKS", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to verify token"})
}
// Verify ID token
idTokenClaims, err := verifyToken(tokens.IDToken, keySet, *config)
if err != nil {
logger.Error("Failed to verify ID token", "error", err)
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid token"})
}
// Extract user groups
userGroups, err := GetUserGroups(idTokenClaims)
if err != nil {
logger.Warn("Failed to extract user groups", "error", err)
userGroups = []string{} // Initialize as empty array
}
// Debug logging for tokens
if os.Getenv("DEBUG") == "true" {
// Log decoded token for debugging
logger.Info("ID Token Claims", "claims", idTokenClaims)
logger.Info("Raw ID Token", "token", tokens.IDToken)
logger.Info("Raw Access Token", "token", tokens.AccessToken)
}
// Check authorization
authorized, requiredGroups := checkPermissions(LOGIN_CALLBACK_PATH, userGroups, routePermissions, logger)
if !authorized {
logger.Warn("OAuth callback - access denied",
"user", idTokenClaims["cognito:username"],
"groups", userGroups,
"required", requiredGroups)
return c.JSON(http.StatusForbidden, map[string]interface{}{
"error": "Insufficient permissions",
"message": "User authenticated successfully but doesn't have the required group membership",
"authenticated": true,
"username": idTokenClaims["cognito:username"],
"email": idTokenClaims["email"],
"groups": userGroups,
"required_groups": requiredGroups,
})
}
// User is authenticated and authorized
// Calculate token expiration time based on token's expires_in value
expiresAt := time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)
// Set a cookie with the access token
tokenCookie := new(http.Cookie)
tokenCookie.Name = "auth_token"
tokenCookie.Value = tokens.AccessToken
tokenCookie.Path = "/"
tokenCookie.Expires = expiresAt
tokenCookie.HttpOnly = true // Not accessible via JavaScript
// In production, set Secure to true
// tokenCookie.Secure = true
c.SetCookie(tokenCookie)
// Extract username for display purposes (optional)
username, _ := idTokenClaims["cognito:username"].(string)
logger.Info("User authenticated successfully", "username", username, "groups", userGroups)
// Redirect to home page
return c.Redirect(http.StatusFound, "/home")
}
@@ -0,0 +1,59 @@
# PKCE Session Management
`PKCESession` and `pkceSessionMap` are uses as part of implementing the Proof Key for Code Exchange (PKCE) flow for OAuth 2.0 authorization with Amazon Cognito.
## What PKCE is solving
PKCE extends the OAuth 2.0 authorization code flow to protect against authorization code interception attacks, which is particularly important for public clients (like browser-based apps) that can't securely store a client secret.
## Role of PKCESession and pkceSessionMap
The `PKCESession` and `pkceSessionMap` together implement a temporary storage mechanism that's critical for the PKCE workflow. Here's why they're necessary:
1. **Maintaining state across HTTP requests**: OAuth requires multiple HTTP redirects between your application and the identity provider (Cognito in this case). The code needs to remember information from the initial request when the callback happens later.
2. **Storing the code verifier**: In PKCE, the code verifier is a cryptographically random string generated at the start of the flow, but needed later when exchanging the authorization code for tokens.
## The exact flow and how they're used
Let's walk through how they're used in the code:
1. **Initial authentication request** (`initiateLoginWithPKCE` function):
- Generates a random `state` parameter to prevent CSRF attacks
- Generates a random `codeVerifier` string
- Creates a `codeChallenge` by hashing the verifier using SHA-256 and encoding it
- Stores the `codeVerifier` in the `pkceSessionMap` with the `state` as the key
- Sends the user to Cognito with the `codeChallenge` but NOT the `codeVerifier`
2. **Storage phase** (`storePKCESession` function):
- Creates a new `PKCESession` with the `codeVerifier`
- Sets an expiration time (5 minutes) to clean up if the flow isn't completed
- Stores it in the in-memory `pkceSessionMap` using the `state` as a key
- Also performs cleanup of expired sessions
3. **Callback handling** (`handleOAuthCallback` function):
- When Cognito redirects back with the authorization code and state
- Retrieves the previously stored `codeVerifier` using the `state` parameter from the query string
- Uses `getCodeVerifier` function to look up the session in the `pkceSessionMap`
- Verifies the session hasn't expired
4. **Token exchange** (`exchangeCodeForTokensWithPKCE` function):
- Sends the authorization code AND the original code verifier to Cognito
- Cognito verifies that the code verifier, when hashed, matches the code challenge it received earlier
- If valid, Cognito issues the tokens
- The app then validates these tokens and sets them as cookies
Without the `PKCESession` and `pkceSessionMap`, the application would have no way to remember the code verifier between the initial request and the callback, making it impossible to complete the PKCE flow.
## Security benefits
This approach:
1. Prevents authorization code interception attacks: Even if an attacker intercepts the authorization code, they can't exchange it for tokens without knowing the code verifier, which never leaves your server.
2. Protects against CSRF: The state parameter ensures the callback is responding to a request that your application initiated.
3. Ensures secure token issuance: Cognito will only issue tokens if the code verifier matches the challenge it received earlier.
The implementation in this code uses an in-memory map with locking for thread safety, though as noted in the comments, a production application would likely use a more robust session store (like Redis) especially in a distributed environment.
@@ -0,0 +1,83 @@
# JWKSCache
This cache is needed for efficient token validation in this OAuth 2.0 implementation with Amazon Cognito.
Below is how it's used and why its needed.
## Why the JWKSCache is needed
1. **Performance optimization**: Without caching, the application would need to fetch the JSON Web Key Set (JWKS) from Cognito's servers on every token validation, which would be inefficient and could lead to rate limiting.
2. **Reduced network dependency**: Caching reduces the application's dependency on network availability to the JWKS endpoint, making token validation more reliable.
3. **Lower latency**: Token validation happens faster with cached keys, improving overall application response time.
## Where and how JWKSCache is used
The JWKS cache is primarily used during JWT token validation. Here's the flow:
1. **Initialization**:
- A global `jwksCache` instance is created at the application level with an initially expired state.
```go
var jwksCache = &JWKSCache{
ExpiresAt: time.Now(), // Initial state is expired, forcing a fetch on first use
}
```
2. **Key retrieval** through the `GetJWKS` function:
- This function is called during token validation to get the public keys needed to verify token signatures.
- It's called from two main places:
- The `TokenValidationMiddleware` for API requests
- The `handleOAuthCallback` function during the OAuth callback
3. **Caching logic** in the `GetJWKS` function:
- First tries to read from cache using a read lock
- If keys are valid (not expired), returns them immediately
- If expired, acquires a write lock and fetches new keys
- Sets a 24-hour expiration time for the newly fetched keys
```go
func GetJWKS(jwksURL string, logger *slog.Logger) (jwk.Set, error) {
// Try to use cached JWKS first (read lock)
jwksCache.mutex.RLock()
if jwksCache.KeySet != nil && time.Now().Before(jwksCache.ExpiresAt) {
defer jwksCache.mutex.RUnlock()
logger.Debug("Using cached JWKS")
return jwksCache.KeySet, nil
}
jwksCache.mutex.RUnlock()
// Need to fetch new JWKS (write lock)
jwksCache.mutex.Lock()
defer jwksCache.mutex.Unlock()
// Double-check expiration after acquiring the write lock
if jwksCache.KeySet != nil && time.Now().Before(jwksCache.ExpiresAt) {
return jwksCache.KeySet, nil
}
// Fetch and store new key set...
}
```
4. **Actual token verification** in the `verifyToken` function:
- Uses the JWKS from the cache to verify the token's signature
- Validates claims like issuer and expiration
- Returns the token's claims if verification is successful
## Thread safety aspects
The implementation uses a read-write mutex (`sync.RWMutex`) to allow multiple readers but exclusive writers, following a common pattern for high-performance caching:
1. **Read lock** for cache hits: Many requests can read the cache simultaneously
2. **Write lock** for cache misses: Only one request updates the cache at a time
3. **Double-check pattern**: Rechecks expiration after acquiring the write lock to prevent multiple fetches
## Benefits in the application
In the application flow:
1. First request fetches the JWKS from Cognito and caches it
2. Subsequent requests use the cached keys
3. After 24 hours, a new request will trigger a refresh
4. If the network is temporarily unavailable, the application can still validate tokens using the cached keys
This caching is particularly important because the application validates tokens on every protected API request, making efficiency crucial for good performance.
-310
View File
@@ -2,16 +2,11 @@ package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"regexp"
"strings"
@@ -24,16 +19,6 @@ import (
"github.com/lestrrat-go/jwx/v2/jwt"
)
// CognitoTokenResponse represents the response from the token endpoint
// Returned by Cognito when exchanging an authorization code for tokens
type CognitoTokenResponse struct {
IDToken string `json:"id_token"` // OpenID Connect ID token containing user claims
AccessToken string `json:"access_token"` // OAuth2 access token for accessing resources
RefreshToken string `json:"refresh_token"` // Token used to get new access tokens without re-authentication
ExpiresIn int `json:"expires_in"` // Token validity period in seconds
TokenType string `json:"token_type"` // Type of token, typically "Bearer"
}
// CognitoConfig holds the configuration for AWS Cognito
// Contains all necessary parameters to interact with Cognito endpoints
type CognitoConfig struct {
@@ -46,23 +31,6 @@ type CognitoConfig struct {
ClientSecret string // Client secret for authenticated clients
}
// PKCESession stores PKCE code verifier for verification
// We need to store the code verifier temporarily to use during token exchange
type PKCESession struct {
CodeVerifier string
CreatedAt time.Time
ExpiresAt time.Time
}
// Global map to store PKCE sessions by state parameter
// In a production environment, this should be replaced with a proper session store
var pkceSessionMap = struct {
sync.RWMutex
sessions map[string]*PKCESession
}{
sessions: make(map[string]*PKCESession),
}
// JWKSCache caches the JWKS to avoid frequent fetches
// Implements a thread-safe caching mechanism with expiration
type JWKSCache struct {
@@ -215,7 +183,6 @@ func TokenValidationMiddleware(config *CognitoConfig, routePermissions map[strin
}
// JWTAuthMiddleware checks for JWT token in cookies and adds it to the Authorization header
// This middleware is simpler than full session management and aligns with JWT's stateless nature
func JWTAuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Skip for login and callback paths
@@ -300,283 +267,6 @@ func checkPermissions(path string, userGroups []string, routePermissions map[str
return false, requiredGroups
}
// initiateLoginWithPKCE generates PKCE code challenge and redirects to Cognito
// This function starts the OAuth authorization flow with PKCE
func initiateLoginWithPKCE(c echo.Context, config *CognitoConfig, logger *slog.Logger) error {
// Generate random state parameter to prevent CSRF
state, err := generateRandomString(32)
if err != nil {
logger.Error("Failed to generate state parameter", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Authentication initialization failed"})
}
// Generate code verifier (random string between 43-128 chars)
codeVerifier, err := generateRandomString(64)
if err != nil {
logger.Error("Failed to generate code verifier", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Authentication initialization failed"})
}
// Create code challenge from verifier (SHA256 + Base64URL without padding)
codeChallenge := createCodeChallenge(codeVerifier)
// Store in session for later verification (with expiration time)
storePKCESession(state, codeVerifier, logger)
// Build authorization URL with PKCE parameters
params := url.Values{}
params.Set("client_id", config.ClientID)
params.Set("response_type", "code")
params.Set("redirect_uri", config.RedirectURI)
params.Set("scope", "openid email profile")
params.Set("state", state)
params.Set("code_challenge", codeChallenge)
params.Set("code_challenge_method", "S256")
authURL := fmt.Sprintf("%s?%s", config.AuthURL, params.Encode())
if os.Getenv("DEBUG") == "true" {
logger.Debug("Initiating login with PKCE",
"code_verifier", codeVerifier,
"code_challenge", codeChallenge,
"state", state,
"redirect_uri", config.RedirectURI)
}
// Redirect user to Cognito login page
return c.Redirect(http.StatusFound, authURL)
}
// handleOAuthCallback handles the OAuth 2.0 authorization code flow callback with PKCE
// Called when Cognito redirects back to our application with an authorization code
// Exchanges the code for tokens, verifies them, and redirects to home page with token in cookie
func handleOAuthCallback(c echo.Context, config *CognitoConfig, routePermissions map[string][]string, logger *slog.Logger) error {
// Extract the authorization code and state
code := c.QueryParam("code")
if code == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Missing code parameter"})
}
state := c.QueryParam("state")
if state == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Missing state parameter"})
}
// Check for OAuth errors
errorMsg := c.QueryParam("error")
if errorMsg != "" {
errorDesc := c.QueryParam("error_description")
return c.JSON(http.StatusBadRequest, map[string]string{
"error": errorMsg,
"error_description": errorDesc,
})
}
// Retrieve stored code verifier
codeVerifier, err := getCodeVerifier(state, logger)
if err != nil {
logger.Error("Failed to retrieve code verifier", "error", err, "state", state)
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid or expired session"})
}
// Exchange the code for tokens using PKCE
tokens, err := exchangeCodeForTokensWithPKCE(code, codeVerifier, *config, logger)
if err != nil {
logger.Error("Failed to exchange code for tokens", "error", err)
return c.JSON(http.StatusUnauthorized, map[string]string{"error": err.Error()})
}
// Get the JWKS for token verification
keySet, err := GetJWKS(config.JwksURL, logger)
if err != nil {
logger.Error("Failed to fetch JWKS", "error", err)
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to verify token"})
}
// Verify ID token
idTokenClaims, err := verifyToken(tokens.IDToken, keySet, *config)
if err != nil {
logger.Error("Failed to verify ID token", "error", err)
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid token"})
}
// Extract user groups
userGroups, err := GetUserGroups(idTokenClaims)
if err != nil {
logger.Warn("Failed to extract user groups", "error", err)
userGroups = []string{} // Initialize as empty array
}
// Debug logging for tokens
if os.Getenv("DEBUG") == "true" {
// Log decoded token for debugging
logger.Info("ID Token Claims", "claims", idTokenClaims)
logger.Info("Raw ID Token", "token", tokens.IDToken)
logger.Info("Raw Access Token", "token", tokens.AccessToken)
}
// Check authorization
authorized, requiredGroups := checkPermissions(LOGIN_CALLBACK_PATH, userGroups, routePermissions, logger)
if !authorized {
logger.Warn("OAuth callback - access denied",
"user", idTokenClaims["cognito:username"],
"groups", userGroups,
"required", requiredGroups)
return c.JSON(http.StatusForbidden, map[string]interface{}{
"error": "Insufficient permissions",
"message": "User authenticated successfully but doesn't have the required group membership",
"authenticated": true,
"username": idTokenClaims["cognito:username"],
"email": idTokenClaims["email"],
"groups": userGroups,
"required_groups": requiredGroups,
})
}
// User is authenticated and authorized
// Calculate token expiration time based on token's expires_in value
expiresAt := time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)
// Set a cookie with the access token
tokenCookie := new(http.Cookie)
tokenCookie.Name = "auth_token"
tokenCookie.Value = tokens.AccessToken
tokenCookie.Path = "/"
tokenCookie.Expires = expiresAt
tokenCookie.HttpOnly = true // Not accessible via JavaScript
// In production, set Secure to true
// tokenCookie.Secure = true
c.SetCookie(tokenCookie)
// Extract username for display purposes (optional)
username, _ := idTokenClaims["cognito:username"].(string)
logger.Info("User authenticated successfully", "username", username, "groups", userGroups)
// Redirect to home page
return c.Redirect(http.StatusFound, "/home")
}
// generateRandomString creates a cryptographically secure random string
// Used for generating state parameter and code verifier
func generateRandomString(length int) (string, error) {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b)[:length], nil
}
// createCodeChallenge creates a code challenge from a code verifier
// Implements S256 code challenge method as specified in PKCE RFC 7636
func createCodeChallenge(verifier string) string {
// Create SHA256 hash of the verifier
hash := sha256.Sum256([]byte(verifier))
// Base64URL encode the hash without padding
challenge := base64.RawURLEncoding.EncodeToString(hash[:])
return challenge
}
// storePKCESession stores the PKCE session for later verification
// In a production environment, this should be replaced with a proper session store
func storePKCESession(state, codeVerifier string, logger *slog.Logger) {
pkceSessionMap.Lock()
defer pkceSessionMap.Unlock()
// Create new session with expiration (5 minutes is common)
session := &PKCESession{
CodeVerifier: codeVerifier,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(5 * time.Minute),
}
pkceSessionMap.sessions[state] = session
// Clean up expired sessions
for k, v := range pkceSessionMap.sessions {
if time.Now().After(v.ExpiresAt) {
logger.Debug("Cleaning up expired PKCE session", "state", k)
delete(pkceSessionMap.sessions, k)
}
}
}
// getCodeVerifier retrieves and validates the code verifier for a state
func getCodeVerifier(state string, logger *slog.Logger) (string, error) {
pkceSessionMap.RLock()
defer pkceSessionMap.RUnlock()
session, ok := pkceSessionMap.sessions[state]
if !ok {
return "", errors.New("no session found for state")
}
if time.Now().After(session.ExpiresAt) {
return "", errors.New("session expired")
}
return session.CodeVerifier, nil
}
// exchangeCodeForTokensWithPKCE exchanges the authorization code for tokens using PKCE
// Called during the OAuth callback flow to get tokens from the authorization code
// Makes an HTTP request to Cognito's token endpoint to perform this exchange
func exchangeCodeForTokensWithPKCE(authCode, codeVerifier string, config CognitoConfig, logger *slog.Logger) (*CognitoTokenResponse, error) {
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("client_id", config.ClientID)
data.Set("code", authCode)
data.Set("redirect_uri", config.RedirectURI)
data.Set("code_verifier", codeVerifier) // Include code verifier for PKCE
logger.Debug("Token request details",
"url", config.TokenURL,
"client_id", config.ClientID,
"redirect_uri", config.RedirectURI)
req, err := http.NewRequest("POST", config.TokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// Add Authorization header if client secret is provided
if config.ClientSecret != "" {
req.SetBasicAuth(config.ClientID, config.ClientSecret)
logger.Debug("Using Basic Auth authentication")
} else {
logger.Debug("Using public client authentication (no secret)")
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token endpoint returned status %d: %s", resp.StatusCode, string(body))
}
var tokenResponse CognitoTokenResponse
if err := json.Unmarshal(body, &tokenResponse); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResponse, nil
}
// verifyToken verifies the JWT token and returns its claims
// Used during both OAuth callback and subsequent API requests with bearer token
// Verifies signature, expiration, issuer, and other JWT claims