From 023e892321cb2f202458e62a43e44ae4d89bb7ab Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(workspace): keep what the user may not read out of their clones A clone still fetched every file, and pushed whatever its user changed, leaving the server to refuse it. Every clone and fetch now records the user's rights on the remote in `.origin/access/`, kept by who the remote says they are and their token's scope, so users, and the tokens of one user, whose workspaces share a repository never check their work against one another's rights, and the remote's event cursor is kept per user too. The paths they may not read are withheld: their content never reaches the repository, so they're never in the working copy, and snapshots keep them as they were. When the remote lets them read more, a fetch restores the files they can read now. Pushes that change a path the user may not write, or take a change over with another effect where they can't write, fail before sending anything, as of the user's own rights, which a push asks the remote for if they never synced. The README gains a section on permissions. --- AGENTS.md | 6 + README.md | 53 ++++ apps/origin-src/Cargo.toml | 2 +- apps/origin-src/src/permissions.rs | 2 +- apps/origin-src/src/sync.rs | 70 +++++- apps/origin-src/src/workspace/access.rs | 287 +++++++++++++++++++++- apps/origin-src/src/workspace/mod.rs | 35 ++- apps/origin-src/src/workspace/remote.rs | 60 +++-- apps/origin-src/tests/common/mod.rs | 43 ++++ apps/origin-src/tests/permissions.rs | 309 ++++++++++++++++++++++++ 10 files changed, 821 insertions(+), 46 deletions(-) create mode 100644 apps/origin-src/tests/permissions.rs diff --git a/AGENTS.md b/AGENTS.md index ce68a480..e8065bba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,12 @@ review bots read and write at the same time, written in Rust. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). +## API changes + +Every server feature lives in `OriginService`; transports like HTTP only +translate requests. A new HTTP endpoint also takes a line in the SDK's +`endpoints!` macro, and `just openapi` to update `docs/openapi.json`. + ## Testing & Benchmarks Performance is a primary goal, so benchmarks matter as much as tests. A change diff --git a/README.md b/README.md index a207a818..5c7f04b8 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,59 @@ send each server under `[tokens]`, by its URL (`"http://127.0.0.1:7878" = ""`), or in `$ORIGIN_TOKEN`. See [the design](docs/design.md) for the model. +## Permissions + +What each user may do lives in `policy.toml`, so changing it is a landing +on `policy`, which only `admin` may make: + +```toml +[grants] # capabilities: annotate, land, admin +"group:maintainers" = ["admin", "land *", "annotate review"] +"group:runners" = ["annotate ci.*"] + +[[paths]] # path access: none, read or write +path = "secrets" +grants = { all = "none", "group:maintainers" = "write" } + +[[paths]] # CI's checks: only maintainers redefine them +path = "checks.toml" +grants = { all = "read", "group:maintainers" = "write" } +``` + +Under a path, the most specific rule that mentions you decides, and paths +no rule mentions you for are writable. Without `[grants]`, everyone lands +on every target but `policy` and issues every kind of statement. Content +you may not read never reaches your clone: those files are missing from +the working copy and stay as they were in your revisions, and fetching +restores them once you may read them. Revisions that only change what you +can't read, and the statements about them, are hidden from you, and you +may not issue statements about them, nor promote their results. Reading +nothing hides the repository whole. You may only push revisions that +change paths you write, and land what changes only paths you write. You +may take over someone else's change, and hand it on: where you can't +write, your revision must do exactly what theirs did, the same files +changed from the same contents to the same ones, with exactly the same +conflicts unresolved, on the same change below, and a new change lists +there only those of the revision it's on. Only a new change gets a root +revision. Anyone who reads a change, even with a token that only reads, +may still copy its head as it is: the change then diverges until someone +converges it again. The statements you push need their kind's `annotate`, promotions +included, but for the reserved `core.*` kinds, which come only from whom +core names: `core.abandon` from the change's creator, who made its root +revision, or an `admin`, so you can't abandon a change you took over; +`core.conflict` from a revision's author, or a node. Each user of a clone, +and each scope of their tokens, keeps their own rights on the remote, as +of their last fetch, so workspaces of one clone can act for different +users, or agents. + +`origin token issue --scope ... --ttl ` asks the remote +for a token acting for you with a narrower scope, such as `write src`, +`read /`, `annotate ci.*`, `land main` or `admin`; the server verifies it +without storing it. A server's operator signs one for any principal with +`origin token issue --config origin-server.toml --as user:agent-1 --scope +...`. A token never grants more than its principal's rights, lasts at most +7 days, and a token issued with a token expires with it. + `converge` merges the files of a change's heads. A text file two heads changed holds both versions between conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`), and a binary one keeps one side. A `core.conflict` statement diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 395df508..273e930a 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -25,6 +25,7 @@ origin-client.workspace = true origin-platform.workspace = true origin-shared.workspace = true serde.workspace = true +serde_json.workspace = true similar.workspace = true thiserror.workspace = true tokio.workspace = true @@ -39,7 +40,6 @@ zstd.workspace = true divan.workspace = true # The benchmarks build their working trees with the fixtures. origin-src = { workspace = true, features = ["fixture"] } -serde_json.workspace = true tempfile.workspace = true [[bench]] diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index 32f9513b..b0169d47 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -491,7 +491,7 @@ impl<'a, P: Platform> Writer<'a, P> { /// What revisions do where their writer may not write, as the module /// explains: the service checks it of every revision a signed-in caller -/// puts. +/// puts, and a client of those it pushes, before sending anything. pub struct Effects<'a, P, V> { store: &'a Store

