Create KeyHippo Policies
Guide to creating Row Level Security (RLS) policies with KeyHippo integration
This guide will walk you through the process of creating effective RLS policies using KeyHippo.
Understanding KeyHippo in RLS
KeyHippo extends Supabase’s RLS with two primary functions:
auth.keyhippo_check(user_id UUID)
: Verifies if the request is authenticated with a valid API key for the given user.keyhippo.key_uid()
: Retrieves the user ID associated with the current API key.
These functions allow you to create policies that seamlessly handle both traditional session-based auth and API key auth.
Basic Policy Structure
A typical KeyHippo-enabled RLS policy follows this structure:
Example Policies
1. Basic Read Access Policy
This policy allows users to read their own data, whether authenticated by session or API key:
2. Write Access Policy
This policy allows users to insert or update their own data:
3. Role-Based Access Control
This policy allows admin users to access all data:
4. API Key-Specific Permissions
This policy allows access based on specific API key permissions:
Best Practices
-
Consistency: Ensure policies treat session-based and API key authentication consistently where appropriate.
-
Granularity: Create separate policies for different operations (SELECT, INSERT, UPDATE, DELETE) rather than using catch-all policies.
-
Performance: Be mindful of policy complexity. Overly complex policies can impact query performance.
-
Testing: Thoroughly test your policies with both authentication methods to ensure they behave as expected.
-
Documentation: Maintain clear documentation of your RLS policies, including the reasoning behind each policy.
Advanced Techniques
Combining Multiple Conditions
You can create more complex policies by combining multiple conditions:
Using KeyHippo Metadata
Leverage KeyHippo’s metadata functions for more sophisticated policies:
Troubleshooting
If your policies aren’t working as expected:
- Verify KeyHippo Installation: Ensure the KeyHippo extension is properly installed and up to date.
- Check Permissions: Verify that the necessary permissions have been granted to the
authenticated
andanon
roles. - Test Individually: Test session-based and API key authentication separately to isolate issues.
- Use Supabase Logs: Utilize Supabase’s logging features to debug policy evaluation.
Next Steps
With your RLS policies in place, you can now:
- Implement API key authentication in your client application
- Test your policies with various authentication scenarios
- Monitor and analyze API key usage patterns
Manage API Keys
Learn how to effectively manage API keys throughout their lifecycle.