From a5c5917978738a3440441752259c6498858c09f5 Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 13:57:32 +0100 Subject: [PATCH] feat(shared): add the API's contracts and the JSON forms of records The HTTP API needs one definition of everything it sends and receives, shared by the server and its clients so the two can't disagree, and an OpenAPI document generated from it. Records, events, landings and policy requirements now serialize with serde and describe themselves with utoipa. Ids, names, paths, principals, verdicts, kind patterns and periods are JSON strings in the form they display as, and parse from: one `as_text!` line each. An acceptance's signature is hex. `origin_shared::api` holds the rest of the contract: repository names, the requests and responses that aren't records or events themselves, such as `Annotation`, which says whether a statement's claim holds, and `ApiError` with its `ErrorCode`, so clients tell failures apart without reading messages. --- Cargo.lock | 92 +++++ Cargo.toml | 2 + apps/origin-src/src/ancestry.rs | 2 +- crates/origin-shared/Cargo.toml | 3 + crates/origin-shared/src/api.rs | 346 ++++++++++++++++++ crates/origin-shared/src/event.rs | 20 +- crates/origin-shared/src/landing.rs | 11 +- crates/origin-shared/src/lib.rs | 1 + crates/origin-shared/src/object/acceptance.rs | 39 +- crates/origin-shared/src/object/revision.rs | 7 +- crates/origin-shared/src/object/statement.rs | 4 +- crates/origin-shared/src/policy.rs | 4 +- crates/origin-shared/src/target.rs | 4 +- crates/origin-shared/src/text.rs | 80 +++- 14 files changed, 594 insertions(+), 21 deletions(-) create mode 100644 crates/origin-shared/src/api.rs diff --git a/Cargo.lock b/Cargo.lock index 0dac5087..9c3e7ddd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "anstream" version = "1.0.0" @@ -355,6 +364,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -363,6 +374,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jobserver" version = "0.1.35" @@ -429,7 +446,10 @@ dependencies = [ "divan", "ed25519-dalek", "getrandom", + "serde", + "serde_json", "thiserror", + "utoipa", ] [[package]] @@ -493,12 +513,41 @@ dependencies = [ "windows", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-lite" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rustc_version" version = "0.4.1" @@ -557,6 +606,19 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "serde_spanned" version = "1.1.2" @@ -732,6 +794,30 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utoipa" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8765fe27aeff71012a3f90fa474cf1df863a7d0dd81ed25de4e63fff2544994f" +dependencies = [ + "indexmap", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-gen" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d935f1c83fdf8b88f09bbe050d0cea78ea4afee6d7b0317403228c1200b2c8ab" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.9", +] + [[package]] name = "windows" version = "0.62.2" @@ -871,6 +957,12 @@ version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + [[package]] name = "zstd" version = "0.14.3" diff --git a/Cargo.toml b/Cargo.toml index 03b5ad75..4c63dd4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,10 +35,12 @@ reflink-copy = "0.1.30" # Only in origin-platform. The version and features reflink-copy uses on Linux. rustix = { version = "1.1.6", default-features = false, features = ["fs", "std"] } serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" similar = "3.2.0" tempfile = "3.27.0" thiserror = "2.0.21" toml = "1.1.8" +utoipa = { version = "6.0.0", features = ["axum_extras"] } zstd = "0.14.3" [workspace.lints.rust] diff --git a/apps/origin-src/src/ancestry.rs b/apps/origin-src/src/ancestry.rs index 8278e72f..fc644c3c 100644 --- a/apps/origin-src/src/ancestry.rs +++ b/apps/origin-src/src/ancestry.rs @@ -190,6 +190,6 @@ mod tests { #[test] fn unrelated_histories_have_none() { let history = ancestry(&[(2, &[1]), (4, &[3])]); - assert_eq!(bases(&history, &[2, 4]), []); + assert_eq!(bases(&history, &[2, 4]), Vec::::new()); } } diff --git a/crates/origin-shared/Cargo.toml b/crates/origin-shared/Cargo.toml index 4ea995d9..f1c656e3 100644 --- a/crates/origin-shared/Cargo.toml +++ b/crates/origin-shared/Cargo.toml @@ -11,10 +11,13 @@ repository.workspace = true blake3.workspace = true ed25519-dalek.workspace = true getrandom.workspace = true +serde.workspace = true thiserror.workspace = true +utoipa.workspace = true [dev-dependencies] divan.workspace = true +serde_json.workspace = true [[bench]] name = "object" diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs new file mode 100644 index 00000000..3ef81095 --- /dev/null +++ b/crates/origin-shared/src/api.rs @@ -0,0 +1,346 @@ +//! Types of the HTTP API shared by the server and the SDK: the requests, +//! responses and errors that aren't records or events. + +use std::fmt; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; + +use crate::landing::{Landing, Proposal}; +use crate::policy::{KindPattern, Requirement}; +use crate::text::Period; +use crate::{ + Acceptance, AcceptanceId, Head, ObjectId, PrincipalName, RecordId, Revision, RevisionId, + Statement, StatementId, TargetName, +}; + +/// The name of a repository on a server: ASCII letters, digits, `.`, `_` +/// and `-`, not starting with `.`. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, ToSchema)] +#[serde(try_from = "String", into = "String")] +#[schema(value_type = String, example = "origin")] +pub struct RepoName(String); + +impl RepoName { + /// Creates a repository name, checking it follows the rules above. + /// + /// # Errors + /// + /// Fails if the name contains other characters, or starts with `.`. + pub fn new(name: impl Into) -> Result { + let name = name.into(); + let valid = !name.is_empty() + && !name.starts_with('.') + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)); + if valid { + Ok(Self(name)) + } else { + Err(InvalidRepoName(name)) + } + } + + /// The name as a string. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl TryFrom for RepoName { + type Error = InvalidRepoName; + + fn try_from(name: String) -> Result { + Self::new(name) + } +} + +impl From for String { + fn from(name: RepoName) -> Self { + name.0 + } +} + +impl FromStr for RepoName { + type Err = InvalidRepoName; + + fn from_str(name: &str) -> Result { + Self::new(name) + } +} + +impl fmt::Display for RepoName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl fmt::Debug for RepoName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +/// A repository name that [`RepoName::new`] rejected. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("invalid repository name {0:?}")] +pub struct InvalidRepoName(pub String); + +/// A repository, as the server lists it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct RepoSummary { + /// The repository's name. + pub name: RepoName, +} + +/// A request for records, or any other objects, by id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct FetchRecords { + /// The ids of the objects, which are returned in this order. + pub ids: Vec, +} + +/// The result of storing a batch of records. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct Stored { + /// How many of the objects were new to the repository. + pub new: u64, +} + +/// A request for the statements about a record. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, IntoParams)] +#[into_params(parameter_in = Query)] +pub struct StatementsQuery { + /// The record, such as `revision:`. + #[param(value_type = String)] + pub subject: RecordId, +} + +/// A statement, whether its issuer superseded it, and whether its claim +/// holds. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct Annotation { + /// The statement's id. + pub id: StatementId, + /// The statement. + pub statement: Statement, + /// The first statement from the same issuer that supersedes it. + pub superseded_by: Option, + /// Whether the landing queue would count the claim as evidence. It must not + /// be superseded. A promotion must also be valid, its original must not be + /// superseded, and no result about the record may replace it. + pub holds: bool, +} + +/// The revisions of a change. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct Revisions { + /// Every revision, in the order the repository received them. + pub revisions: Vec, + /// The revisions that no other revision of the change evolves from. More + /// than one means the change diverged. + pub heads: Vec, +} + +/// A revision and its id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct RevisionEntry { + /// The revision's id. + pub id: RevisionId, + /// The revision. + pub revision: Revision, +} + +/// A target, its location, and the node that orders it under the policy in +/// force. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct TargetInfo { + /// The target's name. + pub name: TargetName, + /// The target's latest acceptance. + pub head: Head, + /// The node that orders the target, if the policy names one. + pub authority: Option, + /// The statements that landing on the target requires. + pub requirements: Vec, +} + +/// A request for the acceptances of a target. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, IntoParams)] +#[into_params(parameter_in = Query)] +pub struct LogQuery { + /// The target. + #[param(value_type = String)] + pub target: TargetName, + /// The position of the first acceptance to return. Defaults to 0, the first. + #[serde(default)] + pub since: u64, +} + +/// One acceptance in a target's log. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct LogEntry { + /// The revision's id. + pub id: AcceptanceId, + /// The acceptance. Its `seq` is its position in the log. + pub acceptance: Acceptance, +} + +/// A request for the queue to land something. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct LandRequest { + /// What to land. + pub proposal: Proposal, + /// The target to land on. For a change, defaults to the target its stack is + /// on. Landing a target requires it. + pub onto: Option, +} + +/// The outcome of a landing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct Landings { + /// The target landed on. + pub onto: TargetName, + /// The outcome of each landing: one for each change of the stack that the + /// target didn't have, from the bottom, up to the first one that waits. + pub landings: Vec, +} + +/// A request to create a target. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct NewTarget { + /// The new target's name. + pub name: TargetName, + /// The target whose tip the new target starts at. + pub from: TargetName, +} + +/// A request for the events after a cursor. If there are none yet, the +/// server waits for some (a long-poll). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)] +#[into_params(parameter_in = Query)] +pub struct EventsQuery { + /// The cursor to read after: the `next` of the previous page. Defaults to + /// the end of the stream, so only new events are returned. + pub cursor: Option, + /// How long to wait for events, such as `30s`. Without it, the server + /// answers at once, possibly with no events. + #[param(value_type = Option)] + pub wait: Option, + /// Roughly how many events to return. All the events of one op log entry are + /// returned together, so a page can exceed it. + pub limit: Option, + /// Only return events with these names or statement kinds, comma-separated, + /// such as `check.requested,ci.*`. + #[serde(default, skip_serializing_if = "List::is_empty")] + #[param(value_type = Option)] + pub kind: List, + /// Only return events whose subject starts with one of these, + /// comma-separated, such as a revision id prefix, `change:3fa2` or `main`. + #[serde(default, skip_serializing_if = "List::is_empty")] + #[param(value_type = Option)] + pub subject: List, +} + +/// A list written as one comma-separated string, the way query parameters +/// take lists. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct List(pub Vec); + +impl Default for List { + fn default() -> Self { + Self(Vec::new()) + } +} + +impl List { + /// Whether the list has no values. + #[must_use] + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl Serialize for List { + fn serialize(&self, serializer: S) -> Result { + let values: Vec<_> = self.0.iter().map(ToString::to_string).collect(); + serializer.serialize_str(&values.join(",")) + } +} + +impl<'de, T> Deserialize<'de> for List +where + T: FromStr, +{ + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.split(',') + .filter(|value| !value.is_empty()) + .map(str::parse) + .collect::>() + .map(Self) + .map_err(serde::de::Error::custom) + } +} + +/// The error a request failed with. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct ApiError { + /// The kind of failure. + pub code: ErrorCode, + /// A human-readable explanation. + pub message: String, +} + +impl fmt::Display for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for ApiError {} + +/// The kind of an [`ApiError`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + /// The request is malformed, or names records the repository can't accept. + BadRequest, + /// The repository, target, change or record does not exist. + NotFound, + /// The request is valid, but the repository's state refuses it, such as a + /// change that diverged, a target that already exists, or a target another + /// node orders. + Conflict, + /// The event cursor is older than any event the server still keeps. + Expired, + /// The server failed. + Internal, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn repo_names_are_validated() { + for valid in ["origin", "my-repo.v2", "a_b"] { + assert!(RepoName::new(valid).is_ok(), "{valid:?}"); + } + for invalid in ["", ".hidden", "a/b", "sp ace"] { + assert!(RepoName::new(invalid).is_err(), "{invalid:?}"); + } + } + + #[test] + fn lists_are_comma_separated() { + let list: List = serde_json::from_str("\"ci.*,review\"").unwrap(); + assert_eq!(list.0.len(), 2); + assert_eq!(serde_json::to_string(&list).unwrap(), "\"ci.*,review\""); + let empty: List = serde_json::from_str("\"\"").unwrap(); + assert!(empty.is_empty()); + assert!(serde_json::from_str::>("\"CI\"").is_err()); + } +} diff --git a/crates/origin-shared/src/event.rs b/crates/origin-shared/src/event.rs index 1a051596..15726a68 100644 --- a/crates/origin-shared/src/event.rs +++ b/crates/origin-shared/src/event.rs @@ -12,19 +12,26 @@ use crate::{ }; /// An event, with its position in the op log. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Event { /// The sequence number of the op log entry the event comes from. Reading /// from this cursor delivers the events of later entries. pub cursor: u64, /// What happened. + #[serde(flatten)] pub kind: EventKind, } -/// What happened. Consumers deduplicate events by it. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +/// What happened: the event without its cursor. Consumers deduplicate events +/// by it. In JSON, the `event` field holds its name, as [`EventKind::name`] +/// returns it. +#[derive( + Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] +#[serde(tag = "event")] pub enum EventKind { /// A statement was issued. + #[serde(rename = "statement.issued")] StatementIssued { /// The statement. statement: StatementId, @@ -38,6 +45,7 @@ pub enum EventKind { issuer: Principal, }, /// A revision was created. + #[serde(rename = "revision.created")] RevisionCreated { /// The revision. revision: RevisionId, @@ -47,6 +55,7 @@ pub enum EventKind { author: Principal, }, /// A target advanced. + #[serde(rename = "target.advanced")] TargetAdvanced { /// The target. target: TargetName, @@ -56,6 +65,7 @@ pub enum EventKind { acceptance: AcceptanceId, }, /// A waiting landing lacks a statement it requires. + #[serde(rename = "check.requested")] CheckRequested { /// The target it lands on. onto: TargetName, @@ -238,7 +248,9 @@ impl Filter { } /// A batch of events, and the cursor to read the next batch from. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] pub struct Page { /// The events, oldest first. pub events: Vec, diff --git a/crates/origin-shared/src/landing.rs b/crates/origin-shared/src/landing.rs index e2fe3eeb..ab6e91d3 100644 --- a/crates/origin-shared/src/landing.rs +++ b/crates/origin-shared/src/landing.rs @@ -6,7 +6,8 @@ use crate::policy::Requirement; use crate::{ChangeId, Head, RecordId, RepoPath, Source, StatementId, TargetName}; /// What a landing lands. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] pub enum Proposal { /// A change, as of its head. Change(ChangeId), @@ -15,7 +16,8 @@ pub enum Proposal { } /// The outcome of a landing. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] pub enum Landing { /// It landed. Landed { @@ -33,7 +35,7 @@ pub enum Landing { } /// A landing that waits, kept in the queue to be listed and retried. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Pending { /// The target it lands on. pub onto: TargetName, @@ -48,7 +50,8 @@ pub struct Pending { } /// Why a landing waits. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] pub enum Blocked { /// The subject lacks these statements, which the target requires. Evidence(Vec), diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index d310c2c1..25b563b9 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -1,6 +1,7 @@ //! Types shared by every origin component: the object model, the wire //! formats, and the API contracts. +pub mod api; pub mod event; mod id; pub mod landing; diff --git a/crates/origin-shared/src/object/acceptance.rs b/crates/origin-shared/src/object/acceptance.rs index ecc82997..41ff264e 100644 --- a/crates/origin-shared/src/object/acceptance.rs +++ b/crates/origin-shared/src/object/acceptance.rs @@ -11,11 +11,16 @@ pub use ed25519_dalek::Signature; /// One landing on a target, signed by the target's authority. /// -/// Acceptances form a hash chain per target: each names the one before it, -/// and its sequence number is its position in the target's log. -#[derive(Clone, Debug, PartialEq, Eq)] +/// Each acceptance names the one before it on the target, forming a hash +/// chain, and its sequence number is its position in the target's log. +/// +/// In JSON, it is the body's fields plus the signature in hex. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Acceptance { + #[serde(flatten)] body: AcceptanceBody, + #[serde(with = "signature_hex")] + #[schema(value_type = String)] signature: Signature, } @@ -52,7 +57,7 @@ impl Acceptance { } /// An acceptance without its signature. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct AcceptanceBody { /// The target landed on. pub target: TargetId, @@ -104,7 +109,10 @@ impl AcceptanceBody { } /// What an acceptance landed. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] +#[serde(rename_all = "snake_case")] pub enum Source { /// A revision of a change. Revision(RevisionId), @@ -127,6 +135,27 @@ impl Field for Signature { } } +/// Serializes signatures as lowercase hex in JSON. +mod signature_hex { + use serde::{Deserialize, Deserializer, Serializer, de}; + + use super::{Signature, hex}; + + pub fn serialize( + signature: &Signature, + serializer: S, + ) -> Result { + serializer.serialize_str(&hex::string(&signature.to_bytes())) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + hex::decode::<{ ed25519_dalek::SIGNATURE_LENGTH }>(&text) + .map(|bytes| Signature::from_bytes(&bytes)) + .ok_or_else(|| de::Error::custom(format!("invalid signature `{text}`"))) + } +} + /// A node's ed25519 key pair. As a target's authority, the node signs the /// acceptances it writes. pub struct NodeKey(SigningKey); diff --git a/crates/origin-shared/src/object/revision.rs b/crates/origin-shared/src/object/revision.rs index bd97abe0..05e2ebf7 100644 --- a/crates/origin-shared/src/object/revision.rs +++ b/crates/origin-shared/src/object/revision.rs @@ -6,7 +6,7 @@ use crate::{AcceptanceId, BlobId, ChangeId, Principal, RevisionId, TreeId}; /// Editing, rebasing or handing a change to someone else creates a new /// revision of the same change, whose predecessors are the revisions it /// evolves from. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Revision { /// The change this is a version of. pub change: ChangeId, @@ -41,7 +41,10 @@ impl Record for Revision { } /// What a revision was made on top of. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] +#[serde(rename_all = "snake_case")] pub enum Base { /// The state of a target after one of its acceptances. Acceptance(AcceptanceId), diff --git a/crates/origin-shared/src/object/statement.rs b/crates/origin-shared/src/object/statement.rs index dd0be80d..52aa857e 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -16,7 +16,7 @@ use crate::{ /// Statements are permanent. An issuer revises one by issuing another that /// supersedes it. A promoted statement carries another one over to a record /// with the same input digest, pointing at it instead of copying its issuer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Statement { /// The record the claim is about. pub subject: RecordId, @@ -309,7 +309,7 @@ impl Field for Verdict { /// The input digest of a snapshot hashes the ids it stores at `paths`, with /// `definition` and `toolchain`. A statement that declares inputs and isn't /// `external` is promoted to every revision with the same input digest. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Inputs { /// The files and directories read, each covering everything under it. pub paths: Vec, diff --git a/crates/origin-shared/src/policy.rs b/crates/origin-shared/src/policy.rs index a0cbfe70..77f56d30 100644 --- a/crates/origin-shared/src/policy.rs +++ b/crates/origin-shared/src/policy.rs @@ -8,7 +8,9 @@ use crate::{InvalidName, Kind, Principal, PrincipalName, Verdict}; /// A statement that landing needs: of `kind`, with `verdict`, from one of /// `issuer`, about what lands. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive( + Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] pub struct Requirement { /// The statement's kind. pub kind: Kind, diff --git a/crates/origin-shared/src/target.rs b/crates/origin-shared/src/target.rs index 8d78725a..521c4975 100644 --- a/crates/origin-shared/src/target.rs +++ b/crates/origin-shared/src/target.rs @@ -41,7 +41,9 @@ impl TargetName { } /// The latest acceptance of a target. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive( + Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema, +)] pub struct Head { /// Its position in the log, from 0. pub seq: u64, diff --git a/crates/origin-shared/src/text.rs b/crates/origin-shared/src/text.rs index 43416d72..0800e157 100644 --- a/crates/origin-shared/src/text.rs +++ b/crates/origin-shared/src/text.rs @@ -1,9 +1,78 @@ -//! Values written as text. +//! Values written as text in the HTTP API. Ids, names, paths, principals and +//! verdicts are JSON strings in the form they display as and parse from. use std::fmt; use std::str::FromStr; use std::time::Duration; +use utoipa::openapi::RefOr; +use utoipa::openapi::schema::{ObjectBuilder, Schema, Type}; + +use crate::policy::{KindPattern, Principals}; +use crate::{ + AcceptanceId, BlobId, ChangeId, Digest, EntryName, Kind, NodePublicKey, ObjectId, Principal, + PrincipalName, RecordId, RepoPath, RevisionId, StatementId, TargetId, TargetName, TreeId, + Verdict, +}; + +/// Implements serialization for each type as the string it displays as, and +/// deserialization by parsing that string. Also describes it in the OpenAPI +/// document as a string, with an example. +macro_rules! as_text { + ($($type:ty => $example:expr;)*) => {$( + impl serde::Serialize for $type { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } + } + + impl<'de> serde::Deserialize<'de> for $type { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } + } + + impl utoipa::PartialSchema for $type { + fn schema() -> RefOr { + ObjectBuilder::new() + .schema_type(Type::String) + .examples([$example]) + .into() + } + } + + impl utoipa::ToSchema for $type {} + )*}; +} + +/// An example of a 32-byte id. +const ID: &str = "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b"; + +as_text! { + ObjectId => ID; + BlobId => ID; + TreeId => ID; + RevisionId => ID; + StatementId => ID; + AcceptanceId => ID; + TargetId => ID; + Digest => ID; + ChangeId => "3fa2c1d0e9b84f6a7c5d2e1f0a9b8c7d"; + NodePublicKey => "3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29"; + RecordId => format!("revision:{ID}"); + Kind => "ci.test"; + TargetName => "main"; + PrincipalName => "alice"; + EntryName => "main.rs"; + RepoPath => "src/main.rs"; + Principal => "user:alice"; + Verdict => "pass"; + Principals => "group:runners"; + KindPattern => "ci.*"; + Period => "30s"; +} + /// A length of time in whole seconds. It is written as a whole number of /// seconds (`s`), minutes (`m`), hours (`h`) or days (`d`), such as `90d` or /// `30s`. @@ -82,4 +151,13 @@ mod tests { assert!(invalid.parse::().is_err(), "{invalid:?}"); } } + + #[test] + fn values_are_json_strings() { + let record = RecordId::Revision(ID.parse().unwrap()); + let json = serde_json::to_string(&record).unwrap(); + assert_eq!(json, format!("\"revision:{ID}\"")); + assert_eq!(serde_json::from_str::(&json).unwrap(), record); + assert!(serde_json::from_str::("\"Not A Kind\"").is_err()); + } }