Spaces:
Runtime error
Runtime error
| import postgres from 'postgres'; | |
| import path from 'path'; | |
| import fs from 'fs'; | |
| // 1. Load DATABASE_URL from .env | |
| const envPath = path.resolve('artifacts/api-server/.env'); | |
| const envContent = fs.readFileSync(envPath, 'utf8'); | |
| const dbUrlMatch = envContent.match(/DATABASE_URL=(.+)/); | |
| if (!dbUrlMatch) { | |
| console.error("DATABASE_URL not found in .env"); | |
| process.exit(1); | |
| } | |
| const DATABASE_URL = dbUrlMatch[1].trim(); | |
| const sql = postgres(DATABASE_URL); | |
| // Test IDs | |
| const USER_A = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'; | |
| const USER_B = 'b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a12'; | |
| async function runErrorTests() { | |
| try { | |
| console.log("--- Starting Backend Error Testing ---"); | |
| const runAsUser = async (userId, queryFn) => { | |
| return await sql.begin(async (tx) => { | |
| await tx.unsafe(`SET LOCAL role TO authenticated`); | |
| await tx.unsafe(`SET LOCAL "request.jwt.claims" TO '{"sub": "${userId}"}'`); | |
| return await queryFn(tx); | |
| }); | |
| }; | |
| // Test 1: Insert missing required field (DB Level) | |
| console.log("\nTest 1: Inserting missing required field..."); | |
| try { | |
| await runAsUser(USER_A, tx => tx.unsafe(`INSERT INTO clients (user_id) VALUES ('${USER_A}')`)); | |
| console.log("FAIL: Inserted client without name!"); | |
| } catch (err) { | |
| console.log(`✓ Caught expected DB error: ${err.message}`); | |
| } | |
| // Test 2: Invalid UUID format | |
| console.log("\nTest 2: Using invalid UUID format..."); | |
| try { | |
| await runAsUser(USER_A, tx => tx.unsafe(`SELECT * FROM clients WHERE user_id = 'not-a-uuid'`)); | |
| console.log("FAIL: DB allowed invalid UUID query!"); | |
| } catch (err) { | |
| console.log(`✓ Caught expected UUID error: ${err.message}`); | |
| } | |
| // Test 3: Unauthorized Update (RLS) | |
| // First, insert as User A | |
| await sql.unsafe(`DELETE FROM clients WHERE name = 'Error Test Client'`); | |
| await runAsUser(USER_A, tx => tx.unsafe(`INSERT INTO clients (name, user_id) VALUES ('Error Test Client', '${USER_A}')`)); | |
| console.log("\nTest 3: User B tries to update User A's client (RLS Check)..."); | |
| const updateResult = await runAsUser(USER_B, tx => tx.unsafe(`UPDATE clients SET name = 'Hacked' WHERE name = 'Error Test Client'`)); | |
| if (updateResult.count === 0) { | |
| console.log("✓ User B update failed (0 rows affected) as expected due to RLS."); | |
| } else { | |
| console.log("FAIL: User B successfully updated User A's client!"); | |
| } | |
| console.log("\n--- Backend Error Testing Completed ---"); | |
| } catch (err) { | |
| console.error("Error during testing:", err); | |
| } finally { | |
| await sql.end(); | |
| } | |
| } | |
| runErrorTests(); | |