Files
buzz/crates/buzz-db/src/error.rs
Brad Seiler 96af488d96 fix(media): revoke private channel attachment reads (#9077)
## Summary

Removed private-channel members can currently download attachments if
they know the URL. With `BUZZ_MEDIA_READ_MODE=enforce`, fresh GET, HEAD
and Range requests check current membership and readable references on
the primary database. Removed members receive 404; remaining members
retain access, and rejoining restores access. Thumbnail aliases use the
parent attachment’s permissions.

Publication checks also prevent copied private URLs from granting new
access. They cover attachments, link previews, profile pictures,
banners, group pictures and emoji. Persona creation and changed-avatar
edits, plus team and individual snapshot imports, transfer animated
posters and animations under the agent’s signer before profile
publication. Failed persona transfers preserve existing local records;
import failures appear in the results.

Authorization uses bounded queries, a two-second statement deadline and
transaction-local JIT suppression. An index on edit targets avoids broad
scans. Publications have a 512-reference limit, and capacity waits up to
500 ms before refusal.

Protection defaults off. Existing downloaded bytes cannot be recalled.
All modes stop creating immutable HTTP cache entries.

### Related issue

Related approaches: #7565, #5185, #8451 and #8444. This change evaluates
live stored references directly.

### Testing

Published head: `3d1aa7431cc495a001a0f13e95e2e422c5a77ab1`, rebased on
main `2cd40badb85de059a6916206e133da7a0a88fb2e`. Push hooks were
**SKIPPED** with explicit author approval. Current-head HTTP, full
package, PostgreSQL migration/media and profile-filter mutation checks
are pending; CI is pending. The earlier complete HTTP journey passed at
`f20b449262` (identical source tree), with its evidence attributed
separately. Earlier failing preview/report-fixture runs are preserved;
they do not count as passes.

The HTTP journey covers upload/publication, fresh GET/HEAD/Range
revocation and rejoin, emoji replacement, edited previews, persona
visibility and non-reference decoys. The migration regression forces an
index timeout, verifies no 0086 history or media tables, then proves a
migrator through the base's 0085 can restart.

Human attachment removal/rejoin testing passed on the pinned
`1f08a8e0fd2edf19dc94321f7258518149fe1bf6` trial. Native animated
persona edits and team/individual import acceptance remain incomplete.
That old-snapshot database stays intact and cannot run the reconciled
binary; a new trial needs a separate fresh database.

### Rollout prerequisites

- Build and verify the reference index before shadow mode. Small
databases can auto-migrate through one atomic 0086 migration within the
configured timeouts. It builds the index before creating the media
tables, so failure records no new migration version. Large deployments
must disable auto-migration and prebuild indexes concurrently.
- **Enforce remains blocked unless the operator can rule out SDK/CLI
attachment edits and the unverified agent-harness edit producer.**
SDK/CLI edits still omit attachment metadata. That behavior is deferred,
not fixed. Removing this blocker requires latest-effective attachment
metadata across successive edits, no restoration of removed files, and
an upload → successive edits → GET/HEAD regression.
- Validate client signer compatibility and split emoji publications
above 512 references before enforce mode.
- Complete the human workflows above in an isolated community with
enforce enabled.
- Follow the [index deployment
guide](https://github.com/block/buzz/blob/honor/private-channel-media/docs/private-media-index-deployment.md)
and [operator
guidance](https://github.com/block/buzz/blob/honor/private-channel-media/docs/operator-private-media.md)
for rollout and rollback.

The [prebuild timeout
finding](https://github.com/block/buzz/pull/9077#discussion_r4486221478)
and [avatar-transfer
finding](https://github.com/block/buzz/pull/9077#discussion_r4486221458)
are implemented and independently reviewed.

### Schema change checklist

- [x] Additive expand and code deployment; no backfill or contract
phase. Prebuild/verify before shadow under either schema deployment
path.
- [x] No SQL function, trigger, procedure, rule or foreign key added.
Signed events are untouched.
- [x] No migration mutates existing rows.
- [x] Migration and desired-state schema match. Catalog parity, target
parsing, future partition inheritance and upgrade refusal are covered.
- [x] Old/new binaries coexist for serving. Suspend community deletion
during expansion and while rolled back to a binary with the old deletion
catalog.
- [x] Keep auto-migration disabled on old binaries after schema
expansion; sqlx rejects unknown versions.
- [x] Migration lock timeout 1 s; statement timeout 5 s. Small populated
databases build inline within those budgets; large deployments use
concurrent child-index prebuild/attachment with auto-migration off.
Missing, invalid or wrong indexes fail verification.

Generated with Codex

---------

Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
2026-11-06 22:35:00 +00:00

217 lines
8.1 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,
/// 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 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:?}");
}
}
}