diff --git a/docs/reference/lore-server-config.md b/docs/reference/lore-server-config.md index 6cd05b844..00a88cda9 100644 --- a/docs/reference/lore-server-config.md +++ b/docs/reference/lore-server-config.md @@ -213,6 +213,7 @@ This field is optional. When it's absent, the server starts with the presigned U | `jwt_issuer` | none | Expected JWT `iss` claim. When set, tokens with a different issuer are rejected; when unset, issuer validation is skipped. | | `jwt_audience` | none | Array of accepted JWT `aud` values. A token's audience must match one entry; when unset, audience validation is skipped. | | `jwk` | none | The `[server.auth.jwk]` sub-table below. Its presence enables JWT verification. | +| `managed_repositories_file` | none | Path of a JSON policy naming managed repositories and their publishers (format in `lore-server/src/auth/managed.rs`). On a managed repository only an explicit `urc-` grant carrying `publish`, held by a listed publisher (`sub`), writes or performs elevated operations; every other grant reads only. Unset: nothing is managed. Set but missing or invalid: the server refuses to start; if it breaks later, every repository is treated as managed with no publishers until it is valid again. Changes are picked up within 5 s. | `[server.auth.jwk]`: diff --git a/lore-server/src/auth/jwt.rs b/lore-server/src/auth/jwt.rs index 6c810abec..6f094bfdc 100644 --- a/lore-server/src/auth/jwt.rs +++ b/lore-server/src/auth/jwt.rs @@ -19,6 +19,9 @@ use tracing::debug; use tracing::warn; use super::jwk::JWKServiceError; +use super::managed; +use super::managed::EffectiveGrants; +use super::managed::Snapshot; use crate::auth::jwk::JWKService; #[serde_as] @@ -53,25 +56,26 @@ impl ResourcePermission { self.resource_id == "urc-*" } - pub fn matches_repository(&self, repository_id: &String) -> bool { - self.resource_id == *repository_id || self.is_wildcard_resource() + pub fn matches_repository(&self, repository_id: &str) -> bool { + self.resource_id == repository_id || self.is_wildcard_resource() } /// Whether this grant allows reading repository content. Fail-closed: a grant must /// explicitly carry a permission that implies read; an empty permission list grants - /// nothing. `write`/`owner`/`admin` imply read. + /// nothing. `write`/`owner`/`admin`/`publish` imply read. pub fn allows_read(&self) -> bool { self.permission.iter().any(|permission| { matches!( permission.as_str(), - "read" | "write" | "owner" | "admin" | "obliterate" | "migrate" + "read" | "write" | "owner" | "admin" | "obliterate" | "migrate" | "publish" ) }) } /// Whether this grant allows mutating the repository (push, remote commit, locks, /// mutable-store writes). Fail-closed: requires `write`, `owner`, or `admin`; a grant - /// listing only `read` (or nothing) does not. + /// listing only `read` (or nothing) does not. On a managed repository only a publisher's + /// grant counts at all: see [`super::managed`]. pub fn allows_write(&self) -> bool { self.permission .iter() @@ -196,6 +200,19 @@ pub fn remaining_lifetime(authorization: &AuthorizationToken) -> Duration { Duration::from_secs(authorization.expires).saturating_sub(now) } +/// The caller's grants that count on `repository` under `policy`. +pub fn effective_grants<'a>( + authorization: &'a AuthorizationToken, + repository: lore_revision::lore::RepositoryId, + policy: &Snapshot, +) -> EffectiveGrants<'a> { + policy.effective_grants( + &authorization.user_id, + &format!("urc-{repository}"), + authorization.resources.as_deref().unwrap_or_default(), + ) +} + pub fn verify_authorization( authorization: &AuthorizationToken, repository: lore_revision::lore::RepositoryId, @@ -216,23 +233,25 @@ pub fn verify_authorization( /// Like [`verify_authorization`], but for mutating operations: the matching resource grant /// must include write (or an elevated grant implying it). A token scoped `read` on the -/// repository can therefore clone and sync but never push, lock, or store. +/// repository can therefore clone and sync but never push, lock, or store. On a managed +/// repository only a listed publisher's explicit `publish` grant writes. pub fn verify_write_authorization( authorization: &AuthorizationToken, repository: lore_revision::lore::RepositoryId, ) -> Result<(), JwtVerifierError> { - if let Some(resources) = authorization.resources.as_ref() { - let checked_repository = format!("urc-{repository}"); - for authorized_resource in resources.iter() { - if authorized_resource.matches_repository(&checked_repository) - && authorized_resource.allows_write() - { - return Ok(()); - } - } - } + verify_write_authorization_under(authorization, repository, &managed::current()) +} - Err(JwtVerifierError::NotAuthorized) +pub fn verify_write_authorization_under( + authorization: &AuthorizationToken, + repository: lore_revision::lore::RepositoryId, + policy: &Snapshot, +) -> Result<(), JwtVerifierError> { + if effective_grants(authorization, repository, policy).allows_write() { + Ok(()) + } else { + Err(JwtVerifierError::NotAuthorized) + } } #[cfg(test)] diff --git a/lore-server/src/auth/managed.rs b/lore-server/src/auth/managed.rs new file mode 100644 index 000000000..025a1351c --- /dev/null +++ b/lore-server/src/auth/managed.rs @@ -0,0 +1,503 @@ +// SPDX-FileCopyrightText: 2026 Epic Games, Inc. +// SPDX-License-Identifier: MIT +//! Managed repositories: repositories whose content only a listed publisher may change. +//! +//! A JSON policy file (`[server.auth] managed_repositories_file`) lists them: +//! +//! ```json +//! {"version": 1, +//! "managed": [{"resource_id": "urc-<32 lowercase hex>", "name": "pack", +//! "publishers": [""], "authors": [""]}]} +//! ``` +//! +//! On a managed repository, write is granted only by an explicit `urc-` grant carrying +//! `publish`, held by a subject listed in `publishers`; `write`, `owner` and `admin`, wildcard +//! or explicit, read only. Elevated permissions (`owner`, `admin`, `obliterate`, `migrate`) +//! count only from such a publisher grant. `authors` is validated here and used elsewhere. +//! +//! No file configured: nothing is managed. A configured file that is missing or invalid +//! fails closed: at startup the server refuses to start, after startup every repository is +//! treated as managed with no publishers until the file is valid again. The file is re-read +//! when its modification time or size changes, checked at most every [`RECHECK`]. + +use std::collections::HashMap; +use std::collections::HashSet; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::RwLock; +use std::time::Duration; +use std::time::Instant; +use std::time::SystemTime; + +use serde::Deserialize; +use thiserror::Error; +use tracing::error; +use tracing::info; + +use super::jwt::ResourcePermission; + +/// The only policy format this server reads. +const VERSION: u32 = 1; + +/// The only permission that grants write on a managed repository. +pub const PUBLISH: &str = "publish"; + +/// How long a loaded policy is trusted before the file is checked for a change. +pub const RECHECK: Duration = Duration::from_secs(5); + +#[derive(Debug, Error)] +pub enum PolicyError { + #[error("cannot read managed repositories policy {path}: {source}")] + Read { + path: PathBuf, + source: std::io::Error, + }, + #[error("invalid managed repositories policy: {0}")] + Invalid(String), +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyFile { + version: u32, + managed: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyEntry { + resource_id: String, + #[serde(default)] + #[allow(dead_code)] + name: Option, + publishers: Vec, + authors: Vec, +} + +/// A parsed, validated policy: managed resource id to its publishers. +#[derive(Debug, Default, PartialEq)] +pub struct ManagedPolicy { + publishers: HashMap>, +} + +impl ManagedPolicy { + pub fn parse(bytes: &[u8]) -> Result { + let file: PolicyFile = + serde_json::from_slice(bytes).map_err(|err| PolicyError::Invalid(err.to_string()))?; + if file.version != VERSION { + return Err(PolicyError::Invalid(format!( + "version {} is not {VERSION}", + file.version + ))); + } + let mut publishers = HashMap::new(); + for entry in file.managed { + if !is_canonical_resource_id(&entry.resource_id) { + return Err(PolicyError::Invalid(format!( + "resource_id {:?} is not urc- followed by 32 lowercase hex digits", + entry.resource_id + ))); + } + let listed = subjects(&entry.resource_id, "publishers", entry.publishers)?; + subjects(&entry.resource_id, "authors", entry.authors)?; + if publishers + .insert(entry.resource_id.clone(), listed) + .is_some() + { + return Err(PolicyError::Invalid(format!( + "resource_id {} is listed twice", + entry.resource_id + ))); + } + } + Ok(Self { publishers }) + } + + pub fn len(&self) -> usize { + self.publishers.len() + } + + pub fn is_empty(&self) -> bool { + self.publishers.is_empty() + } +} + +/// Subjects are non-empty visible-ASCII strings (0x21-0x7e), compared exactly (case-sensitive); +/// anything else, or a duplicate, makes the policy invalid. GRID's broker and GDAM apply the +/// same rule, so all three agree on which policies are valid. +fn subjects( + resource_id: &str, + field: &str, + listed: Vec, +) -> Result, PolicyError> { + let mut set = HashSet::with_capacity(listed.len()); + for subject in listed { + if subject.is_empty() || !subject.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) { + return Err(PolicyError::Invalid(format!( + "{resource_id}: {field} holds an empty or malformed subject" + ))); + } + if !set.insert(subject) { + return Err(PolicyError::Invalid(format!( + "{resource_id}: {field} lists a subject twice" + ))); + } + } + Ok(set) +} + +fn is_canonical_resource_id(resource_id: &str) -> bool { + resource_id.strip_prefix("urc-").is_some_and(|hex| { + hex.len() == 32 + && hex + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + && hex.bytes().any(|byte| byte != b'0') + }) +} + +/// The policy as an authorization check sees it. +#[derive(Clone, Debug, Default)] +pub enum Snapshot { + /// No policy configured: nothing is managed. + #[default] + Unconfigured, + Valid(Arc), + /// A configured policy that cannot be read or parsed: everything is managed and nobody + /// may publish. + Invalid, +} + +/// How `repository` (a `urc-` resource id) is governed. +pub enum Governance<'a> { + Unmanaged, + Managed { + publishers: Option<&'a HashSet>, + }, +} + +impl Snapshot { + pub fn governance(&self, repository: &str) -> Governance<'_> { + match self { + Snapshot::Unconfigured => Governance::Unmanaged, + Snapshot::Invalid => Governance::Managed { publishers: None }, + Snapshot::Valid(policy) => match policy.publishers.get(repository) { + None => Governance::Unmanaged, + Some(publishers) => Governance::Managed { + publishers: Some(publishers), + }, + }, + } + } + + /// The grants of `subject` that count on `repository`. On an unmanaged repository, every + /// grant naming it or `urc-*`. On a managed one, only an explicit grant carrying `publish` + /// held by a listed publisher; every other grant is reduced to read. + pub fn effective_grants<'g>( + &self, + subject: &str, + repository: &str, + grants: &'g [ResourcePermission], + ) -> EffectiveGrants<'g> { + let matching = grants + .iter() + .filter(|grant| grant.matches_repository(repository)); + match self.governance(repository) { + Governance::Unmanaged => EffectiveGrants { + full: matching.collect(), + read_only: Vec::new(), + managed: false, + }, + Governance::Managed { publishers } => { + let publisher = publishers.is_some_and(|publishers| publishers.contains(subject)); + let (full, read_only) = matching.partition(|grant| { + publisher + && !grant.is_wildcard_resource() + && grant + .permission + .iter() + .any(|permission| permission == PUBLISH) + }); + EffectiveGrants { + full, + read_only, + managed: true, + } + } + } + } +} + +/// The grants that apply to one repository, split by how far they count. +pub struct EffectiveGrants<'g> { + /// Grants whose every permission counts. + pub full: Vec<&'g ResourcePermission>, + /// Grants that count only for read on a managed repository. + pub read_only: Vec<&'g ResourcePermission>, + /// On a managed repository every grant in `full` is a publisher's `publish` grant, which is + /// what writes there; elsewhere `write`, `owner` or `admin` writes. + managed: bool, +} + +impl EffectiveGrants<'_> { + pub fn allows_read(&self) -> bool { + self.full + .iter() + .chain(self.read_only.iter()) + .any(|grant| grant.allows_read()) + } + + pub fn allows_write(&self) -> bool { + if self.managed { + !self.full.is_empty() + } else { + self.full.iter().any(|grant| grant.allows_write()) + } + } + + pub fn has_permission(&self, wanted: &str) -> bool { + self.full.iter().any(|grant| { + grant + .permission + .iter() + .any(|permission| permission == wanted) + }) + } +} + +struct Holder { + path: Option, + snapshot: Snapshot, + stamp: Option<(SystemTime, u64)>, + checked: Instant, +} + +static POLICY: RwLock> = RwLock::new(None); + +fn stamp(path: &Path) -> std::io::Result<(SystemTime, u64)> { + let metadata = std::fs::metadata(path)?; + Ok((metadata.modified()?, metadata.len())) +} + +fn load(path: &Path) -> Result<(ManagedPolicy, (SystemTime, u64)), PolicyError> { + let read = |source| PolicyError::Read { + path: path.to_path_buf(), + source, + }; + let stamp = stamp(path).map_err(read)?; + let bytes = std::fs::read(path).map_err(read)?; + Ok((ManagedPolicy::parse(&bytes)?, stamp)) +} + +/// Load the configured policy at startup. An error must stop the server. +pub fn configure(path: Option<&Path>) -> Result<(), PolicyError> { + let holder = match path { + None => Holder { + path: None, + snapshot: Snapshot::Unconfigured, + stamp: None, + checked: Instant::now(), + }, + Some(path) => { + let (policy, stamp) = load(path)?; + info!( + path = %path.display(), + managed = policy.len(), + "Loaded managed repositories policy" + ); + Holder { + path: Some(path.to_path_buf()), + snapshot: Snapshot::Valid(Arc::new(policy)), + stamp: Some(stamp), + checked: Instant::now(), + } + } + }; + *POLICY + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(holder); + Ok(()) +} + +/// The policy in force, re-read first when the file may have changed. +pub fn current() -> Snapshot { + { + let guard = POLICY + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + match guard.as_ref() { + None => return Snapshot::Unconfigured, + Some(holder) if holder.path.is_none() || holder.checked.elapsed() < RECHECK => { + return holder.snapshot.clone(); + } + Some(_) => {} + } + } + let mut guard = POLICY + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(holder) = guard.as_mut() else { + return Snapshot::Unconfigured; + }; + let Some(path) = holder.path.clone() else { + return holder.snapshot.clone(); + }; + if holder.checked.elapsed() >= RECHECK { + holder.checked = Instant::now(); + let unchanged = + matches!(holder.snapshot, Snapshot::Valid(_)) && stamp(&path).ok() == holder.stamp; + if !unchanged { + match load(&path) { + Ok((policy, stamp)) => { + info!( + path = %path.display(), + managed = policy.len(), + "Reloaded managed repositories policy" + ); + holder.snapshot = Snapshot::Valid(Arc::new(policy)); + holder.stamp = Some(stamp); + } + Err(err) => { + if !matches!(holder.snapshot, Snapshot::Invalid) { + error!( + error = %err, + "Managed repositories policy is unusable: every repository is \ + treated as managed with no publishers until it is fixed" + ); + } + holder.snapshot = Snapshot::Invalid; + holder.stamp = None; + } + } + } + } + holder.snapshot.clone() +} + +#[cfg(test)] +mod tests { + use super::*; + + const PACK: &str = "urc-0123456789abcdef0123456789abcdef"; + const OTHER: &str = "urc-fedcba9876543210fedcba9876543210"; + + fn grant(resource_id: &str, permission: &[&str]) -> ResourcePermission { + ResourcePermission { + resource_id: resource_id.to_string(), + permission: permission.iter().map(|p| (*p).to_string()).collect(), + } + } + + fn policy(json: &str) -> Result { + ManagedPolicy::parse(json.as_bytes()) + } + + fn pack_policy() -> Snapshot { + Snapshot::Valid(Arc::new( + policy(&format!( + r#"{{"version":1,"managed":[{{"resource_id":"{PACK}","name":"pack", + "publishers":["gdam-publisher"],"authors":["alice"]}}]}}"# + )) + .expect("valid policy"), + )) + } + + #[test] + fn parse_accepts_empty_and_rejects_malformed_policies() { + assert!( + policy(r#"{"version":1,"managed":[]}"#) + .expect("empty") + .is_empty() + ); + let entry = |id: &str, publishers: &str| { + format!( + r#"{{"version":1,"managed":[{{"resource_id":"{id}","publishers":{publishers},"authors":[]}}]}}"# + ) + }; + assert!(policy(&entry(PACK, r#"["svc"]"#)).is_ok()); + for bad in [ + String::new(), + "{}".to_string(), + r#"{"version":2,"managed":[]}"#.to_string(), + r#"{"version":1,"managed":[],"extra":1}"#.to_string(), + entry(&PACK.to_uppercase().replace("URC-", "urc-"), r#"["svc"]"#), + entry("urc-*", r#"["svc"]"#), + entry("urc-0123", r#"["svc"]"#), + entry("urc-00000000000000000000000000000000", r#"["svc"]"#), + entry(PACK, r#"[""]"#), + entry(PACK, r#"[" svc"]"#), + entry(PACK, r#"["svc","svc"]"#), + format!( + r#"{{"version":1,"managed":[{{"resource_id":"{PACK}","publishers":[],"authors":[]}}, + {{"resource_id":"{PACK}","publishers":[],"authors":[]}}]}}"# + ), + format!( + r#"{{"version":1,"managed":[{{"resource_id":"{PACK}","publishers":[],"authors":[""]}}]}}"# + ), + ] { + assert!(policy(&bad).is_err(), "{bad} must be rejected"); + } + } + + #[test] + fn only_a_listed_publishers_explicit_publish_grant_counts_on_a_managed_repository() { + let snapshot = pack_policy(); + let check = |subject: &str, grants: &[ResourcePermission]| { + let effective = snapshot.effective_grants(subject, PACK, grants); + ( + effective.allows_read(), + effective.allows_write(), + effective.has_permission("admin"), + ) + }; + assert_eq!( + check("gdam-publisher", &[grant(PACK, &["publish", "admin"])]), + (true, true, true) + ); + // `publish` alone is what writes a managed repository. + assert_eq!( + check("gdam-publisher", &[grant(PACK, &["read", "publish"])]), + (true, true, false) + ); + // Case-sensitive subjects, no wildcard publish, no unlisted publisher. + assert_eq!( + check("GDAM-publisher", &[grant(PACK, &["publish"])]), + (true, false, false) + ); + assert_eq!( + check("gdam-publisher", &[grant("urc-*", &["publish"])]), + (true, false, false) + ); + assert_eq!( + check("alice", &[grant(PACK, &["publish"])]), + (true, false, false) + ); + // Ordinary and elevated grants read only, wildcard or explicit, even for a publisher. + for permissions in [ + &["read", "write"][..], + &["owner", "admin", "obliterate", "migrate"], + ] { + for resource in [PACK, "urc-*"] { + for subject in ["gdam-publisher", "alice"] { + let (read, write, admin) = check(subject, &[grant(resource, permissions)]); + assert!(!write && !admin, "{subject} {resource} {permissions:?}"); + assert!(read, "{subject} {resource} {permissions:?}"); + } + } + } + // Unmanaged repositories keep today's behaviour. + let wildcard_writer = [grant("urc-*", &["write"])]; + let effective = snapshot.effective_grants("alice", OTHER, &wildcard_writer); + assert!(effective.allows_write()); + } + + #[test] + fn an_invalid_policy_manages_everything_and_lets_nobody_publish() { + let grants = [grant(OTHER, &["publish", "write", "admin"])]; + let effective = Snapshot::Invalid.effective_grants("gdam-publisher", OTHER, &grants); + assert!(effective.allows_read()); + assert!(!effective.allows_write()); + assert!(!effective.has_permission("admin")); + } +} diff --git a/lore-server/src/auth/mod.rs b/lore-server/src/auth/mod.rs index 159b694a4..8b6bf2d25 100644 --- a/lore-server/src/auth/mod.rs +++ b/lore-server/src/auth/mod.rs @@ -4,6 +4,7 @@ pub mod jwk; pub mod jwt; pub mod jwt_axum_middleware; pub mod jwt_interceptor; +pub mod managed; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; diff --git a/lore-server/src/authnz/grants.rs b/lore-server/src/authnz/grants.rs index 36bc883fe..c99b8dfa6 100644 --- a/lore-server/src/authnz/grants.rs +++ b/lore-server/src/authnz/grants.rs @@ -16,6 +16,10 @@ use crate::auth::Access; use crate::auth::jwt::AuthorizationToken; use crate::auth::jwt::verify_authorization; use crate::auth::jwt::verify_write_authorization; +use crate::auth::jwt::verify_write_authorization_under; +use crate::auth::managed; +use crate::auth::managed::Governance; +use crate::auth::managed::Snapshot; const WILDCARD: &str = "urc-*"; @@ -124,17 +128,32 @@ pub fn token_scope(token: Option<&AuthorizationToken>) -> ListScope { scope } -/// Whether the caller may create repositories. Names are global, so a create reveals whether a +/// Whether the caller may create `repository`. Names are global, so a create reveals whether a /// name is taken anywhere on the origin: only a token holding a writable `urc-*`, whose holder -/// may see every repository anyway, may ask. -pub fn may_create(token: Option<&AuthorizationToken>) -> bool { - token - .and_then(|token| token.resources.as_ref()) - .is_some_and(|resources| { +/// may see every repository anyway, may ask. A managed repository is created only by one of +/// its listed publishers, through an explicit `publish` grant on its id. +pub fn may_create(token: Option<&AuthorizationToken>, repository: RepositoryId) -> bool { + may_create_under(token, repository, &managed::current()) +} + +fn may_create_under( + token: Option<&AuthorizationToken>, + repository: RepositoryId, + policy: &Snapshot, +) -> bool { + let Some(token) = token else { + return false; + }; + match policy.governance(&resource_id(repository)) { + Governance::Unmanaged => token.resources.as_ref().is_some_and(|resources| { resources .iter() .any(|grant| grant.is_wildcard_resource() && grant.allows_write()) - }) + }), + Governance::Managed { .. } => { + verify_write_authorization_under(token, repository, policy).is_ok() + } + } } /// `urc-` followed by exactly 32 hex digits naming a non-zero repository. @@ -146,6 +165,7 @@ fn parse_resource_id(resource_id: &str) -> Option { #[cfg(test)] mod tests { use super::*; + use crate::auth::managed::ManagedPolicy; fn grant(resource_id: &str, permission: &[&str]) -> ResourcePermission { ResourcePermission { @@ -269,7 +289,7 @@ mod tests { "{absent:?}" ); assert!(token_scope(absent).is_empty(), "{absent:?}"); - assert!(!may_create(absent), "{absent:?}"); + assert!(!may_create(absent, repository), "{absent:?}"); } } @@ -315,20 +335,79 @@ mod tests { #[test] fn only_a_writable_wildcard_may_create() { - let scoped = resource_id(rand::random()); - assert!(may_create(Some(&token(Some(vec![( - WILDCARD, - &["read", "write"][..] - )]))))); + let repository = rand::random(); + let scoped = resource_id(repository); + assert!(may_create( + Some(&token(Some(vec![(WILDCARD, &["read", "write"][..])]))), + repository + )); for resources in [ vec![(WILDCARD, &["read"][..])], vec![(scoped.as_str(), &["read", "write"][..])], vec![(WILDCARD, &[][..]), (scoped.as_str(), &["write"][..])], ] { assert!( - !may_create(Some(&token(Some(resources.clone())))), + !may_create(Some(&token(Some(resources.clone()))), repository), "{resources:?}" ); } } + + #[test] + fn only_a_listed_publisher_may_create_or_write_a_managed_repository() { + let repository: RepositoryId = rand::random(); + let unmanaged: RepositoryId = rand::random(); + let id = resource_id(repository); + let policy = Snapshot::Valid(std::sync::Arc::new( + ManagedPolicy::parse( + format!( + r#"{{"version":1,"managed":[{{"resource_id":"{id}", + "publishers":["publisher"],"authors":[]}}]}}"# + ) + .as_bytes(), + ) + .expect("valid policy"), + )); + let as_subject = |subject: &str, resources: Vec<(&str, &[&str])>| AuthorizationToken { + user_id: subject.to_string(), + ..token(Some(resources)) + }; + let writes = |token: &AuthorizationToken, repository| { + verify_write_authorization_under(token, repository, &policy).is_ok() + }; + + let publisher = as_subject("publisher", vec![(id.as_str(), &["publish"][..])]); + assert!(may_create_under(Some(&publisher), repository, &policy)); + assert!(writes(&publisher, repository)); + assert!(verify_authorization(&publisher, repository).is_ok()); + assert!( + !writes(&publisher, unmanaged), + "publish writes only managed repositories" + ); + + let staff = as_subject( + "publisher", + vec![(WILDCARD, &["read", "write", "admin"][..])], + ); + assert!(!may_create_under(Some(&staff), repository, &policy)); + assert!(!writes(&staff, repository)); + assert!(verify_authorization(&staff, repository).is_ok()); + assert!(may_create_under(Some(&staff), unmanaged, &policy)); + assert!(writes(&staff, unmanaged)); + + for refused in [ + as_subject( + "publisher", + vec![(id.as_str(), &["read", "write", "owner"][..])], + ), + as_subject("publisher", vec![(WILDCARD, &["publish"][..])]), + as_subject("someone-else", vec![(id.as_str(), &["publish"][..])]), + ] { + assert!( + !may_create_under(Some(&refused), repository, &policy), + "{refused:?}" + ); + assert!(!writes(&refused, repository), "{refused:?}"); + } + } } diff --git a/lore-server/src/grpc/mod.rs b/lore-server/src/grpc/mod.rs index 5da1b7f03..bba869450 100644 --- a/lore-server/src/grpc/mod.rs +++ b/lore-server/src/grpc/mod.rs @@ -55,12 +55,14 @@ use tracing::warn; use crate::auth::Access; use crate::auth::jwt::AuthorizationToken; use crate::auth::jwt::ResourcePermission; +use crate::auth::jwt::effective_grants; use crate::auth::jwt::verify_authorization; +use crate::auth::managed; +use crate::auth::managed::Governance; use crate::hooks::traits::HookError; use crate::hooks::traits::StatusCode; use crate::protocol::storage::messages::MessageHandleError; use crate::util::get_user_id_from_token_ref; -use crate::util::resources_from_token; /// Matches the Infrastructure alerting rule regex /// for what counts as an internal status code error @@ -389,16 +391,20 @@ pub fn can_admin_lock(extensions: &Extensions, repository: RepositoryId) -> bool has_required_permission(extensions, repository, "migrate") } +/// The caller's grants that apply to `repository` (exact or `urc-*`) and count in full under +/// the managed repositories policy: on a managed repository, only a listed publisher's +/// explicit `publish` grant. pub fn get_matching_permissions( extensions: &Extensions, repository: RepositoryId, ) -> Vec { - let user_resources = resources_from_token(get_authorization(extensions).ok()); - let repository_to_match = format!("urc-{repository}"); - - user_resources + let Some(token) = extensions.get::() else { + return Vec::new(); + }; + effective_grants(token, repository, &managed::current()) + .full .into_iter() - .filter(|resource| resource.matches_repository(&repository_to_match)) + .cloned() .collect() } @@ -416,9 +422,19 @@ pub fn has_required_permission( }) } +/// The permissions of the caller's explicit grant on `repository`, if that grant counts in +/// full under the managed repositories policy. pub fn user_permissions(extensions: &Extensions, repository: RepositoryId) -> Vec { - let user_resources = resources_from_token(get_authorization(extensions).ok()); - for resource in user_resources { + let Some(token) = extensions.get::() else { + return Vec::new(); + }; + // Only a managed repository narrows which explicit grant counts. + let policy = managed::current(); + let counted = match policy.governance(&format!("urc-{repository}")) { + Governance::Unmanaged => None, + Governance::Managed { .. } => Some(effective_grants(token, repository, &policy).full), + }; + for resource in token.resources.iter().flatten() { let resource_repository = resource .resource_id .strip_prefix("urc-") @@ -427,7 +443,14 @@ pub fn user_permissions(extensions: &Extensions, repository: RepositoryId) -> Ve .unwrap_or_default() .into(); if resource_repository == repository { - return resource.permission; + return if counted + .as_ref() + .is_none_or(|counted| counted.iter().any(|grant| std::ptr::eq(*grant, resource))) + { + resource.permission.clone() + } else { + Vec::new() + }; } } diff --git a/lore-server/src/grpc/repository/v1/repository_create.rs b/lore-server/src/grpc/repository/v1/repository_create.rs index 06eae4b50..47bc363f4 100644 --- a/lore-server/src/grpc/repository/v1/repository_create.rs +++ b/lore-server/src/grpc/repository/v1/repository_create.rs @@ -137,9 +137,10 @@ pub async fn handler( .await } -/// Creating needs a writable `urc-*` in the caller's own token, and then a write grant on the -/// new id from the broker. Repository names are global, so a collision would tell a scoped -/// caller that a name it cannot see is taken: every scoped caller is refused alike. Both are +/// Creating needs a writable `urc-*` in the caller's own token (for a managed id, a listed +/// publisher's explicit `publish` grant on it instead), and then a write grant on the new id +/// from the broker. Repository names are global, so a collision would tell a scoped caller +/// that a name it cannot see is taken: every other scoped caller is refused alike. Both are /// checked before any hook, lookup or collision check, so a refused caller learns nothing about /// existing names or ids, and a retry only returns an existing record to a caller that may /// write it. @@ -149,7 +150,7 @@ async fn authorize_create( token: Option<&AuthorizationToken>, id: RepositoryId, ) -> Result<(), Status> { - if may_create(token) + if may_create(token, id) && check_repository_access(auth_url, authorization, token, id, Access::Write).await? { Ok(()) diff --git a/lore-server/src/server.rs b/lore-server/src/server.rs index 6462c1103..5198d1a65 100644 --- a/lore-server/src/server.rs +++ b/lore-server/src/server.rs @@ -1854,6 +1854,8 @@ async fn async_main(settings: (Settings, StringHash), config: ServerConfig) -> R jwk_service .fetch_new_keys(None /* fetch all keys */) .await?; + crate::auth::managed::configure(auth.managed_repositories_file.as_deref()) + .map_err(|err| anyhow!("{err}: refusing to start"))?; Some(JwtVerifier { jwk_service: Arc::new(jwk_service), jwt_issuer: auth.jwt_issuer.clone(), diff --git a/lore-server/src/settings.rs b/lore-server/src/settings.rs index aebba0714..9184e9fcb 100644 --- a/lore-server/src/settings.rs +++ b/lore-server/src/settings.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: MIT use std::collections::HashMap; use std::env; +use std::path::PathBuf; use config::Config; use lore_base::runtime::TokioSettings; @@ -224,6 +225,10 @@ pub struct AuthSettings { pub jwk: Option, pub jwt_audience: Option>, pub jwt_issuer: Option, + /// JSON policy naming the managed repositories and their publishers; see + /// [`crate::auth::managed`]. Absent: nothing is managed. Set but unreadable or invalid: + /// the server refuses to start. + pub managed_repositories_file: Option, } #[derive(Clone, Debug, Deserialize)] diff --git a/lore-server/src/util/mod.rs b/lore-server/src/util/mod.rs index 98c8d0e58..1a4dc1026 100644 --- a/lore-server/src/util/mod.rs +++ b/lore-server/src/util/mod.rs @@ -5,7 +5,6 @@ pub mod cert_metrics; use lore_revision::interface::LoreGlobalArgs; use crate::auth::jwt::AuthorizationToken; -use crate::auth::jwt::ResourcePermission; #[cfg(test)] pub fn address_with_random_context(address: lore_storage::Address) -> lore_storage::Address { @@ -59,16 +58,6 @@ pub fn get_user_id_from_token(token: Option) -> String { get_user_id_from_token_ref(token.as_ref()) } -pub fn resources_from_token(token: Option) -> Vec { - if let Some(token) = token - && let Some(resources) = token.resources - { - return resources; - } - - Vec::new() -} - #[cfg(test)] mod tests { use super::*;