use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::PolicyBuildError;
use crate::schema::{Policy, PolicyCommand};
#[derive(Debug, Clone)]
pub struct PolicyBuilder {
name: Option<String>,
table: Option<String>,
schema: Option<String>,
command: Option<PolicyCommand>,
role: Option<String>,
expression: Option<String>,
check_expression: Option<String>,
permissive: bool,
}
impl PolicyBuilder {
pub fn new() -> Self {
Self {
name: None,
table: None,
schema: None,
command: None,
role: None,
expression: None,
check_expression: None,
permissive: true, }
}
pub fn for_table(table: impl Into<String>) -> Self {
Self::new().table(table)
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn table(mut self, table: impl Into<String>) -> Self {
self.table = Some(table.into());
self
}
pub fn schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn allow_all(mut self) -> Self {
self.command = Some(PolicyCommand::All);
self
}
pub fn allow_select(mut self) -> Self {
self.command = Some(PolicyCommand::Select);
self
}
pub fn allow_insert(mut self) -> Self {
self.command = Some(PolicyCommand::Insert);
self
}
pub fn allow_update(mut self) -> Self {
self.command = Some(PolicyCommand::Update);
self
}
pub fn allow_delete(mut self) -> Self {
self.command = Some(PolicyCommand::Delete);
self
}
pub fn command(mut self, command: PolicyCommand) -> Self {
self.command = Some(command);
self
}
pub fn for_role(mut self, role: impl Into<String>) -> Self {
self.role = Some(role.into());
self
}
pub fn using_expression(mut self, expression: impl Into<String>) -> Self {
self.expression = Some(expression.into());
self
}
pub fn with_check(mut self, expression: impl Into<String>) -> Self {
self.check_expression = Some(expression.into());
self
}
pub fn restrictive(mut self) -> Self {
self.permissive = false;
self
}
pub fn permissive(mut self) -> Self {
self.permissive = true;
self
}
pub fn jwt_user_isolation(self) -> Self {
self.using_expression("id = current_setting('jwt.claims.user_id')::UUID")
}
pub fn tenant_isolation(self, tenant_column: impl Into<String>) -> Self {
let tenant_col = tenant_column.into();
self.using_expression(&format!(
"{} = current_setting('jwt.claims.tenant_id')::UUID",
tenant_col
))
}
pub fn admin_bypass(self) -> Self {
self.using_expression("has_role(current_user, 'admin')")
}
pub fn user_or_admin(self) -> Self {
self.using_expression(
"id = current_setting('jwt.claims.user_id')::UUID OR has_role(current_user, 'admin')",
)
}
}
impl SchemaBuilder for PolicyBuilder {
type Output = Policy;
type Error = PolicyBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
let name = self.name.ok_or(PolicyBuildError::MissingName)?;
let table = self.table.ok_or(PolicyBuildError::MissingTable)?;
let command = self.command.ok_or(PolicyBuildError::MissingCommand)?;
let expression = self.expression.ok_or(PolicyBuildError::MissingExpression)?;
Ok(Policy {
name,
table,
schema: self.schema,
command,
role: self.role,
expression,
check_expression: self.check_expression,
permissive: self.permissive,
})
}
}
impl ValidatableBuilder for PolicyBuilder {
fn is_valid(&self) -> bool {
self.name.is_some()
&& self.table.is_some()
&& self.command.is_some()
&& self.expression.is_some()
&& self
.expression
.as_ref()
.map_or(false, |expr| !expr.trim().is_empty())
&& self
.check_expression
.as_ref()
.map_or(true, |check| !check.trim().is_empty())
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.name.is_none() {
errors.push("Policy name is required".to_string());
}
if self.table.is_none() {
errors.push("Table name is required".to_string());
}
if self.command.is_none() {
errors.push("Policy command is required".to_string());
}
if self.expression.is_none() {
errors.push("USING expression is required".to_string());
} else if let Some(ref expr) = self.expression {
if expr.trim().is_empty() {
errors.push("USING expression cannot be empty".to_string());
}
}
if let Some(ref check) = self.check_expression {
if check.trim().is_empty() {
errors.push("WITH CHECK expression cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for PolicyBuilder {
fn when<F>(mut self, condition: bool, config_fn: F) -> Self
where
F: FnOnce(&mut Self),
Self: Sized,
{
if condition {
config_fn(&mut self);
}
self
}
fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
where
F: FnOnce(&mut Self),
G: FnOnce(&mut Self),
Self: Sized,
{
if condition {
if_true(&mut self);
} else {
if_false(&mut self);
}
self
}
}
impl InspectableBuilder for PolicyBuilder {
fn debug_info(&self) -> String {
format!(
"PolicyBuilder {{ name: {:?}, table: {:?}, command: {:?}, role: {:?}, permissive: {} }}",
self.name, self.table, self.command, self.role, self.permissive
)
}
fn summary(&self) -> String {
let mut parts = vec![format!(
"policy '{}'",
self.name.as_deref().unwrap_or("unnamed")
)];
if let Some(ref table) = self.table {
parts.push(format!("for table '{}'", table));
}
if let Some(ref command) = self.command {
parts.push(format!("command: {:?}", command));
}
if let Some(ref role) = self.role {
parts.push(format!("role: '{}'", role));
}
parts.push(format!("permissive: {}", self.permissive));
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_policy_builder_basic() {
let policy = PolicyBuilder::for_table("users")
.name("user_access_policy")
.allow_all()
.for_role("authenticated_user")
.using_expression("id = current_setting('jwt.claims.user_id')::UUID")
.build()
.unwrap();
assert_eq!(policy.name, "user_access_policy");
assert_eq!(policy.table, "users");
assert_eq!(policy.command, PolicyCommand::All);
assert_eq!(policy.role, Some("authenticated_user".to_string()));
assert_eq!(
policy.expression,
"id = current_setting('jwt.claims.user_id')::UUID"
);
assert!(policy.permissive);
}
#[test]
fn test_policy_builder_jwt_isolation() {
let policy = PolicyBuilder::for_table("posts")
.name("user_posts_policy")
.allow_select()
.jwt_user_isolation()
.build()
.unwrap();
assert_eq!(
policy.expression,
"id = current_setting('jwt.claims.user_id')::UUID"
);
}
#[test]
fn test_policy_builder_tenant_isolation() {
let policy = PolicyBuilder::for_table("documents")
.name("tenant_docs_policy")
.allow_all()
.tenant_isolation("tenant_id")
.build()
.unwrap();
assert_eq!(
policy.expression,
"tenant_id = current_setting('jwt.claims.tenant_id')::UUID"
);
}
#[test]
fn test_policy_builder_restrictive() {
let policy = PolicyBuilder::for_table("sensitive_data")
.name("restrictive_policy")
.allow_select()
.using_expression("has_role(current_user, 'admin')")
.restrictive()
.build()
.unwrap();
assert!(!policy.permissive);
}
#[test]
fn test_policy_builder_validation() {
let result = PolicyBuilder::for_table("users")
.allow_all()
.using_expression("true")
.build();
assert!(matches!(result, Err(PolicyBuildError::MissingName)));
let result = PolicyBuilder::new()
.name("test_policy")
.allow_all()
.using_expression("true")
.build();
assert!(matches!(result, Err(PolicyBuildError::MissingTable)));
let result = PolicyBuilder::for_table("users")
.name("test_policy")
.using_expression("true")
.build();
assert!(matches!(result, Err(PolicyBuildError::MissingCommand)));
let result = PolicyBuilder::for_table("users")
.name("test_policy")
.allow_all()
.build();
assert!(matches!(result, Err(PolicyBuildError::MissingExpression)));
}
}