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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,10 @@ The HTTP API, under `/api/v1`, puts records in batches, if the changes
they revise are where the client saw them, and fetches them by id, walks
snapshots for the trees and blobs a client lacks (the only way files leave
a server), in parts of at most 64 MiB each way, compares the records of
changes, lists statements, revisions, targets and their logs, lands
changes and targets, and streams
changes, lists statements,
revisions, targets and their logs, lists the directories and reads the
files of a target's tip or any revision, without its history, issues
scoped tokens, lands changes and targets, and streams
events by long-poll: `GET
/api/v1/repos/<repo>/events?cursor=<n>&wait=30s` answers as soon as there
are events after the cursor, with a JSON batch, the next cursor, and the
Expand Down
66 changes: 63 additions & 3 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ use origin_shared::ChangeId;
use origin_shared::Head;
use origin_shared::access::{InvalidToken, Rights};
use origin_shared::api::{
Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory,
InventoryRequest, IssuedToken, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget,
PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, TokenRequest,
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,
};
use origin_shared::event::Page;
use origin_shared::landing::Pending;
Expand Down Expand Up @@ -70,6 +71,8 @@ impl Api {
.routes(routes!(events))
.routes(routes!(whoami))
.routes(routes!(issue_token))
.routes(routes!(tree))
.routes(routes!(file))
.routes(routes!(openapi_document))
}

Expand Down Expand Up @@ -574,6 +577,63 @@ async fn issue_token(
.map(Json)
}

/// Lists a directory of a snapshot: a target's tip, or a revision's or an
/// acceptance's. Withheld entries keep their place.
#[utoipa::path(
get,
path = "/api/v1/repos/{repo}/tree",
operation_id = "tree",
params(("repo" = String, Path, description = "The repository"), BrowseQuery),
responses(
(status = 200, description = "The directory's entries", body = Listing),
(status = 400, description = "The path is a file, or the record has no snapshot", body = ApiError),
(status = 403, description = "The caller reads nothing under the path", body = ApiError),
(status = 404, description = "The repository, the target, the record or the path does not exist", body = ApiError)
)
)]
async fn tree(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Query(query): Query<BrowseQuery>,
) -> Result<Json<Listing>, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.tree(caller, &query)
})
.await
.map(Json)
}

/// Reads a file of a snapshot, as `tree` finds it.
#[utoipa::path(
get,
path = "/api/v1/repos/{repo}/file",
operation_id = "file",
params(("repo" = String, Path, description = "The repository"), BrowseQuery),
responses(
(status = 200, description = "The file's content", content_type = "application/octet-stream", body = Binary),
(status = 400, description = "The path is a directory, or the record has no snapshot", body = ApiError),
(status = 403, description = "The caller may not read the file", body = ApiError),
(status = 404, description = "The repository, the target, the record or the path does not exist", body = ApiError)
)
)]
async fn file(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Query(query): Query<BrowseQuery>,
) -> Result<Response, HttpError> {
let content = call(repos, repo, caller, move |service, caller| {
service.file(caller, &query)
})
.await?;
Ok((
[(header::CONTENT_TYPE, "application/octet-stream")],
content,
)
.into_response())
}

