-- AwoooP RLS Canary Wave 1.1: low-row MCP tool registry
-- Date: 2026-05-12
--
-- Scope:
--   - awooop_mcp_tool_registry
--
-- Why this table:
--   Latest production exact count: 4 rows, all project_id='ewoooc'.
--   Runtime read path is MCP Gateway Gate 3 and filters by ctx.project_id.
--
-- Why not awooop_projects in this wave:
--   Operator Console list_tenants() currently expects cross-tenant visibility.
--   A normal tenant policy would hide ewoooc when context is awoooi, so
--   awooop_projects remains blocked until an explicit platform-admin DB path
--   exists.
--
-- Safety:
--   - fail-closed policy only; no NULL/empty-string app.project_id bypass.
--   - aborts if target is missing project_id, has NULL project_id, or has
--     more rows than the reviewed canary cap.
--   - run with a migration/operator role, not through the production app role.

BEGIN;

SET LOCAL lock_timeout = '5s';
SET LOCAL statement_timeout = '30s';

DO $$
DECLARE
    total_rows bigint;
    null_project_rows bigint;
BEGIN
    IF to_regclass('public.awooop_mcp_tool_registry') IS NULL THEN
        RAISE EXCEPTION 'RLS canary target table does not exist: awooop_mcp_tool_registry';
    END IF;

    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'awooop_mcp_tool_registry'
          AND column_name = 'project_id'
    ) THEN
        RAISE EXCEPTION 'RLS canary target missing project_id: awooop_mcp_tool_registry';
    END IF;

    SELECT COUNT(*), COUNT(*) FILTER (WHERE project_id IS NULL)
    INTO total_rows, null_project_rows
    FROM awooop_mcp_tool_registry;

    IF null_project_rows <> 0 THEN
        RAISE EXCEPTION 'RLS canary target has NULL project_id rows: %, nulls=%',
            'awooop_mcp_tool_registry', null_project_rows;
    END IF;

    IF total_rows > 20 THEN
        RAISE EXCEPTION 'RLS canary wave1.1 reviewed cap exceeded: %, rows=%',
            'awooop_mcp_tool_registry', total_rows;
    END IF;
END
$$;

ALTER TABLE awooop_mcp_tool_registry ENABLE ROW LEVEL SECURITY;
ALTER TABLE awooop_mcp_tool_registry FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS mcp_tool_registry_tenant_isolation ON awooop_mcp_tool_registry;
DROP POLICY IF EXISTS awooop_mcp_tool_registry_tenant ON awooop_mcp_tool_registry;
CREATE POLICY awooop_mcp_tool_registry_tenant ON awooop_mcp_tool_registry
    FOR ALL TO awooop_app
    USING (project_id = current_setting('app.project_id', TRUE))
    WITH CHECK (project_id = current_setting('app.project_id', TRUE));

COMMIT;
