|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/dgellow/mcp-front/internal" |
| 13 | + "github.com/dgellow/mcp-front/internal/crypto" |
| 14 | + "github.com/dgellow/mcp-front/internal/log" |
| 15 | + "github.com/dgellow/mcp-front/internal/storage" |
| 16 | + "github.com/ory/fosite" |
| 17 | + "github.com/ory/fosite/compose" |
| 18 | +) |
| 19 | + |
| 20 | +// userContextKey is the context key for user email |
| 21 | +const userContextKey contextKey = "user_email" |
| 22 | + |
| 23 | +// GetUserFromContext extracts user email from context |
| 24 | +func GetUserFromContext(ctx context.Context) (string, bool) { |
| 25 | + email, ok := ctx.Value(userContextKey).(string) |
| 26 | + return email, ok |
| 27 | +} |
| 28 | + |
| 29 | +// GetUserContextKey returns the context key for user email (for testing) |
| 30 | +func GetUserContextKey() contextKey { |
| 31 | + return userContextKey |
| 32 | +} |
| 33 | + |
| 34 | +// Server wraps fosite.OAuth2Provider with clean architecture |
| 35 | +type Server struct { |
| 36 | + provider fosite.OAuth2Provider |
| 37 | + storage storage.Storage |
| 38 | + authService *authService |
| 39 | + config Config |
| 40 | + sessionEncryptor crypto.Encryptor // Created once for browser SSO performance |
| 41 | +} |
| 42 | + |
| 43 | +// Config holds OAuth server configuration |
| 44 | +type Config struct { |
| 45 | + Issuer string |
| 46 | + TokenTTL time.Duration |
| 47 | + SessionDuration time.Duration // Duration for browser session cookies (default: 24h) |
| 48 | + AllowedDomains []string |
| 49 | + AllowedOrigins []string // For CORS validation |
| 50 | + GoogleClientID string |
| 51 | + GoogleClientSecret string |
| 52 | + GoogleRedirectURI string |
| 53 | + JWTSecret string // Should be provided via environment variable |
| 54 | + EncryptionKey string // Should be provided via environment variable |
| 55 | + StorageType string // "memory" or "firestore" |
| 56 | + GCPProjectID string // Required for firestore storage |
| 57 | + FirestoreDatabase string // Optional: Firestore database name (default: "(default)") |
| 58 | + FirestoreCollection string // Optional: Collection name for Firestore storage (default: "mcp_front_oauth_clients") |
| 59 | +} |
| 60 | + |
| 61 | +// NewServer creates a new OAuth 2.1 server |
| 62 | +func NewServer(config Config, store storage.Storage) (*Server, error) { |
| 63 | + // Create session encryptor for browser SSO |
| 64 | + key := []byte(string(config.EncryptionKey)) |
| 65 | + sessionEncryptor, err := crypto.NewEncryptor(key) |
| 66 | + if err != nil { |
| 67 | + return nil, fmt.Errorf("failed to create session encryptor: %w", err) |
| 68 | + } |
| 69 | + log.Logf("Session encryptor initialized for browser SSO") |
| 70 | + |
| 71 | + // Create auth service (business logic) |
| 72 | + authService, err := newAuthService(config) |
| 73 | + if err != nil { |
| 74 | + return nil, fmt.Errorf("failed to create auth service: %w", err) |
| 75 | + } |
| 76 | + |
| 77 | + // Use provided JWT secret or generate a secure one |
| 78 | + var secret []byte |
| 79 | + if config.JWTSecret != "" { |
| 80 | + secret = []byte(string(config.JWTSecret)) |
| 81 | + // Validate JWT secret length for HMAC-SHA512/256 |
| 82 | + if len(secret) < 32 { |
| 83 | + return nil, fmt.Errorf("JWT secret must be at least 32 bytes long for security, got %d bytes", len(secret)) |
| 84 | + } |
| 85 | + } else { |
| 86 | + secret = make([]byte, 32) |
| 87 | + if _, err := rand.Read(secret); err != nil { |
| 88 | + return nil, fmt.Errorf("failed to generate JWT secret: %w", err) |
| 89 | + } |
| 90 | + log.LogWarn("Generated random JWT secret. Set JWT_SECRET env var for persistent tokens across restarts") |
| 91 | + } |
| 92 | + |
| 93 | + // Determine min parameter entropy based on environment |
| 94 | + minEntropy := 8 // Production default - enforce secure state parameters (8+ chars) |
| 95 | + log.Logf("OAuth server initialization - MCP_FRONT_ENV=%s, isDevelopmentMode=%v", os.Getenv("MCP_FRONT_ENV"), internal.IsDevelopmentMode()) |
| 96 | + if internal.IsDevelopmentMode() { |
| 97 | + minEntropy = 0 // Development mode - allow empty state parameters |
| 98 | + log.LogWarn("Development mode enabled - OAuth security checks relaxed (state parameter entropy: %d)", minEntropy) |
| 99 | + } |
| 100 | + |
| 101 | + // Configure fosite |
| 102 | + oauthConfig := &compose.Config{ |
| 103 | + AccessTokenLifespan: config.TokenTTL, |
| 104 | + RefreshTokenLifespan: config.TokenTTL * 2, |
| 105 | + AuthorizeCodeLifespan: 10 * time.Minute, |
| 106 | + MinParameterEntropy: minEntropy, |
| 107 | + EnforcePKCE: true, |
| 108 | + ScopeStrategy: fosite.HierarchicScopeStrategy, |
| 109 | + AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy, |
| 110 | + HashCost: 12, |
| 111 | + } |
| 112 | + |
| 113 | + // Create provider using compose |
| 114 | + provider := compose.ComposeAllEnabled( |
| 115 | + oauthConfig, |
| 116 | + store, |
| 117 | + secret, |
| 118 | + nil, // RSA key not needed for our use case |
| 119 | + ) |
| 120 | + |
| 121 | + return &Server{ |
| 122 | + provider: provider, |
| 123 | + storage: store, |
| 124 | + authService: authService, |
| 125 | + config: config, |
| 126 | + sessionEncryptor: sessionEncryptor, |
| 127 | + }, nil |
| 128 | +} |
| 129 | + |
| 130 | +// GetProvider returns the fosite OAuth2Provider |
| 131 | +func (s *Server) GetProvider() fosite.OAuth2Provider { |
| 132 | + return s.provider |
| 133 | +} |
| 134 | + |
| 135 | +// GetStorage returns the storage instance |
| 136 | +func (s *Server) GetStorage() storage.Storage { |
| 137 | + return s.storage |
| 138 | +} |
| 139 | + |
| 140 | +// GetAuthService returns the auth service |
| 141 | +func (s *Server) GetAuthService() *authService { |
| 142 | + return s.authService |
| 143 | +} |
| 144 | + |
| 145 | +// GetConfig returns the server configuration |
| 146 | +func (s *Server) GetConfig() Config { |
| 147 | + return s.config |
| 148 | +} |
| 149 | + |
| 150 | +// GetSessionEncryptor returns the session encryptor |
| 151 | +func (s *Server) GetSessionEncryptor() crypto.Encryptor { |
| 152 | + return s.sessionEncryptor |
| 153 | +} |
| 154 | + |
| 155 | +// ValidateTokenMiddleware creates middleware that validates OAuth tokens |
| 156 | +func (s *Server) ValidateTokenMiddleware() func(http.Handler) http.Handler { |
| 157 | + return func(next http.Handler) http.Handler { |
| 158 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 159 | + ctx := r.Context() |
| 160 | + |
| 161 | + // Extract token from Authorization header |
| 162 | + auth := r.Header.Get("Authorization") |
| 163 | + if auth == "" { |
| 164 | + http.Error(w, "Missing authorization header", http.StatusUnauthorized) |
| 165 | + return |
| 166 | + } |
| 167 | + |
| 168 | + parts := strings.Split(auth, " ") |
| 169 | + if len(parts) != 2 || parts[0] != "Bearer" { |
| 170 | + http.Error(w, "Invalid authorization header format", http.StatusUnauthorized) |
| 171 | + return |
| 172 | + } |
| 173 | + |
| 174 | + token := parts[1] |
| 175 | + |
| 176 | + // Validate token and extract session |
| 177 | + // IMPORTANT: Fosite's IntrospectToken behavior is non-intuitive: |
| 178 | + // - The session parameter passed to IntrospectToken is NOT populated with data |
| 179 | + // - This is documented fosite behavior, not a bug |
| 180 | + // - The actual session data must be retrieved from the returned AccessRequester |
| 181 | + // See: https://github.com/ory/fosite/issues/256 |
| 182 | + session := &Session{DefaultSession: &fosite.DefaultSession{}} |
| 183 | + _, accessRequest, err := s.provider.IntrospectToken(ctx, token, fosite.AccessToken, session) |
| 184 | + if err != nil { |
| 185 | + http.Error(w, "Invalid or expired token", http.StatusUnauthorized) |
| 186 | + return |
| 187 | + } |
| 188 | + |
| 189 | + // Get the actual session from the access request (not the input session parameter) |
| 190 | + // This is the correct way to retrieve session data after token introspection |
| 191 | + var userEmail string |
| 192 | + if accessRequest != nil { |
| 193 | + if reqSession, ok := accessRequest.GetSession().(*Session); ok { |
| 194 | + if reqSession.UserInfo != nil && reqSession.UserInfo.Email != "" { |
| 195 | + userEmail = reqSession.UserInfo.Email |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + // Pass user info through context |
| 201 | + if userEmail != "" { |
| 202 | + ctx = context.WithValue(ctx, userContextKey, userEmail) |
| 203 | + r = r.WithContext(ctx) |
| 204 | + } |
| 205 | + |
| 206 | + next.ServeHTTP(w, r) |
| 207 | + }) |
| 208 | + } |
| 209 | +} |
0 commit comments