From 4349e5975c8821bb65e34fda1db760fd9835f05b Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:43:49 +0100 Subject: [PATCH 1/2] fix(auth): alert updates stay readable when a newer release recorded an author this one doesn't know An alert update's author of a type this release does not know, or a known type naming a value it does not know such as a new job, reads as no author instead of failing the alerts read, and the dashboard's Alerts page shows the update without a byline. A known author that does not decode is still an error, and writes stay typed. Closes #701 --- apps/auth-service/src/alerts/tests.rs | 2 +- .../src/web/admin/tests/operations.rs | 54 +++++++++++++ crates/common/src/alerts.rs | 5 +- ...6ed13ea09ff47e4988e2e5974c4d2874a792.json} | 6 +- crates/database/src/repositories/alerts.rs | 75 +++++++++++++++---- .../database/src/repositories/events/mod.rs | 25 +++++-- .../database/src/repositories/events/tests.rs | 49 ++++++++++++ crates/ui/src/admin/alerts.rs | 20 ++--- docs/dev/architecture/database.md | 12 ++- 9 files changed, 208 insertions(+), 40 deletions(-) rename crates/database/.sqlx/{query-d5cc0480c4b9381062c39b91ca0775251bcdb3805b94222aa37bfb8496c2afd1.json => query-15064ec7c2f1cd43ee2b2fe0c2ac6ed13ea09ff47e4988e2e5974c4d2874a792.json} (62%) diff --git a/apps/auth-service/src/alerts/tests.rs b/apps/auth-service/src/alerts/tests.rs index b09627ecb..a1c33c115 100644 --- a/apps/auth-service/src/alerts/tests.rs +++ b/apps/auth-service/src/alerts/tests.rs @@ -211,7 +211,7 @@ async fn updates_acknowledge_an_alert_until_its_condition_changes() { ); assert!(matches!( detail.updates[0].author, - AlertAuthor::Administrator { handle: Some(_) } + Some(AlertAuthor::Administrator { handle: Some(_) }) )); let recorded = database .events() diff --git a/apps/auth-service/src/web/admin/tests/operations.rs b/apps/auth-service/src/web/admin/tests/operations.rs index b7c0cc039..08e22184a 100644 --- a/apps/auth-service/src/web/admin/tests/operations.rs +++ b/apps/auth-service/src/web/admin/tests/operations.rs @@ -358,3 +358,57 @@ async fn alerts_take_updates_from_the_dashboard() { assert!(previous.contains("Previous alerts"), "{previous}"); assert!(!previous.contains(&position.to_string()), "{previous}"); } + +/// Updates whose author a newer release recorded, of a type this one does not +/// know or a known type naming a job it does not know, show on the Alerts page +/// without a byline, and the overview's banner still leads there. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn alert_updates_by_authors_a_newer_release_recorded_show_without_a_byline() { + use sourceorigin_common::{ + admin::{ChainBreak, ChainProblem}, + alerts::{Alert, AlertStatus}, + }; + let harness = Harness::isolated().await; + let admin = harness.admin().await; + let alert = Alert::AuditChainBroken(ChainBreak { + position: 1, + problem: ChainProblem::EventChanged, + }); + let id = harness + .database + .alerts() + .raise(&alert) + .await + .expect("raise"); + for (status, author) in [ + ( + AlertStatus::Investigating, + serde_json::json!({"type": "from_a_newer_release"}), + ), + ( + AlertStatus::Fixing, + serde_json::json!({"type": "system", "job": "from_a_newer_release"}), + ), + ] { + harness + .database + .alerts() + .add_update_written_elsewhere(id, status, &author) + .await + .expect("update"); + } + let dashboard = harness.sign_in(&admin, "/alerts").await; + let page = html(harness.visit(&dashboard, "/alerts").await).await; + for status in ["Investigating", "Fixing"] { + assert!( + page.contains(&format!("{status}")), + "{page}" + ); + } + let overview = html(harness.visit(&dashboard, "/").await).await; + assert!( + overview.contains("1 alert needs attention") && overview.contains("See the alerts"), + "{overview}" + ); +} diff --git a/crates/common/src/alerts.rs b/crates/common/src/alerts.rs index 7bd1660b5..5d6d12f82 100644 --- a/crates/common/src/alerts.rs +++ b/crates/common/src/alerts.rs @@ -201,8 +201,9 @@ pub struct AlertUpdate { pub status: AlertStatus, /// What they added, if anything. pub note: Option, - /// Who posted it. - pub author: AlertAuthor, + /// Who posted it, or `None` if a newer release recorded an author this one + /// does not know, which is shown without a byline. + pub author: Option, /// When. pub posted_at: DateTime, } diff --git a/crates/database/.sqlx/query-d5cc0480c4b9381062c39b91ca0775251bcdb3805b94222aa37bfb8496c2afd1.json b/crates/database/.sqlx/query-15064ec7c2f1cd43ee2b2fe0c2ac6ed13ea09ff47e4988e2e5974c4d2874a792.json similarity index 62% rename from crates/database/.sqlx/query-d5cc0480c4b9381062c39b91ca0775251bcdb3805b94222aa37bfb8496c2afd1.json rename to crates/database/.sqlx/query-15064ec7c2f1cd43ee2b2fe0c2ac6ed13ea09ff47e4988e2e5974c4d2874a792.json index 250a1395b..9e62760d4 100644 --- a/crates/database/.sqlx/query-d5cc0480c4b9381062c39b91ca0775251bcdb3805b94222aa37bfb8496c2afd1.json +++ b/crates/database/.sqlx/query-15064ec7c2f1cd43ee2b2fe0c2ac6ed13ea09ff47e4988e2e5974c4d2874a792.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT u.alert_id AS \"alert_id: AlertId\", u.status AS \"status: AlertStatus\",\n p.reason AS \"note?\", u.author AS \"author: Json\",\n h.handle AS \"handle?: Handle\", u.posted_at\n FROM alert_updates u\n LEFT JOIN event_personal_data p ON p.event_id = u.event_id\n LEFT JOIN handles h\n ON h.user_id = (u.author ->> 'user_id')::uuid AND h.released_at IS NULL\n WHERE u.alert_id = ANY($1)\n ORDER BY u.posted_at, u.id", + "query": "SELECT u.alert_id AS \"alert_id: AlertId\", u.status AS \"status: AlertStatus\",\n p.reason AS \"note?\", u.author,\n h.handle AS \"handle?: Handle\", u.posted_at\n FROM alert_updates u\n LEFT JOIN event_personal_data p ON p.event_id = u.event_id\n LEFT JOIN handles h\n ON h.user_id = (u.author ->> 'user_id')::uuid AND h.released_at IS NULL\n WHERE u.alert_id = ANY($1)\n ORDER BY u.posted_at, u.id", "describe": { "columns": [ { @@ -20,7 +20,7 @@ }, { "ordinal": 3, - "name": "author: Json", + "name": "author", "type_info": "Jsonb" }, { @@ -48,5 +48,5 @@ false ] }, - "hash": "d5cc0480c4b9381062c39b91ca0775251bcdb3805b94222aa37bfb8496c2afd1" + "hash": "15064ec7c2f1cd43ee2b2fe0c2ac6ed13ea09ff47e4988e2e5974c4d2874a792" } diff --git a/crates/database/src/repositories/alerts.rs b/crates/database/src/repositories/alerts.rs index de02cf97c..65ef15c02 100644 --- a/crates/database/src/repositories/alerts.rs +++ b/crates/database/src/repositories/alerts.rs @@ -3,7 +3,7 @@ //! current, the one not cleared yet. use super::{AlertRepository, KindProbe, RepositoryExecutor, Unsigned}; -use crate::{DatabaseError, LockKey}; +use crate::{DatabaseError, DecodeFailure, LockKey, RecordedActor}; use chrono::{DateTime, Utc}; use serde_json::Value; use sourceorigin_common::{ @@ -63,8 +63,8 @@ struct UpdateRow { status: AlertStatus, /// The note, until its event's personal data is erased. note: Option, - /// Who posted it, as an event's actor. - author: Json, + /// Who posted it, as an event's actor, which [`RecordedActor`] decodes. + author: Value, /// The administrator's handle, unless their account was purged. handle: Option, /// When. @@ -72,19 +72,27 @@ struct UpdateRow { } impl UpdateRow { - /// The update, with its alert. + /// The update, with its alert. An author a newer release recorded, which this + /// one does not know, reads as `None`; a known one that does not decode, or + /// that is not an administrator or an operator, fails. fn decode(self) -> Result<(AlertId, AlertUpdate), DatabaseError> { - let author = match self.author.0 { - Actor::Admin { .. } => AlertAuthor::Administrator { + let invalid = |source: DecodeFailure| DatabaseError::InvalidStoredData { + column: "author".into(), + source, + }; + let recorded = + RecordedActor::try_from(self.author).map_err(|error| invalid(error.into()))?; + let author = match recorded { + RecordedActor::Known(Actor::Admin { .. }) => Some(AlertAuthor::Administrator { handle: self.handle, - }, - Actor::Cli { os_user, host } => AlertAuthor::Operator { os_user, host }, - _ => { - return Err(DatabaseError::InvalidStoredData { - column: "author".into(), - source: "not an administrator or operator".into(), - }); + }), + RecordedActor::Known(Actor::Cli { os_user, host }) => { + Some(AlertAuthor::Operator { os_user, host }) + } + RecordedActor::Known(_) => { + return Err(invalid("not an administrator or operator".into())); } + RecordedActor::Unknown(_) => None, }; let update = AlertUpdate { status: self.status, @@ -284,7 +292,7 @@ impl AlertRepository<'_> { sqlx::query_as!( UpdateRow, r#"SELECT u.alert_id AS "alert_id: AlertId", u.status AS "status: AlertStatus", - p.reason AS "note?", u.author AS "author: Json", + p.reason AS "note?", u.author, h.handle AS "handle?: Handle", u.posted_at FROM alert_updates u LEFT JOIN event_personal_data p ON p.event_id = u.event_id @@ -334,4 +342,43 @@ impl AlertRepository<'_> { )?; Ok(()) } + + /// Adds an update on alert `id` as a newer release would, with any `author` + /// and no note, for tests of what this release reads back. That release + /// widened the column's check to the authors it writes, so this drops the + /// check: run it on a schema of its own, from + /// [`Database::isolated`](crate::Database::isolated). + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if a query fails. + #[cfg(any(test, feature = "test-util"))] + pub async fn add_update_written_elsewhere( + &mut self, + id: AlertId, + status: AlertStatus, + author: &Value, + ) -> Result<(), DatabaseError> { + run!( + self, + execute, + sqlx::query( + "ALTER TABLE alert_updates DROP CONSTRAINT IF EXISTS alert_updates_author_check" + ) + )?; + run!( + self, + execute, + sqlx::query!( + "INSERT INTO alert_updates (id, alert_id, event_id, status, author) + VALUES ($1, $2, $3, $4, $5)", + Uuid::now_v7(), + id.as_uuid(), + EventId::new().as_uuid(), + status.as_str(), + author, + ) + )?; + Ok(()) + } } diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index 035195388..6fb3096ef 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -117,8 +117,9 @@ impl RecordedEvent { /// actors newer releases recorded: a type it does not know, or a known type /// naming a value it does not know, such as a new [`JobName`] of an /// [`Actor::System`]. Those read as [`Self::Unknown`] instead of failing, and each -/// reader decides what to do with them. Only reads produce one: `record` takes an -/// [`EventContext`], whose actor is an [`Actor`]. +/// reader decides what to do with them. An alert update's author reads by the +/// same rule. Only reads produce one: `record` takes an [`EventContext`], whose +/// actor is an [`Actor`], and an alert update's author is one too. /// /// Serializes as stored. /// @@ -143,6 +144,20 @@ impl RecordedActor { } } +impl TryFrom for RecordedActor { + type Error = serde_json::Error; + + /// Decodes a stored actor, an event's or an alert update's author: one this + /// release does not know reads as [`Self::Unknown`], and a known one that + /// does not decode fails. + fn try_from(stored: Value) -> Result { + match KindProbe::known_flat(&stored) { + Some(actor) => actor.map(Self::Known), + None => Ok(Self::Unknown(stored)), + } + } +} + /// A checked `sqlx::query_as!` returning [`EventRow`]s, whose columns are written /// only here: every event column, joined with the event's personal data, from /// `domain_events e` and `event_personal_data p`. `$rest` filters and orders, @@ -241,10 +256,8 @@ impl TryFrom for StoredEvent { data: payload, }, }; - let actor = match KindProbe::known_flat(&row.actor) { - Some(actor) => RecordedActor::Known(actor.map_err(|source| invalid("actor", source))?), - None => RecordedActor::Unknown(row.actor), - }; + let actor = + RecordedActor::try_from(row.actor).map_err(|source| invalid("actor", source))?; Ok(Self { id: row.id, occurred_at: row.occurred_at, diff --git a/crates/database/src/repositories/events/tests.rs b/crates/database/src/repositories/events/tests.rs index 8729e43cd..ff5987dda 100644 --- a/crates/database/src/repositories/events/tests.rs +++ b/crates/database/src/repositories/events/tests.rs @@ -357,6 +357,55 @@ async fn actors_a_newer_release_wrote_read_as_unknown() { tx.rollback().await.expect("rollback"); } +/// Alert update authors a newer release recorded, of a type this one does not +/// know or a known type naming a job it does not know, read as no author. A +/// known type that does not decode still fails. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn alert_authors_a_newer_release_wrote_read_as_unknown() { + use crate::DatabaseConfig; + use sourceorigin_common::{ + admin::{ChainBreak, ChainProblem}, + alerts::{Alert, AlertStatus}, + }; + use std::time::Duration; + let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let database = Database::isolated( + DatabaseConfig::new(&url, 1, Duration::from_secs(5)).expect("configuration"), + ) + .await + .expect("isolated database"); + let alert = Alert::AuditChainBroken(ChainBreak { + position: 1, + problem: ChainProblem::EventChanged, + }); + let id = database.alerts().raise(&alert).await.expect("alert"); + let post = async |author| { + database + .alerts() + .add_update_written_elsewhere(id, AlertStatus::Fixing, &author) + .await + .expect("update"); + }; + post(serde_json::json!({"type": "from_a_newer_release"})).await; + post(serde_json::json!({"type": "system", "job": "from_a_newer_release"})).await; + let authors: Vec<_> = database + .alerts() + .updates(&[id]) + .await + .expect("updates") + .into_iter() + .map(|(_, update)| update.author) + .collect(); + assert_eq!(authors, [None, None]); + + post(serde_json::json!({"type": "cli"})).await; + assert!(matches!( + database.alerts().updates(&[id]).await, + Err(DatabaseError::InvalidStoredData { .. }) + )); +} + /// An alert update's note is its event's reason, so it is read while the event's /// personal data is kept, and reads as none once that is erased. #[tokio::test] diff --git a/crates/ui/src/admin/alerts.rs b/crates/ui/src/admin/alerts.rs index f2baee2b4..069467e42 100644 --- a/crates/ui/src/admin/alerts.rs +++ b/crates/ui/src/admin/alerts.rs @@ -2,9 +2,7 @@ use super::{Action, Badge, Change, badge, confirm, moment}; use crate::layout::page_head; -use sourceorigin_common::alerts::{ - Alert, AlertAuthor, AlertDetail, AlertState, AlertStatus, AlertUpdate, -}; +use sourceorigin_common::alerts::{Alert, AlertAuthor, AlertDetail, AlertState, AlertStatus}; use topcoat::{ Result, view::{View, class, component, view}, @@ -42,14 +40,14 @@ fn alert_badge(detail: &AlertDetail) -> Badge { } } -/// Who posted `update`, in words. -fn author(update: &AlertUpdate) -> String { - match &update.author { +/// Who posted an update, as its byline. +fn byline(author: &AlertAuthor) -> String { + match author { AlertAuthor::Administrator { handle: Some(handle), - } => format!("@{handle}"), - AlertAuthor::Administrator { handle: None } => "a deleted account".to_owned(), - AlertAuthor::Operator { os_user, host } => format!("the terminal, {os_user}@{host}"), + } => format!(" by @{handle}"), + AlertAuthor::Administrator { handle: None } => " by a deleted account".to_owned(), + AlertAuthor::Operator { os_user, host } => format!(" by the terminal, {os_user}@{host}"), } } @@ -138,7 +136,9 @@ async fn alert_card<'a>(card: &'a AlertCard<'a>) -> Result {
(status_badge(update.status).label) - (format!(" by {}", author(update))) + if let Some(author) = &update.author { + (byline(author)) + } if let Some(note) = &update.note { (note.as_str()) } diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index fe7bac2ba..6254d72fa 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -416,10 +416,14 @@ release never writes an unknown one, and an actor of a known type that does not decode, such as a `user` with no `user_id`, is still `DatabaseError::InvalidStoredData`. -Closed vocabularies stored in other columns, such as `AccountStatus` and the -actor in `alert_updates.author`, have no such tolerance: a release fails to -decode a value it does not know -([#701](https://github.com/sourceorigin-dev/sourceorigin/issues/701)). Add the +An [alert update](#alerts)'s author is an actor too, and is read by the same +rule. The alerts read returns `AlertUpdate.author` as `None` for an author this +release does not know, and the dashboard's **Alerts** page shows that update +without a byline. An administrator or operator that does not decode, or a known +actor of another type, is still `DatabaseError::InvalidStoredData`. + +Closed vocabularies stored in other columns, such as `AccountStatus`, have no +such tolerance: a release fails to decode a value it does not know. Add the value in one release that never writes it, and start writing it in a later one, so the release a deploy or rollback runs beside always reads it. From 361b317dd14576b4eba02043e668031e6a8da992 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 15:59:01 +0100 Subject: [PATCH 2/2] fix(auth): review follow-ups for unknown alert authors The database docs say alerts list --json prints a null author for one this release does not know, and that the column's CHECK is widened by the release that writes another author type, a migration a rollback keeps. The dashboard test no longer asserts the overview's banner, which never reads authors. add_update_written_elsewhere refuses outside a schema from Database::isolated. --- apps/auth-service/src/web/admin/tests/operations.rs | 7 +------ crates/database/src/repositories/alerts.rs | 11 ++++++++--- docs/dev/architecture/database.md | 10 +++++++--- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/apps/auth-service/src/web/admin/tests/operations.rs b/apps/auth-service/src/web/admin/tests/operations.rs index 08e22184a..c7d94bb58 100644 --- a/apps/auth-service/src/web/admin/tests/operations.rs +++ b/apps/auth-service/src/web/admin/tests/operations.rs @@ -361,7 +361,7 @@ async fn alerts_take_updates_from_the_dashboard() { /// Updates whose author a newer release recorded, of a type this one does not /// know or a known type naming a job it does not know, show on the Alerts page -/// without a byline, and the overview's banner still leads there. +/// without a byline. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn alert_updates_by_authors_a_newer_release_recorded_show_without_a_byline() { @@ -406,9 +406,4 @@ async fn alert_updates_by_authors_a_newer_release_recorded_show_without_a_byline "{page}" ); } - let overview = html(harness.visit(&dashboard, "/").await).await; - assert!( - overview.contains("1 alert needs attention") && overview.contains("See the alerts"), - "{overview}" - ); } diff --git a/crates/database/src/repositories/alerts.rs b/crates/database/src/repositories/alerts.rs index 65ef15c02..33ac82bc9 100644 --- a/crates/database/src/repositories/alerts.rs +++ b/crates/database/src/repositories/alerts.rs @@ -346,12 +346,12 @@ impl AlertRepository<'_> { /// Adds an update on alert `id` as a newer release would, with any `author` /// and no note, for tests of what this release reads back. That release /// widened the column's check to the authors it writes, so this drops the - /// check: run it on a schema of its own, from + /// check, and only on a schema of its own, from /// [`Database::isolated`](crate::Database::isolated). /// /// # Errors /// - /// Returns [`DatabaseError`] if a query fails. + /// Returns [`DatabaseError`] outside such a schema, or if a query fails. #[cfg(any(test, feature = "test-util"))] pub async fn add_update_written_elsewhere( &mut self, @@ -363,7 +363,12 @@ impl AlertRepository<'_> { self, execute, sqlx::query( - "ALTER TABLE alert_updates DROP CONSTRAINT IF EXISTS alert_updates_author_check" + r"DO $$ BEGIN + IF current_schema() NOT LIKE 'test\_%' THEN + RAISE EXCEPTION 'add_update_written_elsewhere runs only on Database::isolated'; + END IF; + ALTER TABLE alert_updates DROP CONSTRAINT IF EXISTS alert_updates_author_check; + END $$" ) )?; run!( diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index 6254d72fa..e3fc84dd2 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -418,9 +418,13 @@ decode, such as a `user` with no `user_id`, is still An [alert update](#alerts)'s author is an actor too, and is read by the same rule. The alerts read returns `AlertUpdate.author` as `None` for an author this -release does not know, and the dashboard's **Alerts** page shows that update -without a byline. An administrator or operator that does not decode, or a known -actor of another type, is still `DatabaseError::InvalidStoredData`. +release does not know: the dashboard's **Alerts** page shows that update +without a byline, and `auth-service alerts list --json` prints its +`"author": null`. An administrator or operator that does not decode, or a known +actor of another type, is still `DatabaseError::InvalidStoredData`. The +column's `CHECK` allows only `admin` and `cli` authors, so a release that writes +another type widens it in a migration first. Migrations aren't reverted, so +after a rollback the older release reads that author as unknown. Closed vocabularies stored in other columns, such as `AccountStatus`, have no such tolerance: a release fails to decode a value it does not know. Add the