//! Where accounts have been seen, for staff: one `user_ips` row per (user,
//! address) with first/last seen, a count and the last action. Recorded on
//! sign-in, registration (an invite redeemed), starting a topic or replying,
//! flagging, and app (API token) use; read only by staff pages; purged after
//! `IP_RETENTION_DAYS`. Best effort: a failure to record is logged and never
//! fails the request.
use std::net::IpAddr;
use chrono::{DateTime, Utc};
use sea_orm::{ConnectionTrait, DatabaseBackend, DatabaseConnection, FromQueryResult, Statement};
use uuid::Uuid;
use crate::client_ip::{canonical, Cidr};
/// What the address was seen doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Seen {
SignIn,
Register,
Post,
Flag,
/// App use. Coalesced: at most one update per address per
/// [`API_COALESCE_MINUTES`], so a busy app isn't a write per request.
Api,
}
pub const API_COALESCE_MINUTES: i64 = 10;
impl Seen {
pub fn as_str(self) -> &'static str {
match self {
Seen::SignIn => "sign_in",
Seen::Register => "register",
Seen::Post => "post",
Seen::Flag => "flag",
Seen::Api => "api",
}
}
}
/// Record that `user` was seen at `ip`.
pub async fn record<C: ConnectionTrait>(db: &C, user: Uuid, ip: Option<IpAddr>, what: Seen) {
let Some(ip) = ip.map(canonical) else { return };
let coalesce = if what == Seen::Api {
format!("WHERE user_ips.last_seen < now() - interval '{API_COALESCE_MINUTES} minutes'")
} else {
String::new()
};
let sql = format!(
"INSERT INTO user_ips (user_id, ip, first_seen, last_seen, count, last_action) \
VALUES ($1, $2, now(), now(), 1, $3) \
ON CONFLICT (user_id, ip) DO UPDATE SET last_seen = now(), count = user_ips.count + 1, \
last_action = EXCLUDED.last_action {coalesce}"
);
let stmt = Statement::from_sql_and_values(
DatabaseBackend::Postgres,
sql,
[user.into(), ip.to_string().into(), what.as_str().into()],
);
if let Err(e) = db.execute(stmt).await {
tracing::warn!(error = %e, "record client address");
}
}
/// Drop rows not seen for `days`, and flags' addresses older than that.
/// Returns the number of `user_ips` rows removed.
pub async fn purge<C: ConnectionTrait>(db: &C, days: i64) -> Result<u64, sea_orm::DbErr> {
let removed = db
.execute(Statement::from_sql_and_values(
DatabaseBackend::Postgres,
"DELETE FROM user_ips WHERE last_seen < now() - make_interval(days => $1)",
[(days as i32).into()],
))
.await?
.rows_affected();
db.execute(Statement::from_sql_and_values(
DatabaseBackend::Postgres,
"UPDATE post_flags SET ip = NULL WHERE ip IS NOT NULL AND created_at < now() - make_interval(days => $1)",
[(days as i32).into()],
))
.await?;
Ok(removed)
}
/// Purge now and then hourly, for as long as the server runs.
pub fn spawn_purger(db: std::sync::Arc<DatabaseConnection>, days: i64) {
tokio::spawn(async move {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(3600));
loop {
tick.tick().await;
match purge(db.as_ref(), days).await {
Ok(0) => {}
Ok(n) => tracing::info!(removed = n, days, "purged old client addresses"),
Err(e) => tracing::warn!(error = %e, "purge client addresses"),
}
}
});
}
#[derive(Debug, Clone, FromQueryResult, serde::Serialize)]
pub struct Sighting {
pub user_id: Uuid,
pub username: String,
pub ip: String,
pub first_seen: DateTime<Utc>,
pub last_seen: DateTime<Utc>,
pub count: i32,
pub last_action: String,
pub is_staff: bool,
pub silenced_until: Option<DateTime<Utc>>,
pub silenced_at: Option<DateTime<Utc>>,
pub suspended_at: Option<DateTime<Utc>>,
pub suspended_until: Option<DateTime<Utc>>,
}
const SIGHTING: &str = "SELECT ui.user_id, u.username, ui.ip, ui.first_seen, ui.last_seen, ui.count, ui.last_action, \
u.is_staff, u.silenced_until, u.silenced_at, u.suspended_at, u.suspended_until \
FROM user_ips ui JOIN users u ON u.id = ui.user_id";
/// One account's addresses, most recent first.
pub async fn of_user<C: ConnectionTrait>(db: &C, user: Uuid) -> Result<Vec<Sighting>, sea_orm::DbErr> {
Sighting::find_by_statement(Statement::from_sql_and_values(
DatabaseBackend::Postgres,
format!("{SIGHTING} WHERE ui.user_id = $1 ORDER BY ui.last_seen DESC LIMIT 200"),
[user.into()],
))
.all(db)
.await
}
/// Every account seen in `net` (a single address is a /32 or /128).
pub async fn in_network<C: ConnectionTrait>(db: &C, net: Cidr) -> Result<Vec<Sighting>, sea_orm::DbErr> {
Sighting::find_by_statement(Statement::from_sql_and_values(
DatabaseBackend::Postgres,
format!("{SIGHTING} WHERE ui.ip::inet <<= $1::inet ORDER BY ui.last_seen DESC LIMIT 500"),
[net.to_string().into()],
))
.all(db)
.await
}
#[derive(Debug, FromQueryResult)]
struct Count {
n: i64,
}
/// How many other accounts share any address with `user`.
pub async fn others_sharing<C: ConnectionTrait>(db: &C, user: Uuid) -> Result<i64, sea_orm::DbErr> {
Ok(Count::find_by_statement(Statement::from_sql_and_values(
DatabaseBackend::Postgres,
"SELECT count(DISTINCT o.user_id) AS n FROM user_ips mine \
JOIN user_ips o ON o.ip = mine.ip AND o.user_id <> mine.user_id WHERE mine.user_id = $1",
[user.into()],
))
.one(db)
.await?
.map(|c| c.n)
.unwrap_or(0))
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
5.6 KiB · text
History
a4db355