Skip to content
Merged
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
19 changes: 16 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ Administrators can also list, create and revoke invitations through the admin AP
### Administration

Every administrative operation has a command, which runs the same code as the
admin API (`AdminService` in `apps/auth-service/src/admin`). Commands need only
admin API (`AdminService` in `apps/auth-service/src/admin`), and so does every
setting administrators may change on another account (`AccountService` in
`apps/auth-service/src/account`). Commands need only
`AUTH_DATABASE_URL` (`invite create` also needs `AUTH_PUBLIC_BASE_URL`, to build its
link), so they work while auth is down: they are the break-glass path when the
dashboard or auth's frontends are unreachable. In deployed environments,
Expand All @@ -128,15 +130,26 @@ just auth user enable alice
just auth session revoke <session-id> # one session, as `user show` lists it
just auth session revoke-all alice # every session of the account
just auth audit --user alice --kind session_revoked
just auth account alice passkeys list # the account's settings, as its owner sees them
just auth account alice passkeys revoke <passkey-id> --reason "Phone stolen"
just auth account alice emails remove <email-id> --reason "Asked by email"
```

- Accounts are named by username, ID or a verified email of an active account.
- `--output json` prints the admin API's body for `user search` (`UserPage`), `user
show` (`UserDetail`), `audit` (`EventPage`), `client list`, `invite list` and
`admin list`, as defined in `crates/admin-api`. It changes only as the API does.
- `user disable`, `session revoke-all`, `admin revoke` and `client
disable|suspend|delete` describe what they will change and ask for confirmation.
- `user disable`, `session revoke-all`, `admin revoke`, `client
disable|suspend|delete`, and `account … passkeys revoke`, `identities unlink` and
`sessions revoke-all` describe what they will change and ask for confirmation.
Without a terminal they refuse unless given `--yes`.
- `account <user>` reads and changes the settings administrators share with the
owner: passkeys, social identities, email addresses, sessions and the security
history, with the owner's own operations. It never adds a way to sign in or an
address. Every change needs `--reason`, which the owner sees in their history;
reads are recorded as views. See
[surfaces.md](docs/architecture/surfaces.md#changing-an-account-on-its-owners-behalf)
for what is shared.
- Each change is recorded as a domain event with the operator: `$USER` and the host
name. Unlike the admin API, the CLI may act on administrators' accounts.
- Failures print their causes and exit with 1; usage errors exit with 2.
Expand Down
61 changes: 61 additions & 0 deletions apps/auth-service/src/account/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//! Failures of a shared settings operation, from the owner's routes or the CLI.

use crate::{
AdminError,
emails::EmailError,
federation::FederationError,
passkey::PasskeyError,
security::{ApiError, SessionError},
sessions::SessionsError,
};
use axum::response::{IntoResponse, Response};
use piquel_repository::DatabaseError;

/// Why a shared settings operation failed: the setting's own failure, or the
/// actor's. The owner's routes answer each failure as its module always has.
#[derive(Debug, thiserror::Error)]
pub(crate) enum AccountError {
/// A passkey could not be renamed or removed.
#[error(transparent)]
Passkey(#[from] PasskeyError),
/// A linked identity could not be unlinked.
#[error(transparent)]
Identity(#[from] FederationError),
/// An email address could not be changed or removed.
#[error(transparent)]
Email(#[from] EmailError),
/// A session could not be signed out.
#[error(transparent)]
Session(#[from] SessionsError),
/// The owner's session ended, or lacks a recent enough passkey confirmation.
#[error(transparent)]
Owner(#[from] SessionError),
/// The administrator or operator may not act on this account.
#[error(transparent)]
Operator(#[from] AdminError),
/// Persistence failed.
#[error(transparent)]
Database(#[from] DatabaseError),
}

impl From<AccountError> for ApiError {
/// Answers as the failure's own module does.
fn from(error: AccountError) -> Self {
match error {
AccountError::Passkey(error) => error.into(),
AccountError::Identity(error) => error.into(),
AccountError::Email(error) => error.into(),
AccountError::Session(error) => error.into(),
AccountError::Owner(error) => error.into(),
AccountError::Operator(error) => error.into(),
AccountError::Database(error) => error.into(),
}
}
}

impl IntoResponse for AccountError {
/// Answers as [`ApiError`] does.
fn into_response(self) -> Response {
ApiError::from(self).into_response()
}
}
265 changes: 265 additions & 0 deletions apps/auth-service/src/account/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
//! Account settings any administrator may also change, as [`AccountService`]
//! operations on a [`Subject`], for changes, or a [`Viewer`], for reads: the
//! account, and who acts on it. The owner's
//! `/account` routes run them with the subject of their session cookie, and the
//! `account` command with the operator at the terminal. The admin dashboard will
//! call them in-process, as an administrator.
//!
//! The rule for sharing: administrators may view, edit and remove, but never add
//! a way to sign in or to receive the account's email, which would let them take
//! the account over. Operations that add one, the owner's own reports, and the
//! owner's clients, which administrators manage through `AdminService`, stay with
//! their modules, for the owner only.

/// Failures of the shared operations.
mod error;
/// The account acted on, and who acts on it.
mod subject;

pub(crate) use error::AccountError;
pub(crate) use subject::{ConfirmedSubject, Subject, Viewer};

use crate::{
emails::EmailView,
federation::FederationError,
history::{HistoryPage, HistoryQuery},
operations::operations,
passkey::Rename,
routes::{emails, federation, history, passkey, sessions},
sessions::{Revoked, SessionItem},
};
use axum::{
Json, Router,
extract::{FromRef, Path, Query, State},
http::StatusCode,
routing::{MethodRouter, delete, get, patch, post},
};
use piquel_common::{
EmailId, PasskeyId, SessionId,
protocol::api::{Identity, Passkey},
};
use piquel_repository::Database;

operations! {
/// Every shared settings operation. The owner's router maps each to its
/// route, and the `account` command has a command for each, which a CLI test
/// checks.
pub(crate) enum AccountOperation {
/// List the account's passkeys.
ListPasskeys,
/// Rename a passkey.
RenamePasskey,
/// Remove a passkey, keeping at least one, and sign the account out
/// elsewhere.
RevokePasskey,
/// List the account's linked social identities.
ListIdentities,
/// Unlink a social identity, and sign the account out elsewhere.
UnlinkIdentity,
/// List the account's email addresses.
ListEmails,
/// Make a verified address the primary one.
MakeEmailPrimary,
/// Remove an email address.
RemoveEmail,
/// List the account's sessions.
ListSessions,
/// Sign one session out.
RevokeSession,
/// Sign every other session out.
RevokeOtherSessions,
/// Page through the account's security history.
ViewHistory,
}
}

/// Every shared settings operation, on any account: what the owner's routes and
/// the `account` command run. A change takes the [`Subject`] it acts on, and a read
/// the [`Viewer`] it shows. Each operation lives with its setting in the passkey,
/// federation, emails, sessions or history module.
#[derive(Clone)]
pub(crate) struct AccountService {
/// Accounts, their settings and events.
pub(crate) database: Database,
}

impl AccountService {
/// Operates on `database`.
pub(crate) const fn new(database: Database) -> Self {
Self { database }
}
}

/// The owner's routes for the shared settings, at `/account`.
#[derive(Clone)]
pub(crate) struct AccountApplication {
/// The operations behind the routes.
service: AccountService,
}

impl FromRef<AccountApplication> for Database {
/// Shares persistence with the session extractors.
fn from_ref(application: &AccountApplication) -> Self {
application.service.database.clone()
}
}

impl AccountApplication {
/// Serves the shared settings of the signed-in owner from `database`.
pub(crate) const fn new(database: Database) -> Self {
Self {
service: AccountService::new(database),
}
}

/// Returns every shared route at its `/account/…` path, with this
/// application as state.
pub(crate) fn routes(self) -> Router {
AccountOperation::ALL
.iter()
.map(|operation| Self::route(*operation))
.fold(Router::new(), |router, (path, method)| {
router.route(path, method)
})
.with_state(self)
}

/// The path and method serving `operation`. Methods on one path merge, here
/// and with the owner-only methods of the same path.
fn route(operation: AccountOperation) -> (&'static str, MethodRouter<Self>) {
type Op = AccountOperation;
match operation {
Op::ListPasskeys => (passkey::LIST, get(Self::passkeys)),
Op::RenamePasskey => (passkey::ITEM, patch(Self::rename_passkey)),
Op::RevokePasskey => (passkey::ITEM, delete(Self::revoke_passkey)),
Op::ListIdentities => (federation::IDENTITIES, get(Self::identities)),
Op::UnlinkIdentity => (federation::IDENTITY, delete(Self::unlink_identity)),
Op::ListEmails => (emails::LIST, get(Self::emails)),
Op::MakeEmailPrimary => (emails::PRIMARY, post(Self::make_primary_email)),
Op::RemoveEmail => (emails::ITEM, delete(Self::remove_email)),
Op::ListSessions => (sessions::LIST, get(Self::sessions)),
Op::RevokeSession => (sessions::ITEM, delete(Self::revoke_session)),
Op::RevokeOtherSessions => (sessions::REVOKE_OTHERS, post(Self::revoke_other_sessions)),
Op::ViewHistory => (history::LIST, get(Self::history)),
}
}

/// Lists the account's active passkeys.
async fn passkeys(
State(app): State<Self>,
viewer: Viewer,
) -> Result<Json<Vec<Passkey>>, AccountError> {
Ok(Json(app.service.passkeys(&viewer).await?))
}

/// Renames a passkey. A name grants nothing, so the owner's session is enough.
async fn rename_passkey(
State(app): State<Self>,
subject: Subject,
Path(id): Path<PasskeyId>,
Json(input): Json<Rename>,
) -> Result<StatusCode, AccountError> {
app.service
.rename_passkey(&subject, id, input.friendly_name)
.await?;
Ok(StatusCode::NO_CONTENT)
}

/// Removes a passkey, keeping at least one.
async fn revoke_passkey(
State(app): State<Self>,
subject: ConfirmedSubject,
Path(id): Path<PasskeyId>,
) -> Result<StatusCode, AccountError> {
app.service.revoke_passkey(&subject, id).await?;
Ok(StatusCode::NO_CONTENT)
}

/// Lists the account's linked social identities.
async fn identities(
State(app): State<Self>,
viewer: Viewer,
) -> Result<Json<Vec<Identity>>, AccountError> {
Ok(Json(app.service.identities(&viewer).await?))
}

/// Unlinks the provider the path names.
async fn unlink_identity(
State(app): State<Self>,
subject: ConfirmedSubject,
Path(provider): Path<String>,
) -> Result<StatusCode, AccountError> {
let provider = provider
.parse()
.map_err(FederationError::UnsupportedProvider)?;
app.service.unlink_identity(&subject, provider).await?;
Ok(StatusCode::NO_CONTENT)
}

/// Lists the account's addresses, primary first.
async fn emails(
State(app): State<Self>,
viewer: Viewer,
) -> Result<Json<Vec<EmailView>>, AccountError> {
Ok(Json(app.service.emails(&viewer).await?))
}

/// Makes a verified address the primary one.
async fn make_primary_email(
State(app): State<Self>,
subject: ConfirmedSubject,
Path(id): Path<EmailId>,
) -> Result<StatusCode, AccountError> {
app.service.make_primary_email(&subject, id).await?;
Ok(StatusCode::NO_CONTENT)
}

/// Removes an address.
async fn remove_email(
State(app): State<Self>,
subject: ConfirmedSubject,
Path(id): Path<EmailId>,
) -> Result<StatusCode, AccountError> {
app.service.remove_email(&subject, id).await?;
Ok(StatusCode::NO_CONTENT)
}

/// Lists the account's active sessions, most recently active first.
async fn sessions(
State(app): State<Self>,
viewer: Viewer,
) -> Result<Json<Vec<SessionItem>>, AccountError> {
Ok(Json(app.service.sessions(&viewer).await?))
}

/// Signs one session out.
async fn revoke_session(
State(app): State<Self>,
subject: Subject,
Path(id): Path<SessionId>,
) -> Result<StatusCode, AccountError> {
app.service.revoke_session(&subject, id).await?;
Ok(StatusCode::NO_CONTENT)
}

/// Signs every other session out, and says how many there were.
async fn revoke_other_sessions(
State(app): State<Self>,
subject: Subject,
) -> Result<Json<Revoked>, AccountError> {
Ok(Json(app.service.revoke_other_sessions(&subject).await?))
}

/// Returns a page of the account's history, newest first.
async fn history(
State(app): State<Self>,
viewer: Viewer,
Query(query): Query<HistoryQuery>,
) -> Result<Json<HistoryPage>, AccountError> {
Ok(Json(app.service.history(&viewer, query.before).await?))
}
}

/// Database-backed scenarios of administrators acting on another account.
#[cfg(test)]
mod tests;
Loading
Loading