Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/auth-service/src/alerts/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
49 changes: 49 additions & 0 deletions apps/auth-service/src/web/admin/tests/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,52 @@ 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.
#[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!("<strong>{status}</strong></div>")),
"{page}"
);
}
}
5 changes: 3 additions & 2 deletions crates/common/src/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,9 @@ pub struct AlertUpdate {
pub status: AlertStatus,
/// What they added, if anything.
pub note: Option<String>,
/// 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<AlertAuthor>,
/// When.
pub posted_at: DateTime<Utc>,
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

80 changes: 66 additions & 14 deletions crates/database/src/repositories/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -63,28 +63,36 @@ struct UpdateRow {
status: AlertStatus,
/// The note, until its event's personal data is erased.
note: Option<String>,
/// Who posted it, as an event's actor.
author: Json<Actor>,
/// Who posted it, as an event's actor, which [`RecordedActor`] decodes.
author: Value,
/// The administrator's handle, unless their account was purged.
handle: Option<Handle>,
/// When.
posted_at: DateTime<Utc>,
}

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,
Expand Down Expand Up @@ -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<Actor>",
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
Expand Down Expand Up @@ -334,4 +342,48 @@ 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, and only on a schema of its own, from
/// [`Database::isolated`](crate::Database::isolated).
///
/// # Errors
///
/// 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,
id: AlertId,
status: AlertStatus,
author: &Value,
) -> Result<(), DatabaseError> {
run!(
self,
execute,
sqlx::query(
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!(
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(())
}
}
25 changes: 19 additions & 6 deletions crates/database/src/repositories/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand All @@ -143,6 +144,20 @@ impl RecordedActor {
}
}

impl TryFrom<Value> 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<Self, Self::Error> {
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,
Expand Down Expand Up @@ -241,10 +256,8 @@ impl TryFrom<EventRow> 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,
Expand Down
49 changes: 49 additions & 0 deletions crates/database/src/repositories/events/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
20 changes: 10 additions & 10 deletions crates/ui/src/admin/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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}"),
}
}

Expand Down Expand Up @@ -138,7 +136,9 @@ async fn alert_card<'a>(card: &'a AlertCard<'a>) -> Result<impl View> {
<span class=(class!("dot", status_badge(update.status).tone))></span>
<div class="text">
<strong>(status_badge(update.status).label)</strong>
(format!(" by {}", author(update)))
if let Some(author) = &update.author {
(byline(author))
}
if let Some(note) = &update.note {
<small class="wrap">(note.as_str())</small>
}
Expand Down
16 changes: 12 additions & 4 deletions docs/dev/architecture/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,10 +416,18 @@ 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: 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
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.

Expand Down