, /// Where revisions are read: a batch's, then the store's. diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index ccab6da2..a8ef5254 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -20,13 +20,16 @@ //! are all the changes this node knows compared. //! - Snapshots don't come with records: [`Sync::need`] fetches one when //! something reads it, such as a checkout, so a clone fetches one -//! snapshot, its target's tip. A snapshot is marked while it's fetched -//! ([`Store::fetching`]), so one whose fetch was interrupted is fetched -//! again rather than taken for whole. +//! snapshot, its target's tip. The remote withholds the content of the +//! paths the user may not read: the trees keep their place, and nothing +//! reads them (see [`Store::with_withheld`]). A snapshot is marked while +//! it's fetched ([`Store::fetching`]), so one whose fetch was interrupted +//! is fetched again rather than taken for whole. //! - **Pushing** shares revisions, with their snapshots, and the user's -//! statements. It never lands anything. It first compares each change's heads with the -//! remote's, and refuses before uploading anything when the remote has a -//! revision this node lacks: the change is stale. The remote checks the +//! statements. It never lands anything. It first compares each change's +//! heads with the remote's, and refuses before uploading anything when +//! the remote has a revision this node lacks: the change is stale, or a +//! revision changes a path the user may not write. The remote checks the //! heads again as it publishes the revisions, so a push racing another //! is refused too. Revisions only go to a remote that has the acceptance //! they're based on. Each object goes after those it needs: snapshots @@ -50,6 +53,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::{iter, mem}; use origin_platform::Native; +use origin_shared::access::{Level, PathAccess}; use origin_shared::api::{ ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, List, LogQuery, PutQuery, @@ -59,12 +63,13 @@ use origin_shared::object::{BadSignature, DecodeError}; use origin_shared::pack::{Pack, Packer, Part}; use origin_shared::{ Acceptance, AcceptanceId, Base, ChangeId, EncodedObject, Head, Object, ObjectId, ObjectKind, - Principal, PrincipalName, Record, RecordId, Revision, RevisionId, Statement, StatementId, - TargetName, TreeId, + Principal, PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Statement, + StatementId, TargetName, TreeId, }; use crate::annotations::Annotations; use crate::index::Index; +use crate::permissions::{Effects, Forbidden}; use crate::policy::{Policy, PolicyError}; use crate::remote::{Remote, RemoteError}; use crate::service::Dependencies; @@ -78,6 +83,8 @@ pub struct Sync<'a> { node: Principal, /// The user, whose statements pushes share. user: Principal, + /// What the user may write on the remote, as of the last fetch. + writes: PathAccess, /// The most bytes a push's request holds: [`Pack::LIMIT`], but in /// tests. pack_limit: usize, @@ -358,17 +365,29 @@ impl<'a> Sync<'a> { /// server sends. const EVENTS: u32 = 1024; - /// Syncs `store` with `remote`, as the node `node`, for `user`. + /// Syncs `store` with `remote`, as the node `node`, for `user`, who + /// writes everything until [`Sync::writing`] says otherwise. pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName, user: Principal) -> Self { Self { store, remote, node: Principal::Node(node), user, + writes: PathAccess::uniform(Level::Write), pack_limit: Pack::LIMIT, } } + /// Syncs knowing the user may only write `paths`, so pushes that would + /// be refused fail before sending anything. + #[must_use] + pub fn writing(self, paths: PathAccess) -> Self { + Self { + writes: paths, + ..self + } + } + /// Syncs pushing requests of at most `limit` bytes. #[cfg(test)] fn with_pack_limit(self, limit: usize) -> Self { @@ -948,6 +967,24 @@ impl<'a> Sync<'a> { Ok(true) } + /// Fetches what the snapshot of `record` holds under `paths`, whatever + /// the store has: files a checkout lacks, such as those whose content + /// was withheld until the user could read them. + /// + /// # Errors + /// + /// Fails if the remote doesn't have the record, or the remote or the + /// store fails. + pub fn need_paths(&self, record: RecordId, paths: Vec) -> Result<(), SyncError> { + let request = FetchSnapshot { + of: record, + have: Vec::new(), + paths, + skip: 0, + }; + self.fetch_parts(request, None) + } + /// Fetches what `request` asks for, part after part, in one batch. With /// `whole`, the snapshot it fetches whole, which is marked until the /// batch is durable. @@ -1013,6 +1050,7 @@ impl<'a> Sync<'a> { { self.check_shared(*id, revision, base)?; } + self.check_writes(revision)?; } // Snapshots and attachments first, then revisions, then statements. @@ -1265,6 +1303,15 @@ impl<'a> Sync<'a> { Ok(()) } + /// Checks that `revision` has an effect the user may give it (see + /// [`Effects`]). + fn check_writes(&self, revision: &Revision) -> Result<(), SyncError> { + match Effects::new(self.store, self.store, &self.writes).check(revision)? { + Some(forbidden) => Err(forbidden.into()), + None => Ok(()), + } + } + /// `changes`, and every change below their revisions, following their /// bases and dependencies. fn stack(&self, index: &Index, changes: &[ChangeId]) -> Result, SyncError> { @@ -1366,6 +1413,9 @@ pub enum SyncError { /// A snapshot was needed of a record that has none. #[error("{0} has no snapshot")] NoSnapshot(RecordId), + /// A push would change what the user may not. + #[error("the remote would refuse the push, as of your rights when you last fetched")] + Forbidden(#[from] Forbidden), /// The change has no revision to push. #[error("change {} has no revisions", .0.short())] UnknownChange(ChangeId), @@ -1442,7 +1492,7 @@ mod tests { use origin_platform::Native; use origin_shared::event::Filter; - use origin_shared::{AcceptanceBody, Kind, NodeKey, RepoPath, Verdict}; + use origin_shared::{AcceptanceBody, Kind, NodeKey, Verdict}; use super::*; use crate::events::Events; diff --git a/apps/origin-src/src/workspace/access.rs b/apps/origin-src/src/workspace/access.rs index 0fdf6101..2d1fcb6c 100644 --- a/apps/origin-src/src/workspace/access.rs +++ b/apps/origin-src/src/workspace/access.rs @@ -1,15 +1,276 @@ //! What the remote lets the user do: `whoami`, `permissions` and `token -//! issue`. +//! issue`, and the paths it withholds. +//! +//! Every clone and fetch records the user's rights on the remote in the +//! repository's `.origin/access/`, in a file of their own, kept by who the +//! remote says they are and their token's scope, so the users, and the +//! tokens of one user, whose workspaces share the repository never check +//! their work against one another's rights, and a new token with the same +//! scope keeps what they knew. Until a user syncs, the paths withheld +//! are those the cloner may not read. The paths they may not read are +//! withheld: their content never reaches this repository, so they're +//! never in the working copy, and snapshots keep them as they were (see +//! [`Store::with_withheld`]). Pushes that change a path they may not write +//! fail before sending anything, as of the user's own rights, which a push +//! asks the remote for if they never synced. When the remote lets them +//! read more, a fetch restores the files they can read now. +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use origin_shared::Period; -use origin_shared::access::{Capability, Rights}; +use origin_shared::access::{Capability, PathAccess, Rights}; use origin_shared::api::TokenRequest; +use origin_shared::{Base, Digest, Period, RepoPath}; use super::{Workspace, WorkspaceError}; +use crate::config::UserConfig; +use crate::remote::RemoteUrl; +use crate::store::Store; +use crate::tree::{FileChange, Snapshots}; +use crate::worktree::Worktree; impl Workspace { + /// The directory in the repository's `.origin` holding what each user + /// who synced with the remote knows of it, in a directory of their own, + /// named by the hash of the remote's URL and their + /// [holder name](Workspace::holder_name): their rights there, `rights`, + /// as JSON, and the remote's event cursor as of their last fetch, which + /// skips the events their rights hide. `tokens/` holds that name + /// for a token, by the hash of the remote's URL and the token, so a new + /// token for the same user, with the same scope, keeps their cursor. `clone/rights` + /// holds the rights of whoever cloned the repository, for the users + /// who haven't synced yet. + const ACCESS: &str = "access"; + + /// The directory of [`Workspace::ACCESS`] naming the bearers of tokens. + const TOKENS: &str = "tokens"; + + /// The file of [`Workspace::ACCESS`] naming who the remote at `url` + /// says the user of `config`, with their token, is. + fn token_file(store: &Store, url: &RemoteUrl, config: &UserConfig) -> PathBuf { + let token = url.token(config).unwrap_or_default(); + let token = Digest::of(format!("{url}\n{token}").as_bytes()); + let tokens = store.root().join(Self::ACCESS).join(Self::TOKENS); + tokens.join(token.to_hex()) + } + + /// What [`Workspace::ACCESS`] calls the user who has `rights`: who the + /// remote says they are, or an anonymous user, and their token's scope, + /// if it's a scoped one, sorted. + fn holder_name(rights: &Rights) -> String { + let principal = rights.principal.as_ref(); + let mut name = principal.map_or_else(|| "anonymous".to_owned(), ToString::to_string); + if let Some(scope) = &rights.scope { + let mut scope: Vec<_> = scope.iter().map(ToString::to_string).collect(); + scope.sort_unstable(); + scope.dedup(); + name = format!("{name} [{}]", scope.join(", ")); + } + name + } + + /// The directory of [`Workspace::ACCESS`] of the user it calls `name` + /// (see [`Workspace::holder_name`]), on the remote at `url`. + fn principal_dir(store: &Store, url: &RemoteUrl, name: &str) -> PathBuf { + let user = Digest::of(format!("{url}\n{name}").as_bytes()); + store.root().join(Self::ACCESS).join(user.to_hex()) + } + + /// The directory of [`Workspace::ACCESS`] of the user of `config`, for + /// the remote at `url`, once the remote said who they are. + fn user_dir( + store: &Store, + url: &RemoteUrl, + config: &UserConfig, + ) -> Result, WorkspaceError> { + let path = Self::token_file(store, url, config); + match fs::read_to_string(&path) { + Ok(name) => Ok(Some(Self::principal_dir(store, url, name.trim_end()))), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(WorkspaceError::io(&path, source)), + } + } + + /// The file in the directory of [`Workspace::ACCESS`] of the user of + /// `config` named `name`, if the repository has a remote, and the + /// user synced with it. + pub(super) fn user_file( + store: &Store, + config: &UserConfig, + name: &str, + ) -> Result, WorkspaceError> { + let Some(url) = Self::remote_url(store)? else { + return Ok(None); + }; + Ok(Self::user_dir(store, &url, config)?.map(|dir| dir.join(name))) + } + + /// The rights a file of [`Workspace::ACCESS`] holds, if it exists. + fn read_access(path: &Path) -> Result, WorkspaceError> { + let content = match fs::read(path) { + Ok(content) => content, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(source) => return Err(WorkspaceError::io(path, source)), + }; + serde_json::from_slice(&content) + .map(Some) + .map_err(|_| WorkspaceError::Malformed(path.to_owned())) + } + + /// The rights on the remote of the user of `config`, as of their last + /// sync, if they synced with it. + fn own_access(store: &Store, config: &UserConfig) -> Result, WorkspaceError> { + match Self::user_file(store, config, "rights")? { + Some(file) => Self::read_access(&file), + None => Ok(None), + } + } + + /// The rights on the remote of the user of `config`, as of their last + /// sync, or else as of the clone, if the repository has a remote. + pub(super) fn access( + store: &Store, + config: &UserConfig, + ) -> Result, WorkspaceError> { + if Self::remote_url(store)?.is_none() { + return Ok(None); + } + match Self::own_access(store, config)? { + Some(rights) => Ok(Some(rights)), + None => Self::read_access(&store.root().join(Self::ACCESS).join("clone/rights")), + } + } + + /// The rights on the remote of the user of `config` that a push is + /// checked against: as of their last sync, or, if they never synced, + /// as the remote says now, never as of the clone, which another user + /// may have made. + pub(super) fn push_access(&mut self) -> Result, WorkspaceError> { + if Self::remote_url(&self.store)?.is_some() + && Self::own_access(&self.store, &self.config)?.is_none() + { + self.refresh_access()?; + } + Self::own_access(&self.store, &self.config) + } + + /// `store`, withholding what the remote does from the user of `config`. + pub(super) fn withholding(store: Store, config: &UserConfig) -> Result { + Ok(match Self::access(&store, config)? { + Some(rights) => store.with_withheld(rights.paths), + None => store, + }) + } + + /// Records the rights of the user of `config` on the remote at `url` in + /// `store`, and as the clone's, if `cloning`. + pub(super) fn save_access( + store: &Store, + url: &RemoteUrl, + config: &UserConfig, + rights: &Rights, + cloning: bool, + ) -> Result<(), WorkspaceError> { + let json = serde_json::to_vec_pretty(rights).expect("rights serialize to JSON"); + let name = Self::holder_name(rights); + let write = store.durable_write(); + let mut dirs = vec![Self::principal_dir(store, url, &name)]; + if cloning { + dirs.push(store.root().join(Self::ACCESS).join("clone")); + } + dirs.into_iter() + .try_for_each(|dir| write.stage(dir.join("rights"), &json)) + .and_then(|()| { + let file = Self::token_file(store, url, config); + write.stage(file, format!("{name}\n").as_bytes()) + }) + .and_then(|()| write.commit()) + .map_err(crate::store::StoreError::from)?; + Ok(()) + } + + /// Records the user's rights on the remote, and withholds what they may + /// not read from now on. Restores the files of the working copy they + /// read now but didn't before. + pub(super) fn refresh_access(&mut self) -> Result<(), WorkspaceError> { + let rights = self.require_remote()?.whoami()?; + let url = Self::remote_url(&self.store)?.ok_or(WorkspaceError::NoRemote)?; + let name = Self::holder_name(&rights); + let dir = Self::principal_dir(&self.store, &url, &name); + // What the user's cursor was read with, and what is withheld now. + let saved = Self::read_access(&dir.join("rights"))?; + let withheld = Self::access(&self.store, &self.config)?; + let known = Self::user_dir(&self.store, &url, &self.config)?.as_ref() == Some(&dir); + if known && saved.as_ref() == Some(&rights) { + return Ok(()); + } + Self::save_access(&self.store, &url, &self.config, &rights, false)?; + if saved.as_ref() != Some(&rights) { + // What the user didn't see before has no events since the + // cursor. + self.forget_cursor()?; + } + if withheld.as_ref() == Some(&rights) { + return Ok(()); + } + self.store = self.store.clone().with_withheld(rights.paths.clone()); + match withheld { + Some(old) => self.restore_readable(&old.paths, &rights.paths), + None => Ok(()), + } + } + + /// Fetches and writes the files of the working copy under the paths + /// `now` reads and `before` didn't. + fn restore_readable( + &self, + before: &PathAccess, + now: &PathAccess, + ) -> Result<(), WorkspaceError> { + let mut paths: Vec = before + .rules() + .chain(now.rules()) + .map(|(path, _)| path.clone()) + .filter(|path| now.reads(path) && !before.reads(path)) + .collect(); + paths.sort_unstable(); + paths.dedup_by(|inner, outer| inner.starts_with(outer)); + if paths.is_empty() { + return Ok(()); + } + let snapshot = self.store.get(self.revision)?.snapshot; + // The working copy kept what it couldn't read as the acceptance at + // the bottom of its stack has it, which the remote has too. + let mut base = self.store.get(self.revision)?.base; + while let Base::Revision(below) = base { + base = self.store.get(below)?.base; + } + self.sync(self.require_remote()?) + .need_paths(base.into(), paths.clone())?; + let mut restored = Vec::new(); + for path in &paths { + let at = Snapshots::new(&self.store).entry_at(snapshot, path)?; + let (tree, file) = match at { + Some(entry) => (entry.subtree(), entry.file()), + None => continue, + }; + if let Some(file) = file { + restored.push(FileChange { + path: path.clone(), + old: None, + new: Some(file), + }); + } + restored.extend(self.store.diff_at(path, None, tree)?); + } + // A restored file never replaces one the user wrote. + restored + .retain(|change| fs::symlink_metadata(self.root.join(change.path.as_str())).is_err()); + Ok(Worktree::new(&self.root, &self.store).checkout(&restored, &[], None)?) + } + /// `origin whoami`: prints who the remote thinks the user is. /// /// # Errors @@ -97,3 +358,23 @@ impl Workspace { Ok(()) } } + +#[cfg(test)] +mod tests { + use origin_shared::access::Level; + + use super::*; + + #[test] + fn rights_round_trip_through_the_access_file() { + let rights = Rights { + paths: PathAccess::new( + Level::Read, + [(RepoPath::new("secrets").unwrap(), Level::None)], + ), + ..Rights::all() + }; + let json = serde_json::to_vec(&rights).unwrap(); + assert_eq!(serde_json::from_slice::(&json).unwrap(), rights); + } +} diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 2529a687..2902af6f 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -9,6 +9,7 @@ //! state the stat cache of the last snapshot //! moving the move in progress, if a checkout is //! lock held by the command working in the working copy +//! remote, access the remote, and what it lets the user do //! ``` //! //! A repository can have several working copies, its workspaces, which @@ -339,7 +340,7 @@ impl Workspace { let revision = Self::read_pointer(root)?.ok_or_else(|| WorkspaceError::Incomplete(root.to_owned()))?; let store = Store::open_writable(store, Native::default())?; - let store = store.with_actor(actor.in_workspace(root)); + let store = Self::withholding(store.with_actor(actor.in_workspace(root)), &config)?; let mut workspace = Self { lock: Some(lock), ..Self::at(root.to_owned(), store, config, revision) @@ -481,7 +482,7 @@ impl Workspace { let revision: Revision = self.store.get(self.revision)?; let path = self.meta(Self::STATE); let loaded = StatCache::load(&path); - let (files, cache) = Worktree::new(&self.root, &self.store).snapshot(&loaded)?; + let (found, cache) = Worktree::new(&self.root, &self.store).snapshot(&loaded)?; let cache = match cache { Some(cache) => { cache @@ -491,6 +492,11 @@ impl Workspace { } None => loaded, }; + // What the user cannot read stays as the revision has it. + let (files, trees) = self.store.keep_withheld(found, revision.snapshot)?; + if !trees.is_empty() { + self.store.write_all(&trees)?; + } let mut index = Index::open(&self.store)?; let behind = self.behind(&index, self.revision, &revision)?; let mut conflicts = self.conflicts(&mut index, self.revision, &revision)?; @@ -854,15 +860,16 @@ impl Workspace { /// The changes that make the files of `from` those of the snapshot of /// `to`, a revision or an acceptance, after fetching what the - /// repository lacks of it. A move asks for them before it publishes - /// `moving`, so a fetch that fails moves nothing. + /// repository lacks of it. The paths the remote withholds stay as they + /// are. A move asks for them before it publishes `moving`, so a fetch + /// that fails moves nothing. fn changes(&self, from: TreeId, to: RecordId) -> Result, WorkspaceError> { self.need(&[to])?; let tree = self .store .snapshot_of(to)? .ok_or(SyncError::NoSnapshot(to))?; - Ok(match self.store.diff(from, tree) { + let changes = match self.store.diff(from, tree) { // A snapshot can lack trees its root names, if its fetch was // cut short before fetches were marked: fetch it whole again. Err(StoreError::NotFound(missing)) => match self.remote()? { @@ -873,7 +880,23 @@ impl Workspace { None => return Err(StoreError::NotFound(missing).into()), }, changes => changes?, - }) + }; + // A clone may lack files its snapshots name: those it could not + // read when it fetched them. + if Self::remote_url(&self.store)?.is_some() { + let mut missing = Vec::new(); + for change in &changes { + if let Some(new) = change.new + && !self.store.contains(new.id)? + { + missing.push(change.path.clone()); + } + } + if !missing.is_empty() { + self.sync(self.require_remote()?).need_paths(to, missing)?; + } + } + Ok(changes) } /// Makes the files match a snapshot, given `changes`, how they differ diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index 92eb9a0f..ab731f1f 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -9,12 +9,12 @@ //! Syncing never changes files under a running workspace: `pull` is a //! fetch, then a move of the working copy. //! -//! The remote's event cursor as of the last fetch, and the generation of -//! the op log it's of, are kept in `.origin/remote-cursor`, so the next -//! fetch only compares the changes -//! that moved since (see [`Sync::moved`]). Every way this repository learns -//! of a change brings all the remote has of it, so the changes it knows are -//! whole as of that cursor. +//! The remote's event cursor as of each user's last fetch, and the +//! generation of the op log it's of, are kept with their rights (see +//! [`Workspace::access`]), so their next fetch only compares the changes +//! that moved since (see [`Sync::moved`]). Every way this repository +//! learns of a change brings all the remote has of it, so the changes it +//! knows are whole as of that cursor. use std::fs; use std::io; @@ -112,6 +112,9 @@ impl Workspace { let meta = root.join(Self::META_DIR); let store = Store::new(meta, Native::default()).with_actor(actor.in_workspace(&root)); store.init()?; + let rights = remote.whoami()?; + Self::save_access(&store, url, &config, &rights, true)?; + let store = store.with_withheld(rights.paths); let sync = Sync::new(&store, &remote, config.node().clone(), config.user()); let cursor = sync.moved(None)?.cursor; sync.fetch_chains(slice::from_ref(target))?; @@ -156,15 +159,11 @@ impl Workspace { Ok(workspace) } - /// The file in the repository's `.origin` holding the remote's event - /// cursor as of the last fetch. - const CURSOR: &str = "remote-cursor"; - - /// The remote's event cursor as of the last fetch, if any, written - /// ` `. One that cannot be read is forgotten: the - /// next fetch compares every change. + /// The remote's event cursor as of the user's last fetch, if any, + /// written ` `. One that cannot be read is + /// forgotten: the next fetch compares every change. fn cursor(&self) -> Option { - let path = self.store.root().join(Self::CURSOR); + let path = Self::user_file(&self.store, &self.config, "cursor").ok()??; let text = fs::read_to_string(path).ok()?; let (generation, next) = text.trim_end().split_once(' ')?; Some(Cursor { @@ -177,15 +176,20 @@ impl Workspace { /// or none, is as good, only slower to fetch from, and one torn by a /// crash doesn't parse, or reads from earlier. fn save_cursor(&self, cursor: &Cursor) -> Result<(), WorkspaceError> { - let path = self.store.root().join(Self::CURSOR); + let Some(path) = Self::user_file(&self.store, &self.config, "cursor")? else { + return Ok(()); + }; let text = format!("{} {}\n", cursor.generation, cursor.next); fs::write(&path, text).map_err(|source| WorkspaceError::io(&path, source)) } - /// Forgets the remote's event cursor: the next fetch compares every - /// change, for a new remote, or once the user sees more of it. + /// Forgets the remote's event cursor as of the user's last fetch: the + /// next fetch compares every change, for a new remote, or once the user + /// sees more of it. pub(super) fn forget_cursor(&self) -> Result<(), WorkspaceError> { - let path = self.store.root().join(Self::CURSOR); + let Some(path) = Self::user_file(&self.store, &self.config, "cursor")? else { + return Ok(()); + }; match fs::remove_file(&path) { Err(error) if error.kind() != io::ErrorKind::NotFound => { Err(WorkspaceError::io(&path, error)) @@ -194,9 +198,9 @@ impl Workspace { } } - /// The URL of the repository's remote, if it has one. - fn remote_url(&self) -> Result, WorkspaceError> { - let path = self.store.root().join(Self::REMOTE); + /// The URL of the remote of the repository in `store`, if it has one. + pub(super) fn remote_url(store: &Store) -> Result, WorkspaceError> { + let path = store.root().join(Self::REMOTE); match fs::read_to_string(&path) { Ok(url) => Ok(Some(RemoteUrl::parse(url.trim_end())?)), Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), @@ -220,7 +224,7 @@ impl Workspace { if let Some(remote) = self.remote.get() { return Ok(remote.as_ref()); } - let remote = match self.remote_url()? { + let remote = match Self::remote_url(&self.store)? { Some(url) => Some(Self::open_remote(&url, &self.config)?), None => None, }; @@ -250,7 +254,7 @@ impl Workspace { /// read or written. pub fn set_remote(&self, url: Option<&str>) -> Result<(), WorkspaceError> { let Some(url) = url else { - match self.remote_url()? { + match Self::remote_url(&self.store)? { Some(url) => println!("{url}"), None => println!("No remote: set one with `origin remote `."), } @@ -277,10 +281,11 @@ impl Workspace { /// Fails if there's no remote, it lacks a target or change asked for, /// or the remote or the store fails. pub fn fetch( - &self, + &mut self, targets: &[TargetName], changes: &[ChangeId], ) -> Result<(), WorkspaceError> { + self.refresh_access()?; let remote = self.require_remote()?; // Changes landed on a target fetched for the first time are older // than the cursor: forget it, so they're compared, by a retry too. @@ -344,7 +349,12 @@ impl Workspace { .map(|change| working_copy.find_change(change)) .collect::>()? }; - let pushed = self.sync(self.require_remote()?).push(&changes)?; + let rights = self.push_access()?; + let mut sync = self.sync(self.require_remote()?); + if let Some(rights) = rights { + sync = sync.writing(rights.paths); + } + let pushed = sync.push(&changes)?; for statement in &pushed.unsent { println!( "Statement {} stays here: it needs a statement the remote doesn't have", diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 1e2865a2..8c5dfeef 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -358,6 +358,49 @@ impl Server { pub fn url(&self) -> String { format!("{}/demo", self.base) } + + /// Adds `rules` to `demo`'s `policy.toml`, landing them on `policy` as + /// the server's own user, who runs its node, through the repository's + /// path. + pub fn add_policy(&self, rules: &str) { + let operator = User::anonymous("operator"); + fs::write( + operator.config().join("config.toml"), + "user = \"operator\"\nnode = \"hosted\"\n", + ) + .unwrap(); + fs::copy( + self.dir().join("node.key"), + operator.config().join("node.key"), + ) + .unwrap(); + let path = self.dir().join("repos/demo"); + let policy = Repo::clone(&operator, path.to_str().unwrap(), &["--target", "policy"]); + let mut toml = policy.read("policy.toml"); + toml.push_str(rules); + policy.write("policy.toml", &toml); + policy.ok(&["describe", "Change the rules"]); + let landed = policy.ok(&["land"]); + assert!(landed.contains("Landed change"), "{landed}"); + } + + /// Signs a token for `principal` with `scope` with the server's key. + pub fn issue_token(&self, principal: &str, scope: &[&str]) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + command + .args(["token", "issue", "--as", principal, "--config"]) + .arg(self.dir().join("origin-server.toml")); + for capability in scope { + command.args(["--scope", capability]); + } + let output = command.output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap().trim().to_owned() + } } impl Drop for Server { diff --git a/apps/origin-src/tests/permissions.rs b/apps/origin-src/tests/permissions.rs new file mode 100644 index 00000000..61415531 --- /dev/null +++ b/apps/origin-src/tests/permissions.rs @@ -0,0 +1,309 @@ +//! End-to-end tests of permissions: what users see of a server's +//! repository, and what they may change, through the real binary. + +mod common; + +use std::fs; + +use common::{Repo, Server, User}; + +/// Everyone reads, alice writes everything and changes the rules, bob +/// writes `src` and `policy.toml`, but isn't admin, both land, and only +/// alice sees `secrets`. +const RULES: &str = r#" +[grants] +"user:alice" = ["admin", "land *"] +"user:bob" = ["land *"] + +[[paths]] +path = "/" +grants = { all = "read", "user:alice" = "write" } + +[[paths]] +path = "src" +grants = { "user:bob" = "write" } + +[[paths]] +path = "policy.toml" +grants = { "user:bob" = "write" } + +[[paths]] +path = "secrets" +grants = { all = "none", "user:alice" = "write" } +"#; + +/// A server with [`RULES`], and alice's clone, where she landed a README, +/// a library and a secret. +fn server() -> (Server, Repo) { + let server = Server::start(); + server.add_policy(RULES); + let alice = Repo::clone(&User::new("alice"), &server.url(), &[]); + alice.write("README.md", "hello\n"); + alice.write("src/lib.rs", "fn lib() {}\n"); + alice.write("secrets/key", "hunter2\n"); + alice.ok(&["describe", "First"]); + alice.ok(&["push"]); + alice.ok(&["land"]); + (server, alice) +} + +#[test] +fn users_see_and_change_only_what_they_may() { + let (server, alice) = server(); + assert_eq!(alice.ok(&["whoami"]), "user:alice\n"); + + // Bob gets everything but the secret, and the working copy is clean. + let bob = Repo::clone(&User::new("bob"), &server.url(), &[]); + assert_eq!(bob.read("src/lib.rs"), "fn lib() {}\n"); + assert!(!bob.path("secrets/key").exists()); + assert!(bob.ok(&["status"]).ends_with("No changes.\n")); + + // Bob may change `src`, and the secret survives his landing. + bob.write("src/lib.rs", "fn lib() { bob() }\n"); + bob.ok(&["describe", "Bob's"]); + bob.ok(&["push"]); + bob.ok(&["land"]); + alice.ok(&["pull"]); + assert_eq!(alice.read("src/lib.rs"), "fn lib() { bob() }\n"); + assert_eq!(alice.read("secrets/key"), "hunter2\n"); + + // Changes to files bob may not write fail before reaching the server. + bob.write("README.md", "bob was here\n"); + let error = bob.fails(&["push"]); + assert!(error.contains("you may not change `README.md`"), "{error}"); + + // Anonymous users read what everyone may, and change nothing. + let anonymous = Repo::clone(&User::anonymous("eve"), &server.url(), &[]); + assert_eq!(anonymous.read("README.md"), "hello\n"); + assert!(!anonymous.path("secrets").exists()); + assert!(anonymous.ok(&["whoami"]).starts_with("Anonymous")); + let permissions = anonymous.ok(&["permissions"]); + assert!( + permissions.contains("read /\nnone secrets\n"), + "{permissions}" + ); +} + +#[test] +fn readable_files_sharing_a_secret_files_content_are_kept() { + let (server, alice) = server(); + alice.write("public", "hunter2\n"); + alice.ok(&["push"]); + alice.ok(&["land"]); + + let bob = Repo::clone(&User::new("bob"), &server.url(), &[]); + assert_eq!(bob.read("public"), "hunter2\n"); + assert!(!bob.path("secrets/key").exists()); + assert!(bob.ok(&["status"]).ends_with("No changes.\n")); +} + +#[test] +fn granting_read_access_restores_withheld_files() { + let (server, _alice) = server(); + let bob = Repo::clone(&User::new("bob"), &server.url(), &[]); + assert!(!bob.path("secrets/key").exists()); + + // Bob can't change the rules: writing `policy.toml` isn't enough, only + // an admin lands on `policy`. + let rules = Repo::clone(&User::new("bob"), &server.url(), &["--target", "policy"]); + let mut policy = rules.read("policy.toml"); + policy.push_str("\n[[paths]]\npath = \"secrets/key\"\ngrants = { \"user:bob\" = \"read\" }\n"); + rules.write("policy.toml", &policy); + rules.ok(&["describe", "Let bob read the key"]); + rules.ok(&["push"]); + let error = rules.fails(&["land"]); + assert!(error.contains("you may not land on `policy`"), "{error}"); + + // Alice can. + let admin = Repo::clone(&User::new("alice"), &server.url(), &["--target", "policy"]); + admin.write("policy.toml", &policy); + admin.ok(&["describe", "Let bob read the key"]); + admin.ok(&["push"]); + admin.ok(&["land"]); + + bob.ok(&["fetch"]); + assert_eq!(bob.read("secrets/key"), "hunter2\n"); + assert!(bob.ok(&["status"]).ends_with("No changes.\n")); +} + +#[test] +fn agents_act_with_scoped_tokens() { + let (server, alice) = server(); + let output = alice.run( + alice.root(), + &[ + "token", + "issue", + "--scope", + "read README.md", + "--scope", + "write src", + ], + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let token = String::from_utf8(output.stdout).unwrap(); + + // The agent acts for alice, but only reads and writes what its token + // allows: it lands nothing. + let agent = Repo::clone( + &User::new("alice").with_token(token.trim()), + &server.url(), + &[], + ); + assert_eq!(agent.read("README.md"), "hello\n"); + assert!( + !agent.path("secrets").exists(), + "alice reads it, her token doesn't" + ); + let whoami = agent.ok(&["whoami"]); + assert_eq!( + whoami, + "user:alice\nToken scope: read README.md, write src\n" + ); + agent.write("src/lib.rs", "fn lib() { agent() }\n"); + agent.ok(&["describe", "The agent's work"]); + agent.ok(&["push"]); + let error = agent.fails(&["land"]); + assert!(error.contains("you may not land on `main`"), "{error}"); + agent.write("README.md", "agent was here\n"); + let error = agent.fails(&["push"]); + assert!(error.contains("you may not change `README.md`"), "{error}"); + let error = agent.fails(&["token", "issue", "--scope", "write /"]); + assert!(error.contains("which don't include `write /`"), "{error}"); + + // An operator signs tokens for identities of their own: they act with + // the rights the policy gives them. + let token = server.issue_token("user:agent-1", &["read /"]); + let other = Repo::clone( + &User::anonymous("agent-1").with_token(&token), + &server.url(), + &[], + ); + assert_eq!(other.read("README.md"), "hello\n"); + assert!(other.ok(&["whoami"]).starts_with("user:agent-1\n")); +} + +#[test] +fn users_with_other_rights_take_changes_over() { + let (server, alice) = server(); + // Alice changes the README and the library, and hands the change to + // bob, who writes the library alone. + alice.ok(&["new", "Shared work"]); + alice.write("README.md", "hello, bob\n"); + alice.write("src/lib.rs", "fn lib() { alice() }\n"); + alice.ok(&["push"]); + let change = alice.full_change(); + let bob = Repo::clone(&User::new("bob"), &server.url(), &[]); + bob.ok(&["fetch", "--change", &change]); + bob.ok(&["edit", &change]); + bob.write("src/lib.rs", "fn lib() { bob() }\n"); + bob.ok(&["push", &change]); + + // He can't give it up for her: she created it. + let error = bob.fails(&["abandon", "--reason", "Mine now"]); + assert!(error.contains("may not issue `core.abandon`"), "{error}"); + + // She lands it as he left it. + alice.ok(&["fetch"]); + alice.ok(&["land", &change]); + alice.ok(&["pull"]); + assert_eq!(alice.read("README.md"), "hello, bob\n"); + assert_eq!(alice.read("src/lib.rs"), "fn lib() { bob() }\n"); +} + +#[test] +fn users_sharing_a_repository_keep_their_own_rights() { + let (_server, alice) = server(); + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path().join("bob"); + alice.workspace(&workspace, &[]); + let bob = |args: &[&str]| User::new("bob").command(&workspace, args).output().unwrap(); + assert!(bob(&["fetch"]).status.success()); + + // Bob's rights, which his fetch saved, aren't alice's. + alice.write("README.md", "hello, alice\n"); + alice.ok(&["push"]); + fs::write(workspace.join("README.md"), "hello, bob\n").unwrap(); + let pushed = bob(&["push"]); + let error = String::from_utf8_lossy(&pushed.stderr); + assert!(error.contains("you may not change `README.md`"), "{error}"); +} + +#[test] +fn users_who_never_synced_push_with_their_own_rights() { + let server = Server::start(); + server.add_policy(RULES); + // Bob, who writes `src` alone, clones; alice, in a workspace of his + // clone, pushes a README before she ever fetches. + let bob = Repo::clone(&User::new("bob"), &server.url(), &[]); + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path().join("alice"); + let alice = User::new("alice"); + let path = workspace.to_str().unwrap(); + let made = alice + .command(bob.root(), &["workspace", "new", path]) + .output(); + assert!(made.unwrap().status.success()); + let alice = |args: &[&str]| alice.command(&workspace, args).output().unwrap(); + fs::write(workspace.join("README.md"), "hello\n").unwrap(); + assert!(alice(&["describe", "Readme"]).status.success()); + let pushed = alice(&["push"]); + assert!( + pushed.status.success(), + "{}", + String::from_utf8_lossy(&pushed.stderr) + ); + + // Her rights are kept as hers, and those of each scope of her tokens + // apart: a new token with the same scope keeps them. + let access = bob.path(".origin/access"); + let kept = || fs::read_dir(&access).unwrap().count(); + let fetch = |scope: &[&str]| { + let token = server.issue_token("user:alice", scope); + let rotated = User::new("alice").with_token(&token); + let fetched = rotated.command(&workspace, &["fetch"]).output().unwrap(); + assert!(fetched.status.success()); + kept() + }; + let before = kept(); + let scoped = fetch(&["read /", "write /"]); + assert_eq!(scoped, before + 1); + assert_eq!(fetch(&["write /", "read /"]), scoped); +} + +#[test] +fn tokens_of_one_user_keep_their_own_rights() { + let (server, alice) = server(); + let dir = tempfile::tempdir().unwrap(); + // An agent of alice's, whose token reads and writes `src` alone, + // fetches in a workspace of her clone. + let token = server.issue_token("user:alice", &["read src", "write src"]); + let agent = User::new("alice").with_token(&token); + let workspace = dir.path().join("agent"); + alice.workspace(&workspace, &[]); + let fetched = agent.command(&workspace, &["fetch"]).output().unwrap(); + assert!(fetched.status.success()); + + // Alice's rights are still hers: a new workspace of hers has every + // file, and her pushes are checked as she may write. + let own = dir.path().join("own"); + alice.workspace(&own, &[]); + assert_eq!( + fs::read_to_string(own.join("secrets/key")).unwrap(), + "hunter2\n" + ); + fs::write(own.join("README.md"), "hello, alice\n").unwrap(); + let pushed = User::new("alice") + .command(&own, &["push"]) + .output() + .unwrap(); + assert!( + pushed.status.success(), + "{}", + String::from_utf8_lossy(&pushed.stderr) + ); +}