A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(admin): add Operator Pass client and ACL, drop ACL tests
Hampus41b4dd74d43d
diff --git a/fluxer_admin/Cargo.toml b/fluxer_admin/Cargo.tomlindex abd6eeabd..62ec0bc02 100644--- a/fluxer_admin/Cargo.toml+++ b/fluxer_admin/Cargo.toml@@ -8,7 +8,7 @@ build = "build.rs"[dependencies]anyhow = "1.0.104"-axum = { version = "0.8.9", features = ["macros"] }+axum = { version = "0.8.9", features = ["macros", "multipart"] }base64 = "0.23.1"chrono = { version = "0.4", default-features = false, features = ["serde"] }fluxer_common = { path = "../fluxer_common" }@@ -22,7 +22,6 @@ serde_json = "1.0.151"sha2 = "0.11.0"time = { version = "0.3.55", features = ["formatting", "parsing"] }tokio = { version = "1.53.1", features = ["macros", "net", "rt-multi-thread", "signal"] }-tower = { version = "0.5.3", features = ["util"] }tower-http = { version = "0.7.1", features = ["compression-gzip", "trace"] }tracing = "0.1.44"tracing-subscriber = "0.3.23"diff --git a/fluxer_admin/src/acl.rs b/fluxer_admin/src/acl.rsindex d2735065d..e3c32abd2 100644--- a/fluxer_admin/src/acl.rs+++ b/fluxer_admin/src/acl.rs@@ -72,6 +72,7 @@ pub const MESSAGE_DELETE_ALL: &str = "message:delete_all";pub const MESSAGE_DELETE: &str = "message:delete";pub const MESSAGE_LOOKUP: &str = "message:lookup";pub const MESSAGE_SHRED: &str = "message:shred";+pub const OPERATOR_PASS_WAITLIST_STATS: &str = "operator_pass:waitlist_stats";pub const REGISTRATION_REVIEW: &str = "registration:review";pub const REPORT_DELETE: &str = "report:delete";pub const REPORT_RESOLVE: &str = "report:resolve";@@ -182,6 +183,7 @@ pub const ALL_ACLS: &[&str] = &[MESSAGE_DELETE,MESSAGE_LOOKUP,MESSAGE_SHRED,+ OPERATOR_PASS_WAITLIST_STATS,REGISTRATION_REVIEW,REPORT_DELETE,REPORT_RESOLVE,@@ -238,62 +240,3 @@ pub fn has_any_permission(admin_acls: &[String], required: &[&str]) -> bool {fn acl_key_alias(acl: &str) -> String {acl.replace(':', "_").to_ascii_uppercase()}--#[cfg(test)]-mod tests {- use super::*;-- fn acls(items: &[&str]) -> Vec<String> {- items.iter().map(|s| s.to_string()).collect()- }-- #[test]- fn has_permission_exact_match() {- assert!(has_permission(&acls(&[USER_LOOKUP]), USER_LOOKUP));- }-- #[test]- fn has_permission_wildcard() {- assert!(has_permission(&acls(&[WILDCARD]), USER_LOOKUP));- assert!(has_permission(&acls(&[WILDCARD]), GUILD_DELETE));- }-- #[test]- fn has_permission_accepts_constant_key_aliases() {- assert!(has_permission(- &acls(&["USER_REMOVE_RELATIONSHIP"]),- USER_REMOVE_RELATIONSHIP- ));- assert!(has_permission(&acls(&["WILDCARD"]), GUILD_DELETE));- }-- #[test]- fn has_permission_no_match() {- assert!(!has_permission(&acls(&[USER_LOOKUP]), GUILD_LOOKUP));- assert!(!has_permission(&acls(&[]), USER_LOOKUP));- }-- #[test]- fn has_any_permission_any_match() {- let user_acls = acls(&[USER_LOOKUP, GUILD_LOOKUP]);- assert!(has_any_permission(- &user_acls,- &[GUILD_DELETE, GUILD_LOOKUP]- ));- }-- #[test]- fn has_any_permission_empty_required() {- assert!(has_any_permission(&acls(&[USER_LOOKUP]), &[]));- assert!(has_any_permission(&acls(&[]), &[]));- }-- #[test]- fn has_any_permission_none_match() {- let user_acls = acls(&[USER_LOOKUP]);- assert!(!has_any_permission(- &user_acls,- &[GUILD_DELETE, GUILD_LOOKUP]- ));- }-}diff --git a/fluxer_admin/src/api/mod.rs b/fluxer_admin/src/api/mod.rsindex 887f6b4ca..eb07f81f5 100644--- a/fluxer_admin/src/api/mod.rs+++ b/fluxer_admin/src/api/mod.rs@@ -20,6 +20,8 @@ pub mod instance_config;pub mod jobs;pub mod limit_config;pub mod messages;+pub mod operator_pass;+pub mod payment_disputes;pub mod reports;pub mod search;pub mod system;diff --git a/fluxer_admin/src/api/operator_pass.rs b/fluxer_admin/src/api/operator_pass.rsnew file mode 100644index 000000000..95a8fc839--- /dev/null+++ b/fluxer_admin/src/api/operator_pass.rs@@ -0,0 +1,446 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++use super::client::{AdminApiClient, ApiError, ApiResult};+use super::generated::snowflake;+use super::generated::types::{+ AdminOperatorPassReleaseFileResponse, AdminOperatorPassReleasePreviewResponse,+ AdminOperatorPassReleasePublishRequest, AdminOperatorPassReleasePublishRequestTag,+ AdminOperatorPassUserResponse, AdminOperatorPassWaitlistFollowupTextsResponse,+ AdminOperatorPassWaitlistStatsResponse, AdminOperatorPassWallAsOfResponse,+ AdminOperatorPassWallBulkResponse, AdminOperatorPassWallDecisionResponse,+ AdminOperatorPassWallEntryResponse, AdminOperatorPassWallQueueResponse,+ AdminOperatorPassWallRevisionResponse, AdminOperatorPassWallStateResponse,+ AdminOperatorPassWithdrawRequest, AdminOperatorPassWithdrawRequestName,+ AdminOperatorPassWithdrawalChannelSchema, OperatorPassPurchaseResponse,+ OperatorPassWallDeclineReasonSchema, SnowflakeStringType,+ WithdrawAdminOperatorPassPurchasePurchaseId,+};+use chrono::{DateTime, Utc};+use reqwest::Method;+use serde::{Deserialize, Serialize};+use serde_json::json;++#[derive(Serialize)]+pub struct WallDecision<'a> {+ pub reason: OperatorPassWallDeclineReasonSchema,+ pub note: &'a str,+ pub username_declined: bool,+}++#[derive(Serialize)]+#[serde(tag = "action", rename_all = "snake_case")]+pub enum WallBulkAction<'a> {+ Approve,+ Decline {+ reason: OperatorPassWallDeclineReasonSchema,+ note: &'a str,+ },+}++#[derive(Serialize)]+struct WallRevision<'a> {+ user_id: &'a str,+ revision_id: &'a str,+}++#[derive(Serialize)]+struct WallBulkRequest<'a> {+ #[serde(flatten)]+ action: &'a WallBulkAction<'a>,+ revisions: Vec<WallRevision<'a>>,+}++pub struct PerkRemoval<'a> {+ pub rule: &'a str,+ pub facts: &'a str,+ pub serious: bool,+ pub duration_days: Option<u32>,+}++pub struct PassWithdrawal<'a> {+ pub name: &'a str,+ pub received_at: DateTime<Utc>,+ pub channel: &'a str,+}++#[derive(Deserialize, Clone, Debug)]+pub struct WallTimelineEvent {+ pub occurred_at: DateTime<Utc>,+ pub kind: String,+ #[serde(default)]+ pub name: Option<String>,+ #[serde(default)]+ pub reason: Option<String>,+ #[serde(default)]+ pub cause: Option<String>,+ #[serde(default)]+ pub purchase_id: Option<String>,+ #[serde(default)]+ pub release_year: Option<i64>,+ #[serde(default)]+ pub release_tag: Option<String>,+ #[serde(default)]+ pub actor_id: Option<String>,+ #[serde(default)]+ pub pass_count: Option<i64>,+}++#[derive(Deserialize, Clone, Debug)]+pub struct WallTimeline {+ pub entry: Option<AdminOperatorPassWallEntryResponse>,+ pub revisions: Vec<AdminOperatorPassWallRevisionResponse>,+ pub decisions: Vec<AdminOperatorPassWallDecisionResponse>,+ pub events: Vec<WallTimelineEvent>,+}++fn parse<T, E: std::fmt::Display>(value: Result<T, E>) -> ApiResult<T> {+ value.map_err(|e| ApiError::Parse(e.to_string()))+}++impl AdminApiClient {+ pub async fn get_operator_pass_waitlist_stats(+ &self,+ ) -> ApiResult<AdminOperatorPassWaitlistStatsResponse> {+ let response = self+ .generated()+ .get_admin_operator_pass_waitlist_stats()+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn list_operator_pass_waitlist_followup_texts(+ &self,+ ) -> ApiResult<AdminOperatorPassWaitlistFollowupTextsResponse> {+ let response = self+ .generated()+ .list_admin_operator_pass_waitlist_followup_texts()+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn get_user_operator_pass(+ &self,+ user_id: &str,+ ) -> ApiResult<AdminOperatorPassUserResponse> {+ let response = self+ .generated()+ .get_admin_user_operator_pass(&snowflake(user_id))+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn list_operator_pass_wall_review_queue(+ &self,+ ) -> ApiResult<AdminOperatorPassWallQueueResponse> {+ let response = self+ .generated()+ .list_admin_operator_pass_wall_review_queue()+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn approve_operator_pass_wall_revision(+ &self,+ user_id: &str,+ revision_id: &str,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/revisions/{revision_id}/approve"),+ None::<&()>,+ None,+ )+ .await+ }++ pub async fn decline_operator_pass_wall_revision(+ &self,+ user_id: &str,+ revision_id: &str,+ decision: &WallDecision<'_>,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/revisions/{revision_id}/decline"),+ Some(decision),+ None,+ )+ .await+ }++ pub async fn revert_operator_pass_wall_revision(+ &self,+ user_id: &str,+ revision_id: &str,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/revisions/{revision_id}/revert"),+ None::<&()>,+ None,+ )+ .await+ }++ pub async fn force_operator_pass_wall_fallback(+ &self,+ user_id: &str,+ decision: &WallDecision<'_>,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/force-fallback"),+ Some(decision),+ None,+ )+ .await+ }++ pub async fn set_operator_pass_wall_business_listing(+ &self,+ user_id: &str,+ name: &str,+ logo_base64: &str,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::PUT,+ &format!("/admin/users/{user_id}/operator-pass/wall/business"),+ Some(&json!({"name": name, "logo": logo_base64})),+ None,+ )+ .await+ }++ pub async fn set_operator_pass_wall_hidden(+ &self,+ user_id: &str,+ hidden: bool,+ reason: Option<&str>,+ note: Option<&str>,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/hide"),+ Some(&json!({"hidden": hidden, "reason": reason, "note": note})),+ None,+ )+ .await+ }++ pub async fn set_operator_pass_wall_legal_hold(+ &self,+ user_id: &str,+ held: bool,+ ) -> ApiResult<AdminOperatorPassWallEntryResponse> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/wall/legal-hold"),+ Some(&json!({"held": held})),+ None,+ )+ .await+ }++ pub async fn send_operator_pass_removal_notice(+ &self,+ user_id: &str,+ rule: &str,+ facts: &str,+ ) -> ApiResult<serde_json::Value> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/removal-notice"),+ Some(&json!({"rule": rule, "facts": facts})),+ None,+ )+ .await+ }++ pub async fn remove_operator_pass_perks(+ &self,+ user_id: &str,+ removal: &PerkRemoval<'_>,+ ) -> ApiResult<serde_json::Value> {+ self.send(+ Method::POST,+ &format!("/admin/users/{user_id}/operator-pass/removal"),+ Some(&json!({+ "rule": removal.rule,+ "facts": removal.facts,+ "automated": false,+ "serious": removal.serious,+ "duration_days": removal.duration_days,+ "notify_user": true,+ })),+ None,+ )+ .await+ }++ pub async fn restore_operator_pass_perks(&self, user_id: &str) -> ApiResult<()> {+ self.send_void(+ Method::DELETE,+ &format!("/admin/users/{user_id}/operator-pass/removal"),+ None::<&()>,+ None,+ )+ .await+ }++ pub async fn withdraw_operator_pass_purchase(+ &self,+ purchase_id: &str,+ withdrawal: &PassWithdrawal<'_>,+ ) -> ApiResult<OperatorPassPurchaseResponse> {+ let purchase_id = parse(WithdrawAdminOperatorPassPurchasePurchaseId::try_from(+ purchase_id,+ ))?;+ let body = AdminOperatorPassWithdrawRequest {+ channel: parse(+ withdrawal+ .channel+ .parse::<AdminOperatorPassWithdrawalChannelSchema>(),+ )?,+ name: parse(AdminOperatorPassWithdrawRequestName::try_from(+ withdrawal.name,+ ))?,+ received_at: withdrawal.received_at,+ };+ let response = self+ .generated()+ .withdraw_admin_operator_pass_purchase(&purchase_id, &body)+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn bulk_operator_pass_wall_revisions(+ &self,+ action: &WallBulkAction<'_>,+ revisions: &[(String, String)],+ ) -> ApiResult<AdminOperatorPassWallBulkResponse> {+ let body = WallBulkRequest {+ action,+ revisions: revisions+ .iter()+ .map(|(user_id, revision_id)| WallRevision {+ user_id,+ revision_id,+ })+ .collect(),+ };+ self.send(+ Method::POST,+ "/admin/operator-pass/wall/bulk",+ Some(&body),+ None,+ )+ .await+ }++ pub async fn get_operator_pass_wall_timeline(&self, user_id: &str) -> ApiResult<WallTimeline> {+ self.get(+ &format!("/admin/users/{user_id}/operator-pass/wall/timeline"),+ None,+ )+ .await+ }++ pub async fn get_operator_pass_wall_avatar(+ &self,+ user_id: &str,+ sha256: &str,+ ) -> ApiResult<(String, Vec<u8>)> {+ self.get_bytes(&format!(+ "/admin/users/{user_id}/operator-pass/wall/avatars/{sha256}"+ ))+ .await+ }++ pub async fn get_operator_pass_wall_as_of(+ &self,+ at: &str,+ ) -> ApiResult<AdminOperatorPassWallAsOfResponse> {+ self.get("/admin/operator-pass/wall/as-of", Some(&[("at", at)]))+ .await+ }++ pub async fn get_operator_pass_wall_state(+ &self,+ ) -> ApiResult<AdminOperatorPassWallStateResponse> {+ self.get("/admin/operator-pass/wall/state", None).await+ }++ pub async fn set_operator_pass_wall_frozen(+ &self,+ frozen: bool,+ ) -> ApiResult<AdminOperatorPassWallStateResponse> {+ self.send(+ Method::POST,+ "/admin/operator-pass/wall/freeze",+ Some(&json!({"frozen": frozen})),+ None,+ )+ .await+ }++ pub async fn republish_operator_pass_wall(+ &self,+ ) -> ApiResult<AdminOperatorPassWallStateResponse> {+ self.send(+ Method::POST,+ "/admin/operator-pass/wall/republish",+ None::<&()>,+ None,+ )+ .await+ }++ pub async fn get_operator_pass_release(+ &self,+ year: i64,+ ) -> ApiResult<AdminOperatorPassReleasePreviewResponse> {+ let response = self+ .generated()+ .get_admin_operator_pass_release(year)+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn publish_operator_pass_release(+ &self,+ year: i64,+ tag: &str,+ released_at: DateTime<Utc>,+ ) -> ApiResult<AdminOperatorPassReleaseFileResponse> {+ let body = AdminOperatorPassReleasePublishRequest {+ released_at,+ tag: parse(AdminOperatorPassReleasePublishRequestTag::try_from(tag))?,+ };+ let response = self+ .generated()+ .publish_admin_operator_pass_release(year, &body)+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }++ pub async fn erase_operator_pass_release_name(+ &self,+ year: i64,+ user_id: &str,+ ) -> ApiResult<AdminOperatorPassReleaseFileResponse> {+ let user_id = parse(SnowflakeStringType::try_from(user_id))?;+ let response = self+ .generated()+ .erase_admin_operator_pass_release_name(year, &user_id)+ .await+ .map_err(|e| self.generated_error(e))?;+ Ok(response.into_inner())+ }+}diff --git a/fluxer_admin/src/utils/timestamps.rs b/fluxer_admin/src/utils/timestamps.rsindex 4de900d24..98e43b5c1 100644--- a/fluxer_admin/src/utils/timestamps.rs+++ b/fluxer_admin/src/utils/timestamps.rs@@ -8,7 +8,7 @@ pub fn snowflake_to_timestamp_ms(snowflake: &str) -> Option<u64> {Some(timestamp_ms)}-pub fn format_admin_timestamp(iso: &str) -> String {+fn parse_admin_timestamp(iso: &str) -> Option<time::OffsetDateTime> {time::OffsetDateTime::parse(iso, &time::format_description::well_known::Rfc3339).or_else(|_| {time::OffsetDateTime::parse(@@ -16,12 +16,30 @@ pub fn format_admin_timestamp(iso: &str) -> String {&time::format_description::well_known::Iso8601::DEFAULT,)})- .map_or_else(|_| iso.to_owned(), format_admin_datetime)+ .ok()}-fn format_admin_datetime(dt: time::OffsetDateTime) -> String {- let dt = dt.to_offset(time::UtcOffset::UTC);- let month = match dt.month() {+pub fn format_admin_timestamp(iso: &str) -> String {+ parse_admin_timestamp(iso).map_or_else(|| iso.to_owned(), format_admin_datetime)+}++pub fn format_admin_date(iso: &str) -> String {+ parse_admin_timestamp(iso).map_or_else(+ || iso.to_owned(),+ |dt| {+ let dt = dt.to_offset(time::UtcOffset::UTC);+ format!(+ "{} {}, {}",+ month_abbreviation(dt.month()),+ dt.day(),+ dt.year()+ )+ },+ )+}++fn month_abbreviation(month: time::Month) -> &'static str {+ match month {time::Month::January => "Jan",time::Month::February => "Feb",time::Month::March => "Mar",@@ -34,7 +52,12 @@ fn format_admin_datetime(dt: time::OffsetDateTime) -> String {time::Month::October => "Oct",time::Month::November => "Nov",time::Month::December => "Dec",- };+ }+}++fn format_admin_datetime(dt: time::OffsetDateTime) -> String {+ let dt = dt.to_offset(time::UtcOffset::UTC);+ let month = month_abbreviation(dt.month());let day = dt.day();let year = dt.year();let hour_12 = match dt.hour() {