From bc2914f06b67c9f4e2a2fd0525259892bef12664 Mon Sep 17 00:00:00 2001 From: "Ioannis T." Date: Thu, 19 Nov 2026 18:08:20 +0100 Subject: [PATCH] desktop: Add an actor profile editor behind the actorRepos lab Co-authored-by: Brandon Oxendine --- desktop/Cargo.lock | 2 + desktop/crates/radicle-tauri/src/commands.rs | 1 + .../radicle-tauri/src/commands/actor.rs | 157 + desktop/crates/radicle-tauri/src/lib.rs | 19 +- desktop/crates/radicle-types/Cargo.toml | 2 + .../radicle-types/bindings/actor/ActorFork.ts | 40 + .../radicle-types/bindings/actor/ActorInfo.ts | 57 + .../radicle-types/bindings/actor/ActorKey.ts | 18 + .../radicle-types/bindings/actor/ActorKind.ts | 7 + .../bindings/actor/ActorProfile.ts | 19 + .../bindings/actor/ActorRevision.ts | 41 + .../bindings/actor/EnrollmentPreview.ts | 18 + .../bindings/actor/ProfileEdit.ts | 35 + .../bindings/actor/ProfileImages.ts | 9 + .../bindings/actor/ProfileLink.ts | 3 + .../bindings/actor/RevisionState.ts | 6 + .../bindings/repo/RepoSummary.ts | 4 + desktop/crates/radicle-types/src/actor.rs | 414 +++ .../radicle-types/src/actor/identity.rs | 820 +++++ .../radicle-types/src/actor/identity/tests.rs | 692 ++++ .../crates/radicle-types/src/actor/profile.rs | 583 ++++ .../radicle-types/src/actor/profile/tests.rs | 550 +++ desktop/crates/radicle-types/src/error.rs | 12 + desktop/crates/radicle-types/src/lib.rs | 3 + desktop/crates/radicle-types/src/repo.rs | 2 + desktop/crates/radicle-types/src/traits.rs | 1 + .../crates/radicle-types/src/traits/actor.rs | 1612 +++++++++ .../radicle-types/src/traits/actor/tests.rs | 3034 +++++++++++++++++ .../crates/radicle-types/src/traits/repo.rs | 34 +- desktop/crates/test-http-api/src/api.rs | 213 +- desktop/src/App.svelte | 3 + desktop/src/components/ActorAvatar.svelte | 97 + desktop/src/components/AddRepoButton.svelte | 13 +- desktop/src/components/AppSidebar.svelte | 4 +- desktop/src/components/Icon.svelte | 9 +- desktop/src/components/IdentityButton.svelte | 26 +- desktop/src/components/SidebarRepoList.svelte | 6 +- desktop/src/lib/hints.ts | 7 +- desktop/src/lib/invoke.ts | 31 +- desktop/src/lib/labs.ts | 9 + desktop/src/lib/projects.ts | 10 + desktop/src/lib/router.ts | 30 +- desktop/src/lib/router/definitions.ts | 63 +- desktop/src/modals/ConfirmModal.svelte | 12 +- desktop/src/modals/ProfileHistory.svelte | 246 ++ desktop/src/modals/ProfileVersion.svelte | 136 + desktop/src/modals/Settings.svelte | 21 + .../src/views/profile/ClosedRevision.svelte | 107 + desktop/src/views/profile/EnrollKey.svelte | 235 ++ .../src/views/profile/ExplorerPreview.svelte | 264 ++ desktop/src/views/profile/HoverCard.svelte | 163 + desktop/src/views/profile/ImagePicker.svelte | 289 ++ desktop/src/views/profile/JoinActor.svelte | 597 ++++ desktop/src/views/profile/KeyChunks.svelte | 56 + desktop/src/views/profile/Keys.svelte | 511 +++ desktop/src/views/profile/Notice.svelte | 132 + .../src/views/profile/PendingRevision.svelte | 332 ++ desktop/src/views/profile/Profile.svelte | 272 ++ .../src/views/profile/ProfileCreated.svelte | 179 + desktop/src/views/profile/ProfileForm.svelte | 965 ++++++ .../src/views/profile/PronounsPicker.svelte | 152 + .../src/views/profile/RetireProfile.svelte | 88 + .../src/views/profile/SeveralProfiles.svelte | 308 ++ desktop/src/views/profile/SplitNotice.svelte | 214 ++ .../src/views/profile/TimezonePicker.svelte | 257 ++ desktop/src/views/profile/actor.ts | 199 ++ desktop/src/views/profile/form.ts | 88 + desktop/tests/e2e/actorRepos.spec.ts | 109 + desktop/tests/e2e/joinActor.spec.ts | 294 ++ desktop/tests/e2e/leaveProfile.spec.ts | 194 ++ desktop/tests/e2e/profileForm.spec.ts | 253 ++ desktop/tests/e2e/profileSplit.spec.ts | 121 + desktop/tests/unit/profileForm.test.ts | 65 + desktop/tests/unit/projects.test.ts | 23 + 74 files changed, 15563 insertions(+), 35 deletions(-) create mode 100644 desktop/crates/radicle-tauri/src/commands/actor.rs create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorFork.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorInfo.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorKey.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorKind.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorProfile.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ActorRevision.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/EnrollmentPreview.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ProfileEdit.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ProfileImages.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/ProfileLink.ts create mode 100644 desktop/crates/radicle-types/bindings/actor/RevisionState.ts create mode 100644 desktop/crates/radicle-types/src/actor.rs create mode 100644 desktop/crates/radicle-types/src/actor/identity.rs create mode 100644 desktop/crates/radicle-types/src/actor/identity/tests.rs create mode 100644 desktop/crates/radicle-types/src/actor/profile.rs create mode 100644 desktop/crates/radicle-types/src/actor/profile/tests.rs create mode 100644 desktop/crates/radicle-types/src/traits/actor.rs create mode 100644 desktop/crates/radicle-types/src/traits/actor/tests.rs create mode 100644 desktop/src/components/ActorAvatar.svelte create mode 100644 desktop/src/lib/projects.ts create mode 100644 desktop/src/modals/ProfileHistory.svelte create mode 100644 desktop/src/modals/ProfileVersion.svelte create mode 100644 desktop/src/views/profile/ClosedRevision.svelte create mode 100644 desktop/src/views/profile/EnrollKey.svelte create mode 100644 desktop/src/views/profile/ExplorerPreview.svelte create mode 100644 desktop/src/views/profile/HoverCard.svelte create mode 100644 desktop/src/views/profile/ImagePicker.svelte create mode 100644 desktop/src/views/profile/JoinActor.svelte create mode 100644 desktop/src/views/profile/KeyChunks.svelte create mode 100644 desktop/src/views/profile/Keys.svelte create mode 100644 desktop/src/views/profile/Notice.svelte create mode 100644 desktop/src/views/profile/PendingRevision.svelte create mode 100644 desktop/src/views/profile/Profile.svelte create mode 100644 desktop/src/views/profile/ProfileCreated.svelte create mode 100644 desktop/src/views/profile/ProfileForm.svelte create mode 100644 desktop/src/views/profile/PronounsPicker.svelte create mode 100644 desktop/src/views/profile/RetireProfile.svelte create mode 100644 desktop/src/views/profile/SeveralProfiles.svelte create mode 100644 desktop/src/views/profile/SplitNotice.svelte create mode 100644 desktop/src/views/profile/TimezonePicker.svelte create mode 100644 desktop/src/views/profile/actor.ts create mode 100644 desktop/src/views/profile/form.ts create mode 100644 desktop/tests/e2e/actorRepos.spec.ts create mode 100644 desktop/tests/e2e/joinActor.spec.ts create mode 100644 desktop/tests/e2e/leaveProfile.spec.ts create mode 100644 desktop/tests/e2e/profileForm.spec.ts create mode 100644 desktop/tests/e2e/profileSplit.spec.ts create mode 100644 desktop/tests/unit/profileForm.test.ts create mode 100644 desktop/tests/unit/projects.test.ts diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index acf0b2262..97699f9a6 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -4825,6 +4825,7 @@ dependencies = [ "infer", "log", "mime-infer", + "multibase", "radicle", "radicle-artifact", "radicle-artifact-client", @@ -4842,6 +4843,7 @@ dependencies = [ "tempfile", "thiserror 2.0.19", "ts-rs", + "unicode-normalization", "url", "which", ] diff --git a/desktop/crates/radicle-tauri/src/commands.rs b/desktop/crates/radicle-tauri/src/commands.rs index ff016c7c3..9aa80bcbd 100644 --- a/desktop/crates/radicle-tauri/src/commands.rs +++ b/desktop/crates/radicle-tauri/src/commands.rs @@ -1,3 +1,4 @@ +pub mod actor; pub mod auth; pub mod cob; pub mod diff; diff --git a/desktop/crates/radicle-tauri/src/commands/actor.rs b/desktop/crates/radicle-tauri/src/commands/actor.rs new file mode 100644 index 000000000..617123b25 --- /dev/null +++ b/desktop/crates/radicle-tauri/src/commands/actor.rs @@ -0,0 +1,157 @@ +use radicle::git; +use radicle::identity::{Did, RepoId}; +use radicle_types::actor::{ + ActorInfo, ActorProfile, ActorRevision, EnrollmentPreview, ProfileEdit, ProfileImages, +}; +use radicle_types::cobs::{CobOptions, PaginatedQuery}; +use radicle_types::error::Error; +use radicle_types::traits::actor::Actor; + +use crate::AppState; +use crate::commands::blocking; + +#[tauri::command] +pub async fn actor(ctx: tauri::State<'_, AppState>) -> Result, Error> { + blocking(ctx, move |ctx| ctx.actor()).await +} + +#[tauri::command] +pub async fn create_actor( + ctx: tauri::State<'_, AppState>, + profile: ActorProfile, + images: ProfileImages, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.create_actor(profile, images, opts)).await +} + +#[tauri::command] +pub async fn update_actor_profile( + ctx: tauri::State<'_, AppState>, + profile: ActorProfile, + images: ProfileImages, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| { + ctx.update_actor_profile(profile, images, opts) + }) + .await +} + +#[tauri::command] +pub async fn joinable_actor( + ctx: tauri::State<'_, AppState>, + rid: RepoId, +) -> Result { + blocking(ctx, move |ctx| ctx.joinable_actor(rid)).await +} + +#[tauri::command] +pub async fn join_actor(ctx: tauri::State<'_, AppState>, rid: RepoId) -> Result { + blocking(ctx, move |ctx| ctx.join_actor(rid)).await +} + +#[tauri::command] +pub async fn decode_enrollment( + ctx: tauri::State<'_, AppState>, + code: String, +) -> Result { + blocking(ctx, move |ctx| ctx.decode_enrollment(code)).await +} + +#[tauri::command] +pub async fn approve_enrollment( + ctx: tauri::State<'_, AppState>, + code: String, + controller: bool, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| { + ctx.approve_enrollment(code, controller, opts) + }) + .await +} + +#[tauri::command] +pub async fn approve_actor_revision( + ctx: tauri::State<'_, AppState>, + id: git::Oid, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.approve_actor_revision(id, opts)).await +} + +#[tauri::command] +pub async fn withdraw_actor_revision( + ctx: tauri::State<'_, AppState>, + id: git::Oid, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.withdraw_actor_revision(id, opts)).await +} + +#[tauri::command] +pub async fn reject_actor_revision( + ctx: tauri::State<'_, AppState>, + id: git::Oid, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.reject_actor_revision(id, opts)).await +} + +#[tauri::command] +pub async fn remove_actor_key( + ctx: tauri::State<'_, AppState>, + did: Did, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.remove_actor_key(did, opts)).await +} + +#[tauri::command] +pub async fn actors_of_key(ctx: tauri::State<'_, AppState>) -> Result, Error> { + blocking(ctx, move |ctx| ctx.actors_of_key()).await +} + +#[tauri::command] +pub async fn closed_actor_revisions( + ctx: tauri::State<'_, AppState>, +) -> Result, Error> { + blocking(ctx, move |ctx| ctx.closed_actor_revisions()).await +} + +#[tauri::command] +pub async fn actor_profile_history( + ctx: tauri::State<'_, AppState>, + skip: Option, + take: Option, +) -> Result>, Error> { + blocking(ctx, move |ctx| ctx.actor_profile_history(skip, take)).await +} + +#[tauri::command] +pub async fn leave_actor( + ctx: tauri::State<'_, AppState>, + rid: RepoId, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.leave_actor(rid, opts)).await +} + +#[tauri::command] +pub async fn cancel_leave( + ctx: tauri::State<'_, AppState>, + rid: RepoId, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.cancel_leave(rid, opts)).await +} + +#[tauri::command] +pub async fn retire_actor( + ctx: tauri::State<'_, AppState>, + rid: RepoId, + opts: CobOptions, +) -> Result { + blocking(ctx, move |ctx| ctx.retire_actor(rid, opts)).await +} diff --git a/desktop/crates/radicle-tauri/src/lib.rs b/desktop/crates/radicle-tauri/src/lib.rs index a1c057d2c..fae9ed1e0 100644 --- a/desktop/crates/radicle-tauri/src/lib.rs +++ b/desktop/crates/radicle-tauri/src/lib.rs @@ -9,7 +9,7 @@ use tauri::menu::{Menu, MenuItem, MenuItemKind}; use tauri::{Emitter, Manager}; use tauri_plugin_log::{Target, TargetKind}; -use commands::{auth, cob, diff, identity, inbox, profile, repo, startup, thread}; +use commands::{actor, auth, cob, diff, identity, inbox, profile, repo, startup, thread}; #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { @@ -135,6 +135,23 @@ pub fn run() { diff::save_diff_to_disk, repo::get_commit_diff, identity::identity_by_repo, + actor::actor, + actor::create_actor, + actor::update_actor_profile, + actor::joinable_actor, + actor::join_actor, + actor::decode_enrollment, + actor::approve_enrollment, + actor::approve_actor_revision, + actor::withdraw_actor_revision, + actor::reject_actor_revision, + actor::remove_actor_key, + actor::actors_of_key, + actor::closed_actor_revisions, + actor::actor_profile_history, + actor::leave_actor, + actor::cancel_leave, + actor::retire_actor, inbox::clear_notifications, inbox::notification_count, inbox::list_notifications, diff --git a/desktop/crates/radicle-types/Cargo.toml b/desktop/crates/radicle-types/Cargo.toml index 79ca7a5ae..aeb58a5b5 100644 --- a/desktop/crates/radicle-types/Cargo.toml +++ b/desktop/crates/radicle-types/Cargo.toml @@ -14,6 +14,7 @@ git2 = { version = "0.21", default-features = false, features = ["vendored-libgi log = { version = "0.4.22" } infer = { version = "0.19.0" } mime-infer = { version = "3.0.0" } +multibase = { version = "0.9.3" } radicle = { version = "0.25", features = ["tor", "i2p"] } radicle-artifact = { version = "0.23" } radicle-artifact-client = { version = "0.23" } @@ -35,6 +36,7 @@ ts-rs = { version = "12.0.1", features = [ "no-serde-warnings", "format", ] } +unicode-normalization = { version = "0.1.25" } url = { version = "2.5.4", features = ["serde"] } which = { version = "8.0.5" } diff --git a/desktop/crates/radicle-types/bindings/actor/ActorFork.ts b/desktop/crates/radicle-types/bindings/actor/ActorFork.ts new file mode 100644 index 000000000..4764d829d --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorFork.ts @@ -0,0 +1,40 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ActorProfile } from "./ActorProfile"; + +/** + * Another controller's version of the profile, on a branch that is not + * behind the one this key reads. + */ +export type ActorFork = { + did: string; + /** + * The commit that controller's branch is on. + */ + head: string; + /** + * Unset when that version holds no profile this Desktop can read. + */ + profile?: ActorProfile; + /** + * The profile as it was where the two versions split. Unset when they + * split at no one commit, or that commit holds no profile this Desktop + * can read in full. + */ + base?: ActorProfile; + /** + * What that version changed since the two split, as a unified diff of + * the profile cleaned as it is for display. Unset when `base` is, or + * that version holds no profile this Desktop can read. + */ + changes?: string; + /** + * That version changed files other than the profile since the two + * split or, when they split at no one commit, holds other files that + * differ from the version shown. A save here leaves those changes out. + */ + otherFiles: boolean; + /** + * That version is from a newer client, so Desktop must not replace it. + */ + profileNewer: boolean; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ActorInfo.ts b/desktop/crates/radicle-types/bindings/actor/ActorInfo.ts new file mode 100644 index 000000000..768e192ed --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorInfo.ts @@ -0,0 +1,57 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ActorFork } from "./ActorFork"; +import type { ActorKey } from "./ActorKey"; +import type { ActorKind } from "./ActorKind"; +import type { ActorProfile } from "./ActorProfile"; +import type { ActorRevision } from "./ActorRevision"; + +/** + * An actor as Desktop shows it: the local one, or one the local key may + * join. + */ +export type ActorInfo = { + rid: string; + kind: ActorKind; + /** + * The founding key first, then the other bound keys, then the + * controllers that are not bound. + */ + keys: Array; + /** + * How many controllers must agree on a profile edit. + */ + threshold: number; + /** + * How many controllers must accept an identity change. + */ + majority: number; + /** + * The payload is from a newer client, so Desktop must not change it. + */ + payloadNewer: boolean; + /** + * Unset when the default branch has no readable profile yet. + */ + profile?: ActorProfile; + /** + * The profile is from a newer client, so Desktop must not rewrite it. + */ + profileNewer: boolean; + /** + * The profile file cannot be read; a save replaces it. + */ + profileUnreadable: boolean; + /** + * The commit the profile was read from. + */ + head?: string; + /** + * Identity changes open for the controllers' votes. + */ + pending: Array; + /** + * The other controllers' versions of the profile that are not behind + * the one shown, when this key publishes alone; a save replaces them. + */ + forks: Array; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ActorKey.ts b/desktop/crates/radicle-types/bindings/actor/ActorKey.ts new file mode 100644 index 000000000..cec9657d7 --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorKey.ts @@ -0,0 +1,18 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * A key of the actor as Desktop shows it. + */ +export type ActorKey = { + did: string; + /** + * The node alias, local to this machine and no part of the profile. + */ + alias?: string; + bound: boolean; + controller: boolean; + /** + * Seconds since the epoch. + */ + addedAt: number; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ActorKind.ts b/desktop/crates/radicle-types/bindings/actor/ActorKind.ts new file mode 100644 index 000000000..251755ce9 --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorKind.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * What the actor repository describes; any other value makes the payload + * invalid. + */ +export type ActorKind = "person" | "agent" | "org"; diff --git a/desktop/crates/radicle-types/bindings/actor/ActorProfile.ts b/desktop/crates/radicle-types/bindings/actor/ActorProfile.ts new file mode 100644 index 000000000..9b7cd7db5 --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorProfile.ts @@ -0,0 +1,19 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ProfileLink } from "./ProfileLink"; + +/** + * The contents of `.radicle/profile.json`. A file of `PROFILE_VERSION` must + * match the schema exactly; a newer one is read for its known fields. + */ +export type ActorProfile = { + version: number; + displayName: string; + fullName?: string; + pronouns?: string; + bio?: string; + location?: string; + timezone?: string; + avatar?: string; + banner?: string; + links?: Array; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ActorRevision.ts b/desktop/crates/radicle-types/bindings/actor/ActorRevision.ts new file mode 100644 index 000000000..3ec18b68b --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ActorRevision.ts @@ -0,0 +1,41 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ActorKey } from "./ActorKey"; +import type { RevisionState } from "./RevisionState"; + +/** + * A change to the actor's identity. One open for votes applies once a + * majority of the controllers accept it. What it adds, removes and lowers is + * told against the identity it was proposed on. + */ +export type ActorRevision = { + id: string; + author: string; + /** + * Seconds since the epoch. + */ + createdAt: number; + /** + * The keys it adds or gives another role, with the roles they get. + */ + added: Array; + removed: Array; + /** + * How many controllers a profile edit needs after the change, if it + * lowers that. + */ + threshold?: number; + /** + * The controllers that accepted it, the author among them. + */ + accepted: Array; + /** + * The controllers that rejected it. The change stays open until it can no + * longer reach a majority. + */ + rejected: Array; + /** + * It changes more than Desktop can show, so Desktop must not sign it. + */ + unreadable: boolean; + state: RevisionState; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/EnrollmentPreview.ts b/desktop/crates/radicle-types/bindings/actor/EnrollmentPreview.ts new file mode 100644 index 000000000..fb33e879f --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/EnrollmentPreview.ts @@ -0,0 +1,18 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * The key an enrollment code would bind, shown before a controller approves + * it. + */ +export type EnrollmentPreview = { + did: string; + /** + * The key's node alias, when this machine knows it. + */ + alias?: string; + /** + * The key already controls the actor, as a recovery key does, and keeps + * that role. + */ + controller: boolean; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ProfileEdit.ts b/desktop/crates/radicle-types/bindings/actor/ProfileEdit.ts new file mode 100644 index 000000000..28edbde10 --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ProfileEdit.ts @@ -0,0 +1,35 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * One version of the profile in the history of the one shown. + */ +export type ProfileEdit = { + commit: string; + /** + * The versions it was saved over: none for the first version, several + * for a save that joined versions that had split. + */ + parents: Array; + /** + * Seconds since the epoch, by the clock of the device that saved it. + */ + savedAt: number; + /** + * The key of the device that saved it, as the commit records it, which + * nothing verifies. Unset when the commit names no key. + */ + author?: string; + /** + * The fields of the profile, by their names in the file, that differ + * from the first of `parents`, or that the first version sets; `avatar` + * and `banner` also when the picture they name changed. Unset when this + * version or that parent holds a profile this Desktop cannot read in + * full. + */ + fields?: Array; + /** + * It is in the history of the profile `actor` shows. Otherwise it is on + * this key's own branch, and waits for the other controllers. + */ + live: boolean; +}; diff --git a/desktop/crates/radicle-types/bindings/actor/ProfileImages.ts b/desktop/crates/radicle-types/bindings/actor/ProfileImages.ts new file mode 100644 index 000000000..b1196935c --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ProfileImages.ts @@ -0,0 +1,9 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * The pictures to save in the repository with a profile, each the base64 of + * an image file: a PNG, JPEG, WebP or GIF of at most 1 MiB for the avatar + * and 2 MiB for the banner. The kind is told from the first bytes of the + * file, and the rest is not decoded: what is saved may not show. + */ +export type ProfileImages = { avatar?: string; banner?: string }; diff --git a/desktop/crates/radicle-types/bindings/actor/ProfileLink.ts b/desktop/crates/radicle-types/bindings/actor/ProfileLink.ts new file mode 100644 index 000000000..597f87dad --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/ProfileLink.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ProfileLink = { url: string; label?: string }; diff --git a/desktop/crates/radicle-types/bindings/actor/RevisionState.ts b/desktop/crates/radicle-types/bindings/actor/RevisionState.ts new file mode 100644 index 000000000..8c17a7274 --- /dev/null +++ b/desktop/crates/radicle-types/bindings/actor/RevisionState.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Where a change to the actor's identity stands. + */ +export type RevisionState = "open" | "accepted" | "rejected" | "lapsed"; diff --git a/desktop/crates/radicle-types/bindings/repo/RepoSummary.ts b/desktop/crates/radicle-types/bindings/repo/RepoSummary.ts index a7c7bd4de..4232c3fa0 100644 --- a/desktop/crates/radicle-types/bindings/repo/RepoSummary.ts +++ b/desktop/crates/radicle-types/bindings/repo/RepoSummary.ts @@ -9,4 +9,8 @@ export type RepoSummary = { * `rad ls --all` shows as "local". */ seeding: boolean; + /** + * The repository is an actor's, a profile and not a project. + */ + actor: boolean; }; diff --git a/desktop/crates/radicle-types/src/actor.rs b/desktop/crates/radicle-types/src/actor.rs new file mode 100644 index 000000000..5ec28c64c --- /dev/null +++ b/desktop/crates/radicle-types/src/actor.rs @@ -0,0 +1,414 @@ +//! Actor repositories: what an actor is and what Desktop shows of one. +//! Nothing here signs or talks to a node; `traits::actor` does. + +use serde::Serialize; +use ts_rs::TS; + +use radicle::git; +use radicle::identity::{Did, RepoId}; +use radicle::node::Alias; + +mod identity; +mod profile; + +// The public interface of the actor rules. +pub use identity::{ + ActorKind, ActorPayload, ClosedIdentityRevision, Enrollment, EnrollmentError, + IdentityDocRevision, OpenIdentityRevision, ResolvedActor, ResolvedKey, RevisionState, + changed_key_entries, changes_only_keys, closed_revisions, enrolled_doc, identity_history, + initial_doc, open_revisions, removed_doc, repo_name, resolve, retired_doc, +}; +pub use profile::{ + ActorProfile, PROFILE_PATH, ProfileFile, ProfileImage, ProfileImages, ProfileLink, + changed_fields, profile_changes, profile_tree, profile_tree_with, read_profile, +}; + +/// Drops the entries of `object` that `fields` does not name, and says whether +/// there were any. +fn retain_fields(object: &mut serde_json::Map, fields: &[&str]) -> bool { + let before = object.len(); + object.retain(|key, _| fields.contains(&key.as_str())); + + object.len() != before +} + +/// Every way an actor operation can fail. Desktop shows the messages to the +/// user as they are. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The profile fails `ActorProfile::validate`; the message names the field. + #[error("Invalid profile: {0}.")] + Profile(String), + + /// The local key is already bound to an actor repository. + #[error("This key already has a profile, {0}.")] + Exists(RepoId), + + /// The key had an actor of that name, retired or left over. + #[error("A profile named {0} is already in storage. Pick another display name.")] + NameTaken(String), + + /// No actor repository binds the local key. + #[error("The profile is no longer in storage.")] + NotFound, + + /// More than one actor binds the local key. + #[error("This key belongs to more than one profile: {}.", .0.iter().map(ToString::to_string).collect::>().join(", "))] + Ambiguous(Vec), + + /// The profile is from a newer client; rewriting it would drop fields. + #[error("A newer version of Desktop has written this profile since the page loaded.")] + ProfileNewer, + + /// The enrollment code cannot be read, or its signature is not the + /// joining key's consent. + #[error("That is not a valid code.")] + InvalidCode, + + /// The enrollment code is for another actor. + #[error("That code is for another profile, {0}.")] + WrongActor(RepoId), + + /// An actor binds the key, and what it is cannot be read. + #[error( + "This key belongs to a profile, {0}, written by a newer app that this version of Desktop cannot read. Update Desktop." + )] + ActorNewer(RepoId), + + /// The identity changed while a change to it was being prepared. + #[error("Your keys changed just now. Check them and try again.")] + Moved, + + /// The identity changed after the joining key consented. + #[error("Your keys changed after that code was created. Create a new one on the other device.")] + Stale, + + /// The key is already bound to the actor. + #[error("That key is already yours.")] + AlreadyBound, + + /// The payload lists as many keys as it can hold. + #[error("You have the most keys a profile can list.")] + Full, + + /// Only a controller can change the identity. + #[error("This device's key cannot change which keys are yours. Use a key that can.")] + NotController, + + /// The actor payload holds more than this client knows; a change would + /// sign what it cannot read. + #[error( + "Your keys hold fields this version of Desktop does not know, so it cannot change them." + )] + PayloadNewer, + + /// The repository is not in storage. + #[error("The profile {0} is not on this device.")] + NotFetched(RepoId), + + /// The copy in storage has no head and none can be computed, so the node + /// fetches nothing more into it. + #[error( + "This device fetched the profile while two of its devices had saved different versions, and it cannot update that copy. Save the profile on a device that controls it, then fetch it again here." + )] + CopyStuck(RepoId), + + /// The user blocked the repository, so nothing here seeds it. + #[error("You blocked {0}. Unblock it first, then add this device.")] + Blocked(RepoId), + + /// The repository is not an individual actor that a key can join. + #[error("{0} is not a profile a device can be added to.")] + NotJoinable(RepoId), + + /// Only the key that proposed an identity change can withdraw it. + #[error("Only the key that proposed this change can withdraw it.")] + NotAuthor, + + /// No open identity change has this id. + #[error("The change {0} is no longer open.")] + RevisionNotFound(git::Oid), + + /// A key cannot remove itself from the actor. + #[error("This device cannot revoke its own key. Revoke it from another controller.")] + RemoveSelf, + + /// The actor has no such key. + #[error("The key {0} is no longer part of your profile.")] + KeyNotFound(Did), + + /// No live individual actor of that id binds the local key. + #[error("This device's key is not in the profile {0}.")] + NotBound(RepoId), + + /// The local key is the actor's only controller, so its removal would + /// leave the actor without one. + #[error("This device's key is the only controller of {0}. That profile can only be retired.")] + OnlyController(RepoId), + + /// The local key does not control the actor, so it has no vote on its own + /// removal; the controllers are the keys that have. + #[error("This device's key cannot approve changes in {rid}. A device that controls that profile has to revoke it: {}.", .controllers.iter().map(ToString::to_string).collect::>().join(", "))] + LeaveNeedsController { rid: RepoId, controllers: Vec }, + + /// The local key has voted to leave another actor, and that change is + /// still open. + #[error( + "This device is already leaving {0}. Cancel that leave first, or wait until it is approved or rejected." + )] + Leaving(RepoId), + + /// No open change by which the local key leaves the actor holds its vote. + #[error("This device is not leaving {0}.")] + NotLeaving(RepoId), + + /// Another key proposed the removal the local key accepted, and only the + /// proposer withdraws a change. + #[error( + "Another device proposed removing this one from {0}, so only that device can withdraw it." + )] + LeaveNotOwn(RepoId), + + /// Retiring the actor would leave the local key with none. + #[error("{0} is the only profile this device is in, so it is not retired from here.")] + LastActor(RepoId), + + /// Other keys control the actor too, and Desktop has no way for them to + /// sign a retirement. + #[error( + "Other devices control {0} too, so this device cannot retire it alone. Leave it instead." + )] + RetireShared(RepoId), + + /// This key already voted on the identity change. + #[error("This key already voted on that change.")] + AlreadyVoted, + + /// This key already accepted another change at the same identity version. + #[error("This key already approved another change; that one has to be settled first.")] + VotedElsewhere, + + /// The change does more than Desktop can show, so the user cannot vote on it. + #[error("This change does more than Desktop can show, so it cannot be signed here.")] + RevisionUnreadable, + + /// The edit is on this key's branch, signed, and announced if the node + /// runs, but the controllers' branches have split. + #[error( + "Saved under this key only. The profile did not update because its controllers' copies have diverged. Open the profile on another device that controls it, once it has synced, and save there." + )] + Diverged, + + #[error(transparent)] + Repository(#[from] radicle::storage::RepositoryError), + #[error("the identity revision {0} is missing")] + Missing(git::Oid), + #[error("the identity document has no actor payload with keys")] + Payload, + #[error(transparent)] + Doc(#[from] radicle::identity::doc::DocError), + #[error(transparent)] + Project(#[from] radicle::identity::project::ProjectError), + #[error(transparent)] + Branch(#[from] git::fmt::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), + #[error(transparent)] + Git(#[from] git::raw::Error), +} + +impl Error { + /// The code the frontend branches on; every other error shows its message. + pub const fn code(&self) -> &'static str { + match self { + Self::Exists(_) => "ActorError.Exists", + Self::Ambiguous(_) => "ActorError.Ambiguous", + Self::NotController => "ActorError.NotController", + Self::PayloadNewer => "ActorError.PayloadNewer", + Self::NotFetched(_) => "ActorError.NotFetched", + Self::CopyStuck(_) => "ActorError.CopyStuck", + _ => "UnknownError", + } + } +} + +/// A key of the actor as Desktop shows it. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ActorKey { + #[ts(as = "String")] + pub did: Did, + /// The node alias, local to this machine and no part of the profile. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(as = "Option", optional)] + pub alias: Option, + pub bound: bool, + pub controller: bool, + /// Seconds since the epoch. + #[ts(type = "number")] + pub added_at: i64, +} + +/// An actor as Desktop shows it: the local one, or one the local key may +/// join. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ActorInfo { + #[ts(as = "String")] + pub rid: RepoId, + pub kind: ActorKind, + /// The founding key first, then the other bound keys, then the + /// controllers that are not bound. + pub keys: Vec, + /// How many controllers must agree on a profile edit. + pub threshold: usize, + /// How many controllers must accept an identity change. + pub majority: usize, + /// The payload is from a newer client, so Desktop must not change it. + pub payload_newer: bool, + /// Unset when the default branch has no readable profile yet. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub profile: Option, + /// The profile is from a newer client, so Desktop must not rewrite it. + pub profile_newer: bool, + /// The profile file cannot be read; a save replaces it. + pub profile_unreadable: bool, + /// The commit the profile was read from. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(as = "Option", optional)] + pub head: Option, + /// Identity changes open for the controllers' votes. + pub pending: Vec, + /// The other controllers' versions of the profile that are not behind + /// the one shown, when this key publishes alone; a save replaces them. + pub forks: Vec, +} + +/// Another controller's version of the profile, on a branch that is not +/// behind the one this key reads. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ActorFork { + #[ts(as = "String")] + pub did: Did, + /// The commit that controller's branch is on. + #[ts(as = "String")] + pub head: git::Oid, + /// Unset when that version holds no profile this Desktop can read. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub profile: Option, + /// The profile as it was where the two versions split. Unset when they + /// split at no one commit, or that commit holds no profile this Desktop + /// can read in full. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub base: Option, + /// What that version changed since the two split, as a unified diff of + /// the profile cleaned as it is for display. Unset when `base` is, or + /// that version holds no profile this Desktop can read. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub changes: Option, + /// That version changed files other than the profile since the two + /// split or, when they split at no one commit, holds other files that + /// differ from the version shown. A save here leaves those changes out. + pub other_files: bool, + /// That version is from a newer client, so Desktop must not replace it. + pub profile_newer: bool, +} + +/// A change to the actor's identity. One open for votes applies once a +/// majority of the controllers accept it. What it adds, removes and lowers is +/// told against the identity it was proposed on. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ActorRevision { + #[ts(as = "String")] + pub id: git::Oid, + #[ts(as = "String")] + pub author: Did, + /// Seconds since the epoch. + #[ts(type = "number")] + pub created_at: i64, + /// The keys it adds or gives another role, with the roles they get. + pub added: Vec, + #[ts(as = "Vec")] + pub removed: Vec, + /// How many controllers a profile edit needs after the change, if it + /// lowers that. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub threshold: Option, + /// The controllers that accepted it, the author among them. + #[ts(as = "Vec")] + pub accepted: Vec, + /// The controllers that rejected it. The change stays open until it can no + /// longer reach a majority. + #[ts(as = "Vec")] + pub rejected: Vec, + /// It changes more than Desktop can show, so Desktop must not sign it. + pub unreadable: bool, + pub state: RevisionState, +} + +/// One version of the profile in the history of the one shown. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ProfileEdit { + #[ts(as = "String")] + pub commit: git::Oid, + /// The versions it was saved over: none for the first version, several + /// for a save that joined versions that had split. + #[ts(as = "Vec")] + pub parents: Vec, + /// Seconds since the epoch, by the clock of the device that saved it. + #[ts(type = "number")] + pub saved_at: i64, + /// The key of the device that saved it, as the commit records it, which + /// nothing verifies. Unset when the commit names no key. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(as = "Option")] + #[ts(optional)] + pub author: Option, + /// The fields of the profile, by their names in the file, that differ + /// from the first of `parents`, or that the first version sets; `avatar` + /// and `banner` also when the picture they name changed. Unset when this + /// version or that parent holds a profile this Desktop cannot read in + /// full. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub fields: Option>, + /// It is in the history of the profile `actor` shows. Otherwise it is on + /// this key's own branch, and waits for the other controllers. + pub live: bool, +} + +/// The key an enrollment code would bind, shown before a controller approves +/// it. +#[derive(Clone, Debug, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct EnrollmentPreview { + #[ts(as = "String")] + pub did: Did, + /// The key's node alias, when this machine knows it. + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(as = "Option", optional)] + pub alias: Option, + /// The key already controls the actor, as a recovery key does, and keeps + /// that role. + pub controller: bool, +} diff --git a/desktop/crates/radicle-types/src/actor/identity.rs b/desktop/crates/radicle-types/src/actor/identity.rs new file mode 100644 index 000000000..9f51d26a8 --- /dev/null +++ b/desktop/crates/radicle-types/src/actor/identity.rs @@ -0,0 +1,820 @@ +//! The identity side of an actor repository: its payload, how a key consents +//! to join, and how the identity history resolves to an actor. + +use std::collections::BTreeMap; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use radicle::cob; +use radicle::crypto::Signature; +use radicle::crypto::signature::Verifier as _; +use radicle::git; +use radicle::identity::doc::{Payload, PayloadId}; +use radicle::identity::project::ProjectName; +use radicle::identity::{Did, Doc, Project, RepoId, Visibility}; +use radicle::storage::ReadRepository; + +use super::{Error, retain_fields}; + +/// The identity payload that marks a repository as an actor repository. +const PAYLOAD_ID: &str = "dev.radicle.actor"; +/// The value in the payload's `keys` map that marks the founding key. +const ROOT_KEY: &str = "root"; +/// The prefix of the statement a key signs to consent to joining an actor. +const CONSENT_PREFIX: &str = "rad-actor-consent-v1"; +const PAYLOAD_VERSION: u32 = 1; +/// The most keys a payload may bind. +const MAX_KEYS: usize = 255; +/// The most actor repositories a payload may say it replaces. +const MAX_SUPERSEDES: usize = 16; +/// The fields of a payload of `PAYLOAD_VERSION`. +const PAYLOAD_FIELDS: &[&str] = &[ + "version", + "type", + "keys", + "migrations", + "supersededBy", + "retired", + "supersedes", +]; +/// The fields of a migration in such a payload. +const MIGRATION_FIELDS: &[&str] = &["from", "signature"]; +/// The longest project name, in bytes. +const MAX_REPO_NAME: usize = 255; + +fn payload_id() -> PayloadId { + PayloadId::from_str(PAYLOAD_ID).expect("PAYLOAD_ID is a valid payload id") +} + +/// What the actor repository describes; any other value makes the payload +/// invalid. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "actor/")] +pub enum ActorKind { + #[default] + Person, + Agent, + Org, +} + +impl ActorKind { + pub fn is_individual(self) -> bool { + matches!(self, Self::Person | Self::Agent) + } +} + +/// A key's signed claim that it moved here from another actor. +/// Desktop copies it into every new revision as it is and never checks or acts on it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Migration { + from: String, + signature: String, +} + +/// The `dev.radicle.actor` payload, read for the fields of `PAYLOAD_VERSION`. +/// A payload of that version must match its schema in them. What else a +/// payload holds, at any version, is left out, and such a payload is never +/// written back, see `is_newer`. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ActorPayload { + pub version: u32, + #[serde(rename = "type", default)] + pub kind: ActorKind, + /// Bound keys: the founding key maps to `root`, every other key to its + /// consent signature. + #[serde(default)] + pub keys: BTreeMap, + /// By the DID of the key that moved. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + migrations: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub superseded_by: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub retired: bool, + /// The actor repositories this one replaces; a move counts only if the old + /// one names this one in `superseded_by`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub supersedes: Vec, + /// The document held fields `PAYLOAD_VERSION` does not define. + #[serde(skip)] + undefined_fields: bool, + /// The payload is of a newer version and gives its kind, its keys, or + /// whether it has ended, in a form this version cannot read. + #[serde(skip)] + unsure: bool, +} + +impl ActorPayload { + /// The payload an actor is created with. + fn founding(did: Did) -> Self { + Self { + version: PAYLOAD_VERSION, + kind: ActorKind::Person, + keys: BTreeMap::from([(did, ROOT_KEY.to_string())]), + migrations: BTreeMap::new(), + superseded_by: None, + retired: false, + supersedes: Vec::new(), + undefined_fields: false, + unsure: false, + } + } + + /// Whether `doc` carries the payload at all, valid or not. + pub fn marks(doc: &Doc) -> bool { + doc.payload().contains_key(&payload_id()) + } + + /// The valid payload of `doc`, if any, see `ActorPayload`. A payload of a + /// newer version is always one. + pub fn of(doc: &Doc) -> Option { + let payload = doc.payload().get(&payload_id())?; + let version = payload.get("version")?.as_u64()?; + if version > u64::from(PAYLOAD_VERSION) { + return Some(Self::of_newer(version, payload.as_object()?)); + } + + let mut value = (**payload).clone(); + let object = value.as_object_mut()?; + if object.get("supersededBy").is_some_and(|rid| rid.is_null()) { + return None; + } + + let mut undefined_fields = retain_fields(object, PAYLOAD_FIELDS); + if let Some(migrations) = object.get_mut("migrations").and_then(|m| m.as_object_mut()) { + for migration in migrations.values_mut().filter_map(|m| m.as_object_mut()) { + undefined_fields |= retain_fields(migration, MIGRATION_FIELDS); + } + } + + let mut payload: Self = serde_json::from_value(value).ok()?; + payload.undefined_fields = undefined_fields; + // The limits are those of `PAYLOAD_VERSION`'s schema. + let valid = payload.version >= 1 + && payload.keys.len() <= MAX_KEYS + && payload.supersedes.len() <= MAX_SUPERSEDES + && payload + .migrations + .keys() + .all(|did| did.starts_with("did:key:")); + + valid.then_some(payload) + } + + /// A payload of a newer `version`, read for what this version knows of + /// it. It is an actor's whatever it holds, and it is never written back. + /// A value this version cannot read counts as absent; where that leaves + /// the actor's kind, its ending or its keys open, the payload is `unsure`. + fn of_newer(version: u64, object: &serde_json::Map) -> Self { + let kind = object + .get("type") + .map(|kind| serde_json::from_value(kind.clone()).ok()); + let retired = object.get("retired").map(|retired| retired.as_bool()); + let superseded_by = object + .get("supersededBy") + .filter(|rid| !rid.is_null()) + .map(|rid| rid.as_str().and_then(|rid| rid.parse().ok())); + + // Entry by entry: the keys this version reads keep their binding. One + // it cannot read still leaves the payload `unsure`, so the actor is + // shown to none of them as theirs. + let entries = object.get("keys").and_then(|keys| keys.as_object()); + let keys = entries + .into_iter() + .flatten() + .filter_map(|(did, binding)| Some((did.parse().ok()?, binding.as_str()?.to_string()))) + .collect::>(); + let keys_read = entries.is_some_and(|entries| entries.len() == keys.len()); + let supersedes = object + .get("supersedes") + .and_then(|rids| rids.as_array()) + .into_iter() + .flatten() + .filter_map(|rid| rid.as_str()?.parse().ok()) + .collect(); + + Self { + version: u32::try_from(version).unwrap_or(u32::MAX), + unsure: kind == Some(None) + || retired == Some(None) + || superseded_by == Some(None) + || !keys_read, + kind: kind.flatten().unwrap_or_default(), + keys, + // Nothing here acts on the migrations. + migrations: BTreeMap::new(), + superseded_by: superseded_by.flatten(), + retired: retired.flatten().unwrap_or_default(), + supersedes, + undefined_fields: false, + } + } + + /// Whether the payload holds more than this version knows: it is of a + /// newer version, or holds fields `PAYLOAD_VERSION` does not define. Such + /// a payload must not be written back. + pub(super) fn is_newer(&self) -> bool { + self.version > PAYLOAD_VERSION || self.undefined_fields + } +} + +/// One version of a repository's identity document. +#[derive(Clone, Debug)] +pub struct IdentityDocRevision { + pub commit: git::Oid, + /// When the revision was committed, in seconds since the epoch. + pub time: i64, + pub doc: Doc, +} + +impl From<&cob::identity::Revision> for IdentityDocRevision { + fn from(revision: &cob::identity::Revision) -> Self { + Self { + commit: revision.id, + time: revision.timestamp.as_secs() as i64, + doc: revision.doc.clone(), + } + } +} + +/// What the identity history of an actor repository establishes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResolvedActor { + pub kind: ActorKind, + /// Every key of the actor: the founding key first, then the other bound + /// keys, then the controllers that are not bound. + pub keys: Vec, + /// The payload is newer than `PAYLOAD_VERSION`, so it must not be written + /// back. + pub payload_newer: bool, + /// The payload gives the actor's kind, its keys, or whether it has ended, + /// in a form this version cannot read, so it is not known to be live. + pub unsure: bool, + /// The actor has ended with no successor. + pub retired: bool, + /// The actor repository that replaces this one, as this actor claims it. + pub superseded_by: Option, +} + +impl ResolvedActor { + /// The keys that act as the actor: their activity shows as the actor's. + pub fn bound_keys(&self) -> impl Iterator + '_ { + self.keys.iter().filter(|k| k.bound).map(|k| k.did) + } + + /// Whether the actor is known to be a person or an agent, neither + /// retired nor superseded; only such an actor can be joined or acted as. + pub fn is_live_individual(&self) -> bool { + self.kind.is_individual() && !self.retired && self.superseded_by.is_none() && !self.unsure + } +} + +/// A key of the actor and its roles. A key can be bound, a controller, or both. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResolvedKey { + pub did: Did, + /// Listed under `keys` with a valid consent, or the founding key. + pub bound: bool, + /// A delegate of the identity document. + pub controller: bool, + /// When the revision that gave the key its current role was committed. + pub added_at: i64, +} + +/// The message a key signs to consent to joining the actor at `rid`. `parent` +/// ties it to one identity revision, so it cannot be reused. +fn consent_message(rid: RepoId, did: Did, parent: git::Oid) -> String { + format!("{CONSENT_PREFIX} {rid} {did} {parent}") +} + +/// The actor that `rid`'s identity history describes, or `None` if it is not +/// an actor's. +pub fn resolve(rid: RepoId, history: &[IdentityDocRevision]) -> Option { + let root = history.first()?; + let current = history.last()?; + ActorPayload::of(&root.doc)?; + let mut delegates = root.doc.delegates().iter(); + let founding_key = match (delegates.next(), delegates.next()) { + (Some(founding_key), None) => *founding_key, + _ => return None, + }; + let current_payload = ActorPayload::of(¤t.doc)?; + // Each revision's raw `keys`, indexed like `history`, read even where the + // payload is not. A consent from before a key's removal does not count + // once the key comes back. + let keys_by_revision = history + .iter() + .map(|revision| raw_keys(revision.doc.payload())) + .collect::>(); + + let mut keys = Vec::new(); + for (did, binding) in ¤t_payload.keys { + // The revision that introduced the entry: the latest one where it is + // present and differs from its parent's. + let mut introduced = history.len() - 1; + while introduced > 0 + && keys_by_revision[introduced - 1] + .and_then(|keys| keys.get(&did.to_string())) + .and_then(serde_json::Value::as_str) + .is_some_and(|previous| previous == binding) + { + introduced -= 1; + } + let bound = if introduced == 0 { + binding == ROOT_KEY && *did == founding_key + } else { + let parent = history[introduced - 1].commit; + consent_signature(binding) + .is_some_and(|signature| consents(rid, *did, parent, &signature)) + }; + if bound { + keys.push(ResolvedKey { + did: *did, + bound: true, + controller: current.doc.is_delegate(did), + added_at: history[introduced].time, + }); + } + } + keys.sort_by_key(|key| (key.did != founding_key, key.did)); + for did in current.doc.delegates().iter() { + if keys.iter().any(|key| key.did == *did) { + continue; + } + // The revision that last made the key a delegate; if it was removed + // and added back, the one that added it back. + let mut introduced = history.len() - 1; + while introduced > 0 && history[introduced - 1].doc.is_delegate(did) { + introduced -= 1; + } + keys.push(ResolvedKey { + did: *did, + bound: false, + controller: true, + added_at: history[introduced].time, + }); + } + + Some(ResolvedActor { + kind: current_payload.kind, + keys, + payload_newer: current_payload.is_newer(), + unsure: current_payload.unsure, + retired: current_payload.retired, + superseded_by: current_payload.superseded_by, + }) +} + +/// Every accepted version of `repo`'s identity document, oldest first, each +/// built on the one before it. +pub fn identity_history( + repo: &R, +) -> Result, Error> { + let identity = cob::identity::Identity::load(repo)?; + let mut history = Vec::new(); + let mut next = Some(identity.current); + while let Some(id) = next { + let revision = identity.revision(&id).ok_or(Error::Missing(id))?; + history.push(IdentityDocRevision::from(revision)); + next = revision.parent; + } + history.reverse(); + Ok(history) +} + +/// A proposed change to the actor's identity that controllers are still +/// voting on. +#[derive(Clone, Debug)] +pub struct OpenIdentityRevision { + pub id: git::Oid, + pub author: Did, + /// When it was proposed, in seconds since the epoch. + pub time: i64, + /// The identity document it proposes. + pub doc: Doc, + /// The controllers that accepted it, the author included. + pub accepted: Vec, + /// The controllers that rejected it. + pub rejected: Vec, + /// The actor if the change is accepted; `None` if it would no longer be + /// one. + pub resolved: Option, +} + +/// The changes to `repo`'s identity still open for votes, given its `history`. +pub fn open_revisions( + repo: &R, + rid: RepoId, + history: &[IdentityDocRevision], +) -> Result, Error> { + let identity = cob::identity::Identity::load(repo)?; + let open = identity + .revisions() + .filter(|revision| revision.is_active() && revision.parent == Some(identity.current)) + .map(|revision| { + let mut proposed = history.to_vec(); + proposed.push(IdentityDocRevision::from(revision)); + OpenIdentityRevision { + id: revision.id, + author: *revision.author.id(), + time: revision.timestamp.as_secs() as i64, + doc: revision.doc.clone(), + accepted: revision.accepted().collect(), + rejected: revision.rejected().collect(), + resolved: resolve(rid, &proposed), + } + }) + .collect(); + Ok(open) +} + +/// Where a change to the actor's identity stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, ts_rs::TS)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +#[ts(export_to = "actor/")] +pub enum RevisionState { + /// The controllers are still voting on it. + Open, + /// A majority of the controllers accepted it, and it applied. + Accepted, + /// A majority of the controllers rejected it. + Rejected, + /// It can no longer apply: another change was accepted first, or the + /// change it was built on was rejected. + Lapsed, +} + +/// A change to the actor's identity that `open_revisions` does not give, or +/// the identity's first version. +#[derive(Clone, Debug)] +pub struct ClosedIdentityRevision { + pub id: git::Oid, + pub author: Did, + /// When it was proposed, in seconds since the epoch. + pub time: i64, + /// The identity document it proposed. + pub doc: Doc, + pub accepted: Vec, + pub rejected: Vec, + pub state: RevisionState, + /// The document it was proposed on, with the actor that one gave if it + /// gave one; `None` for the first version. + pub before: Option<(Doc, Option)>, + /// The actor with the change applied; `None` if it would not be one. + pub after: Option, +} + +/// Every change to `repo`'s identity but those `open_revisions` gives, newest +/// first, the first version last: the ones that ended, and one still open +/// that waits on another open change. A change its author withdrew is not +/// among them: the identity keeps none it can list. Resolves the actor once +/// for each change and once for the version it was proposed on. +pub fn closed_revisions( + repo: &R, + rid: RepoId, +) -> Result, Error> { + use cob::identity::{RejectedBy, State}; + + let identity = cob::identity::Identity::load(repo)?; + + // The versions a change builds on, root first, whether or not they were + // accepted. + let line = |from: Option| { + let mut line = Vec::new(); + let mut next = from; + + while let Some(id) = next { + let revision = identity.revision(&id).ok_or(Error::Missing(id))?; + line.push(IdentityDocRevision::from(revision)); + next = revision.parent; + } + line.reverse(); + + Ok::<_, Error>(line) + }; + + let mut closed = Vec::new(); + + for revision in identity.revisions() { + let state = match revision.state { + State::Active if revision.parent == Some(identity.current) => continue, + State::Active => RevisionState::Open, + State::Accepted => RevisionState::Accepted, + State::Rejected(RejectedBy::Vote) => RevisionState::Rejected, + State::Rejected(RejectedBy::Sibling(_) | RejectedBy::Parent) => RevisionState::Lapsed, + State::Redacted(_) => continue, + }; + + let mut proposed = line(revision.parent)?; + let before = proposed + .last() + .map(|parent| (parent.doc.clone(), resolve(rid, &proposed))); + proposed.push(IdentityDocRevision::from(revision)); + + closed.push(ClosedIdentityRevision { + id: revision.id, + author: *revision.author.id(), + time: revision.timestamp.as_secs() as i64, + doc: revision.doc.clone(), + accepted: revision.accepted().collect(), + rejected: revision.rejected().collect(), + state, + before, + after: resolve(rid, &proposed), + }); + } + closed.reverse(); + + Ok(closed) +} + +const ENROLLMENT_PREFIX: &str = "rad-enroll:"; +/// The code's version, which is the consent statement's. +const ENROLLMENT_VERSION: u8 = 0x01; +const ENROLLMENT_LEN: usize = 1 + 20 + 32 + 20 + 64; + +/// A key's consent to joining an actor, as the joining key hands it to a +/// controller. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Enrollment { + pub rid: RepoId, + pub did: Did, + /// The identity revision the consent is anchored to. + pub parent: git::Oid, + pub signature: Signature, +} + +impl Enrollment { + /// The consent of `signer`'s key to joining `rid` on top of `parent`. + pub fn sign(rid: RepoId, parent: git::Oid, signer: &impl radicle::crypto::Signer) -> Self { + let did = Did::from(*signer.public_key()); + let signature = signer.sign(consent_message(rid, did, parent).as_bytes()); + Self { + rid, + did, + parent, + signature, + } + } + + /// The value of the key's entry under the payload's `keys`. + pub fn consent(&self) -> String { + multibase::encode(multibase::Base::Base58Btc, self.signature.to_bytes()) + } + + /// Whether the signature is the key's consent. + pub fn verifies(&self) -> bool { + consents(self.rid, self.did, self.parent, &self.signature) + } + + /// The code the joining key shows: `rad-enroll:` and the enrollment in + /// base58. + pub fn encode(&self) -> String { + let mut bytes = Vec::with_capacity(ENROLLMENT_LEN); + bytes.push(ENROLLMENT_VERSION); + bytes.extend_from_slice(&sha1(&self.rid)); + bytes.extend_from_slice(self.did.as_ref()); + bytes.extend_from_slice(&sha1(&self.parent)); + bytes.extend_from_slice(&self.signature.to_bytes()); + format!( + "{ENROLLMENT_PREFIX}{}", + multibase::encode(multibase::Base::Base58Btc, bytes) + ) + } + + /// The enrollment in a code from `encode`, ignoring whitespace. It does not + /// check the signature; see `verifies`. + pub fn decode(code: &str) -> Result { + let code = code.split_whitespace().collect::(); + let encoded = code + .strip_prefix(ENROLLMENT_PREFIX) + .ok_or(EnrollmentError::Prefix)?; + let (base, bytes) = multibase::decode(encoded).map_err(|_| EnrollmentError::Encoding)?; + if base != multibase::Base::Base58Btc { + return Err(EnrollmentError::Encoding); + } + let Some((&version, rest)) = bytes.split_first() else { + return Err(EnrollmentError::Length); + }; + if version != ENROLLMENT_VERSION { + return Err(EnrollmentError::Version(version)); + } + if bytes.len() != ENROLLMENT_LEN { + return Err(EnrollmentError::Length); + } + let (rid, rest) = rest.split_at(20); + let (key, rest) = rest.split_at(32); + let (parent, signature) = rest.split_at(20); + let oid = + |bytes: &[u8]| git::Oid::from_sha1(bytes.try_into().expect("the slice is 20 bytes")); + let key: [u8; 32] = key.try_into().expect("the slice is 32 bytes"); + Ok(Self { + rid: RepoId::from(oid(rid)), + did: Did::from(radicle::crypto::PublicKey::from(key)), + parent: oid(parent), + signature: Signature::from_slice(signature).map_err(|_| EnrollmentError::Encoding)?, + }) + } +} + +fn sha1(oid: &git::Oid) -> [u8; 20] { + oid.into_sha1() + .expect("version 1 codes carry SHA-1 object ids") +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum EnrollmentError { + #[error("an enrollment code starts with {ENROLLMENT_PREFIX}")] + Prefix, + #[error("the enrollment code is not valid base58")] + Encoding, + #[error("the enrollment code has the wrong length")] + Length, + #[error("the enrollment code has version {0}, which this version does not know")] + Version(u8), +} + +/// The actor payload's `keys` as raw JSON, so an edit changes those entries +/// and leaves the rest of the payload as it is. +fn raw_keys( + payloads: &BTreeMap, +) -> Option<&serde_json::Map> { + payloads + .get(&payload_id()) + .and_then(|payload| payload.as_object()) + .and_then(|payload| payload.get("keys")) + .and_then(|keys| keys.as_object()) +} + +/// `raw_keys`, for editing. +fn raw_keys_mut( + payloads: &mut BTreeMap, +) -> Option<&mut serde_json::Map> { + payloads + .get_mut(&payload_id()) + .and_then(|payload| payload.as_object_mut()) + .and_then(|payload| payload.get_mut("keys")) + .and_then(|keys| keys.as_object_mut()) +} + +/// `doc` with the enrolling key added to the payload's `keys`, and to the +/// delegates if `controller` is set. A delegate stays one. `Full` if the +/// payload has the most keys it can. +pub fn enrolled_doc(doc: &Doc, enrollment: &Enrollment, controller: bool) -> Result { + let mut raw = doc.clone().edit(); + let keys = raw_keys_mut(&mut raw.payload).ok_or(Error::Payload)?; + keys.insert( + enrollment.did.to_string(), + serde_json::Value::String(enrollment.consent()), + ); + if keys.len() > MAX_KEYS { + return Err(Error::Full); + } + if controller && !raw.delegates.contains(&enrollment.did) { + raw.delegates.push(enrollment.did); + } + Ok(Doc::try_from(raw)?) +} + +/// `doc` without `did` in the payload's `keys` or the delegates, with the +/// threshold lowered to fit the delegates left. +pub fn removed_doc(doc: &Doc, did: &Did) -> Result { + let mut raw = doc.clone().edit(); + raw_keys_mut(&mut raw.payload) + .ok_or(Error::Payload)? + .remove(&did.to_string()); + raw.delegates.retain(|delegate| delegate != did); + raw.threshold = raw.threshold.min(raw.delegates.len()); + Ok(Doc::try_from(raw)?) +} + +/// `doc` with `retired` set in the actor payload and nothing else changed. +pub fn retired_doc(doc: &Doc) -> Result { + let mut raw = doc.clone().edit(); + raw.payload + .get_mut(&payload_id()) + .and_then(|payload| payload.as_object_mut()) + .ok_or(Error::Payload)? + .insert("retired".into(), true.into()); + + Ok(Doc::try_from(raw)?) +} + +/// Whether `proposed` changes only the actor's keys and the delegates, which +/// is all Desktop shows of a change. The threshold may only drop to fit the +/// delegates left. +pub fn changes_only_keys(doc: &Doc, proposed: &Doc) -> bool { + let fitted = doc.threshold().min(proposed.delegates().len()); + let without_keys = |doc: &Doc| { + let mut raw = doc.clone().edit(); + // The field goes whole, so an empty map and a missing one read alike. + if let Some(payload) = raw + .payload + .get_mut(&payload_id()) + .and_then(|payload| payload.as_object_mut()) + { + payload.remove("keys"); + } + raw.delegates.clear(); + raw.threshold = 0; + raw + }; + proposed.threshold() == fitted && without_keys(doc) == without_keys(proposed) +} + +/// The keys whose entry under the payload's `keys` differs between `doc` and +/// `proposed`. +pub fn changed_key_entries(doc: &Doc, proposed: &Doc) -> Vec { + let entries = |doc: &Doc| raw_keys(doc.payload()).cloned().unwrap_or_default(); + let (before, after) = (entries(doc), entries(proposed)); + let mut changed = before + .keys() + .chain(after.keys()) + .filter(|key| before.get(*key) != after.get(*key)) + .cloned() + .collect::>(); + changed.sort(); + changed.dedup(); + changed +} + +/// The signature in a `keys` entry, which must be multibase base58btc. +fn consent_signature(value: &str) -> Option { + let (multibase::Base::Base58Btc, bytes) = multibase::decode(value).ok()? else { + return None; + }; + Signature::from_slice(&bytes).ok() +} + +/// Whether `signature` is `did`'s consent to joining `rid` on top of `parent`. +fn consents(rid: RepoId, did: Did, parent: git::Oid, signature: &Signature) -> bool { + let Ok(key) = radicle::crypto::VerifyingKey::try_from(&*did) else { + return false; + }; + key.verify(consent_message(rid, did, parent).as_bytes(), signature) + .is_ok() +} + +/// The repository name for a display name: the characters a project name +/// allows, any other run as one dash, at most 255 bytes. Falls back to +/// `fallback`, then to "actor". Dots alone count as empty, since a clone would +/// land in `.` or `..`. +pub fn repo_name(display_name: &str, fallback: &str) -> String { + fn clean(value: &str) -> String { + let name = value + .chars() + .map(|c| { + if c.is_alphanumeric() || ProjectName::ALLOWED_CHARS.contains(&c) { + c + } else { + '-' + } + }) + .fold(String::new(), |mut name, c| { + if !(c == '-' && name.ends_with('-')) { + name.push(c); + } + name + }); + let mut name = name.trim_matches('-').to_string(); + while name.len() > MAX_REPO_NAME { + name.pop(); + } + let name = name.trim_end_matches('-'); + if name.chars().all(|c| c == '.') { + return String::new(); + } + name.to_string() + } + + [clean(display_name), clean(fallback)] + .into_iter() + .find(|name| !name.is_empty()) + .unwrap_or_else(|| "actor".to_string()) +} + +/// The identity document of a new actor: a project payload, which a default +/// branch needs, and an actor payload with `did` as the only key. +pub fn initial_doc(name: &str, default_branch: &str, did: Did) -> Result { + let name = ProjectName::try_from(name.to_string())?; + let branch = git::fmt::RefString::try_from(default_branch)?; + let project = Project::new(name, "Actor repository".to_string(), branch).map_err(|errs| { + errs.into_iter() + .next() + .expect("a failed Project::new returns at least one error") + })?; + let payload = serde_json::to_value(ActorPayload::founding(did))?; + let doc = Doc::initial(project, did, Visibility::Public).with_edits(|raw| { + raw.payload.insert(payload_id(), Payload::from(payload)); + })?; + + Ok(doc) +} + +#[cfg(test)] +mod tests; diff --git a/desktop/crates/radicle-types/src/actor/identity/tests.rs b/desktop/crates/radicle-types/src/actor/identity/tests.rs new file mode 100644 index 000000000..47fccc16c --- /dev/null +++ b/desktop/crates/radicle-types/src/actor/identity/tests.rs @@ -0,0 +1,692 @@ +use std::str::FromStr; + +use radicle::crypto::{Seed, Signer as _, SigningKey}; +use radicle::git; +use radicle::identity::doc::{Payload, PayloadId}; +use radicle::identity::project::ProjectName; +use radicle::identity::{Did, Doc, Project, RepoId, Visibility}; + +use super::*; + +fn key(seed: u8) -> SigningKey { + SigningKey::from_seed(Seed::new([seed; 32])) +} + +fn did_of(key: &SigningKey) -> Did { + Did::from(*key.public_key()) +} + +fn did() -> Did { + did_of(&key(7)) +} + +fn oid(byte: u8) -> git::Oid { + git::raw::Oid::from_bytes(&[byte; 20]).unwrap().into() +} + +fn rid() -> RepoId { + RepoId::from(oid(42)) +} + +fn payload_id() -> PayloadId { + PayloadId::from_str("dev.radicle.actor").unwrap() +} + +/// The payload an actor is created with, as `initial_doc` writes it. +fn founding_payload(did: Did) -> ActorPayload { + ActorPayload::of(&initial_doc("alice", "master", did).unwrap()).unwrap() +} + +fn root() -> IdentityDocRevision { + IdentityDocRevision { + commit: oid(1), + time: 1, + doc: initial_doc("alice", "master", did()).unwrap(), + } +} + +fn copy(revision: &IdentityDocRevision) -> IdentityDocRevision { + IdentityDocRevision { + commit: revision.commit, + time: revision.time, + doc: revision.doc.clone(), + } +} + +fn bound(resolved: &ResolvedActor) -> Vec { + resolved.bound_keys().collect() +} + +fn recovery(resolved: &ResolvedActor) -> Vec { + resolved + .keys + .iter() + .filter(|k| !k.bound && k.controller) + .map(|k| k.did) + .collect() +} + +/// `previous` edited: `payload` replaces the actor payload and +/// `delegates`, when given, the delegate list. +fn revision( + previous: &IdentityDocRevision, + commit: u8, + payload: &ActorPayload, + delegates: Option>, +) -> IdentityDocRevision { + let value = serde_json::to_value(payload).unwrap(); + let doc = previous + .doc + .clone() + .with_edits(|raw| { + raw.payload.insert(payload_id(), Payload::from(value)); + if let Some(delegates) = delegates { + raw.delegates = delegates; + } + }) + .unwrap(); + IdentityDocRevision { + commit: oid(commit), + time: i64::from(commit), + doc, + } +} + +fn with_payload(revision: &IdentityDocRevision, payload: serde_json::Value) -> IdentityDocRevision { + IdentityDocRevision { + commit: revision.commit, + time: revision.time, + doc: revision + .doc + .clone() + .with_edits(|raw| { + raw.payload.insert(payload_id(), Payload::from(payload)); + }) + .unwrap(), + } +} + +fn consent(key: &SigningKey, parent: git::Oid) -> String { + Enrollment::sign(rid(), parent, key).consent() +} + +#[test] +fn initial_doc_marks_the_actor() { + let did = did(); + let doc = initial_doc("alice", "master", did).unwrap(); + let payload = ActorPayload::of(&doc).unwrap(); + + assert_eq!(payload.version, 1); + assert_eq!(payload.kind, ActorKind::Person); + assert_eq!(payload.keys.get(&did).map(String::as_str), Some("root")); + assert_eq!(doc.delegates().iter().collect::>(), vec![&did]); + assert_eq!(doc.project().unwrap().default_branch().as_str(), "master"); +} + +#[test] +fn a_plain_project_is_not_an_actor() { + let project = Project::new( + "alice".to_string().try_into().unwrap(), + String::new(), + git::fmt::RefString::try_from("master").unwrap(), + ) + .unwrap(); + let doc = Doc::initial(project, did(), Visibility::Public); + + assert!(ActorPayload::of(&doc).is_none()); + let plain = IdentityDocRevision { + commit: oid(1), + time: 1, + doc, + }; + assert!(resolve(rid(), &[copy(&plain)]).is_none()); + + // The payload arriving in a later revision does not make an actor. + let later = revision(&plain, 2, &founding_payload(did()), None); + assert!(resolve(rid(), &[plain, later]).is_none()); +} + +#[test] +fn a_payload_of_this_version_is_held_to_its_schema() { + let root = root(); + let moved = did_of(&key(9)).to_string(); + let read = + |payload: &serde_json::Value| ActorPayload::of(&with_payload(&root, payload.clone()).doc); + use serde_json::json; + + // Every field of the version survives a read and a write. + let whole = json!({ + "version": 1, + "type": "person", + "keys": {}, + "migrations": { moved.clone(): { "from": rid().to_string(), "signature": "z4jHmar" } }, + "supersededBy": rid().to_string(), + "retired": true, + "supersedes": vec![rid().to_string(); 16], + }); + let payload = read(&whole).unwrap(); + assert!(!payload.is_newer()); + assert_eq!(serde_json::to_value(&payload).unwrap(), whole); + + // A migration is keyed by any `did:key`, not only one of a key this + // version can verify with. + let other_curve = json!({ + "version": 1, + "migrations": { + "did:key:zQ3s": + { "from": "a", "signature": "b" }, + }, + }); + assert!(read(&other_curve).is_some()); + + for invalid in [ + json!({ "version": 1, "migrations": [{ "from": "a", "signature": "b" }] }), + json!({ "version": 1, "migrations": { moved.clone(): { "from": "a" } } }), + json!({ "version": 1, "migrations": { "alice": { "from": "a", "signature": "b" } } }), + json!({ "version": 1, "supersededBy": null }), + json!({ "version": 1, "supersedes": vec![rid().to_string(); 17] }), + ] { + assert!(read(&invalid).is_none(), "{invalid}"); + } +} + +#[test] +fn a_payload_with_fields_its_version_does_not_define_is_read_but_not_written() { + let root = root(); + let did = did(); + use serde_json::json; + + for beyond in [ + json!({ "version": 1, "keys": { did.to_string(): "root" }, "mood": "unknown" }), + json!({ + "version": 1, + "keys": { did.to_string(): "root" }, + "names": [{ "source": "dns", "name": "example.org" }], + }), + json!({ + "version": 1, + "keys": { did.to_string(): "root" }, + "migrations": { did.to_string(): { "from": "a", "signature": "b", "to": "c" } }, + }), + ] { + let revision = with_payload(&root, beyond.clone()); + let payload = ActorPayload::of(&revision.doc).unwrap(); + assert!(payload.is_newer(), "{beyond}"); + let resolved = resolve(rid(), &[revision]).unwrap(); + assert!(resolved.payload_newer, "{beyond}"); + assert_eq!(bound(&resolved), vec![did], "{beyond}"); + } +} + +#[test] +fn the_payload_is_validated() { + let root = root(); + let did = did(); + use serde_json::json; + + let plain = ActorPayload::of(&with_payload(&root, json!({ "version": 1 })).doc).unwrap(); + assert_eq!(plain.kind, ActorKind::Person); + assert!(plain.keys.is_empty()); + + for invalid in [ + json!({ "type": "person" }), + json!({ "version": 0 }), + json!({ "version": 1, "type": "robot" }), + json!({ "version": 1, "keys": { "alice": "root" } }), + ] { + assert!( + ActorPayload::of(&with_payload(&root, invalid.clone()).doc).is_none(), + "{invalid}" + ); + } + + // A newer payload is read for every field this version acts on, whatever + // else it holds and whatever limits its own version sets. + let newer = with_payload( + &root, + json!({ + "version": 2, + "type": "agent", + "keys": { did.to_string(): "root" }, + "migrations": ["reshaped"], + "supersededBy": rid().to_string(), + "retired": true, + "supersedes": vec![rid().to_string(); 17], + "mood": "new", + }), + ); + let payload = ActorPayload::of(&newer.doc).unwrap(); + assert_eq!(payload.kind, ActorKind::Agent); + assert_eq!(payload.superseded_by, Some(rid())); + assert!(payload.retired); + assert_eq!(payload.supersedes.len(), 17); + let resolved = resolve(rid(), &[newer]).unwrap(); + assert!(resolved.payload_newer); + assert_eq!(bound(&resolved), vec![did]); +} + +#[test] +fn a_newer_payload_stays_an_actor_whatever_its_fields_hold() { + use serde_json::json; + + let did = did(); + let root = root(); + let read = |payload: serde_json::Value| ActorPayload::of(&with_payload(&root, payload).doc); + + // What cannot be read costs nothing else its reading: the key keeps its + // binding and the list its other entries. + let partly = with_payload( + &root, + json!({ + "version": 2, + "keys": { did.to_string(): "root", "not a key": "root", did_of(&key(8)).to_string(): 7 }, + "supersedes": [rid().to_string(), 7, "not an id"], + }), + ); + let payload = ActorPayload::of(&partly.doc).unwrap(); + assert_eq!(payload.keys.keys().collect::>(), vec![&did]); + assert_eq!(payload.supersedes, vec![rid()]); + + let resolved = resolve(rid(), &[partly]).unwrap(); + assert!(resolved.payload_newer); + assert_eq!(bound(&resolved), vec![did]); + + // Where the kind or the ending cannot be read, the actor is not known to + // be live, and says so. + for unread in [ + json!({ "type": "team" }), + json!({ "type": 7 }), + json!({ "retired": "no" }), + json!({ "supersededBy": 7 }), + ] { + let mut payload = json!({ "version": 2, "keys": { did.to_string(): "root" } }); + payload + .as_object_mut() + .unwrap() + .extend(unread.as_object().unwrap().clone()); + let resolved = resolve(rid(), &[with_payload(&root, payload)]).unwrap(); + + assert!(resolved.unsure, "{unread}"); + assert!(!resolved.is_live_individual(), "{unread}"); + assert_eq!(bound(&resolved), vec![did], "{unread}"); + } + + // Nor is it known whose it is where the keys cannot all be read. + for keys in [ + json!({ "version": 2 }), + json!({ "version": 2, "keys": [did.to_string()] }), + json!({ "version": 2, "keys": { did.to_string(): { "role": "root" } } }), + ] { + let resolved = resolve(rid(), &[with_payload(&root, keys.clone())]).unwrap(); + + assert!(resolved.unsure, "{keys}"); + assert!(bound(&resolved).is_empty(), "{keys}"); + } + + // In a payload of this version, a kind it does not define is invalid. + assert!(read(json!({ "version": 1, "type": "team" })).is_none()); +} + +#[test] +fn the_root_decides_what_is_an_actor() { + let did = did(); + let other = did_of(&key(8)); + let root = root(); + + // Two delegates in the root do not make an actor. + let two = IdentityDocRevision { + commit: oid(1), + time: 1, + doc: root + .doc + .clone() + .with_edits(|raw| raw.delegates.push(other)) + .unwrap(), + }; + assert!(resolve(rid(), &[two]).is_none()); + + // A root entry for a key other than the founding one is ignored. + let mut payload = founding_payload(did); + payload.keys.insert(other, "root".to_string()); + let claimed = with_payload(&root, serde_json::to_value(&payload).unwrap()); + let resolved = resolve(rid(), &[claimed]).unwrap(); + assert_eq!(bound(&resolved), vec![did]); + assert!(recovery(&resolved).is_empty()); + + // A current document that dropped the payload is not an actor. + let dropped = IdentityDocRevision { + commit: oid(2), + time: 2, + doc: root + .doc + .clone() + .with_edits(|raw| { + raw.payload.remove(&payload_id()); + }) + .unwrap(), + }; + assert!(resolve(rid(), &[root, dropped]).is_none()); +} + +#[test] +fn a_key_is_bound_only_with_its_consent() { + let founding = key(7); + let joining = key(9); + let root = root(); + let mut payload = founding_payload(did_of(&founding)); + + // Claimed without consent: a controller, not a bound key. + payload + .keys + .insert(did_of(&joining), "zinvalid".to_string()); + let claimed = revision( + &root, + 2, + &payload, + Some(vec![did_of(&founding), did_of(&joining)]), + ); + let resolved = resolve(rid(), &[copy(&root), claimed]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); + assert_eq!(recovery(&resolved), vec![did_of(&joining)]); + assert_eq!( + resolved.keys[1].added_at, 2, + "added when it became a delegate" + ); + + // Consent anchored to another revision does not count. + payload + .keys + .insert(did_of(&joining), consent(&joining, oid(3))); + let elsewhere = revision(&root, 2, &payload, None); + let resolved = resolve(rid(), &[copy(&root), elsewhere]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); + + // Consent by another key does not count. + payload + .keys + .insert(did_of(&joining), consent(&founding, root.commit)); + let forged = revision(&root, 2, &payload, None); + let resolved = resolve(rid(), &[copy(&root), forged]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); + + // Consent to joining another actor does not count. + let elsewhere = Enrollment::sign(RepoId::from(oid(43)), root.commit, &joining).consent(); + payload.keys.insert(did_of(&joining), elsewhere); + let replayed = revision(&root, 2, &payload, None); + let resolved = resolve(rid(), &[copy(&root), replayed]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); + + // The right signature in another multibase does not count either. + let signature = Enrollment::sign(rid(), root.commit, &joining) + .signature + .to_bytes(); + payload.keys.insert( + did_of(&joining), + multibase::encode(multibase::Base::Base64, signature), + ); + let base64 = revision(&root, 2, &payload, None); + let resolved = resolve(rid(), &[copy(&root), base64]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); + + // Consent anchored to the head it extends binds the key, and stays + // bound through later revisions that carry the entry forward. + payload + .keys + .insert(did_of(&joining), consent(&joining, root.commit)); + let enrolled = revision(&root, 2, &payload, None); + let mut later_payload = payload.clone(); + later_payload.kind = ActorKind::Agent; + let later = revision(&enrolled, 3, &later_payload, None); + let resolved = resolve(rid(), &[copy(&root), copy(&enrolled), later]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding), did_of(&joining)]); + assert_eq!(resolved.kind, ActorKind::Agent); + assert!(recovery(&resolved).is_empty()); + assert_eq!(resolved.keys[0].added_at, 1); + assert_eq!( + resolved.keys[1].added_at, 2, + "added when enrolled, not when carried forward" + ); + assert!(!resolved.keys[1].controller); + + // Removing the entry and restating the old statement later does not + // bind the key again: the anchor has moved. + let mut removed_payload = later_payload.clone(); + removed_payload.keys.remove(&did_of(&joining)); + let removed = revision(&enrolled, 3, &removed_payload, None); + let restated = revision(&removed, 4, &later_payload, None); + let resolved = resolve(rid(), &[root, enrolled, removed, restated]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); +} + +#[test] +fn a_revision_that_cannot_be_read_is_stepped_over() { + let did = did(); + let root = root(); + let unreadable = with_payload( + &root, + serde_json::json!({ "version": 1, "type": "weather", "keys": { did.to_string(): "root" } }), + ); + assert!(ActorPayload::of(&unreadable.doc).is_none()); + let repaired = revision(&unreadable, 3, &founding_payload(did), None); + + // The founding key stays bound: its entry is unchanged since the root, + // and the bad revision in between is no introduction. + let resolved = resolve(rid(), &[copy(&root), unreadable, repaired]).unwrap(); + assert_eq!(bound(&resolved), vec![did]); +} + +#[test] +fn a_consent_is_not_replayed_through_an_unreadable_revision() { + let founding = key(7); + let joining = key(9); + let root = root(); + let mut payload = founding_payload(did_of(&founding)); + payload + .keys + .insert(did_of(&joining), consent(&joining, root.commit)); + let joined = revision(&root, 2, &payload, None); + assert_eq!( + bound(&resolve(rid(), &[copy(&root), copy(&joined)]).unwrap()), + vec![did_of(&founding), did_of(&joining)] + ); + + // A revision that cannot be read drops the key, and the next one adds it + // back with the consent from before: that consent names the root as its + // parent, which the revision adding it back does not extend. + let dropped = with_payload( + &joined, + serde_json::json!({ + "version": 1, "type": "weather", "keys": { did_of(&founding).to_string(): "root" }, + }), + ); + let replayed = revision(&dropped, 4, &payload, None); + let resolved = resolve(rid(), &[copy(&root), joined, dropped, replayed]).unwrap(); + assert_eq!(bound(&resolved), vec![did_of(&founding)]); +} + +#[test] +fn lifecycle_flags_are_read() { + let root = root(); + let mut payload = founding_payload(did()); + payload.retired = true; + let retired = revision(&root, 2, &payload, None); + assert!(resolve(rid(), &[copy(&root), retired]).unwrap().retired); + + payload.retired = false; + payload.superseded_by = Some(RepoId::from(oid(9))); + let superseded = revision(&root, 2, &payload, None); + assert_eq!( + resolve(rid(), &[root, superseded]).unwrap().superseded_by, + Some(RepoId::from(oid(9))) + ); +} + +#[test] +fn the_repo_name_derives_from_the_display_name() { + assert_eq!(repo_name("Alice Liddell", "alice"), "Alice-Liddell"); + assert_eq!(repo_name("cloudhead", "alice"), "cloudhead"); + assert_eq!(repo_name("日本", "alice"), "日本"); + assert_eq!(repo_name("!!!", "alice"), "alice"); + assert_eq!(repo_name("!!!", "j@t"), "j-t"); + assert_eq!(repo_name("", ""), "actor"); + assert_eq!(repo_name("John Doe", "alice"), "John-Doe"); + // A clone of `.` or `..` would land in the current or the parent directory. + assert_eq!(repo_name("..", "alice"), "alice"); + assert_eq!(repo_name(".", "."), "actor"); + let long = repo_name(&"æ—¥".repeat(255), "alice"); + assert!(long.len() <= 255 && long.starts_with("æ—¥")); + assert!(ProjectName::try_from(long).is_ok(), "fits a project name"); +} + +fn code_bytes(code: &str) -> Vec { + multibase::decode(code.strip_prefix("rad-enroll:").unwrap()) + .unwrap() + .1 +} + +fn code_of(bytes: &[u8]) -> String { + format!( + "rad-enroll:{}", + multibase::encode(multibase::Base::Base58Btc, bytes) + ) +} + +#[test] +fn an_enrollment_code_carries_the_consent_whole() { + let joining = key(9); + let enrollment = Enrollment::sign(rid(), oid(3), &joining); + let code = enrollment.encode(); + // A paste that wrapped the code still reads. + let wrapped = format!("{}\n {}", &code[..40], &code[40..]); + assert_eq!(Enrollment::decode(&wrapped).unwrap(), enrollment); + + assert_eq!(code_bytes(&code).len(), 137); + let decoded = Enrollment::decode(&code).unwrap(); + assert_eq!(decoded, enrollment); + assert_eq!(decoded.did, did_of(&joining)); + assert!(decoded.verifies()); +} + +#[test] +fn an_enrollment_code_that_is_not_one_is_refused() { + let code = Enrollment::sign(rid(), oid(3), &key(9)).encode(); + let bytes = code_bytes(&code); + + // The version byte decides first, whatever follows it. + let mut newer = bytes.clone(); + newer[0] = 0x02; + newer.truncate(40); + assert_eq!( + Enrollment::decode(&code_of(&newer)), + Err(EnrollmentError::Version(2)) + ); + assert_eq!( + Enrollment::decode(&code_of(&bytes[..100])), + Err(EnrollmentError::Length) + ); + assert_eq!( + Enrollment::decode(code.strip_prefix("rad-enroll:").unwrap()), + Err(EnrollmentError::Prefix) + ); + + // A code for another anchor carries a signature that is not the + // key's consent to it. + let mut moved = bytes; + moved[1 + 20 + 32] ^= 0xff; + let moved = Enrollment::decode(&code_of(&moved)).unwrap(); + assert!(!moved.verifies()); +} + +#[test] +fn an_approval_binds_the_key_and_keeps_the_rest_of_the_payload() { + let migrations = serde_json::json!({ + did().to_string(): { "from": rid().to_string(), "signature": "z4jHmar" }, + }); + let root = with_payload( + &root(), + serde_json::json!({ + "version": 1, + "type": "person", + "keys": { did().to_string(): "root" }, + "migrations": migrations.clone(), + }), + ); + let joining = key(9); + let enrollment = Enrollment::sign(rid(), root.commit, &joining); + + for controller in [true, false] { + let doc = enrolled_doc(&root.doc, &enrollment, controller).unwrap(); + let id = PayloadId::from_str("dev.radicle.actor").unwrap(); + let payload = &**doc.payload().get(&id).unwrap(); + assert_eq!(payload["migrations"], migrations); + + let next = IdentityDocRevision { + commit: oid(2), + time: 2, + doc, + }; + let resolved = resolve(rid(), &[root.clone(), next]).unwrap(); + let key = resolved + .keys + .iter() + .find(|key| key.did == did_of(&joining)) + .unwrap(); + assert!(key.bound); + assert_eq!(key.controller, controller); + } +} + +#[test] +fn a_removal_needs_the_keys_it_removes_from() { + let root = with_payload( + &root(), + serde_json::json!({ "version": 1, "type": "person" }), + ); + assert!(matches!( + removed_doc(&root.doc, &did_of(&key(9))), + Err(Error::Payload) + )); + + // An empty map of keys and none at all are the same to a vote. + let empty = with_payload( + &root, + serde_json::json!({ "version": 1, "type": "person", "keys": {} }), + ); + assert!(changes_only_keys(&root.doc, &empty.doc)); +} + +/// What another client has to produce from the same inputs: the key of seed 9 +/// joining `rid()` on top of `oid(3)`. +#[test] +fn the_consent_and_the_code_are_fixed_to_the_byte() { + use radicle::crypto::signature::Verifier as _; + + const SIGNED: &str = + "zp3FoCpC5kviWaZojkW9C4oktXW253yuxfcsQwaFKkKy8LEBZgTxucUTCfDCropNBKqokohCTZEqCQoGWHad4U2k"; + const CODE: &str = "rad-enroll:zPXUVBCd7FA4epFwD8Das7hXuxxTXVHBBKxV3qsjBkBTCzp96L5U49q9mvikdWz69LAHWFGmJ2HR7rUzPyFUMsyzPaNRcBpZhaFCFD6Q7hGWwbm5BPiNhMTCMi6qRFebGqiwGrX5aTG5Hk3BajC4DAdr6R7VbgUowtFKs5sWmo3okrYfnj1DJ6jhh1i"; + let joining = did_of(&key(9)); + let enrollment = Enrollment::sign(rid(), oid(3), &key(9)); + + // The statement: the prefix, then the actor, the joining key and the + // anchor in their textual forms, one space apart. + let statement = format!( + "rad-actor-consent-v1 rad:zb56iBSEKUikofQ1eb4cGFfpsstM {joining} 0303030303030303030303030303030303030303" + ); + let verifier = radicle::crypto::VerifyingKey::try_from(&*joining).unwrap(); + assert!( + verifier + .verify(statement.as_bytes(), &enrollment.signature) + .is_ok() + ); + assert_eq!(enrollment.consent(), SIGNED); + + // The code: the version, the actor, the joining key, the anchor and the + // signature, raw and with nothing between them. + let mut bytes = vec![0x01]; + bytes.extend([42; 20]); + bytes.extend_from_slice(joining.as_ref()); + bytes.extend([3; 20]); + bytes.extend(enrollment.signature.to_bytes()); + assert_eq!(code_bytes(CODE), bytes); + assert_eq!(enrollment.encode(), CODE); +} diff --git a/desktop/crates/radicle-types/src/actor/profile.rs b/desktop/crates/radicle-types/src/actor/profile.rs new file mode 100644 index 000000000..5beff1527 --- /dev/null +++ b/desktop/crates/radicle-types/src/actor/profile.rs @@ -0,0 +1,583 @@ +//! The profile file of an actor repository: its limits, how its text is +//! cleaned, and how it is read and written. + +use serde::{Deserialize, Serialize}; +use unicode_normalization::UnicodeNormalization as _; + +use radicle::git; + +use super::{Error, retain_fields}; + +/// Where the profile lives, relative to the root of the default branch. +pub const PROFILE_PATH: &str = ".radicle/profile.json"; +const PROFILE_VERSION: u32 = 1; +/// The limits on the profile file's strings, in characters, and on its links. +const MAX_STRING: usize = 255; +const MAX_LABEL: usize = 64; +const MAX_LINKS: usize = 16; +/// The most bytes a profile file is read with; a valid one is a few hundred. +const MAX_PROFILE_BYTES: usize = 64 * 1024; +/// The most bytes a picture saved with the profile may have. Every node that +/// has the profile copies its pictures and keeps the earlier ones. +const MAX_AVATAR_BYTES: usize = 1024 * 1024; +const MAX_BANNER_BYTES: usize = 2 * 1024 * 1024; +/// The pictures a save takes, by what their content is, and the extension +/// each is saved under. +const IMAGE_TYPES: &[(&str, &str)] = &[ + ("image/png", "png"), + ("image/jpeg", "jpg"), + ("image/webp", "webp"), + ("image/gif", "gif"), +]; + +/// The pictures to save in the repository with a profile, each the base64 of +/// an image file: a PNG, JPEG, WebP or GIF of at most 1 MiB for the avatar +/// and 2 MiB for the banner. The kind is told from the first bytes of the +/// file, and the rest is not decoded: what is saved may not show. +#[derive(Clone, Debug, Default, Deserialize, ts_rs::TS)] +#[ts(export)] +#[ts(export_to = "actor/")] +pub struct ProfileImages { + #[serde(default)] + #[ts(optional)] + pub avatar: Option, + #[serde(default)] + #[ts(optional)] + pub banner: Option, +} + +/// A picture that passed the checks of `ProfileImages::place`. +#[derive(Debug)] +pub struct ProfileImage { + /// The file's name without its extension, which says what it is for. + stem: &'static str, + /// Where it is saved, relative to the root of the default branch. + path: String, + bytes: Vec, +} + +impl ProfileImages { + /// `profile` with the field of each picture naming the file it is saved + /// as, and the pictures to save. The error names the field and what is + /// wrong with its picture: not base64, too large, or not an image of a + /// kind that is taken. + pub fn place( + self, + mut profile: ActorProfile, + ) -> Result<(ActorProfile, Vec), String> { + use base64::Engine as _; + + let fields = [ + ("avatar", self.avatar, MAX_AVATAR_BYTES, &mut profile.avatar), + ("banner", self.banner, MAX_BANNER_BYTES, &mut profile.banner), + ]; + let mut images = Vec::new(); + for (stem, encoded, limit, field) in fields { + let Some(encoded) = encoded else { continue }; + let bytes = base64::engine::general_purpose::STANDARD + .decode(encoded) + .map_err(|_| format!("the {stem} picture is not base64"))?; + if bytes.len() > limit { + return Err(format!( + "the {stem} picture is {} KiB, and the limit is {} KiB", + bytes.len().div_ceil(1024), + limit / 1024 + )); + } + let kind = infer::get(&bytes).map(|kind| kind.mime_type()); + let Some((_, extension)) = IMAGE_TYPES.iter().find(|(mime, _)| Some(*mime) == kind) + else { + return Err(format!( + "the {stem} picture must be a PNG, JPEG, WebP or GIF image, and this is {}", + kind.unwrap_or("none of them") + )); + }; + let path = format!("{stem}.{extension}"); + *field = Some(path.clone()); + images.push(ProfileImage { stem, path, bytes }); + } + + Ok((profile, images)) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)] +#[serde(deny_unknown_fields)] +#[ts(export_to = "actor/")] +pub struct ProfileLink { + pub url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub label: Option, +} + +/// The contents of `.radicle/profile.json`. A file of `PROFILE_VERSION` must +/// match the schema exactly; a newer one is read for its known fields. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[ts(export_to = "actor/")] +pub struct ActorProfile { + pub version: u32, + pub display_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub full_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub pronouns: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub bio: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub location: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub timezone: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub avatar: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub banner: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub links: Vec, +} + +const PROFILE_FIELDS: &[&str] = &[ + "version", + "displayName", + "fullName", + "pronouns", + "bio", + "location", + "timezone", + "avatar", + "banner", + "links", +]; +const LINK_FIELDS: &[&str] = &["url", "label"]; + +/// Text as it is displayed or compared: one line, without control or +/// invisible characters, then NFC, so that what is left composes; trimmed. +/// A line break or a tab stands between words, so a space takes its place. +fn clean_text(value: &str) -> String { + // The character before, of those that stay. + let mut before = None; + + value + .chars() + .filter_map(|c| { + let is_break = c.is_control() && c.is_whitespace(); + let c = if is_break { ' ' } else { c }; + // A break after a space adds nothing to it. + let dropped = is_hidden(c) + || (is_emoji_selector(c) && !before.is_some_and(takes_selector)) + || (is_break && before == Some(' ')); + if dropped { + return None; + } + before = Some(c); + + Some(c) + }) + .nfc() + .collect::() + .trim() + .to_string() +} + +fn is_hidden(c: char) -> bool { + c.is_control() || is_invisible(c) +} + +/// The two variation selectors that pick an emoji's text or picture form. +fn is_emoji_selector(c: char) -> bool { + matches!(c, '\u{FE0E}' | '\u{FE0F}') +} + +/// Whether a selector after `c` can change what shows: after a symbol or a +/// digit it can, after a letter or a space it only hides in the text. +fn takes_selector(c: char) -> bool { + !(c.is_alphabetic() || c.is_whitespace() || is_emoji_selector(c)) +} + +/// Characters that do not show and can make one name look like another: the +/// line separators, and what Unicode says to ignore when text is drawn. Those +/// are the bidirectional marks, the zero-width characters, the fillers, the +/// tags and the variation selectors, but for the two of `is_emoji_selector`. +/// What is drawn with one of them loses its form: a joined emoji, the flag +/// of a region, the variant of an ideograph. +fn is_invisible(c: char) -> bool { + matches!( + c, + '\u{00AD}' + | '\u{034F}' + | '\u{061C}' + | '\u{115F}'..='\u{1160}' + | '\u{17B4}'..='\u{17B5}' + | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200F}' + | '\u{2028}'..='\u{202E}' + | '\u{2060}'..='\u{206F}' + | '\u{3164}' + | '\u{FE00}'..='\u{FE0D}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF0}'..='\u{FFF8}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E0FFF}' + ) +} + +/// Whether `name` shows nothing once cleaned; the braille blank is a +/// character that draws as a space. +fn is_blank(name: &str) -> bool { + clean_text(name) + .chars() + .all(|c| c.is_whitespace() || c == '\u{2800}' || is_emoji_selector(c)) +} + +const LINK_SCHEMES: &[&str] = &["https", "http", "mailto", "rad"]; +const IMAGE_SCHEMES: &[&str] = &["https", "http"]; + +/// A web URL, or a path relative to the repository root. A path may not hold +/// `%`, since a browser decodes `%2e%2e` to `..`. +fn is_image_ref(value: &str) -> bool { + if value.contains(':') { + return has_scheme(value, IMAGE_SCHEMES); + } + !value.contains('\\') + && !value.contains('%') + && !value.starts_with('/') + && !value.split('/').any(|part| part == "..") +} + +fn has_scheme(url: &str, schemes: &[&str]) -> bool { + url.split_once(':').is_some_and(|(scheme, _)| { + schemes + .iter() + .any(|allowed| scheme.eq_ignore_ascii_case(allowed)) + }) +} + +impl ActorProfile { + /// The first field that breaks a limit, as a message for the form. + pub fn validate(&self) -> Result<(), String> { + if is_blank(&self.display_name) { + return Err("display name is required".to_string()); + } + + let strings = [ + ("display name", Some(&self.display_name)), + ("full name", self.full_name.as_ref()), + ("pronouns", self.pronouns.as_ref()), + ("bio", self.bio.as_ref()), + ("location", self.location.as_ref()), + ("time zone", self.timezone.as_ref()), + ("avatar", self.avatar.as_ref()), + ("banner", self.banner.as_ref()), + ]; + for (field, value) in strings { + if value.is_some_and(|v| v.chars().count() > MAX_STRING) { + return Err(format!("{field} cannot exceed {MAX_STRING} characters")); + } + } + + // Other clients render these as links and images, so a scheme that + // runs code or reads local files never gets signed. Nor does an + // address with characters that do not show: cleaning it would point + // it somewhere else. + for (field, value) in [("avatar", &self.avatar), ("banner", &self.banner)] { + let Some(image) = value else { continue }; + if image.chars().any(is_hidden) { + return Err(format!("{field} cannot hold characters that do not show")); + } + if !is_image_ref(image) { + return Err(format!( + "{field} must be a path in the repository or a web URL" + )); + } + } + + if self.links.len() > MAX_LINKS { + return Err(format!("at most {MAX_LINKS} links are allowed")); + } + for link in &self.links { + let length = link.url.chars().count(); + if length == 0 || length > MAX_STRING { + return Err(format!("a link must be 1 to {MAX_STRING} characters")); + } + if link.url.chars().any(is_hidden) { + return Err("a link cannot hold characters that do not show".to_string()); + } + if !has_scheme(&link.url, LINK_SCHEMES) { + return Err("a link must be a web URL, a mailto: address or a rad: URI".to_string()); + } + if link + .label + .as_ref() + .is_some_and(|l| l.chars().count() > MAX_LABEL) + { + return Err(format!("a link label cannot exceed {MAX_LABEL} characters")); + } + } + Ok(()) + } + + /// The file as written to the repository: its text cleaned, its addresses + /// only trimmed, empty fields dropped. `validate` refuses an address with + /// characters that do not show. + pub fn normalized(mut self) -> Self { + self.version = PROFILE_VERSION; + self.rewritten(|address| address.trim().to_string()) + } + + /// The profile as it is displayed: every string cleaned, addresses too, + /// and a name that shows nothing left empty. + fn cleaned(self) -> Self { + let mut cleaned = self.rewritten(clean_text); + if is_blank(&cleaned.display_name) { + cleaned.display_name.clear(); + } + + cleaned + } + + /// Every text cleaned with `clean_text`, the image and link addresses + /// passed through `address`, empty optional fields dropped. + fn rewritten(mut self, address: impl Fn(&str) -> String) -> Self { + fn kept(value: Option, rewrite: impl Fn(&str) -> String) -> Option { + value.map(|v| rewrite(&v)).filter(|v| !v.is_empty()) + } + + self.display_name = clean_text(&self.display_name); + self.full_name = kept(self.full_name, clean_text); + self.pronouns = kept(self.pronouns, clean_text); + self.bio = kept(self.bio, clean_text); + self.location = kept(self.location, clean_text); + self.timezone = kept(self.timezone, clean_text); + self.avatar = kept(self.avatar, &address); + self.banner = kept(self.banner, &address); + self.links = self + .links + .into_iter() + .map(|link| ProfileLink { + url: address(&link.url), + label: kept(link.label, clean_text), + }) + .filter(|link| !link.url.is_empty()) + .collect(); + + self + } + + /// The profile in a file of any version, see `ActorProfile`. + fn from_json(bytes: &[u8]) -> Option { + let mut value: serde_json::Value = serde_json::from_slice(bytes).ok()?; + let version = value.get("version")?.as_u64()?; + if version == 0 { + return None; + } + let newer = version > u64::from(PROFILE_VERSION); + if newer { + let object = value.as_object_mut()?; + retain_fields(object, PROFILE_FIELDS); + if let Some(links) = object.get_mut("links").and_then(|l| l.as_array_mut()) { + for link in links.iter_mut().filter_map(|l| l.as_object_mut()) { + retain_fields(link, LINK_FIELDS); + } + } + } + let profile: Self = serde_json::from_value(value).ok()?; + + Some(ReadProfile { + profile: profile.cleaned(), + newer, + }) + } + + fn to_json(&self) -> Result, serde_json::Error> { + let mut bytes = serde_json::to_vec_pretty(self)?; + bytes.push(b'\n'); + Ok(bytes) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReadProfile { + pub profile: ActorProfile, + /// The file is newer than `PROFILE_VERSION`; writing it back would drop + /// fields. + pub newer: bool, +} + +/// What a commit's tree holds at `PROFILE_PATH`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileFile { + /// No file there. + Missing, + /// A file this version cannot read: not JSON, not its version's schema, or + /// over `MAX_PROFILE_BYTES`. A save replaces it, so the user is told. + Unreadable, + Read(Box), +} + +/// `parent`'s tree, or an empty one, with `profile` at `PROFILE_PATH`. +pub fn profile_tree<'a>( + repo: &'a git::raw::Repository, + parent: Option<&git::raw::Tree<'a>>, + profile: &ActorProfile, +) -> Result, Error> { + profile_tree_with(repo, parent, profile, &[], &[]) +} + +/// As `profile_tree`, with `images` saved at the root. An `avatar` or `banner` +/// picture at the root that the profile no longer names is left out of the +/// tree. One the profile names that `parent` lacks is taken from the first of +/// `others` that has it, so a version merged in keeps its picture; where +/// `parent` has a file of that name, that one stays. `Profile` if a folder is +/// where a picture would be saved. +pub fn profile_tree_with<'a>( + repo: &'a git::raw::Repository, + parent: Option<&git::raw::Tree<'a>>, + profile: &ActorProfile, + images: &[ProfileImage], + others: &[git::raw::Tree<'a>], +) -> Result, Error> { + let blob = repo.blob(&profile.to_json()?)?; + let empty; + let baseline = match parent { + Some(tree) => tree, + None => { + empty = repo.find_tree(repo.treebuilder(None)?.write()?)?; + &empty + } + }; + let is_file = |entry: &git2::TreeEntry| entry.kind() == Some(git2::ObjectType::Blob); + let mut update = git2::build::TreeUpdateBuilder::new(); + update.upsert(PROFILE_PATH, blob, git::raw::FileMode::Blob); + + for (stem, named) in [("avatar", &profile.avatar), ("banner", &profile.banner)] { + let named = named.as_deref(); + let earlier = IMAGE_TYPES + .iter() + .map(|(_, extension)| format!("{stem}.{extension}")) + .filter(|path| Some(path.as_str()) != named) + .filter(|path| baseline.get_name(path).is_some_and(|entry| is_file(&entry))); + for path in earlier { + update.remove(path); + } + + if let Some(image) = images.iter().find(|image| image.stem == stem) { + if baseline + .get_name(&image.path) + .is_some_and(|entry| !is_file(&entry)) + { + return Err(Error::Profile(format!( + "the repository has a folder named {}, where the {stem} picture is saved", + image.path + ))); + } + update.upsert( + image.path.as_str(), + repo.blob(&image.bytes)?, + git::raw::FileMode::Blob, + ); + } else if let Some(path) = named.filter(|path| !path.contains(':')) { + let path = std::path::Path::new(path); + let theirs = || { + others + .iter() + .find_map(|tree| tree.get_path(path).ok().filter(is_file)) + }; + if baseline.get_path(path).is_err() + && let Some(entry) = theirs() + { + update.upsert(path, entry.id(), git::raw::FileMode::Blob); + } + } + } + let tree = update.create_updated(repo, baseline)?; + + Ok(repo.find_tree(tree)?) +} + +/// The fields in which `to` differs from `from`, by their names in the file. +/// `None` is a version with no profile file, which sets no field. +pub fn changed_fields(from: Option<&ActorProfile>, to: Option<&ActorProfile>) -> Vec<&'static str> { + let unset = ActorProfile { + version: PROFILE_VERSION, + display_name: String::new(), + full_name: None, + pronouns: None, + bio: None, + location: None, + timezone: None, + avatar: None, + banner: None, + links: Vec::new(), + }; + let (from, to) = (from.unwrap_or(&unset), to.unwrap_or(&unset)); + let fields = [ + ("displayName", from.display_name != to.display_name), + ("fullName", from.full_name != to.full_name), + ("pronouns", from.pronouns != to.pronouns), + ("bio", from.bio != to.bio), + ("location", from.location != to.location), + ("timezone", from.timezone != to.timezone), + ("avatar", from.avatar != to.avatar), + ("banner", from.banner != to.banner), + ("links", from.links != to.links), + ]; + + fields + .into_iter() + .filter_map(|(field, changed)| changed.then_some(field)) + .collect() +} + +/// What turns the profile `from` into `to`, as a unified diff of the file +/// each would be saved as. +pub fn profile_changes(from: &ActorProfile, to: &ActorProfile) -> Result { + let path = std::path::Path::new(PROFILE_PATH); + let (from, to) = (from.to_json()?, to.to_json()?); + let mut patch = git2::Patch::from_buffers(&from, Some(path), &to, Some(path), None)?; + + Ok(String::from_utf8_lossy(&patch.to_buf()?).into_owned()) +} + +/// The profile in `commit`'s tree. A directory or a submodule at the path +/// counts as no file. +pub fn read_profile( + repo: &git::raw::Repository, + commit: git::Oid, +) -> Result { + let tree = repo.find_commit(commit.into())?.tree()?; + let Ok(entry) = tree.get_path(std::path::Path::new(PROFILE_PATH)) else { + return Ok(ProfileFile::Missing); + }; + if entry.kind() != Some(git::raw::ObjectType::Blob) { + return Ok(ProfileFile::Missing); + } + // The size comes from the object's header, so a file over the limit is + // never loaded. + let (size, _) = repo.odb()?.read_header(entry.id())?; + if size > MAX_PROFILE_BYTES { + return Ok(ProfileFile::Unreadable); + } + let object = entry.to_object(repo)?; + let Some(blob) = object.as_blob() else { + return Ok(ProfileFile::Missing); + }; + + Ok( + ActorProfile::from_json(blob.content()).map_or(ProfileFile::Unreadable, |read| { + ProfileFile::Read(Box::new(read)) + }), + ) +} + +#[cfg(test)] +mod tests; diff --git a/desktop/crates/radicle-types/src/actor/profile/tests.rs b/desktop/crates/radicle-types/src/actor/profile/tests.rs new file mode 100644 index 000000000..ca4e49c61 --- /dev/null +++ b/desktop/crates/radicle-types/src/actor/profile/tests.rs @@ -0,0 +1,550 @@ +use super::*; + +fn profile(display_name: &str) -> ActorProfile { + ActorProfile { + version: 1, + display_name: display_name.to_string(), + full_name: None, + pronouns: None, + bio: None, + location: None, + timezone: None, + avatar: None, + banner: None, + links: vec![], + } +} + +#[test] +fn profile_validation_follows_the_schema() { + assert!(profile(" ").validate().is_err()); + + let long = ActorProfile { + bio: Some("é".repeat(255)), + ..profile("alice") + }; + assert!( + long.validate().is_ok(), + "limits count characters, not bytes" + ); + let too_long = ActorProfile { + bio: Some("é".repeat(256)), + ..profile("alice") + }; + assert!(too_long.validate().unwrap_err().starts_with("bio")); + + let many = ActorProfile { + links: (0..17) + .map(|i| ProfileLink { + url: format!("https://example.com/{i}"), + label: None, + }) + .collect(), + ..profile("alice") + }; + assert!(many.validate().unwrap_err().contains("16 links")); + + let link = |url: &str| ActorProfile { + links: vec![ProfileLink { + url: url.to_string(), + label: None, + }], + ..profile("alice") + }; + for url in [ + "HTTPS://example.com", + "mailto:a@b.c", + "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5", + ] { + assert!(link(url).validate().is_ok(), "{url}"); + } + for url in ["javascript:alert(1)", "file:///etc/passwd", "example.com"] { + assert!(link(url).validate().is_err(), "{url}"); + } + let avatar = |value: &str| ActorProfile { + avatar: Some(value.to_string()), + ..profile("alice") + }; + for value in ["images/avatar.png", "https://example.com/a.png"] { + assert!(avatar(value).validate().is_ok(), "{value}"); + } + for value in [ + "javascript:alert(1)", + "/etc/passwd", + "//evil.example/a.png", + "../a.png", + // A browser folds a percent-encoded dot into `..`. + "%2e%2e/%2e%2e/a.png", + ] { + assert!( + avatar(value).validate().unwrap_err().starts_with("avatar"), + "{value}" + ); + } +} + +#[test] +fn profile_text_is_cleaned_for_display() { + // A decomposed "é", a bidirectional override and a control character. + let cleaned = ActorProfile { + full_name: Some(" Ali\u{202E}ce\u{0} ".to_string()), + ..profile("Zoe\u{301}") + } + .normalized(); + assert_eq!(cleaned.display_name, "Zo\u{e9}"); + assert_eq!(cleaned.full_name.as_deref(), Some("Alice")); + + // Zero-width characters, direction marks and line separators hide in a + // name and go the same way. + let hidden = profile("\u{FEFF}al\u{200B}i\u{200E}c\u{2028}e\u{061C}").normalized(); + assert_eq!(hidden.display_name, "alice"); +} + +#[test] +fn a_line_break_becomes_a_space() { + let cleaned = ActorProfile { + bio: Some(" Rust dev\r\n\u{0}Berlin\n".to_string()), + location: Some("Ber\tlin".to_string()), + ..profile("Al\nice") + } + .normalized(); + + // No string keeps a control character, and no two words run together. + assert_eq!(cleaned.bio.as_deref(), Some("Rust dev Berlin")); + assert_eq!(cleaned.display_name, "Al ice"); + assert_eq!(cleaned.location.as_deref(), Some("Ber lin")); +} + +/// A tree with `json` as its only file, at the profile path, whatever it +/// holds. +fn profile_file_tree<'r>(repo: &'r git::raw::Repository, json: &[u8]) -> git::raw::Tree<'r> { + let empty = repo + .find_tree(repo.treebuilder(None).unwrap().write().unwrap()) + .unwrap(); + let tree = git2::build::TreeUpdateBuilder::new() + .upsert( + PROFILE_PATH, + repo.blob(json).unwrap(), + git::raw::FileMode::Blob, + ) + .create_updated(repo, &empty) + .unwrap(); + repo.find_tree(tree).unwrap() +} + +/// Reads `json` as the profile file of a commit, as Desktop does. +fn read_file(json: &[u8]) -> ProfileFile { + let tmp = tempfile::tempdir().unwrap(); + let repo = git::raw::Repository::init_bare(tmp.path()).unwrap(); + let tree = profile_file_tree(&repo, json); + let signature = git::raw::Signature::now("alice", "alice@example.com").unwrap(); + let commit = repo + .commit(None, &signature, &signature, "Profile", &tree, &[]) + .unwrap(); + read_profile(&repo, commit.into()).unwrap() +} + +/// The profile `json` reads as, which the case expects to be one. +fn read_back(json: &[u8]) -> ReadProfile { + match read_file(json) { + ProfileFile::Read(read) => *read, + other => panic!("expected a profile, got {other:?}"), + } +} + +#[test] +fn profile_files_are_read_by_version() { + let known = br#"{ "version": 1, "displayName": "alice" }"#; + let read = read_back(known); + assert_eq!(read.profile.display_name, "alice"); + assert!(!read.newer); + + // A file this version cannot read is told apart from no file, so a save + // does not replace it unannounced. + let unknown_field = br#"{ "version": 1, "displayName": "alice", "mood": "sunny" }"#; + assert_eq!(read_file(unknown_field), ProfileFile::Unreadable); + + let unknown_link_field = + br#"{ "version": 1, "displayName": "alice", "links": [{ "url": "x", "icon": "y" }] }"#; + assert_eq!(read_file(unknown_link_field), ProfileFile::Unreadable); + + assert_eq!( + read_file(br#"{ "displayName": "alice" }"#), + ProfileFile::Unreadable + ); + assert_eq!( + read_file(br#"{ "version": 0, "displayName": "alice" }"#), + ProfileFile::Unreadable + ); + assert_eq!(read_file(b"not json"), ProfileFile::Unreadable); + + // A file over the size limit is not read at all, whatever it holds. + let mut padded = br#"{"version":1,"displayName":"Alice"}"#.to_vec(); + assert!(matches!(read_file(&padded), ProfileFile::Read(_))); + padded.resize(MAX_PROFILE_BYTES + 1, b' '); + assert_eq!(read_file(&padded), ProfileFile::Unreadable); + + let newer = br#"{ "version": 2, "displayName": "alice", "mood": "sunny", "links": [{ "url": "https://x", "icon": "y" }] }"#; + let read = read_back(newer); + assert!(read.newer); + assert_eq!(read.profile.display_name, "alice"); + assert_eq!(read.profile.links[0].url, "https://x"); +} + +#[test] +fn links_and_images_another_client_wrote_are_read_whole() { + // The editor gets the file as it is, so the user sees what to fix. + let file = br#"{ "version": 1, "displayName": "alice", "avatar": "javascript:alert(1)", + "banner": "..\\..\\etc\\passwd", "links": [{ "url": "x" }, { "url": "javascript:alert(1)" }, + { "url": "https://x" }] }"#; + let read = read_back(file); + assert_eq!(read.profile.links.len(), 3); + assert_eq!(read.profile.avatar.as_deref(), Some("javascript:alert(1)")); + assert!(read.profile.validate().is_err()); +} + +#[test] +fn profile_round_trips_through_a_tree() { + let tmp = tempfile::tempdir().unwrap(); + let repo = git::raw::Repository::init_bare(tmp.path()).unwrap(); + let profile = ActorProfile { + full_name: Some("Alice Liddell".to_string()), + bio: Some(" Curiouser. ".to_string()), + links: vec![ProfileLink { + url: "https://example.com".to_string(), + label: Some("".to_string()), + }], + ..profile("alice") + } + .normalized(); + let signature = git::raw::Signature::now("alice", "alice@example.com").unwrap(); + + let tree = profile_tree(&repo, None, &profile).unwrap(); + let commit = repo + .commit(None, &signature, &signature, "Create profile", &tree, &[]) + .unwrap(); + let ProfileFile::Read(read) = read_profile(&repo, commit.into()).unwrap() else { + panic!("the profile is read back"); + }; + let read = read.profile.clone(); + assert_eq!(read.bio.as_deref(), Some("Curiouser.")); + assert_eq!(read.links[0].label, None); + + // A second write replaces the file and keeps the rest of the tree. + let updated = ActorProfile { bio: None, ..read }; + let parent = repo.find_commit(commit).unwrap(); + let tree = profile_tree(&repo, Some(&parent.tree().unwrap()), &updated).unwrap(); + let commit = repo + .commit( + None, + &signature, + &signature, + "Edit profile", + &tree, + &[&parent], + ) + .unwrap(); + let ProfileFile::Read(read) = read_profile(&repo, commit.into()).unwrap() else { + panic!("the profile is read back"); + }; + let read = read.profile.clone(); + assert_eq!(read.bio, None); + assert_eq!(read.full_name.as_deref(), Some("Alice Liddell")); +} + +#[test] +fn characters_that_do_not_show_are_stripped() { + let hidden = [ + '\u{00AD}', + '\u{034F}', + '\u{180E}', + '\u{2061}', + '\u{3164}', + '\u{FE00}', + '\u{FFA0}', + '\u{E0041}', + '\u{E0100}', + ]; + for c in hidden { + let cleaned = profile(&format!("al{c}ice")).normalized(); + assert_eq!(cleaned.display_name, "alice", "U+{:04X}", u32::from(c)); + } + + // What is left composes, so cleaning twice changes nothing more. + let joined = profile("Zoe\u{034F}\u{301}").normalized(); + assert_eq!(joined.display_name, "Zo\u{e9}"); + + // A selector that picks an emoji's form changes what shows, so it stays + // after a symbol or a digit. After a letter it shows nothing. + for emoji in ["\u{2764}\u{FE0F}", "1\u{FE0F}\u{20E3}"] { + assert_eq!(profile(emoji).normalized().display_name, emoji); + } + let lookalike = profile("al\u{FE0F}ice \u{FE0E}").normalized(); + assert_eq!(lookalike.display_name, "alice"); +} + +#[test] +fn a_name_that_shows_nothing_is_no_name() { + let blanks = [ + "\u{3164}", + "\u{2800}", + " \u{2800} \u{200B}", + "\u{FE0F}", + "\u{2800}\u{FE0F}", + ]; + for blank in blanks { + assert!(profile(blank).normalized().validate().is_err(), "{blank:?}"); + assert!(profile(blank).validate().is_err(), "{blank:?} as given"); + } + + // Read from a file, such a name is empty, so that what shows the profile + // can tell there is none. + let read = read_back(br#"{ "version": 1, "displayName": "\u2800" }"#); + assert_eq!(read.profile.display_name, ""); +} + +#[test] +fn an_address_is_refused_not_rewritten() { + let hidden = "https://exa\u{00AD}mple.com"; + let written = ActorProfile { + avatar: Some(format!(" {hidden} ")), + links: vec![ProfileLink { + url: hidden.to_string(), + label: None, + }], + ..profile("alice") + } + .normalized(); + assert_eq!(written.avatar.as_deref(), Some(hidden), "only trimmed"); + assert_eq!(written.links[0].url, hidden); + assert!(written.validate().unwrap_err().starts_with("avatar")); + + let link_only = ActorProfile { + avatar: None, + ..written + }; + assert!(link_only.validate().unwrap_err().starts_with("a link")); + + // Read for display, it is cleaned like any other string. + let file = format!(r#"{{ "version": 1, "displayName": "alice", "avatar": "{hidden}" }}"#); + let read = read_back(file.as_bytes()); + assert_eq!(read.profile.avatar.as_deref(), Some("https://example.com")); +} + +/// The first bytes of a file of each kind, which is all that tells them apart. +const PNG: &[u8] = b"\x89PNG\r\n\x1a\na picture"; +const JPEG: &[u8] = b"\xff\xd8\xff\xe0a picture"; +const PDF: &[u8] = b"%PDF-1.4 a document"; + +fn encoded(bytes: &[u8]) -> Option { + use base64::Engine as _; + + Some(base64::engine::general_purpose::STANDARD.encode(bytes)) +} + +fn avatar(bytes: &[u8]) -> ProfileImages { + ProfileImages { + avatar: encoded(bytes), + banner: None, + } +} + +/// The tree of `profile` saved over `parent` with `images`, next to `others`. +fn saved<'r>( + repo: &'r git::raw::Repository, + parent: Option<&git::raw::Tree<'r>>, + profile: ActorProfile, + images: ProfileImages, + others: &[git::raw::Tree<'r>], +) -> Result, Error> { + let (profile, images) = images.place(profile).map_err(Error::Profile)?; + + profile_tree_with(repo, parent, &profile, &images, others) +} + +fn files(tree: &git::raw::Tree) -> Vec { + tree.iter() + .map(|entry| entry.name().unwrap().to_owned()) + .collect() +} + +fn file(repo: &git::raw::Repository, tree: &git::raw::Tree, name: &str) -> Vec { + let entry = tree.get_name(name).unwrap(); + + repo.find_blob(entry.id()).unwrap().content().to_vec() +} + +#[test] +fn a_picture_is_named_by_what_its_content_is() { + let images = ProfileImages { + avatar: encoded(JPEG), + banner: encoded(PNG), + }; + let typed = ActorProfile { + avatar: Some("https://example.com/me.png".to_string()), + ..profile("alice") + }; + + let (placed, pictures) = images.place(typed).unwrap(); + + assert_eq!(placed.avatar.as_deref(), Some("avatar.jpg")); + assert_eq!(placed.banner.as_deref(), Some("banner.png")); + assert_eq!(pictures.len(), 2); + + // Without a picture the fields are the form's. + let (kept, pictures) = ProfileImages::default().place(profile("alice")).unwrap(); + assert_eq!(kept, profile("alice")); + assert!(pictures.is_empty()); +} + +#[test] +fn a_picture_over_its_limit_or_of_no_taken_kind_is_refused() { + let sized = |bytes: usize| { + let mut picture = PNG.to_vec(); + picture.resize(bytes, 0); + picture + }; + let banner = |bytes: &[u8]| ProfileImages { + avatar: None, + banner: encoded(bytes), + }; + + assert!( + avatar(&sized(MAX_AVATAR_BYTES)) + .place(profile("alice")) + .is_ok() + ); + let refused = avatar(&sized(MAX_AVATAR_BYTES + 1)) + .place(profile("alice")) + .unwrap_err(); + assert!(refused.contains("avatar")); + + // The banner has its own limit. + assert!( + banner(&sized(MAX_AVATAR_BYTES + 1)) + .place(profile("alice")) + .is_ok() + ); + let refused = banner(&sized(MAX_BANNER_BYTES + 1)) + .place(profile("alice")) + .unwrap_err(); + assert!(refused.contains("banner")); + + let refused = banner(PDF).place(profile("alice")).unwrap_err(); + assert!(refused.contains("banner") && refused.contains("application/pdf")); + assert!(avatar(b"").place(profile("alice")).is_err()); + + let not_base64 = ProfileImages { + avatar: Some("not base64!".to_string()), + banner: None, + }; + assert!(not_base64.place(profile("alice")).is_err()); +} + +#[test] +fn a_picture_the_profile_stops_naming_leaves_the_tree() { + let tmp = tempfile::tempdir().unwrap(); + let repo = git::raw::Repository::init_bare(tmp.path()).unwrap(); + let none = ProfileImages::default; + let with_png = saved(&repo, None, profile("alice"), avatar(PNG), &[]).unwrap(); + assert_eq!(files(&with_png), [".radicle", "avatar.png"]); + assert_eq!(file(&repo, &with_png, "avatar.png"), PNG); + let named = || ActorProfile { + avatar: Some("avatar.png".to_string()), + ..profile("alice") + }; + + // A save that still names it keeps it. + let kept = saved(&repo, Some(&with_png), named(), none(), &[]).unwrap(); + assert_eq!(files(&kept), [".radicle", "avatar.png"]); + + // One of another kind takes its place. + let replaced = saved(&repo, Some(&with_png), named(), avatar(JPEG), &[]).unwrap(); + assert_eq!(files(&replaced), [".radicle", "avatar.jpg"]); + + // A cleared field, or one that names an address, has no file. + let cleared = saved(&repo, Some(&with_png), profile("alice"), none(), &[]).unwrap(); + assert_eq!(files(&cleared), [".radicle"]); + let linked = ActorProfile { + avatar: Some("https://example.com/me.png".to_string()), + ..profile("alice") + }; + let linked = saved(&repo, Some(&with_png), linked, none(), &[]).unwrap(); + assert_eq!(files(&linked), [".radicle"]); +} + +#[test] +fn a_folder_where_a_picture_goes_is_not_replaced() { + let tmp = tempfile::tempdir().unwrap(); + let repo = git::raw::Repository::init_bare(tmp.path()).unwrap(); + let empty = saved(&repo, None, profile("alice"), ProfileImages::default(), &[]).unwrap(); + let with_folder = git2::build::TreeUpdateBuilder::new() + .upsert( + "avatar.png/inside.txt", + repo.blob(b"kept").unwrap(), + git::raw::FileMode::Blob, + ) + .create_updated(&repo, &empty) + .unwrap(); + let with_folder = repo.find_tree(with_folder).unwrap(); + + let refused = saved( + &repo, + Some(&with_folder), + profile("alice"), + avatar(PNG), + &[], + ); + assert!(matches!(refused, Err(Error::Profile(_)))); + + // Nor does a save that names no picture take it away. + let kept = saved( + &repo, + Some(&with_folder), + profile("alice"), + ProfileImages::default(), + &[], + ) + .unwrap(); + assert_eq!(files(&kept), [".radicle", "avatar.png"]); +} + +#[test] +fn a_picture_only_a_merged_version_has_comes_along() { + let tmp = tempfile::tempdir().unwrap(); + let repo = git::raw::Repository::init_bare(tmp.path()).unwrap(); + let none = ProfileImages::default; + let mine = saved(&repo, None, profile("alice"), none(), &[]).unwrap(); + let theirs = saved(&repo, None, profile("alice"), avatar(PNG), &[]).unwrap(); + let named = || ActorProfile { + avatar: Some("avatar.png".to_string()), + ..profile("alice") + }; + + let merged = saved( + &repo, + Some(&mine), + named(), + none(), + std::slice::from_ref(&theirs), + ) + .unwrap(); + assert_eq!(file(&repo, &merged, "avatar.png"), PNG); + + // A profile that does not name it leaves it behind. + let without = saved( + &repo, + Some(&mine), + profile("alice"), + none(), + std::slice::from_ref(&theirs), + ) + .unwrap(); + assert_eq!(files(&without), [".radicle"]); + + // Where both have a file of that name, the one saved over stays. + let other_bytes = b"\x89PNG\r\n\x1a\nanother picture"; + let mine = saved(&repo, None, profile("alice"), avatar(other_bytes), &[]).unwrap(); + let merged = saved(&repo, Some(&mine), named(), none(), &[theirs]).unwrap(); + assert_eq!(file(&repo, &merged, "avatar.png"), other_bytes); +} diff --git a/desktop/crates/radicle-types/src/error.rs b/desktop/crates/radicle-types/src/error.rs index b86b03ece..2cecd0929 100644 --- a/desktop/crates/radicle-types/src/error.rs +++ b/desktop/crates/radicle-types/src/error.rs @@ -154,6 +154,17 @@ pub enum Error { #[error("revision not found: {0}")] RevisionNotFound(String), + /// Reading or writing an actor repository. + #[error(transparent)] + Actor(#[from] crate::actor::Error), + /// Reading a payload of an identity document. + #[error(transparent)] + Payload(#[from] radicle::identity::doc::PayloadError), + + /// Changing an identity. + #[error(transparent)] + Identity(#[from] radicle::cob::identity::Error), + /// Commit not found in the repository. #[error("commit not found: {0}")] CommitNotFound(radicle::git::Oid), @@ -271,6 +282,7 @@ impl Error { "AliasError.InvalidAlias" } Error::FileTooLarge(_) => "PayloadError.TooLarge", + Error::Actor(error) => error.code(), Error::ReviewExists => "PatchError.ReviewExists", Error::CommitNotFound(_) => "RepoError.CommitNotFound", Error::InvalidLocation(_) => "ArtifactError.InvalidLocation", diff --git a/desktop/crates/radicle-types/src/lib.rs b/desktop/crates/radicle-types/src/lib.rs index 27fd48176..6be66c025 100644 --- a/desktop/crates/radicle-types/src/lib.rs +++ b/desktop/crates/radicle-types/src/lib.rs @@ -1,4 +1,5 @@ use traits::Profile; +use traits::actor::Actor; use traits::artifact_node::ArtifactNode; use traits::board::Boards; use traits::cobs::Cobs; @@ -12,6 +13,7 @@ use traits::release_mut::ReleasesMut; use traits::repo::Repo; use traits::thread::Thread; +pub mod actor; pub mod artifact; pub mod auth; pub mod binaries; @@ -34,6 +36,7 @@ pub struct AppState { impl Boards for AppState {} impl Repo for AppState {} +impl Actor for AppState {} impl Thread for AppState {} impl Cobs for AppState {} impl Identity for AppState {} diff --git a/desktop/crates/radicle-types/src/repo.rs b/desktop/crates/radicle-types/src/repo.rs index 2894470f9..9119291c7 100644 --- a/desktop/crates/radicle-types/src/repo.rs +++ b/desktop/crates/radicle-types/src/repo.rs @@ -31,6 +31,8 @@ pub struct RepoSummary { /// False for a repository that is in storage but not seeded, which /// `rad ls --all` shows as "local". pub seeding: bool, + /// The repository is an actor's, a profile and not a project. + pub actor: bool, } #[derive(Serialize, TS)] diff --git a/desktop/crates/radicle-types/src/traits.rs b/desktop/crates/radicle-types/src/traits.rs index fa4d66ea5..9a454a4bf 100644 --- a/desktop/crates/radicle-types/src/traits.rs +++ b/desktop/crates/radicle-types/src/traits.rs @@ -10,6 +10,7 @@ use crate::error::Error; const ALIAS_SEARCH_LIMIT: usize = 50; +pub mod actor; pub mod artifact_node; pub mod board; pub mod cobs; diff --git a/desktop/crates/radicle-types/src/traits/actor.rs b/desktop/crates/radicle-types/src/traits/actor.rs new file mode 100644 index 000000000..d8f3d132e --- /dev/null +++ b/desktop/crates/radicle-types/src/traits/actor.rs @@ -0,0 +1,1612 @@ +use std::collections::BTreeSet; +use std::path::Path; + +use radicle::cob::identity::{self, ApplyError, Identity, IdentityMut}; +use radicle::cob::{self, EntryId, Title}; +use radicle::crypto::PublicKey; +use radicle::identity::{Did, Doc, RepoId}; +use radicle::node::{AliasStore as _, Handle}; +use radicle::profile::Signer; +use radicle::storage::git::Repository; +use radicle::storage::{ + ReadRepository, ReadStorage, RepositoryError, SignRepository, WriteRepository, +}; +use radicle::{Node, git, node}; + +use crate::actor; +use crate::actor::{ + ActorFork, ActorInfo, ActorKey, ActorPayload, ActorProfile, ActorRevision, Enrollment, + EnrollmentPreview, IdentityDocRevision, PROFILE_PATH, ProfileEdit, ProfileImages, + ResolvedActor, +}; +use crate::cobs::{CobOptions, PaginatedQuery}; +use crate::error::Error; +use crate::traits::repo::Repo; + +/// The default branch a new actor repository gets; after that, the default +/// branch is whatever its identity document names. +const NEW_BRANCH: &str = "main"; + +pub trait Actor: Repo { + /// The local actor, the one live individual actor that binds the local key. + /// `None` if there is none, `Ambiguous` if there are several, `ActorNewer` + /// as `bound` says. Scans every repository. + fn actor(&self) -> Result, Error> { + bound(self)? + .map(|(repo, history, resolved)| actor_info(self, &repo, &history, resolved)) + .transpose() + } + + /// The new actor for the local key, with `profile` and `images` as its first + /// commit; a failure leaves nothing behind. `Exists` if the key has an + /// actor, `Profile` if `profile` or a picture is invalid, `NameTaken` if the + /// key had an actor of that name, and the errors of `actor`. Scans every + /// repository. + fn create_actor( + &self, + profile: ActorProfile, + images: ProfileImages, + opts: CobOptions, + ) -> Result { + let (profile, images) = images.place(profile).map_err(actor::Error::Profile)?; + let profile = profile.normalized(); + profile.validate().map_err(actor::Error::Profile)?; + if let Some(existing) = self.actor()? { + return Err(actor::Error::Exists(existing.rid).into()); + } + + let radicle_profile = self.profile(); + let signer = radicle_profile.signer()?; + let public_key = radicle_profile.public_key; + let did = radicle_profile.did(); + let alias = radicle_profile.config.node.alias.to_string(); + let name = actor::repo_name(&profile.display_name, &alias); + let doc = actor::initial_doc(&name, NEW_BRANCH, did)?; + // The id is the document's hash, so a retired actor or a leftover of + // the same name has it already. + let rid = RepoId::from(doc.encode().map_err(actor::Error::Doc)?.0); + if radicle::storage::git::paths::repository(&radicle_profile.storage, &rid).exists() { + return Err(actor::Error::NameTaken(name).into()); + } + + let (repo, identity) = Repository::init(&doc, &radicle_profile.storage, &signer)?; + + // Everything after `init` must land, or the repository goes away: + // a half-built one would block every later attempt as "exists". + let finish = || -> Result<(Vec, ResolvedActor), Error> { + let tree = actor::profile_tree_with(&repo.backend, None, &profile, &images, &[])?; + let signature = repo.backend.signature()?; + let branch = git::fmt::RefString::try_from(NEW_BRANCH) + .expect("NEW_BRANCH is a valid branch name"); + let branch = git::refs::storage::branch_of(&public_key, &branch); + repo.backend.commit( + Some(branch.as_str()), + &signature, + &signature, + "Create profile", + &tree, + &[], + )?; + + repo.set_remote_identity_root_to(&public_key, identity)?; + repo.set_identity_head_to(identity)?; + repo.set_canonical_symbolic_refs("set-canonical from actor init")?; + repo.set_default_branch_to_canonical_head()?; + repo.sign_refs(&signer)?; + + let history = actor::identity_history(&repo)?; + let resolved = actor::resolve(rid, &history).ok_or(actor::Error::NotFound)?; + Ok((history, resolved)) + }; + let remove = || { + if let Err(removal) = repo.remove() { + log::error!("Not able to remove the half-built actor repository {rid}: {removal}"); + } + }; + let (history, resolved) = match finish() { + Ok(finished) => finished, + Err(e) => { + remove(); + return Err(e); + } + }; + + // Seeded only once the actor resolves, so a removal above leaves no + // policy behind. A repository the node will not seed is removed too, + // since no peer could fetch it. + let mut node = Node::new(radicle_profile.home().socket_from_env()); + if let Err(e) = radicle_profile.seed(rid, node::policy::Scope::All, &mut node) { + remove(); + return Err(e.into()); + } + // Peers learn a new repository from the node's inventory, which it + // gossips at once, so this is the announcement; a refs announcement + // would reach only peers that seed it already, and none does yet. + if opts.announce() + && node.is_running() + && let Err(e) = node.add_inventory(rid) + { + log::error!("Not able to add {rid} to the node's inventory: {e}"); + } + actor_info(self, &repo, &history, resolved) + } + + /// The actor after saving `profile`, and `images` next to it, each named by + /// its field of the profile. It becomes the actor's profile at once when + /// this key alone controls the actor, and otherwise waits for the other + /// controllers. Where it applies at once it also replaces the versions on + /// the other controllers' branches that are not behind it: those stay in + /// the history, and no file of theirs is carried over but a picture the + /// saved profile names and only theirs has; where both have a file of + /// that name, this key's stays. `Profile` if `profile` or a picture is + /// invalid; `ProfileNewer` if the saved profile, or one it would replace, + /// is from a newer client; `Diverged` if the controllers' branches have + /// split and the save could not close it, which happens when several other + /// controllers' branches have split from each other too; a save by a second + /// controller that has this one's commit closes it. Scans every repository. + fn update_actor_profile( + &self, + profile: ActorProfile, + images: ProfileImages, + opts: CobOptions, + ) -> Result { + let (profile, images) = images.place(profile).map_err(actor::Error::Profile)?; + let profile = profile.normalized(); + profile.validate().map_err(actor::Error::Profile)?; + let (current, repo) = current(self)?; + if current.profile_newer { + return Err(actor::Error::ProfileNewer.into()); + } + + let radicle_profile = self.profile(); + let signer = radicle_profile.signer()?; + let public_key = radicle_profile.public_key; + let default_branch = repo.identity_doc()?.project()?.default_branch().clone(); + let branch = git::refs::storage::branch_of(&public_key, &default_branch); + + // A controller under a threshold of one moves the canonical branch + // alone, and the move fails only when the controllers' branches have + // split, which is reported. Any other key writes its own branch and + // waits for the others. + let did = radicle_profile.did(); + let decides_alone = decides_alone(current.threshold, ¤t.keys, &did); + + // The new commit extends the canonical head, so a save from a device + // that is behind does not fork the branch: the form carries the whole + // profile. No head at all means the first commit. + let local = repo + .backend + .find_reference(branch.as_str()) + .ok() + .and_then(|reference| reference.peel_to_commit().ok()); + let parent = match current.head { + Some(base) => Some(repo.backend.find_commit(base.into())?), + None => local.clone(), + }; + // Without a canonical head the file replaced is this key's own, which + // `actor` did not read. + if current.head.is_none() + && let Some(parent) = &parent + && let actor::ProfileFile::Read(read) = + actor::read_profile(&repo.backend, parent.id().into())? + && read.newer + { + return Err(actor::Error::ProfileNewer.into()); + } + // The save replaces the other controllers' versions that are not + // behind the canonical head, so one from a newer client stops it. The + // new commit takes them as parents: it then descends from every side + // of a split, and the canonical branch can move again. + if current.forks.iter().any(|fork| fork.profile_newer) { + return Err(actor::Error::ProfileNewer.into()); + } + let mut seen = BTreeSet::new(); + let forks = current + .forks + .iter() + .filter(|fork| seen.insert(fork.head)) + .map(|fork| repo.backend.find_commit(fork.head.into())) + .collect::, _>>()?; + let parent_tree = parent.as_ref().map(|commit| commit.tree()).transpose()?; + let their_trees = forks + .iter() + .map(|commit| commit.tree()) + .collect::, _>>()?; + let tree = actor::profile_tree_with( + &repo.backend, + parent_tree.as_ref(), + &profile, + &images, + &their_trees, + )?; + let unchanged = forks.is_empty() + && parent + .as_ref() + .is_some_and(|parent| tree.id() == parent.tree_id()); + if unchanged && local.as_ref().map(|c| c.id()) == parent.as_ref().map(|c| c.id()) { + return Ok(current); + } + let commit = match &parent { + // The canonical profile again: the branch goes back onto its + // commit, which takes back an edit this key made on its own. + Some(parent) if unchanged => parent.id(), + _ => { + let parents = parent.iter().chain(&forks).collect::>(); + let signature = repo.backend.signature()?; + repo.backend.commit( + None, + &signature, + &signature, + &format!("Edit {PROFILE_PATH}"), + &tree, + &parents, + )? + } + }; + let canonical = format!("refs/heads/{default_branch}"); + let canonical_before = repo.backend.refname_to_id(&canonical).ok(); + // By force, since git only moves a ref to a commit whose parent is + // the ref's tip, which a device that is behind does not have; but + // only from the tip that was read, so a second writer since then + // keeps its branch and the undo below never restores a stale tip. + repo.backend.reference_matching( + branch.as_str(), + commit, + true, + local + .as_ref() + .map_or(git::raw::Oid::ZERO_SHA1, |local| local.id()), + "actor: edit profile", + )?; + + // An unsigned move would be invisible to peers, so it is undone when + // signing fails: the local branch and the canonical one, which may + // already point at the new commit. + let publish = || -> Result { + // Only a missing quorum is waited out; any other failure undoes + // the edit. + let moved = match repo.set_default_branch_to_canonical_head() { + Ok(_) => true, + Err(RepositoryError::Quorum(e)) => { + log::warn!("The canonical head of {} has no quorum: {e}", current.rid); + false + } + Err(e) => return Err(e.into()), + }; + repo.sign_refs(&signer)?; + Ok(moved) + }; + let moved = match publish() { + Ok(moved) => moved, + Err(e) => { + let restore = |name: &str, oid: Option| match oid { + Some(oid) => repo + .backend + .reference(name, oid, true, "actor: undo edit") + .map(|_| ()), + None => repo + .backend + .find_reference(name) + .and_then(|mut reference| reference.delete()), + }; + // Each restore runs whether or not the other one does. + let restores = [ + restore(branch.as_str(), local.as_ref().map(|local| local.id())), + restore(&canonical, canonical_before), + ]; + for undo in restores.into_iter().filter_map(Result::err) { + log::error!( + "Not able to undo the profile edit on {}: {undo}", + current.rid + ); + } + return Err(e); + } + }; + + if opts.announce() { + let mut node = Node::new(radicle_profile.home().socket_from_env()); + announce(&mut node, current.rid, public_key); + } + + if decides_alone && !moved { + return Err(actor::Error::Diverged.into()); + } + reread(self, &repo) + } + + /// The changes to the local actor's identity that `ActorInfo::pending` + /// does not list, newest first, down to its first version: the ones that + /// ended, and one still open that waits on another open change. A change + /// its author withdrew is not among them. Reads the whole identity + /// history and resolves the actor twice for each change, which stays + /// cheap while that history is as short as an actor's is meant to be. + /// `NotFound` if the key has no actor, and the errors of `actor`. Scans + /// every repository. + fn closed_actor_revisions(&self) -> Result, Error> { + let (repo, _, _) = bound(self)?.ok_or(actor::Error::NotFound)?; + let key_of = key_shown(self); + + Ok(actor::closed_revisions(&repo, repo.id)? + .into_iter() + .map(|closed| closed_revision(closed, &key_of)) + .collect()) + } + + /// The versions of the local actor's profile that this key has: those + /// behind the profile `actor` shows, and those this key saved on its own + /// branch that are not part of it yet. Each comes before every version + /// it was saved over. Gives `take` of them after the first `skip`, or all + /// without `take`; a caller that pages while the profile moves gets a + /// version twice, never misses one. Reads two versions for each one + /// returned and checks its ancestry once. `NotFound` if the key has no + /// actor, and the errors of `actor`. Scans every repository. + fn actor_profile_history( + &self, + skip: Option, + take: Option, + ) -> Result>, Error> { + let (repo, _, _) = bound(self)?.ok_or(actor::Error::NotFound)?; + let cursor = skip.unwrap_or(0); + + let head = repo.head().ok().map(|(_, oid)| git::raw::Oid::from(oid)); + let default_branch = repo.identity_doc()?.project()?.default_branch().clone(); + let branch = git::refs::storage::branch_of(&self.profile().public_key, &default_branch); + let own = repo.backend.refname_to_id(branch.as_str()).ok(); + + let mut walk = repo.backend.revwalk()?; + walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?; + + for tip in head.iter().chain(&own) { + walk.push(*tip)?; + } + + // One more than asked for says whether there are more. + let mut content = walk + .skip(cursor) + .take(take.map_or(usize::MAX, |take| take.saturating_add(1))) + .map(|oid| profile_edit(&repo, oid?, head)) + .collect::, _>>()?; + let more = take.is_some_and(|take| content.len() > take); + if let Some(take) = take { + content.truncate(take); + } + + Ok(PaginatedQuery { + cursor, + more, + content, + }) + } + + /// The actor at `rid` as it is before the local key joins it, for the user + /// to see what they would consent to. Writes and signs nothing. `NotFetched` + /// if `rid` is not in storage, `Blocked` if the user blocked it, `CopyStuck` + /// if the node can no longer fetch into the copy, `Exists` if the key has + /// an actor, `NotJoinable` if `rid` is not a live individual actor, and the + /// errors of `actor`. Scans every repository. + fn joinable_actor(&self, rid: RepoId) -> Result { + let Joinable { + repo, + history, + resolved, + } = joinable(self, rid)?; + + // The join needs only the identity. + actor_by_identity(self, &repo, &history, resolved) + } + + /// An enrollment code with the local key's consent to join the actor at + /// `rid`, for one of its controllers to approve. Writes nothing. Fails as + /// `joinable_actor` does. Scans every repository. + fn join_actor(&self, rid: RepoId) -> Result { + let Joinable { history, .. } = joinable(self, rid)?; + let parent = history + .last() + .expect("a resolved history has a revision") + .commit; + let signer = self.profile().signer()?; + + Ok(Enrollment::sign(rid, parent, &signer).encode()) + } + + /// The actor after binding the key that signed `code`, as a controller too + /// if `controller` is set. It applies at once when this key's vote is a + /// majority, and otherwise waits for the other controllers. Fails as + /// `checked_enrollment` does. If the identity changes meanwhile: `Stale` + /// when the code no longer fits it, `Moved` otherwise. Scans every + /// repository. + fn approve_enrollment( + &self, + code: String, + controller: bool, + opts: CobOptions, + ) -> Result { + let CheckedEnrollment { + enrollment, + repo, + history, + } = checked_enrollment(self, &code)?; + let head = history.last().expect("an actor's history has a revision"); + // A vote signs the whole document, so only a change that is exactly + // this enrollment gets it: one that adds more, or gives the key + // another role, gets a change of its own next to it. + let doc = actor::enrolled_doc(&head.doc, &enrollment, controller)?; + let description = format!("Add {}", enrollment.did); + vote_or_propose(self, &repo, &history, &doc, "Add key", description, opts).or_else(|e| { + // Another try helps only while the code still fits the identity; + // once it does not, the check says so. + if matches!(e, Error::Actor(actor::Error::Moved)) { + checked_enrollment(self, &code)?; + } + Err(e) + }) + } + + /// The key that signed `code`, for the user to compare with the other + /// machine before approving. Writes nothing. Fails as `checked_enrollment` + /// does. Scans every repository. + fn decode_enrollment(&self, code: String) -> Result { + let CheckedEnrollment { + enrollment, + history, + .. + } = checked_enrollment(self, &code)?; + let head = history.last().expect("an actor's history has a revision"); + let radicle_profile = self.profile(); + Ok(EnrollmentPreview { + did: enrollment.did, + alias: radicle_profile.aliases().alias(&enrollment.did), + controller: head.doc.is_delegate(&enrollment.did), + }) + } + + /// The actor after removing `did` from its keys and controllers. It applies + /// at once when this key's vote is a majority, and otherwise waits for the + /// other controllers. `RemoveSelf` for the local key, `KeyNotFound` for a key + /// the actor does not have, `Moved` if the identity changed meanwhile, and + /// the errors of `may_change_identity`. Scans every repository. + fn remove_actor_key(&self, did: Did, opts: CobOptions) -> Result { + let ActorWithHistory { + current, + repo, + history, + } = actor_with_history(self)?; + may_change_identity(self, ¤t)?; + let local = self.profile().did(); + // Keeping the local key keeps a controller this machine signs with, + // so the actor never ends up without one. + if did == local { + return Err(actor::Error::RemoveSelf.into()); + } + if !current.keys.iter().any(|key| key.did == did) { + return Err(actor::Error::KeyNotFound(did).into()); + } + + remove_key(self, &repo, &history, did, opts) + } + + /// Every live individual actor that binds the local key: more than one + /// when `actor` answers `Ambiguous`, for the user to pick the one to leave. + /// One that cannot be shown is left out, with a warning in the log. Writes + /// nothing. Scans every repository. + fn actors_of_key(&self) -> Result, Error> { + let (found, _) = bindings(self)?; + + // One that cannot be shown must not hide the rest. + Ok(found + .into_iter() + .filter_map(|(repo, history, resolved)| { + actor_by_identity(self, &repo, &history, resolved) + .inspect_err(|e| log::warn!("Not able to show the actor {}: {e}", repo.id)) + .ok() + }) + .collect()) + } + + /// The actor at `rid` after the local key's vote to remove itself from + /// it, which is how a key bound to several actors gets back to one. It + /// proposes the removal, or accepts it if another controller proposed + /// it, and the removal applies once a majority of the controllers has + /// accepted. `NotBound` if `rid` does not bind the key, `RemoveSelf` if no + /// other actor does, `Leaving` if the key's vote to leave another actor is + /// still open, `LeaveNeedsController` if the key has no vote in `rid`, + /// `PayloadNewer`, `OnlyController`, and `Moved` as `remove_actor_key`. It + /// fails before writing if the profile file cannot be read. Scans every + /// repository. + fn leave_actor(&self, rid: RepoId, opts: CobOptions) -> Result { + let local = self.profile().did(); + let ((repo, history, resolved), others) = binding_at(self, rid)?; + + // The last actor that binds the key is its own, which it keeps. + if others.is_empty() { + return Err(actor::Error::RemoveSelf.into()); + } + + not_leaving(&others, &local)?; + + // Read as it is read back after the vote, so that a failure comes + // before anything is written. + let current = actor_info(self, &repo, &history, resolved)?; + let controllers = current + .keys + .iter() + .filter(|key| key.controller) + .map(|key| key.did) + .collect::>(); + if !controllers.contains(&local) { + return Err(actor::Error::LeaveNeedsController { rid, controllers }.into()); + } + may_change_identity(self, ¤t)?; + if controllers.len() == 1 { + return Err(actor::Error::OnlyController(rid).into()); + } + + remove_key(self, &repo, &history, local, opts) + } + + /// The actor at `rid` after withdrawing the open change by which the local + /// key leaves it, which the key proposed with `leave_actor`. `NotBound` if + /// `rid` does not bind the key, `NotLeaving` if no such change is open, + /// `LeaveNotOwn` if another key proposed it, `Moved` if the withdrawal did + /// not hold. It fails before writing if the profile file cannot be read. + /// Scans every repository. + fn cancel_leave(&self, rid: RepoId, opts: CobOptions) -> Result { + let local = self.profile().did(); + let ((repo, history, resolved), _) = binding_at(self, rid)?; + + // As in `leave_actor`: read first as it is read back afterwards. + actor_info(self, &repo, &history, resolved)?; + + let open = leaves(&repo, &history, &local)?; + let Some(own) = open.iter().find(|open| open.author == local) else { + return Err(match open.is_empty() { + true => actor::Error::NotLeaving(rid), + false => actor::Error::LeaveNotOwn(rid), + } + .into()); + }; + let signer = self.profile().signer()?; + Identity::load_mut(&repo, &signer)? + .redact(own.id) + .map_err(vote_error)?; + let actor = publish_identity(self, &repo, opts)?; + landed(&repo, &own.id, |change| { + matches!(change.state, identity::State::Redacted(_)) + })?; + + Ok(actor) + } + + /// The actor at `rid` after the local key retires it, which ends it for + /// every key with no successor. Only for an actor the key alone controls, + /// where its vote decides, and only while another actor binds the key + /// too. `NotBound` if `rid` does not bind the key, `LastActor` if no other + /// actor does, `Leaving` if the key's vote to leave another actor is + /// still open, `NotController`, `PayloadNewer`, `RetireShared` if other + /// keys control the actor too, `Moved`. It fails before writing if the + /// profile file cannot be read. Scans every repository. + fn retire_actor(&self, rid: RepoId, opts: CobOptions) -> Result { + let local = self.profile().did(); + let ((repo, history, resolved), others) = binding_at(self, rid)?; + + if others.is_empty() { + return Err(actor::Error::LastActor(rid).into()); + } + + not_leaving(&others, &local)?; + + // As in `leave_actor`: read first as it is read back afterwards. + let current = actor_info(self, &repo, &history, resolved)?; + may_change_identity(self, ¤t)?; + + // A retirement that waited for other votes would be a change Desktop + // can neither show, sign nor withdraw. + if current.keys.iter().filter(|key| key.controller).count() > 1 { + return Err(actor::Error::RetireShared(rid).into()); + } + + let head = history.last().expect("an actor's history has a revision"); + let doc = actor::retired_doc(&head.doc)?; + let description = format!("Retire {rid}"); + + vote_or_propose( + self, + &repo, + &history, + &doc, + "Retire profile", + description, + opts, + ) + } + + /// The actor after accepting the open identity change `id`. + /// `RevisionNotFound`, `AlreadyVoted`, `VotedElsewhere`, `RevisionUnreadable` + /// if Desktop cannot show the whole change, `Moved` if the vote did not + /// hold, and the errors of `may_change_identity`. Scans every repository. + fn approve_actor_revision(&self, id: git::Oid, opts: CobOptions) -> Result { + let local = self.profile().did(); + vote( + self, + id, + opts, + |current, open| { + may_change_identity(self, current)?; + if open.accepted.contains(&local) { + return Err(actor::Error::AlreadyVoted.into()); + } + // A vote signs the whole document, what Desktop does not show + // of it included. + if open.unreadable { + return Err(actor::Error::RevisionUnreadable.into()); + } + Ok(()) + }, + |identity| identity.accept(&id), + |change| approved(change, &local), + ) + } + + /// The actor after withdrawing the open identity change `id`. + /// `RevisionNotFound`, `NotAuthor` if another key proposed it, `Moved` if + /// the withdrawal did not hold. Scans every repository. + fn withdraw_actor_revision(&self, id: git::Oid, opts: CobOptions) -> Result { + let local = self.profile().did(); + vote( + self, + id, + opts, + |_, open| { + if open.author != local { + return Err(actor::Error::NotAuthor.into()); + } + Ok(()) + }, + |identity| identity.redact(id), + |change| matches!(change.state, identity::State::Redacted(_)), + ) + } + + /// The actor after rejecting the open identity change `id`. + /// `NotController`, `AlreadyVoted`, `RevisionNotFound`, `Moved` if the + /// rejection did not hold. Scans every repository. + fn reject_actor_revision(&self, id: git::Oid, opts: CobOptions) -> Result { + let local = self.profile().did(); + vote( + self, + id, + opts, + |current, open| { + // A rejection signs a verdict, not the document, so a payload + // of a newer version is no bar to it. + controls(self, current)?; + if open.accepted.contains(&local) { + return Err(actor::Error::AlreadyVoted.into()); + } + Ok(()) + }, + |identity| identity.reject(id), + |change| { + matches!(change.state, identity::State::Rejected(_)) + || change.rejected().any(|did| did == local) + }, + ) + } +} + +/// The actor in `repo` after the local key's vote for the change that removes +/// `did` from its keys and controllers, as `vote_or_propose` casts it. +fn remove_key( + actor: &A, + repo: &Repository, + history: &[IdentityDocRevision], + did: Did, + opts: CobOptions, +) -> Result { + let head = history.last().expect("an actor's history has a revision"); + let doc = actor::removed_doc(&head.doc, &did)?; + let description = format!("Remove {did}"); + + vote_or_propose(actor, repo, history, &doc, "Remove key", description, opts) +} + +/// `Leaving` if `did`'s vote to leave one of `others` is still open: that +/// leave and another end of a binding, both going through, would leave the +/// key in no actor. +fn not_leaving(others: &[Bound], did: &Did) -> Result<(), Error> { + for (other, history, _) in others { + if !leaves(other, history, did)?.is_empty() { + return Err(actor::Error::Leaving(other.id).into()); + } + } + + Ok(()) +} + +/// The open changes to the actor in `repo` that hold `did`'s vote and after +/// which the actor would no longer bind it, whatever else they do. A +/// retirement the key approved is not one of them; Desktop opens none that +/// stays open. +fn leaves( + repo: &Repository, + history: &[IdentityDocRevision], + did: &Did, +) -> Result, Error> { + let unbinds = |open: &actor::OpenIdentityRevision| { + open.resolved + .as_ref() + .is_none_or(|proposed| !proposed.bound_keys().any(|bound| bound == *did)) + }; + + Ok(actor::open_revisions(repo, repo.id, history)? + .into_iter() + .filter(|open| open.accepted.contains(did) && unbinds(open)) + .collect()) +} + +/// `NotController` unless the local key is a controller of the actor. +fn controls(actor: &A, current: &ActorInfo) -> Result<(), Error> { + let local = actor.profile().did(); + if !current + .keys + .iter() + .any(|key| key.did == local && key.controller) + { + return Err(actor::Error::NotController.into()); + } + Ok(()) +} + +/// `NotController` unless the local key is a controller, `PayloadNewer` if the +/// payload is from a newer client. +fn may_change_identity(actor: &A, current: &ActorInfo) -> Result<(), Error> { + controls(actor, current)?; + if current.payload_newer { + return Err(actor::Error::PayloadNewer.into()); + } + Ok(()) +} + +/// The actor after accepting the open identity change whose document is +/// `doc`, or proposing `doc` if there is none, and publishing. `Moved` if the +/// identity is no longer at the head of `history`, which `doc` was built on; +/// nothing is written then. `Moved` too if the change does not hold this +/// key's vote afterwards: by then the vote is written, signed and announced, +/// and counts for nothing. +fn vote_or_propose( + actor: &A, + repo: &Repository, + history: &[IdentityDocRevision], + doc: &Doc, + title: &str, + description: String, + opts: CobOptions, +) -> Result { + let radicle_profile = actor.profile(); + let local = radicle_profile.did(); + let matching = actor::open_revisions(repo, repo.id, history)? + .into_iter() + .find(|open| open.doc == *doc); + + let signer = radicle_profile.signer()?; + let mut identity = Identity::load_mut(repo, &signer)?; + + // `doc` and the open change were read from `history`. On any other head + // they would undo what came in between, and a consent binds only on the + // head it names. + let head = history.last().expect("an actor's history has a revision"); + if identity.current != head.commit { + return Err(actor::Error::Moved.into()); + } + + let id = match matching { + // Accepted already, maybe by an attempt that failed to publish; + // publishing again is the retry. + Some(open) if open.accepted.contains(&local) => open.id, + Some(open) => { + identity.accept(&open.id).map_err(vote_error)?; + open.id + } + None => { + let title = Title::new(title).expect("the title is valid"); + identity + .update(title, description, doc) + .map_err(vote_error)? + } + }; + let actor = publish_identity(actor, repo, opts)?; + landed(repo, &id, |change| approved(change, &local))?; + + Ok(actor) +} + +/// `Moved` unless the identity in storage holds the change `id` as `held` +/// wants it. Something else can change the identity while a vote is written, +/// and the vote then counts for nothing without an error, so success is said +/// only of what is read back. +fn landed( + repo: &Repository, + id: &git::Oid, + held: impl FnOnce(&identity::Revision) -> bool, +) -> Result<(), Error> { + if repo.identity()?.revision(id).is_some_and(held) { + Ok(()) + } else { + Err(actor::Error::Moved.into()) + } +} + +/// Whether `change` is the current identity, or open with `local`'s vote for +/// it. +fn approved(change: &identity::Revision, local: &Did) -> bool { + change.is_accepted() || (change.is_active() && change.accepted().any(|did| did == *local)) +} + +/// The actor after pointing the identity at what the votes accept, then +/// signing and announcing the refs. +fn publish_identity( + actor: &A, + repo: &Repository, + opts: CobOptions, +) -> Result { + let radicle_profile = actor.profile(); + repo.set_identity_head()?; + repo.sign_refs(&radicle_profile.signer()?)?; + if opts.announce() { + let mut node = Node::new(radicle_profile.home().socket_from_env()); + announce(&mut node, repo.id, radicle_profile.public_key); + } + reread(actor, repo) +} + +/// The actor in `repo` as it is now, which may no longer bind the local key. +fn reread(actor: &A, repo: &Repository) -> Result { + let history = actor::identity_history(repo)?; + let resolved = actor::resolve(repo.id, &history).ok_or(actor::Error::NotFound)?; + actor_info(actor, repo, &history, resolved) +} + +/// The actor in `repo` as Desktop shows it, with the profile as the file +/// holds it, so the editor shows what `validate` would refuse. +fn actor_info( + actor: &A, + repo: &Repository, + history: &[IdentityDocRevision], + resolved: ResolvedActor, +) -> Result { + let head = repo.head().ok().map(|(_, oid)| oid); + let read = profile_file(repo, head)?; + + actor_shown(actor, repo, history, resolved, head, read) +} + +/// `actor_info` for a step that needs only the identity: a profile file that +/// cannot be read at all is shown as such and stops nothing. +fn actor_by_identity( + actor: &A, + repo: &Repository, + history: &[IdentityDocRevision], + resolved: ResolvedActor, +) -> Result { + let head = repo.head().ok().map(|(_, oid)| oid); + let read = profile_file(repo, head).unwrap_or_else(|e| { + log::warn!("Not able to read the profile of {}: {e}", repo.id); + actor::ProfileFile::Unreadable + }); + + actor_shown(actor, repo, history, resolved, head, read) +} + +/// The profile file at `head`, the default branch's commit if it has one. +fn profile_file( + repo: &Repository, + head: Option, +) -> Result { + match head { + Some(head) => actor::read_profile(&repo.backend, head), + None => Ok(actor::ProfileFile::Missing), + } +} + +/// `actor_info`, given the profile file `read` at `head`. +fn actor_shown( + actor: &A, + repo: &Repository, + history: &[IdentityDocRevision], + resolved: ResolvedActor, + head: Option, + read: actor::ProfileFile, +) -> Result { + let local = actor.profile().public_key; + let doc = &history + .last() + .expect("a resolved history has a revision") + .doc; + let (file, profile_newer, profile_unreadable) = match read { + actor::ProfileFile::Read(read) => (Some(read.profile.clone()), read.newer, false), + actor::ProfileFile::Unreadable => (None, false, true), + actor::ProfileFile::Missing => (None, false, false), + }; + let key_of = key_shown(actor); + let keys: Vec = resolved.keys.iter().map(&key_of).collect(); + let pending = pending(repo, history, &resolved, &key_of)?; + // Only a key that publishes alone can close a split, by saving. + let forks = match head { + Some(head) if decides_alone(doc.threshold(), &keys, &local.into()) => { + forks(repo, doc, &resolved, &local, head)? + } + _ => Vec::new(), + }; + + Ok(ActorInfo { + rid: repo.id, + kind: resolved.kind, + keys, + threshold: doc.threshold(), + majority: doc.majority(), + payload_newer: resolved.payload_newer, + profile: file, + profile_newer, + profile_unreadable, + head, + pending, + forks, + }) +} + +/// A key as Desktop shows it, with the name its node goes by. +fn key_shown(actor: &A) -> impl Fn(&actor::ResolvedKey) -> ActorKey { + let profile = actor.profile(); + let aliases = profile.aliases(); + let local = profile.public_key; + let own = profile.config.node.alias.clone(); + + move |key| ActorKey { + alias: if *key.did == local { + Some(own.clone()) + } else { + aliases.alias(&key.did) + }, + did: key.did, + bound: key.bound, + controller: key.controller, + added_at: key.added_at, + } +} + +/// Whether `did` moves the canonical branch by itself: it is a controller +/// under a threshold of one. +fn decides_alone(threshold: usize, keys: &[ActorKey], did: &Did) -> bool { + threshold == 1 && keys.iter().any(|key| key.controller && key.did == *did) +} + +/// The versions of the profile on the branches of the controllers other than +/// `local` that are not behind `head`: each has split from it, or is ahead +/// of it. A branch that cannot be read is left out. +fn forks( + repo: &Repository, + doc: &Doc, + resolved: &ResolvedActor, + local: &PublicKey, + head: git::Oid, +) -> Result, Error> { + let default_branch = doc.project()?.default_branch().clone(); + let head = git::raw::Oid::from(head); + let profile_at = |commit: git::raw::Oid| { + Ok::<_, actor::Error>(match actor::read_profile(&repo.backend, commit.into())? { + actor::ProfileFile::Read(read) => Some(*read), + actor::ProfileFile::Unreadable | actor::ProfileFile::Missing => None, + }) + }; + let fork = |did: Did, tip: git::raw::Oid| { + if tip == head || repo.backend.graph_descendant_of(head, tip)? { + return Ok(None); + } + let theirs = profile_at(tip)?; + // Two versions that each merged the other split at several commits, + // and none of them is where both started from. + let split = match repo.backend.merge_bases(head, tip) { + Ok(splits) if splits.len() == 1 => Some(splits[0]), + Ok(_) => None, + Err(e) => { + log::warn!("Not able to find where {tip} split from {head}: {e}"); + None + } + }; + // A newer profile is read without the fields this version does not + // know, which is not what the two versions started from. + let base = match split { + Some(split) => profile_at(split)?.filter(|read| !read.newer), + None => None, + }; + // With no commit to count from, the other files are those that + // differ from the version shown. + let before = repo.backend.find_commit(split.unwrap_or(head))?.tree()?; + let after = repo.backend.find_commit(tip)?.tree()?; + let other_files = repo + .backend + .diff_tree_to_tree(Some(&before), Some(&after), None)? + .deltas() + .any(|delta| delta.new_file().path() != Some(Path::new(PROFILE_PATH))); + let changes = match (&base, &theirs) { + (Some(base), Some(theirs)) => { + Some(actor::profile_changes(&base.profile, &theirs.profile)?) + } + _ => None, + }; + + Ok::<_, actor::Error>(Some(ActorFork { + did, + head: tip.into(), + profile_newer: theirs.as_ref().is_some_and(|read| read.newer), + profile: theirs.map(|read| read.profile), + base: base.map(|read| read.profile), + changes, + other_files, + })) + }; + let mut forks = Vec::new(); + let others = resolved + .keys + .iter() + .filter(|key| key.controller && *key.did != *local); + + for key in others { + let branch = git::refs::storage::branch_of(&key.did, &default_branch); + let Ok(tip) = repo.backend.refname_to_id(branch.as_str()) else { + continue; + }; + match fork(key.did, tip) { + Ok(fork) => forks.extend(fork), + Err(e) => log::warn!( + "Not able to read the profile of {} on {}: {e}", + repo.id, + key.did + ), + } + } + Ok(forks) +} + +/// The open identity changes of the actor in `repo`, each with the keys it +/// adds and removes. +fn pending( + repo: &Repository, + history: &[IdentityDocRevision], + resolved: &ResolvedActor, + key_of: impl Fn(&actor::ResolvedKey) -> ActorKey, +) -> Result, Error> { + let doc = &history + .last() + .expect("a resolved history has a revision") + .doc; + let pending = actor::open_revisions(repo, repo.id, history)? + .into_iter() + .map(|open| { + let effect = effect(doc, resolved, &open.doc, open.resolved.as_ref(), &key_of); + ActorRevision { + id: open.id, + author: open.author, + created_at: open.time, + added: effect.added, + removed: effect.removed, + threshold: effect.threshold, + accepted: voters(doc, open.accepted), + rejected: voters(doc, open.rejected), + unreadable: effect.unreadable, + state: actor::RevisionState::Open, + } + }) + .collect(); + Ok(pending) +} + +/// What a change to the identity does, as Desktop shows it. +struct Effect { + added: Vec, + removed: Vec, + threshold: Option, + unreadable: bool, +} + +/// What the change from `doc`, which gives the actor `resolved`, to +/// `proposed_doc` does; `proposed` is the actor that one gives, if any. +fn effect( + doc: &Doc, + resolved: &ResolvedActor, + proposed_doc: &Doc, + proposed: Option<&ResolvedActor>, + key_of: impl Fn(&actor::ResolvedKey) -> ActorKey, +) -> Effect { + let (added, removed) = match proposed { + Some(proposed) => ( + proposed + .keys + .iter() + .filter(|key| !resolved.keys.contains(key)) + .map(&key_of) + .collect(), + resolved + .keys + .iter() + .filter(|key| !proposed.keys.iter().any(|k| k.did == key.did)) + .map(|key| key.did) + .collect(), + ), + None => (Vec::new(), Vec::new()), + }; + // A keys entry the change edits without adding or removing that key is + // one Desktop does not show. + let shown = added + .iter() + .map(|key: &ActorKey| key.did) + .chain(removed.iter().copied()) + .map(|did| did.to_string()) + .collect::>(); + let hidden = actor::changed_key_entries(doc, proposed_doc) + .iter() + .any(|entry| !shown.contains(entry)); + + Effect { + added, + removed, + threshold: (proposed_doc.threshold() < doc.threshold()).then_some(proposed_doc.threshold()), + unreadable: proposed.is_none_or(|proposed| proposed.payload_newer) + || !actor::changes_only_keys(doc, proposed_doc) + || hidden, + } +} + +/// Those of `dids` that vote on a change to `doc`. +fn voters(doc: &Doc, dids: Vec) -> Vec { + dids.into_iter() + .filter(|did| doc.is_delegate(did)) + .collect() +} + +/// A change `closed_revisions` gives, as Desktop shows it. +fn closed_revision( + closed: actor::ClosedIdentityRevision, + key_of: impl Fn(&actor::ResolvedKey) -> ActorKey, +) -> ActorRevision { + let (effect, voting) = match &closed.before { + Some((doc, Some(resolved))) => ( + effect(doc, resolved, &closed.doc, closed.after.as_ref(), &key_of), + doc, + ), + // What it was proposed on gave no actor, so what it did to one cannot + // be told. + Some((doc, None)) => ( + Effect { + added: Vec::new(), + removed: Vec::new(), + threshold: None, + unreadable: true, + }, + doc, + ), + // The first version adds the keys the actor starts with, and its own + // controllers are the ones that made it. + None => ( + Effect { + added: closed + .after + .iter() + .flat_map(|actor| &actor.keys) + .map(&key_of) + .collect(), + removed: Vec::new(), + threshold: None, + unreadable: closed + .after + .as_ref() + .is_none_or(|actor| actor.payload_newer), + }, + &closed.doc, + ), + }; + + ActorRevision { + id: closed.id, + author: closed.author, + created_at: closed.time, + added: effect.added, + removed: effect.removed, + threshold: effect.threshold, + accepted: voters(voting, closed.accepted), + rejected: voters(voting, closed.rejected), + unreadable: effect.unreadable, + state: closed.state, + } +} + +/// The profile fields in which `commit` differs from the first version it +/// was saved over; `None` if either holds a profile that cannot be read in +/// full. +fn edited_fields( + repo: &Repository, + commit: &git::raw::Commit, +) -> Result>, git::raw::Error> { + // `None` if the profile cannot be read in full, `Some(None)` if the + // version has no profile file. + let whole = |commit: &git::raw::Commit| { + Ok::<_, git::raw::Error>( + match actor::read_profile(&repo.backend, commit.id().into())? { + actor::ProfileFile::Read(read) if !read.newer => Some(Some(read.profile)), + actor::ProfileFile::Missing => Some(None), + _ => None, + }, + ) + }; + let Some(after) = whole(commit)? else { + return Ok(None); + }; + let Some(parent) = commit.parents().next() else { + return Ok(Some(actor::changed_fields(None, after.as_ref()))); + }; + let Some(before) = whole(&parent)? else { + return Ok(None); + }; + let mut fields = actor::changed_fields(before.as_ref(), after.as_ref()); + + // A picture saved again under the name it had. + let (old, new) = (parent.tree()?, commit.tree()?); + let pictures = after + .iter() + .flat_map(|after| [("avatar", &after.avatar), ("banner", &after.banner)]); + for (field, path) in pictures { + let file = |tree: &git::raw::Tree| { + let path = path.as_deref().filter(|path| !path.contains(':'))?; + Some(tree.get_path(Path::new(path)).ok()?.id()) + }; + if !fields.contains(&field) && file(&old) != file(&new) { + fields.push(field); + } + } + + Ok(Some(fields)) +} + +/// The version `oid` of the profile in `repo`; `head` is the commit of the +/// profile `actor` shows. +fn profile_edit( + repo: &Repository, + oid: git::raw::Oid, + head: Option, +) -> Result { + let commit = repo.backend.find_commit(oid)?; + // A version that cannot be read is still one that was saved. + let fields = edited_fields(repo, &commit).unwrap_or_else(|e| { + log::warn!("Not able to read the version {oid} of {}: {e}", repo.id); + None + }); + // Storage writes a commit as `alias@key`. + let author = commit + .author() + .email() + .ok() + .and_then(|email| email.rsplit_once('@')) + .and_then(|(_, key)| key.parse::().ok()) + .map(Did::from); + // A version whose place cannot be told is not said to be the profile's. + let live = head.is_some_and(|head| { + head == oid + || repo + .backend + .graph_descendant_of(head, oid) + .unwrap_or_else(|e| { + log::warn!("Not able to place the version {oid} of {}: {e}", repo.id); + false + }) + }); + + Ok(ProfileEdit { + commit: oid.into(), + parents: commit.parent_ids().map(Into::into).collect(), + saved_at: commit.time().seconds(), + author, + fields: fields.map(|fields| fields.into_iter().map(str::to_owned).collect()), + live, + }) +} + +/// Every readable repository in storage with its current identity document. +/// Unlike radicle's own listing, it keeps one whose default branch has no +/// quorum. +fn repositories(storage: &radicle::storage::git::Storage) -> Result, Error> { + let mut repos = Vec::new(); + for entry in std::fs::read_dir(storage.path())? { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let Ok(rid) = RepoId::try_from(entry.file_name()) else { + continue; + }; + match storage.repository(rid).and_then(|repo| repo.identity_doc()) { + Ok(doc) => repos.push((rid, doc.into())), + Err(e) => log::warn!("Skipping {rid} while looking for the actor: {e}"), + } + } + Ok(repos) +} + +/// The repository of an actor, its identity history, and what that resolves +/// to. +type Bound = (Repository, Vec, ResolvedActor); + +/// The one live individual actor that binds the local key. `None` if there +/// is none, `Ambiguous` if there are several. `ActorNewer` if there is none +/// and the key is bound by an actor that cannot be told to be one, or +/// controls one whose keys cannot be read, so that the key is not given a +/// second actor. A key such an actor binds without control is not found: +/// nothing readable ties it to the actor. Scans every repository. +fn bound(actor: &A) -> Result, Error> { + let (mut found, unsure) = bindings(actor)?; + + match found.len() { + 0 => unsure.map_or(Ok(None), |rid| Err(actor::Error::ActorNewer(rid).into())), + 1 => Ok(Some(found.remove(0))), + _ => { + Err(actor::Error::Ambiguous(found.iter().map(|(repo, _, _)| repo.id).collect()).into()) + } + } +} + +/// Every live individual actor that binds the local key, and an actor that +/// may bind it but cannot be read well enough to tell, if there is one. +/// Scans every repository. +fn bindings(actor: &A) -> Result<(Vec, Option), Error> { + let profile = actor.profile(); + let did = profile.did(); + let mut found = Vec::new(); + let mut unsure = None; + + for (rid, doc) in repositories(&profile.storage)? { + // Only a repository whose current document names the key has + // its history walked. + let Some(payload) = ActorPayload::of(&doc) else { + if ActorPayload::marks(&doc) { + log::warn!( + "Skipping {rid} while looking for the actor: its actor payload is not valid" + ); + } + continue; + }; + if !payload.keys.contains_key(&did) && !doc.is_delegate(&did) { + continue; + } + // One repository that cannot be read must not hide the rest. + let loaded = profile + .storage + .repository(rid) + .map_err(Error::from) + .and_then(|repo| Ok((actor::identity_history(&repo)?, repo))); + let (history, repo) = match loaded { + Ok(loaded) => loaded, + Err(e) => { + log::warn!("Skipping {rid} while looking for the actor: {e}"); + continue; + } + }; + let Some(resolved) = actor::resolve(rid, &history) else { + continue; + }; + let bound = resolved.bound_keys().any(|bound| bound == did); + // Where the keys cannot be read, control is all that shows the key + // is the actor's. + if resolved.unsure && (bound || resolved.keys.iter().any(|key| key.did == did)) { + unsure = Some(rid); + } else if bound && resolved.is_live_individual() { + found.push((repo, history, resolved)); + } + } + + Ok((found, unsure)) +} + +/// The actor at `rid` among those that bind the local key, and the others. +/// `NotBound` if it is not one of them. Scans every repository. +fn binding_at(actor: &A, rid: RepoId) -> Result<(Bound, Vec), Error> { + let (mut found, _) = bindings(actor)?; + let at = found + .iter() + .position(|(repo, _, _)| repo.id == rid) + .ok_or(actor::Error::NotBound(rid))?; + + Ok((found.remove(at), found)) +} + +/// What `actor` finds, with its repository. `NotFound` if there is none. +/// Scans every repository. +fn current(actor: &A) -> Result<(ActorInfo, Repository), Error> { + let ActorWithHistory { current, repo, .. } = actor_with_history(actor)?; + + Ok((current, repo)) +} + +/// The actor after applying `vote` to the open identity change `id`, once +/// `check` passes, and publishing. `RevisionNotFound` if no open change has +/// `id`. `Moved` if the change is not as `held` wants it afterwards: by then +/// the vote is written, signed and announced, and counts for nothing. Scans +/// every repository. +fn vote( + actor: &A, + id: git::Oid, + opts: CobOptions, + check: impl FnOnce(&ActorInfo, &ActorRevision) -> Result<(), Error>, + cast: impl FnOnce(&mut IdentityMut<'_, '_, Repository, Signer>) -> Result, + held: impl FnOnce(&identity::Revision) -> bool, +) -> Result { + let (current, repo) = current(actor)?; + let open = current + .pending + .iter() + .find(|open| open.id == id) + .ok_or(actor::Error::RevisionNotFound(id))?; + check(¤t, open)?; + let signer = actor.profile().signer()?; + // A key gets one verdict on a change, and one accepted change per + // identity version; the identity enforces both, and its refusal maps to + // Desktop's errors. + cast(&mut Identity::load_mut(&repo, &signer)?).map_err(vote_error)?; + let actor = publish_identity(actor, &repo, opts)?; + landed(&repo, &id, held)?; + + Ok(actor) +} + +/// The app's error for `e`, which the identity raised on a vote. +fn vote_error(e: identity::Error) -> Error { + vote_refused(&e).unwrap_or_else(|| e.into()) +} + +/// The app's error for a vote the identity refused because the key already +/// voted on the change or accepted another at the same version. +fn vote_refused(e: &identity::Error) -> Option { + match e { + identity::Error::Apply(ApplyError::DuplicateVerdict) => { + Some(actor::Error::AlreadyVoted.into()) + } + identity::Error::Apply(ApplyError::SiblingAccepted { .. }) => { + Some(actor::Error::VotedElsewhere.into()) + } + identity::Error::Store(cob::store::Error::Update(cob::error::Update::Evaluate(inner))) => { + inner + .downcast_ref::() + .and_then(vote_refused) + } + _ => None, + } +} + +/// The local actor, with what an identity change builds on. +struct ActorWithHistory { + current: ActorInfo, + repo: Repository, + /// The actor's identity history, root first. + history: Vec, +} + +/// The local actor with its repository and identity history. The caller +/// checks `may_change_identity`. `NotFound` if there is none. Scans every +/// repository. +fn actor_with_history(actor: &A) -> Result { + let (repo, history, resolved) = bound(actor)?.ok_or(actor::Error::NotFound)?; + // The actor as this history gives it, so that what the caller checks and + // what it builds on are one state. + let current = actor_info(actor, &repo, &history, resolved)?; + + Ok(ActorWithHistory { + current, + repo, + history, + }) +} + +/// An actor the local key may join. +struct Joinable { + repo: Repository, + history: Vec, + resolved: ResolvedActor, +} + +/// The actor at `rid`, if the local key may join it: see `joinable_actor` +/// for the refusals. +fn joinable(actor: &A, rid: RepoId) -> Result { + if let Some(existing) = actor.actor()? { + return Err(actor::Error::Exists(existing.rid).into()); + } + let radicle_profile = actor.profile(); + if !radicle::storage::git::paths::repository(&radicle_profile.storage, &rid).exists() { + // The row the user set, not the node's default for a missing one. + let policies = radicle_profile.policies()?; + if let Some(row) = (*policies).seed_policy(&rid)? + && matches!(row.policy, node::policy::SeedingPolicy::Block) + { + return Err(actor::Error::Blocked(rid).into()); + } + return Err(actor::Error::NotFetched(rid).into()); + } + let repo = radicle_profile.storage.repository(rid)?; + let history = actor::identity_history(&repo)?; + let resolved = actor::resolve(rid, &history) + .filter(ResolvedActor::is_live_individual) + .ok_or(actor::Error::NotJoinable(rid))?; + // The node asks for the head before it fetches, and gives up on a copy + // that has none. + if repo.head().is_err() { + return Err(actor::Error::CopyStuck(rid).into()); + } + + Ok(Joinable { + repo, + history, + resolved, + }) +} + +/// An enrollment code that passed every check but the vote. +struct CheckedEnrollment { + enrollment: Enrollment, + repo: Repository, + /// The actor's identity history, ending at the code's anchor. + history: Vec, +} + +/// The enrollment in `code`, checked against the local actor. `WrongActor`, +/// `InvalidCode`, `AlreadyBound`, `Stale` if the identity changed since the +/// code was made, and the errors of `may_change_identity`. +fn checked_enrollment( + actor: &A, + code: &str, +) -> Result { + let enrollment = Enrollment::decode(code).map_err(|_| actor::Error::InvalidCode)?; + let ActorWithHistory { + current, + repo, + history, + } = actor_with_history(actor)?; + if enrollment.rid != current.rid { + return Err(actor::Error::WrongActor(enrollment.rid).into()); + } + may_change_identity(actor, ¤t)?; + if !enrollment.verifies() { + return Err(actor::Error::InvalidCode.into()); + } + if current + .keys + .iter() + .any(|key| key.did == enrollment.did && key.bound) + { + return Err(actor::Error::AlreadyBound.into()); + } + + let head = history.last().expect("an actor's history has a revision"); + // The consent is anchored to the identity it saw; on any other it binds + // nothing, and the joining key has to make a new code. + if enrollment.parent != head.commit { + return Err(actor::Error::Stale.into()); + } + // Whether the payload has room for the key does not depend on its role. + actor::enrolled_doc(&head.doc, &enrollment, false)?; + Ok(CheckedEnrollment { + enrollment, + repo, + history, + }) +} + +/// Announce new refs; a node that is not running announces them when it +/// starts. +fn announce(node: &mut Node, rid: RepoId, public_key: PublicKey) { + if node.is_running() + && let Err(e) = node.announce_refs_for(rid, [public_key]) + { + log::error!("Not able to announce changes: {e}"); + } +} + +#[cfg(test)] +mod tests; diff --git a/desktop/crates/radicle-types/src/traits/actor/tests.rs b/desktop/crates/radicle-types/src/traits/actor/tests.rs new file mode 100644 index 000000000..739758e17 --- /dev/null +++ b/desktop/crates/radicle-types/src/traits/actor/tests.rs @@ -0,0 +1,3034 @@ +use radicle::cob::Title; +use radicle::crypto::{PublicKey, Seed, Signer as _, SigningKey}; +use radicle::identity::{Did, Identity, RepoId}; +use radicle::storage::{ + ReadRepository, ReadStorage, RemoteRepository as _, SignRepository, WriteRepository as _, + WriteStorage, +}; + +use std::str::FromStr as _; + +use radicle::identity::doc::PayloadId; + +use super::Actor; +use crate::actor; +use crate::actor::{ActorProfile, Enrollment}; +use crate::cobs::CobOptions; +use crate::error::Error; +use crate::traits::Profile; +use crate::traits::repo::Repo; +use crate::{AppState, test}; + +fn quiet() -> CobOptions { + serde_json::from_value(serde_json::json!({ "announce": false })).unwrap() +} + +fn named(display_name: &str) -> ActorProfile { + serde_json::from_value(serde_json::json!({ "version": 1, "displayName": display_name })) + .unwrap() +} + +/// An app whose key, of seed `0xff`, made the actor alice. +fn actor_state() -> (tempfile::TempDir, AppState, RepoId) { + let tmp = tempfile::tempdir().unwrap(); + let state = AppState { + profile: test::profile(&tmp.path().join("home"), [0xff; 32]), + }; + let rid = state + .create_actor(named("alice"), Default::default(), quiet()) + .unwrap() + .rid; + (tmp, state, rid) +} + +fn key(seed: u8) -> SigningKey { + SigningKey::from_seed(Seed::new([seed; 32])) +} + +fn oid(repo: &radicle::storage::git::Repository, name: &str) -> Option { + repo.backend.refname_to_id(name).ok() +} + +#[test] +fn a_failed_signing_leaves_both_branches_as_they_were() { + let (_tmp, state, rid) = actor_state(); + let repo = state.profile.storage.repository(rid).unwrap(); + let key = state.profile.public_key; + let local = format!("refs/namespaces/{key}/refs/heads/main"); + let canonical = "refs/heads/main"; + let before = (oid(&repo, &local), oid(&repo, canonical)); + + // Git refuses to write a ref whose lock file exists, so signing fails. + let lock = repo + .path() + .join(format!("refs/namespaces/{key}/refs/rad/sigrefs.lock")); + std::fs::create_dir_all(lock.parent().unwrap()).unwrap(); + std::fs::write(&lock, "").unwrap(); + + assert!( + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .is_err() + ); + assert_eq!((oid(&repo, &local), oid(&repo, canonical)), before); + let shown = state.actor().unwrap().unwrap().profile.unwrap(); + assert_eq!(shown.display_name, "alice"); + + std::fs::remove_file(&lock).unwrap(); + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + assert_eq!(saved.profile.unwrap().display_name, "bob"); +} + +#[test] +fn a_key_that_cannot_publish_alone_writes_only_its_own_branch() { + let (_tmp, state, rid) = actor_state(); + // A second controller and a threshold of two: the canonical branch + // has no quorum until the other key carries the same commit. + share_with(&state, rid, &key(0xee), 2); + let repo = state.profile.storage.repository(rid).unwrap(); + let key = state.profile.public_key; + let local = format!("refs/namespaces/{key}/refs/heads/main"); + let canonical = "refs/heads/main"; + let before = (oid(&repo, &local), oid(&repo, canonical)); + + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + + assert_ne!( + oid(&repo, &local), + before.0, + "the edit is on the local branch" + ); + assert_eq!( + oid(&repo, canonical), + before.1, + "the canonical branch stays put" + ); + let refs = repo.remote(&key).unwrap().refs; + assert_eq!( + refs.get(&radicle::git::fmt::qualified!("refs/heads/main")), + oid(&repo, &local).map(Into::into), + "the edit is signed" + ); +} + +/// The identity COB of the local key, as its namespace holds it. +fn local_cob(repo: &radicle::storage::git::Repository, key: &PublicKey) -> Option { + repo.backend + .references_glob(&format!("refs/namespaces/{key}/refs/cobs/xyz.radicle.id/*")) + .unwrap() + .next() + .and_then(|r| r.ok()?.target()) + .map(|oid| oid.to_string()) +} + +/// The identity COB of the local key, as its signed refs vouch for it. +fn signed_cob(repo: &radicle::storage::git::Repository, key: &PublicKey) -> Option { + repo.remote(key) + .unwrap() + .refs + .iter() + .find(|(name, _)| name.starts_with("refs/cobs/xyz.radicle.id/")) + .map(|(_, oid)| oid.to_string()) +} + +#[test] +fn a_retry_signs_a_vote_the_store_could_not() { + let (_tmp, state, rid) = actor_state(); + // Two controllers: the enrollment stays open with this key's vote on it. + share_with(&state, rid, &key(0xee), 2); + let joining = key(0xdd); + let code = code(&state, &joining); + let repo = state.profile.storage.repository(rid).unwrap(); + let key = state.profile.public_key; + + // The store writes the vote, then fails to sign the refs: the vote is + // in the identity, and no peer can see it. + let lock = repo + .path() + .join(format!("refs/namespaces/{key}/refs/rad/sigrefs.lock")); + std::fs::create_dir_all(lock.parent().unwrap()).unwrap(); + std::fs::write(&lock, "").unwrap(); + assert!( + state + .approve_enrollment(code.clone(), true, quiet()) + .is_err() + ); + assert_ne!(signed_cob(&repo, &key), local_cob(&repo, &key)); + std::fs::remove_file(&lock).unwrap(); + + // The retry finds the vote cast already and publishes it. + let info = state.approve_enrollment(code, true, quiet()).unwrap(); + assert_eq!(info.pending.len(), 1); + assert!(info.pending[0].accepted.contains(&Did::from(key))); + assert_eq!(signed_cob(&repo, &key), local_cob(&repo, &key)); +} + +#[test] +fn a_failed_canonical_move_undoes_the_edit() { + let (_tmp, state, rid) = actor_state(); + // Two controllers under a threshold of one: this key moves the + // canonical branch alone, and a failure to is not a split. + share_with(&state, rid, &key(0xee), 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let key = state.profile.public_key; + let local = format!("refs/namespaces/{key}/refs/heads/main"); + let canonical = "refs/heads/main"; + let before = (oid(&repo, &local), oid(&repo, canonical)); + + let lock = repo.path().join("refs/heads/main.lock"); + std::fs::write(&lock, "").unwrap(); + let refused = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap_err(); + assert!( + !matches!(refused, Error::Actor(actor::Error::Diverged)), + "a locked ref is no split: {refused}" + ); + assert_eq!((oid(&repo, &local), oid(&repo, canonical)), before); + + std::fs::remove_file(&lock).unwrap(); + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + assert_eq!(saved.profile.unwrap().display_name, "bob"); +} + +/// The consent of `joining` to the local actor as it is now. +fn code(state: &AppState, joining: &SigningKey) -> String { + let actor = state.actor().unwrap().unwrap(); + let repo = state.profile.storage.repository(actor.rid).unwrap(); + Enrollment::sign(actor.rid, repo.identity().unwrap().current, joining).encode() +} + +#[test] +fn a_withdrawn_enrollment_does_not_break_the_next_binding() { + let (_tmp, state, rid) = actor_state(); + + // A second controller, so the next enrollments wait for its vote. + let other = key(0xee); + let code_of_other = code(&state, &other); + state + .approve_enrollment(code_of_other, true, quiet()) + .unwrap(); + + // An enrollment proposed and withdrawn leaves its proposal and the + // withdrawal in the identity's history, beside the accepted chain. + let withdrawn = key(0x11); + let pending = state + .approve_enrollment(code(&state, &withdrawn), true, quiet()) + .unwrap() + .pending; + state + .withdraw_actor_revision(pending[0].id, quiet()) + .unwrap(); + + let joining = key(0x22); + let pending = state + .approve_enrollment(code(&state, &joining), true, quiet()) + .unwrap() + .pending; + { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + Identity::load_mut(&repo, &other) + .unwrap() + .accept(&pending[0].id) + .unwrap(); + repo.set_identity_head().unwrap(); + } + + let actor = state.actor().unwrap().unwrap(); + let bound = actor + .keys + .iter() + .filter(|key| key.bound) + .map(|key| key.did) + .collect::>(); + assert!(bound.contains(&Did::from(*joining.public_key()))); + assert!(bound.contains(&Did::from(*other.public_key()))); + assert!(!bound.contains(&Did::from(*withdrawn.public_key()))); + assert!(actor.pending.is_empty()); +} + +/// Copies `from` into `to`, so a second app can hold a repository the first +/// made without a node between them. +fn copy_dir(from: &std::path::Path, to: &std::path::Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_dir(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), target).unwrap(); + } + } +} + +#[test] +fn a_key_joins_an_actor_it_holds_a_copy_of_and_nothing_else() { + let (tmp, state, rid) = actor_state(); + let joining = key(0xee); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + + // The key that made the actor has one, whatever repository it names. + let refused = state.join_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::Exists(existing)) if existing == rid)); + + // Without a copy there is nothing to consent to; a block the user set is + // named over the missing copy. + let refused = other.join_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::NotFetched(r)) if r == rid)); + other + .profile + .policies_mut() + .unwrap() + .set_seed_policy(&rid, radicle::node::policy::Policy::Block) + .unwrap(); + let refused = other.join_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::Blocked(r)) if r == rid)); + + let repo_path = radicle::storage::git::paths::repository(&state.profile.storage, &rid); + copy_dir( + &repo_path, + &radicle::storage::git::paths::repository(&other.profile.storage, &rid), + ); + let code = other.join_actor(rid).unwrap(); + let enrollment = Enrollment::decode(&code).unwrap(); + assert_eq!(enrollment.did, Did::from(*joining.public_key())); + + // The code is the one the actor's controller can approve. + let actor = state.approve_enrollment(code, false, quiet()).unwrap(); + assert!( + actor + .keys + .iter() + .any(|key| key.did == Did::from(*joining.public_key()) && key.bound) + ); + + // A retired actor is no longer one a key can join. + let signer = key(0xff); + { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + let payload = raw + .payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap(); + payload.insert("retired".into(), true.into()); + }) + .unwrap(); + identity + .update(Title::new("Retire").unwrap(), "", &doc) + .unwrap(); + repo.set_identity_head().unwrap(); + repo.sign_refs(&signer).unwrap(); + } + let third = AppState { + profile: test::profile(&tmp.path().join("third"), [0xdd; 32]), + }; + copy_dir( + &repo_path, + &radicle::storage::git::paths::repository(&third.profile.storage, &rid), + ); + let refused = third.join_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::NotJoinable(r)) if r == rid)); +} + +#[test] +fn the_actor_to_join_is_shown_before_anything_is_signed() { + let (tmp, state, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + + // The refusals are the join's own. + let refused = state.joinable_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::Exists(existing)) if existing == rid)); + let refused = other.joinable_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::NotFetched(r)) if r == rid)); + + copy_dir( + &radicle::storage::git::paths::repository(&state.profile.storage, &rid), + &radicle::storage::git::paths::repository(&other.profile.storage, &rid), + ); + let repo = other.profile.storage.repository(rid).unwrap(); + let refs = |repo: &radicle::storage::git::Repository| { + repo.backend + .references() + .unwrap() + .map(|reference| { + let reference = reference.unwrap(); + (reference.name().unwrap().to_owned(), reference.target()) + }) + .collect::>() + }; + let before = refs(&repo); + + let shown = other.joinable_actor(rid).unwrap(); + assert_eq!(shown.rid, rid); + assert_eq!(shown.profile.unwrap().display_name, "alice"); + assert_eq!(shown.keys.len(), 1); + assert_eq!(shown.keys[0].did, state.profile.did()); + assert_eq!(refs(&repo), before, "showing the actor writes nothing"); +} + +/// Moves `repo`'s default branch onto a commit that names a profile file +/// whose contents never arrived. +fn lose_profile_file(repo: &radicle::storage::git::Repository) { + let absent = radicle::git::raw::Oid::from_str(&"1".repeat(40)).unwrap(); + let odb = repo.backend.odb().unwrap(); + let entry = |mode: &str, name: &str, oid: radicle::git::raw::Oid| { + [format!("{mode} {name}\0").as_bytes(), oid.as_bytes()].concat() + }; + let folder = odb + .write( + radicle::git::raw::ObjectType::Tree, + &entry("100644", "profile.json", absent), + ) + .unwrap(); + let root = odb + .write( + radicle::git::raw::ObjectType::Tree, + &entry("40000", ".radicle", folder), + ) + .unwrap(); + let parent = repo + .backend + .find_commit(oid(repo, "refs/heads/main").unwrap()) + .unwrap(); + let signature = repo.backend.signature().unwrap(); + let broken = repo + .backend + .commit( + None, + &signature, + &signature, + "Edit", + &repo.backend.find_tree(root).unwrap(), + &[&parent], + ) + .unwrap(); + repo.backend + .reference("refs/heads/main", broken, true, "fetch") + .unwrap(); +} + +#[test] +fn a_profile_file_that_cannot_be_read_stops_the_page_but_not_the_preview() { + let (tmp, state, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + copy_dir( + &radicle::storage::git::paths::repository(&state.profile.storage, &rid), + &radicle::storage::git::paths::repository(&other.profile.storage, &rid), + ); + + // The join needs only the identity, so the preview must not ask for more. + lose_profile_file(&other.profile.storage.repository(rid).unwrap()); + other.join_actor(rid).unwrap(); + let shown = other.joinable_actor(rid).unwrap(); + assert!(shown.profile.is_none()); + assert!(shown.profile_unreadable); + assert_eq!(shown.keys.len(), 1); + + // The key's own page offers to save over the file, so there a failed + // read is an error and never an empty form. + lose_profile_file(&state.profile.storage.repository(rid).unwrap()); + assert!(state.actor().is_err()); +} + +#[test] +fn only_the_proposer_withdraws_and_the_others_reject() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + // The other controller proposes the next enrollment. + let joining = key(0x22); + let enrollment = Enrollment::decode(&code(&state, &joining)).unwrap(); + { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &other).unwrap(); + let doc = crate::actor::enrolled_doc(identity.doc(), &enrollment, true).unwrap(); + identity + .update(Title::new("Enroll key").unwrap(), "", &doc) + .unwrap(); + } + let id = state.actor().unwrap().unwrap().pending[0].id; + + assert!(matches!( + state.withdraw_actor_revision(id, quiet()), + Err(Error::Actor(actor::Error::NotAuthor)) + )); + let after = state.reject_actor_revision(id, quiet()).unwrap(); + assert!(after.pending.iter().all(|open| open.id != id)); + assert!( + !after + .keys + .iter() + .any(|key| key.did == Did::from(*joining.public_key())) + ); +} + +/// Sets `field` of the actor payload of `rid` to `value`, as another app would. +fn write_payload_field(state: &AppState, rid: RepoId, field: &str, value: serde_json::Value) { + write_payload_field_as(state, rid, &key(0xff), field, value); +} + +/// As `write_payload_field`, signed by `signer`, the actor's one controller. +fn write_payload_field_as( + state: &AppState, + rid: RepoId, + signer: &SigningKey, + field: &str, + value: serde_json::Value, +) { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, signer).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + let payload = raw + .payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap(); + payload.insert(field.into(), value); + }) + .unwrap(); + identity + .update(Title::new("Another app's payload").unwrap(), "", &doc) + .unwrap(); + repo.sign_refs(signer).unwrap(); + repo.set_identity_head().unwrap(); +} + +#[test] +fn a_newer_actor_this_version_cannot_place_is_not_given_a_sibling() { + let fields = [ + ("type", serde_json::Value::from("team")), + ("retired", "no".into()), + ("supersededBy", 7.into()), + // The bindings in a form of the newer version's own. + ("keys", serde_json::json!([])), + ]; + for (field, value) in fields { + let (_tmp, state, rid) = actor_state(); + write_payload_field(&state, rid, "version", 2.into()); + assert!(state.actor().unwrap().unwrap().payload_newer); + + write_payload_field(&state, rid, field, value); + + let refused = |result: Result<(), Error>| matches!(result, Err(Error::Actor(actor::Error::ActorNewer(found))) if found == rid); + assert!(refused(state.actor().map(|_| ())), "{field}"); + assert!( + refused( + state + .create_actor(named("bob"), Default::default(), quiet()) + .map(|_| ()) + ), + "{field}" + ); + assert!(refused(state.join_actor(rid).map(|_| ())), "{field}"); + } +} + +#[test] +fn a_newer_actor_this_version_cannot_place_does_not_hide_the_profile() { + let (tmp, state, rid) = actor_state(); + let founder = key(0xee); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + + // A second actor binds the key as well, in a payload of a newer version + // with a kind this one does not know. + let second = other + .create_actor(named("team"), Default::default(), quiet()) + .unwrap() + .rid; + let repo = other.profile.storage.repository(second).unwrap(); + let code = Enrollment::sign(second, repo.identity().unwrap().current, &key(0xff)).encode(); + other.approve_enrollment(code, false, quiet()).unwrap(); + write_payload_field_as(&other, second, &founder, "version", 2.into()); + write_payload_field_as(&other, second, &founder, "type", "team".into()); + copy_dir( + &radicle::storage::git::paths::repository(&other.profile.storage, &second), + &radicle::storage::git::paths::repository(&state.profile.storage, &second), + ); + + assert_eq!(state.actor().unwrap().unwrap().rid, rid); +} + +#[test] +fn a_payload_with_a_field_its_version_does_not_define_is_never_signed() { + let (_tmp, state, rid) = actor_state(); + write_payload_field(&state, rid, "mood", "unknown".into()); + + // Still the key's actor, so nothing offers to create another. + let actor = state.actor().unwrap().unwrap(); + assert_eq!(actor.rid, rid); + assert!(actor.payload_newer); + + let refused = state.approve_enrollment(code(&state, &key(0x22)), true, quiet()); + assert!(matches!( + refused, + Err(Error::Actor(actor::Error::PayloadNewer)) + )); +} + +#[test] +fn a_payload_from_a_newer_app_is_never_signed() { + let (_tmp, state, rid) = actor_state(); + write_payload_field(&state, rid, "version", 2.into()); + assert!(state.actor().unwrap().unwrap().payload_newer); + + let joining = key(0x22); + let refused = state.approve_enrollment(code(&state, &joining), true, quiet()); + assert!(matches!( + refused, + Err(Error::Actor(actor::Error::PayloadNewer)) + )); + assert!(state.actor().unwrap().unwrap().pending.is_empty()); + + // A code for another actor says so first, whatever this key may do. + let elsewhere = RepoId::from_str("rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5").unwrap(); + let repo = state.profile.storage.repository(rid).unwrap(); + let parent = repo.identity().unwrap().current; + let foreign = Enrollment::sign(elsewhere, parent, &joining).encode(); + assert!(matches!( + state.decode_enrollment(foreign), + Err(Error::Actor(actor::Error::WrongActor(other))) if other == elsewhere + )); +} + +/// Makes `other` a second controller, under `threshold` for profile edits: +/// two, and an edit by the local key only proposes. +fn share_with(state: &AppState, rid: RepoId, other: &SigningKey, threshold: usize) { + let signer = key(0xff); + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let mut doc = identity.doc().clone().edit(); + doc.delegate(Did::from(*other.public_key())); + doc.threshold = threshold; + identity + .update( + Title::new("Add a controller").unwrap(), + "", + &doc.verified().unwrap(), + ) + .unwrap(); + repo.sign_refs(&signer).unwrap(); + repo.set_identity_head().unwrap(); +} + +#[test] +fn a_name_whose_repository_is_in_storage_is_refused() { + let (_tmp, state, rid) = actor_state(); + // The actor retires, so the key has none; its repository stays. + let signer = key(0xff); + { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + let payload = raw + .payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap(); + payload.insert("retired".into(), true.into()); + }) + .unwrap(); + identity + .update(Title::new("Retire").unwrap(), "", &doc) + .unwrap(); + repo.set_identity_head().unwrap(); + repo.sign_refs(&signer).unwrap(); + } + assert!(state.actor().unwrap().is_none()); + + // The same name gives the same document, so the same repository id. + let again = state + .create_actor(named("alice"), Default::default(), quiet()) + .unwrap_err(); + assert!(matches!(again, Error::Actor(actor::Error::NameTaken(ref name)) if name == "alice")); + assert!(state.actor().unwrap().is_none()); + + let other = state + .create_actor(named("alice2"), Default::default(), quiet()) + .unwrap(); + assert_ne!(other.rid, rid); +} + +/// The identity change `doc`, proposed by `author`. +fn propose(state: &AppState, rid: RepoId, author: &SigningKey, doc: &radicle::identity::Doc) { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + Identity::load_mut(&repo, author) + .unwrap() + .update(Title::new("Enroll key").unwrap(), "", doc) + .unwrap(); +} + +#[test] +fn a_code_never_signs_a_change_that_does_more_than_enroll() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + // The other controller proposes the enrollment and slips in a + // controller of its own. + let joining = key(0x22); + let code_of_joining = code(&state, &joining); + let enrollment = Enrollment::decode(&code_of_joining).unwrap(); + let head = state.profile.storage.repository(rid).unwrap(); + let head = head.identity_doc().unwrap().doc; + let mut doc = crate::actor::enrolled_doc(&head, &enrollment, true) + .unwrap() + .edit(); + let intruder = Did::from(*key(0x33).public_key()); + doc.delegate(intruder); + propose(&state, rid, &other, &doc.verified().unwrap()); + + let after = state + .approve_enrollment(code_of_joining, true, quiet()) + .unwrap(); + let local = Did::from(state.profile.public_key); + let foreign = after + .pending + .iter() + .find(|open| open.author != local) + .unwrap(); + assert!(!foreign.accepted.contains(&local)); + assert!(after.pending.iter().any(|open| open.author == local)); + assert!(!after.keys.iter().any(|key| key.did == intruder)); +} + +#[test] +fn a_code_signs_the_same_enrollment_only_with_the_same_role() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + let local = Did::from(state.profile.public_key); + // The other controller proposes the enrollment of `joining` as a + // controller, and the local key approves its code. + let enroll = |joining: &SigningKey, controller: bool| { + let code_of_joining = code(&state, joining); + let enrollment = Enrollment::decode(&code_of_joining).unwrap(); + let repo = state.profile.storage.repository(rid).unwrap(); + let head = repo.identity_doc().unwrap().doc; + propose( + &state, + rid, + &other, + &crate::actor::enrolled_doc(&head, &enrollment, true).unwrap(), + ); + state + .approve_enrollment(code_of_joining, controller, quiet()) + .unwrap() + }; + + // With the same role, the vote applies the other controller's change. + let joining = key(0x22); + let joined = enroll(&joining, true); + let enrolled = joined + .keys + .iter() + .find(|key| key.did == Did::from(*joining.public_key())) + .unwrap(); + assert!(enrolled.bound && enrolled.controller); + assert!(joined.pending.is_empty()); + + // Without the controller role, it is another change. + let apart = enroll(&key(0x33), false); + assert_eq!(apart.pending.len(), 2); + assert!( + apart + .pending + .iter() + .all(|open| (open.author == local) == open.accepted.contains(&local)) + ); +} + +#[test] +fn a_change_beyond_the_keys_is_never_approved() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + let head = state.profile.storage.repository(rid).unwrap(); + let mut doc = head.identity_doc().unwrap().doc.edit(); + doc.threshold = 2; + propose(&state, rid, &other, &doc.verified().unwrap()); + + let open = state.actor().unwrap().unwrap().pending.remove(0); + assert!(open.unreadable); + assert!(matches!( + state.approve_actor_revision(open.id, quiet()), + Err(Error::Actor(actor::Error::RevisionUnreadable)) + )); +} + +#[test] +fn a_key_votes_once_on_a_change() { + let (_tmp, state, _) = actor_state(); + state + .approve_enrollment(code(&state, &key(0xee)), true, quiet()) + .unwrap(); + let pending = state + .approve_enrollment(code(&state, &key(0x22)), true, quiet()) + .unwrap() + .pending; + + assert!(matches!( + state.reject_actor_revision(pending[0].id, quiet()), + Err(Error::Actor(actor::Error::AlreadyVoted)) + )); +} + +#[test] +fn a_change_to_a_keys_entry_the_app_does_not_show_is_never_approved() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + // An entry with no valid consent binds nothing, so nothing shows it. + let stranger = Did::from(*key(0x33).public_key()); + let head = state.profile.storage.repository(rid).unwrap(); + let doc = head + .identity_doc() + .unwrap() + .doc + .with_edits(|raw| { + raw.payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap() + .get_mut("keys") + .unwrap() + .as_object_mut() + .unwrap() + .insert(stranger.to_string(), "z1".into()); + }) + .unwrap(); + propose(&state, rid, &other, &doc); + + let open = state.actor().unwrap().unwrap().pending.remove(0); + assert!(open.added.is_empty() && open.removed.is_empty()); + assert!(open.unreadable); +} + +#[test] +fn a_revoke_refuses_this_key_and_a_key_the_actor_does_not_have() { + let (_tmp, state, _) = actor_state(); + let local = Did::from(state.profile.public_key); + let stranger = Did::from(*key(0x33).public_key()); + + assert!(matches!( + state.remove_actor_key(local, quiet()), + Err(Error::Actor(actor::Error::RemoveSelf)) + )); + assert!(matches!( + state.remove_actor_key(stranger, quiet()), + Err(Error::Actor(actor::Error::KeyNotFound(did))) if did == stranger + )); +} + +#[test] +fn a_revoke_lowers_the_threshold_to_the_controllers_left_and_says_so() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 2); + + let after = state + .remove_actor_key(Did::from(*other.public_key()), quiet()) + .unwrap(); + let open = &after.pending[0]; + assert_eq!(open.removed, vec![Did::from(*other.public_key())]); + assert_eq!(open.threshold, Some(1)); + assert!(!open.unreadable); +} + +#[test] +fn a_revoke_signs_the_same_removal_by_another_controller() { + let (_tmp, state, rid) = actor_state(); + let leaving = key(0x22); + state + .approve_enrollment(code(&state, &leaving), false, quiet()) + .unwrap(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + let leaving = Did::from(*leaving.public_key()); + let head = state.profile.storage.repository(rid).unwrap(); + let head = head.identity_doc().unwrap().doc; + propose( + &state, + rid, + &other, + &crate::actor::removed_doc(&head, &leaving).unwrap(), + ); + + let after = state.remove_actor_key(leaving, quiet()).unwrap(); + assert!(after.pending.is_empty()); + assert!(!after.keys.iter().any(|key| key.did == leaving)); +} + +#[test] +fn the_founding_key_is_revoked_like_any_other() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + let founding = Did::from(state.profile.public_key); + let head = state.profile.storage.repository(rid).unwrap(); + let head = head.identity_doc().unwrap().doc; + propose( + &state, + rid, + &other, + &crate::actor::removed_doc(&head, &founding).unwrap(), + ); + let id = state.actor().unwrap().unwrap().pending[0].id; + // The founding key's vote applies it: the actor stands, without it. + let after = state.approve_actor_revision(id, quiet()).unwrap(); + let keys = after.keys.iter().map(|key| key.did).collect::>(); + assert_eq!(keys, vec![Did::from(*other.public_key())]); + assert!(state.actor().unwrap().is_none()); +} + +#[test] +fn a_preview_shows_the_key_of_a_code_and_writes_nothing() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + let repo = state.profile.storage.repository(rid).unwrap(); + let before = repo.identity().unwrap().current; + + let joining = key(0x22); + let preview = state.decode_enrollment(code(&state, &joining)).unwrap(); + assert_eq!(preview.did, Did::from(*joining.public_key())); + assert_eq!(repo.identity().unwrap().current, before); + assert!(state.actor().unwrap().unwrap().pending.is_empty()); + + assert!(matches!( + state.decode_enrollment(code(&state, &other)), + Err(Error::Actor(actor::Error::AlreadyBound)) + )); +} + +#[test] +fn a_preview_refuses_a_key_the_payload_has_no_room_for() { + let (_tmp, state, rid) = actor_state(); + let signer = key(0xff); + { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + let keys = raw + .payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap() + .get_mut("keys") + .unwrap() + .as_object_mut() + .unwrap(); + for n in keys.len()..255 { + let mut seed = [0xaa; 32]; + seed[0] = n as u8; + let filler = SigningKey::from_seed(Seed::new(seed)); + keys.insert(Did::from(*filler.public_key()).to_string(), "z1".into()); + } + }) + .unwrap(); + identity + .update(Title::new("Fill the keys").unwrap(), "", &doc) + .unwrap(); + repo.sign_refs(&signer).unwrap(); + repo.set_identity_head().unwrap(); + } + + let joining = key(0x22); + assert!(matches!( + state.decode_enrollment(code(&state, &joining)), + Err(Error::Actor(crate::actor::Error::Full)) + )); +} + +#[test] +fn a_key_that_rejected_a_change_cannot_approve_it() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + // Three controllers, so one rejection leaves the change open. + { + let signer = key(0xff); + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let mut doc = identity.doc().clone().edit(); + doc.delegate(Did::from(*other.public_key())); + doc.delegate(Did::from(*key(0x33).public_key())); + doc.threshold = 2; + identity + .update( + Title::new("Add controllers").unwrap(), + "", + &doc.verified().unwrap(), + ) + .unwrap(); + repo.sign_refs(&signer).unwrap(); + repo.set_identity_head().unwrap(); + } + let code_of_joining = code(&state, &key(0x22)); + let enrollment = Enrollment::decode(&code_of_joining).unwrap(); + let head = state.profile.storage.repository(rid).unwrap(); + let head = head.identity_doc().unwrap().doc; + let doc = crate::actor::enrolled_doc(&head, &enrollment, true).unwrap(); + propose(&state, rid, &other, &doc); + let open = state.actor().unwrap().unwrap().pending[0].id; + + let after = state.reject_actor_revision(open, quiet()).unwrap(); + assert_eq!( + after.pending[0].rejected, + vec![Did::from(state.profile.public_key)], + "the rejection shows on the open change" + ); + let result = state.approve_actor_revision(open, quiet()); + assert!( + matches!(result, Err(Error::Actor(actor::Error::AlreadyVoted))), + "{result:?}" + ); + // The same code co-signs that change, which is the same verdict. + let result = state.approve_enrollment(code_of_joining, true, quiet()); + assert!( + matches!(result, Err(Error::Actor(actor::Error::AlreadyVoted))), + "{result:?}" + ); +} + +#[test] +fn a_preview_says_when_the_key_already_controls_the_actor() { + let (_tmp, state, rid) = actor_state(); + let recovery = key(0xee); + share_with(&state, rid, &recovery, 2); + let preview = state.decode_enrollment(code(&state, &recovery)).unwrap(); + assert!(preview.controller); + let preview = state.decode_enrollment(code(&state, &key(0x22))).unwrap(); + assert!(!preview.controller); +} + +#[test] +fn a_key_with_an_accepted_change_cannot_approve_a_sibling() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 2); + // The local key's own change: its accept is on record. + let own = state + .approve_enrollment(code(&state, &key(0x22)), true, quiet()) + .unwrap() + .pending[0] + .id; + let result = state.approve_actor_revision(own, quiet()); + assert!( + matches!(result, Err(Error::Actor(actor::Error::AlreadyVoted))), + "{result:?}" + ); + + // The other controller proposes a sibling at the same version. + let enrollment = Enrollment::decode(&code(&state, &key(0x33))).unwrap(); + let head = state.profile.storage.repository(rid).unwrap(); + let head = head.identity_doc().unwrap().doc; + let doc = crate::actor::enrolled_doc(&head, &enrollment, true).unwrap(); + propose(&state, rid, &other, &doc); + let local = Did::from(state.profile.public_key); + let sibling = state + .actor() + .unwrap() + .unwrap() + .pending + .into_iter() + .find(|open| open.author != local) + .unwrap() + .id; + let result = state.approve_actor_revision(sibling, quiet()); + assert!( + matches!(result, Err(Error::Actor(actor::Error::VotedElsewhere))), + "{result:?}" + ); + // Nor propose a third change beside them. + let result = state.approve_enrollment(code(&state, &key(0x44)), true, quiet()); + assert!( + matches!(result, Err(Error::Actor(actor::Error::VotedElsewhere))), + "{result:?}" + ); +} + +#[test] +fn restoring_the_canonical_profile_takes_back_an_edit() { + let (_tmp, state, rid) = actor_state(); + share_with(&state, rid, &key(0xee), 2); + let repo = state.profile.storage.repository(rid).unwrap(); + let key = state.profile.public_key; + let local = format!("refs/namespaces/{key}/refs/heads/main"); + let canonical = oid(&repo, "refs/heads/main"); + let original = state.actor().unwrap().unwrap().profile.unwrap(); + + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + assert_ne!( + oid(&repo, &local), + canonical, + "the edit is on the local branch" + ); + + state + .update_actor_profile(original, Default::default(), quiet()) + .unwrap(); + assert_eq!( + oid(&repo, &local), + canonical, + "the branch is back on the canonical head" + ); + let refs = repo.remote(&key).unwrap().refs; + assert_eq!( + refs.get(&radicle::git::fmt::qualified!("refs/heads/main")), + canonical.map(Into::into), + "the move is signed" + ); +} + +/// The app in `state`, where something else acts in the middle of one call: +/// `meanwhile` runs once, at the `at`th time the call reads the profile. +struct Interrupted<'a> { + state: &'a AppState, + at: usize, + reads: std::cell::Cell, + meanwhile: std::cell::RefCell>>, +} + +impl<'a> Interrupted<'a> { + fn new(state: &'a AppState, at: usize, meanwhile: impl FnOnce() + 'a) -> Self { + Self { + state, + at, + reads: std::cell::Cell::new(0), + meanwhile: std::cell::RefCell::new(Some(Box::new(meanwhile))), + } + } + + /// Whether `meanwhile` ran. + fn interrupted(&self) -> bool { + self.meanwhile.borrow().is_none() + } +} + +impl Profile for Interrupted<'_> { + fn profile(&self) -> radicle::Profile { + self.reads.set(self.reads.get() + 1); + if self.reads.get() == self.at + && let Some(meanwhile) = self.meanwhile.take() + { + meanwhile(); + } + self.state.profile.clone() + } +} + +impl Repo for Interrupted<'_> {} +impl Actor for Interrupted<'_> {} + +fn did_of(key: &SigningKey) -> Did { + Did::from(*key.public_key()) +} + +/// Runs `round` with `meanwhile` set off at each read of the profile in turn, +/// until a call ends before that read comes. `round` gets the app and says +/// whether `meanwhile` ran. A call that reads the profile too few times to +/// be interrupted at several points is no test of anything. +fn at_every_read(mut round: impl FnMut(usize) -> bool) { + let mut at = 1; + while round(at) { + at += 1; + } + assert!(at > 3, "interrupted at {} reads only", at - 1); +} + +#[test] +fn a_change_that_lands_during_an_approval_survives_it() { + at_every_read(|at| { + let (_tmp, state, _rid) = actor_state(); + let (first, second) = (key(0xcc), key(0xdd)); + let app = Interrupted::new(&state, at, || { + state + .approve_enrollment(code(&state, &first), false, quiet()) + .unwrap(); + }); + + let result = app.approve_enrollment(code(&state, &second), false, quiet()); + + let actor = state.actor().unwrap().unwrap(); + let bound = |key: &SigningKey| actor.keys.iter().any(|k| k.did == did_of(key) && k.bound); + if app.interrupted() { + assert!(bound(&first), "read {at}: the other change is undone"); + } + match result { + Ok(_) => assert!(bound(&second), "read {at}: reported as done, not bound"), + // Only a new code helps, so the error must say so. + Err(e) => assert!( + matches!(e, Error::Actor(actor::Error::Stale)), + "read {at}: {e}" + ), + } + app.interrupted() + }); +} + +#[test] +fn a_change_that_lands_during_a_removal_survives_it() { + at_every_read(|at| { + let (_tmp, state, _rid) = actor_state(); + let (first, second) = (key(0xcc), key(0xdd)); + state + .approve_enrollment(code(&state, &second), false, quiet()) + .unwrap(); + let app = Interrupted::new(&state, at, || { + state + .approve_enrollment(code(&state, &first), false, quiet()) + .unwrap(); + }); + + let result = app.remove_actor_key(did_of(&second), quiet()); + + let actor = state.actor().unwrap().unwrap(); + let listed = |key: &SigningKey| actor.keys.iter().any(|k| k.did == did_of(key)); + if app.interrupted() { + assert!(listed(&first), "read {at}: the other change is undone"); + } + match result { + Ok(_) => assert!(!listed(&second), "read {at}: reported as done, still there"), + Err(e) => assert!( + matches!(e, Error::Actor(actor::Error::Moved)), + "read {at}: {e}" + ), + } + app.interrupted() + }); +} + +#[test] +fn a_field_that_lands_during_a_removal_is_never_signed() { + at_every_read(|at| { + let (_tmp, state, rid) = actor_state(); + let leaving = did_of(&key(0xdd)).to_string(); + state + .approve_enrollment(code(&state, &key(0xdd)), false, quiet()) + .unwrap(); + let app = Interrupted::new(&state, at, || { + write_payload_field(&state, rid, "mood", "unknown".into()); + }); + + let result = app.remove_actor_key(did_of(&key(0xdd)), quiet()); + + // The revision that removed the key, if any, holds no field this + // version does not define: the field came after it, never before. + let repo = state.profile.storage.repository(rid).unwrap(); + let id = PayloadId::from_str("dev.radicle.actor").unwrap(); + let removing = actor::identity_history(&repo) + .unwrap() + .into_iter() + .map(|revision| (**revision.doc.payload().get(&id).unwrap()).clone()) + .skip_while(|payload| payload["keys"].get(&leaving).is_none()) + .find(|payload| payload["keys"].get(&leaving).is_none()); + match (&result, removing) { + (Ok(_), Some(payload)) => { + assert!( + payload.get("mood").is_none(), + "read {at}: signed with the field" + ) + } + (Err(Error::Actor(actor::Error::Moved | actor::Error::PayloadNewer)), None) => {} + (result, removing) => panic!("read {at}: {result:?} with {removing:?}"), + } + app.interrupted() + }); +} + +/// The open change in which `author`, the other of two controllers, enrolls +/// a key. +fn enrollment_by( + state: &AppState, + rid: RepoId, + author: &SigningKey, + joining: &SigningKey, +) -> radicle::git::Oid { + share_with(state, rid, author, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let enrollment = Enrollment::sign(rid, repo.identity().unwrap().current, joining); + let doc = actor::enrolled_doc(&repo.identity_doc().unwrap().doc, &enrollment, false).unwrap(); + propose(state, rid, author, &doc); + + state.actor().unwrap().unwrap().pending[0].id +} + +/// Withdraws the open change `id` as `author`. +fn withdraw(state: &AppState, rid: RepoId, author: &SigningKey, id: radicle::git::Oid) { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + Identity::load_mut(&repo, author) + .unwrap() + .redact(id) + .unwrap(); +} + +#[test] +fn a_change_withdrawn_during_its_approval_is_not_reported_as_approved() { + at_every_read(|at| { + let (_tmp, state, rid) = actor_state(); + let (other, joining) = (key(0xee), key(0xdd)); + let local = Did::from(state.profile.public_key); + let id = enrollment_by(&state, rid, &other, &joining); + let app = Interrupted::new(&state, at, || withdraw(&state, rid, &other, id)); + + let result = app.approve_actor_revision(id, quiet()); + + let actor = state.actor().unwrap().unwrap(); + let approved = actor + .keys + .iter() + .any(|key| key.did == did_of(&joining) && key.bound) + || actor + .pending + .iter() + .any(|open| open.accepted.contains(&local)); + match result { + Ok(_) => assert!(approved, "read {at}: reported as approved, and it is not"), + Err(e) => assert!(!approved, "read {at}: {e}, and it is approved"), + } + app.interrupted() + }); +} + +#[test] +fn a_change_withdrawn_during_its_rejection_is_not_reported_as_rejected() { + at_every_read(|at| { + let (_tmp, state, rid) = actor_state(); + let (other, joining) = (key(0xee), key(0xdd)); + let local = Did::from(state.profile.public_key); + let id = enrollment_by(&state, rid, &other, &joining); + let app = Interrupted::new(&state, at, || withdraw(&state, rid, &other, id)); + + let result = app.reject_actor_revision(id, quiet()); + + let repo = state.profile.storage.repository(rid).unwrap(); + let rejected = repo + .identity() + .unwrap() + .revision(&id) + .is_some_and(|change| change.rejected().any(|did| did == local)); + if result.is_ok() { + assert!(rejected, "read {at}: reported as rejected, and it is not"); + } + app.interrupted() + }); +} + +#[test] +fn a_change_approved_during_its_withdrawal_is_not_reported_as_withdrawn() { + at_every_read(|at| { + let (_tmp, state, rid) = actor_state(); + let (other, joining) = (key(0xee), key(0xdd)); + share_with(&state, rid, &other, 1); + let id = state + .approve_enrollment(code(&state, &joining), false, quiet()) + .unwrap() + .pending[0] + .id; + let app = Interrupted::new(&state, at, || { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + Identity::load_mut(&repo, &other) + .unwrap() + .accept(&id) + .unwrap(); + }); + + let result = app.withdraw_actor_revision(id, quiet()); + + let actor = state.actor().unwrap().unwrap(); + let bound = actor + .keys + .iter() + .any(|key| key.did == did_of(&joining) && key.bound); + if result.is_ok() { + assert!( + !bound, + "read {at}: reported as withdrawn, and the key is bound" + ); + } + app.interrupted() + }); +} + +#[test] +fn an_actor_repository_is_told_apart_from_a_project() { + use radicle::identity::doc::Payload; + use radicle::test::fixtures; + + let (tmp, state, rid) = actor_state(); + let signer = key(0xff); + let storage = &state.profile.storage; + let (project, ..) = fixtures::project(tmp.path().join("project"), storage, &signer).unwrap(); + let (late, ..) = { + let working = fixtures::repository(tmp.path().join("late")).0; + radicle::rad::init( + &working, + "late".try_into().unwrap(), + "", + radicle::git::fmt::refname!("master"), + radicle::identity::Visibility::default(), + &signer, + storage, + ) + .unwrap() + }; + + // A project that takes on the payload later is still a project: what a + // repository is, its first document says. + let repo = storage.repository_mut(late).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let keys = serde_json::json!({ Did::from(state.profile.public_key).to_string(): "root" }); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + raw.payload.insert( + PayloadId::from_str("dev.radicle.actor").unwrap(), + Payload::from(serde_json::json!({ "version": 1, "keys": keys })), + ); + }) + .unwrap(); + identity + .update(Title::new("Take on the payload").unwrap(), "", &doc) + .unwrap(); + repo.sign_refs(&signer).unwrap(); + repo.set_identity_head().unwrap(); + + let summaries = state + .list_repos_summary(crate::traits::repo::Show::All) + .unwrap(); + let is_actor = |rid: RepoId| summaries.iter().find(|repo| repo.rid == rid).unwrap().actor; + assert!(is_actor(rid)); + assert!(!is_actor(project)); + assert!(!is_actor(late)); + + // An actor whose current document no longer holds a valid payload is + // not one either. + write_payload_field(&state, rid, "type", "team".into()); + let summaries = state + .list_repos_summary(crate::traits::repo::Show::All) + .unwrap(); + assert!(summaries.iter().any(|repo| repo.rid == rid && !repo.actor)); +} + +#[test] +fn a_key_bound_to_two_actors_has_neither() { + let (tmp, state, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + + // Another actor binds the key too, with its consent, and reaches this + // machine. + let second = other + .create_actor(named("bob"), Default::default(), quiet()) + .unwrap() + .rid; + let repo = other.profile.storage.repository(second).unwrap(); + let consent = Enrollment::sign(second, repo.identity().unwrap().current, &key(0xff)); + other + .approve_enrollment(consent.encode(), false, quiet()) + .unwrap(); + copy_dir( + &radicle::storage::git::paths::repository(&other.profile.storage, &second), + &radicle::storage::git::paths::repository(&state.profile.storage, &second), + ); + + // No rule picks one of them, so nothing is read or written as either. + let mut both = vec![rid, second]; + both.sort(); + let ambiguous = |result: Result<(), Error>| match result { + Err(Error::Actor(actor::Error::Ambiguous(mut rids))) => { + rids.sort(); + rids == both + } + _ => false, + }; + assert!(ambiguous(state.actor().map(|_| ()))); + assert!(ambiguous( + state + .update_actor_profile(named("carol"), Default::default(), quiet()) + .map(|_| ()) + )); + assert!(ambiguous( + state + .remove_actor_key(did_of(&key(0x11)), quiet()) + .map(|_| ()) + )); + assert!(ambiguous(state.join_actor(rid).map(|_| ()))); + assert_eq!(state.actor().unwrap_err().code(), "ActorError.Ambiguous"); +} + +#[test] +fn a_key_that_does_not_control_the_actor_saves_on_its_own_branch() { + let (tmp, state, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + let ours = radicle::storage::git::paths::repository(&state.profile.storage, &rid); + let theirs = radicle::storage::git::paths::repository(&other.profile.storage, &rid); + + // The other machine joins as a key without control, and gets the approval. + copy_dir(&ours, &theirs); + let code = other.join_actor(rid).unwrap(); + state.approve_enrollment(code, false, quiet()).unwrap(); + std::fs::remove_dir_all(&theirs).unwrap(); + copy_dir(&ours, &theirs); + + let repo = other.profile.storage.repository(rid).unwrap(); + let canonical = oid(&repo, "refs/heads/main"); + let shown = other + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + + // Its edit is a commit on the profile, on a branch of its own, signed. + let key = other.profile.public_key; + let branch = oid(&repo, &format!("refs/namespaces/{key}/refs/heads/main")) + .expect("the key has a branch"); + let parent = repo.backend.find_commit(branch).unwrap().parent_id(0).ok(); + assert_eq!(parent, canonical); + let refs = repo.remote(&key).unwrap().refs; + assert_eq!( + refs.get(&radicle::git::fmt::qualified!("refs/heads/main")), + Some(branch.into()) + ); + + // The profile itself waits for a controller. + assert_eq!(oid(&repo, "refs/heads/main"), canonical); + assert_eq!(shown.profile.unwrap().display_name, "alice"); +} + +#[test] +fn a_save_closes_a_split_between_two_controllers() { + let (_tmp, state, rid) = actor_state(); + // Two controllers under a threshold of one: two devices of one person. + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = oid(&repo, "refs/heads/main").unwrap(); + + // The other device saves on the head both have, before it has this + // device's edit. + let parent = repo.backend.find_commit(base).unwrap(); + let tree = actor::profile_tree( + &repo.backend, + Some(&parent.tree().unwrap()), + &named("carol"), + ) + .unwrap(); + let signature = repo.backend.signature().unwrap(); + let theirs = repo + .backend + .commit(None, &signature, &signature, "Edit", &tree, &[&parent]) + .unwrap(); + + // This device saves on the same head, and alone it moves the canonical + // branch. + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + assert_eq!(saved.profile.unwrap().display_name, "bob"); + assert!(saved.forks.is_empty()); + + // A fetch brings the other device's branch: the two have split, and the + // other version is reported. + let their_branch = format!("refs/namespaces/{}/refs/heads/main", other.public_key()); + repo.backend + .reference(&their_branch, theirs, true, "fetch") + .unwrap(); + let split = state.actor().unwrap().unwrap(); + assert_eq!(split.profile.unwrap().display_name, "bob"); + assert_eq!(split.forks.len(), 1); + assert_eq!(split.forks[0].did, Did::from(*other.public_key())); + assert_eq!( + split.forks[0].profile.as_ref().unwrap().display_name, + "carol" + ); + assert_eq!(split.forks[0].base.as_ref().unwrap().display_name, "alice"); + // The changes are told from where the two versions split, so this + // device's own edit is none of them. + let changes = split.forks[0].changes.as_ref().unwrap(); + assert!(changes.contains("- \"displayName\": \"alice\"")); + assert!(changes.contains("+ \"displayName\": \"carol\"")); + assert!(!changes.contains("bob")); + + // The next save descends from both sides, so the canonical branch moves + // again, even when the form is saved as it is. + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + assert_eq!(saved.profile.unwrap().display_name, "bob"); + assert!(saved.forks.is_empty()); + let canonical = oid(&repo, "refs/heads/main").unwrap(); + let key = state.profile.public_key; + assert_eq!( + oid(&repo, &format!("refs/namespaces/{key}/refs/heads/main")), + Some(canonical) + ); + assert!(repo.backend.graph_descendant_of(canonical, theirs).unwrap()); + + let saved = state + .update_actor_profile(named("dave"), Default::default(), quiet()) + .unwrap(); + assert_eq!(saved.profile.unwrap().display_name, "dave"); +} + +/// Makes the keys `0xee` and `0xdd` controllers too, under a threshold of +/// one: three devices of one person. +fn three_controllers(state: &AppState, rid: RepoId) -> (SigningKey, SigningKey) { + let (first, second, third) = (key(0xff), key(0xee), key(0xdd)); + let repo = state.profile.storage.repository_mut(rid).unwrap(); + let mut identity = Identity::load_mut(&repo, &first).unwrap(); + let mut doc = identity.doc().clone().edit(); + doc.delegate(did_of(&second)); + doc.delegate(did_of(&third)); + identity + .update( + Title::new("Add controllers").unwrap(), + "", + &doc.verified().unwrap(), + ) + .unwrap(); + repo.sign_refs(&first).unwrap(); + repo.set_identity_head().unwrap(); + + (second, third) +} + +/// A commit over `base` that names the profile `name`, as another device +/// would save it. +fn saved_elsewhere( + repo: &radicle::storage::git::Repository, + base: radicle::git::raw::Oid, + name: &str, +) -> radicle::git::raw::Oid { + let parent = repo.backend.find_commit(base).unwrap(); + let tree = + actor::profile_tree(&repo.backend, Some(&parent.tree().unwrap()), &named(name)).unwrap(); + let signature = repo.backend.signature().unwrap(); + + repo.backend + .commit(None, &signature, &signature, "Edit", &tree, &[&parent]) + .unwrap() +} + +/// Points the branch of `key` at `commit`, as a fetch would. +fn fetched( + repo: &radicle::storage::git::Repository, + key: &PublicKey, + commit: radicle::git::raw::Oid, +) { + repo.backend + .reference( + &format!("refs/namespaces/{key}/refs/heads/main"), + commit, + true, + "fetch", + ) + .unwrap(); +} + +#[test] +fn a_save_closes_a_split_with_one_of_three_controllers() { + let (_tmp, state, rid) = actor_state(); + let (second, third) = three_controllers(&state, rid); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = oid(&repo, "refs/heads/main").unwrap(); + + // One other device saved while apart; the third never edited. + let theirs = saved_elsewhere(&repo, base, "carol"); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + fetched(&repo, second.public_key(), theirs); + fetched(&repo, third.public_key(), base); + assert_eq!(state.actor().unwrap().unwrap().forks.len(), 1); + + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + + assert!(saved.forks.is_empty()); + let canonical = oid(&repo, "refs/heads/main").unwrap(); + assert!(repo.backend.graph_descendant_of(canonical, theirs).unwrap()); +} + +#[test] +fn a_three_way_split_closes_once_a_second_controller_has_the_merge() { + let (_tmp, state, rid) = actor_state(); + let (second, third) = three_controllers(&state, rid); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = oid(&repo, "refs/heads/main").unwrap(); + + // All three devices saved while apart, and both other versions show. + let (carol, erin) = ( + saved_elsewhere(&repo, base, "carol"), + saved_elsewhere(&repo, base, "erin"), + ); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + fetched(&repo, second.public_key(), carol); + fetched(&repo, third.public_key(), erin); + assert_eq!(state.actor().unwrap().unwrap().forks.len(), 2); + + // The save merges both. Whether the canonical branch then moves is up + // to how three tips are told apart, and a refusal says so. + if let Err(refused) = state.update_actor_profile(named("bob"), Default::default(), quiet()) { + assert!( + matches!(refused, Error::Actor(actor::Error::Diverged)), + "{refused}" + ); + } + let merge = oid( + &repo, + &format!( + "refs/namespaces/{}/refs/heads/main", + state.profile.public_key + ), + ) + .unwrap(); + assert!(repo.backend.graph_descendant_of(merge, carol).unwrap()); + assert!(repo.backend.graph_descendant_of(merge, erin).unwrap()); + + // A second device that has the merge settles it. + fetched(&repo, second.public_key(), merge); + let saved = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + + assert!(saved.forks.is_empty()); + let canonical = oid(&repo, "refs/heads/main").unwrap(); + assert!(repo.backend.graph_descendant_of(canonical, carol).unwrap()); + assert!(repo.backend.graph_descendant_of(canonical, erin).unwrap()); +} + +#[test] +fn a_copy_fetched_during_a_split_is_not_joined() { + let (tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = oid(&repo, "refs/heads/main").unwrap(); + let theirs = saved_elsewhere(&repo, base, "carol"); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + fetched(&repo, other.public_key(), theirs); + + // A device that had the actor before the split keeps its head, and the + // node goes on fetching for it. + let joining = AppState { + profile: test::profile(&tmp.path().join("joining"), [0xdd; 32]), + }; + fetch(&joining, &state, rid); + assert_eq!(joining.joinable_actor(rid).unwrap().keys.len(), 2); + + // A first fetch during the split finds no head to set, and the node + // fetches nothing more into a copy without one: an approval would never + // arrive. + let copy = joining.profile.storage.repository(rid).unwrap(); + copy.backend + .find_reference("refs/heads/main") + .unwrap() + .delete() + .unwrap(); + assert!(joining.profile.storage.contains(&rid).is_err()); + + let refused = joining.joinable_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::CopyStuck(r)) if r == rid)); + let refused = joining.join_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::CopyStuck(r)) if r == rid)); + + // This device wrote nothing to the copy, so storage drops it whole, and + // the next fetch starts from nothing. + joining.clean(rid).unwrap(); + let refused = joining.joinable_actor(rid).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::NotFetched(r)) if r == rid)); +} + +#[test] +fn seeding_again_keeps_the_scope_the_user_set() { + use radicle::node::policy::{Scope, SeedingPolicy}; + + let (tmp, _, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + let scope = |state: &AppState| { + let policies = state.profile.policies().unwrap(); + match (*policies).seed_policy(&rid).unwrap().unwrap().policy { + SeedingPolicy::Allow { scope } => scope, + SeedingPolicy::Block => panic!("the repository is blocked"), + } + }; + + other.seed(rid).unwrap(); + assert_eq!(scope(&other), Scope::All); + + other + .profile + .policies_mut() + .unwrap() + .seed(&rid, Scope::Followed) + .unwrap(); + other.seed(rid).unwrap(); + assert_eq!(scope(&other), Scope::Followed); +} + +#[test] +fn a_project_without_a_head_is_not_taken_for_a_split_actor() { + use radicle::test::fixtures; + + let (tmp, state, _) = actor_state(); + let signer = key(0xff); + let (project, ..) = + fixtures::project(tmp.path().join("project"), &state.profile.storage, &signer).unwrap(); + let joining = AppState { + profile: test::profile(&tmp.path().join("joining"), [0xdd; 32]), + }; + fetch(&joining, &state, project); + let copy = joining.profile.storage.repository(project).unwrap(); + let branches = ["refs/heads/master".to_owned(), { + let key = signer.public_key(); + format!("refs/namespaces/{key}/refs/heads/master") + }]; + for branch in branches { + copy.backend + .find_reference(&branch) + .unwrap() + .delete() + .unwrap(); + } + assert!(joining.profile.storage.contains(&project).is_err()); + + let refused = joining.joinable_actor(project).unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::NotJoinable(r)) if r == project)); +} + +/// Puts `file` as the profile on the branch of `other`, on a commit of its +/// own over the canonical head: a version this device does not have. +fn their_version( + repo: &radicle::storage::git::Repository, + other: &SigningKey, + file: &str, +) -> radicle::git::raw::Oid { + let parent = repo + .backend + .find_commit(oid(repo, "refs/heads/main").unwrap()) + .unwrap(); + let root = parent.tree().unwrap(); + let folder = root.get_name(".radicle").unwrap().to_object(&repo.backend); + let mut folder = repo.backend.treebuilder(folder.unwrap().as_tree()).unwrap(); + let blob = repo.backend.blob(file.as_bytes()).unwrap(); + folder.insert("profile.json", blob, 0o100_644).unwrap(); + let mut root = repo.backend.treebuilder(Some(&root)).unwrap(); + root.insert(".radicle", folder.write().unwrap(), 0o040_000) + .unwrap(); + let tree = repo.backend.find_tree(root.write().unwrap()).unwrap(); + + let signature = repo.backend.signature().unwrap(); + let theirs = repo + .backend + .commit(None, &signature, &signature, "Edit", &tree, &[&parent]) + .unwrap(); + let branch = format!("refs/namespaces/{}/refs/heads/main", other.public_key()); + repo.backend + .reference(&branch, theirs, true, "fetch") + .unwrap(); + + theirs +} + +#[test] +fn another_controllers_version_is_cleaned_before_it_is_shown() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + + their_version( + &repo, + &other, + "{\"version\": 1, \"displayName\": \"ca\u{202e}rol\"}", + ); + + let split = state.actor().unwrap().unwrap(); + assert_eq!( + split.forks[0].profile.as_ref().unwrap().display_name, + "carol" + ); + let changes = split.forks[0].changes.as_ref().unwrap(); + assert!(changes.contains("+ \"displayName\": \"carol\"")); +} + +#[test] +fn a_newer_version_elsewhere_is_never_replaced() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let canonical = oid(&repo, "refs/heads/main"); + + their_version( + &repo, + &other, + r#"{"version": 2, "displayName": "carol", "later": true}"#, + ); + + let split = state.actor().unwrap().unwrap(); + assert!(split.forks[0].profile_newer); + + let refused = state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::ProfileNewer))); + assert_eq!(oid(&repo, "refs/heads/main"), canonical); +} + +#[test] +fn a_version_elsewhere_that_cannot_be_read_is_still_reported() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + + let theirs = their_version(&repo, &other, "no profile"); + + let split = state.actor().unwrap().unwrap(); + assert_eq!(split.forks.len(), 1); + assert_eq!(split.forks[0].head, theirs); + assert!(split.forks[0].profile.is_none()); + assert_eq!(split.forks[0].base.as_ref().unwrap().display_name, "alice"); +} + +#[test] +fn two_versions_that_each_merged_the_other_have_no_one_split_point() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + // A picture both versions have had all along. + let base = { + let parent = repo + .backend + .find_commit(oid(&repo, "refs/heads/main").unwrap()) + .unwrap(); + let blob = repo.backend.blob(b"a picture").unwrap(); + let mut root = repo + .backend + .treebuilder(Some(&parent.tree().unwrap())) + .unwrap(); + root.insert("avatar.png", blob, 0o100_644).unwrap(); + let tree = repo.backend.find_tree(root.write().unwrap()).unwrap(); + let signature = repo.backend.signature().unwrap(); + let with_picture = repo + .backend + .commit(None, &signature, &signature, "Add", &tree, &[&parent]) + .unwrap(); + moved_to(&repo, &state, with_picture); + + with_picture + }; + + // Both devices save apart, and then each closes the split before it has + // the other's merge. + let theirs = saved_elsewhere(&repo, base, "carol"); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + let mine = oid(&repo, "refs/heads/main").unwrap(); + fetched(&repo, other.public_key(), theirs); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + let their_merge = { + let parents = [theirs, mine].map(|parent| repo.backend.find_commit(parent).unwrap()); + let tree = actor::profile_tree( + &repo.backend, + Some(&parents[0].tree().unwrap()), + &named("dave"), + ) + .unwrap(); + let signature = repo.backend.signature().unwrap(); + repo.backend + .commit( + None, + &signature, + &signature, + "Merge", + &tree, + &[&parents[0], &parents[1]], + ) + .unwrap() + }; + fetched(&repo, other.public_key(), their_merge); + + // Either save could be called the point they split at, so neither is. + let split = state.actor().unwrap().unwrap(); + assert_eq!(split.forks.len(), 1); + assert_eq!( + split.forks[0].profile.as_ref().unwrap().display_name, + "dave" + ); + assert!(split.forks[0].base.is_none()); + assert!(split.forks[0].changes.is_none()); + // With no point to count from, the other files are those that differ + // from this device's version, and the picture does not. + assert!(!split.forks[0].other_files); +} + +/// Points the canonical branch and this device's own at `commit`, as a save +/// from this device would. +fn moved_to( + repo: &radicle::storage::git::Repository, + state: &AppState, + commit: radicle::git::raw::Oid, +) { + let own = format!( + "refs/namespaces/{}/refs/heads/main", + state.profile.public_key + ); + for branch in ["refs/heads/main", own.as_str()] { + repo.backend + .reference(branch, commit, true, "save") + .unwrap(); + } +} + +#[test] +fn a_split_from_a_newer_profile_is_not_told_from_a_trimmed_one() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + + // Another app wrote the profile both versions start from. + let newer = their_version( + &repo, + &other, + r#"{"version": 2, "displayName": "alice", "later": true}"#, + ); + moved_to(&repo, &state, newer); + their_version(&repo, &other, r#"{"version": 1, "displayName": "carol"}"#); + + let split = state.actor().unwrap().unwrap(); + assert_eq!(split.forks.len(), 1); + assert_eq!( + split.forks[0].profile.as_ref().unwrap().display_name, + "carol" + ); + assert!(split.forks[0].base.is_none()); + assert!(split.forks[0].changes.is_none()); +} + +#[test] +fn a_branch_that_cannot_be_walked_does_not_hide_the_profile() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + + // The other controller's branch points at something that is no commit. + let blob = repo.backend.blob(b"no commit").unwrap(); + let branch = format!("refs/namespaces/{}/refs/heads/main", other.public_key()); + repo.backend + .reference(&branch, blob, true, "fetch") + .unwrap(); + + let shown = state.actor().unwrap().unwrap(); + assert_eq!(shown.profile.unwrap().display_name, "alice"); + assert!(shown.forks.is_empty()); +} + +#[test] +fn a_version_elsewhere_that_changed_other_files_says_so() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + + let theirs = their_version(&repo, &other, r#"{"version": 1, "displayName": "carol"}"#); + let split = state.actor().unwrap().unwrap(); + assert!(!split.forks[0].other_files); + + // The other device adds a picture next to the profile. + let parent = repo.backend.find_commit(theirs).unwrap(); + let blob = repo.backend.blob(b"a picture").unwrap(); + let mut root = repo + .backend + .treebuilder(Some(&parent.tree().unwrap())) + .unwrap(); + root.insert("avatar.png", blob, 0o100_644).unwrap(); + let tree = repo.backend.find_tree(root.write().unwrap()).unwrap(); + let signature = repo.backend.signature().unwrap(); + let with_picture = repo + .backend + .commit(None, &signature, &signature, "Add", &tree, &[&parent]) + .unwrap(); + let branch = format!("refs/namespaces/{}/refs/heads/main", other.public_key()); + repo.backend + .reference(&branch, with_picture, true, "fetch") + .unwrap(); + + let split = state.actor().unwrap().unwrap(); + assert!(split.forks[0].other_files); +} + +/// Gives `other` a copy of the actor at `rid` as `state` holds it now. +fn fetch(other: &AppState, state: &AppState, rid: RepoId) { + let target = radicle::storage::git::paths::repository(&other.profile.storage, &rid); + let _ = std::fs::remove_dir_all(&target); + copy_dir( + &radicle::storage::git::paths::repository(&state.profile.storage, &rid), + &target, + ); +} + +/// A key that makes a code for one actor, creates another, and then has the +/// code approved, with the role `controller`. +fn bound_twice(controller: bool) -> (tempfile::TempDir, AppState, AppState, RepoId, RepoId) { + let (tmp, state, joined) = actor_state(); + // The machine of the key `0xee`. + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + fetch(&other, &state, joined); + + let code = other.join_actor(joined).unwrap(); + let created = other + .create_actor(named("bob"), Default::default(), quiet()) + .unwrap() + .rid; + state.approve_enrollment(code, controller, quiet()).unwrap(); + fetch(&other, &state, joined); + + (tmp, state, other, joined, created) +} + +#[test] +fn an_old_code_binds_a_key_that_has_made_its_own_actor() { + let (_tmp, _state, other, joined, created) = bound_twice(true); + + let refused = other.actor().unwrap_err(); + assert!( + matches!(&refused, Error::Actor(actor::Error::Ambiguous(rids)) + if rids.contains(&joined) && rids.contains(&created)), + "{refused}" + ); + let refused = other + .update_actor_profile(named("carol"), Default::default(), quiet()) + .unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Ambiguous(_))), + "{refused}" + ); +} + +#[test] +fn a_key_bound_twice_cannot_approve_its_own_removal() { + let (_tmp, state, other, joined, _created) = bound_twice(true); + let did = did_of(&key(0xee)); + + // The actor's first controller revokes the key: with two controllers + // the change waits for the key's own vote. + let actor = state.remove_actor_key(did, quiet()).unwrap(); + assert!(actor.keys.iter().any(|key| key.did == did && key.bound)); + assert_eq!(actor.pending.len(), 1); + + // Approving acts on the local actor, and a key in two has none: it casts + // this vote only by leaving the actor it names. + fetch(&other, &state, joined); + let refused = other + .approve_actor_revision(actor.pending[0].id, quiet()) + .unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Ambiguous(_))), + "{refused}" + ); +} + +#[test] +fn a_key_bound_twice_leaves_one_actor_by_its_own_vote() { + let (_tmp, state, other, joined, created) = bound_twice(true); + let did = did_of(&key(0xee)); + + let mut both = other + .actors_of_key() + .unwrap() + .iter() + .map(|actor| actor.rid) + .collect::>(); + both.sort(); + let mut expected = vec![joined, created]; + expected.sort(); + assert_eq!(both, expected); + + // Two controllers: the key's vote proposes, and the other one decides. + let leaving = other.leave_actor(joined, quiet()).unwrap(); + assert_eq!(leaving.rid, joined); + assert!(leaving.keys.iter().any(|key| key.did == did)); + assert_eq!(leaving.pending.len(), 1); + assert_eq!(leaving.pending[0].removed, vec![did]); + assert_eq!(leaving.pending[0].accepted, vec![did]); + + fetch(&state, &other, joined); + let left = state + .approve_actor_revision(leaving.pending[0].id, quiet()) + .unwrap(); + assert!(!left.keys.iter().any(|key| key.did == did)); + + fetch(&other, &state, joined); + assert_eq!(other.actor().unwrap().unwrap().rid, created); +} + +#[test] +fn leaving_accepts_the_removal_another_controller_proposed() { + let (_tmp, state, other, joined, created) = bound_twice(true); + let did = did_of(&key(0xee)); + state.remove_actor_key(did, quiet()).unwrap(); + fetch(&other, &state, joined); + + let left = other.leave_actor(joined, quiet()).unwrap(); + + assert!(!left.keys.iter().any(|key| key.did == did)); + assert!(left.pending.is_empty()); + assert_eq!(other.actor().unwrap().unwrap().rid, created); +} + +#[test] +fn a_key_leaves_only_an_actor_it_is_in_and_only_when_it_is_in_two() { + let (_tmp, state, other, joined, created) = bound_twice(true); + + // The first controller is in one actor, and stays in it. + let refused = state.leave_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::NotBound(rid)) if rid == created), + "{refused}" + ); + let refused = state.leave_actor(joined, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::RemoveSelf)), + "{refused}" + ); + assert_eq!(state.actors_of_key().unwrap().len(), 1); + + // An actor would be left without a controller. + let refused = other.leave_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::OnlyController(rid)) if rid == created), + "{refused}" + ); + assert!( + other + .actors_of_key() + .unwrap() + .iter() + .all(|a| a.pending.is_empty()) + ); +} + +#[test] +fn a_key_never_signs_its_leave_of_an_actor_from_a_newer_app() { + let (_tmp, state, other, joined, _created) = bound_twice(true); + + // Both controllers accept a field this version does not define. + let (first, second) = (key(0xff), key(0xee)); + let repo = state.profile.storage.repository_mut(joined).unwrap(); + let mut identity = Identity::load_mut(&repo, &first).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + raw.payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap() + .insert("mood".into(), "unknown".into()); + }) + .unwrap(); + let id = identity + .update(Title::new("Another app's payload").unwrap(), "", &doc) + .unwrap(); + repo.sign_refs(&first).unwrap(); + let mut identity = Identity::load_mut(&repo, &second).unwrap(); + identity.accept(&id).unwrap(); + repo.sign_refs(&second).unwrap(); + repo.set_identity_head().unwrap(); + fetch(&other, &state, joined); + + let refused = other.leave_actor(joined, quiet()).unwrap_err(); + + assert!( + matches!(refused, Error::Actor(actor::Error::PayloadNewer)), + "{refused}" + ); + assert!( + other + .actors_of_key() + .unwrap() + .iter() + .all(|a| a.pending.is_empty()) + ); +} + +/// A key bound twice, where both actors have another controller, so the key +/// could leave either. +fn bound_twice_and_free() -> (tempfile::TempDir, AppState, AppState, RepoId, RepoId) { + let (tmp, state, joined) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + fetch(&other, &state, joined); + + let code = other.join_actor(joined).unwrap(); + let created = other + .create_actor(named("bob"), Default::default(), quiet()) + .unwrap() + .rid; + let repo = other.profile.storage.repository(created).unwrap(); + let third = Enrollment::sign(created, repo.identity().unwrap().current, &key(0xdd)); + other + .approve_enrollment(third.encode(), true, quiet()) + .unwrap(); + state.approve_enrollment(code, true, quiet()).unwrap(); + fetch(&other, &state, joined); + + (tmp, state, other, joined, created) +} + +#[test] +fn a_key_leaves_one_actor_at_a_time() { + // The key would be in no actor if both removals went through. + let (_tmp, state, other, joined, created) = bound_twice_and_free(); + + let leaving = other.leave_actor(joined, quiet()).unwrap(); + let refused = other.leave_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Leaving(rid)) if rid == joined), + "{refused}" + ); + // Asking again for the same one is no second leave. + other.leave_actor(joined, quiet()).unwrap(); + + // One rejection of two controllers closes the change, and the key may + // leave the other actor instead. + fetch(&state, &other, joined); + state + .reject_actor_revision(leaving.pending[0].id, quiet()) + .unwrap(); + fetch(&other, &state, joined); + + let leaving = other.leave_actor(created, quiet()).unwrap(); + assert_eq!(leaving.pending.len(), 1); +} + +#[test] +fn a_key_bound_twice_without_control_is_removed_by_the_controller() { + let (_tmp, state, other, joined, created) = bound_twice(false); + let did = did_of(&key(0xee)); + + let actor = state.remove_actor_key(did, quiet()).unwrap(); + assert!(!actor.keys.iter().any(|key| key.did == did)); + + fetch(&other, &state, joined); + assert_eq!(other.actor().unwrap().unwrap().rid, created); +} + +#[test] +fn a_key_without_control_is_told_who_can_remove_it() { + let (_tmp, _state, other, joined, _created) = bound_twice(false); + let controller = did_of(&key(0xff)); + + let refused = other.leave_actor(joined, quiet()).unwrap_err(); + + assert!( + matches!( + &refused, + Error::Actor(actor::Error::LeaveNeedsController { rid, controllers }) + if *rid == joined && *controllers == vec![controller] + ), + "{refused}" + ); + assert!(refused.to_string().contains(&controller.to_string())); +} + +#[test] +fn a_cancelled_leave_frees_the_key_to_leave_either_actor() { + let (_tmp, _state, other, joined, created) = bound_twice_and_free(); + let did = did_of(&key(0xee)); + let first = other.leave_actor(joined, quiet()).unwrap().pending[0].id; + + // The other controller may never answer, so the key takes its leave back. + let stayed = other.cancel_leave(joined, quiet()).unwrap(); + assert_eq!(stayed.rid, joined); + assert!(stayed.pending.is_empty()); + assert!(stayed.keys.iter().any(|key| key.did == did)); + + let refused = other.cancel_leave(joined, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::NotLeaving(rid)) if rid == joined), + "{refused}" + ); + + // Leaving the same actor again is a new change. + let again = other.leave_actor(joined, quiet()).unwrap(); + assert_eq!(again.pending.len(), 1); + assert_ne!(again.pending[0].id, first); + other.cancel_leave(joined, quiet()).unwrap(); + + let leaving = other.leave_actor(created, quiet()).unwrap(); + assert_eq!(leaving.pending.len(), 1); +} + +#[test] +fn a_key_cancels_only_a_leave_it_proposed() { + let (tmp, state, joined) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + // Four controllers in the end, so two votes leave a change open. + let (first, second) = (key(0xff), key(0xdd)); + { + let repo = state.profile.storage.repository_mut(joined).unwrap(); + let mut identity = Identity::load_mut(&repo, &first).unwrap(); + let mut doc = identity.doc().clone().edit(); + doc.delegate(did_of(&second)); + doc.delegate(did_of(&key(0xcc))); + identity + .update( + Title::new("Add controllers").unwrap(), + "", + &doc.verified().unwrap(), + ) + .unwrap(); + repo.sign_refs(&first).unwrap(); + repo.set_identity_head().unwrap(); + } + fetch(&other, &state, joined); + let code = other.join_actor(joined).unwrap(); + let created = other + .create_actor(named("bob"), Default::default(), quiet()) + .unwrap() + .rid; + let enrolling = state.approve_enrollment(code, true, quiet()).unwrap(); + let accept = |signer: &SigningKey, id| { + let repo = state.profile.storage.repository_mut(joined).unwrap(); + Identity::load_mut(&repo, signer) + .unwrap() + .accept(&id) + .unwrap(); + repo.sign_refs(signer).unwrap(); + repo.set_identity_head().unwrap(); + }; + accept(&second, enrolling.pending[0].id); + + let did = did_of(&key(0xee)); + state.remove_actor_key(did, quiet()).unwrap(); + fetch(&other, &state, joined); + let leaving = other.leave_actor(joined, quiet()).unwrap(); + assert_eq!(leaving.pending.len(), 1); + assert_eq!(leaving.pending[0].accepted.len(), 2); + + let refused = other.cancel_leave(joined, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::LeaveNotOwn(rid)) if rid == joined), + "{refused}" + ); + let refused = other.leave_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Leaving(rid)) if rid == joined), + "{refused}" + ); +} + +#[test] +fn a_change_that_only_unbinds_the_key_counts_as_its_leave() { + let (_tmp, _state, other, joined, created) = bound_twice(true); + let (signer, did) = (key(0xee), did_of(&key(0xee))); + + // Another tool proposes, as the key, to drop it from the keys and keep + // it a controller. + let repo = other.profile.storage.repository_mut(joined).unwrap(); + let mut identity = Identity::load_mut(&repo, &signer).unwrap(); + let doc = identity + .doc() + .clone() + .with_edits(|raw| { + raw.payload + .get_mut(&PayloadId::from_str("dev.radicle.actor").unwrap()) + .unwrap() + .as_object_mut() + .unwrap()["keys"] + .as_object_mut() + .unwrap() + .remove(&did.to_string()); + }) + .unwrap(); + identity + .update(Title::new("Unbind").unwrap(), "", &doc) + .unwrap(); + repo.sign_refs(&signer).unwrap(); + + let refused = other.leave_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Leaving(rid)) if rid == joined), + "{refused}" + ); +} + +#[test] +fn a_leave_that_could_not_be_read_back_writes_nothing() { + let (_tmp, _state, other, joined, _created) = bound_twice(true); + lose_profile_file(&other.profile.storage.repository(joined).unwrap()); + + assert!(other.leave_actor(joined, quiet()).is_err()); + + let listed = other.actors_of_key().unwrap(); + assert_eq!(listed.len(), 2); + assert!(listed.iter().all(|actor| actor.pending.is_empty())); +} + +/// The actor payload of `rid` as `state` holds it now, with its delegates. +fn payload_and_delegates(state: &AppState, rid: RepoId) -> (serde_json::Value, Vec) { + let doc = state + .profile + .storage + .repository(rid) + .unwrap() + .identity_doc() + .unwrap() + .doc; + let payload = doc.payload()[&PayloadId::from_str("dev.radicle.actor").unwrap()].clone(); + + ( + serde_json::to_value(payload).unwrap(), + doc.delegates().iter().copied().collect(), + ) +} + +#[test] +fn retiring_the_actor_a_key_alone_controls_leaves_it_in_the_other() { + let (_tmp, _state, other, joined, created) = bound_twice(true); + let (mut before, delegates) = payload_and_delegates(&other, created); + + let retired = other.retire_actor(created, quiet()).unwrap(); + assert_eq!(retired.rid, created); + assert!(retired.pending.is_empty()); + + // The flag and nothing else: the keys stay, so what they did stays theirs. + before["retired"] = true.into(); + assert_eq!(payload_and_delegates(&other, created), (before, delegates)); + + assert_eq!(other.actor().unwrap().unwrap().rid, joined); + assert_eq!(other.actors_of_key().unwrap().len(), 1); +} + +#[test] +fn a_key_retires_only_an_actor_it_is_in_and_controls() { + let (_tmp, state, other, joined, created) = bound_twice(false); + + let refused = state.retire_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::NotBound(rid)) if rid == created), + "{refused}" + ); + let refused = other.retire_actor(joined, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::NotController)), + "{refused}" + ); + + write_payload_field_as(&other, created, &key(0xee), "mood", "unknown".into()); + let refused = other.retire_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::PayloadNewer)), + "{refused}" + ); + assert_eq!(other.actors_of_key().unwrap().len(), 2); +} + +#[test] +fn a_key_that_is_leaving_one_actor_does_not_retire_another() { + // The key would be in no actor if the leave went through too. + let (_tmp, _state, other, joined, created) = bound_twice(true); + other.leave_actor(joined, quiet()).unwrap(); + + let refused = other.retire_actor(created, quiet()).unwrap_err(); + assert!( + matches!(refused, Error::Actor(actor::Error::Leaving(rid)) if rid == joined), + "{refused}" + ); + + other.cancel_leave(joined, quiet()).unwrap(); + other.retire_actor(created, quiet()).unwrap(); + assert_eq!(other.actor().unwrap().unwrap().rid, joined); +} + +#[test] +fn a_key_does_not_retire_an_actor_others_control_too() { + // Desktop could neither show nor sign the change this would open. + let (_tmp, _state, other, joined, _created) = bound_twice(true); + + let refused = other.retire_actor(joined, quiet()).unwrap_err(); + + assert!( + matches!(refused, Error::Actor(actor::Error::RetireShared(rid)) if rid == joined), + "{refused}" + ); + let listed = other.actors_of_key().unwrap(); + assert_eq!(listed.len(), 2); + assert!(listed.iter().all(|actor| actor.pending.is_empty())); +} + +#[test] +fn a_key_does_not_retire_its_last_actor() { + let (_tmp, state, rid) = actor_state(); + + let refused = state.retire_actor(rid, quiet()).unwrap_err(); + + assert!( + matches!(refused, Error::Actor(actor::Error::LastActor(last)) if last == rid), + "{refused}" + ); + assert_eq!(state.actor().unwrap().unwrap().rid, rid); +} + +#[test] +fn a_retirement_that_could_not_be_read_back_writes_nothing() { + let (_tmp, _state, other, _joined, created) = bound_twice(true); + lose_profile_file(&other.profile.storage.repository(created).unwrap()); + + assert!(other.retire_actor(created, quiet()).is_err()); + + assert_eq!(other.actors_of_key().unwrap().len(), 2); +} + +const PNG: &[u8] = b"\x89PNG\r\n\x1a\na picture"; + +fn with_avatar(bytes: &[u8]) -> actor::ProfileImages { + use base64::Engine as _; + + actor::ProfileImages { + avatar: Some(base64::engine::general_purpose::STANDARD.encode(bytes)), + banner: None, + } +} + +#[test] +fn a_profile_is_created_and_saved_with_its_pictures() { + let tmp = tempfile::tempdir().unwrap(); + let state = AppState { + profile: test::profile(&tmp.path().join("home"), [0xff; 32]), + }; + + let created = state + .create_actor(named("alice"), with_avatar(PNG), quiet()) + .unwrap(); + let rid = created.rid; + assert_eq!( + created.profile.unwrap().avatar.as_deref(), + Some("avatar.png") + ); + let picture = |head: radicle::git::Oid| state.repo_blob_bytes(rid, "avatar.png".into(), head); + assert_eq!(picture(created.head.unwrap()).unwrap(), PNG); + + // A picture that is refused leaves the profile as it was. + let refused = state + .update_actor_profile(named("bob"), with_avatar(b"no picture"), quiet()) + .unwrap_err(); + assert!(matches!(refused, Error::Actor(actor::Error::Profile(_)))); + let current = state.actor().unwrap().unwrap(); + assert_eq!(current.head, created.head); + + let other = b"\x89PNG\r\n\x1a\nanother picture"; + let saved = state + .update_actor_profile(named("alice"), with_avatar(other), quiet()) + .unwrap(); + assert_eq!(picture(saved.head.unwrap()).unwrap(), other); + + // A save that names no picture takes the file away. + let cleared = state + .update_actor_profile(named("alice"), Default::default(), quiet()) + .unwrap(); + assert!(cleared.profile.unwrap().avatar.is_none()); + assert!(picture(cleared.head.unwrap()).is_err()); +} + +#[test] +fn a_save_that_closes_a_split_keeps_the_picture_it_names() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = repo + .backend + .find_commit(oid(&repo, "refs/heads/main").unwrap()) + .unwrap(); + + // The other device saves a picture, apart from an edit on this one. + let (theirs, pictures) = with_avatar(PNG).place(named("carol")).unwrap(); + let tree = actor::profile_tree_with( + &repo.backend, + Some(&base.tree().unwrap()), + &theirs, + &pictures, + &[], + ) + .unwrap(); + let signature = repo.backend.signature().unwrap(); + let their_commit = repo + .backend + .commit(None, &signature, &signature, "Edit", &tree, &[&base]) + .unwrap(); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + fetched(&repo, other.public_key(), their_commit); + + let saved = state + .update_actor_profile(theirs, Default::default(), quiet()) + .unwrap(); + + assert!(saved.forks.is_empty()); + let picture = state.repo_blob_bytes(rid, "avatar.png".into(), saved.head.unwrap()); + assert_eq!(picture.unwrap(), PNG); +} + +/// The other key's change that enrolls `joining`, proposed on the identity +/// as it is. +fn proposed_by(state: &AppState, rid: RepoId, author: &SigningKey, joining: &SigningKey) { + let enrollment = Enrollment::decode(&code(state, joining)).unwrap(); + let repo = state.profile.storage.repository(rid).unwrap(); + let doc = actor::enrolled_doc(&repo.identity_doc().unwrap().doc, &enrollment, true).unwrap(); + + propose(state, rid, author, &doc); +} + +#[test] +fn past_key_changes_are_listed_with_how_each_ended() { + use crate::actor::RevisionState; + + let (_tmp, state, rid) = actor_state(); + let local = Did::from(state.profile.public_key); + let other = key(0xee); + let added = |revision: &actor::ActorRevision| { + revision.added.iter().map(|key| key.did).collect::>() + }; + + // The only controller adds a second, by its vote alone. + state + .approve_enrollment(code(&state, &other), true, quiet()) + .unwrap(); + + // The second proposes a third key, and this one rejects it: with two + // controllers that ends it. + let refused = key(0x22); + proposed_by(&state, rid, &other, &refused); + let id = state.actor().unwrap().unwrap().pending[0].id; + state.reject_actor_revision(id, quiet()).unwrap(); + + // A third controller comes in by both votes. + let third = key(0x66); + let accept = |by: &SigningKey, id: radicle::git::Oid| { + let repo = state.profile.storage.repository_mut(rid).unwrap(); + Identity::load_mut(&repo, by).unwrap().accept(&id).unwrap(); + }; + let proposed = |joining: &SigningKey| { + let pending = state + .approve_enrollment(code(&state, joining), true, quiet()) + .unwrap() + .pending; + pending + .into_iter() + .find(|open| open.author == local) + .unwrap() + .id + }; + accept(&other, proposed(&third)); + + // Two of them each propose another key on the same identity, and the + // remaining one accepts this key's: the other change can no longer apply. + let (taken, passed_over) = (key(0x33), key(0x44)); + proposed_by(&state, rid, &third, &passed_over); + accept(&other, proposed(&taken)); + + // One more is still open, and is not among the past ones. + proposed_by(&state, rid, &other, &key(0x55)); + let open = state.actor().unwrap().unwrap().pending; + assert_eq!(open.len(), 1); + assert_eq!(open[0].state, RevisionState::Open); + + let past = state.closed_actor_revisions().unwrap(); + let told = past + .iter() + .map(|revision| (revision.state, added(revision))) + .collect::>(); + assert_eq!( + told, + [ + (RevisionState::Accepted, vec![did_of(&taken)]), + (RevisionState::Lapsed, vec![did_of(&passed_over)]), + (RevisionState::Accepted, vec![did_of(&third)]), + (RevisionState::Rejected, vec![did_of(&refused)]), + (RevisionState::Accepted, vec![did_of(&other)]), + // The first version adds the key the actor starts with. + (RevisionState::Accepted, vec![local]), + ] + ); + + // The votes are those of the controllers of the time. + let rejected = &past[3]; + assert_eq!(rejected.author, did_of(&other)); + assert_eq!(rejected.accepted, [did_of(&other)]); + assert_eq!(rejected.rejected, [local]); + assert_eq!(past[4].accepted, [local]); + assert!(past[4].added[0].controller); + assert!(past.iter().all(|revision| !revision.unreadable)); +} + +#[test] +fn the_versions_of_a_profile_are_listed_with_what_each_changed() { + let (_tmp, state, _) = actor_state(); + let local = Did::from(state.profile.public_key); + let bio = |text: &str| ActorProfile { + bio: Some(text.to_string()), + ..named("bob") + }; + let pictured = || ActorProfile { + avatar: Some("avatar.png".to_string()), + ..bio("Curiouser.") + }; + let other = b"\x89PNG\r\n\x1a\nanother picture"; + + state + .update_actor_profile(bio("Curiouser."), Default::default(), quiet()) + .unwrap(); + state + .update_actor_profile(bio("Curiouser."), with_avatar(PNG), quiet()) + .unwrap(); + // The picture again, under the name it has. + state + .update_actor_profile(pictured(), with_avatar(other), quiet()) + .unwrap(); + + let all = state.actor_profile_history(None, None).unwrap(); + assert!(!all.more); + let fields = all + .content + .iter() + .map(|edit| edit.fields.clone().unwrap()) + .collect::>(); + assert_eq!( + fields, + [ + vec!["avatar"], + vec!["avatar"], + vec!["displayName", "bio"], + // What the first version sets. + vec!["displayName"], + ] + ); + let head = state.actor().unwrap().unwrap().head.unwrap(); + assert_eq!(all.content[0].commit, head); + assert_eq!(all.content[0].parents, [all.content[1].commit]); + assert!(all.content[3].parents.is_empty()); + assert!(all.content.iter().all(|edit| edit.live)); + assert!(all.content.iter().all(|edit| edit.author == Some(local))); + + // A page says whether more follow it. + let commits = |skip, take| { + let page = state.actor_profile_history(Some(skip), Some(take)).unwrap(); + let commits = page + .content + .iter() + .map(|edit| edit.commit) + .collect::>(); + (commits, page.more) + }; + let listed = all + .content + .iter() + .map(|edit| edit.commit) + .collect::>(); + assert_eq!(commits(0, 3), (listed[..3].to_vec(), true)); + assert_eq!(commits(3, 3), (listed[3..].to_vec(), false)); + assert_eq!(commits(4, 3), (Vec::new(), false)); +} + +#[test] +fn a_joined_split_is_one_version_over_two() { + let (_tmp, state, rid) = actor_state(); + let other = key(0xee); + share_with(&state, rid, &other, 1); + let repo = state.profile.storage.repository(rid).unwrap(); + let base = oid(&repo, "refs/heads/main").unwrap(); + let theirs = saved_elsewhere(&repo, base, "carol"); + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + let mine = oid(&repo, "refs/heads/main").unwrap(); + fetched(&repo, other.public_key(), theirs); + + // Until the save, the other version is none of this key's. + let before = state.actor_profile_history(None, None).unwrap().content; + assert!(before.iter().all(|edit| edit.commit != theirs)); + + state + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + let after = state.actor_profile_history(None, None).unwrap().content; + + let parents = [mine, theirs].map(radicle::git::Oid::from); + assert_eq!(after[0].parents, parents); + // Told against the version it was saved over, which is this key's. + assert_eq!(after[0].fields.as_deref(), Some(&[][..])); + let other_version = after.iter().find(|edit| edit.commit == theirs).unwrap(); + assert_eq!( + other_version.fields.as_deref(), + Some(&["displayName".to_string()][..]) + ); + assert!(after.iter().all(|edit| edit.live)); +} + +#[test] +fn a_save_that_waits_for_a_controller_is_listed_as_waiting() { + let (tmp, state, rid) = actor_state(); + let other = AppState { + profile: test::profile(&tmp.path().join("other"), [0xee; 32]), + }; + let code = { + fetch(&other, &state, rid); + other.join_actor(rid).unwrap() + }; + state.approve_enrollment(code, false, quiet()).unwrap(); + fetch(&other, &state, rid); + + other + .update_actor_profile(named("bob"), Default::default(), quiet()) + .unwrap(); + + let listed = other.actor_profile_history(None, None).unwrap().content; + assert_eq!(listed.len(), 2); + assert!(!listed[0].live); + assert!(listed[1].live); + // The controller's copy has no such version. + assert_eq!( + state + .actor_profile_history(None, None) + .unwrap() + .content + .len(), + 1 + ); +} + +#[test] +fn a_version_that_cannot_be_read_is_listed_without_what_it_changed() { + let (_tmp, state, rid) = actor_state(); + let repo = state.profile.storage.repository(rid).unwrap(); + let own = |commit| moved_to(&repo, &state, commit); + let over = |tree: radicle::git::raw::Oid| { + let parent = repo + .backend + .find_commit(oid(&repo, "refs/heads/main").unwrap()) + .unwrap(); + let signature = repo.backend.signature().unwrap(); + let tree = repo.backend.find_tree(tree).unwrap(); + repo.backend + .commit(None, &signature, &signature, "Edit", &tree, &[&parent]) + .unwrap() + }; + let fields = || { + let listed = state.actor_profile_history(None, None).unwrap().content; + listed[0].fields.clone() + }; + + // A file whose contents never arrived. + lose_profile_file(&repo); + own(oid(&repo, "refs/heads/main").unwrap()); + assert_eq!(fields(), None); + assert_eq!( + state + .actor_profile_history(None, None) + .unwrap() + .content + .len(), + 2 + ); + + // No profile file at all sets no field, so the save after it sets its own. + let empty = repo.backend.treebuilder(None).unwrap().write().unwrap(); + own(over(empty)); + assert_eq!(fields(), None, "told against a version that cannot be read"); + let with_profile = actor::profile_tree(&repo.backend, None, &named("bob")).unwrap(); + own(over(with_profile.id())); + assert_eq!(fields(), Some(vec!["displayName".to_string()])); + + // A profile from a newer version is not told apart field by field. + let newer = their_version( + &repo, + &key(0xee), + r#"{"version": 2, "displayName": "bob", "later": true}"#, + ); + own(newer); + assert_eq!(fields(), None); +} diff --git a/desktop/crates/radicle-types/src/traits/repo.rs b/desktop/crates/radicle-types/src/traits/repo.rs index 74efdce7e..de007677e 100644 --- a/desktop/crates/radicle-types/src/traits/repo.rs +++ b/desktop/crates/radicle-types/src/traits/repo.rs @@ -13,6 +13,7 @@ use radicle::storage; use radicle::storage::{ReadRepository, ReadStorage, RepositoryInfo, WriteStorage}; use radicle::{git, identity, node}; +use crate::actor; use crate::cobs; use crate::diff; use crate::diff::Diff; @@ -426,6 +427,7 @@ pub trait Repo: Profile { name: data.name, private: doc.is_private(), seeding, + actor: is_actor(storage, rid, &doc), }); } @@ -1096,7 +1098,15 @@ pub trait Repo: Profile { let profile = self.profile(); let mut node = radicle::Node::new(profile.home().socket_from_env()); - profile.seed(rid, node::policy::Scope::All, &mut node)?; + // A scope the user already set for the repository stays as it is. + let scope = match (*profile.policies()?).seed_policy(&rid)? { + Some(node::policy::SeedPolicy { + policy: node::policy::SeedingPolicy::Allow { scope }, + .. + }) => scope, + _ => node::policy::Scope::All, + }; + profile.seed(rid, scope, &mut node)?; // The policy alone only fetches once a seed next announces the repo, // which a quiet one may not do for a long time. Fetch now, like @@ -1209,6 +1219,28 @@ fn seed_candidates( .collect() } +/// Whether `rid`, with `doc` as its current document, is an actor's +/// repository: both its first document and `doc` hold a valid actor payload. +/// Reads the first document of a repository whose current one holds such a +/// payload, and of no other. +fn is_actor(storage: &storage::git::Storage, rid: identity::RepoId, doc: &Doc) -> bool { + if actor::ActorPayload::of(doc).is_none() { + return false; + } + + let root = storage + .repository(rid) + .and_then(|repo| Ok(repo.identity_doc_at(repo.identity_root()?)?)); + + match root { + Ok(root) => actor::ActorPayload::of(&root.doc).is_some(), + Err(e) => { + log::warn!("Not able to tell whether {rid} is an actor's: {e}"); + false + } + } +} + fn is_radicle_metadata(repo: &git2::Repository, oid: git::Oid) -> bool { repo.find_commit(oid.into()) .and_then(|commit| commit.tree()) diff --git a/desktop/crates/test-http-api/src/api.rs b/desktop/crates/test-http-api/src/api.rs index 82868d0e1..c1cba86a8 100644 --- a/desktop/crates/test-http-api/src/api.rs +++ b/desktop/crates/test-http-api/src/api.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use axum::Router; use axum::body::Bytes; -use axum::extract::{FromRequestParts, Request, State}; +use axum::extract::{DefaultBodyLimit, FromRequestParts, Request, State}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Json, Response}; use axum::routing::post; @@ -22,6 +22,7 @@ use radicle::node::{NOTIFICATIONS_DB_FILE, NodeId}; use radicle::storage::{ReadRepository as _, ReadStorage as _}; use radicle::{git, identity}; use radicle_types as types; +use radicle_types::actor::ActorProfile; use radicle_types::cobs::CobOptions; use radicle_types::cobs::FromRadicleAction; use radicle_types::cobs::issue; @@ -37,6 +38,7 @@ use radicle_types::domain::patch::traits::PatchService; use radicle_types::error::Error; use radicle_types::outbound::sqlite::Sqlite; use radicle_types::traits::Profile; +use radicle_types::traits::actor::Actor; use radicle_types::traits::artifact_node::ArtifactNode; use radicle_types::traits::board::Boards; use radicle_types::traits::cobs::Cobs; @@ -62,6 +64,7 @@ impl Boards for Context {} impl Repo for Context {} impl Cobs for Context {} impl Identity for Context {} +impl Actor for Context {} impl Inbox for Context {} impl Thread for Context {} impl Issues for Context {} @@ -177,6 +180,43 @@ pub fn router(shared: Shared) -> Router { .route("/update_board", post(update_board_handler)) .route("/rename_board", post(rename_board_handler)) .route("/set_board_columns", post(set_board_columns_handler)) + // A save carries its pictures in the body. + .route( + "/create_actor", + post(create_actor_handler).layer(DefaultBodyLimit::max(PROFILE_BODY_BYTES)), + ) + .route( + "/update_actor_profile", + post(update_actor_profile_handler).layer(DefaultBodyLimit::max(PROFILE_BODY_BYTES)), + ) + .route("/joinable_actor", post(joinable_actor_handler)) + .route("/join_actor", post(join_actor_handler)) + .route("/approve_enrollment", post(approve_enrollment_handler)) + .route( + "/approve_actor_revision", + post(approve_actor_revision_handler), + ) + .route( + "/withdraw_actor_revision", + post(withdraw_actor_revision_handler), + ) + .route( + "/reject_actor_revision", + post(reject_actor_revision_handler), + ) + .route("/remove_actor_key", post(remove_actor_key_handler)) + .route("/actors_of_key", post(actors_of_key_handler)) + .route( + "/closed_actor_revisions", + post(closed_actor_revisions_handler), + ) + .route( + "/actor_profile_history", + post(actor_profile_history_handler), + ) + .route("/leave_actor", post(leave_actor_handler)) + .route("/cancel_leave", post(cancel_leave_handler)) + .route("/retire_actor", post(retire_actor_handler)) .route_layer(middleware::from_fn_with_state( Arc::new(Mutex::new(())), serialize_writes, @@ -201,6 +241,8 @@ pub fn router(shared: Shared) -> Router { .route("/list_repo_refs", post(list_repo_refs_handler)) .route("/list_canonical_tags", post(list_canonical_tags_handler)) .route("/identity_by_repo", post(identity_handler)) + .route("/actor", post(actor_handler)) + .route("/decode_enrollment", post(decode_enrollment_handler)) .route("/version", post(version_handler)) .route("/git_info", post(git_info_handler)) .route("/diff_stats", post(diff_stats_handler)) @@ -468,6 +510,175 @@ async fn identity_handler( Ok::<_, Error>(Json(identity)) } +async fn actor_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.actor()?)) +} + +/// Room for an avatar and a banner at their limits, as base64. +const PROFILE_BODY_BYTES: usize = 8 * 1024 * 1024; + +#[derive(Deserialize)] +struct ActorProfileBody { + pub profile: ActorProfile, + #[serde(default)] + pub images: types::actor::ProfileImages, + pub opts: types::cobs::CobOptions, +} + +async fn create_actor_handler( + Ctx(ctx): Ctx, + Json(ActorProfileBody { + profile, + images, + opts, + }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.create_actor(profile, images, opts)?)) +} + +async fn update_actor_profile_handler( + Ctx(ctx): Ctx, + Json(ActorProfileBody { + profile, + images, + opts, + }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.update_actor_profile(profile, images, opts)?)) +} + +async fn joinable_actor_handler( + Ctx(ctx): Ctx, + Json(RepoBody { rid }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.joinable_actor(rid)?)) +} + +async fn join_actor_handler( + Ctx(ctx): Ctx, + Json(RepoBody { rid }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.join_actor(rid)?)) +} + +#[derive(Deserialize)] +struct CodeBody { + pub code: String, +} + +async fn decode_enrollment_handler( + Ctx(ctx): Ctx, + Json(CodeBody { code }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.decode_enrollment(code)?)) +} + +#[derive(Deserialize)] +struct EnrollmentBody { + pub code: String, + pub controller: bool, + pub opts: types::cobs::CobOptions, +} + +async fn approve_enrollment_handler( + Ctx(ctx): Ctx, + Json(EnrollmentBody { + code, + controller, + opts, + }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.approve_enrollment(code, controller, opts)?)) +} + +#[derive(Deserialize)] +struct RevisionBody { + pub id: radicle::git::Oid, + pub opts: types::cobs::CobOptions, +} + +async fn approve_actor_revision_handler( + Ctx(ctx): Ctx, + Json(RevisionBody { id, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.approve_actor_revision(id, opts)?)) +} + +async fn withdraw_actor_revision_handler( + Ctx(ctx): Ctx, + Json(RevisionBody { id, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.withdraw_actor_revision(id, opts)?)) +} + +async fn reject_actor_revision_handler( + Ctx(ctx): Ctx, + Json(RevisionBody { id, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.reject_actor_revision(id, opts)?)) +} + +#[derive(Deserialize)] +struct KeyBody { + pub did: identity::Did, + pub opts: types::cobs::CobOptions, +} + +async fn remove_actor_key_handler( + Ctx(ctx): Ctx, + Json(KeyBody { did, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.remove_actor_key(did, opts)?)) +} + +async fn actors_of_key_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.actors_of_key()?)) +} + +async fn closed_actor_revisions_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.closed_actor_revisions()?)) +} + +#[derive(Deserialize)] +struct PageBody { + pub skip: Option, + pub take: Option, +} + +async fn actor_profile_history_handler( + Ctx(ctx): Ctx, + Json(PageBody { skip, take }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.actor_profile_history(skip, take)?)) +} + +#[derive(Deserialize)] +struct RepoWriteBody { + pub rid: identity::RepoId, + pub opts: types::cobs::CobOptions, +} + +async fn leave_actor_handler( + Ctx(ctx): Ctx, + Json(RepoWriteBody { rid, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.leave_actor(rid, opts)?)) +} + +async fn cancel_leave_handler( + Ctx(ctx): Ctx, + Json(RepoWriteBody { rid, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.cancel_leave(rid, opts)?)) +} + +async fn retire_actor_handler( + Ctx(ctx): Ctx, + Json(RepoWriteBody { rid, opts }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.retire_actor(rid, opts)?)) +} + async fn list_repo_refs_handler( Ctx(ctx): Ctx, Json(RepoBody { rid }): Json, diff --git a/desktop/src/App.svelte b/desktop/src/App.svelte index da015c7b1..f26a8075b 100644 --- a/desktop/src/App.svelte +++ b/desktop/src/App.svelte @@ -42,6 +42,7 @@ import Auth from "@app/views/auth/Auth.svelte"; import CreateIdentity from "@app/views/auth/CreateIdentity.svelte"; import InboxView from "@app/views/Inbox.svelte"; + import ProfileView from "@app/views/profile/Profile.svelte"; import Board from "@app/views/repo/Board.svelte"; import Identity from "@app/views/repo/Identity.svelte"; import Issue from "@app/views/repo/Issue.svelte"; @@ -272,6 +273,8 @@ {:else if $activeRouteStore.resource === "repo.board"} + {:else if $activeRouteStore.resource === "profile"} + {:else if $activeRouteStore.resource === "repo.home"} {:else if $activeRouteStore.resource === "repo.commits"} diff --git a/desktop/src/components/ActorAvatar.svelte b/desktop/src/components/ActorAvatar.svelte new file mode 100644 index 000000000..be02d34fa --- /dev/null +++ b/desktop/src/components/ActorAvatar.svelte @@ -0,0 +1,97 @@ + + + + +{#if src && !broken} + Avatar (broken = true)} /> +{:else if patternId && (!named || failed || broken)} + +{/if} diff --git a/desktop/src/components/AddRepoButton.svelte b/desktop/src/components/AddRepoButton.svelte index 04ae13185..8258caba8 100644 --- a/desktop/src/components/AddRepoButton.svelte +++ b/desktop/src/components/AddRepoButton.svelte @@ -3,12 +3,11 @@ + + + + diff --git a/desktop/src/modals/ProfileVersion.svelte b/desktop/src/modals/ProfileVersion.svelte new file mode 100644 index 000000000..6fdf6dc7f --- /dev/null +++ b/desktop/src/modals/ProfileVersion.svelte @@ -0,0 +1,136 @@ + + + + + diff --git a/desktop/src/modals/Settings.svelte b/desktop/src/modals/Settings.svelte index 8f50f1718..b4f0e7429 100644 --- a/desktop/src/modals/Settings.svelte +++ b/desktop/src/modals/Settings.svelte @@ -7,6 +7,7 @@ import { hints } from "@app/lib/hints"; import { invoke } from "@app/lib/invoke"; import { labs } from "@app/lib/labs"; + import * as router from "@app/lib/router"; import { updateChecker } from "@app/lib/updateChecker.svelte"; import { pluralize } from "@app/lib/utils"; @@ -34,6 +35,7 @@ // Shown so that a user seeing the slower fallback can tell which git, if // any, was picked. const gitInfo = invoke("git_info"); + const activeRoute = router.activeUnloadedRouteStore; const diffStyleOptions: Option[] = [ { value: "unified", icon: "diff-unified", title: "Unified" }, @@ -302,6 +304,25 @@ value={labs.boards ? "on" : "off"} onchange={value => (labs.boards = value === "on")} /> +
+
+ Rich profiles + + Link the keys on your devices into one profile. Experimental: the + profile format may still change. + +
+ { + labs.actorRepos = value === "on"; + // The sidebar is loaded with the route, so the page loads again + // for it to follow; the router leaves a page that needs this + // experiment. + void router.replace($activeRoute); + }} /> +