|
| 1 | +//! Operator-global intake for synthetic user-deletion requests. |
| 2 | +
|
| 3 | +use chrono::{DateTime, Utc}; |
| 4 | +use serde::Serialize; |
| 5 | +use sqlx::PgPool; |
| 6 | +use uuid::Uuid; |
| 7 | + |
| 8 | +use crate::{Db, DbError, Result}; |
| 9 | + |
| 10 | +/// A submitted demonstration request; no cleanup is authorized by this record. |
| 11 | +#[derive(Debug, Serialize, sqlx::FromRow)] |
| 12 | +pub struct EntityRequest { |
| 13 | + /// Stable request identifier. |
| 14 | + pub id: Uuid, |
| 15 | + /// Currently always `user`. |
| 16 | + pub entity_type: String, |
| 17 | + /// Synthetic `demo:` label, not a resolved account identity. |
| 18 | + pub target: String, |
| 19 | + /// Currently always `submitted`. |
| 20 | + pub status: String, |
| 21 | + /// Operator identity supplied at submission. |
| 22 | + pub requested_by: String, |
| 23 | + /// Optional explanation supplied at submission. |
| 24 | + pub reason: Option<String>, |
| 25 | + /// Time of the original submission. |
| 26 | + pub created_at: DateTime<Utc>, |
| 27 | + /// Time of the last change; identical resubmissions do not change it. |
| 28 | + pub updated_at: DateTime<Utc>, |
| 29 | +} |
| 30 | + |
| 31 | +/// Writer-database access to synthetic deletion requests. |
| 32 | +#[derive(Clone)] |
| 33 | +pub struct EntityDeletionStore { |
| 34 | + pool: PgPool, |
| 35 | +} |
| 36 | + |
| 37 | +impl Db { |
| 38 | + /// Use the writer pool for operator-global request intake and inspection. |
| 39 | + pub fn entity_deletion_store(&self) -> EntityDeletionStore { |
| 40 | + EntityDeletionStore { |
| 41 | + pool: self.pool().clone(), |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl EntityDeletionStore { |
| 47 | + /// Save a request or return an identical previous submission. |
| 48 | + /// |
| 49 | + /// A conflicting operator or reason returns an error without changing the |
| 50 | + /// existing request. Concurrent identical submissions converge on one row. |
| 51 | + pub async fn submit( |
| 52 | + &self, |
| 53 | + target: &str, |
| 54 | + requested_by: &str, |
| 55 | + reason: Option<&str>, |
| 56 | + ) -> Result<EntityRequest> { |
| 57 | + validate_submission(target, requested_by, reason)?; |
| 58 | + let mut tx = self.pool.begin().await?; |
| 59 | + sqlx::query( |
| 60 | + "INSERT INTO entity_deletion_requests (target, requested_by, reason) |
| 61 | + VALUES ($1, $2, $3) ON CONFLICT (entity_type, target) DO NOTHING", |
| 62 | + ) |
| 63 | + .bind(target) |
| 64 | + .bind(requested_by) |
| 65 | + .bind(reason) |
| 66 | + .execute(&mut *tx) |
| 67 | + .await?; |
| 68 | + let request: EntityRequest = sqlx::query_as( |
| 69 | + "SELECT * FROM entity_deletion_requests WHERE entity_type = 'user' AND target = $1", |
| 70 | + ) |
| 71 | + .bind(target) |
| 72 | + .fetch_one(&mut *tx) |
| 73 | + .await?; |
| 74 | + if request.requested_by != requested_by || request.reason.as_deref() != reason { |
| 75 | + return Err(DbError::DeletionSafety(format!( |
| 76 | + "target already has request {}; inspect it before resubmission", |
| 77 | + request.id |
| 78 | + ))); |
| 79 | + } |
| 80 | + tx.commit().await?; |
| 81 | + Ok(request) |
| 82 | + } |
| 83 | + |
| 84 | + /// Load a request from the authoritative writer database. |
| 85 | + pub async fn get(&self, id: Uuid) -> Result<EntityRequest> { |
| 86 | + sqlx::query_as("SELECT * FROM entity_deletion_requests WHERE id = $1") |
| 87 | + .bind(id) |
| 88 | + .fetch_optional(&self.pool) |
| 89 | + .await? |
| 90 | + .ok_or_else(|| DbError::NotFound(format!("entity deletion request {id}"))) |
| 91 | + } |
| 92 | + |
| 93 | + /// List up to 1,000 requests, newest first. |
| 94 | + pub async fn list(&self, limit: u16) -> Result<Vec<EntityRequest>> { |
| 95 | + Ok(sqlx::query_as( |
| 96 | + "SELECT * FROM entity_deletion_requests ORDER BY created_at DESC, id LIMIT $1", |
| 97 | + ) |
| 98 | + .bind(i64::from(limit.clamp(1, 1000))) |
| 99 | + .fetch_all(&self.pool) |
| 100 | + .await?) |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +fn validate_submission(target: &str, requested_by: &str, reason: Option<&str>) -> Result<()> { |
| 105 | + let slug = target.strip_prefix("demo:").unwrap_or_default(); |
| 106 | + if slug.is_empty() |
| 107 | + || slug.len() > 64 |
| 108 | + || !slug.as_bytes()[0].is_ascii_alphanumeric() |
| 109 | + || !slug |
| 110 | + .bytes() |
| 111 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-') |
| 112 | + { |
| 113 | + return Err(DbError::DeletionSafety( |
| 114 | + "target must be demo:<1..64 lowercase letters, digits, underscores or hyphens>".into(), |
| 115 | + )); |
| 116 | + } |
| 117 | + if requested_by.is_empty() || requested_by.len() > 256 || requested_by.trim() != requested_by { |
| 118 | + return Err(DbError::DeletionSafety( |
| 119 | + "operator identity must be 1..256 bytes without surrounding whitespace".into(), |
| 120 | + )); |
| 121 | + } |
| 122 | + if reason.is_some_and(|r| r.len() > 4096) { |
| 123 | + return Err(DbError::DeletionSafety("reason exceeds 4096 bytes".into())); |
| 124 | + } |
| 125 | + Ok(()) |
| 126 | +} |
| 127 | + |
| 128 | +#[cfg(test)] |
| 129 | +#[path = "entity_deletion_postgres_tests.rs"] |
| 130 | +mod postgres_tests; |
0 commit comments