Custom RLS Policies
Advanced Row Level Security with KeyHippo
KeyHippo extends Supabase’s Row Level Security (RLS) framework, allowing for sophisticated access control policies that incorporate both session-based and API key authentication. This guide explores advanced RLS policy creation using KeyHippo functions.
KeyHippo RLS Basics
At its core, KeyHippo introduces the auth.keyhippo_check()
function, which can be used in RLS policies alongside Supabase’s auth.uid()
. Here’s a basic example:
This policy grants access when the user is authenticated via a session token (auth.uid()
) or a valid API key associated with the resource owner (auth.keyhippo_check()
).
Advanced Policy Patterns
Role-Based Access Control (RBAC)
Combine KeyHippo with role checks for granular access control:
This policy allows access only if the user (authenticated via session or API key) has an ‘admin’ role.
Time-Based Policies
Implement time-sensitive access control:
This policy restricts access to business hours, regardless of the authentication method.
Resource-Specific Permissions
Create policies that check for specific permissions on resources:
This policy checks a project_permissions
table to determine if the user has the required permission for a specific project.
KeyHippo-Specific Functions
KeyHippo provides additional functions for advanced policy creation:
keyhippo.key_uid()
Retrieves the user ID associated with the current API key:
This policy allows access if the user is authenticated or if the API key used is specifically allowed for the resource.
keyhippo.get_api_key_metadata()
Fetches metadata about API keys, useful for policies based on key properties:
This policy grants access to premium resources only if the API key has ‘premium’ permission.
Best Practices
-
Principle of Least Privilege: Always grant the minimum necessary permissions in your policies.
-
Consistent Authentication Checks: Include both
auth.uid()
and KeyHippo checks in policies for comprehensive coverage. -
Performance Considerations: Complex policies can impact query performance. Test and optimize as necessary.
-
Regular Audits: Periodically review and update your RLS policies to ensure they align with your security requirements.
-
Documentation: Maintain clear documentation of your RLS policies, including the reasoning behind each policy.
Security Best Practices
Learn more about securing your Supabase application with KeyHippo.