@@ -96,4 +96,52 @@ describe('RLS Demo - Data Insertion', () => {
9696
9797 expect ( userData . id ) . toBe ( user . id ) ;
9898 } ) ;
99+
100+ it ( 'should fail RLS when trying to access other user\'s data' , async ( ) => {
101+ // Get two different users
102+ const users = await pg . many ( `SELECT id FROM rls_test.users ORDER BY email LIMIT 2` ) ;
103+ expect ( users . length ) . toBeGreaterThanOrEqual ( 2 ) ;
104+
105+ const user1 = users [ 0 ] ;
106+ const user2 = users [ 1 ] ;
107+
108+ // Set context to user1
109+ db . setContext ( {
110+ role : 'authenticated' ,
111+ 'jwt.claims.user_id' : user1 . id
112+ } ) ;
113+
114+ // This should work - user1 accessing their own data
115+ const ownData = await db . one (
116+ `SELECT id, email FROM rls_test.users WHERE id = $1` ,
117+ [ user1 . id ]
118+ ) ;
119+ expect ( ownData . id ) . toBe ( user1 . id ) ;
120+
121+ // This should fail - user1 trying to access user2's data
122+ await expect (
123+ db . one ( `SELECT id, email FROM rls_test.users WHERE id = $1` , [ user2 . id ] )
124+ ) . rejects . toThrow ( ) ;
125+
126+ // This should also fail - user1 trying to access user2's products
127+ await expect (
128+ db . one ( `SELECT id, name FROM rls_test.products WHERE owner_id = $1` , [ user2 . id ] )
129+ ) . rejects . toThrow ( ) ;
130+ } ) ;
131+
132+ it ( 'should fail RLS when not authenticated' , async ( ) => {
133+ // Clear context to simulate unauthenticated user
134+ db . setContext ( {
135+ role : 'anon'
136+ } ) ;
137+
138+ // These should all fail because we're not authenticated
139+ await expect (
140+ db . one ( `SELECT id FROM rls_test.users LIMIT 1` )
141+ ) . rejects . toThrow ( ) ;
142+
143+ await expect (
144+ db . one ( `SELECT id FROM rls_test.products LIMIT 1` )
145+ ) . rejects . toThrow ( ) ;
146+ } ) ;
99147} ) ;
0 commit comments