29 lines
1020 B
Rust
29 lines
1020 B
Rust
use anyhow::{Result, ensure};
|
|
use sqlx::{PgPool, Postgres, Transaction};
|
|
use uuid::Uuid;
|
|
|
|
pub async fn tenant_tx(pool: &PgPool, tenant: Uuid) -> Result<Transaction<'_, Postgres>> {
|
|
let mut tx = pool.begin().await?;
|
|
sqlx::query("SELECT set_config('app.tenant_id', $1, true)")
|
|
.bind(tenant.to_string())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
Ok(tx)
|
|
}
|
|
pub async fn verify_application_role(pool: &PgPool) -> Result<()> {
|
|
let unsafe_role: bool = sqlx::query_scalar(
|
|
"SELECT rolsuper OR rolbypassrls OR EXISTS (SELECT 1 FROM pg_tables WHERE schemaname='public' AND tableowner=current_user) FROM pg_roles WHERE rolname=current_user",
|
|
).fetch_one(pool).await?;
|
|
ensure!(
|
|
!unsafe_role,
|
|
"application database role must not own tables, bypass RLS or be superuser"
|
|
);
|
|
Ok(())
|
|
}
|
|
pub async fn migrate(url: &str) -> Result<()> {
|
|
let pool = PgPool::connect(url).await?;
|
|
sqlx::migrate!("../../migrations").run(&pool).await?;
|
|
pool.close().await;
|
|
Ok(())
|
|
}
|