Files
buzz/crates/buzz-db/src/error.rs
Will Pfleger 792a9ce563 feat(relay): list and revoke invite links (#9680)
Stack: this PR → #9690

## What this does

Adds listing and revocation for v2 invite links, and makes every reader
of an invite's expiry accept a missing value.

- **`GET /api/invites?limit=&before=`** lists the community's v2
invites, newest first: id, creator, created/expiry/revoked times, uses
and a computed `status` (`active`, `revoked`, `expired`, `exhausted`).
Owner/admin only. The NIP-98 signature covers the full URL including the
query. `limit` defaults to 50 (max 200). `next_before` is an opaque
cursor holding the last row's `created_at` (microseconds) and id, so
paging doesn't depend on that row still existing.
- **`POST /api/invites/revoke`** takes exactly one of `{"id": "<uuid>"}`
or `{"code": "v2...."}`. The code is hashed and looked up only inside
the request's community. v1 and malformed codes get `400
invite_not_revocable`; an invite not in the community gets 404. Revoking
twice returns the first `revoked_at`. Members who already joined stay.
- **Authorization.** Mint, list and revoke share one HTTP admission
helper (tenant bind → NIP-98 via NIP-FI → replay → membership/ban →
NIP-OA owner link → role gate). Revoke's final decision is made in the
write transaction, in the same order as mint: admission lock → actor's
role row `FOR SHARE` → restriction check → invite row `FOR UPDATE`.
Owners and admins can revoke any invite; any other member only one they
created. A removed or restricted actor is refused. Mint now uses the
same role-lock helper.
- **Mint response** now includes `invite_id`.
- **Nullable expiry readers.** Claim, list, the mint response and
operator mint treat a missing `expires_at` as "never expires". The
column is still `NOT NULL` here.
- **Secrets.** No list/revoke response or access-log line contains a
code or its hash; request errors are fixed strings that never echo
input. Revoke logs only `invite_id`. A revoke the database refuses is
logged as denied with its reason.

## Deploy order

A follow-up PR adds links that never expire (`expires_at` nullable).
**It depends on this PR being deployed everywhere first**, so every
serving relay can read a missing expiry before one is written.

## Tests

- DB (`relay_invite/manage_postgres_tests.rs`): revoke by code targets
exactly one of two near-identical invites, idempotent revoke, community
scoping, creator demoted to member can revoke theirs, a member who
didn't create it is refused, a removed creator is refused, a restricted
admin is refused, a demotion holding the role row or a restriction
holding the admission lock makes revoke wait and then refuse with the
row unchanged, a paused claim and a revoke serialize with the member
kept, revoke is refused while the community is quiescing, paging
survives deleting the cursor row, and a row with no expiry is listed,
claimed, kept by the reaper and revocable (on a scratch database with
`NOT NULL` dropped).
- Relay (`invites/postgres_tests/manage_tests.rs`): list/revoke by id
and code end to end, no code or hash in responses, member/non-member
refusals, bad selectors, other-community lookups, query-string signature
binding, malformed requests not echoing a code in responses or access
logs, refused revokes logged as denied, and replayed list/revoke
requests refused.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-20 15:48:36 -05:00

232 lines
8.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Database error types.
use thiserror::Error;
/// Errors produced by database operations.
#[derive(Debug, Error)]
pub enum DbError {
/// Media authorization could not reserve capacity within its bounded wait.
#[error("media authorization capacity exceeded")]
MediaAuthorizationCapacity,
/// A SQLx driver-level error.
#[error("database error: {0}")]
Sqlx(#[from] sqlx::Error),
/// A SQLx migration error.
#[error("migration error: {0}")]
Migrate(#[from] sqlx::migrate::MigrateError),
/// Attempted to store an AUTH event (kind 22242), which is forbidden.
#[error("AUTH events (kind 22242) must not be stored")]
AuthEventRejected,
/// Attempted to store an ephemeral event (kinds 20000–29999), which is forbidden.
#[error("ephemeral events (kind {0}) must not be stored")]
EphemeralEventRejected(u16),
/// The requested channel does not exist.
#[error("channel not found: {0}")]
ChannelNotFound(uuid::Uuid),
/// Another listed open channel in the community already has this name
/// (the `idx_channels_listed_name` index, migration 0083).
#[error("an open channel named \"{0}\" already exists")]
ChannelNameTaken(String),
/// The requested member is not in the channel.
#[error("member not found in channel {0}")]
MemberNotFound(uuid::Uuid),
/// A generic not-found error.
#[error("not found: {0}")]
NotFound(String),
/// The caller lacks permission for the requested operation.
#[error("access denied: {0}")]
AccessDenied(String),
/// Required initial policy cannot be created without issuer bindings.
#[error("required community creation needs NIP-FI issuer bindings")]
NipFiBindingRequired,
/// Invitation admission or minting was denied by authoritative restrictions.
#[error("invitation principal is restricted")]
InviteRestricted,
/// The invitation issuer is not an owner or admin at mint time.
#[error("invitation issuer is not an owner or admin")]
InviteIssuerNotAdmin,
/// The revoker is neither an owner or admin nor the invite's creator.
#[error("invite revoker is not an owner, admin or the invite's creator")]
InviteRevokeForbidden,
/// A verified invitation owner conflicts with the recorded owner.
#[error("invitation owner does not match the recorded owner")]
InviteOwnerMismatch,
/// JSON serialization or deserialization failed.
#[error("serialization error: {0}")]
Serde(#[from] serde_json::Error),
/// A value in the database is malformed or unexpected.
#[error("invalid data: {0}")]
InvalidData(String),
/// A partition the catalog audit had already listed was dropped before the
/// audit finished. A fresh snapshot sees a consistent catalog.
#[error("partition catalog changed mid-audit: {0}")]
PartitionDroppedMidAudit(String),
/// A serving write admitted before the lifecycle transition is still live.
/// This is an ordinary retryable drain condition, not a safety violation.
#[error(
"community {community_id} still has {active_count} active serving write lease(s): {operations:?}"
)]
ServingWritesNotDrained {
/// Community whose lifecycle transition must retry.
community_id: uuid::Uuid,
/// Number of currently unexpired serving-write leases.
active_count: i64,
/// Distinct operation categories holding those leases.
operations: Vec<String>,
},
/// A deletion safety invariant is structurally violated and requires
/// operator/code remediation rather than blind retry.
#[error("deletion safety error: {0}")]
DeletionSafety(String),
/// An artifact sync page exceeds its resource limit.
#[error("artifact sync limit exceeded")]
ArtifactSyncLimit,
/// A complete read-state snapshot exceeds its bounded resource budget.
#[error("read-state snapshot exceeds event or byte limit")]
ReadStateSnapshotTooLarge,
/// A complete membership snapshot exceeds its bounded resource budget.
#[error("membership snapshot exceeds channel or byte limit")]
MembershipSnapshotTooLarge,
/// A complete thread window exceeds its request-wide work allowance.
#[error("thread window exceeds {0} budget")]
ThreadWindowBudgetExceeded(&'static str),
/// A stored timestamp value could not be interpreted.
#[error("invalid timestamp: {0}")]
InvalidTimestamp(i64),
/// A channel event is too old for replica-fence completeness. Retrying the
/// same signed event cannot make its timestamp newer. Like the mixed-version
/// trigger's SQLx error, this remains a database error at the relay boundary
/// (WS OK false / HTTP 500), rather than a different ingest rejection class.
#[error("database error: events.created_at is below the replica-fence floor")]
CreatedAtFloorRejected,
/// A roster mutation would remove the last effective relay Operator,
/// leaving no one able to administer the deployment through the API.
/// The transaction is rolled back and the caller must add a replacement
/// Operator before demoting or deleting the current one.
#[error("operation would remove the last relay operator")]
LastOperator,
}
impl DbError {
/// Whether Postgres cancelled the statement (SQLSTATE 57014:
/// `statement_timeout` or an explicit cancel).
///
/// Replica-routed reads surface a cancel instead of re-running on the
/// writer. Usually the cancel means expensive work that the writer would
/// only repeat at the primary's cost. It can also mean the replica waited
/// on a lock that only it holds (a replayed `ACCESS EXCLUSIVE` from
/// primary DDL), when the writer would have answered quickly. That miss is
/// the accepted price of keeping runaway reads off the primary. Per-call
/// routed reads record it as the `statement_cancelled` route reason;
/// `ReadSession` reads return it to the relay, which logs the failed read.
pub fn is_statement_cancelled(&self) -> bool {
matches!(
self,
DbError::Sqlx(sqlx::Error::Database(db)) if db.code().as_deref() == Some("57014")
)
}
/// Whether the failure is about reaching the database at all (pool
/// acquire timeout, closed pool, or socket I/O) rather than about the
/// statement or its tenant. Every later query on the pool is expected to
/// fail the same way.
pub fn is_connection_unavailable(&self) -> bool {
matches!(
self,
DbError::Sqlx(sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Io(_))
)
}
}
/// Convenience alias for `Result<T, DbError>`.
pub type Result<T> = std::result::Result<T, DbError>;
/// A fixed description of a driver error for log lines. Postgres primary
/// messages can repeat a bound value (`invalid input syntax for type uuid:
/// "<value>"`), so only the SQLSTATE code is kept.
pub fn sqlx_error_kind(e: &sqlx::Error) -> String {
let kind = match e {
sqlx::Error::Database(db) => {
return format!("database:{}", db.code().as_deref().unwrap_or("unknown"))
}
sqlx::Error::RowNotFound => "row_not_found",
sqlx::Error::PoolTimedOut => "pool_timed_out",
sqlx::Error::PoolClosed => "pool_closed",
sqlx::Error::Io(_) => "io",
sqlx::Error::Tls(_) => "tls",
sqlx::Error::Protocol(_) => "protocol",
sqlx::Error::ColumnDecode { .. } | sqlx::Error::Decode(_) => "decode",
sqlx::Error::Encode(_) => "encode",
_ => "other",
};
kind.to_owned()
}
impl DbError {
/// A fixed description of this error for log lines: never the
/// message, which can repeat bound values.
pub fn kind(&self) -> String {
use DbError as E;
let kind = match self {
E::Sqlx(e) => return sqlx_error_kind(e),
E::Serde(_) => "serde",
E::InvalidData(_) => "invalid_data",
E::NotFound(_) | E::ChannelNotFound(_) | E::MemberNotFound(_) => "not_found",
E::AccessDenied(_) => "access_denied",
E::NipFiBindingRequired => "nip_fi_binding_required",
_ => "other",
};
kind.to_owned()
}
}
#[cfg(test)]
mod tests {
use super::DbError;
#[test]
fn connection_unavailable_covers_only_pool_and_io_failures() {
for error in [
sqlx::Error::PoolTimedOut,
sqlx::Error::PoolClosed,
sqlx::Error::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset)),
] {
assert!(DbError::Sqlx(error).is_connection_unavailable());
}
for error in [
DbError::Sqlx(sqlx::Error::RowNotFound),
DbError::Sqlx(sqlx::Error::Protocol("bad frame".into())),
DbError::AccessDenied("write-fenced".into()),
DbError::InvalidData("bad row".into()),
] {
assert!(!error.is_connection_unavailable(), "{error:?}");
}
}
}