Skip to content

Commit 7efaa53

Browse files
schwaaampclaude
andcommitted
Fix: Update SERVICE_ROLE_KEY test for production schema
- Change query from 'id' to 'event_id' (matches production schema) - Accept 206 Partial Content status (valid for count queries) - Add detailed error messages for invalid/short keys - Warn if key is <50 chars (likely wrong key) Fixes test failures: - ❌ 'column user_health_events.id does not exist' → ✅ Uses event_id - ⚠️ 206 status rejected → ✅ Accepts 200 or 206 - ❓ Unknown key format → ✅ Clear diagnostic messages Common issue: Testing with 41-char key (likely anon key, not service_role) Solution: Use Secret API key from Supabase dashboard (sbp_..., 50+ chars) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent da5ad89 commit 7efaa53

File tree

1 file changed

+215
-0
lines changed

1 file changed

+215
-0
lines changed
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
#!/usr/bin/env -S deno run --allow-env --allow-net
2+
3+
/**
4+
* Integration Test: Verify New SERVICE_ROLE_KEY Works
5+
*
6+
* This test validates that the new Secret API key (sbp_...) works correctly
7+
* after migrating from the legacy JWT-based service_role key.
8+
*
9+
* Prerequisites:
10+
* 1. New Secret API key created in Supabase dashboard
11+
* 2. Secret set: supabase secrets set SERVICE_ROLE_KEY=<new_key>
12+
* 3. Edge Functions deployed with new key
13+
*
14+
* Run this test:
15+
* deno run --allow-env --allow-net supabase/functions/test-service-role-key.ts
16+
*/
17+
18+
import { assertEquals, assertExists } from 'https://deno.land/std@0.208.0/assert/mod.ts';
19+
20+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
21+
const SERVICE_ROLE_KEY = Deno.env.get('SERVICE_ROLE_KEY');
22+
23+
if (!SUPABASE_URL || !SERVICE_ROLE_KEY) {
24+
console.error('❌ Missing environment variables:');
25+
console.error(' SUPABASE_URL:', SUPABASE_URL ? '✓' : '✗');
26+
console.error(' SERVICE_ROLE_KEY:', SERVICE_ROLE_KEY ? '✓' : '✗');
27+
console.error('\nSet these variables and try again.');
28+
Deno.exit(1);
29+
}
30+
31+
console.log('🔐 Service Role Key Migration Test');
32+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
33+
34+
// Detect key format
35+
const isLegacyJWT = SERVICE_ROLE_KEY.startsWith('eyJ');
36+
const isSecretAPIKey = SERVICE_ROLE_KEY.startsWith('sbp_');
37+
38+
console.log('Key Format Detection:');
39+
if (isLegacyJWT) {
40+
console.log(' 🔑 Legacy JWT format detected (eyJ...)');
41+
console.log(' ⚠️ Recommendation: Migrate to Secret API key (sbp_...)');
42+
} else if (isSecretAPIKey) {
43+
console.log(' ✅ New Secret API key format detected (sbp_...)');
44+
} else {
45+
console.log(' ❌ Unknown key format (length: ' + SERVICE_ROLE_KEY.length + ')');
46+
console.log(' \n⚠️ WARNING: This key does not match expected formats:');
47+
console.log(' - Legacy JWT: starts with "eyJ" (200+ chars)');
48+
console.log(' - Secret API key: starts with "sbp_" (50+ chars)\n');
49+
50+
if (SERVICE_ROLE_KEY.length < 50) {
51+
console.log(' ❌ CRITICAL: Key is too short (' + SERVICE_ROLE_KEY.length + ' chars)');
52+
console.log(' This is likely the anon key or an invalid key.\n');
53+
console.log(' 📋 To get the correct key:');
54+
console.log(' 1. Go to: https://supabase.com/dashboard/project/akadvlbhqurijywfgena/settings/api');
55+
console.log(' 2. Click "Publishable and secret API keys" tab');
56+
console.log(' 3. Under "Secret API keys", click "Reveal" on your key');
57+
console.log(' 4. Copy the FULL key (should be 50+ characters)\n');
58+
}
59+
}
60+
console.log(' 📏 Key length: ' + SERVICE_ROLE_KEY.length + ' characters\n');
61+
62+
// Test 1: Direct database query via Supabase client
63+
console.log('Test 1: Direct Database Query');
64+
console.log('─────────────────────────────────────────');
65+
66+
const testDatabaseQuery = async () => {
67+
const response = await fetch(`${SUPABASE_URL}/rest/v1/user_health_events?select=event_id&limit=1`, {
68+
headers: {
69+
'Authorization': `Bearer ${SERVICE_ROLE_KEY}`,
70+
'apikey': SERVICE_ROLE_KEY,
71+
'Content-Type': 'application/json',
72+
},
73+
});
74+
75+
console.log(' Status:', response.status, response.statusText);
76+
77+
if (response.status === 200) {
78+
const data = await response.json();
79+
console.log(' ✅ Query successful');
80+
return true;
81+
} else if (response.status === 401) {
82+
const error = await response.text();
83+
console.log(' ❌ Authentication failed:', error);
84+
return false;
85+
} else {
86+
const error = await response.text();
87+
console.log(' ⚠️ Unexpected response:', error);
88+
return false;
89+
}
90+
};
91+
92+
const dbTest = await testDatabaseQuery();
93+
console.log('');
94+
95+
// Test 2: Edge Function call (OpenAI proxy)
96+
console.log('Test 2: Edge Function Authentication');
97+
console.log('─────────────────────────────────────────');
98+
99+
const testEdgeFunctionAuth = async () => {
100+
// We need a user JWT for this test, so we'll test the echo-test function if it exists
101+
const echoUrl = `${SUPABASE_URL}/functions/v1/echo-test`;
102+
103+
const response = await fetch(echoUrl, {
104+
method: 'POST',
105+
headers: {
106+
'Authorization': `Bearer ${SERVICE_ROLE_KEY}`,
107+
'Content-Type': 'application/json',
108+
},
109+
body: JSON.stringify({ test: 'service_role_key_migration' }),
110+
});
111+
112+
console.log(' Status:', response.status, response.statusText);
113+
114+
if (response.status === 200) {
115+
const data = await response.json();
116+
console.log(' ✅ Edge Function call successful');
117+
return true;
118+
} else if (response.status === 404) {
119+
console.log(' ⚠️ echo-test function not found (optional test)');
120+
return true; // Not a failure - function might not be deployed
121+
} else if (response.status === 401) {
122+
const error = await response.text();
123+
console.log(' ❌ Authentication failed:', error);
124+
return false;
125+
} else {
126+
const error = await response.text();
127+
console.log(' ⚠️ Unexpected response:', error);
128+
return false;
129+
}
130+
};
131+
132+
const edgeFunctionTest = await testEdgeFunctionAuth();
133+
console.log('');
134+
135+
// Test 3: RLS Bypass (service role should bypass RLS)
136+
console.log('Test 3: Row Level Security Bypass');
137+
console.log('─────────────────────────────────────────');
138+
139+
const testRLSBypass = async () => {
140+
// Try to query a table that has RLS enabled
141+
// Service role key should bypass RLS and see all rows
142+
const response = await fetch(`${SUPABASE_URL}/rest/v1/app_logs?select=count&limit=1`, {
143+
headers: {
144+
'Authorization': `Bearer ${SERVICE_ROLE_KEY}`,
145+
'apikey': SERVICE_ROLE_KEY,
146+
'Content-Type': 'application/json',
147+
'Prefer': 'count=exact',
148+
},
149+
});
150+
151+
console.log(' Status:', response.status, response.statusText);
152+
153+
// Accept both 200 OK and 206 Partial Content (valid for count queries)
154+
if (response.status === 200 || response.status === 206) {
155+
const contentRange = response.headers.get('content-range');
156+
console.log(' Content-Range:', contentRange);
157+
console.log(' ✅ RLS bypass successful (can query protected tables)');
158+
return true;
159+
} else if (response.status === 401) {
160+
console.log(' ❌ Authentication failed - key may not have service_role permissions');
161+
return false;
162+
} else if (response.status === 403) {
163+
console.log(' ❌ RLS not bypassed - key may not have service_role scope');
164+
return false;
165+
} else {
166+
const error = await response.text();
167+
console.log(' ⚠️ Unexpected response:', error);
168+
return false;
169+
}
170+
};
171+
172+
const rlsTest = await testRLSBypass();
173+
console.log('');
174+
175+
// Summary
176+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
177+
console.log('Test Summary:');
178+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
179+
console.log(' Database Query:', dbTest ? '✅ PASS' : '❌ FAIL');
180+
console.log(' Edge Function:', edgeFunctionTest ? '✅ PASS' : '❌ FAIL');
181+
console.log(' RLS Bypass:', rlsTest ? '✅ PASS' : '❌ FAIL');
182+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
183+
184+
if (dbTest && rlsTest) {
185+
console.log('✅ All critical tests passed!');
186+
console.log(' Your new SERVICE_ROLE_KEY is working correctly.\n');
187+
188+
if (isLegacyJWT) {
189+
console.log('📋 Next Steps:');
190+
console.log(' 1. You\'re still using the legacy JWT key');
191+
console.log(' 2. Migrate to Secret API key for easier rotation');
192+
console.log(' 3. See: /tmp/security-incident-remediation.md\n');
193+
} else if (isSecretAPIKey) {
194+
console.log('🎉 Migration Complete!');
195+
console.log(' • You\'ve successfully migrated to Secret API keys');
196+
console.log(' • You can now disable legacy JWT keys in Supabase');
197+
console.log(' • See: https://supabase.com/dashboard/project/' +
198+
SUPABASE_URL.split('//')[1].split('.')[0] + '/settings/api\n');
199+
}
200+
201+
Deno.exit(0);
202+
} else {
203+
console.log('❌ Some tests failed!');
204+
console.log(' Your SERVICE_ROLE_KEY may not be configured correctly.\n');
205+
console.log('📋 Troubleshooting:');
206+
console.log(' 1. Verify the key is set correctly:');
207+
console.log(' supabase secrets list');
208+
console.log(' 2. Ensure the key has "Full access" or "service_role" scope');
209+
console.log(' 3. Redeploy Edge Functions after updating secrets:');
210+
console.log(' supabase functions deploy --all');
211+
console.log(' 4. Check Supabase logs for errors:');
212+
console.log(' https://supabase.com/dashboard/project/[your-project]/logs\n');
213+
214+
Deno.exit(1);
215+
}

0 commit comments

Comments
 (0)