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/admin/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ pub enum AdminError {
Event(#[from] serde_json::Error),
/// A link could not be written.
#[error("could not write a link")]
Link(#[from] sourceorigin_ui::QueryError),
Link(#[from] serde_urlencoded::ser::Error),
/// The audit chain could not be verified or pruned.
#[error(transparent)]
Audit(#[from] crate::AuditError),
Expand Down
41 changes: 24 additions & 17 deletions apps/auth-service/src/admin/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use sourceorigin_common::{
Handle, HandleError, UserId,
admin::{AnnouncementAudience, DraftAnnouncement, MessageUser},
};
use sourceorigin_ui::Grace;
use std::{fmt, str::FromStr};
use thiserror::Error;

Expand Down Expand Up @@ -43,8 +42,6 @@ const MINUTES_PER_HOUR: i64 = 60;
const MINUTES_PER_DAY: i64 = 24 * MINUTES_PER_HOUR;
/// Invitation lifetime when none is given: seven days.
const DEFAULT_INVITE_EXPIRY: i64 = 7 * MINUTES_PER_DAY;
/// Grace period of a rotation when none is given: a day.
const DEFAULT_GRACE_PERIOD: i64 = MINUTES_PER_DAY;

/// A whole number of minutes, written in its largest whole unit, e.g. `365d`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -92,6 +89,16 @@ pub struct InvalidLifetime {
}

impl<const MIN: i64, const MAX: i64> Lifetime<MIN, MAX> {
/// A lifetime of `minutes`, for a constant: one outside the bounds fails to
/// compile.
const fn within(minutes: i64) -> Self {
assert!(
MIN <= minutes && minutes <= MAX,
"a lifetime outside its bounds"
);
Self(Minutes(minutes))
}

/// The lifetime as a duration.
#[must_use]
pub const fn duration(self) -> Duration {
Expand All @@ -106,23 +113,23 @@ impl Default for InviteExpiry {
}
}

impl GracePeriod {
/// None: earlier secrets stop at once.
pub const NONE: Self = Self::within(0);
/// An hour.
pub const HOUR: Self = Self::within(MINUTES_PER_HOUR);
/// A day, when none is given.
pub const DAY: Self = Self::within(MINUTES_PER_DAY);
/// A week.
pub const WEEK: Self = Self::within(7 * MINUTES_PER_DAY);
/// 30 days, the longest.
pub const MONTH: Self = Self::within(30 * MINUTES_PER_DAY);
}

impl Default for GracePeriod {
/// A day.
fn default() -> Self {
Self(Minutes(DEFAULT_GRACE_PERIOD))
}
}

impl From<Grace> for GracePeriod {
/// The period the rotation form's choice names.
fn from(grace: Grace) -> Self {
Self(Minutes(match grace {
Grace::Now => 0,
Grace::Hour => MINUTES_PER_HOUR,
Grace::Day => MINUTES_PER_DAY,
Grace::Week => 7 * MINUTES_PER_DAY,
Grace::Month => 30 * MINUTES_PER_DAY,
}))
Self::DAY
}
}

Expand Down
15 changes: 0 additions & 15 deletions apps/auth-service/src/admin/types/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,6 @@ fn lifetimes_accept_bounded_minutes_hours_and_days() {
);
}

/// Each choice of the rotation form is the grace period it is written as.
#[test]
fn rotation_choices_are_the_periods_they_name() {
for grace in Grace::ALL {
assert_eq!(
Ok(GracePeriod::from(grace)),
grace
.as_str()
.parse::<GracePeriod>()
.map_err(|error| error.to_string()),
"{grace}"
);
}
}

/// A letter's subject is one line, and its text keeps its line breaks as `\n`;
/// both are trimmed and bounded.
#[test]
Expand Down
20 changes: 1 addition & 19 deletions apps/auth-service/src/federation/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use axum::http::header::InvalidHeaderValue;
use sourceorigin_common::{VocabularyError, config::ConfigurationError};
use sourceorigin_crypto::CryptoError;
use sourceorigin_repository::DatabaseError;
use sourceorigin_ui::{CallbackError, QueryError};
use thiserror::Error;

/// Federation failures that reach the browser, mapped to HTTP once in `From<FederationError>`.
Expand Down Expand Up @@ -70,7 +69,7 @@ pub(crate) enum FederationError {
Url(#[from] url::ParseError),
/// The sign-in page's address could not be written.
#[error("the sign-in page's address could not be written")]
PageAddress(#[from] QueryError),
PageAddress(#[from] serde_urlencoded::ser::Error),
/// A database operation failed.
#[error(transparent)]
Database(#[from] DatabaseError),
Expand All @@ -88,23 +87,6 @@ pub(crate) enum FederationError {
CookieHeader(#[from] InvalidHeaderValue),
}

impl FederationError {
/// What the sign-in page says of a provider's callback that failed with this,
/// when the browser can start again: `None` for the service's own failures.
pub(super) const fn callback_error(&self) -> Option<CallbackError> {
Some(match self {
Self::FlowBrowserMissing | Self::InvalidAttempt => CallbackError::Expired,
Self::SessionChanged | Self::Session(SessionError::Missing) => {
CallbackError::SessionChanged
}
Self::IdentityAlreadyLinked => CallbackError::AlreadyLinked,
Self::LinkedAccountUnavailable => CallbackError::AccountUnavailable,
Self::Session(SessionError::PasskeyRequired) => CallbackError::PasskeyRequired,
_ => return None,
})
}
}

impl From<FederationError> for ApiError {
/// The single place mapping each federation failure to its status and browser message.
fn from(error: FederationError) -> Self {
Expand Down
23 changes: 17 additions & 6 deletions apps/auth-service/src/federation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,17 +369,28 @@ impl FederationApplication {
}

/// The answer to a callback that failed with `error`: the sign-in page saying
/// why, going on to `return_to`, or the error itself when the browser cannot
/// do anything about it.
/// why, going on to `return_to`, when the browser can start again, or the error
/// itself for the service's own failures.
fn refused(
&self,
error: FederationError,
return_to: Option<&str>,
) -> Result<Response, ApiError> {
match error.callback_error() {
Some(reason) => Ok(self.failed_callback(reason, return_to)?),
None => Err(error.into()),
}
let reason = match error {
FederationError::FlowBrowserMissing | FederationError::InvalidAttempt => {
CallbackError::Expired
}
FederationError::SessionChanged | FederationError::Session(SessionError::Missing) => {
CallbackError::SessionChanged
}
FederationError::IdentityAlreadyLinked => CallbackError::AlreadyLinked,
FederationError::LinkedAccountUnavailable => CallbackError::AccountUnavailable,
FederationError::Session(SessionError::PasskeyRequired) => {
CallbackError::PasskeyRequired
}
error => return Err(error.into()),
};
Ok(self.failed_callback(reason, return_to)?)
}

/// Consumes the flow the callback names, bound to this browser, before
Expand Down
3 changes: 1 addition & 2 deletions apps/auth-service/src/oidc/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use sourceorigin_common::{
};
use sourceorigin_crypto::CryptoError;
use sourceorigin_repository::DatabaseError;
use sourceorigin_ui::QueryError;
use std::{borrow::Cow, error::Error as StdError};
use thiserror::Error;
use url::Url;
Expand Down Expand Up @@ -152,7 +151,7 @@ pub(crate) enum OAuthError {
CookieHeader(#[from] axum::http::header::InvalidHeaderValue),
/// The address of the page the browser goes on to could not be written.
#[error("a page's address could not be written")]
PageAddress(#[from] QueryError),
PageAddress(#[from] serde_urlencoded::ser::Error),
/// A grant read back from the database holds an invalid scope.
#[error("a stored grant holds an invalid scope")]
StoredScopes(#[from] InvalidScope),
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/pictures/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ impl AccountService {
let upload = client
.get(
url.as_str(),
sourceorigin_ui::PICTURE_TYPES,
sourceorigin_common::PICTURE_TYPES,
MAX_UPLOAD_BYTES + 1,
)
.await
Expand Down
20 changes: 17 additions & 3 deletions apps/auth-service/src/web/developers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ use super::{
account::{AccountPage, Applied, Framed, Reader, no_change},
};
use crate::{
MAX_OWNED_CLIENTS,
GracePeriod, MAX_OWNED_CLIENTS,
account::{AccountError, Owner},
clients::{ClientSettings, NewClient, OwnedClient, OwnedClientView},
routes::page::developers::{self, APP, APP_SECRETS, APP_SETTINGS, HOME, NEW},
};
use sourceorigin_common::clients::{ClientKind, ClientStatus};
use sourceorigin_ui::{
AppLink, AppTab, ClientDraft, ClientRow, Crumb, Messages, NewAppChange, NewAppState, Notice,
Registered, Revealed, Section, Title,
AppLink, AppTab, ClientDraft, ClientRow, Crumb, Grace, Messages, NewAppChange, NewAppState,
Notice, Registered, Revealed, Section, Title,
};
use topcoat::{
context::Cx,
Expand Down Expand Up @@ -199,6 +199,20 @@ impl From<ClientDraft> for ClientSettings {
}
}

impl From<Grace> for GracePeriod {
/// The period the rotation form's choice names, which the console and the
/// dashboard both offer.
fn from(grace: Grace) -> Self {
match grace {
Grace::Now => Self::NONE,
Grace::Hour => Self::HOUR,
Grace::Day => Self::DAY,
Grace::Week => Self::WEEK,
Grace::Month => Self::MONTH,
}
}
}

impl WebApplication {
/// The app the page's path names, as `owner` owns it. Another account's, a
/// deleted or an unknown one is not found.
Expand Down
16 changes: 16 additions & 0 deletions apps/auth-service/src/web/developers/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! The developer console through the whole service, as a browser uses it.

use crate::{
GracePeriod,
routes::page::developers::{self, APP, APP_SECRETS, APP_SETTINGS, HOME, NEW},
security::BrowserCookie,
tests::{Browser, Replicas, cookie, html, policy, redirect},
Expand Down Expand Up @@ -112,6 +113,21 @@ fn browser_forms_decode() {
assert_eq!(grace, Some(Grace::Week));
}

/// Each choice of the rotation form is the grace period it is written as.
#[test]
fn rotation_choices_are_the_periods_they_name() {
for grace in Grace::ALL {
assert_eq!(
Ok(GracePeriod::from(grace)),
grace
.as_str()
.parse::<GracePeriod>()
.map_err(|error| error.to_string()),
"{grace}"
);
}
}

/// A confidential app's secret shows once, in the answer registering it, which
/// nothing stores and which asks the passkey script to put back the form's address;
/// neither its overview nor the apps show it again. A rotation shows the new one the
Expand Down
4 changes: 4 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,10 @@ uuid_id!(
PictureId,
"Identifier of one upload of an account's profile picture, in its URL: a new picture gets a new one."
);
/// The media types auth reads a profile picture from, as an upload's file input
/// and a provider picture's fetch name them in `accept` and `Accept`; auth
/// recognises the format by content.
pub const PICTURE_TYPES: &str = "image/png,image/jpeg,image/gif";
uuid_id!(
RecoveryId,
"Identifier of an account recovery, which its link's token is derived from."
Expand Down
8 changes: 4 additions & 4 deletions crates/ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ pub use settings::{
ConnectedAppsState, DataChange, DataState, DeviceChange, DeviceRow, EmailChange, EmailRow,
EmailsState, HistoryChange, HistoryPage, HistoryRow, HistoryState, Holdings, InboxChange,
InboxPage, InboxRow, InboxState, NotificationPage, NotificationState, OverviewLinks,
PASTE_WHOLE_LINK, PICTURE_FIELD, PICTURE_TYPES, ProfileChange, ProfileDialog, ProfilePages,
ProfileState, ProviderRow, SignInChange, SignInState, SignOutStep, Tab, UnsubscribeStep,
account_data, account_deleted, account_overview, addresses, connected_apps, devices, history,
inbox, known_devices, notification, profile_settings, sign_in_methods, sign_out_everywhere,
PASTE_WHOLE_LINK, PICTURE_FIELD, ProfileChange, ProfileDialog, ProfilePages, ProfileState,
ProviderRow, SignInChange, SignInState, SignOutStep, Tab, UnsubscribeStep, account_data,
account_deleted, account_overview, addresses, connected_apps, devices, history, inbox,
known_devices, notification, profile_settings, sign_in_methods, sign_out_everywhere,
unsubscribe, verified, verify,
};
4 changes: 2 additions & 2 deletions crates/ui/src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ pub use notifications::{
};
pub use overview::{AccountOverview, OverviewLinks, account_overview};
pub use profile::{
CROP_SIZE, CROP_X, CROP_Y, PICTURE_FIELD, PICTURE_TYPES, ProfileChange, ProfileDialog,
ProfilePages, ProfileState, profile_settings,
CROP_SIZE, CROP_X, CROP_Y, PICTURE_FIELD, ProfileChange, ProfileDialog, ProfilePages,
ProfileState, profile_settings,
};
pub use sessions::{DeviceChange, DeviceRow, devices, known_devices};
pub use sign_in::{ProviderRow, SignInChange, SignInState, sign_in_methods};
Expand Down
5 changes: 1 addition & 4 deletions crates/ui/src/settings/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sourceorigin_common::PICTURE_TYPES;
use topcoat::{
Result,
view::{View, component, view},
Expand All @@ -16,10 +17,6 @@ use topcoat::{
/// The file input an upload sends its picture in.
pub const PICTURE_FIELD: &str = "picture";

/// The media types auth reads a picture from, as an upload's file input and a
/// fetch's `Accept` header name them; auth recognises the format by content.
pub const PICTURE_TYPES: &str = "image/png,image/jpeg,image/gif";

/// The hidden inputs an upload sends the square to keep in, in the picture's
/// pixels once upright: its left edge, its top edge and its side. The picture
/// script fills them as the owner moves and zooms the picture; without a script
Expand Down
10 changes: 7 additions & 3 deletions docs/dev/architecture/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,12 @@ its routes, and `src/routes.rs` declares every path. Pages live in `src/web`, gr
the recovery pages and the admin dashboard's handoff), `settings`, `developers`,
and `admin`, the admin dashboard, whose views are in `crates/ui/src/admin`.
`src/admin` is not a page module: it holds `AdminService` and the operator rules
that the dashboard and the CLI share. [Rust conventions](../rust-conventions.md)
explains how applications, routes and services fit together.
that the dashboard and the CLI share. Services never depend on
`sourceorigin-ui`: the pages convert between ui's types and the services'. The
exceptions are the code that redirects to a page or renders one, which the
[crates' conventions](../rust-conventions.md#crates) list.
[Rust conventions](../rust-conventions.md) explains how applications, routes and
services fit together.

## Crates

Expand All @@ -86,7 +90,7 @@ explains how applications, routes and services fit together.
| `sourceorigin-crypto` (`crates/crypto`) | Every cryptographic primitive, on `aws-lc-rs`: secrets, digests, HMAC, PKCE, RS256 signing and key sets, AES-256-GCM sealing, Ed25519 signed notes and SCRAM verifiers |
| `sourceorigin-repository` (`crates/database`) | The only crate that runs SQL: connections, migrations, repositories, transactions, events and the delivery queue's storage |
| `sourceorigin-telemetry` (`crates/telemetry`) | Logs, traces and metrics, and the HTTP layer every router uses |
| `sourceorigin-ui` (`crates/ui`) | The Topcoat components of auth's pages and the admin dashboard, and the bodies of its emails, which know nothing of the database or HTTP |
| `sourceorigin-ui` (`crates/ui`) | The Topcoat components of auth's pages and the admin dashboard, and the bodies of its emails, which know nothing of the database or HTTP. It uses `sourceorigin-common`'s types, never the other way round |
| `sourceorigin-auth` (`crates/auth-sdk`) | The Rust SDK, which depends only on `sourceorigin-common` and `sourceorigin-crypto` |

The SDK and the two crates it depends on are published to crates.io, under the
Expand Down
12 changes: 11 additions & 1 deletion docs/dev/rust-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,17 @@ Keep implementations simple. Follow neighbouring modules and share repeated logi
the changes and queries their forms and links send. They render plain data,
`sourceorigin-common` IDs, vocabularies and events, or plain rows such as `EmailRow`
or `ClientRow` that the pages map the service's views into, and take URLs as
props; they know nothing of the domain, the database or HTTP. `layout` holds
props; they know nothing of the domain, the database or HTTP. Dependencies
point one way: ui uses `sourceorigin-common`'s types, and auth's services never
name ui's. A service's inputs, rules, views, outcomes and errors are its own
types or common's, and the pages in `src/web` convert between them and ui's,
such as a rotation form's `Grace` into the service's `GracePeriod`. Outside
`src/web`, only what answers a browser or renders an email names ui: a
redirect to a page writes that page's query, as federation's callback and the
OIDC flows write `LoginQuery`; the security layer renders its error page and keeps the preference and notice cookies,
`assets` serves ui's files, the email deliverer renders each email's bodies,
and the configuration finds sourceorigin.dev's policies at the
`Policies::PATHS` that site serves them at. `layout` holds
the document and the two frames: the shell of a signed-in page, a sidebar of
`NavItem`s beside the page and a status bar below it, which the account's
pages (`account`) and the admin dashboard (`dashboard_frame`) both fill, and
Expand Down