Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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<Annotation>),
(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<RepoName>,
caller: Caller,
Json(request): Json<PromoteRequest>,
) -> Result<Json<Vec<Annotation>>, 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,
Expand Down
91 changes: 77 additions & 14 deletions apps/origin-src/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()])
Expand Down Expand Up @@ -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();
Expand Down
75 changes: 75 additions & 0 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<Annotation>, 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.
///
Expand Down Expand Up @@ -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(), []);
}
}
12 changes: 6 additions & 6 deletions apps/origin-src/src/workspace/annotate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -328,6 +329,7 @@ impl Workspace {
/// `origin promote [<rev>]`: 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
///
Expand All @@ -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;
};
Expand Down
58 changes: 57 additions & 1 deletion apps/origin-src/tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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::<Statement>()
.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;
Expand Down
9 changes: 7 additions & 2 deletions crates/origin-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -92,6 +92,11 @@ endpoints! {
/// received them.
fn statements(query: &StatementsQuery) -> Vec<Annotation> =
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<Annotation> =
POST "promote", json(request) => json;
/// What the server holds of some changes: their revisions, heads
/// and statements, by id.
fn inventory(request: &InventoryRequest) -> Vec<Inventory> =
Expand Down
8 changes: 8 additions & 0 deletions crates/origin-shared/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
Loading