diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index 6cbc94b7..a560a93e 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -20,8 +20,8 @@ use origin_shared::access::{InvalidToken, Rights}; use origin_shared::api::{ Annotation, ApiError, BrowseQuery, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken, LandRequest, Landings, Listing, LogEntry, LogQuery, - MORE, NewTarget, PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, - TargetInfo, TokenRequest, + MORE, NewTarget, PromoteRequest, PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, + Stored, TargetInfo, TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -63,6 +63,7 @@ impl Api { .routes(routes!(put_records)) .routes(routes!(inventory)) .routes(routes!(statements)) + .routes(routes!(promote)) .routes(routes!(revisions)) .routes(routes!(targets, create_target)) .routes(routes!(log)) @@ -356,6 +357,34 @@ async fn statements( .map(Json) } +/// Promotes results to a record from the records on the same target with +/// the same input digest, as statements this server issues, and retries the +/// landings waiting for them. +#[utoipa::path( + post, + path = "/api/v1/repos/{repo}/promote", + operation_id = "promote", + params(("repo" = String, Path, description = "The repository")), + request_body = PromoteRequest, + responses( + (status = 200, description = "The statements promoted: none if nothing matched", body = Vec), + (status = 403, description = "The caller isn't signed in", body = ApiError), + (status = 404, description = "The repository or the record does not exist", body = ApiError) + ) +)] +async fn promote( + repos: Repos, + Path(repo): Path, + caller: Caller, + Json(request): Json, +) -> Result>, HttpError> { + call(repos, repo, caller, move |service, caller| { + service.promote(caller, request.subject) + }) + .await + .map(Json) +} + /// Lists the revisions of a change, and its heads. #[utoipa::path( get, diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index b8b965b0..7979cf14 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -1475,6 +1475,21 @@ grants = { all = "none", "user:ada" = "write" } } } + /// A passing result of `kind` by ada about `subject`, which reads only + /// the README, so every revision of `main` shares its input digest. + fn readme_result(subject: RecordId, kind: &str) -> Statement { + Statement { + verdict: Some(origin_shared::Verdict::Pass), + inputs: Some(origin_shared::Inputs { + paths: vec![path("README.md")], + definition: origin_shared::Digest::of(b"test"), + toolchain: origin_shared::Digest::of(b""), + external: false, + }), + ..statement(subject, kind, "user:ada") + } + } + /// `caller`, with a token narrowing them to `scope`, expiring at /// `expires`. fn scoped(principal: &str, scope: &[&str], expires: u64) -> Caller { @@ -1533,20 +1548,8 @@ grants = { all = "none", "user:ada" = "write" } hidden ); - // Ada's results about both, which every revision of `main` shares. - let result = |subject| { - Statement { - verdict: Some(origin_shared::Verdict::Pass), - inputs: Some(origin_shared::Inputs { - paths: vec![path("README.md")], - definition: origin_shared::Digest::of(b"test"), - toolchain: origin_shared::Digest::of(b""), - external: false, - }), - ..statement(subject, "ci.test", "user:ada") - } - .encode() - }; + // Ada's results about both. + let result = |subject| readme_result(subject, "ci.test").encode(); let (of_hidden, of_visible) = (result(hidden), result(visible)); repo.store .write_all(&[of_hidden.clone(), of_visible.clone()]) @@ -1587,6 +1590,66 @@ grants = { all = "none", "user:ada" = "write" } fixture.put(&eve, vec![review(&of_visible)]).unwrap(); } + #[test] + fn promoting_copies_nothing_the_caller_cannot_see() { + let fixture = Fixture::new(); + let repo = &fixture.repo; + let hidden = RecordId::Revision(repo.change_on_main(2, &[("secrets/key", "new")])); + let visible = RecordId::Revision(repo.change_on_main(3, &[("src/lib.rs", "fn b() {}")])); + // Ada's review of the hidden change, with a payload eve can't read. + let payload = EncodedObject::attachment(b"a review of the new secret"); + let review = Statement { + payload: Some(payload.id().into()), + ..readme_result(hidden, "review") + }; + repo.store.write_all(&[payload, review.encode()]).unwrap(); + let promote = |who: &str| fixture.service.promote(&caller(who), visible).unwrap(); + assert_eq!(promote("user:eve").len(), 0); + let [promoted] = &promote("user:ada")[..] else { + panic!("ada sees the review") + }; + assert_eq!(promoted.statement.payload, review.payload); + + // Nor does eve read it by naming its payload in a review of hers. + let eve = caller("user:eve"); + let naming = Statement { + payload: review.payload, + ..statement(visible, "review", "user:eve") + }; + assert!(matches!( + forbidden(fixture.put(&eve, vec![naming.encode()])), + Forbidden::UnsuppliedAttachment { .. } + )); + // Nor as the description of a revision of hers. + let main = TargetName::MAIN; + let (_, records) = Fixture::revision( + 5, + "user:eve", + fixture.tip(&main), + Vec::new(), + fixture.state(&main), + ); + let mut revision: Revision = records[1].decode_as().unwrap(); + revision.description = review.payload.unwrap(); + assert!(matches!( + forbidden(fixture.put(&eve, vec![revision.encode()])), + Forbidden::UnsuppliedAttachment { .. } + )); + // Nor by bringing the review again, to promote it herself. + let promotion = Statement { + subject: visible, + issuer: "user:eve".parse().unwrap(), + promoted_from: Some(review.encode().id().into()), + ..review.clone() + }; + match fixture.put(&eve, vec![review.encode(), promotion.encode()]) { + Err(ServiceError::UnknownRecord(record)) => { + assert_eq!(record, RecordId::Statement(review.encode().id().into())); + } + other => panic!("expected an unknown record, got {other:?}"), + } + } + #[test] fn reserved_kinds_come_from_their_authors_whatever_the_caller_annotates() { let fixture = Fixture::new(); diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 048db7dd..b6e00fc9 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -977,6 +977,57 @@ impl OriginService { Ok(self.store.write_all(&checked)?) } + /// Promotes results to `subject`, a revision or an acceptance the + /// caller sees, from the records they see on the same target with the + /// same input digest, as statements this node issues, and returns them: + /// what a check that would run again can skip. A promotion claims + /// nothing new, so any signed-in caller may ask for one. Landings waiting + /// for evidence about the subject are retried if it has any statement, + /// even when nothing new was promoted: a result put by a call a crash + /// cut short may be what they wait for. + /// + /// # Errors + /// + /// Fails if the caller is anonymous, or a record cannot be read or + /// written. + pub fn promote( + &self, + caller: &Caller, + subject: RecordId, + ) -> Result, ServiceError> { + if *caller == Caller::Anonymous { + return Err(Forbidden::Anonymous.into()); + } + let rights = self.rights(caller)?; + let mut reader = Reader::new(&self.store, &rights.paths); + if !reader.sees(subject)? { + return Err(ServiceError::UnknownRecord(subject)); + } + let (promoted, stated) = self.annotations(|annotations| { + let promoter = self.node.principal(); + let issued = annotations.promote(subject, &promoter, |record| reader.sees(record))?; + let stated = !annotations.index().statements(subject).is_empty(); + Ok((issued, stated)) + })?; + if !promoted.is_empty() { + self.wakeup.notify(); + } + if stated || !promoted.is_empty() { + self.resume(Some(&HashSet::from([subject])))?; + } + Ok(promoted + .into_iter() + // Only originals nothing superseded are promoted, where no + // result of the kind from their issuer holds. + .map(|(id, statement)| Annotation { + id, + statement, + superseded_by: None, + holds: true, + }) + .collect()) + } + /// The statements about `subject`, in the order the repository received /// them: none if the caller doesn't see it. /// @@ -1665,4 +1716,28 @@ mod tests { [Landing::Landed { .. }] )); } + + #[test] + fn results_whose_retry_a_crash_cut_short_land_later() { + let (repo, service) = requiring_ci(); + let revisions = [1, 2].map(|change| { + let revision = repo.change_on_main(change, &[(&format!("docs/{change}"), "")]); + assert!(matches!( + &land(&service, &Caller::Owner, change)[..], + [Landing::Pending(_)] + )); + revision + }); + // Both results are stored, but their landings are never retried. + let results = revisions.map(|revision| ci_test(revision, "user:ci").encode()); + repo.store.write_all(&results).unwrap(); + // A worker asking for promotions, before it finds its result, + // retries the first; a service opening, every one. + service + .promote(&Caller::Owner, RecordId::Revision(revisions[0])) + .unwrap(); + assert_eq!(service.landings(&Caller::Owner).unwrap().len(), 1); + service.resume_waiting().unwrap(); + assert_eq!(service.landings(&Caller::Owner).unwrap(), []); + } } diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 539dc54d..1253e085 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -7,6 +7,7 @@ use std::io; use std::path::{Path, PathBuf}; use std::time::SystemTime; +use origin_shared::api::Annotation; use origin_shared::{ AttachmentId, EncodedObject, Inputs, Kind, Principal, RecordId, Revision, RevisionId, Statement, StatementId, Verdict, @@ -328,6 +329,7 @@ impl Workspace { /// `origin promote []`: carries promotable results over to a /// revision, the working copy by default, from the records on the same /// target with the same input digest, as statements this node issues. + /// Landings waiting for them continue. /// /// # Errors /// @@ -336,15 +338,13 @@ impl Workspace { pub fn promote(&mut self, rev: &str) -> Result<(), WorkspaceError> { let working_copy = self.refresh()?; let revision = working_copy.find_revision(rev)?; - let mut annotations = Annotations::new(&self.store, working_copy.index); - let promoted = - annotations.promote(RecordId::Revision(revision), &self.node_principal(), |_| { - Ok(true) - })?; + let promoted = self + .service(Some(working_copy.index))? + .promote(&Caller::Owner, RecordId::Revision(revision))?; if promoted.is_empty() { println!("Nothing to promote to revision {}", revision.short()); } - for (id, statement) in promoted { + for Annotation { id, statement, .. } in promoted { let Some(original) = statement.promoted_from else { continue; }; diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index db9ece25..e5efd7ea 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -9,7 +9,8 @@ use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; use origin_shared::api::{ BrowseQuery, ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest, - LandRequest, List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, TokenRequest, + LandRequest, List, LogQuery, NewTarget, PromoteRequest, PutQuery, RepoName, StatementsQuery, + TokenRequest, }; use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; @@ -767,6 +768,61 @@ async fn landings_wait_for_evidence() { ); } +#[tokio::test] +async fn promotes_results_by_input_digest() { + let server = Server::start().await; + let repo = &server.demo; + let base = main_tip(repo).await; + let first = Made::revision(change(1), base, vec![], &[("a.txt", "a"), ("doc", "1")]); + let statement = Statement { + inputs: Some(Inputs { + paths: vec![RepoPath::new("a.txt").unwrap()], + definition: Digest::of(b"test"), + toolchain: Digest::of(b""), + external: false, + }), + ..ci_test(first.id, "user:ada") + .decode_as::() + .unwrap() + } + .encode(); + let mut pack = first.pack(); + pack.objects.push(statement.clone()); + repo.put_records(&pack).await.unwrap(); + + let docs_only = Made::revision(change(2), base, vec![], &[("a.txt", "a"), ("doc", "2")]); + repo.put_records(&docs_only.pack()).await.unwrap(); + let request = PromoteRequest { + subject: RecordId::Revision(docs_only.id), + }; + let promoted = repo.promote(&request).await.unwrap(); + let [promotion] = &promoted[..] else { + panic!("{promoted:?}") + }; + assert_eq!( + promotion.statement.promoted_from, + Some(statement.id().into()) + ); + assert_eq!(promotion.statement.issuer.to_string(), "node:hosted"); + assert_eq!( + repo.promote(&request).await.unwrap(), + [], + "already promoted" + ); + + let changed = Made::revision(change(3), base, vec![], &[("a.txt", "b")]); + repo.put_records(&changed.pack()).await.unwrap(); + let request = PromoteRequest { + subject: RecordId::Revision(changed.id), + }; + assert_eq!(repo.promote(&request).await.unwrap(), []); + let anonymous = Client::new(&server.base).repo("demo".parse().unwrap()); + assert_eq!( + code(anonymous.promote(&request).await.unwrap_err()), + ErrorCode::Forbidden + ); +} + #[tokio::test] async fn events_long_poll() { let server = Server::start().await; diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index c815c350..cb10a667 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -22,8 +22,8 @@ use origin_shared::access::Rights; use origin_shared::api::{ Annotation, ApiError, BrowseQuery, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken, LandRequest, Landings, Listing, LogEntry, LogQuery, MORE, - NewTarget, PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, - TokenRequest, + NewTarget, PromoteRequest, PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, + TargetInfo, TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -92,6 +92,11 @@ endpoints! { /// received them. fn statements(query: &StatementsQuery) -> Vec = GET "statements", query(query) => json; + /// Promotes results to a record from the records with the same + /// input digest, as statements the server issues, returning them, + /// and retries the landings waiting for them. + fn promote(request: &PromoteRequest) -> Vec = + POST "promote", json(request) => json; /// What the server holds of some changes: their revisions, heads /// and statements, by id. fn inventory(request: &InventoryRequest) -> Vec = diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 475c0f75..ab8feea3 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -245,6 +245,14 @@ pub struct StatementsQuery { pub subject: RecordId, } +/// Asks for the results of other records to be promoted to one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct PromoteRequest { + /// The record: a revision or an acceptance. + #[schema(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)] diff --git a/docs/openapi.json b/docs/openapi.json index 6a3caf92..35aab7c3 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -526,6 +526,68 @@ } } }, + "/api/v1/repos/{repo}/promote": { + "post": { + "summary": "Promotes results to a record from the records on the same target with\nthe same input digest, as statements this server issues, and retries the\nlandings waiting for them.", + "operationId": "promote", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PromoteRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The statements promoted: none if nothing matched", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Annotation" + } + } + } + } + }, + "403": { + "description": "The caller isn't signed in", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "The repository or the record does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, "/api/v1/repos/{repo}/records": { "put": { "summary": "Puts a batch of objects, as a pack: snapshots, revisions and\nstatements, each needing only objects the batch or the repository has,\nof the kinds it names. With `expect`, only if the changes it names have\nthe heads it says when the records are published.", @@ -2003,6 +2065,19 @@ "group:runners" ] }, + "PromoteRequest": { + "type": "object", + "description": "Asks for the results of other records to be promoted to one.", + "required": [ + "subject" + ], + "properties": { + "subject": { + "type": "string", + "description": "The record: a revision or an acceptance." + } + } + }, "Proposal": { "oneOf": [ {