diff --git a/api/internal/auth/handlers.go b/api/internal/auth/handlers.go index c5e3f672..8465f0a6 100644 --- a/api/internal/auth/handlers.go +++ b/api/internal/auth/handlers.go @@ -1,3 +1,103 @@ +// Package auth provides authentication and authorization mechanisms for StreamSpace. +// This file implements HTTP handlers for authentication endpoints including local, +// SAML, and password management operations. +// +// AUTHENTICATION HANDLERS: +// - Local authentication (username/password) +// - SAML SSO authentication (enterprise identity providers) +// - Token refresh (JWT token renewal) +// - Password change (local users only) +// - Logout (session termination) +// +// SUPPORTED AUTHENTICATION FLOWS: +// +// 1. Local Authentication (POST /auth/login): +// - User submits username and password +// - System verifies credentials against database +// - Returns JWT token for subsequent requests +// - Supports account status validation (active/disabled) +// +// 2. SAML SSO Authentication (GET /auth/saml/login): +// - User initiates SSO flow +// - Redirects to enterprise IdP (Okta, Azure AD, etc.) +// - IdP sends SAML assertion after authentication +// - System validates assertion and creates local session +// - Returns JWT token for API access +// +// 3. Token Refresh (POST /auth/refresh): +// - Client submits existing JWT token +// - System validates token is within refresh window +// - Issues new token with extended expiration +// - Prevents indefinite token refresh (7-day window) +// +// 4. Password Change (POST /auth/password): +// - Local users can change their password +// - Requires current password verification +// - Not available for SSO users (SAML/OIDC) +// +// SECURITY FEATURES: +// +// - Password verification with bcrypt hashing +// - Account status validation (prevent disabled accounts from logging in) +// - JWT token generation with configurable expiration +// - SAML group synchronization for role-based access control +// - Secure cookie handling for SAML return URLs +// - Auto-provisioning of SSO users on first login +// +// SAML GROUP SYNCHRONIZATION: +// +// When users authenticate via SAML, their group memberships are automatically +// synchronized with StreamSpace groups: +// - SAML assertion contains groups claim from IdP +// - System matches SAML group names to local groups +// - Adds user to matching groups (does not remove from other groups by default) +// - Enables role-based access control based on IdP group membership +// +// SECURITY CONSIDERATIONS: +// +// 1. Password Security: +// - Passwords hashed with bcrypt (cost factor 10+) +// - Never return password hashes in API responses +// - Minimum password length enforced (8 characters) +// +// 2. Account Lockout: +// - Disabled accounts cannot authenticate +// - Returns 403 Forbidden for disabled accounts +// - Prevents unauthorized access to suspended accounts +// +// 3. Token Security: +// - JWT tokens include user ID, role, and groups +// - Tokens expire after configured duration (default: 24 hours) +// - Refresh tokens only valid within 7-day window +// - See jwt.go for detailed token security +// +// 4. SAML Security: +// - Assertion signatures validated by middleware +// - Return URLs stored in secure cookies +// - SAML groups synced on every login +// - See saml.go for detailed SAML security +// +// EXAMPLE USAGE: +// +// // Initialize handler with dependencies +// handler := NewAuthHandler(userDB, jwtManager, samlAuth) +// +// // Register routes +// router := gin.Default() +// handler.RegisterRoutes(router.Group("/api/v1")) +// +// // Routes will be available at: +// // - POST /api/v1/auth/login (local authentication) +// // - POST /api/v1/auth/refresh (token refresh) +// // - POST /api/v1/auth/logout (logout) +// // - GET /api/v1/auth/saml/login (initiate SAML SSO) +// // - POST /api/v1/auth/saml/acs (SAML callback) +// // - GET /api/v1/auth/saml/metadata (SAML SP metadata) +// +// THREAD SAFETY: +// +// All handler methods are thread-safe and can handle concurrent requests. +// Database operations use connection pooling for safe concurrent access. package auth import ( diff --git a/api/internal/auth/middleware.go b/api/internal/auth/middleware.go index 46140ea7..f311ffeb 100644 --- a/api/internal/auth/middleware.go +++ b/api/internal/auth/middleware.go @@ -1,3 +1,135 @@ +// Package auth provides authentication and authorization mechanisms for StreamSpace. +// This file implements Gin middleware for JWT token validation and role-based access control. +// +// MIDDLEWARE COMPONENTS: +// - JWT authentication middleware (required authentication) +// - Optional authentication middleware (authentication not required) +// - Role-based authorization middleware (require specific roles) +// - Helper functions for extracting user context +// +// AUTHENTICATION FLOW: +// +// 1. Client Request: +// - Client includes JWT token in Authorization header +// - Format: "Authorization: Bearer " +// - Example: "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." +// +// 2. Token Extraction: +// - Middleware extracts token from Authorization header +// - Validates header format (must start with "Bearer ") +// - Rejects requests with missing or malformed headers +// +// 3. Token Validation: +// - Validates JWT signature using secret key +// - Checks token expiration (exp claim) +// - Verifies token issuer (iss claim) +// - Ensures algorithm is HMAC (prevents algorithm substitution) +// +// 4. User Validation: +// - Extracts user ID from validated token claims +// - Queries database to verify user still exists +// - Checks if user account is active (not disabled) +// - Rejects requests from disabled or deleted users +// +// 5. Context Population: +// - Stores user information in Gin context +// - Available to downstream handlers via c.Get() +// - Includes: userID, username, email, role, groups +// +// MIDDLEWARE TYPES: +// +// 1. Middleware (Required Authentication): +// - Rejects requests without valid JWT token +// - Returns 401 Unauthorized for invalid/missing tokens +// - Returns 403 Forbidden for disabled accounts +// - Use for protected API endpoints +// +// 2. OptionalAuth (Optional Authentication): +// - Accepts requests with or without token +// - Validates token if present, ignores if absent +// - Useful for endpoints that behave differently for authenticated users +// - Example: Public catalog with favorites for logged-in users +// +// 3. RequireRole (Role-Based Authorization): +// - Requires specific role (admin, operator, user) +// - Must be used after Middleware (requires authentication) +// - Returns 403 Forbidden if user lacks required role +// +// 4. RequireAnyRole (Multi-Role Authorization): +// - Accepts any of multiple roles +// - Example: RequireAnyRole("admin", "operator") for management endpoints +// - Returns 403 if user has none of the allowed roles +// +// SECURITY FEATURES: +// +// - Token signature validation prevents tampering +// - Expiration checking limits token lifetime +// - Active user validation prevents disabled account access +// - Role checking enforces principle of least privilege +// - Context isolation prevents request cross-contamination +// +// SECURITY CONSIDERATIONS: +// +// 1. Token Transmission: +// - Tokens must be sent over HTTPS in production +// - Never log or expose tokens in error messages +// - Clear tokens from memory after use +// +// 2. Account Status: +// - Always check user.Active before allowing access +// - Disabled accounts cannot authenticate even with valid token +// - Supports immediate access revocation +// +// 3. Token Expiration: +// - Tokens expire after configured duration (default: 24 hours) +// - Expired tokens rejected with 401 Unauthorized +// - Forces periodic re-authentication +// +// 4. Role Validation: +// - Roles stored in JWT claims (tamper-proof via signature) +// - Role hierarchy: admin > operator > user +// - Always validate role before privileged operations +// +// EXAMPLE USAGE: +// +// // Require authentication for all /api routes +// api := router.Group("/api") +// api.Use(auth.Middleware(jwtManager, userDB)) +// { +// api.GET("/sessions", listSessions) // Requires valid token +// } +// +// // Admin-only endpoints +// admin := api.Group("/admin") +// admin.Use(auth.RequireRole("admin")) +// { +// admin.GET("/users", listAllUsers) // Requires admin role +// } +// +// // Optional authentication (public + user features) +// router.GET("/catalog", auth.OptionalAuth(jwtManager, userDB), showCatalog) +// +// // Extract user info in handler +// func listSessions(c *gin.Context) { +// userID, _ := auth.GetUserID(c) +// role, _ := auth.GetUserRole(c) +// // ... use user info +// } +// +// CONTEXT KEYS: +// +// The middleware stores the following keys in Gin context: +// - "userID": string - Unique user identifier +// - "username": string - Username for display +// - "userEmail": string - User's email address +// - "userRole": string - Role (admin, operator, user) +// - "userGroups": []string - Group memberships +// - "claims": *Claims - Full JWT claims object +// +// THREAD SAFETY: +// +// All middleware functions are thread-safe and can handle concurrent requests. +// Each request gets its own Gin context, preventing data leakage between requests. package auth import ( diff --git a/api/internal/auth/oidc.go b/api/internal/auth/oidc.go index a219fb78..a4e39fa6 100644 --- a/api/internal/auth/oidc.go +++ b/api/internal/auth/oidc.go @@ -1,3 +1,186 @@ +// Package auth provides authentication and authorization mechanisms for StreamSpace. +// This file implements OpenID Connect (OIDC) authentication for integration with +// modern identity providers supporting OAuth 2.0 and OIDC standards. +// +// OIDC AUTHENTICATION OVERVIEW: +// +// OpenID Connect is an identity layer built on top of OAuth 2.0 that provides: +// - User authentication (not just authorization like OAuth 2.0) +// - Standard claims for user identity (sub, email, name, etc.) +// - ID tokens (JWT) containing user information +// - UserInfo endpoint for additional user details +// - Discovery mechanism for automatic configuration +// +// SUPPORTED IDENTITY PROVIDERS: +// +// - Keycloak (open source identity provider) +// - Okta (enterprise SSO platform) +// - Auth0 (identity as a service) +// - Google Workspace (Google accounts) +// - Azure AD / Microsoft Entra ID +// - GitHub (limited OIDC support) +// - GitLab (self-hosted or cloud) +// - Generic OIDC providers +// +// OIDC AUTHENTICATION FLOW (Authorization Code Flow): +// +// 1. User Initiates Login: +// - User clicks "Login with [Provider]" +// - App redirects to /auth/oidc/login +// +// 2. Authorization Request: +// - App generates state parameter (CSRF protection) +// - App redirects user to IdP's authorization endpoint +// - URL includes: client_id, redirect_uri, scope, state +// - Example: https://accounts.google.com/o/oauth2/v2/auth?client_id=... +// +// 3. User Authentication: +// - User authenticates at IdP (username/password, MFA, etc.) +// - IdP shows consent screen (if first time) +// - User approves requested scopes (openid, profile, email) +// +// 4. Authorization Code: +// - IdP redirects back to app with authorization code +// - URL: https://streamspace.example.com/auth/oidc/callback?code=abc123&state=xyz +// - App validates state matches (CSRF protection) +// +// 5. Token Exchange: +// - App exchanges authorization code for tokens +// - POST to IdP's token endpoint with code and client_secret +// - IdP returns: access_token, id_token, refresh_token (optional) +// +// 6. ID Token Validation: +// - App validates ID token signature using IdP's public key +// - App verifies claims: issuer, audience, expiration +// - App extracts user info from ID token claims +// +// 7. UserInfo Request (Optional): +// - App calls IdP's UserInfo endpoint with access token +// - Retrieves additional user attributes not in ID token +// - Merges with ID token claims +// +// 8. User Provisioning: +// - App creates or updates user in local database +// - Syncs user attributes from OIDC claims +// - Syncs group memberships if provided +// +// 9. Session Creation: +// - App generates JWT token for StreamSpace API +// - User is authenticated and can access protected resources +// +// SECURITY FEATURES: +// +// - State parameter validation (CSRF protection) +// - ID token signature validation (prevents tampering) +// - Nonce validation (prevents replay attacks) +// - Token expiration checking +// - TLS certificate validation for IdP connections +// - Client secret protection (never exposed to browser) +// +// CONFIGURATION EXAMPLE: +// +// config := &OIDCConfig{ +// Enabled: true, +// ProviderURL: "https://accounts.google.com", // Discovery URL +// ClientID: "123456.apps.googleusercontent.com", +// ClientSecret: "your-client-secret", +// RedirectURI: "https://streamspace.example.com/auth/oidc/callback", +// Scopes: []string{"openid", "profile", "email", "groups"}, +// UsernameClaim: "preferred_username", +// EmailClaim: "email", +// GroupsClaim: "groups", +// } +// +// SECURITY BEST PRACTICES: +// +// 1. Discovery URL: +// - Use HTTPS for provider URL +// - Validate TLS certificates (don't skip verification in production) +// - Provider URL should end at issuer root (not /...well-known/...) +// +// 2. Client Secret: +// - Never commit to version control +// - Load from environment variables or secret manager +// - Rotate periodically +// - Use separate secrets for dev/staging/production +// +// 3. Redirect URI: +// - Must exactly match URI registered with IdP +// - Use HTTPS in production (HTTP only for localhost dev) +// - Validate redirect URI to prevent open redirect attacks +// +// 4. State Parameter: +// - Generate cryptographically random state for each request +// - Store in cookie or session for validation +// - Prevents CSRF attacks +// +// 5. Token Validation: +// - Always validate ID token signature +// - Check expiration (exp claim) +// - Verify audience matches client_id (aud claim) +// - Verify issuer matches provider (iss claim) +// +// COMMON OIDC VULNERABILITIES TO AVOID: +// +// 1. Missing State Validation: +// - Attack: Attacker initiates flow, tricks victim to complete +// - Prevention: Always validate state parameter matches +// +// 2. ID Token Signature Not Verified: +// - Attack: Attacker creates fake ID token with elevated privileges +// - Prevention: Always verify signature using IdP's public key +// +// 3. Open Redirect: +// - Attack: Attacker uses redirect_uri to redirect to malicious site +// - Prevention: Whitelist allowed redirect URIs +// +// 4. Client Secret Exposure: +// - Attack: Secret leaked in client-side code or logs +// - Prevention: Never include secret in frontend, use environment variables +// +// ATTRIBUTE MAPPING: +// +// Different IdPs use different claim names for user attributes. The +// OIDCConfig allows mapping IdP-specific claims to StreamSpace fields: +// +// Keycloak: +// UsernameClaim: "preferred_username" +// EmailClaim: "email" +// GroupsClaim: "groups" +// +// Google: +// UsernameClaim: "email" +// EmailClaim: "email" +// GroupsClaim: "groups" (Google Workspace only) +// +// Azure AD: +// UsernameClaim: "preferred_username" +// EmailClaim: "email" +// GroupsClaim: "groups" +// +// EXAMPLE USAGE: +// +// // Initialize OIDC authenticator +// oidcAuth, err := NewOIDCAuthenticator(config) +// if err != nil { +// log.Fatal(err) +// } +// +// // Register routes +// router.GET("/auth/oidc/login", oidcAuth.OIDCLoginHandler) +// router.GET("/auth/oidc/callback", oidcAuth.OIDCCallbackHandler(userManager)) +// +// // User flow: +// // 1. Visit /auth/oidc/login +// // 2. Redirect to IdP +// // 3. Authenticate at IdP +// // 4. Redirect to /auth/oidc/callback with code +// // 5. Receive JWT token and user info +// +// THREAD SAFETY: +// +// The OIDCAuthenticator is thread-safe and can handle concurrent authentication +// requests. Each request maintains its own state and session isolation. package auth import ( diff --git a/api/internal/auth/providers.go b/api/internal/auth/providers.go index 624c3772..c9205bed 100644 --- a/api/internal/auth/providers.go +++ b/api/internal/auth/providers.go @@ -1,3 +1,184 @@ +// Package auth provides authentication and authorization mechanisms for StreamSpace. +// This file implements identity provider configuration templates and certificate +// management utilities for SAML and OIDC authentication. +// +// IDENTITY PROVIDER SUPPORT: +// +// This module provides pre-configured templates for popular identity providers, +// making it easier to integrate StreamSpace with enterprise SSO systems. It supports +// both SAML 2.0 and OpenID Connect (OIDC) protocols. +// +// SUPPORTED SAML PROVIDERS: +// +// - Okta: Enterprise SSO platform with comprehensive SAML support +// - Azure AD / Microsoft Entra ID: Microsoft's cloud identity provider +// - Google Workspace: Google's enterprise suite with SSO +// - Auth0: Identity as a Service platform +// - Keycloak: Open source identity and access management +// - Authentik: Modern open source identity provider +// - Generic: Template for any SAML 2.0 compliant provider +// +// SUPPORTED OIDC PROVIDERS: +// +// - Keycloak: Open source with full OIDC support +// - Okta: Enterprise OIDC provider +// - Auth0: OIDC identity service +// - Google: Google accounts with OIDC +// - Azure AD: Microsoft's OIDC implementation +// - GitHub: Developer accounts (limited OIDC) +// - GitLab: Self-hosted or cloud OIDC +// - Generic: Any OIDC-compliant provider +// +// PROVIDER CONFIGURATION TEMPLATES: +// +// Each provider has a pre-configured template that includes: +// - Default attribute mappings (email, username, groups, etc.) +// - Metadata URL template (for SAML) +// - Discovery URL template (for OIDC) +// - Default scopes (for OIDC) +// - Claim names for user attributes +// +// WHY PROVIDER TEMPLATES? +// +// Different identity providers use different attribute names and URL patterns: +// +// Example - Email attribute: +// - Okta: "email" +// - Azure AD: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" +// - Google: "email" +// - Authentik: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" +// +// Provider templates eliminate manual configuration and reduce integration errors. +// +// SAML ATTRIBUTE MAPPING: +// +// SAML attributes map user information from IdP to StreamSpace fields: +// +// Okta Mapping: +// Email: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" +// Username: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" +// FirstName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" +// LastName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" +// Groups: "groups" +// +// Azure AD Mapping: +// Email: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" +// Username: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" +// FirstName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" +// LastName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" +// Groups: "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups" +// +// Keycloak Mapping: +// Email: "email" +// Username: "username" +// FirstName: "firstName" +// LastName: "lastName" +// Groups: "groups" +// +// OIDC CLAIM MAPPING: +// +// OIDC providers use simpler claim names than SAML: +// +// Standard OIDC Claims: +// UsernameClaim: "preferred_username" +// EmailClaim: "email" +// GroupsClaim: "groups" +// +// Provider-Specific Variations: +// Google: username = "email" (no preferred_username) +// Auth0: groups = "https://{domain}/claims/groups" (namespaced) +// GitHub: username = "login", groups = "orgs" +// +// METADATA URL TEMPLATES: +// +// SAML providers expose metadata at predictable URLs. Templates use placeholders +// that are replaced with actual values during configuration: +// +// Okta: +// Template: "https://{domain}/app/{app_id}/sso/saml/metadata" +// Example: "https://dev-12345.okta.com/app/abc123/sso/saml/metadata" +// +// Azure AD: +// Template: "https://login.microsoftonline.com/{tenant_id}/federationmetadata/2007-06/federationmetadata.xml" +// Example: "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/federationmetadata/..." +// +// Keycloak: +// Template: "https://{domain}/auth/realms/{realm}/protocol/saml/descriptor" +// Example: "https://auth.example.com/auth/realms/master/protocol/saml/descriptor" +// +// CERTIFICATE MANAGEMENT: +// +// SAML requires X.509 certificates for signing and encryption. This module provides +// utilities for loading certificates and private keys from PEM files: +// +// - LoadCertificate: Loads X.509 certificate from PEM file +// - LoadPrivateKey: Loads RSA private key from PEM file (PKCS1 or PKCS8) +// +// SECURITY CONSIDERATIONS: +// +// 1. Certificate Storage: +// - Store private keys securely (file permissions 0600) +// - Never commit private keys to version control +// - Use secrets management systems (Vault, AWS Secrets Manager) +// - Rotate certificates regularly (annually recommended) +// +// 2. Attribute Mapping Validation: +// - Verify attribute mappings with IdP administrator +// - Test with real user accounts before production +// - Log missing attributes for debugging +// +// 3. Metadata URLs: +// - Always use HTTPS for metadata fetching +// - Validate TLS certificates +// - Consider caching metadata to reduce dependencies +// +// 4. Provider Trust: +// - Only configure trusted identity providers +// - Verify IdP metadata before accepting +// - Monitor IdP configuration changes +// +// EXAMPLE USAGE: +// +// // Get Okta SAML configuration template +// config := GetProviderConfig(ProviderOkta) +// fmt.Printf("Email attribute: %s\n", config.DefaultMapping.Email) +// // Output: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress +// +// // Get Keycloak OIDC configuration template +// oidcConfig := GetOIDCProviderConfig(OIDCProviderKeycloak) +// fmt.Printf("Discovery URL: %s\n", oidcConfig.DiscoveryURL) +// // Output: https://{domain}/auth/realms/{realm} +// +// // Load SAML certificate +// cert, err := LoadCertificate("/path/to/cert.pem") +// if err != nil { +// log.Fatal(err) +// } +// +// // Load SAML private key +// key, err := LoadPrivateKey("/path/to/key.pem") +// if err != nil { +// log.Fatal(err) +// } +// +// AUTHENTICATION MODE CONFIGURATION: +// +// StreamSpace supports multiple authentication modes: +// +// - AuthModeJWT: Local authentication only (username/password + JWT) +// - AuthModeSAML: SAML SSO only (enterprise identity provider) +// - AuthModeOIDC: OIDC authentication only (modern IdPs) +// - AuthModeHybrid: Both local and SAML (flexible deployment) +// +// Mode selection depends on deployment requirements: +// - Small teams: AuthModeJWT (simpler setup) +// - Enterprise: AuthModeSAML or AuthModeOIDC (centralized identity) +// - Mixed: AuthModeHybrid (support both employee SSO and external users) +// +// THREAD SAFETY: +// +// All functions in this module are thread-safe and can be called concurrently. +// Provider configuration templates are read-only and immutable. package auth import ( diff --git a/api/internal/auth/tokenhash.go b/api/internal/auth/tokenhash.go index 9a89ef2a..11c0f062 100644 --- a/api/internal/auth/tokenhash.go +++ b/api/internal/auth/tokenhash.go @@ -1,3 +1,207 @@ +// Package auth provides authentication and authorization mechanisms for StreamSpace. +// This file implements secure token generation and hashing for API tokens, session +// tokens, and other authentication credentials. +// +// TOKEN TYPES AND USE CASES: +// +// StreamSpace uses different token types for different purposes: +// +// 1. API Tokens (Long-lived): +// - Used for programmatic API access +// - Stored in database with bcrypt hash +// - 384 bits of entropy (48 bytes) +// - Never expire (until revoked by user) +// - Example: Personal access tokens, integration keys +// +// 2. Session Tokens (Short-lived): +// - Used for web session management +// - Stored in database with SHA256 hash +// - 256 bits of entropy (32 bytes) +// - Expire after inactivity or logout +// - Example: Browser session cookies +// +// 3. Generic Secure Tokens: +// - Used for password reset, email verification, etc. +// - Stored with bcrypt hash for security +// - Configurable length +// - Single-use tokens with expiration +// +// HASHING ALGORITHMS: +// +// Two hashing algorithms are provided based on use case requirements: +// +// 1. bcrypt (For API Tokens): +// - Intentionally slow (prevents brute force attacks) +// - Adaptive work factor (can increase over time) +// - Salt included automatically +// - Recommended for long-lived tokens +// - Cost factor: 10 (good security/performance balance) +// +// 2. SHA256 (For Session Tokens): +// - Fast hashing (suitable for high-volume lookups) +// - 256-bit output (sufficient for session tokens) +// - No built-in salt (tokens are cryptographically random) +// - Recommended for short-lived, high-frequency tokens +// +// WHY DIFFERENT ALGORITHMS? +// +// bcrypt vs SHA256 trade-offs: +// +// bcrypt Advantages: +// - Slow hashing prevents brute force attacks +// - Adaptive cost factor (security improves over time) +// - Best practice for password-like credentials +// +// bcrypt Disadvantages: +// - Slower performance (intentional, but impacts throughput) +// - Not suitable for high-frequency validation +// +// SHA256 Advantages: +// - Fast validation (thousands of lookups per second) +// - Suitable for session tokens with high request rates +// - Simple implementation +// +// SHA256 Disadvantages: +// - Fast hashing makes brute force easier +// - No adaptive cost factor +// - Not recommended for long-lived credentials +// +// SECURITY BEST PRACTICES: +// +// 1. Token Generation: +// - Use crypto/rand for cryptographically secure randomness +// - Never use math/rand (predictable, insecure) +// - Sufficient entropy: 32+ bytes for session, 48+ bytes for API +// - Base64 URL encoding for safe transmission +// +// 2. Token Storage: +// - NEVER store plain tokens in database +// - Always hash before storage (bcrypt or SHA256) +// - Store hash only, discard plain token after giving to user +// - Use prepared statements to prevent SQL injection +// +// 3. Token Transmission: +// - Send tokens over HTTPS only +// - Use secure, httpOnly cookies for session tokens +// - Never log or expose tokens in error messages +// - Clear tokens from memory after use +// +// 4. Token Expiration: +// - Session tokens: Short lifetime (hours to days) +// - API tokens: Long lifetime but allow user revocation +// - Reset tokens: Very short lifetime (minutes to hours) +// - Always enforce expiration checks +// +// 5. Token Revocation: +// - Support manual revocation by users +// - Revoke all tokens on password change +// - Track last used timestamp for auditing +// - Remove expired tokens regularly +// +// TOKEN GENERATION PROCESS: +// +// 1. Generate Random Bytes: +// - Use crypto/rand.Read() for secure randomness +// - Generate sufficient bytes for desired entropy +// - Check for errors (rare, but possible on some systems) +// +// 2. Encode Plain Token: +// - Base64 URL encode random bytes +// - URL-safe encoding (no +, /, or = padding issues) +// - Result is alphanumeric string safe for URLs +// +// 3. Hash Token: +// - Hash plain token with bcrypt or SHA256 +// - Store hash in database +// - Return plain token to user (shown only once) +// +// 4. User Storage: +// - User stores plain token securely (password manager, env var) +// - User includes token in API requests +// - Server hashes incoming token and compares with stored hash +// +// EXAMPLE USAGE: +// +// hasher := NewTokenHasher() +// +// // Generate API token (long-lived, bcrypt) +// plainToken, hashedToken, err := hasher.GenerateAPIToken() +// if err != nil { +// log.Fatal(err) +// } +// // Store hashedToken in database +// // Give plainToken to user (show only once!) +// +// // Generate session token (short-lived, SHA256) +// plainSession, hashedSession, err := hasher.GenerateSessionToken() +// if err != nil { +// log.Fatal(err) +// } +// // Store hashedSession in database +// // Set plainSession as secure cookie +// +// // Verify API token (bcrypt) +// valid := hasher.VerifyToken(userProvidedToken, storedHash) +// if !valid { +// return errors.New("invalid token") +// } +// +// // Verify session token (SHA256 - faster) +// valid := hasher.VerifyTokenSHA256(cookieToken, storedSessionHash) +// if !valid { +// return errors.New("invalid session") +// } +// +// COMMON VULNERABILITIES TO AVOID: +// +// 1. Weak Random Number Generation: +// - ❌ DON'T use math/rand (predictable) +// - ✅ DO use crypto/rand (cryptographically secure) +// +// 2. Storing Plain Tokens: +// - ❌ DON'T store plain tokens in database +// - ✅ DO store only hashed tokens +// +// 3. Insufficient Entropy: +// - ❌ DON'T use short tokens (< 16 bytes) +// - ✅ DO use 32+ bytes for sessions, 48+ for API tokens +// +// 4. No Expiration: +// - ❌ DON'T allow tokens to live forever +// - ✅ DO enforce expiration and support revocation +// +// 5. Timing Attacks: +// - ❌ DON'T use == for token comparison +// - ✅ DO use bcrypt.CompareHashAndPassword (constant-time) +// +// PERFORMANCE CONSIDERATIONS: +// +// bcrypt Cost Factor Trade-offs: +// +// Cost 10 (Default): +// - ~60ms per hash on modern CPU +// - ~16 hashes per second per core +// - Suitable for login and API token validation +// +// Cost 12 (Higher Security): +// - ~240ms per hash +// - ~4 hashes per second per core +// - Use for extra-sensitive tokens +// +// Cost 14 (Maximum Security): +// - ~960ms per hash +// - ~1 hash per second per core +// - May impact user experience +// +// SHA256 Performance: +// - Microseconds per hash +// - Millions of hashes per second +// - Use for session tokens with high request rates +// +// THREAD SAFETY: +// +// All methods are thread-safe and can be called concurrently from multiple +// goroutines. Each token generation operation is independent. package auth import ( diff --git a/api/internal/cache/cache.go b/api/internal/cache/cache.go index 3d95a121..76e9638f 100644 --- a/api/internal/cache/cache.go +++ b/api/internal/cache/cache.go @@ -1,3 +1,68 @@ +// Package cache provides Redis-based caching for StreamSpace API. +// +// This file implements the core Redis cache client with connection pooling. +// +// Purpose: +// - Provide high-performance caching for frequently accessed data +// - Reduce database load for read-heavy operations +// - Enable distributed caching across multiple API instances +// - Support atomic operations and distributed locks +// +// Features: +// - Connection pooling (25 max connections, 5 min idle) +// - Automatic retry with exponential backoff +// - Graceful fallback when Redis is unavailable (cache disabled mode) +// - JSON serialization/deserialization +// - TTL-based expiration +// - Pattern-based invalidation +// - Atomic counters and distributed locks (SetNX) +// - Statistics and monitoring (pool stats, hit/miss tracking) +// +// Cache Strategy: +// - Get: Retrieve value, deserialize JSON +// - Set: Serialize to JSON, store with TTL +// - Delete: Remove single or multiple keys +// - DeletePattern: Bulk invalidation via pattern matching +// - SetNX: Distributed lock acquisition +// +// Implementation Details: +// - Uses go-redis client with connection pooling +// - Auto-reconnection on connection failures +// - 3 retry attempts with 8-512ms exponential backoff +// - 5-second dial timeout, 3-second read/write timeouts +// - Values stored as JSON for flexibility +// +// Thread Safety: +// - Redis client is thread-safe +// - Safe for concurrent access across goroutines +// +// Dependencies: +// - github.com/redis/go-redis/v9 for Redis client +// +// Example Usage: +// +// // Initialize cache +// cache, err := cache.NewCache(cache.Config{ +// Host: "localhost", +// Port: "6379", +// Password: "", +// DB: 0, +// Enabled: true, +// }) +// if err != nil { +// log.Fatal(err) +// } +// defer cache.Close() +// +// // Store session in cache +// err = cache.Set(ctx, cache.SessionKey("session-123"), session, 5*time.Minute) +// +// // Retrieve from cache +// var session Session +// err = cache.Get(ctx, cache.SessionKey("session-123"), &session) +// +// // Invalidate user's sessions +// err = cache.DeletePattern(ctx, cache.UserPattern("user-123")) package cache import ( diff --git a/api/internal/cache/keys.go b/api/internal/cache/keys.go index 51e51859..1aeb8827 100644 --- a/api/internal/cache/keys.go +++ b/api/internal/cache/keys.go @@ -1,3 +1,50 @@ +// Package cache provides Redis-based caching for StreamSpace API. +// +// This file defines standardized cache key naming conventions and patterns. +// +// Purpose: +// - Provide consistent cache key naming across all cache operations +// - Enable efficient cache invalidation via pattern matching +// - Organize cache keys by resource type +// - Support multi-level cache hierarchies +// +// Features: +// - Resource-specific key prefixes (session, user, template, quota) +// - Hierarchical key structure (prefix:resource:identifier) +// - Pattern-based invalidation (session:*, user:123:*) +// - User-scoped keys for isolation +// - List and collection keys +// +// Key Naming Convention: +// - Format: {prefix}:{resource}:{identifier} +// - Example: session:user1-firefox +// - Example: user:username:alice +// - Example: quota:user:user123 +// +// Key Patterns for Invalidation: +// - session:* - All sessions +// - *:user:123* - All user-specific caches +// - template:category:browsers - Templates in category +// +// Implementation Details: +// - Keys use colon (:) as separator for Redis best practices +// - Prefixes prevent key collisions across resource types +// - Patterns use wildcards (*) for bulk invalidation +// +// Example Usage: +// +// // Generate cache key for session +// key := cache.SessionKey("user1-firefox") +// // Result: "session:user1-firefox" +// +// // Generate key for user by username +// key := cache.UserByUsernameKey("alice") +// // Result: "user:username:alice" +// +// // Invalidate all user-related caches +// pattern := cache.UserPattern("user123") +// err := cache.DeletePattern(ctx, pattern) +// // Deletes: user:user123, session:user:user123:list, quota:user:user123, etc. package cache import "fmt" diff --git a/api/internal/cache/middleware.go b/api/internal/cache/middleware.go index 14623029..932f318f 100644 --- a/api/internal/cache/middleware.go +++ b/api/internal/cache/middleware.go @@ -1,3 +1,55 @@ +// Package cache provides Redis-based caching for StreamSpace API. +// +// This file implements HTTP caching middleware for Gin framework. +// +// Purpose: +// - Cache HTTP GET responses to reduce backend load +// - Automatically invalidate cache on mutations (POST, PUT, DELETE) +// - Add cache control headers for browser/CDN caching +// - Provide cache hit/miss transparency +// +// Features: +// - Response caching for GET requests +// - Cache key generation from request URI (SHA-256 hash) +// - Automatic cache invalidation after mutations +// - X-Cache header (HIT/MISS) for debugging +// - Async cache operations (non-blocking) +// - Cache-Control headers for browser caching +// +// Middleware Types: +// - CacheMiddleware: Caches GET responses +// - InvalidateCacheMiddleware: Clears cache after mutations +// - CacheControl: Adds Cache-Control headers +// +// Implementation Details: +// - Only caches successful responses (2xx status codes) +// - Response body captured via custom ResponseWriter +// - Cache operations run asynchronously to avoid blocking requests +// - Cache keys generated via SHA-256 hash of request URI +// - Gracefully handles cache unavailability (continues without caching) +// +// Thread Safety: +// - Middleware is thread-safe (uses goroutines for async operations) +// - Safe for concurrent requests +// +// Dependencies: +// - github.com/gin-gonic/gin for HTTP framework +// +// Example Usage: +// +// // Apply response caching middleware +// router.Use(cache.CacheMiddleware(cacheClient, 5*time.Minute)) +// +// // Apply cache invalidation for mutations +// router.POST("/sessions", cache.InvalidateCacheMiddleware(cacheClient, cache.SessionPattern()), handler) +// +// // Add cache control headers +// router.Use(cache.CacheControl(1*time.Hour)) +// +// // Result: +// // - GET /sessions: Cached for 5 minutes, X-Cache: HIT/MISS header added +// // - POST /sessions: Invalidates all session:* keys +// // - Response includes: Cache-Control: public, max-age=3600 package cache import ( diff --git a/api/internal/db/database.go b/api/internal/db/database.go index 2ff0276a..b1a2720a 100644 --- a/api/internal/db/database.go +++ b/api/internal/db/database.go @@ -1,3 +1,69 @@ +// Package db provides PostgreSQL database access and management for StreamSpace. +// +// This file implements the core database connection and lifecycle management. +// +// Purpose: +// - Establish and maintain PostgreSQL connection pool +// - Initialize database schema on startup (82+ tables) +// - Provide centralized database instance for all API handlers +// - Execute raw SQL queries and transactions +// - Validate database configuration for security +// +// Features: +// - Connection pooling with configurable limits (25 max open, 5 max idle) +// - Comprehensive schema migrations (82+ tables, 200+ indexes) +// - Health check and ping capabilities +// - Graceful connection cleanup on shutdown +// - Configuration validation (prevents SQL injection in connection strings) +// - SSL/TLS warnings for production security +// +// Database Schema: +// - 82+ tables covering users, sessions, templates, plugins, quotas, audit logs +// - 200+ indexes for query performance optimization +// - JSONB columns for flexible metadata storage +// - Foreign key constraints for referential integrity +// - Composite indexes for common query patterns +// +// Implementation Details: +// - Uses database/sql with lib/pq PostgreSQL driver +// - Connection pool configured for optimal performance (5min max lifetime) +// - Schema initialization runs CREATE TABLE IF NOT EXISTS on startup +// - Thread-safe connection pooling handled by database/sql package +// - Validates hostname, port, username, database name, SSL mode +// +// Thread Safety: +// - Database connections are thread-safe and managed by database/sql pool +// - Safe for concurrent use across multiple goroutines +// - Connection pool prevents resource exhaustion +// +// Dependencies: +// - PostgreSQL 12+ (required) +// - lib/pq driver for database/sql +// +// Example Usage: +// +// config := db.Config{ +// Host: "localhost", +// Port: "5432", +// User: "streamspace", +// Password: "secretpassword", +// DBName: "streamspace", +// SSLMode: "require", +// } +// +// database, err := db.NewDatabase(config) +// if err != nil { +// log.Fatal(err) +// } +// defer database.Close() +// +// // Run migrations +// if err := database.Migrate(); err != nil { +// log.Fatal(err) +// } +// +// // Use database connection +// rows, err := database.DB().Query("SELECT * FROM users") package db import ( diff --git a/api/internal/db/groups.go b/api/internal/db/groups.go index e8e7e7e6..9fded8f5 100644 --- a/api/internal/db/groups.go +++ b/api/internal/db/groups.go @@ -1,3 +1,87 @@ +// Package db provides PostgreSQL database access and management for StreamSpace. +// +// This file implements group management and authorization data access. +// +// Purpose: +// - CRUD operations for user groups +// - Group-based access control and permissions +// - Group quota and resource limit management +// - User-to-group membership mapping +// - Group hierarchy support (parent/child groups) +// +// Features: +// - Group-based resource quotas +// - Group permissions and role-based access +// - User membership tracking with roles +// - Group search and filtering by type/parent +// - Quota inheritance from groups to users +// - Member count aggregation +// +// Database Schema: +// - groups table: Group definitions and metadata +// - id (varchar): Primary key (UUID) +// - name (varchar): Unique group name +// - display_name (varchar): Human-readable name +// - description (text): Group purpose description +// - type (varchar): Group type (team, department, etc.) +// - parent_id (varchar): Optional parent group for hierarchy +// - created_at, updated_at: Timestamps +// +// - group_memberships table: User-to-group junction +// - id (varchar): Primary key +// - user_id (varchar): Foreign key to users +// - group_id (varchar): Foreign key to groups +// - role (varchar): Member role (owner, admin, member) +// - created_at: When user joined +// +// - group_quotas table: Resource limits per group +// - group_id: Foreign key to groups +// - max_sessions, max_cpu, max_memory, max_storage: Limits +// - used_sessions, used_cpu, used_memory, used_storage: Current usage +// +// Quota Hierarchy: +// 1. User-specific quotas (most restrictive wins) +// 2. Group quotas (applied to all group members) +// 3. Platform defaults (fallback) +// +// Implementation Details: +// - Groups can have resource quotas that apply to all members +// - Most restrictive quota wins (user vs group vs platform) +// - Quota stored as separate table with foreign key constraint +// - Supports hierarchical groups with parent_id +// - Member counts calculated via JOIN for efficiency +// +// Thread Safety: +// - All database operations are thread-safe via database/sql pool +// - Safe for concurrent access from multiple goroutines +// +// Dependencies: +// - github.com/google/uuid for ID generation +// - models package for data structures +// +// Example Usage: +// +// groupDB := db.NewGroupDB(database.DB()) +// +// // Create group +// group, err := groupDB.CreateGroup(ctx, &models.CreateGroupRequest{ +// Name: "developers", +// DisplayName: "Developers", +// Description: "Development team", +// Type: "team", +// }) +// +// // Set group quota +// maxSessions := 20 +// err := groupDB.SetGroupQuota(ctx, groupID, &models.SetQuotaRequest{ +// MaxSessions: &maxSessions, +// }) +// +// // Add user to group +// err := groupDB.AddGroupMember(ctx, groupID, &models.AddGroupMemberRequest{ +// UserID: userID, +// Role: "member", +// }) package db import ( diff --git a/api/internal/db/teams.go b/api/internal/db/teams.go index 585f4725..2e46e640 100644 --- a/api/internal/db/teams.go +++ b/api/internal/db/teams.go @@ -1,3 +1,44 @@ +// Package db provides PostgreSQL database access and management for StreamSpace. +// +// This file defines team-related data structures for team management and collaboration. +// +// Purpose: +// - Define team membership data structures +// - Define team role permission structures +// - Support team-based organization and collaboration +// +// Features: +// - Team membership tracking with roles +// - Role-based permission system +// - Team hierarchy support +// +// Data Structures: +// - TeamMembership: Represents a user's membership in a team +// - TeamPermission: Defines permissions for team roles +// - TeamRoleInfo: Aggregates role information with permissions +// +// Team Roles: +// - owner: Full control (manage team, members, sessions, quotas) +// - admin: Administrative access (manage members, sessions) +// - member: Standard access (create sessions, view team data) +// - viewer: Read-only access (view sessions and quotas) +// +// Implementation Details: +// - This file contains only type definitions +// - Actual database operations are in groups.go (teams are a type of group) +// - Team roles and permissions stored in team_role_permissions table +// - Initialized with default permissions during database migration +// +// Example Usage: +// +// membership := &TeamMembership{ +// TeamID: "team-abc", +// TeamName: "frontend-team", +// TeamDisplayName: "Frontend Team", +// TeamType: "team", +// Role: "member", +// JoinedAt: time.Now(), +// } package db import "time" diff --git a/api/internal/db/users.go b/api/internal/db/users.go index 60e514eb..ce8ad506 100644 --- a/api/internal/db/users.go +++ b/api/internal/db/users.go @@ -1,3 +1,84 @@ +// Package db provides PostgreSQL database access and management for StreamSpace. +// +// This file implements user management and authentication data access. +// +// Purpose: +// - CRUD operations for user accounts +// - Password hashing and verification with bcrypt +// - User authentication and authorization +// - User quota and resource limit management +// - User preferences and settings storage +// - Group membership management +// +// Features: +// - Secure password hashing with bcrypt (cost factor 10) +// - User search and filtering by username/email/role/provider +// - Quota enforcement integration with quota system +// - User group membership tracking +// - OAuth provider linking (OIDC, SAML) +// - MFA (TOTP) configuration storage support +// - Last login tracking for auditing +// +// Database Schema: +// - users table: Core user account data +// - id (varchar): Primary key (UUID) +// - username (varchar): Unique username +// - email (varchar): Unique email address +// - password_hash (varchar): bcrypt hashed password (local auth only) +// - role (varchar): User role (user, admin, superadmin) +// - provider (varchar): Auth provider (local, saml, oidc) +// - active (boolean): Account active status +// - created_at, updated_at: Timestamps +// - last_login: Last successful authentication +// +// - user_quotas table: Resource limits per user +// - user_id: Foreign key to users +// - max_sessions, max_cpu, max_memory, max_storage: Limits +// - used_sessions, used_cpu, used_memory, used_storage: Current usage +// +// Implementation Details: +// - Passwords never stored in plaintext (bcrypt with cost 10) +// - User lookups indexed by username and email for performance +// - Quota stored as separate table with foreign key constraint +// - Group membership managed via group_memberships junction table +// - Default quota created automatically on user creation +// - Supports multiple authentication providers (local, SAML, OIDC) +// +// Thread Safety: +// - All database operations are thread-safe via database/sql pool +// - Safe for concurrent access from multiple goroutines +// - bcrypt operations are CPU-intensive but safe for concurrent use +// +// Dependencies: +// - golang.org/x/crypto/bcrypt for password hashing +// - github.com/google/uuid for ID generation +// - models package for data structures +// +// Example Usage: +// +// userDB := db.NewUserDB(database.DB()) +// +// // Create user with password +// user, err := userDB.CreateUser(ctx, &models.CreateUserRequest{ +// Username: "alice", +// Email: "alice@example.com", +// Password: "securepassword", +// FullName: "Alice Smith", +// Role: "user", +// Provider: "local", +// }) +// +// // Authenticate user +// user, err := userDB.VerifyPassword(ctx, "alice", "securepassword") +// +// // Update user quota +// maxSessions := 10 +// err := userDB.SetUserQuota(ctx, userID, &models.SetQuotaRequest{ +// MaxSessions: &maxSessions, +// }) +// +// // Get or create SAML user (SSO) +// user, err := userDB.GetOrCreateSAMLUser(ctx, "bob", "bob@company.com", "Bob Jones", "saml-provider") package db import ( diff --git a/api/internal/errors/middleware.go b/api/internal/errors/middleware.go index 18599687..bcc9ead4 100644 --- a/api/internal/errors/middleware.go +++ b/api/internal/errors/middleware.go @@ -1,3 +1,61 @@ +// Package errors provides standardized error handling for StreamSpace API. +// +// This file implements error handling middleware for Gin framework. +// +// Purpose: +// - Centralize error handling across all API endpoints +// - Convert AppError to consistent JSON responses +// - Log errors with appropriate severity levels +// - Recover from panics gracefully +// - Provide helper functions for error responses +// +// Features: +// - Automatic error logging (ERROR for 5xx, WARN for 4xx) +// - Panic recovery with error response +// - Consistent error response format +// - Error severity classification +// - Request abort on critical errors +// +// Middleware Functions: +// - ErrorHandler: Handles AppError and generic errors +// - Recovery: Recovers from panics +// - HandleError: Helper for error responses in handlers +// - AbortWithError: Helper to abort request with error +// +// Implementation Details: +// - Integrates with Gin's error handling mechanism (c.Errors) +// - Logs errors using standard library log (consider upgrading to structured logging) +// - Preserves error details for debugging +// - Automatically sets HTTP status codes +// +// Thread Safety: +// - Middleware is thread-safe +// - Safe for concurrent requests +// +// Dependencies: +// - github.com/gin-gonic/gin for HTTP framework +// +// Example Usage: +// +// // Apply error handling middleware +// router.Use(errors.Recovery()) +// router.Use(errors.ErrorHandler()) +// +// // In handler: return error and let middleware handle it +// func handler(c *gin.Context) { +// session, err := getSession(id) +// if err != nil { +// errors.HandleError(c, errors.SessionNotFound(id)) +// return +// } +// c.JSON(200, session) +// } +// +// // Or abort immediately +// if !authorized { +// errors.AbortWithError(c, errors.Forbidden("Access denied")) +// return +// } package errors import ( diff --git a/api/internal/handlers/activity.go b/api/internal/handlers/activity.go index f4b5a602..2aed8e00 100644 --- a/api/internal/handlers/activity.go +++ b/api/internal/handlers/activity.go @@ -1,3 +1,48 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements session activity tracking and heartbeat management. +// +// ACTIVITY TRACKING: +// - Session heartbeat recording to prevent auto-hibernation +// - Activity status queries (active, idle, hibernation eligibility) +// - Idle duration calculation +// - Last activity timestamp tracking +// +// HEARTBEAT MECHANISM: +// - Clients send periodic heartbeats to indicate active usage +// - Updates session's lastActivity timestamp +// - Prevents idle timeout and auto-hibernation +// - Typically sent every 30-60 seconds from active sessions +// +// ACTIVITY STATUS: +// - Is session currently active (recent heartbeat) +// - Is session idle (exceeded idle threshold) +// - Time since last activity +// - Should session be hibernated (idle + threshold exceeded) +// - Configurable idle thresholds per session +// +// USE CASES: +// - Auto-hibernation prevention for active sessions +// - Resource optimization by hibernating idle sessions +// - User activity analytics +// - Session health monitoring +// +// API Endpoints: +// - POST /api/v1/sessions/:id/heartbeat - Record session heartbeat +// - GET /api/v1/sessions/:id/activity - Get session activity status +// +// Thread Safety: +// - Activity tracker is thread-safe with mutex protection +// - Kubernetes client operations are thread-safe +// +// Dependencies: +// - Kubernetes: Session CRDs with status updates +// - Activity Tracker: In-memory tracking with persistence +// - External Services: None +// +// Example Usage: +// +// handler := NewActivityHandler(k8sClient, activityTracker) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/apikeys.go b/api/internal/handlers/apikeys.go index 5e2dac71..121db80b 100644 --- a/api/internal/handlers/apikeys.go +++ b/api/internal/handlers/apikeys.go @@ -1,3 +1,61 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements API key management for programmatic API access. +// +// API KEY FEATURES: +// - Secure API key generation with cryptographic randomness +// - API key CRUD operations (create, list, revoke, delete) +// - Key metadata (name, description, scopes, rate limits) +// - Expiration support with configurable durations +// - Usage tracking (last used timestamp, use count) +// - Active/inactive state management +// +// SECURITY: +// - Keys hashed with SHA-256 before storage (never stored in plaintext) +// - Prefix-based identification (first 8 characters for UI display) +// - Keys prefixed with "sk_" for easy identification +// - 32 bytes of cryptographic randomness (256 bits) +// - Keys only shown once during creation (cannot be retrieved later) +// +// API KEY STRUCTURE: +// - Format: sk_{base64_encoded_random_bytes} +// - Storage: SHA-256 hash in database +// - Display: First 8 characters (sk_xxxxx...) +// +// SCOPE MANAGEMENT: +// - Configurable scopes limit API key permissions +// - Examples: sessions:read, sessions:write, admin:all +// - Scope validation during API requests +// +// RATE LIMITING: +// - Per-key rate limits independent of user limits +// - Configurable requests per time window +// - Tracked via use_count and last_used_at +// +// EXPIRATION: +// - Optional expiration with duration strings (30d, 1y, etc.) +// - Automatic enforcement during authentication +// - Expired keys cannot authenticate +// +// API Endpoints: +// - POST /api/v1/apikeys - Create new API key +// - GET /api/v1/apikeys - List user's API keys +// - GET /api/v1/apikeys/:id - Get API key details +// - PUT /api/v1/apikeys/:id - Update API key metadata +// - DELETE /api/v1/apikeys/:id - Delete/revoke API key +// - POST /api/v1/apikeys/:id/rotate - Rotate API key (generate new) +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Cryptographic random generation is thread-safe +// +// Dependencies: +// - Database: api_keys table +// - External Services: None +// +// Example Usage: +// +// handler := NewAPIKeyHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/batch.go b/api/internal/handlers/batch.go index 70484b3a..64141c52 100644 --- a/api/internal/handlers/batch.go +++ b/api/internal/handlers/batch.go @@ -1,3 +1,73 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements batch operations for bulk resource management. +// +// BATCH OPERATION FEATURES: +// - Bulk session operations (terminate, hibernate, wake, delete) +// - Bulk snapshot operations (create, delete) +// - Bulk template operations (install, delete) +// - Asynchronous job execution with progress tracking +// - Job status monitoring and cancellation +// +// OPERATION TYPES: +// - terminate: Stop multiple running sessions +// - hibernate: Put multiple sessions into hibernated state +// - wake: Resume multiple hibernated sessions +// - delete: Remove multiple sessions/snapshots/templates +// - update: Bulk update tags or resource limits +// +// BATCH JOB LIFECYCLE: +// 1. Job creation: Create batch_operations record +// 2. Async execution: Process items in background goroutine +// 3. Progress tracking: Update processed/success/failure counts +// 4. Completion: Mark job as completed or failed +// 5. Cleanup: Jobs can be cancelled or deleted +// +// JOB STATUS TRACKING: +// - Total items to process +// - Processed items count +// - Success count +// - Failure count +// - Errors array for failed items +// - Created/completed timestamps +// +// ASYNC EXECUTION: +// - All batch operations run asynchronously +// - Immediate job ID returned to client +// - Client polls job status endpoint for progress +// - WebSocket notifications for real-time updates +// +// ERROR HANDLING: +// - Partial failures: Continue processing remaining items +// - Error collection: Record all errors for debugging +// - Job status reflects overall success/failure +// +// API Endpoints: +// - POST /api/v1/batch/sessions/terminate - Terminate multiple sessions +// - POST /api/v1/batch/sessions/hibernate - Hibernate multiple sessions +// - POST /api/v1/batch/sessions/wake - Wake multiple sessions +// - POST /api/v1/batch/sessions/delete - Delete multiple sessions +// - POST /api/v1/batch/sessions/update-tags - Update session tags +// - POST /api/v1/batch/sessions/update-resources - Update resource limits +// - POST /api/v1/batch/snapshots/delete - Delete multiple snapshots +// - POST /api/v1/batch/snapshots/create - Create multiple snapshots +// - POST /api/v1/batch/templates/install - Install multiple templates +// - POST /api/v1/batch/templates/delete - Delete multiple templates +// - GET /api/v1/batch/jobs - List batch jobs +// - GET /api/v1/batch/jobs/:id - Get batch job status +// - DELETE /api/v1/batch/jobs/:id - Cancel batch job +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Goroutines for async execution are properly managed +// +// Dependencies: +// - Database: batch_operations, sessions, snapshots, templates tables +// - External Services: None +// +// Example Usage: +// +// handler := NewBatchHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/catalog.go b/api/internal/handlers/catalog.go index 320b8737..f6b5bbb4 100644 --- a/api/internal/handlers/catalog.go +++ b/api/internal/handlers/catalog.go @@ -1,3 +1,55 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements template catalog browsing, ratings, and statistics. +// +// CATALOG FEATURES: +// - Template discovery with advanced search and filtering +// - Featured, trending, and popular template lists +// - User ratings and reviews system +// - View and install tracking for analytics +// +// SEARCH AND FILTERING: +// - Full-text search across template names and descriptions +// - Filter by category, tags, app type +// - Sort by popularity, rating, recency, or install count +// - Pagination support with customizable page size +// +// RATINGS AND REVIEWS: +// - Add, update, and delete template ratings +// - Star ratings (1-5 scale) +// - User comments and reviews +// - Average rating calculation +// - Rating count tracking +// +// STATISTICS: +// - View count tracking (catalog impressions) +// - Install count tracking (template usage) +// - Trending calculation based on recent activity +// - Popular templates based on install count +// +// API Endpoints: +// - GET /api/v1/catalog/templates - List templates with filters and search +// - GET /api/v1/catalog/templates/:id - Get template details +// - GET /api/v1/catalog/templates/featured - List featured templates +// - GET /api/v1/catalog/templates/trending - List trending templates +// - GET /api/v1/catalog/templates/popular - List popular templates +// - POST /api/v1/catalog/templates/:id/ratings - Add rating/review +// - GET /api/v1/catalog/templates/:id/ratings - Get template ratings +// - PUT /api/v1/catalog/templates/:id/ratings/:ratingId - Update rating +// - DELETE /api/v1/catalog/templates/:id/ratings/:ratingId - Delete rating +// - POST /api/v1/catalog/templates/:id/view - Record template view +// - POST /api/v1/catalog/templates/:id/install - Record template install +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: catalog_templates, repositories, template_ratings tables +// - External Services: Repository sync for template metadata +// +// Example Usage: +// +// handler := NewCatalogHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/console.go b/api/internal/handlers/console.go index a84f6ec6..94fd1fab 100644 --- a/api/internal/handlers/console.go +++ b/api/internal/handlers/console.go @@ -1,3 +1,69 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements console access and file management for sessions. +// +// CONSOLE FEATURES: +// - Interactive terminal access to sessions via WebSocket +// - File manager for browsing session filesystems +// - File operations (create, delete, rename, copy, move, upload, download) +// - Multi-shell support (bash, sh, zsh) +// - Terminal resize and configuration +// +// TERMINAL SESSIONS: +// - WebSocket-based terminal connections +// - Configurable rows and columns +// - Shell type selection (bash, sh, zsh) +// - Activity tracking and idle timeout +// - Terminal status monitoring +// +// FILE MANAGEMENT: +// - Directory browsing with file metadata +// - File/directory creation and deletion +// - File rename, copy, and move operations +// - File upload and download +// - Permissions, ownership, and size information +// - MIME type detection +// - Symlink target resolution +// +// FILE OPERATIONS: +// - Create: Create new files or directories +// - Delete: Remove files or directories +// - Rename: Rename files or directories +// - Copy: Duplicate files or directories +// - Move: Move files between locations +// - Upload: Upload files to session +// - Download: Download files from session +// +// SECURITY: +// - Access control via session ownership or sharing +// - User authentication required +// - Path validation to prevent directory traversal +// - Permission checks for file operations +// +// API Endpoints: +// - POST /api/v1/sessions/:sessionId/console - Create console session +// - GET /api/v1/console/:consoleId - Get console session details +// - DELETE /api/v1/console/:consoleId - Disconnect console session +// - GET /api/v1/console/:consoleId/files - List files in directory +// - POST /api/v1/console/:consoleId/files - Create file/directory +// - DELETE /api/v1/console/:consoleId/files - Delete file/directory +// - PUT /api/v1/console/:consoleId/files/rename - Rename file/directory +// - POST /api/v1/console/:consoleId/files/copy - Copy file/directory +// - POST /api/v1/console/:consoleId/files/move - Move file/directory +// - POST /api/v1/console/:consoleId/files/upload - Upload files +// - GET /api/v1/console/:consoleId/files/download - Download files +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - File operations are isolated per session +// +// Dependencies: +// - Database: console_sessions, sessions, session_shares tables +// - External Services: Session container filesystem access +// +// Example Usage: +// +// // Create console handler (integrated in main handler) +// handler.RegisterConsoleRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/dashboard.go b/api/internal/handlers/dashboard.go index f2afee1c..e0a8f579 100644 --- a/api/internal/handlers/dashboard.go +++ b/api/internal/handlers/dashboard.go @@ -1,3 +1,48 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements dashboard statistics and resource usage queries. +// +// DASHBOARD FEATURES: +// - Platform-wide statistics (users, sessions, templates, connections) +// - Resource usage tracking (CPU, memory, storage quotas) +// - Recent activity metrics (last 24 hours) +// - Real-time data from Kubernetes and database +// +// PLATFORM STATISTICS: +// - Total and active user counts +// - Session counts by state (running, hibernated, total) +// - Template count from Kubernetes CRDs +// - Active connection count +// - 24-hour activity metrics +// +// RESOURCE USAGE: +// - Quota utilization per user or platform-wide +// - CPU usage (millicores) +// - Memory usage (bytes/GB) +// - Storage usage (bytes/GB) +// - Session count against quotas +// +// DATA SOURCES: +// - Database: User, session, connection tables +// - Kubernetes: Template CRDs, resource quotas +// - Hybrid queries for comprehensive metrics +// +// API Endpoints: +// - GET /api/v1/dashboard/platform-stats - Overall platform statistics +// - GET /api/v1/dashboard/resource-usage - Resource usage metrics +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Kubernetes client operations are thread-safe +// +// Dependencies: +// - Database: users, sessions, connections tables +// - Kubernetes: Template CRDs, namespace resources +// - External Services: None +// +// Example Usage: +// +// handler := NewDashboardHandler(database, k8sClient) +// // Routes registered in main API router package handlers import ( diff --git a/api/internal/handlers/groups.go b/api/internal/handlers/groups.go index 47ab1700..1c4193b6 100644 --- a/api/internal/handlers/groups.go +++ b/api/internal/handlers/groups.go @@ -1,3 +1,52 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements group management and group-level resource operations. +// +// GROUP MANAGEMENT: +// - Group CRUD operations (list, create, read, update, delete) +// - Group filtering by type or parent group (supports hierarchical groups) +// - Group member management (add, remove, update roles) +// - Member enrichment with user information +// +// GROUP MEMBERSHIP: +// - Add users to groups with specific roles +// - Remove users from groups +// - Update member roles within groups +// - List all members with enriched user details +// - User existence validation before adding to groups +// +// GROUP QUOTAS: +// - Shared resource quotas for group members +// - Group-level limits for sessions, CPU, memory, storage +// - Quota retrieval and modification +// +// API Endpoints: +// - GET /api/v1/groups - List all groups with optional filters +// - POST /api/v1/groups - Create new group +// - GET /api/v1/groups/:id - Get group by ID +// - PATCH /api/v1/groups/:id - Update group information +// - DELETE /api/v1/groups/:id - Delete group +// - GET /api/v1/groups/:id/members - List group members +// - POST /api/v1/groups/:id/members - Add user to group +// - DELETE /api/v1/groups/:id/members/:userId - Remove user from group +// - PATCH /api/v1/groups/:id/members/:userId - Update member role +// - GET /api/v1/groups/:id/quota - Get group quota +// - PUT /api/v1/groups/:id/quota - Set group quota +// +// Security: +// - Password hashes removed from user objects in member lists +// - User existence validated before membership operations +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: groups, group_members, group_quotas, users tables +// - External Services: None +// +// Example Usage: +// +// handler := NewGroupHandler(groupDB, userDB) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/loadbalancing.go b/api/internal/handlers/loadbalancing.go index 39e13d78..b6c11ff5 100644 --- a/api/internal/handlers/loadbalancing.go +++ b/api/internal/handlers/loadbalancing.go @@ -1,3 +1,65 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements load balancing policies and node distribution strategies for sessions. +// +// LOAD BALANCING FEATURES: +// - Multiple load balancing strategies (round robin, least loaded, resource-based, geographic, weighted) +// - Node health monitoring and status tracking +// - Resource-based scheduling (CPU, memory thresholds) +// - Session affinity (sticky sessions) +// - Node selector and taints support +// - Geographic distribution preferences +// - Weighted node distribution +// +// LOAD BALANCING STRATEGIES: +// - round_robin: Distribute sessions evenly across nodes in rotation +// - least_loaded: Schedule on node with fewest active sessions +// - resource_based: Schedule based on available CPU/memory resources +// - geographic: Prefer nodes in specific regions/zones +// - weighted: Distribute based on configured node weights +// +// NODE HEALTH MONITORING: +// - Periodic health checks with configurable intervals +// - Failure and pass thresholds before status changes +// - Node readiness tracking from Kubernetes +// - Resource utilization monitoring +// - Health status: healthy, unhealthy, unknown +// +// RESOURCE THRESHOLDS: +// - Maximum CPU percentage before avoiding node +// - Maximum memory percentage before avoiding node +// - Maximum concurrent sessions per node +// - Minimum free CPU cores required +// - Minimum free memory required +// +// SESSION AFFINITY: +// - Sticky sessions to maintain user experience +// - Session-to-node mapping persistence +// - Reconnection to same node +// +// API Endpoints: +// - GET /api/v1/loadbalancing/policies - List load balancing policies +// - POST /api/v1/loadbalancing/policies - Create load balancing policy +// - GET /api/v1/loadbalancing/policies/:id - Get policy details +// - PUT /api/v1/loadbalancing/policies/:id - Update policy +// - DELETE /api/v1/loadbalancing/policies/:id - Delete policy +// - GET /api/v1/loadbalancing/nodes - List cluster nodes with status +// - GET /api/v1/loadbalancing/nodes/:name - Get node details +// - GET /api/v1/loadbalancing/nodes/:name/sessions - Get sessions on node +// - POST /api/v1/loadbalancing/select-node - Select best node for session +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Kubernetes client operations are thread-safe +// +// Dependencies: +// - Database: load_balancing_policies table +// - Kubernetes: Node metrics, resource status +// - External Services: Kubernetes metrics server +// +// Example Usage: +// +// // Create load balancing handler (integrated in main handler) +// handler.RegisterLoadBalancingRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/monitoring.go b/api/internal/handlers/monitoring.go index 0052bafc..4dc7e6d2 100644 --- a/api/internal/handlers/monitoring.go +++ b/api/internal/handlers/monitoring.go @@ -1,3 +1,71 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements monitoring, metrics, health checks, and alerting endpoints. +// +// MONITORING FEATURES: +// - Prometheus-compatible metrics export +// - Custom application metrics (sessions, users, resources) +// - Health check endpoints (liveness, readiness) +// - Performance metrics (response times, throughput) +// - System resource metrics (CPU, memory, goroutines) +// - Alert management (create, acknowledge, resolve) +// +// METRICS EXPORT: +// - Prometheus format (/monitoring/metrics/prometheus) +// - Session metrics (total, running, hibernated) +// - User metrics (total, active) +// - Resource metrics (CPU, memory, storage usage) +// - Performance metrics (response time percentiles) +// +// HEALTH CHECKS: +// - Basic health: /monitoring/health (200 if API is responding) +// - Detailed health: Database, storage, Kubernetes connectivity +// - Database health: Connection pool status, query latency +// - Storage health: NFS mount status, disk space +// +// SYSTEM METRICS: +// - Go runtime stats (goroutines, memory, GC) +// - Build information (version, git commit, build time) +// - Uptime and request counts +// - Resource usage trends +// +// ALERTING: +// - Create, read, update, delete alerts +// - Acknowledge and resolve workflows +// - Alert severity levels (info, warning, error, critical) +// - Alert filtering and querying +// +// API Endpoints: +// - GET /api/v1/monitoring/metrics/prometheus - Prometheus metrics +// - GET /api/v1/monitoring/metrics/sessions - Session metrics +// - GET /api/v1/monitoring/metrics/resources - Resource metrics +// - GET /api/v1/monitoring/metrics/users - User metrics +// - GET /api/v1/monitoring/metrics/performance - Performance metrics +// - GET /api/v1/monitoring/health - Basic health check +// - GET /api/v1/monitoring/health/detailed - Detailed health check +// - GET /api/v1/monitoring/health/database - Database health +// - GET /api/v1/monitoring/health/storage - Storage health +// - GET /api/v1/monitoring/system/info - System information +// - GET /api/v1/monitoring/system/stats - System statistics +// - GET /api/v1/monitoring/alerts - List alerts +// - POST /api/v1/monitoring/alerts - Create alert +// - GET /api/v1/monitoring/alerts/:id - Get alert +// - PUT /api/v1/monitoring/alerts/:id - Update alert +// - DELETE /api/v1/monitoring/alerts/:id - Delete alert +// - POST /api/v1/monitoring/alerts/:id/acknowledge - Acknowledge alert +// - POST /api/v1/monitoring/alerts/:id/resolve - Resolve alert +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Runtime metrics are thread-safe +// +// Dependencies: +// - Database: sessions, users, alerts tables +// - External Services: Prometheus scraping (optional) +// +// Example Usage: +// +// handler := NewMonitoringHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/notifications.go b/api/internal/handlers/notifications.go index f32b29bb..4fc8b09b 100644 --- a/api/internal/handlers/notifications.go +++ b/api/internal/handlers/notifications.go @@ -1,3 +1,83 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements notification delivery and management across multiple channels. +// +// NOTIFICATION FEATURES: +// - In-app notification management (create, read, delete) +// - Email notifications via SMTP +// - Webhook notifications with HMAC signatures +// - Multiple notification types (session events, quotas, teams, alerts) +// - Priority levels (low, normal, high, urgent) +// - Read/unread tracking +// - Notification preferences per user +// +// NOTIFICATION TYPES: +// - session.created: New session launched +// - session.idle: Session idle timeout warning +// - session.shared: Session shared with user +// - quota.warning: Approaching quota limits (80% threshold) +// - quota.exceeded: Quota limits exceeded +// - team.invitation: Invited to join team +// - system.alert: System-wide alerts +// +// NOTIFICATION CHANNELS: +// - In-app: Stored in database, retrieved via API +// - Email: Sent via SMTP with HTML templates +// - Webhook: HTTP POST to user-configured URLs +// - Integration: Slack, Teams, Discord (via integrations handler) +// +// PRIORITY LEVELS: +// - low: Non-urgent informational messages +// - normal: Standard notifications +// - high: Important notifications requiring attention +// - urgent: Critical notifications requiring immediate action +// +// IN-APP NOTIFICATIONS: +// - Persistent storage in database +// - Unread count tracking +// - Mark as read individually or in bulk +// - Delete individually or clear all +// - Action URLs for quick navigation +// - Pagination support +// +// EMAIL NOTIFICATIONS: +// - HTML template rendering +// - SMTP configuration (host, port, auth) +// - Configurable from/reply-to addresses +// - Environment variable configuration +// - Test email endpoint for debugging +// +// WEBHOOK NOTIFICATIONS: +// - HMAC-SHA256 signature for verification +// - JSON payload with notification data +// - User-configured webhook URLs +// - Test webhook endpoint for debugging +// +// API Endpoints: +// - GET /api/v1/notifications - List user notifications +// - GET /api/v1/notifications/unread - Get unread notifications +// - GET /api/v1/notifications/count - Get unread count +// - POST /api/v1/notifications/:id/read - Mark as read +// - POST /api/v1/notifications/read-all - Mark all as read +// - DELETE /api/v1/notifications/:id - Delete notification +// - DELETE /api/v1/notifications/clear-all - Clear all notifications +// - POST /api/v1/notifications/send - Send notification (admin) +// - GET /api/v1/notifications/preferences - Get notification preferences +// - PUT /api/v1/notifications/preferences - Update notification preferences +// - POST /api/v1/notifications/test/email - Test email delivery +// - POST /api/v1/notifications/test/webhook - Test webhook delivery +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - SMTP client is created per-request +// +// Dependencies: +// - Database: notifications, user_preferences tables +// - External Services: SMTP server for email delivery +// +// Example Usage: +// +// handler := NewNotificationsHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/preferences.go b/api/internal/handlers/preferences.go index 5a3064f1..ec9b7d5b 100644 --- a/api/internal/handlers/preferences.go +++ b/api/internal/handlers/preferences.go @@ -1,3 +1,79 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements user preference management and customization settings. +// +// PREFERENCE FEATURES: +// - User-specific preference storage (JSON-based) +// - UI preferences (theme, layout, language, timezone) +// - Notification preferences (enabled channels, frequency) +// - Default session settings (resources, templates) +// - Favorite templates management +// - Recent session tracking +// +// PREFERENCE CATEGORIES: +// +// 1. UI Preferences: +// - Theme (light, dark, auto) +// - Layout preferences (sidebar, density) +// - Language and locale +// - Timezone for timestamps +// - Default view modes +// +// 2. Notification Preferences: +// - Email notifications enabled/disabled +// - In-app notifications enabled/disabled +// - Webhook notifications +// - Notification types to receive +// - Notification frequency/batching +// +// 3. Default Session Settings: +// - Default template selection +// - Default resource allocations (CPU, memory) +// - Default idle timeout +// - Default hibernation settings +// - Auto-start preferences +// +// 4. Favorites: +// - Favorite template list +// - Quick access templates +// - Template ordering +// +// 5. Recent Sessions: +// - Recently accessed sessions +// - Session history limit +// - Timestamp tracking +// +// PREFERENCE STORAGE: +// - JSON-based flexible schema +// - Per-user preference isolation +// - Default preferences for new users +// - Merge strategy for partial updates +// +// API Endpoints: +// - GET /api/v1/preferences - Get all user preferences +// - PUT /api/v1/preferences - Update all preferences +// - DELETE /api/v1/preferences - Reset to defaults +// - GET /api/v1/preferences/ui - Get UI preferences +// - PUT /api/v1/preferences/ui - Update UI preferences +// - GET /api/v1/preferences/notifications - Get notification preferences +// - PUT /api/v1/preferences/notifications - Update notification preferences +// - GET /api/v1/preferences/defaults - Get default session settings +// - PUT /api/v1/preferences/defaults - Update default session settings +// - GET /api/v1/preferences/favorites - Get favorite templates +// - POST /api/v1/preferences/favorites/:templateName - Add favorite +// - DELETE /api/v1/preferences/favorites/:templateName - Remove favorite +// - GET /api/v1/preferences/recent - Get recent sessions +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: user_preferences table +// - External Services: None +// +// Example Usage: +// +// handler := NewPreferencesHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/search.go b/api/internal/handlers/search.go index 50c29e8b..b65e31f2 100644 --- a/api/internal/handlers/search.go +++ b/api/internal/handlers/search.go @@ -1,3 +1,74 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements advanced search, filtering, and saved search functionality. +// +// SEARCH FEATURES: +// - Universal search across templates, sessions, users +// - Full-text search with relevance scoring +// - Advanced filtering (category, tags, app type) +// - Auto-complete suggestions +// - Saved search queries +// - Search history tracking +// +// SEARCH TYPES: +// - Universal: Search across all resource types +// - Templates: Search template catalog +// - Sessions: Search user sessions +// - Suggestions: Auto-complete for search input +// - Advanced: Multi-filter complex queries +// +// SEARCH RESULTS: +// - Type-specific results (template, session, user) +// - Relevance scoring +// - Result metadata (category, tags, icons) +// - Pagination support +// +// FILTERING: +// - Categories: Filter by template/session category +// - Tags: Filter by tags +// - App Types: Filter by application type +// - Multiple filters combined with AND logic +// +// SAVED SEARCHES: +// - Save frequently used search queries +// - Named searches for quick access +// - Execute saved searches +// - Update and delete saved searches +// - User-specific saved searches +// +// SEARCH HISTORY: +// - Track user search queries +// - Timestamp tracking +// - Result count tracking +// - History limits per user +// +// API Endpoints: +// - GET /api/v1/search - Universal search +// - GET /api/v1/search/templates - Template-specific search +// - GET /api/v1/search/sessions - Session search +// - GET /api/v1/search/suggest - Auto-complete suggestions +// - GET /api/v1/search/advanced - Advanced multi-filter search +// - GET /api/v1/search/filters/categories - List all categories +// - GET /api/v1/search/filters/tags - List popular tags +// - GET /api/v1/search/filters/app-types - List app types +// - GET /api/v1/search/saved - List saved searches +// - POST /api/v1/search/saved - Create saved search +// - GET /api/v1/search/saved/:id - Get saved search +// - PUT /api/v1/search/saved/:id - Update saved search +// - DELETE /api/v1/search/saved/:id - Delete saved search +// - POST /api/v1/search/saved/:id/execute - Execute saved search +// - GET /api/v1/search/history - Get search history +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: catalog_templates, sessions, users, saved_searches, search_history tables +// - External Services: None +// +// Example Usage: +// +// handler := NewSearchHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/sessionactivity.go b/api/internal/handlers/sessionactivity.go index 01ae1d5a..b73fb9ca 100644 --- a/api/internal/handlers/sessionactivity.go +++ b/api/internal/handlers/sessionactivity.go @@ -1,3 +1,66 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements session activity logging and audit trail functionality. +// +// SESSION ACTIVITY FEATURES: +// - Comprehensive session event logging +// - Activity timeline and audit trail +// - Event categorization (lifecycle, connection, state, configuration, access, error) +// - User action tracking with IP addresses and user agents +// - Activity statistics and analytics +// - Activity export for compliance +// +// EVENT CATEGORIES: +// - lifecycle: Session creation, startup, termination, deletion +// - connection: User connections, disconnections, heartbeats +// - state: State changes (running, hibernated, stopped) +// - configuration: Resource updates, config changes, tag updates +// - access: Permission grants, denials, sharing events +// - error: Error occurrences and exceptions +// +// EVENT TYPES: +// - session.created, session.started, session.stopped, session.hibernated +// - session.woken, session.terminated, session.deleted +// - user.connected, user.disconnected, user.heartbeat +// - state.changed, resources.updated, config.updated, tags.updated +// - access.granted, access.denied, share.created, share.revoked +// - error.occurred +// +// ACTIVITY LOGGING: +// - Automatic event logging for all session operations +// - Manual event logging via API +// - Metadata capture (user ID, IP address, user agent) +// - Timestamp tracking with millisecond precision +// +// ACTIVITY QUERIES: +// - List session activity timeline +// - Filter by event type or category +// - Date range filtering +// - Pagination support +// - Export to CSV/JSON for compliance +// +// ACTIVITY STATISTICS: +// - Event count by type +// - Activity heatmap data +// - User activity patterns +// - Session usage analytics +// +// API Endpoints: +// - POST /api/v1/sessions/:id/activity/log - Log activity event +// - GET /api/v1/sessions/:id/activity - Get session activity timeline +// - GET /api/v1/sessions/:id/activity/stats - Get activity statistics +// - GET /api/v1/sessions/:id/activity/export - Export activity data +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: session_activity_events table +// - External Services: None +// +// Example Usage: +// +// handler := NewSessionActivityHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/sessiontemplates.go b/api/internal/handlers/sessiontemplates.go index dfe36d59..9894be25 100644 --- a/api/internal/handlers/sessiontemplates.go +++ b/api/internal/handlers/sessiontemplates.go @@ -1,3 +1,81 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements custom session template management and presets. +// +// SESSION TEMPLATE FEATURES: +// - User-defined session configuration templates +// - Template CRUD operations (create, read, update, delete) +// - Template visibility (private, team, public) +// - Template cloning and versioning +// - Template sharing within teams +// - Create templates from existing sessions +// - Usage tracking and analytics +// +// TEMPLATE VISIBILITY: +// - private: Only visible to template owner +// - team: Visible to team members +// - public: Visible to all users (requires approval) +// +// TEMPLATE STRUCTURE: +// - Based on catalog template (base template reference) +// - Custom configuration overrides +// - Resource allocations (CPU, memory) +// - Environment variables +// - Tags and categorization +// - Version tracking +// +// TEMPLATE OPERATIONS: +// - Create: Define new template from scratch or from session +// - Clone: Duplicate existing template +// - Use: Launch session from template +// - Publish/Unpublish: Make template public or private +// - Share: Share with specific users or teams +// +// TEMPLATE SHARING: +// - Share templates with users or teams +// - Permission levels (view, use, edit) +// - Revoke shares +// - Track who has access +// +// TEMPLATE VERSIONING: +// - Version history tracking +// - Restore previous versions +// - Version comparison +// - Change logs +// +// QUICK ACTIONS: +// - Create template from running session +// - Set as default template for user +// - Clone template with modifications +// +// API Endpoints: +// - GET /api/v1/session-templates - List session templates +// - POST /api/v1/session-templates - Create session template +// - GET /api/v1/session-templates/:id - Get template details +// - PUT /api/v1/session-templates/:id - Update template +// - DELETE /api/v1/session-templates/:id - Delete template +// - POST /api/v1/session-templates/:id/clone - Clone template +// - POST /api/v1/session-templates/:id/use - Launch session from template +// - POST /api/v1/session-templates/:id/publish - Make template public +// - POST /api/v1/session-templates/:id/unpublish - Make template private +// - GET /api/v1/session-templates/:id/shares - List template shares +// - POST /api/v1/session-templates/:id/share - Share template +// - DELETE /api/v1/session-templates/:id/shares/:shareId - Revoke share +// - GET /api/v1/session-templates/:id/versions - List template versions +// - POST /api/v1/session-templates/:id/versions - Create version +// - POST /api/v1/session-templates/:id/versions/:version/restore - Restore version +// - POST /api/v1/session-templates/from-session/:sessionId - Create from session +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: session_templates, template_shares, template_versions tables +// - External Services: None +// +// Example Usage: +// +// handler := NewSessionTemplatesHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/sharing.go b/api/internal/handlers/sharing.go index ab0c6ff3..e9b48716 100644 --- a/api/internal/handlers/sharing.go +++ b/api/internal/handlers/sharing.go @@ -1,3 +1,75 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements session sharing and collaboration features. +// +// SESSION SHARING FEATURES: +// - Direct user-to-user session sharing with permission levels +// - Shareable invitation links with expiration and usage limits +// - Share revocation and ownership transfer +// - Collaborator tracking and activity monitoring +// +// PERMISSION LEVELS: +// - view: Read-only access to view the session +// - collaborate: Can interact but has limited control +// - control: Full control equivalent to owner +// +// SHARING METHODS: +// +// 1. Direct Shares: +// - Share with specific users by user ID +// - Owner-only operation +// - Requires user existence validation +// - Supports expiration timestamps +// - Generates unique share tokens +// +// 2. Invitation Links: +// - Generate shareable invitation tokens +// - Configurable max uses and expiration +// - Anyone with link can accept (until exhausted/expired) +// - Tracks usage count +// +// OWNERSHIP TRANSFER: +// - Transfer session ownership to another user +// - Requires current owner authorization +// - Validates new owner exists +// +// COLLABORATOR MANAGEMENT: +// - Track active collaborators in sessions +// - Update activity timestamps +// - Remove collaborators +// - Permission inheritance from shares +// +// API Endpoints: +// - POST /api/v1/sessions/:id/share - Create direct share with user +// - GET /api/v1/sessions/:id/shares - List all shares for session +// - DELETE /api/v1/sessions/:id/shares/:shareId - Revoke a share +// - POST /api/v1/sessions/:id/transfer - Transfer ownership +// - POST /api/v1/sessions/:id/invitations - Create invitation link +// - GET /api/v1/sessions/:id/invitations - List invitations +// - DELETE /api/v1/invitations/:token - Revoke invitation +// - POST /api/v1/invitations/:token/accept - Accept invitation +// - GET /api/v1/sessions/:id/collaborators - List active collaborators +// - POST /api/v1/sessions/:id/collaborators/:userId/activity - Update activity +// - DELETE /api/v1/sessions/:id/collaborators/:userId - Remove collaborator +// - GET /api/v1/shared-sessions - List sessions shared with user +// +// Security: +// - Owner-only operations for sharing and transfer +// - User existence validation +// - Expiration and usage limit enforcement +// - Authorization checks for all operations +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// - Atomic upsert operations for collaborators and shares +// +// Dependencies: +// - Database: sessions, session_shares, session_share_invitations, session_collaborators, users tables +// - External Services: None +// +// Example Usage: +// +// handler := NewSharingHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/teams.go b/api/internal/handlers/teams.go index ad43bcf0..29531c4b 100644 --- a/api/internal/handlers/teams.go +++ b/api/internal/handlers/teams.go @@ -1,3 +1,48 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements team-based Role-Based Access Control (RBAC) operations. +// +// TEAM RBAC FEATURES: +// - Team permissions and role management +// - User permission queries within teams +// - Team session access control +// - Permission checking for authorization +// +// TEAM PERMISSIONS: +// - Role-based permissions (owner, admin, member, viewer, etc.) +// - Permission inheritance from team roles +// - User-specific permission queries +// - Permission validation for resource access +// +// TEAM SESSIONS: +// - List sessions belonging to a specific team +// - Permission-based access control (requires team.sessions.view) +// - Team member authorization +// +// API Endpoints: +// - GET /api/v1/teams/:teamId/permissions - Get all team role permissions +// - GET /api/v1/teams/:teamId/role-info - Get available team roles +// - GET /api/v1/teams/:teamId/my-permissions - Get current user's permissions +// - GET /api/v1/teams/:teamId/check-permission/:permission - Check specific permission +// - GET /api/v1/teams/:teamId/sessions - List team sessions (requires permission) +// - GET /api/v1/teams/my-teams - Get current user's team memberships +// +// Security: +// - Authentication required for all endpoints +// - Permission-based authorization for sensitive operations +// - Safe type assertions to prevent panics +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: teams, team_members, team_role_permissions, sessions tables +// - Middleware: TeamRBAC for permission checks +// - External Services: None +// +// Example Usage: +// +// handler := NewTeamHandler(database) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/template_versioning.go b/api/internal/handlers/template_versioning.go index 0cbb0835..26297892 100644 --- a/api/internal/handlers/template_versioning.go +++ b/api/internal/handlers/template_versioning.go @@ -1,3 +1,70 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements template versioning, testing, and inheritance management. +// +// TEMPLATE VERSIONING FEATURES: +// - Semantic versioning (major.minor.patch) +// - Version lifecycle (draft, testing, stable, deprecated) +// - Version testing and validation +// - Template inheritance (parent-child relationships) +// - Version comparison and diff +// - Rollback to previous versions +// +// VERSION LIFECYCLE: +// - draft: Work in progress, not ready for use +// - testing: Undergoing validation tests +// - stable: Production-ready, recommended for use +// - deprecated: Old version, migration recommended +// +// VERSION MANAGEMENT: +// - Create new versions with semantic versioning +// - Set default version for template +// - Publish versions for public use +// - Deprecate outdated versions +// - Track version metadata (changelog, test results) +// +// TEMPLATE TESTING: +// - Automated template validation +// - Test types: startup, smoke, functional, performance +// - Test status tracking: pending, running, passed, failed +// - Test results with duration and error messages +// - Test execution history +// +// TEMPLATE INHERITANCE: +// - Parent-child template relationships +// - Field inheritance and overrides +// - Inherited field tracking +// - Override visualization +// - Template family trees +// +// VERSION COMPARISON: +// - Compare configurations between versions +// - Highlight differences +// - Migration guides between versions +// +// API Endpoints: +// - POST /api/v1/templates/:id/versions - Create template version +// - GET /api/v1/templates/:id/versions - List template versions +// - GET /api/v1/templates/:id/versions/:version - Get version details +// - PUT /api/v1/templates/:id/versions/:version - Update version +// - DELETE /api/v1/templates/:id/versions/:version - Delete version +// - POST /api/v1/templates/:id/versions/:version/publish - Publish version +// - POST /api/v1/templates/:id/versions/:version/deprecate - Deprecate version +// - POST /api/v1/templates/:id/versions/:version/test - Run version tests +// - GET /api/v1/templates/:id/versions/:version/tests - Get test results +// - GET /api/v1/templates/:id/inheritance - Get template inheritance tree +// - POST /api/v1/templates/:id/inherit-from - Set parent template +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: template_versions, template_tests, template_inheritance tables +// - External Services: Test execution infrastructure +// +// Example Usage: +// +// // Create version handler (integrated in main handler) +// handler.RegisterTemplateVersioningRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/handlers/types.go b/api/internal/handlers/types.go index 2dee1f1f..454fe1fc 100644 --- a/api/internal/handlers/types.go +++ b/api/internal/handlers/types.go @@ -1,3 +1,19 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file defines common response types used across all handler files. +// +// COMMON TYPES: +// - ErrorResponse: Standardized error response format +// - SuccessResponse: Standardized success message format +// +// These types provide consistency across all API endpoints for error handling +// and success messaging. All handlers in this package use these types to +// ensure uniform API response structures. +// +// Thread Safety: +// - These are simple data structures with no shared state +// +// Dependencies: +// - None (pure data types) package handlers // ErrorResponse represents an error response diff --git a/api/internal/handlers/users.go b/api/internal/handlers/users.go index 2a3e2efd..a943d614 100644 --- a/api/internal/handlers/users.go +++ b/api/internal/handlers/users.go @@ -1,3 +1,55 @@ +// Package handlers provides HTTP handlers for the StreamSpace API. +// This file implements user management and user-level resource quota operations. +// +// USER MANAGEMENT: +// - User CRUD operations (list, create, read, update, delete) +// - User profile management (/me endpoints for current user) +// - User filtering by role, provider, or active status +// - Password hash sanitization (never exposed in responses) +// +// QUOTA MANAGEMENT: +// - Per-user resource quotas (sessions, CPU, memory, storage) +// - Quota retrieval for current user and specific users +// - Admin quota management (list all, set, delete/reset) +// - Username-based quota operations for admin convenience +// +// USER ASSOCIATIONS: +// - User sessions (redirects to /sessions?user=id) +// - User group memberships +// +// API Endpoints: +// - GET /api/v1/users - List all users with optional filters +// - POST /api/v1/users - Create new user account +// - GET /api/v1/users/me - Get current authenticated user +// - GET /api/v1/users/me/quota - Get current user's quota +// - GET /api/v1/users/:id - Get user by ID +// - PATCH /api/v1/users/:id - Update user information +// - DELETE /api/v1/users/:id - Delete user account +// - GET /api/v1/users/:id/sessions - Get user's sessions +// - GET /api/v1/users/:id/quota - Get user's resource quota +// - PUT /api/v1/users/:id/quota - Set user's resource quota +// - GET /api/v1/users/:id/groups - Get user's group memberships +// - GET /api/v1/admin/quotas - List all user quotas (admin) +// - GET /api/v1/admin/quotas/:username - Get quota by username (admin) +// - PUT /api/v1/admin/quotas - Set quota by username (admin) +// - DELETE /api/v1/admin/quotas/:username - Reset quota to defaults (admin) +// +// Security: +// - Password hashes are sanitized before returning user objects +// - Safe type assertions prevent panics +// - Authentication required via middleware for protected endpoints +// +// Thread Safety: +// - All database operations are thread-safe via connection pooling +// +// Dependencies: +// - Database: users, user_quotas, user_groups tables +// - External Services: None +// +// Example Usage: +// +// handler := NewUserHandler(userDB, groupDB) +// handler.RegisterRoutes(router.Group("/api/v1")) package handlers import ( diff --git a/api/internal/k8s/client.go b/api/internal/k8s/client.go index 595c9bc0..6a9b0c4a 100644 --- a/api/internal/k8s/client.go +++ b/api/internal/k8s/client.go @@ -1,3 +1,80 @@ +// Package k8s provides Kubernetes client functionality for StreamSpace CRD operations. +// +// This file implements the Kubernetes client wrapper for StreamSpace custom resources. +// +// Purpose: +// - Provide typed access to StreamSpace CRDs (Session, Template) +// - Wrap Kubernetes dynamic client for custom resource operations +// - Simplify CRUD operations on Sessions and Templates +// - Watch for changes to sessions and templates +// - Access core Kubernetes resources (Pods, Services, PVCs, Nodes) +// +// Features: +// - Session management (create, get, list, update, delete, watch) +// - Template management (create, get, list, delete, watch) +// - State transitions (running → hibernated → terminated) +// - Resource filtering (by user, category, labels) +// - Cluster resource introspection (nodes, pods, services) +// - Auto-configuration (in-cluster or kubeconfig) +// +// Custom Resource Definitions: +// - Sessions (stream.streamspace.io/v1alpha1) +// - Represents a user's containerized workspace session +// - States: running, hibernated, terminated +// - Includes resource limits, idle timeout, persistence settings +// +// - Templates (stream.streamspace.io/v1alpha1) +// - Defines application templates (Firefox, VS Code, etc.) +// - Contains container image, VNC/webapp config, resources +// - Categorized for catalog organization +// +// Implementation Details: +// - Uses Kubernetes dynamic client for CRD operations +// - Auto-detects in-cluster vs local configuration +// - Parses unstructured data to typed Go structs +// - Supports namespace isolation (default: "streamspace") +// - Thread-safe client operations +// +// Thread Safety: +// - Kubernetes clients are thread-safe +// - Safe for concurrent access across goroutines +// +// Dependencies: +// - k8s.io/client-go for Kubernetes API access +// - k8s.io/api for core resource types +// +// Example Usage: +// +// // Initialize client +// client, err := k8s.NewClient() +// if err != nil { +// log.Fatal(err) +// } +// +// // Create a session +// session := &k8s.Session{ +// Name: "user1-firefox", +// Namespace: "streamspace", +// User: "user1", +// Template: "firefox-browser", +// State: "running", +// PersistentHome: true, +// IdleTimeout: "30m", +// } +// created, err := client.CreateSession(ctx, session) +// +// // List sessions for a user +// sessions, err := client.ListSessionsByUser(ctx, "streamspace", "user1") +// +// // Update session state (hibernate) +// updated, err := client.UpdateSessionState(ctx, "streamspace", "user1-firefox", "hibernated") +// +// // Watch for session changes +// watcher, err := client.WatchSessions(ctx, "streamspace") +// for event := range watcher.ResultChan() { +// session := event.Object.(*unstructured.Unstructured) +// // Handle session change +// } package k8s import ( diff --git a/api/internal/middleware/compression.go b/api/internal/middleware/compression.go index bbd49829..beb76333 100644 --- a/api/internal/middleware/compression.go +++ b/api/internal/middleware/compression.go @@ -1,3 +1,47 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements HTTP response compression using gzip. +// +// Purpose: +// The compression middleware reduces bandwidth usage and improves response times +// by compressing HTTP responses with gzip encoding. This is especially beneficial +// for JSON API responses which typically compress to 60-80% smaller sizes. +// +// Implementation Details: +// - Uses sync.Pool for gzip writer reuse (reduces memory allocations) +// - Configurable compression levels (BestSpeed, DefaultCompression, BestCompression) +// - Automatic skip for incompressible content (WebSocket, Server-Sent Events) +// - Wraps response writer transparently (handlers unaware of compression) +// +// Performance Characteristics: +// - Best Speed (level 1): 2-3x faster, 70-80% compression ratio +// - Default (level 6): Balanced, 60-70% compression ratio +// - Best Compression (level 9): Slowest, 50-60% compression ratio +// - Memory: ~256KB per concurrent request (reused via sync.Pool) +// - CPU overhead: 1-5ms per response (depending on compression level and payload size) +// +// Thread Safety: +// Safe for concurrent use. Each request gets its own gzip writer from the pool, +// uses it for the duration of the request, then returns it to the pool. +// +// Usage: +// // Use default compression (level 6) +// router.Use(middleware.Gzip(middleware.DefaultCompression)) +// +// // Use best speed (level 1) for high-throughput APIs +// router.Use(middleware.Gzip(middleware.BestSpeed)) +// +// // Exclude specific paths from compression +// router.Use(middleware.GzipWithExclusions( +// middleware.DefaultCompression, +// []string{"/api/v1/ws/", "/api/v1/upload"}, +// )) +// +// Configuration: +// // Available compression levels +// middleware.NoCompression // No compression (level 0) +// middleware.BestSpeed // Fastest compression (level 1) +// middleware.DefaultCompression // Balanced (level 6) +// middleware.BestCompression // Maximum compression (level 9) package middleware import ( diff --git a/api/internal/middleware/inputvalidation.go b/api/internal/middleware/inputvalidation.go index de313767..8fa5317c 100644 --- a/api/internal/middleware/inputvalidation.go +++ b/api/internal/middleware/inputvalidation.go @@ -1,3 +1,52 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements comprehensive input validation and sanitization. +// +// Purpose: +// The input validation middleware protects against injection attacks by validating +// and sanitizing all user input including query parameters, path parameters, and +// request bodies. This prevents SQL injection, XSS, command injection, LDAP injection, +// and path traversal attacks. +// +// Implementation Details: +// - Path validation: Detects path traversal patterns (../, %2e%2e, etc.) +// - Query parameter validation: Checks for injection patterns in all query strings +// - JSON sanitization: Recursively sanitizes nested objects and arrays using bluemonday +// - Format validation: Validates usernames, emails, Kubernetes resource names, container images +// - Length limits: Prevents buffer overflow with 10KB max input size +// - Pattern detection: Regex-based detection of SQL, command, and LDAP injection attempts +// +// Security Notes: +// This middleware provides defense-in-depth against common web vulnerabilities: +// - SQL Injection: Detects UNION, SELECT, DROP, etc. patterns +// - XSS (Cross-Site Scripting): Bluemonday strips all HTML tags and dangerous content +// - Command Injection: Blocks shell metacharacters (;, |, &, backticks, $()) +// - LDAP Injection: Detects LDAP special characters when used in combinations +// - Path Traversal: Prevents directory traversal attacks (../, ..\, null bytes) +// - Buffer Overflow: Enforces 10KB limit on input values +// +// Thread Safety: +// Safe for concurrent use. Each request gets its own validation context. +// The bluemonday policy is thread-safe and shared across all requests. +// +// Usage: +// // Basic input validation on all routes +// validator := middleware.NewInputValidator() +// router.Use(validator.Middleware()) +// +// // JSON sanitization for API endpoints +// router.Use(validator.SanitizeJSONMiddleware()) +// +// // Standalone validation functions +// if err := middleware.ValidateUsername(username); err != nil { +// return err +// } +// if err := middleware.ValidateEmail(email); err != nil { +// return err +// } +// +// Configuration: +// // Bluemonday uses StrictPolicy by default (strips ALL HTML) +// // To customize, modify the policy in NewInputValidator() package middleware import ( diff --git a/api/internal/middleware/methodrestriction.go b/api/internal/middleware/methodrestriction.go index 9303bede..e556cda1 100644 --- a/api/internal/middleware/methodrestriction.go +++ b/api/internal/middleware/methodrestriction.go @@ -1,3 +1,51 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements HTTP method restriction to prevent abuse through uncommon methods. +// +// Purpose: +// This middleware restricts incoming requests to only commonly-used, safe HTTP methods. +// It prevents security issues and attacks that exploit uncommon or dangerous methods +// like TRACE (XSS via HTTP response splitting) and CONNECT (proxy abuse). +// +// Implementation Details: +// - AllowedHTTPMethods: Whitelist approach (only allow known-safe methods) +// - DisallowedHTTPMethods: Blacklist approach (explicitly block dangerous methods) +// - Returns 405 Method Not Allowed with Allow header +// - Defense in depth: Use both middlewares together for maximum security +// +// Security Notes: +// Dangerous HTTP methods and why they're blocked: +// - TRACE: Can be used in XSS attacks (cross-site tracing) +// * Reflects request in response body +// * Can expose authentication cookies +// * Bypasses HttpOnly cookie protection +// - TRACK: Microsoft proprietary variant of TRACE (same vulnerability) +// - CONNECT: Used for HTTP tunneling (proxy abuse) +// * Only needed for proxy servers +// * Can be used to bypass firewalls +// * Can create unauthorized tunnels +// +// Allowed methods (safe for web APIs): +// - GET: Read resources (idempotent, safe) +// - POST: Create resources (not idempotent) +// - PUT: Update resources (idempotent) +// - PATCH: Partial update (not idempotent) +// - DELETE: Remove resources (idempotent) +// - OPTIONS: CORS preflight (required for browser APIs) +// - HEAD: Metadata only (idempotent, safe) +// +// Thread Safety: +// Safe for concurrent use. No shared state between requests. +// +// Usage: +// // Whitelist safe methods (recommended) +// router.Use(middleware.AllowedHTTPMethods()) +// +// // Blacklist dangerous methods (additional protection) +// router.Use(middleware.DisallowedHTTPMethods()) +// +// // Defense in depth (use both) +// router.Use(middleware.AllowedHTTPMethods()) +// router.Use(middleware.DisallowedHTTPMethods()) package middleware import ( diff --git a/api/internal/middleware/request_id.go b/api/internal/middleware/request_id.go index dd33795b..00431a5a 100644 --- a/api/internal/middleware/request_id.go +++ b/api/internal/middleware/request_id.go @@ -1,3 +1,53 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements request ID generation and correlation. +// +// Purpose: +// The request ID middleware provides unique identifiers for each HTTP request, +// enabling distributed tracing, log correlation, and debugging across multiple +// services and components. This is essential for troubleshooting issues in +// production environments. +// +// Implementation Details: +// - Generates UUIDv4 for each request (or accepts existing from client) +// - Stores in Gin context for handlers to access +// - Adds to response header (X-Request-ID) so clients can reference +// - Enables correlation across logs, metrics, and traces +// - Idempotent: Preserves existing request ID from upstream services +// +// Use Cases: +// 1. Distributed Tracing: Follow a request across multiple microservices +// - API Gateway → StreamSpace API → Kubernetes Controller → Database +// - All logs share the same request ID for easy correlation +// +// 2. Log Correlation: Find all log entries for a specific request +// - User reports error at 10:35:42 AM +// - Search logs for request ID from error response +// - View complete request lifecycle (auth, validation, processing, error) +// +// 3. Customer Support: Users can provide request ID when reporting issues +// - Error message shows: "Request ID: 550e8400-e29b-41d4-a716-446655440000" +// - Support team searches logs with this ID +// - Full context available for debugging +// +// 4. Performance Analysis: Track slow requests end-to-end +// - Identify which service/component caused the delay +// - Compare timing across different layers +// +// Thread Safety: +// Safe for concurrent use. Each request gets its own unique UUID. +// +// Usage: +// // Add to middleware chain (should be first for complete tracing) +// router.Use(middleware.RequestID()) +// +// // Access in handlers +// func MyHandler(c *gin.Context) { +// requestID := middleware.GetRequestID(c) +// log.Printf("[%s] Processing request", requestID) +// } +// +// // Client can send existing request ID for distributed tracing +// // curl -H "X-Request-ID: my-trace-id" https://api.streamspace.io/sessions package middleware import ( diff --git a/api/internal/middleware/sessionmanagement.go b/api/internal/middleware/sessionmanagement.go index c5d7ef5c..e652773c 100644 --- a/api/internal/middleware/sessionmanagement.go +++ b/api/internal/middleware/sessionmanagement.go @@ -1,3 +1,62 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements enhanced session security with idle timeout and concurrency limits. +// +// Purpose: +// The session management middleware provides security features for user authentication +// sessions including automatic logout after inactivity and enforcement of concurrent +// session limits to prevent credential sharing and session hijacking. +// +// Implementation Details: +// - Idle timeout: Automatically invalidates sessions after period of inactivity +// - Activity tracking: Updates last activity timestamp on every authenticated request +// - Concurrent sessions: Limits number of simultaneous logins per user account +// - Memory cleanup: Periodic background cleanup prevents memory leaks +// - In-memory storage: Fast but not distributed (single-server only) +// +// Security Notes: +// This middleware addresses critical security concerns: +// +// 1. Idle Timeout (Prevents Session Hijacking): +// - User forgets to log out on public computer +// - Without timeout: Session stays active indefinitely (attacker can use it) +// - With timeout: Session expires after 30 minutes of inactivity +// +// 2. Concurrent Session Limits (Prevents Credential Sharing): +// - User shares login credentials with colleagues +// - Without limit: Unlimited concurrent sessions (credential abuse) +// - With limit: Max 5 concurrent sessions (discourages sharing) +// +// 3. Session Cleanup (Prevents Memory Leaks): +// - Long-running server accumulates millions of session entries +// - Without cleanup: Memory usage grows unbounded (eventual crash) +// - With cleanup: Stale sessions removed every 5 minutes +// +// Thread Safety: +// Safe for concurrent use. Uses sync.RWMutex for thread-safe access to session maps. +// +// Usage: +// // Create session manager with 30-minute idle timeout and max 5 concurrent sessions +// sessionMgr := middleware.NewSessionManager(30*time.Minute, 5) +// +// // Apply idle timeout check to all authenticated routes +// router.Use(sessionMgr.IdleTimeoutMiddleware()) +// +// // Track session activity on every request +// router.Use(sessionMgr.SessionActivityMiddleware()) +// +// // In login handler, register new session +// if err := sessionMgr.RegisterSession(username, sessionID); err != nil { +// // Max sessions exceeded +// return c.JSON(403, gin.H{"error": "Maximum concurrent sessions reached"}) +// } +// +// // In logout handler, unregister session +// sessionMgr.UnregisterSession(username, sessionID) +// +// Configuration: +// idleTimeout: 30*time.Minute // Session expires after 30 min inactivity +// maxSessions: 5 // Max 5 concurrent logins per user +// cleanupInterval: 5*time.Minute // Cleanup runs every 5 minutes package middleware import ( diff --git a/api/internal/middleware/structured_logger.go b/api/internal/middleware/structured_logger.go index 4f406f67..9a660216 100644 --- a/api/internal/middleware/structured_logger.go +++ b/api/internal/middleware/structured_logger.go @@ -1,3 +1,56 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements structured request logging. +// +// Purpose: +// The structured logger middleware captures detailed information about every HTTP +// request in a consistent, machine-parseable format. This enables log analysis, +// alerting, debugging, and observability in production environments. +// +// Implementation Details: +// - Structured format: Key-value pairs instead of unstructured text +// - Request correlation: Includes request ID for distributed tracing +// - User tracking: Logs authenticated user information when available +// - Performance metrics: Captures request duration in milliseconds +// - Error tracking: Logs Gin errors if any occurred during request processing +// - Configurable skipping: Can skip health check endpoints to reduce noise +// +// Logged Fields: +// - request_id: Correlation ID for distributed tracing (from RequestID middleware) +// - method: HTTP method (GET, POST, PUT, DELETE, etc.) +// - path: Request path (/api/v1/sessions) +// - query: Query string parameters (if enabled) +// - status: HTTP status code (200, 404, 500, etc.) +// - duration: Request processing time (human-readable: "125ms") +// - duration_ms: Request processing time in milliseconds (for metrics: 125) +// - client_ip: Client IP address +// - user_agent: Browser/client user agent string +// - user_id: Authenticated user ID (if authenticated) +// - username: Authenticated username (if authenticated) +// - errors: Concatenated error messages (if any errors occurred) +// +// Log Levels: +// - INFO: Successful requests (2xx status codes) +// - WARN: Client errors (4xx status codes) +// - ERROR: Server errors (5xx status codes) +// +// Thread Safety: +// Safe for concurrent use. Each request logs independently. +// +// Usage: +// // Basic structured logging +// router.Use(middleware.StructuredLogger()) +// +// // Custom configuration +// config := middleware.DefaultStructuredLoggerConfig() +// config.SkipHealthCheck = true // Don't log /health endpoint +// config.LogQuery = false // Don't log query parameters (privacy) +// router.Use(middleware.StructuredLoggerWithConfigFunc(config)) +// +// Configuration: +// SkipPaths: []string{} // Paths to skip (e.g., ["/metrics", "/health"]) +// SkipHealthCheck: true // Skip /health and /api/v1/health endpoints +// LogQuery: true // Log query parameters +// LogUserAgent: true // Log user agent string package middleware import ( diff --git a/api/internal/middleware/team_rbac.go b/api/internal/middleware/team_rbac.go index ba8e6bfd..dda149c9 100644 --- a/api/internal/middleware/team_rbac.go +++ b/api/internal/middleware/team_rbac.go @@ -1,3 +1,75 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements team-based role-based access control (RBAC). +// +// Purpose: +// The team RBAC middleware provides fine-grained access control for multi-tenant +// StreamSpace deployments where users belong to teams/groups and have different +// permission levels within each team. This enables enterprise features like +// shared sessions, team resource quotas, and delegated administration. +// +// Implementation Details: +// - Database-backed permissions: Roles and permissions stored in PostgreSQL +// - Per-team roles: Users can have different roles in different teams +// - Permission-based checks: Middleware validates specific permissions (not just roles) +// - Session-level access: Can check if user can access sessions owned by team +// - Hierarchical model: Teams → Users → Roles → Permissions +// +// Permission Model: +// +// 1. Teams (groups table): +// - Organizations or departments +// - Example: "Engineering", "Sales", "Data Science" +// +// 2. Team Memberships (group_memberships table): +// - Links users to teams with specific roles +// - Example: alice@example.com is "admin" in Engineering team +// +// 3. Roles (team_role_permissions table): +// - Named permission sets +// - Example: "admin", "member", "viewer" +// +// 4. Permissions: +// - Fine-grained capabilities +// - Example: "sessions.create", "sessions.delete", "team.manage" +// +// Common Permissions: +// - sessions.view: View team sessions +// - sessions.create: Create sessions for team +// - sessions.delete: Delete team sessions +// - sessions.share: Share sessions with team members +// - team.manage: Add/remove team members +// - team.billing: View/manage team billing +// +// Security Notes: +// This middleware enforces the principle of least privilege: +// - Users only have access to their own sessions OR team sessions where they have permission +// - Team admins can manage team resources but not other teams +// - Platform admins have global permissions across all teams +// +// Thread Safety: +// Safe for concurrent use. Database queries are isolated per request. +// +// Usage: +// // Create team RBAC middleware +// teamRBAC := middleware.NewTeamRBAC(database) +// +// // Require specific team permission +// router.POST("/api/teams/:teamId/sessions", +// teamRBAC.RequireTeamPermission("sessions.create"), +// handlers.CreateTeamSession, +// ) +// +// // Require session access (owner OR team member with permission) +// router.GET("/api/sessions/:id", +// teamRBAC.RequireSessionAccess("sessions.view"), +// handlers.GetSession, +// ) +// +// // Check permissions manually in handler +// hasPermission, err := teamRBAC.CheckTeamPermission(ctx, userID, teamID, "sessions.delete") +// if !hasPermission { +// return c.JSON(403, gin.H{"error": "Insufficient permissions"}) +// } package middleware import ( diff --git a/api/internal/middleware/timeout.go b/api/internal/middleware/timeout.go index ba53f692..1fbad3a0 100644 --- a/api/internal/middleware/timeout.go +++ b/api/internal/middleware/timeout.go @@ -1,3 +1,67 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements request timeout enforcement. +// +// Purpose: +// The timeout middleware protects the API server from slow clients and long-running +// operations that could exhaust server resources. It enforces maximum request +// duration limits and returns 408 Request Timeout if the limit is exceeded. +// +// Implementation Details: +// - Uses Go context.WithTimeout for cancellation propagation +// - Runs handler in goroutine to detect timeout vs completion +// - Configurable timeout duration per route (via excluded paths) +// - Automatic exclusions for long-running operations (WebSocket, uploads) +// - Graceful cleanup: context cancellation signals handlers to abort +// +// Security Notes: +// This middleware prevents several attack vectors: +// +// 1. Slowloris Attack: +// - Attacker sends HTTP headers very slowly (1 byte per minute) +// - Without timeout: Connections stay open indefinitely (resource exhaustion) +// - With timeout: Connection closed after 30 seconds +// +// 2. Denial of Service (Resource Exhaustion): +// - Attacker triggers expensive database queries or computations +// - Without timeout: Server CPU/memory consumed until crash +// - With timeout: Operation aborted after limit, resources freed +// +// 3. Accidental Long Operations: +// - Bug causes infinite loop or extremely slow query +// - Without timeout: Server hangs indefinitely +// - With timeout: Request fails quickly, server recovers +// +// Performance Characteristics: +// - Overhead: <1ms per request (goroutine spawn + channel operations) +// - Memory: ~4KB per request (goroutine stack + channel) +// - Cleanup: Automatic via defer and context cancellation +// +// Thread Safety: +// Safe for concurrent use. Each request has its own timeout context. +// +// Usage: +// // Use default 30-second timeout +// config := middleware.DefaultTimeoutConfig() +// router.Use(middleware.Timeout(config)) +// +// // Custom timeout duration +// router.Use(middleware.TimeoutWithDuration(60*time.Second)) +// +// // Exclude specific paths (long-running operations) +// config := middleware.TimeoutConfig{ +// Timeout: 30*time.Second, +// ExcludedPaths: []string{ +// "/api/v1/ws/", // WebSocket connections +// "/api/v1/upload", // File uploads +// "/api/v1/export", // Data exports (can be slow) +// }, +// } +// router.Use(middleware.Timeout(config)) +// +// Configuration: +// Timeout: 30*time.Second // Maximum request duration +// ErrorMessage: "Request timeout" // Error message returned to client +// ExcludedPaths: []string{...} // Paths to skip timeout enforcement package middleware import ( diff --git a/api/internal/middleware/webhook.go b/api/internal/middleware/webhook.go index c691e8a9..44c68283 100644 --- a/api/internal/middleware/webhook.go +++ b/api/internal/middleware/webhook.go @@ -1,3 +1,66 @@ +// Package middleware provides HTTP middleware for the StreamSpace API. +// This file implements webhook authentication using HMAC-SHA256 signatures. +// +// Purpose: +// The webhook authentication middleware validates that incoming webhook requests +// are genuinely from authorized sources by verifying cryptographic signatures. +// This prevents unauthorized parties from triggering webhook endpoints and +// injecting malicious data. +// +// Implementation Details: +// - HMAC-SHA256: Industry-standard message authentication algorithm +// - Secret-based signing: Shared secret between sender and receiver +// - Hex-encoded signatures: URL-safe, easy to debug +// - Constant-time comparison: Prevents timing attacks +// - Header-based delivery: Signature sent in X-Webhook-Signature header +// +// Security Notes: +// Without webhook authentication, attackers could: +// 1. Trigger automated actions (e.g., send notifications, create resources) +// 2. Inject malicious payloads (e.g., XSS in notification messages) +// 3. Cause denial of service (e.g., flood system with fake events) +// 4. Impersonate legitimate webhook sources (e.g., GitHub, Stripe, Slack) +// +// HMAC-SHA256 prevents these attacks: +// - Only parties with the secret can create valid signatures +// - Signatures are deterministic (same payload + secret = same signature) +// - Cannot forge signatures without knowing the secret +// - Constant-time comparison prevents timing attacks +// +// How It Works: +// 1. Sender (e.g., GitHub) computes HMAC-SHA256 of request body using secret +// 2. Sender includes signature in X-Webhook-Signature header +// 3. Receiver (StreamSpace) reads request body +// 4. Receiver computes expected signature using same secret +// 5. Receiver compares signatures using constant-time comparison +// 6. If match: Request is authentic, proceed +// 7. If mismatch: Request is invalid or tampered, reject with 401 +// +// Signature Format: +// X-Webhook-Signature: +// Example: "a1b2c3d4e5f67890abcdef1234567890abcdef1234567890abcdef1234567890" +// +// Thread Safety: +// Safe for concurrent use. HMAC computation is stateless. +// +// Usage: +// // Create webhook auth with secret +// webhookAuth := middleware.NewWebhookAuth("your-secret-key-here") +// +// // Apply to webhook endpoints +// router.POST("/api/webhooks/github", +// webhookAuth.Middleware(), +// handlers.HandleGitHubWebhook, +// ) +// +// // Generate signature for testing (sender side) +// payload := []byte(`{"event": "push", "repo": "streamspace"}`) +// signature := webhookAuth.Sign(payload) +// // Send as: curl -H "X-Webhook-Signature: $signature" -d "$payload" /api/webhooks +// +// Configuration: +// secret: Shared secret between sender and receiver (keep confidential!) +// Recommended: Generate with: openssl rand -hex 32 package middleware import ( diff --git a/api/internal/websocket/handlers.go b/api/internal/websocket/handlers.go index 6ca3085b..fd37b7c0 100644 --- a/api/internal/websocket/handlers.go +++ b/api/internal/websocket/handlers.go @@ -1,3 +1,64 @@ +// Package websocket provides real-time WebSocket communication for StreamSpace. +// +// This file implements WebSocket managers and broadcasting for real-time updates. +// +// Purpose: +// - Manage multiple WebSocket hubs (sessions, metrics, logs) +// - Periodically broadcast session and metric updates to connected clients +// - Stream pod logs in real-time via WebSocket +// - Integrate database and Kubernetes for live data +// +// Features: +// - Multi-hub architecture (sessions, metrics separate channels) +// - Periodic broadcast intervals (sessions: 3s, metrics: 5s) +// - Database-enriched session data (active connections, activity status) +// - Real-time pod log streaming +// - Event-driven notifications via Notifier integration +// - Graceful shutdown with connection cleanup +// +// Architecture: +// - Manager: Coordinates all hubs and data sources +// - Hub: Manages WebSocket connections and message delivery +// - Notifier: Routes targeted notifications to subscribed clients +// - Broadcast goroutines: Fetch and push updates periodically +// +// Broadcast Strategy: +// - Sessions: Every 3 seconds, fetch all sessions from Kubernetes +// - Metrics: Every 5 seconds, aggregate counts from database +// - Skip broadcasts when no clients connected (performance) +// - Enriched data includes database fields (active_connections) +// +// Implementation Details: +// - Uses gorilla/websocket for WebSocket protocol +// - Kubernetes client for session data (k8s.Client) +// - Database for enrichment (active connections, metrics) +// - JSON-encoded messages for all broadcasts +// +// Thread Safety: +// - Manager is thread-safe +// - Hub operations use mutex protection +// - Broadcast goroutines run concurrently +// +// Dependencies: +// - github.com/gorilla/websocket for WebSocket protocol +// - internal/db for database access +// - internal/k8s for Kubernetes API +// +// Example Usage: +// +// // Create manager with database and K8s client +// manager := websocket.NewManager(database, k8sClient) +// manager.Start() +// +// // Handle WebSocket connections +// router.GET("/ws/sessions", func(c *gin.Context) { +// userID := c.Query("user_id") +// conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil) +// manager.HandleSessionsWebSocket(conn, userID, "") +// }) +// +// // Shutdown cleanly +// defer manager.CloseAll() package websocket import ( diff --git a/ui/src/components/ActivityIndicator.tsx b/ui/src/components/ActivityIndicator.tsx index 4e4bd4f8..292f5f86 100644 --- a/ui/src/components/ActivityIndicator.tsx +++ b/ui/src/components/ActivityIndicator.tsx @@ -14,6 +14,49 @@ interface ActivityIndicatorProps { showLabel?: boolean; } +/** + * ActivityIndicator - Display session activity status with visual indicator + * + * Shows session activity state with color-coded chip or icon. Combines session + * state (running/hibernated/terminated) with activity flags (active/idle) to + * display appropriate status. Includes tooltip with detailed description. + * + * Features: + * - Multiple activity states (active/idle/hibernated/terminated) + * - Color-coded chips (green/yellow/gray/red) + * - Icon-only or chip with label display + * - Tooltip with status description + * - Configurable size (small/medium) + * - Memoized for performance + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} [props.isActive=false] - Whether session has recent activity + * @param {boolean} [props.isIdle=false] - Whether session is idle + * @param {'running' | 'hibernated' | 'terminated'} [props.state='running'] - Session state + * @param {'small' | 'medium'} [props.size='small'] - Indicator size + * @param {boolean} [props.showLabel=true] - Whether to show text label + * + * @returns {JSX.Element} Rendered activity indicator + * + * @example + * + * + * @example + * // Icon only (no label) + * + * + * @see SessionCard for usage with sessions + */ function ActivityIndicator({ isActive = false, isIdle = false, diff --git a/ui/src/components/EnterpriseWebSocketProvider.tsx b/ui/src/components/EnterpriseWebSocketProvider.tsx index 831a7f9f..91669677 100644 --- a/ui/src/components/EnterpriseWebSocketProvider.tsx +++ b/ui/src/components/EnterpriseWebSocketProvider.tsx @@ -23,8 +23,46 @@ interface Notification { } /** - * Provider component that manages enterprise WebSocket connection - * and displays toast notifications for real-time events + * EnterpriseWebSocketProvider - Provider for WebSocket connection and notifications + * + * Manages enterprise WebSocket connection for real-time events and displays + * toast notifications for various system events. Handles connection lifecycle, + * reconnection attempts, and event routing to appropriate handlers. + * + * Supported events: + * - webhook.delivery: Webhook delivery status updates + * - security.alert: Security alerts and warnings + * - schedule.event: Scheduled session events + * - node.health: Cluster node health updates + * - scaling.event: Auto-scaling events + * - compliance.violation: Compliance violation detections + * - connection: WebSocket connection status + * + * Features: + * - Real-time WebSocket connection management + * - Auto-reconnection with exponential backoff + * - Toast notifications for events + * - Stacked notification display + * - Connection status indicator + * - Event-specific notification handling + * - Optional notification enable/disable + * + * @component + * + * @param {Object} props - Component props + * @param {ReactNode} props.children - Child components + * @param {boolean} [props.enableNotifications=true] - Whether to show notifications + * + * @returns {JSX.Element} Provider with children and notification UI + * + * @example + * + * + * + * + * @see useEnterpriseWebSocket for WebSocket hook + * @see useSecurityAlertEvents for security event handling + * @see useWebhookDeliveryEvents for webhook event handling */ export default function EnterpriseWebSocketProvider({ children, diff --git a/ui/src/components/ErrorBoundary.tsx b/ui/src/components/ErrorBoundary.tsx index 5ca26093..65aa1a46 100644 --- a/ui/src/components/ErrorBoundary.tsx +++ b/ui/src/components/ErrorBoundary.tsx @@ -14,6 +14,40 @@ interface State { errorInfo: ErrorInfo | null; } +/** + * ErrorBoundary - React error boundary for graceful error handling + * + * Catches JavaScript errors anywhere in the child component tree, logs those errors, + * and displays a fallback UI instead of crashing the entire application. Provides + * user-friendly error messages and recovery options. + * + * Features: + * - Catches and displays React component errors + * - Custom fallback UI with recovery options + * - Error details in development mode + * - Optional error callback for logging + * - Reload page, retry, or go home actions + * + * @component + * + * @param {Object} props - Component props + * @param {ReactNode} props.children - Child components to wrap with error boundary + * @param {ReactNode} [props.fallback] - Custom fallback UI to display on error + * @param {Function} [props.onError] - Callback function called when error is caught + * + * @returns {JSX.Element} Children or error fallback UI + * + * @example + * logToService(error)}> + * + * + * + * @example + * // With custom fallback + * }> + * + * + */ class ErrorBoundary extends Component { constructor(props: Props) { super(props); diff --git a/ui/src/components/IdleTimer.tsx b/ui/src/components/IdleTimer.tsx index 0b7070b9..a0435396 100644 --- a/ui/src/components/IdleTimer.tsx +++ b/ui/src/components/IdleTimer.tsx @@ -10,6 +10,51 @@ interface IdleTimerProps { compact?: boolean; } +/** + * IdleTimer - Display session idle time with auto-hibernation countdown + * + * Shows time elapsed since last session activity with optional progress bar + * toward hibernation threshold. Updates every second for real-time countdown. + * Supports both compact and expanded display modes with color coding for + * idle status. + * + * Features: + * - Real-time countdown (updates every second) + * - Human-readable duration formatting (s, m, h, d) + * - Progress bar toward hibernation threshold + * - Color coding (green/yellow/red based on threshold) + * - Compact mode for inline display + * - Tooltip with detailed information + * - Time until auto-hibernation display + * + * @component + * + * @param {Object} props - Component props + * @param {string} [props.lastActivity] - ISO timestamp of last activity + * @param {number} [props.idleDuration=0] - Current idle duration in seconds + * @param {number} [props.idleThreshold=0] - Hibernation threshold in seconds + * @param {boolean} [props.showProgress=false] - Whether to show progress bar + * @param {boolean} [props.compact=false] - Whether to use compact display + * + * @returns {JSX.Element} Rendered idle timer + * + * @example + * + * + * @example + * // Compact mode + * + * + * @see SessionCard for usage with sessions + */ export default function IdleTimer({ lastActivity, idleDuration = 0, diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx index c1fb33af..d2a05b13 100644 --- a/ui/src/components/Layout.tsx +++ b/ui/src/components/Layout.tsx @@ -44,6 +44,36 @@ interface LayoutProps { children: ReactNode; } +/** + * Layout - Main application layout with navigation sidebar and app bar + * + * Provides the consistent layout structure for the entire StreamSpace application, + * including a responsive navigation drawer with user and admin menu items, a top + * app bar with user profile menu, and the main content area. Handles mobile + * responsive behavior with collapsible drawer. + * + * Features: + * - Responsive navigation drawer (permanent on desktop, temporary on mobile) + * - User-specific and admin menu items with role-based access + * - User profile avatar and logout menu + * - Active route highlighting + * - Material-UI theming integration + * + * @component + * + * @param {Object} props - Component props + * @param {ReactNode} props.children - Child components to render in main content area + * + * @returns {JSX.Element} Rendered layout with navigation and content + * + * @example + * + * + * + * + * @see useUserStore for user authentication state + * @see useNavigate for route navigation + */ export default function Layout({ children }: LayoutProps) { const [mobileOpen, setMobileOpen] = useState(false); const [anchorEl, setAnchorEl] = useState(null); diff --git a/ui/src/components/PluginCard.tsx b/ui/src/components/PluginCard.tsx index d932d21d..ddd16e54 100644 --- a/ui/src/components/PluginCard.tsx +++ b/ui/src/components/PluginCard.tsx @@ -29,6 +29,44 @@ interface PluginCardProps { mode?: 'catalog' | 'installed'; } +/** + * PluginCard - Display card for a plugin in the catalog or installed plugins list + * + * Presents plugin information in a compact, visually appealing card format with + * plugin type badge, icon, rating, description, tags, and action buttons. Supports + * both catalog mode (with install button) and installed mode. Includes hover effects + * and memoization for performance. + * + * Features: + * - Plugin type badge with color coding and icons + * - Star rating display with review count + * - Truncated description with ellipsis + * - Category and tag chips + * - Install count statistics + * - Install and view details actions + * - Memoized to prevent unnecessary re-renders + * + * @component + * + * @param {Object} props - Component props + * @param {CatalogPlugin} props.plugin - Plugin data to display + * @param {Function} [props.onInstall] - Callback when install button is clicked + * @param {Function} [props.onViewDetails] - Callback when info button is clicked + * @param {'catalog' | 'installed'} [props.mode='catalog'] - Display mode for the card + * + * @returns {JSX.Element} Rendered plugin card + * + * @example + * + * + * @see RatingStars for rating display component + * @see PluginDetailModal for detailed plugin view + */ const pluginTypeIcons: Record = { extension: , webhook: , diff --git a/ui/src/components/PluginCardSkeleton.tsx b/ui/src/components/PluginCardSkeleton.tsx index 9478b53e..a7ec420d 100644 --- a/ui/src/components/PluginCardSkeleton.tsx +++ b/ui/src/components/PluginCardSkeleton.tsx @@ -6,6 +6,38 @@ import { Skeleton, } from '@mui/material'; +/** + * PluginCardSkeleton - Loading skeleton placeholder for PluginCard + * + * Displays an animated loading placeholder that matches the structure and + * dimensions of the PluginCard component. Used during data fetching to + * provide visual feedback and prevent layout shift. + * + * Features: + * - Matches PluginCard layout structure + * - Animated skeleton loaders + * - Icon, title, rating, description, and tag placeholders + * - Action button placeholders + * + * @component + * + * @returns {JSX.Element} Rendered skeleton card + * + * @example + * {loading ? ( + * + * ) : ( + * + * )} + * + * @example + * // Multiple skeletons while loading + * {loading && Array(6).fill(0).map((_, i) => ( + * + * ))} + * + * @see PluginCard for the actual plugin card component + */ export default function PluginCardSkeleton() { return ( } props.value - Current form values + * @param {Function} props.onChange - Callback when form values change + * @param {boolean} [props.disabled=false] - Whether form fields are disabled + * + * @returns {JSX.Element} Rendered configuration form + * + * @example + * + * + * @example + * // Schema example + * const schema = { + * type: 'object', + * properties: { + * apiKey: { type: 'string', title: 'API Key', description: 'Your API key' }, + * enabled: { type: 'boolean', title: 'Enable Plugin' }, + * mode: { type: 'enum', enum: ['dev', 'prod'] } + * }, + * required: ['apiKey'] + * } + */ export default function PluginConfigForm({ schema, value, diff --git a/ui/src/components/PluginDetailModal.tsx b/ui/src/components/PluginDetailModal.tsx index f467df58..bdee9588 100644 --- a/ui/src/components/PluginDetailModal.tsx +++ b/ui/src/components/PluginDetailModal.tsx @@ -73,6 +73,44 @@ interface PluginDetailModalProps { onInstall?: (plugin: CatalogPlugin) => void; } +/** + * PluginDetailModal - Detailed plugin information modal with tabs + * + * Displays comprehensive plugin information in a modal dialog with tabbed interface. + * Shows plugin details including permissions, dependencies, entry points, and user + * reviews. Allows users to rate and review plugins, and install them directly. + * + * Features: + * - Tabbed interface for Details and Reviews + * - Permission display with risk levels and tooltips + * - Dependency listing + * - Entry point indicators + * - User rating and review submission + * - Review history with user avatars + * - Install action button + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the modal is open + * @param {CatalogPlugin | null} props.plugin - Plugin data to display + * @param {Function} props.onClose - Callback when modal is closed + * @param {Function} [props.onInstall] - Callback when install button is clicked + * + * @returns {JSX.Element | null} Rendered modal or null if no plugin + * + * @example + * setIsOpen(false)} + * onInstall={handleInstall} + * /> + * + * @see RatingStars for rating display + * @see api.getPluginRatings for loading reviews + * @see api.ratePlugin for submitting ratings + */ const pluginTypeIcons: Record = { extension: , webhook: , diff --git a/ui/src/components/QuotaAlert.tsx b/ui/src/components/QuotaAlert.tsx index 07f4bfc4..4c03ff26 100644 --- a/ui/src/components/QuotaAlert.tsx +++ b/ui/src/components/QuotaAlert.tsx @@ -6,6 +6,41 @@ interface QuotaAlertProps { onQuotaLoad?: (quota: UserQuota) => void; } +/** + * QuotaAlert - Alert banner for resource quota warnings + * + * Displays a dismissible alert when user's resource usage exceeds 75% of their + * allocated quota. Shows detailed breakdown of resources approaching or at limits + * with progress bars. Only renders when threshold is exceeded. + * + * Features: + * - Conditional rendering (only shows when usage >= 75%) + * - Severity levels (warning at 75%, error at 90%) + * - Detailed resource breakdown with progress bars + * - Sessions, CPU, memory, and storage metrics + * - Silent failure (optional display) + * - Callback when quota data loads + * + * @component + * + * @param {Object} props - Component props + * @param {Function} [props.onQuotaLoad] - Callback with quota data when loaded + * + * @returns {JSX.Element | null} Rendered alert or null if under threshold + * + * @example + * console.log(quota)} /> + * + * @example + * // Typical placement at top of dashboard + * + * + * + * + * + * @see api.getCurrentUserQuota for quota data fetching + * @see QuotaCard for detailed quota display + */ export default function QuotaAlert({ onQuotaLoad }: QuotaAlertProps) { const [quota, setQuota] = useState(null); const [loading, setLoading] = useState(true); diff --git a/ui/src/components/QuotaCard.tsx b/ui/src/components/QuotaCard.tsx index cd610d52..695c5d99 100644 --- a/ui/src/components/QuotaCard.tsx +++ b/ui/src/components/QuotaCard.tsx @@ -27,6 +27,32 @@ interface QuotaMetric { color: 'primary' | 'secondary' | 'success' | 'warning' | 'error'; } +/** + * QuotaCard - Display user's resource quota usage in a card + * + * Shows current resource usage against allocated quotas for sessions, CPU, + * memory, and storage. Displays progress bars with color coding based on + * usage percentage. Automatically fetches current user's quota on mount. + * + * Features: + * - Real-time resource usage display + * - Progress bars with color coding (green/yellow/red) + * - Sessions, CPU, memory, and storage metrics + * - Warning indicator when approaching limits (75%+) + * - Automatic unit conversion (GiB for memory/storage, cores for CPU) + * - Loading skeleton state + * - Error handling with user-friendly messages + * + * @component + * + * @returns {JSX.Element} Rendered quota card + * + * @example + * + * + * @see api.getCurrentUserQuota for quota data fetching + * @see QuotaAlert for alert-style quota warnings + */ export default function QuotaCard() { const [quota, setQuota] = useState(null); const [loading, setLoading] = useState(true); diff --git a/ui/src/components/RatingStars.tsx b/ui/src/components/RatingStars.tsx index 34cc5b47..3347cbb8 100644 --- a/ui/src/components/RatingStars.tsx +++ b/ui/src/components/RatingStars.tsx @@ -11,6 +11,50 @@ interface RatingStarsProps { onRate?: (rating: number) => void; } +/** + * RatingStars - Star rating display and input component + * + * Displays a 5-star rating with full, half, and empty stars. Supports both + * read-only display mode and interactive rating mode. Shows review count or + * average rating value. Memoized to prevent unnecessary re-renders. + * + * Features: + * - Full, half, and empty star icons + * - Configurable size (small/medium/large) + * - Optional review count display + * - Optional average rating display + * - Interactive mode for user rating input + * - Click handlers for each star + * - Memoized for performance + * + * @component + * + * @param {Object} props - Component props + * @param {number} props.rating - Average rating (0-5) + * @param {number} [props.count] - Number of reviews/ratings + * @param {'small' | 'medium' | 'large'} [props.size='small'] - Star size + * @param {boolean} [props.showCount=true] - Whether to show review count + * @param {boolean} [props.interactive=false] - Whether stars are clickable + * @param {Function} [props.onRate] - Callback when star is clicked (rating: number) + * + * @returns {JSX.Element} Rendered rating stars + * + * @example + * // Display mode + * + * + * @example + * // Interactive mode + * + * + * @see PluginDetailModal for usage in plugin ratings + * @see TemplateDetailModal for usage in template ratings + */ function RatingStars({ rating, count, diff --git a/ui/src/components/RepositoryCard.tsx b/ui/src/components/RepositoryCard.tsx index 4324729c..149010bf 100644 --- a/ui/src/components/RepositoryCard.tsx +++ b/ui/src/components/RepositoryCard.tsx @@ -41,6 +41,47 @@ interface RepositoryCardProps { isSyncing: boolean; } +/** + * RepositoryCard - Display card for a Git repository configuration + * + * Shows repository information including sync status, branch, authentication type, + * and template count. Provides actions for syncing, editing, and deleting repositories. + * Includes expandable details section and visual sync progress indicator. + * + * Features: + * - Repository status badges (synced/syncing/failed/pending) + * - Branch and authentication type indicators + * - Template count display + * - Last sync timestamp + * - Sync progress indicator during sync + * - Error message display + * - Expandable details section + * - Sync, edit, and delete actions + * - Three-dot menu for additional actions + * - Spinning sync icon animation + * + * @component + * + * @param {Object} props - Component props + * @param {Repository} props.repository - Repository data to display + * @param {Function} props.onSync - Callback to sync repository + * @param {Function} props.onEdit - Callback to edit repository + * @param {Function} props.onDelete - Callback to delete repository + * @param {boolean} props.isSyncing - Whether repository is currently syncing + * + * @returns {JSX.Element} Rendered repository card + * + * @example + * + * + * @see RepositoryDialog for repository edit/create dialog + */ export default function RepositoryCard({ repository, onSync, diff --git a/ui/src/components/RepositoryDialog.tsx b/ui/src/components/RepositoryDialog.tsx index 0b7d0780..343ea3e5 100644 --- a/ui/src/components/RepositoryDialog.tsx +++ b/ui/src/components/RepositoryDialog.tsx @@ -34,6 +34,56 @@ interface RepositoryDialogProps { isSaving: boolean; } +/** + * RepositoryDialog - Dialog for adding or editing Git repository configurations + * + * Provides a form for configuring Git repository connections with authentication. + * Supports multiple authentication methods (none, token, SSH, basic auth) and + * validates Git URL formats. Includes helpful tooltips and examples. + * + * Features: + * - Add new or edit existing repositories + * - Repository name, URL, and branch configuration + * - Multiple authentication types (public, token, SSH key, basic) + * - Authentication secret management (show/hide toggle) + * - Git URL validation (GitHub, GitLab, Bitbucket) + * - Helpful tooltips and descriptions + * - Collapsible authentication section + * - Form validation with error messages + * - Password/secret visibility toggle + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the dialog is open + * @param {Function} props.onClose - Callback when dialog is closed + * @param {Function} props.onSave - Callback with form data when saved + * @param {Repository | null} [props.repository] - Repository to edit (null for new) + * @param {boolean} props.isSaving - Whether save operation is in progress + * + * @returns {JSX.Element} Rendered repository dialog + * + * @example + * // Add new repository + * setIsOpen(false)} + * onSave={handleCreateRepo} + * isSaving={saving} + * /> + * + * @example + * // Edit existing repository + * setIsOpen(false)} + * onSave={handleUpdateRepo} + * isSaving={saving} + * /> + * + * @see RepositoryCard for repository display + */ export default function RepositoryDialog({ open, onClose, diff --git a/ui/src/components/SessionCard.tsx b/ui/src/components/SessionCard.tsx index d8d14710..f4b1ae10 100644 --- a/ui/src/components/SessionCard.tsx +++ b/ui/src/components/SessionCard.tsx @@ -34,6 +34,55 @@ interface SessionCardProps { isUpdating?: boolean; } +/** + * SessionCard - Display card for a containerized session + * + * Presents session information with state management controls, resource usage, + * activity indicators, and collaboration features. Supports session lifecycle + * actions (connect, pause, delete) and sharing capabilities. Includes real-time + * activity monitoring with idle timer and connection count. + * + * Features: + * - Session state and phase indicators with color coding + * - Activity indicator (active/idle/hibernated) + * - Idle timer with auto-hibernation countdown + * - Resource usage display (CPU/memory) + * - Active connections counter + * - Session URL display + * - Tag management + * - Sharing and invitation links + * - Connect, pause/resume, and delete actions + * - Memoized for performance optimization + * + * @component + * + * @param {Object} props - Component props + * @param {Session} props.session - Session data to display + * @param {Function} props.onConnect - Callback to connect to session + * @param {Function} props.onStateChange - Callback to change session state (run/hibernate) + * @param {Function} props.onDelete - Callback to delete session + * @param {Function} props.onManageTags - Callback to open tag management dialog + * @param {Function} props.onShare - Callback to open share dialog + * @param {Function} props.onInvitation - Callback to open invitation dialog + * @param {boolean} [props.isUpdating=false] - Whether session is currently updating + * + * @returns {JSX.Element} Rendered session card + * + * @example + * + * + * @see IdleTimer for idle time display + * @see ActivityIndicator for activity status + * @see TagChip for tag display + */ function SessionCard({ session, onConnect, diff --git a/ui/src/components/SessionCollaboratorsPanel.tsx b/ui/src/components/SessionCollaboratorsPanel.tsx index 806769b3..65668bd3 100644 --- a/ui/src/components/SessionCollaboratorsPanel.tsx +++ b/ui/src/components/SessionCollaboratorsPanel.tsx @@ -43,6 +43,43 @@ interface Collaborator { }; } +/** + * SessionCollaboratorsPanel - Display and manage active session collaborators + * + * Shows all users currently collaborating on a session with their activity status, + * permission levels, and join times. Provides real-time updates of collaborator + * activity and allows session owners to remove collaborators. Auto-refreshes + * every 10 seconds to show current activity. + * + * Features: + * - List of active collaborators with avatars + * - Real-time activity indicators (active/idle) + * - Permission level badges + * - Relative timestamps (last activity, join time) + * - Remove collaborator action (owner only) + * - Auto-refresh every 10 seconds + * - Current user highlighting + * - Empty state message + * + * @component + * + * @param {Object} props - Component props + * @param {string} props.sessionId - ID of session to show collaborators for + * @param {boolean} [props.isOwner=false] - Whether current user is session owner + * @param {Function} [props.onUpdate] - Callback when collaborators list changes + * + * @returns {JSX.Element} Rendered collaborators panel + * + * @example + * + * + * @see api.listCollaborators for loading collaborators + * @see api.removeCollaborator for removing access + */ export default function SessionCollaboratorsPanel({ sessionId, isOwner = false, diff --git a/ui/src/components/SessionInvitationDialog.tsx b/ui/src/components/SessionInvitationDialog.tsx index c9c0863b..9b79b89b 100644 --- a/ui/src/components/SessionInvitationDialog.tsx +++ b/ui/src/components/SessionInvitationDialog.tsx @@ -49,6 +49,45 @@ interface Invitation { isExhausted?: boolean; } +/** + * SessionInvitationDialog - Dialog for creating shareable invitation links + * + * Allows session owners to create invitation links that can be shared with anyone + * to grant access to a session. Supports configurable permission levels, usage + * limits, and expiration dates. Displays existing invitations with their status + * and provides easy copy-to-clipboard functionality. + * + * Features: + * - Create shareable invitation links + * - Permission levels: view, collaborate, control + * - Configure max uses (or unlimited) + * - Optional expiration dates + * - Copy invitation URL to clipboard + * - View invitation statistics (uses, status) + * - Revoke invitation links + * - Status indicators (active/expired/exhausted) + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the dialog is open + * @param {string} props.sessionId - ID of session to create invitations for + * @param {string} props.sessionName - Display name of session + * @param {Function} props.onClose - Callback when dialog is closed + * + * @returns {JSX.Element} Rendered invitation dialog + * + * @example + * setIsOpen(false)} + * /> + * + * @see api.createInvitation for creating invitations + * @see api.revokeInvitation for revoking invitations + */ export default function SessionInvitationDialog({ open, sessionId, diff --git a/ui/src/components/SessionShareDialog.tsx b/ui/src/components/SessionShareDialog.tsx index fabee1e5..a862b38d 100644 --- a/ui/src/components/SessionShareDialog.tsx +++ b/ui/src/components/SessionShareDialog.tsx @@ -52,6 +52,45 @@ interface Share { }; } +/** + * SessionShareDialog - Dialog for sharing sessions with specific users + * + * Allows session owners to share sessions with other users by granting specific + * permission levels (view, collaborate, control). Displays existing shares with + * their status and permissions. Supports share expiration, revocation, and + * ownership transfer. + * + * Features: + * - Share with specific users from user list + * - Permission levels: view, collaborate, control + * - Optional expiration dates + * - View and manage existing shares + * - Share status indicators (pending/accepted/expired) + * - Revoke share access + * - Transfer session ownership (irreversible) + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the dialog is open + * @param {string} props.sessionId - ID of session to share + * @param {string} props.sessionName - Display name of session + * @param {Function} props.onClose - Callback when dialog is closed + * + * @returns {JSX.Element} Rendered share dialog + * + * @example + * setIsOpen(false)} + * /> + * + * @see api.createShare for sharing API + * @see api.revokeShare for revoke API + * @see api.transferOwnership for ownership transfer + */ export default function SessionShareDialog({ open, sessionId, diff --git a/ui/src/components/TagChip.tsx b/ui/src/components/TagChip.tsx index c1e0796b..c4047be1 100644 --- a/ui/src/components/TagChip.tsx +++ b/ui/src/components/TagChip.tsx @@ -10,6 +10,52 @@ interface TagChipProps { variant?: 'filled' | 'outlined'; } +/** + * TagChip - Reusable chip component for displaying session tags + * + * Displays a tag in a Material-UI Chip component with consistent styling. + * Supports optional delete and click handlers for tag management and filtering. + * Includes a tag icon and is memoized to prevent unnecessary re-renders. + * + * Features: + * - Tag icon (LocalOffer) + * - Optional delete button + * - Optional click handler for filtering + * - Configurable size (small/medium) + * - Configurable variant (filled/outlined) + * - Primary color theme + * - Memoized for performance + * + * @component + * + * @param {Object} props - Component props + * @param {string} props.tag - Tag text to display + * @param {Function} [props.onDelete] - Callback when delete button clicked + * @param {Function} [props.onClick] - Callback when chip is clicked + * @param {'small' | 'medium'} [props.size='small'] - Chip size + * @param {'filled' | 'outlined'} [props.variant='filled'] - Chip variant + * + * @returns {JSX.Element} Rendered tag chip + * + * @example + * + * + * @example + * // With delete handler + * removeTag('development')} + * /> + * + * @example + * // With click handler for filtering + * filterByTag('testing')} + * /> + * + * @see TagManager for tag management + */ function TagChip({ tag, onDelete, onClick, size = 'small', variant = 'filled' }: TagChipProps) { return ( Promise; } +/** + * TagManager - Dialog for managing session tags + * + * Allows users to add and remove tags for organizing sessions. Tags must follow + * a specific format (lowercase letters, numbers, and hyphens only). Provides + * validation, duplicate prevention, and keyboard shortcuts for quick tag entry. + * + * Features: + * - Add tags with validation (lowercase, alphanumeric, hyphens) + * - Remove tags with delete button + * - Duplicate tag prevention + * - Enter key to add tags quickly + * - Tag format validation feedback + * - Display current tags with TagChip component + * - Save changes to backend + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the dialog is open + * @param {Session} props.session - Session to manage tags for + * @param {Function} props.onClose - Callback when dialog is closed + * @param {Function} props.onSave - Async callback to save tags (returns Promise) + * + * @returns {JSX.Element} Rendered tag manager dialog + * + * @example + * setIsOpen(false)} + * onSave={async (tags) => await api.updateSessionTags(session.id, tags)} + * /> + * + * @see TagChip for tag display component + */ export default function TagManager({ open, session, onClose, onSave }: TagManagerProps) { const [tags, setTags] = useState(session.tags || []); const [newTag, setNewTag] = useState(''); diff --git a/ui/src/components/TemplateCard.tsx b/ui/src/components/TemplateCard.tsx index cb8a6e6b..8f4e2bde 100644 --- a/ui/src/components/TemplateCard.tsx +++ b/ui/src/components/TemplateCard.tsx @@ -26,6 +26,46 @@ interface TemplateCardProps { mode?: 'catalog' | 'installed'; } +/** + * TemplateCard - Display card for an application template + * + * Presents application template information in a card format with icon, rating, + * description, tags, and action buttons. Supports both catalog mode (install) and + * installed mode (create session). Shows template statistics including install + * count and view count. Features hover effects and memoization for performance. + * + * Features: + * - Template icon and display name + * - Featured template indicator (star badge) + * - Star rating with review count + * - Truncated description with ellipsis + * - Category and app type chips + * - Tag display (first 3 + count) + * - Install and view count statistics + * - Install/Create Session and View Details actions + * - Memoized to prevent unnecessary re-renders + * + * @component + * + * @param {Object} props - Component props + * @param {CatalogTemplate} props.template - Template data to display + * @param {Function} [props.onInstall] - Callback when install/create button clicked + * @param {Function} [props.onViewDetails] - Callback when info button clicked + * @param {'catalog' | 'installed'} [props.mode='catalog'] - Display mode + * + * @returns {JSX.Element} Rendered template card + * + * @example + * + * + * @see RatingStars for rating display + * @see TemplateDetailModal for detailed view + */ function TemplateCard({ template, onInstall, diff --git a/ui/src/components/TemplateDetailModal.tsx b/ui/src/components/TemplateDetailModal.tsx index 247d23b6..ec3f4580 100644 --- a/ui/src/components/TemplateDetailModal.tsx +++ b/ui/src/components/TemplateDetailModal.tsx @@ -35,6 +35,46 @@ interface TemplateDetailModalProps { onInstall?: (template: CatalogTemplate) => void; } +/** + * TemplateDetailModal - Detailed template information modal with tabs + * + * Displays comprehensive template information in a modal dialog with tabbed + * interface for Details and Reviews. Records view count when opened. Shows + * template metadata, statistics, and allows users to rate and review templates. + * + * Features: + * - Tabbed interface for Details and Reviews + * - Template icon and basic information + * - Star rating and review count + * - Category, app type, and tags + * - Install and view count statistics + * - User rating and review submission + * - Review history with user avatars + * - Install action button + * - Automatic view tracking + * + * @component + * + * @param {Object} props - Component props + * @param {boolean} props.open - Whether the modal is open + * @param {CatalogTemplate | null} props.template - Template data to display + * @param {Function} props.onClose - Callback when modal is closed + * @param {Function} [props.onInstall] - Callback when install button clicked + * + * @returns {JSX.Element | null} Rendered modal or null if no template + * + * @example + * setIsOpen(false)} + * onInstall={handleInstall} + * /> + * + * @see RatingStars for rating display + * @see api.recordTemplateView for view tracking + * @see api.getTemplateRatings for loading reviews + */ export default function TemplateDetailModal({ open, template, diff --git a/ui/src/pages/Catalog.tsx b/ui/src/pages/Catalog.tsx index ec08fc9b..f58176a3 100644 --- a/ui/src/pages/Catalog.tsx +++ b/ui/src/pages/Catalog.tsx @@ -28,6 +28,9 @@ import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; import { useQueryClient } from '@tanstack/react-query'; +/** + * CatalogContent - Internal component for Catalog page logic + */ function CatalogContent() { const username = useUserStore((state) => state.user?.username); const [tabValue, setTabValue] = useState(0); @@ -220,6 +223,47 @@ function CatalogContent() { ); } +/** + * Catalog - Basic template catalog for browsing and creating sessions + * + * Provides a simple two-tab interface for viewing templates: + * - Installed Templates tab: Templates installed locally in the cluster + * - Marketplace tab: Templates available from external repositories + * + * Features: + * - Tab-based navigation between installed and marketplace templates + * - Template cards showing name, description, category, and tags + * - Quick session creation from installed templates + * - Install action for marketplace templates (stub) + * - Real-time template updates via WebSocket + * - Template event notifications (added, updated, deleted) + * - WebSocket connection status indicator + * + * User workflows: + * - Browse available templates by category and tags + * - Create new sessions from installed templates with default settings + * - View template metadata (display name, description, app type) + * - Monitor template catalog updates in real-time + * + * Note: This is the basic catalog. For advanced features like search, + * filtering, sorting, and detailed views, see EnhancedCatalog. + * + * @page + * @route /catalog - Basic template catalog (alternative to /enhanced-catalog) + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Template catalog page with tabs and template cards + * + * @example + * // Route configuration: + * } /> + * + * @see EnhancedCatalog for advanced catalog features (search, filters, sorting) + * @see Sessions for managing created sessions + * @see Repositories for managing template sources + */ export default function Catalog() { return ( diff --git a/ui/src/pages/Dashboard.tsx b/ui/src/pages/Dashboard.tsx index 7d40595f..57fcdfba 100644 --- a/ui/src/pages/Dashboard.tsx +++ b/ui/src/pages/Dashboard.tsx @@ -19,6 +19,44 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * Dashboard - User home page displaying session and platform overview + * + * Provides a comprehensive overview of the user's StreamSpace account including: + * - Session statistics (running, hibernated, total sessions) + * - Resource quota usage and limits + * - Available templates and repositories counts + * - Real-time active connections metrics + * - Recent sessions quick view (last 5 sessions) + * - Real-time WebSocket status indicator + * + * Features real-time updates via WebSocket for: + * - Session state changes (running → hibernated → terminated) + * - Active connection counts + * - Resource usage metrics + * - Session status notifications + * + * User workflows: + * - Quick view of account status at a glance + * - Monitor resource usage and quotas + * - See recent session activity + * - Navigate to other pages from stats cards + * + * @page + * @route / - Main dashboard route (requires authentication) + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Dashboard page with statistics cards and session overview + * + * @example + * // Route configuration: + * } /> + * + * @see Sessions for managing active sessions + * @see Catalog for browsing available templates + */ export default function Dashboard() { const username = useUserStore((state) => state.user?.username); const [sessions, setSessions] = useState([]); diff --git a/ui/src/pages/EnhancedCatalog.tsx b/ui/src/pages/EnhancedCatalog.tsx index 9e3b65bf..bb6abdfc 100644 --- a/ui/src/pages/EnhancedCatalog.tsx +++ b/ui/src/pages/EnhancedCatalog.tsx @@ -28,6 +28,9 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * EnhancedCatalogContent - Internal component for EnhancedCatalog page logic + */ function EnhancedCatalogContent() { const navigate = useNavigate(); const [loading, setLoading] = useState(true); @@ -355,6 +358,58 @@ function EnhancedCatalogContent() { ); } +/** + * EnhancedCatalog - Advanced template catalog with search, filtering, and sorting + * + * Comprehensive template discovery interface providing: + * - Advanced search across template names and descriptions + * - Multi-level filtering (category, app type, tags, featured) + * - Multiple sort options (popular, rating, recent, installs, views) + * - Paginated results with configurable page size + * - Template detail modal with full metadata + * - Install tracking and analytics + * - Featured template highlighting + * - Real-time catalog updates via WebSocket + * + * Features: + * - Text search with real-time filtering + * - Category and app type dropdown filters + * - Featured templates toggle filter + * - Active filter chips with individual removal + * - "Clear All Filters" quick action + * - Pagination with page navigation + * - Template cards with ratings, install counts, and preview images + * - Detailed template modal with full description and metadata + * - One-click install with usage tracking + * - WebSocket notifications for catalog changes (new, updated, deleted, featured) + * + * User workflows: + * - Search templates by name or keyword + * - Filter by category (e.g., "Browsers", "Development") + * - Filter by app type (e.g., "GUI", "CLI") + * - Toggle featured templates only + * - Sort by popularity, rating, recency, or install count + * - View template details before installing + * - Install template and navigate to create session + * - Clear filters to browse all templates + * + * @page + * @route /enhanced-catalog - Advanced template catalog (default catalog route) + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Enhanced template catalog with search and filters + * + * @example + * // Route configuration: + * } /> + * } /> + * + * @see Catalog for basic catalog without advanced features + * @see Sessions for managing installed templates + * @see Repositories for managing template sources + */ export default function EnhancedCatalog() { return ( diff --git a/ui/src/pages/EnhancedRepositories.tsx b/ui/src/pages/EnhancedRepositories.tsx index 9b15b2e7..92692fd1 100644 --- a/ui/src/pages/EnhancedRepositories.tsx +++ b/ui/src/pages/EnhancedRepositories.tsx @@ -24,7 +24,7 @@ import { ViewModule as ViewModuleIcon, CheckCircle as CheckCircleIcon, Error as ErrorIcon, -} from '@mui/icons-material'; +} from '@mui/material-icons'; import Layout from '../components/Layout'; import RepositoryCard from '../components/RepositoryCard'; import RepositoryDialog from '../components/RepositoryDialog'; @@ -42,6 +42,53 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * EnhancedRepositories - Advanced template repository management with real-time updates + * + * Enhanced version of repository management with real-time WebSocket updates, advanced + * filtering, multiple view modes, and comprehensive statistics. Provides a rich user + * experience for managing template repositories with live sync status monitoring and + * automatic refresh capabilities. + * + * Features: + * - Real-time repository sync status via WebSocket + * - Statistics dashboard (total, synced, syncing, failed) + * - Grid and list view modes + * - Advanced filtering by status + * - Search across repositories + * - Live notification system for sync events + * - Auto-refresh every 10 seconds + * - WebSocket connection status indicator + * + * Real-time features: + * - Live sync progress updates + * - Automatic UI refresh on repository changes + * - Connection status monitoring + * - Event-driven notifications + * + * User workflows: + * - Monitor repository sync status in real-time + * - Quick access to repository statistics + * - Filter and search for specific repositories + * - Switch between grid and list views + * - Receive instant notifications for sync events + * + * @page + * @route /repositories - Enhanced template repository management + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Enhanced repository management interface with real-time updates + * + * @example + * // Route configuration: + * } /> + * + * @see Repositories for basic repository management + * @see RepositoryCard for individual repository display + * @see RepositoryDialog for add/edit repository dialog + */ function EnhancedRepositoriesContent() { const { data: repositories = [], isLoading, refetch } = useRepositories(); const addRepository = useAddRepository(); diff --git a/ui/src/pages/InstalledPlugins.tsx b/ui/src/pages/InstalledPlugins.tsx index ad87e44a..a3c4a233 100644 --- a/ui/src/pages/InstalledPlugins.tsx +++ b/ui/src/pages/InstalledPlugins.tsx @@ -46,6 +46,67 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * InstalledPlugins - Management page for installed StreamSpace plugins + * + * Comprehensive plugin management interface providing: + * - Grid view of all installed plugins with status + * - Enable/disable toggle for each plugin + * - Configuration management for plugin settings + * - Uninstallation with confirmation dialogs + * - Real-time plugin status updates via WebSocket + * - Tab-based filtering (All, Enabled, Disabled) + * - Search functionality for finding plugins + * - Plugin type icons and categorization + * + * Plugin management features: + * - Quick enable/disable toggle switches + * - Configure button opens plugin-specific settings form + * - View plugin details (version, author, description) + * - Uninstall with dependency checking + * - Real-time status updates (enabled → disabled) + * - Plugin event notifications (installed, updated, uninstalled) + * - Empty state with link to plugin catalog + * + * Plugin types supported: + * - Extension: Core platform extensions + * - Webhook: External webhook integrations + * - API: API integrations and connectors + * - UI: User interface components and themes + * - Theme: Visual themes for the platform + * + * User workflows: + * - View all installed plugins at a glance + * - Enable/disable plugins without uninstalling + * - Configure plugin settings via config modal + * - Uninstall plugins with confirmation + * - Filter by status (enabled/disabled) + * - Search plugins by name + * - Navigate to catalog to install more plugins + * + * Real-time features: + * - Plugin state change notifications + * - Installation/uninstallation events + * - Configuration update events + * - WebSocket connection status indicator + * + * @page + * @route /plugins - Installed plugins management page + * @access user - Shows only user-accessible plugins + * + * @component + * + * @returns {JSX.Element} Installed plugins page with management controls + * + * @example + * // Route configuration: + * } /> + * } /> + * + * @see PluginCatalog for installing new plugins + * @see PluginConfigForm for plugin configuration interface + */ + const pluginTypeIcons: Record = { extension: , webhook: , diff --git a/ui/src/pages/InvitationAccept.tsx b/ui/src/pages/InvitationAccept.tsx index bd783bde..a7906284 100644 --- a/ui/src/pages/InvitationAccept.tsx +++ b/ui/src/pages/InvitationAccept.tsx @@ -20,6 +20,43 @@ import Layout from '../components/Layout'; import { api } from '../lib/api'; import { useUserStore } from '../store/userStore'; +/** + * InvitationAccept - Session invitation acceptance page + * + * Handles the workflow for accepting session sharing invitations. Users who receive + * an invitation link can use this page to accept the invitation and gain access to + * a shared session. Requires user authentication before accepting the invitation. + * + * Features: + * - Display invitation details and token + * - Show accepting user information + * - Validate invitation token + * - Automatic redirect to login if not authenticated + * - Success confirmation with auto-redirect to session + * - Error handling for invalid or expired invitations + * + * User workflows: + * - Receive invitation link via email or direct sharing + * - Authenticate if not already logged in + * - Review invitation details + * - Accept invitation to join shared session + * - Automatic redirect to session viewer + * + * @page + * @route /invite/:token - Accept session invitation + * @access public - Available to all users with valid invitation link + * + * @component + * + * @returns {JSX.Element} Invitation acceptance interface with token validation + * + * @example + * // Route configuration: + * } /> + * + * @see SessionShare for session sharing management + * @see SessionViewer for viewing shared sessions + */ export default function InvitationAccept() { const { token } = useParams<{ token: string }>(); const navigate = useNavigate(); diff --git a/ui/src/pages/Login.tsx b/ui/src/pages/Login.tsx index f7dfe314..d9e61961 100644 --- a/ui/src/pages/Login.tsx +++ b/ui/src/pages/Login.tsx @@ -19,6 +19,48 @@ import { api } from '../lib/api'; const AUTH_MODE = import.meta.env.VITE_AUTH_MODE || 'jwt'; const SAML_LOGIN_URL = import.meta.env.VITE_SAML_LOGIN_URL || '/saml/login'; +/** + * Login - User authentication page + * + * Provides authentication interface supporting multiple authentication modes including + * JWT (local), SAML SSO, and hybrid mode. Handles user login, token management, and + * redirect to the application after successful authentication. + * + * Features: + * - JWT/Local authentication with username and password + * - SAML 2.0 SSO integration + * - Hybrid mode supporting both authentication methods + * - Demo mode for development (no password required) + * - Error handling and validation + * - Loading states during authentication + * - Automatic token storage and session management + * + * Authentication modes (configurable via VITE_AUTH_MODE): + * - jwt: Local authentication with JWT tokens + * - saml: SAML 2.0 SSO redirect + * - hybrid: Both JWT and SAML options + * - demo: Development mode with simplified auth + * + * User workflows: + * - Enter credentials for local authentication + * - Click SSO button for SAML authentication + * - Automatic redirect to dashboard on success + * - Error messages for failed authentication + * + * @page + * @route /login - User authentication + * @access public - Available to unauthenticated users + * + * @component + * + * @returns {JSX.Element} Login form with authentication options + * + * @example + * // Route configuration: + * } /> + * + * @see Dashboard for post-login destination + */ export default function Login() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); diff --git a/ui/src/pages/PluginCatalog.tsx b/ui/src/pages/PluginCatalog.tsx index 21e8945d..42029b27 100644 --- a/ui/src/pages/PluginCatalog.tsx +++ b/ui/src/pages/PluginCatalog.tsx @@ -27,6 +27,57 @@ import { api, type CatalogPlugin, type PluginFilters } from '../lib/api'; import { toast } from '../lib/toast'; import { useNavigate } from 'react-router-dom'; +/** + * PluginCatalog - Marketplace catalog for discovering and installing plugins + * + * Comprehensive plugin discovery interface providing: + * - Search across plugin names, descriptions, and authors + * - Multi-level filtering (category, type, tags) + * - Sorting options (popular, rating, recent, downloads) + * - Paginated results with configurable page size + * - Plugin detail modal with full metadata + * - One-click installation with version selection + * - Plugin ratings and download statistics + * - Featured plugin highlighting + * + * Features: + * - Text search with real-time filtering + * - Category filtering (e.g., "Authentication", "Analytics", "UI Enhancement") + * - Plugin type filtering (extension, webhook, API, UI, theme) + * - Tag-based filtering for granular discovery + * - Active filter chips with individual removal + * - Sort by popularity, rating, recency, or download count + * - Plugin cards with ratings, download counts, and screenshots + * - Detailed plugin modal with description, permissions, and changelog + * - Install with automatic dependency resolution + * - Navigate to installed plugins after installation + * - Empty state with helpful guidance + * + * User workflows: + * - Search plugins by name or functionality + * - Filter by category and type + * - View plugin details before installing + * - Install plugin and configure settings + * - Navigate to "Installed Plugins" to manage + * - Clear filters to browse all available plugins + * + * @page + * @route /plugins/catalog - Plugin marketplace catalog + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Plugin catalog page with search and filters + * + * @example + * // Route configuration: + * } /> + * } /> + * + * @see InstalledPlugins for managing installed plugins + * @see PluginCard for plugin card display component + * @see PluginDetailModal for plugin details modal + */ export default function PluginCatalog() { const navigate = useNavigate(); const [loading, setLoading] = useState(true); diff --git a/ui/src/pages/Repositories.tsx b/ui/src/pages/Repositories.tsx index 209baf83..67560ce1 100644 --- a/ui/src/pages/Repositories.tsx +++ b/ui/src/pages/Repositories.tsx @@ -35,6 +35,43 @@ import { useSyncAllRepositories, } from '../hooks/useApi'; +/** + * Repositories - Template repository management page + * + * Provides interface for managing external Git repositories containing application templates. + * Users can add, sync, and remove template repositories to populate the catalog with + * available applications. Repositories are synchronized to pull the latest templates, + * which become available in the template catalog for session creation. + * + * Features: + * - Add new Git repositories with authentication options + * - Manual and automatic repository synchronization + * - View sync status and template counts + * - Delete repositories and their templates + * - Bulk sync all repositories + * - Real-time sync status updates + * + * User workflows: + * - Add custom template repositories (GitHub, GitLab, etc.) + * - Sync repositories to update template catalog + * - Monitor sync progress and status + * - Remove outdated or unused repositories + * + * @page + * @route /repositories - Template repository management + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Repository management interface with sync controls + * + * @example + * // Route configuration: + * } /> + * + * @see EnhancedRepositories for advanced repository management with WebSocket updates + * @see TemplateCatalog for browsing templates from repositories + */ export default function Repositories() { const { data: repositories = [], isLoading, refetch } = useRepositories(); const addRepository = useAddRepository(); diff --git a/ui/src/pages/Scheduling.tsx b/ui/src/pages/Scheduling.tsx index f2d17aad..10d018c7 100644 --- a/ui/src/pages/Scheduling.tsx +++ b/ui/src/pages/Scheduling.tsx @@ -50,6 +50,64 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * Scheduling - Session scheduling and calendar integration page + * + * Provides comprehensive session scheduling functionality with support for recurring + * schedules, calendar integrations, and automated session lifecycle management. Users + * can create one-time or recurring session schedules with auto-termination, pre-warming, + * and calendar synchronization features. + * + * Features: + * - Create scheduled sessions (one-time, daily, weekly, monthly, cron) + * - Configure auto-termination after duration + * - Pre-warm sessions before scheduled time + * - Enable/disable schedules without deletion + * - View next run and last run status + * - Google Calendar and Outlook integration + * - Export schedules to iCalendar format + * - Real-time schedule event notifications via WebSocket + * - Timezone support for scheduling + * + * Schedule types: + * - Once: One-time execution + * - Daily: Repeat daily at specific time + * - Weekly: Repeat on selected days of week + * - Monthly: Repeat on specific day of month + * - Cron: Advanced cron expression scheduling + * + * Calendar integration: + * - Connect Google Calendar or Outlook + * - Auto-sync scheduled sessions to calendar + * - Two-way synchronization support + * + * Real-time features: + * - Live schedule execution notifications + * - Completion and failure alerts + * - WebSocket connection monitoring + * + * User workflows: + * - Create recurring session schedules + * - Set up auto-termination for cost control + * - Connect calendars for visibility + * - Export schedules for external use + * - Monitor schedule execution status + * + * @page + * @route /scheduling - Session scheduling and calendar integration + * @access user - Available to all authenticated users + * + * @component + * + * @returns {JSX.Element} Scheduling interface with calendar integration + * + * @example + * // Route configuration: + * } /> + * + * @see Sessions for manual session management + * @see TemplateCatalog for available session templates + */ interface ScheduledSession { id: number; name: string; diff --git a/ui/src/pages/SessionViewer.tsx b/ui/src/pages/SessionViewer.tsx index 9d1370ee..3ce3cda9 100644 --- a/ui/src/pages/SessionViewer.tsx +++ b/ui/src/pages/SessionViewer.tsx @@ -28,7 +28,7 @@ import { Link as LinkIcon, Wifi as ConnectedIcon, WifiOff as DisconnectedIcon, -} from '@mui/icons-material'; +} from '@mui/material-icons'; import { api } from '../lib/api'; import { useUserStore } from '../store/userStore'; import { useSessionsWebSocket } from '../hooks/useWebSocket'; @@ -40,6 +40,71 @@ import SessionShareDialog from '../components/SessionShareDialog'; import SessionInvitationDialog from '../components/SessionInvitationDialog'; import SessionCollaboratorsPanel from '../components/SessionCollaboratorsPanel'; +/** + * SessionViewer - Full-screen VNC session viewer for connecting to running sessions + * + * Immersive session viewing interface providing: + * - Full-screen VNC client embedded in iframe + * - Session connection management (connect, disconnect, reconnect) + * - Real-time session status monitoring + * - Collaboration features (sharing, invitations, active users) + * - WebSocket-based session state updates + * - Session information panel with metadata + * - Fullscreen mode toggle + * - Connection health monitoring + * + * Features: + * - Embedded VNC iframe with session URL + * - Top toolbar with session controls + * - Connection status indicator (connected/disconnected) + * - Session state chip (running, hibernated, terminated) + * - Share session button (direct sharing dialog) + * - Invite users button (invitation link dialog) + * - Collaborators panel showing active users + * - Session info dialog with details + * - Fullscreen toggle button + * - Close button to return to sessions list + * - Auto-connect on page load + * - Reconnect on session wake + * - Disconnect on page unload + * + * User workflows: + * - Open running session from Sessions page + * - View session in full-screen VNC client + * - Monitor connection status in real-time + * - Share session with other users + * - Create invitation links for external access + * - View active collaborators + * - Toggle fullscreen for immersive experience + * - Close viewer to return to session list + * + * Real-time features: + * - Session state change notifications + * - Collaborator join/leave events + * - Connection health updates + * - Session hibernation/wake events + * - WebSocket connection status + * + * @page + * @route /sessions/:sessionId/view - Session viewer (dynamic route with sessionId param) + * @access user - Requires session ownership or share permission + * + * @component + * + * @returns {JSX.Element} Full-screen session viewer with VNC client + * + * @example + * // Route configuration: + * } /> + * + * // Navigation from Sessions page: + * navigate(`/sessions/${session.id}/view`); + * + * @see Sessions for session management page + * @see SessionShareDialog for sharing sessions + * @see SessionInvitationDialog for creating invitation links + * @see SessionCollaboratorsPanel for viewing active collaborators + */ export default function SessionViewer() { const { sessionId } = useParams<{ sessionId: string }>(); const navigate = useNavigate(); diff --git a/ui/src/pages/Sessions.tsx b/ui/src/pages/Sessions.tsx index 88a71d4f..b4e12af9 100644 --- a/ui/src/pages/Sessions.tsx +++ b/ui/src/pages/Sessions.tsx @@ -48,6 +48,52 @@ import { useNotificationQueue } from '../components/NotificationQueue'; import EnhancedWebSocketStatus from '../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../components/WebSocketErrorBoundary'; +/** + * Sessions - Session management page for viewing and controlling user sessions + * + * Comprehensive session management interface providing: + * - Grid view of all user sessions with detailed status + * - Session state control (start, pause/hibernate, terminate/delete) + * - Real-time session updates via WebSocket + * - Tag management for organizing sessions + * - Session sharing with other users or via invitation links + * - Resource usage and activity monitoring + * - Idle timeout tracking with visual progress indicators + * - Tag-based filtering of sessions + * - Quota alerts for resource limits + * + * Session actions available: + * - Connect to running sessions (opens SessionViewer) + * - Hibernate sessions to save resources + * - Wake hibernated sessions + * - Delete/terminate sessions + * - Share sessions with specific users (direct sharing) + * - Create invitation links for session access + * - Manage session tags for organization + * + * Real-time features: + * - Session state change notifications + * - Activity indicators (active/idle status) + * - Resource usage updates + * - Active connection counts + * - Idle time countdown with auto-hibernate warnings + * + * @page + * @route /sessions - User sessions management page + * @access user - Shows only current user's sessions + * + * @component + * + * @returns {JSX.Element} Sessions management page with session cards and controls + * + * @example + * // Route configuration: + * } /> + * + * @see SessionViewer for connecting to running sessions + * @see Catalog for creating new sessions from templates + * @see SharedSessions for viewing sessions shared by others + */ export default function Sessions() { const navigate = useNavigate(); const username = useUserStore((state) => state.user?.username); diff --git a/ui/src/pages/SharedSessions.tsx b/ui/src/pages/SharedSessions.tsx index 69c613e4..ba96e6d3 100644 --- a/ui/src/pages/SharedSessions.tsx +++ b/ui/src/pages/SharedSessions.tsx @@ -40,6 +40,64 @@ interface SharedSession { url?: string; } +/** + * SharedSessions - View and access sessions shared by other users + * + * Displays sessions that have been shared with the current user, providing: + * - Grid view of all shared sessions + * - Session metadata (owner, template, state, creation time) + * - Permission level indicator (view, edit, control) + * - Quick access to shared session viewers + * - Real-time session status updates via WebSocket + * - Empty state with helpful guidance + * + * Features: + * - Session cards with owner information + * - Template name and app type display + * - Session state chips (running, hibernated, terminated) + * - Permission level badges (view-only, editor, controller) + * - "Shared At" timestamp showing when access was granted + * - Connect button to open session viewer + * - Real-time state change notifications + * - Session state change alerts (running → hibernated → terminated) + * - WebSocket connection status indicator + * + * Permission levels: + * - View: Can view session (read-only access) + * - Edit: Can interact with session + * - Control: Full control including session management + * + * User workflows: + * - View all sessions shared with current user + * - Check session status before connecting + * - Open shared session in viewer + * - Monitor session owner and sharing details + * - Receive notifications when shared sessions change state + * + * Real-time features: + * - Session state change notifications + * - Session termination alerts + * - Sharing revocation notifications + * - New share notifications + * - WebSocket connection status + * + * @page + * @route /shared-sessions - Sessions shared with current user + * @access user - Shows only sessions shared with the authenticated user + * + * @component + * + * @returns {JSX.Element} Shared sessions page with session cards + * + * @example + * // Route configuration: + * } /> + * } /> + * + * @see Sessions for managing own sessions + * @see SessionViewer for viewing shared sessions + * @see SessionShareDialog for sharing workflow (from owner perspective) + */ export default function SharedSessions() { const navigate = useNavigate(); const currentUser = useUserStore((state) => state.user); diff --git a/ui/src/pages/admin/Compliance.tsx b/ui/src/pages/admin/Compliance.tsx index a7ab13b3..f04d5c21 100644 --- a/ui/src/pages/admin/Compliance.tsx +++ b/ui/src/pages/admin/Compliance.tsx @@ -54,6 +54,84 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * Compliance - Compliance framework and policy management for administrators + * + * Administrative interface for managing compliance frameworks (SOC2, HIPAA, GDPR), + * enforcing policies, tracking violations, and generating compliance reports. Provides + * real-time compliance monitoring with automatic violation detection, remediation + * tracking, and comprehensive audit capabilities. + * + * Features: + * - Compliance framework management (SOC2, HIPAA, GDPR) + * - Policy creation and enforcement + * - Violation tracking and resolution + * - Compliance dashboard with metrics + * - Report generation (summary, detailed, attestation) + * - Data retention policy configuration + * - Real-time violation alerts via WebSocket + * - Severity-based prioritization + * + * Administrative capabilities: + * - Enable/disable compliance frameworks + * - Create policies with enforcement levels + * - Monitor violations by severity + * - Generate compliance reports + * - Resolve and remediate violations + * - Configure data retention policies + * - Audit compliance status + * + * Compliance frameworks: + * - SOC2: Service Organization Control 2 + * - HIPAA: Health Insurance Portability and Accountability Act + * - GDPR: General Data Protection Regulation + * - PCI-DSS: Payment Card Industry Data Security Standard + * - ISO27001: Information Security Management + * + * Enforcement levels: + * - advisory: Log only (no blocking) + * - warning: Alert users and admins + * - blocking: Prevent non-compliant actions + * + * Violation severities: + * - critical: Immediate attention required + * - high: Urgent remediation needed + * - medium: Address within SLA + * - low: Monitor and track + * + * Report types: + * - summary: High-level compliance overview + * - detailed: Comprehensive violation details + * - attestation: Formal compliance certification + * + * Real-time features: + * - Live violation notifications (critical/high priority) + * - Automatic dashboard refresh + * - WebSocket connection monitoring + * - Event-driven alerts + * + * User workflows: + * - Enable compliance frameworks + * - Create policies for user groups + * - Monitor violations dashboard + * - Resolve open violations + * - Generate compliance reports + * - Configure data retention policies + * + * @page + * @route /admin/compliance - Compliance and governance management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Compliance management interface with policy enforcement + * + * @example + * // Route configuration: + * } /> + * + * @see Integrations for compliance notification webhooks + */ interface ComplianceFramework { id: number; name: string; diff --git a/ui/src/pages/admin/Dashboard.tsx b/ui/src/pages/admin/Dashboard.tsx index 30b5aed1..50e513da 100644 --- a/ui/src/pages/admin/Dashboard.tsx +++ b/ui/src/pages/admin/Dashboard.tsx @@ -35,6 +35,71 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * AdminDashboard - Platform administration overview and metrics + * + * Provides comprehensive administrative dashboard with real-time platform statistics, + * cluster health monitoring, resource utilization metrics, and recent activity overview. + * Central control panel for platform administrators to monitor system health, user + * activity, resource consumption, and receive critical alerts. + * + * Features: + * - Real-time cluster metrics via WebSocket + * - Cluster health status indicator + * - Node status monitoring (ready/not ready) + * - Active sessions and user tracking + * - CPU and memory utilization graphs + * - Pod capacity monitoring + * - Session distribution visualization + * - Recent sessions table + * - Critical alert notifications + * + * Administrative capabilities: + * - Monitor all active sessions across the platform + * - Track cluster node health in real-time + * - View resource utilization trends + * - Identify capacity bottlenecks + * - Receive automatic alerts for critical events + * - Quick access to detailed admin functions + * + * Real-time metrics: + * - Cluster nodes (total, ready, not ready) + * - Sessions (total, running, hibernated, terminated) + * - Users (total, active) + * - CPU utilization (used, total, percentage) + * - Memory utilization (used, total, percentage) + * - Pod capacity (used, total, percentage) + * + * Critical notifications: + * - Node health degradation + * - CPU utilization > 90% + * - Memory utilization > 90% + * - Pod capacity > 90% + * + * User workflows: + * - Monitor platform health at a glance + * - Identify resource bottlenecks + * - Track user activity patterns + * - Respond to critical alerts + * - Navigate to detailed admin functions + * + * @page + * @route /admin - Platform administration dashboard + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Administrative dashboard with real-time platform metrics + * + * @example + * // Route configuration: + * } /> + * + * @see Users for user management + * @see Nodes for detailed cluster node monitoring + * @see Plugins for plugin administration + * @see Scaling for load balancing and auto-scaling + */ interface ClusterMetrics { nodes: { total: number; diff --git a/ui/src/pages/admin/Integrations.tsx b/ui/src/pages/admin/Integrations.tsx index 2af1fab7..cb1489f8 100644 --- a/ui/src/pages/admin/Integrations.tsx +++ b/ui/src/pages/admin/Integrations.tsx @@ -49,6 +49,76 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * Integrations - Webhook and external integration management for administrators + * + * Administrative interface for configuring webhooks and external service integrations + * to connect StreamSpace with third-party tools and services. Supports webhook creation + * for platform events, delivery tracking, and integration with Slack, Teams, Discord, + * PagerDuty, and email notifications. + * + * Features: + * - Create and manage webhooks for platform events + * - Configure webhook URLs and authentication secrets + * - Select events to trigger webhooks (16+ event types) + * - Test webhook delivery + * - View webhook delivery history and status + * - External integration configuration (Slack, Teams, etc.) + * - Real-time webhook delivery notifications via WebSocket + * - Enable/disable webhooks without deletion + * + * Administrative capabilities: + * - System-wide webhook configuration + * - Multi-event webhook subscriptions + * - HMAC signature verification setup + * - Delivery retry monitoring + * - Integration health tracking + * - Webhook deletion and management + * + * Available webhook events: + * - session.created, session.started, session.hibernated + * - session.terminated, session.failed + * - user.created, user.updated, user.deleted + * - dlp.violation, recording.started, recording.completed + * - workflow.started, workflow.completed + * - collaboration.started, compliance.violation + * - security.alert, scaling.event + * + * External integrations: + * - Slack: Channel notifications and alerts + * - Microsoft Teams: Team notifications + * - Discord: Server notifications + * - PagerDuty: Incident management + * - Email (SMTP): Email notifications + * + * Real-time features: + * - Live webhook delivery status + * - Success/failure notifications + * - Delivery attempt tracking + * - WebSocket connection monitoring + * + * User workflows: + * - Create webhooks for event notifications + * - Test webhook endpoints before activation + * - Monitor delivery success rates + * - Configure external service integrations + * - Review webhook delivery history + * - Troubleshoot failed deliveries + * + * @page + * @route /admin/integrations - Webhook and external integration management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Integration management interface with webhook controls + * + * @example + * // Route configuration: + * } /> + * + * @see Compliance for compliance-related notifications + */ interface Webhook { id: number; name: string; diff --git a/ui/src/pages/admin/Plugins.tsx b/ui/src/pages/admin/Plugins.tsx index bd52b2ed..424f9e44 100644 --- a/ui/src/pages/admin/Plugins.tsx +++ b/ui/src/pages/admin/Plugins.tsx @@ -40,6 +40,68 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * AdminPlugins - System-wide plugin management for administrators + * + * Administrative interface for managing platform plugins that extend functionality across + * the entire system. Administrators can install, configure, enable/disable, and uninstall + * plugins that affect all users. Provides real-time WebSocket updates for plugin lifecycle + * events and comprehensive statistics on plugin usage. + * + * Features: + * - View all installed plugins system-wide + * - Enable/disable plugins globally + * - Configure plugin settings with JSON editor + * - View plugin details (type, version, installer) + * - Uninstall plugins with confirmation + * - Real-time plugin event notifications via WebSocket + * - Plugin statistics dashboard + * - Filter plugins by type and status + * + * Administrative capabilities: + * - System-wide plugin installation management + * - Global enable/disable controls + * - Plugin configuration editing (JSON) + * - Plugin lifecycle monitoring + * - Usage statistics and metrics + * - Plugin dependency management + * + * Plugin types: + * - extension: Platform extensions + * - webhook: Webhook integrations + * - api: API extensions + * - ui: UI components and themes + * - theme: Appearance themes + * + * Real-time features: + * - Live plugin installation notifications + * - Enable/disable event alerts + * - Update notifications + * - Error alerts for plugin failures + * - WebSocket connection monitoring + * + * User workflows: + * - Review installed plugins across the platform + * - Enable/disable plugins for all users + * - Configure global plugin settings + * - Monitor plugin performance and errors + * - Uninstall problematic plugins + * + * @page + * @route /admin/plugins - System-wide plugin management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Plugin management interface with system-wide controls + * + * @example + * // Route configuration: + * } /> + * + * @see PluginCatalog for installing new plugins + * @see InstalledPlugins for user-level plugin management + */ const pluginTypeColors: Record = { extension: '#4CAF50', webhook: '#FF9800', diff --git a/ui/src/pages/admin/Quotas.tsx b/ui/src/pages/admin/Quotas.tsx index d06377e3..d6edb484 100644 --- a/ui/src/pages/admin/Quotas.tsx +++ b/ui/src/pages/admin/Quotas.tsx @@ -35,6 +35,66 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * AdminQuotas - User resource quota management for administrators + * + * Administrative interface for managing user resource quotas across the platform. + * Administrators can set and modify resource limits for individual users to control + * session creation, CPU, memory, and storage usage. Provides real-time quota monitoring + * with usage visualization and automatic alerts for quota violations. + * + * Features: + * - Create and edit user quotas + * - Set limits for sessions, CPU, memory, storage + * - Visual usage indicators with progress bars + * - Real-time quota usage tracking + * - Quota violation warnings + * - Delete quota configurations + * - Real-time quota event notifications via WebSocket + * + * Administrative capabilities: + * - Define per-user resource limits + * - Monitor quota utilization in real-time + * - Prevent resource overconsumption + * - Receive alerts for quota violations + * - Enforce fair resource allocation + * - Audit quota changes + * + * Resource types: + * - Sessions: Maximum concurrent sessions (integer) + * - CPU: Maximum CPU allocation (e.g., "4000m" = 4 cores) + * - Memory: Maximum memory allocation (e.g., "8Gi" = 8 gigabytes) + * - Storage: Maximum persistent storage (e.g., "50Gi" = 50 gigabytes) + * + * Real-time features: + * - Live quota usage updates + * - Quota exceeded notifications (high priority) + * - Quota warning alerts (>90% usage) + * - Create/update/delete notifications + * - WebSocket connection monitoring + * + * User workflows: + * - Create quotas for new users + * - Update quotas based on requirements + * - Monitor user resource consumption + * - Identify users approaching limits + * - Delete quotas to remove restrictions + * + * @page + * @route /admin/quotas - User resource quota management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Quota management interface with usage visualization + * + * @example + * // Route configuration: + * } /> + * + * @see Users for user account management + * @see AdminDashboard for overall resource utilization + */ export default function AdminQuotas() { const [quotas, setQuotas] = useState([]); const [loading, setLoading] = useState(true); diff --git a/ui/src/pages/admin/Scaling.tsx b/ui/src/pages/admin/Scaling.tsx index 899aae3b..6afa29b3 100644 --- a/ui/src/pages/admin/Scaling.tsx +++ b/ui/src/pages/admin/Scaling.tsx @@ -47,6 +47,77 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * Scaling - Load balancing and auto-scaling management for administrators + * + * Administrative interface for configuring load balancing policies, auto-scaling rules, + * and monitoring cluster node performance. Provides comprehensive controls for session + * distribution, resource-based scaling, and capacity management with real-time event + * notifications and metrics. + * + * Features: + * - Load balancing policy configuration + * - Auto-scaling policy management + * - Real-time node status monitoring + * - Manual scaling triggers (scale up/down) + * - Scaling event history + * - Resource utilization metrics per node + * - Session distribution across nodes + * - Critical scaling failure alerts + * + * Administrative capabilities: + * - Create and manage load balancing policies + * - Configure auto-scaling policies (horizontal/vertical) + * - Monitor node health and resource usage + * - Manually trigger scaling operations + * - View scaling history and audit trail + * - Receive alerts for scaling failures + * + * Load balancing strategies: + * - round_robin: Distribute sessions evenly in rotation + * - least_loaded: Route to node with fewest sessions + * - resource_based: Route based on CPU/memory availability + * - geographic: Route based on node location + * - weighted: Distribute based on node weights + * + * Auto-scaling modes: + * - horizontal: Add/remove replicas + * - vertical: Adjust CPU/memory allocation + * + * Metric types: + * - cpu: Scale based on CPU utilization + * - memory: Scale based on memory usage + * - custom: Scale based on custom metrics + * + * Real-time features: + * - Live scaling event notifications (up/down) + * - Critical alerts for scaling failures + * - Node health status updates + * - Resource utilization monitoring + * - WebSocket connection tracking + * + * User workflows: + * - Create load balancing policies for session distribution + * - Configure auto-scaling rules for capacity management + * - Monitor node performance in real-time + * - Manually scale up/down during high load + * - Review scaling history for optimization + * + * @page + * @route /admin/scaling - Load balancing and auto-scaling management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} Scaling management interface with real-time monitoring + * + * @example + * // Route configuration: + * } /> + * + * @see Nodes for detailed node management + * @see AdminDashboard for cluster overview + */ interface LoadBalancingPolicy { id: number; name: string; diff --git a/ui/src/pages/admin/Users.tsx b/ui/src/pages/admin/Users.tsx index c9c4300f..956565d9 100644 --- a/ui/src/pages/admin/Users.tsx +++ b/ui/src/pages/admin/Users.tsx @@ -42,6 +42,72 @@ import { useNotificationQueue } from '../../components/NotificationQueue'; import EnhancedWebSocketStatus from '../../components/EnhancedWebSocketStatus'; import WebSocketErrorBoundary from '../../components/WebSocketErrorBoundary'; +/** + * Users - User account management for administrators + * + * Administrative interface for managing user accounts across the platform. Provides + * comprehensive user management capabilities including creation, editing, deletion, + * and filtering. Administrators can view user details, manage roles and permissions, + * and monitor user activity with real-time WebSocket updates. + * + * Features: + * - View all user accounts in table format + * - Filter by role, provider, and active status + * - Search users by username or email + * - Create new user accounts + * - Edit user details (navigate to UserDetail) + * - Delete user accounts with confirmation + * - Real-time user event notifications via WebSocket + * - User statistics (total, admin, active) + * + * Administrative capabilities: + * - Create and manage user accounts + * - Assign user roles (admin, user) + * - Set authentication provider (local, SAML, OIDC) + * - Enable/disable user accounts + * - Monitor user creation, updates, and deletions + * - View user login activity + * + * User roles: + * - admin: Full administrative access + * - user: Standard user access + * + * Authentication providers: + * - local: Username/password authentication + * - saml: SAML 2.0 SSO + * - oidc: OpenID Connect OAuth2 + * + * Real-time features: + * - Live user creation notifications + * - User update alerts + * - User deletion notifications + * - Optional login activity tracking + * - WebSocket connection monitoring + * + * User workflows: + * - Create new user accounts + * - Filter users by criteria + * - Search for specific users + * - View user details + * - Delete inactive accounts + * - Monitor user events + * + * @page + * @route /admin/users - User account management + * @access admin - Restricted to administrators only + * + * @component + * + * @returns {JSX.Element} User management interface with filtering and search + * + * @example + * // Route configuration: + * } /> + * + * @see CreateUser for creating new user accounts + * @see UserDetail for viewing and editing user details + * @see Quotas for managing user resource quotas + */ export default function Users() { const navigate = useNavigate(); const queryClient = useQueryClient();