/// The OpenAPI document of this API.
#[utoipa::path(
get,
Expand Down
3 changes: 3 additions & 0 deletions apps/origin-src/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ pub enum Forbidden {
/// The owner has no principal to issue a token for.
#[error("only a signed-in caller gets a token, for themselves")]
NoPrincipal,
/// A path the caller may not read.
#[error("you may not read `{0}`")]
Read(RepoPath),
/// A token's scope reaches beyond its issuer's rights.
#[error("a token may only narrow your rights, which don't include `{0}`")]
Scope(Capability),
Expand Down
10 changes: 7 additions & 3 deletions apps/origin-src/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use origin_client::Client;
use origin_shared::Head;
use origin_shared::access::Rights;
use origin_shared::api::{
ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken,
LandRequest, Landings, LogEntry, LogQuery, NewTarget, PutQuery, RepoName, Stored, TargetInfo,
TokenRequest,
BrowseQuery, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest,
IssuedToken, LandRequest, Landings, Listing, LogEntry, LogQuery, NewTarget, PutQuery, RepoName,
Stored, TargetInfo, TokenRequest,
};
use origin_shared::event::Page;
use origin_shared::landing::Pending;
Expand Down Expand Up @@ -99,6 +99,10 @@ calls! {
/// Issues a token acting for the user, with a narrower scope.
fn issue_token(request: &TokenRequest) -> IssuedToken =
issue_token(request), issue_token(request);
/// Lists a directory of a snapshot.
fn tree(query: &BrowseQuery) -> Listing = tree(query), tree(query);
/// Reads a file of a snapshot.
fn file(query: &BrowseQuery) -> Vec<u8> = file(query), file(query);
}

impl Remote {
Expand Down
106 changes: 101 additions & 5 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ use std::time::Duration;
use origin_platform::Native;
use origin_shared::access::{PathAccess, Rights, Token};
use origin_shared::api::{
Annotation, ErrorCode, EventsQuery, Expected, FetchSnapshot, Inventory, InventoryRequest,
IssuedToken, LandRequest, Landings, LogEntry, LogQuery, NewTarget, RevisionEntry, Revisions,
Stored, TargetInfo, TokenRequest,
Annotation, At, BrowseQuery, ErrorCode, EventsQuery, Expected, FetchSnapshot, Inventory,
InventoryRequest, IssuedToken, LandRequest, Landings, Listed, Listing, LogEntry, LogQuery,
NewTarget, RevisionEntry, Revisions, Stored, TargetInfo, TokenRequest,
};
use origin_shared::event::{EventKind, Filter, Page};
use origin_shared::landing::{Pending, Proposal};
use origin_shared::object::DecodeError;
use origin_shared::pack::{Pack, Packer, Part};
use origin_shared::{
AcceptanceId, Base, ChangeId, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, Principal,
PrincipalName, RecordId, RepoPath, Statement, StatementId, TargetName, TreeId,
PrincipalName, RecordId, RepoPath, Statement, StatementId, TargetName, TreeEntry, TreeId,
};

use crate::annotations::{AnnotateError, Annotations};
Expand All @@ -50,6 +50,7 @@ use crate::permissions::{Forbidden, Reader};
use crate::policy::{Policy, PolicyError};
use crate::queue::{LandError, Queue};
use crate::store::{Store, StoreError};
use crate::tree::Snapshots;

/// A node: its name, and the key it signs acceptances with as the
/// authority of the targets its repositories' policies name it for. A
Expand Down Expand Up @@ -450,6 +451,89 @@ impl OriginService {
Ok(Some(&rights.paths))
}

/// What `query` names, a directory or file of a snapshot the caller
/// sees, the snapshot, and what it withholds from the caller.
fn browse(
&self,
caller: &Caller,
query: &BrowseQuery,
) -> Result<(Option<PathAccess>, TreeId, TreeEntry), ServiceError> {
let rights = self.rights(caller)?;
let record = match &query.at {
At::Target(target) => {
let head = self
.store
.head(target)?
.ok_or_else(|| ServiceError::UnknownTarget(target.clone()))?;
RecordId::Acceptance(head.acceptance)
}
&At::Record(record) => record,
};
let snapshot = self.snapshot_of(&mut Reader::new(&self.store, &rights.paths), record)?;
let withheld = self.filter(&rights, record)?.cloned();
let entry = Snapshots::new(&self.store)
.entry_at(snapshot, &query.path)?
.ok_or_else(|| ServiceError::NoSuchPath(query.path.clone()))?;
if withheld
.as_ref()
.is_some_and(|access| !access.reads_entry(&query.path, &entry))
{
return Err(Forbidden::Read(query.path.clone()).into());
}
Ok((withheld, snapshot, entry))
}

/// Lists a directory of a snapshot: of a target's tip, or of a revision
/// or an acceptance the caller sees. Entries whose content is withheld
/// from the caller keep their place, marked.
///
/// # Errors
///
/// Fails if the target or record doesn't exist or isn't seen, the path
/// isn't a directory, the caller reads nothing under it, or a tree
/// cannot be read.
pub fn tree(&self, caller: &Caller, query: &BrowseQuery) -> Result<Listing, ServiceError> {
let (withheld, snapshot, entry) = self.browse(caller, query)?;
let tree = entry
.subtree()
.ok_or_else(|| ServiceError::NotADirectory(query.path.clone()))?;
let entries = self
.store
.get(tree)?
.iter()
.map(|(name, &entry)| Listed {
name: name.clone(),
kind: entry.kind,
id: entry.id,
withheld: withheld
.as_ref()
.is_some_and(|access| !access.reads_entry(&query.path.join(name), &entry)),
})
.collect();
Ok(Listing {
snapshot,
path: query.path.clone(),
entries,
})
}

/// The content of a file of a snapshot, as [`OriginService::tree`]
/// finds it, which the caller must read.
///
/// # Errors
///
/// Fails like [`OriginService::tree`], or if the path isn't a file.
pub fn file(&self, caller: &Caller, query: &BrowseQuery) -> Result<Vec<u8>, ServiceError> {
let (_, _, entry) = self.browse(caller, query)?;
if entry.kind.is_tree() {
return Err(ServiceError::NotAFile(query.path.clone()));
}
Ok(self
.store
.try_blob(entry.id)?
.ok_or(StoreError::NotFound(entry.id))?)
}

/// What the repository holds of each change that the caller sees: its
/// revisions and heads, and the statements about them, by id. A change
/// it never heard of has none.
Expand Down Expand Up @@ -1072,6 +1156,15 @@ pub enum ServiceError {
/// A snapshot was asked of a record that has none.
#[error("{0} has no snapshot: name a revision or an acceptance")]
NotASnapshot(RecordId),
/// A snapshot has nothing at a path.
#[error("nothing is at `{0}`")]
NoSuchPath(RepoPath),
/// A path listed is a file.
#[error("`{0}` is not a directory")]
NotADirectory(RepoPath),
/// A path read is a directory.
#[error("`{0}` is not a file")]
NotAFile(RepoPath),
/// An object put refers to one as an object of another kind: a
/// snapshot that isn't a tree, a file that is one, a description that
/// isn't an attachment.
Expand Down Expand Up @@ -1156,10 +1249,13 @@ impl ServiceError {
| Self::UnknownChange(_)
| Self::UnknownTarget(_)
| Self::UnknownSnapshot(_)
| Self::UnknownRecord(_) => ErrorCode::NotFound,
| Self::UnknownRecord(_)
| Self::NoSuchPath(_) => ErrorCode::NotFound,
Self::NoTarget
| Self::NotARecord(_)
| Self::NotASnapshot(_)
| Self::NotADirectory(_)
| Self::NotAFile(_)
| Self::WrongKind { .. }
| Self::Malformed { .. }
| Self::Acceptance(_)
Expand Down
67 changes: 65 additions & 2 deletions apps/origin-src/tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use std::time::{Duration, Instant};

use origin_client::{Client, Error, Repo};
use origin_shared::api::{
ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest, LandRequest,
List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, TokenRequest,
BrowseQuery, ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest,
LandRequest, List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, TokenRequest,
};
use origin_shared::event::EventKind;
use origin_shared::landing::{Blocked, Landing, Proposal};
Expand Down Expand Up @@ -869,6 +869,69 @@ async fn tells_callers_what_they_may_do_and_issues_narrower_tokens() {
assert_eq!(code(error), ErrorCode::Forbidden);
}

#[tokio::test]
async fn browses_snapshots_without_their_history() {
let server = Server::start().await;
let made = land_on_strict(
&server,
1,
&[
("README.md", "hello"),
("secrets/key", "hunter2"),
("src/lib.rs", "fn a() {}"),
],
)
.await;
let at = |at: &str, path: &str| BrowseQuery {
at: at.parse().unwrap(),
path: RepoPath::new(path).unwrap(),
};
let root = server.strict.tree(&at("main", "/")).await.unwrap();
let names: Vec<_> = root
.entries
.iter()
.map(|entry| (entry.name.as_str(), entry.kind, entry.withheld))
.collect();
assert_eq!(
names,
[
("README.md", EntryKind::File, false),
("secrets", EntryKind::Tree, false),
("src", EntryKind::Tree, false),
]
);
let revision = format!("revision:{}", made.id);
assert_eq!(
server
.strict
.file(&at(&revision, "secrets/key"))
.await
.unwrap(),
b"hunter2"
);

// Others see that the secret is there, but not what it is.
let anonymous = &server.anonymous;
let root = anonymous.tree(&at("main", "")).await.unwrap();
assert!(root.entries[1].withheld, "{root:?}");
assert_eq!(
anonymous.file(&at("main", "README.md")).await.unwrap(),
b"hello"
);
for path in ["secrets/key", "secrets"] {
let error = anonymous.file(&at("main", path)).await.unwrap_err();
assert_eq!(code(error), ErrorCode::Forbidden, "{path}");
}
let error = anonymous.tree(&at("main", "secrets")).await.unwrap_err();
assert_eq!(code(error), ErrorCode::Forbidden);
let error = anonymous.tree(&at("main", "README.md")).await.unwrap_err();
assert_eq!(code(error), ErrorCode::BadRequest);
let error = anonymous.file(&at("main", "missing")).await.unwrap_err();
assert_eq!(code(error), ErrorCode::NotFound);
let error = anonymous.tree(&at("nowhere", "")).await.unwrap_err();
assert_eq!(code(error), ErrorCode::NotFound);
}

#[tokio::test]
async fn reads_only_what_the_caller_may() {
let server = Server::start().await;
Expand Down
Loading