-- Security Fix: SQL Injection Hardening for is_workspace_admin() Helper Function
-- This migration adds explicit UUID validation to prevent SQL injection attacks
--
-- Related: #355 Code Review - Security CRIT-3
-- Original issue: Migration 20260129221004_add_rls_policies

-- =============================================================================
-- SECURITY FIX: Add explicit UUID validation to is_workspace_admin()
-- =============================================================================
-- The is_workspace_admin() function previously accepted UUID parameters without
-- explicit type casting/validation. Although PostgreSQL's parameter binding provides
-- some protection, explicit UUID type validation is a security best practice.
--
-- This fix adds explicit UUID validation using PostgreSQL's uuid type checking
-- to ensure that non-UUID values cannot bypass the function's intent.

CREATE OR REPLACE FUNCTION is_workspace_admin(workspace_uuid UUID, user_uuid UUID)
RETURNS BOOLEAN AS $$
DECLARE
  -- Validate input parameters are valid UUIDs
  v_workspace_id UUID;
  v_user_id UUID;
BEGIN
  -- Explicitly validate workspace_uuid parameter
  IF workspace_uuid IS NULL THEN
    RETURN FALSE;
  END IF;
  v_workspace_id := workspace_uuid::UUID;

  -- Explicitly validate user_uuid parameter
  IF user_uuid IS NULL THEN
    RETURN FALSE;
  END IF;
  v_user_id := user_uuid::UUID;

  -- Query with validated parameters
  RETURN EXISTS (
    SELECT 1 FROM workspace_members
    WHERE workspace_id = v_workspace_id
    AND user_id = v_user_id
    AND role IN ('OWNER', 'ADMIN')
  );
END;
$$ LANGUAGE plpgsql STABLE SECURITY DEFINER;

-- =============================================================================
-- NOTES
-- =============================================================================
-- This is a hardening fix that adds defense-in-depth to the is_workspace_admin()
-- helper function. While PostgreSQL's parameterized queries already provide
-- protection against SQL injection, explicit UUID type validation ensures:
--
-- 1. Parameters are explicitly cast to UUID type
-- 2. NULL values are handled defensively
-- 3. The function's intent is clear and secure
-- 4. Compliance with security best practices
--
-- This change is backward compatible and does not affect existing functionality.
