# CRITICAL FIX: Secret Permissions Error

## The Problem
You're getting the error: **"Integrations do not allow secret 'FANSIFTER_APP_REPORTING.DEV_MMACHADO.SPARK_APIFY_API_KEY'"**

## Root Cause
We missed the **most critical step** in the Snowflake secrets workflow: granting READ permission on the secret to the role.

## The Missing Step
According to official Snowflake documentation, after creating a secret, you MUST grant READ permission:

```sql
GRANT READ ON SECRET secret_name TO ROLE role_name;
```

Without this grant, the external access integration cannot access the secret, causing the error.

## Immediate Fix
Execute this script to resolve the issue immediately:

**File:** `/Users/mach071/Documents/collab/mymac80/spark/SQL/fix_secret_permissions.sql`

Or run these commands directly in Snowflake:

```sql
-- Set context
USE ROLE ACCOUNTADMIN;
USE WAREHOUSE DEV_OWS_WH;
USE DATABASE FANSIFTER_APP_REPORTING;
USE SCHEMA DEV_MMACHADO;

-- Apply the missing permissions
GRANT READ ON SECRET spark_apify_api_key TO ROLE ACCOUNTADMIN;
GRANT USAGE ON INTEGRATION spark_analytics_external_access TO ROLE ACCOUNTADMIN;
```

## Complete Workflow (For Future Reference)
The COMPLETE and CORRECT Snowflake secrets workflow is:

```sql
-- 1. Create Secret
CREATE OR REPLACE SECRET secret_name
  TYPE = GENERIC_STRING
  SECRET_STRING = 'actual_secret_value';

-- 2. CRITICAL: Grant READ permission (MOST COMMONLY MISSED!)
GRANT READ ON SECRET secret_name TO ROLE role_name;

-- 3. Create External Access Integration
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION integration_name
  ALLOWED_NETWORK_RULES = (network_rules)
  ALLOWED_AUTHENTICATION_SECRETS = (secret_name)
  ENABLED = TRUE;

-- 4. Grant USAGE on Integration
GRANT USAGE ON INTEGRATION integration_name TO ROLE role_name;

-- 5. Create Streamlit App
CREATE STREAMLIT database.schema.app_name
    ROOT_LOCATION = '@database.schema.stage_name'
    MAIN_FILE = 'app.py'
    EXTERNAL_ACCESS_INTEGRATIONS = (integration_name)
    SECRETS = ('alias' = database.schema.secret_name);
```

## Verification Steps
After applying the fix:

1. Run the fix script: `SQL/fix_secret_permissions.sql`
2. Test the application - the secret error should be resolved
3. Navigate to "Test Apify API" page in your Spark Analytics app
4. Use the diagnostic tools to verify everything is working

## Prevention
This critical step has been added to:
- The main deployment script (`deploy_with_diagnostics.sql`)
- The CLAUDE.md best practices section
- This will prevent the issue from recurring in future deployments

## Reference
- **Official Documentation:** https://docs.snowflake.com/en/developer-guide/streamlit/additional-features
- **Fix Script:** `/Users/mach071/Documents/collab/mymac80/spark/SQL/fix_secret_permissions.sql`
- **Updated Deployment:** `/Users/mach071/Documents/collab/mymac80/spark/SQL/deploy_with_diagnostics.sql`

Execute the fix script and your Spark Analytics application should work immediately!