What is Row-Level Security with OPA?
The database whispered secrets only some eyes could see. You decide who those eyes belong to. That is the core of Row-Level Security (RLS). And with Open Policy Agent (OPA), you can enforce it everywhere, consistently, without bending to the quirks of any single database vendor.
What is Row-Level Security with OPA?
Row-Level Security restricts queries so users only get rows they are allowed to see. Instead of hardcoding access rules deep in SQL or application code, OPA moves those rules into policies. Policies are written in Rego, OPA’s declarative language, and evaluated outside your app, making them flexible, testable, and portable.
Why use OPA for Row-Level Security?
- Centralized control: One policy source across multiple services.
- Database independence: Apply the same RLS logic to PostgreSQL, MySQL, or even APIs that front your data.
- Auditable rules: Every access decision is transparent and traceable.
- Dynamic conditions: Policies can adapt to user attributes, roles, tenancy, and time-based rules in real time.
How it works
- Extract query context – Send the user’s identity, roles, and requested resource to OPA.
- Evaluate policy – OPA runs the Rego rules to determine allowed rows.
- Filter data – The application or query builder applies the constraints returned from OPA.
- Return results – Only authorized rows reach the user.
Example Rego for Row-Level Security:
package rls
default allow = false
allow {
input.user.role == "manager"
}
allow {
input.user.id == data.rows[_].owner_id
}
This example allows managers to see all rows, while other users see only rows they own. Integrating with your query logic ensures the filter happens before data leaves the database.
Best practices for OPA Row-Level Security
- Keep policies small and modular for easier testing.
- Use OPA’s built-in test framework to validate rules before deployment.
- Cache policy decisions when possible to reduce evaluation time for high-volume queries.
- Always consider edge cases: empty datasets, deleted users, or stale role assignments.
Row-Level Security is more than a database feature. With OPA, it becomes a service—consistent, scalable, and open. Stop scattering access logic across multiple layers. Put the rules in one place. Enforce them everywhere.
See it live with a working demo at hoop.dev and deploy row-level security in minutes.