use super::locus::{read_is_unshieldable, read_locus};
use crate::engine::facet::*;
pub(super) fn reads_path(path: &str, scale: Scale, because: &str) -> Capability {
let mut c = reads_content(read_locus(path), scale, because);
if unclearable_read(path, scale) {
claims_secret_read(&mut c);
}
c
}
pub(super) fn claims_secret_read(c: &mut Capability) {
c.secret.level = SecretLevel::Reads;
if c.operation == Operation::Observe {
c.reversibility = c.reversibility.max(Reversibility::Exposed);
}
}
pub(super) fn unclearable_read(path: &str, scale: Scale) -> bool {
unshieldable(path) || sweeps_unnameable(path, scale)
}
fn sweeps_unnameable(path: &str, scale: Scale) -> bool {
let sweeps = scale == Scale::Unbounded || names_many(path);
sweeps && read_locus(path) >= crate::engine::facet::LocalLocus::User
}
fn names_many(path: &str) -> bool {
path.contains(['*', '?', '['])
}
pub(super) fn observes_path(path: &str, scale: Scale, because: &str) -> Capability {
let mut c = observes(read_locus(path), scale, because);
if unclearable_read(path, scale) {
claims_secret_read(&mut c);
}
c
}
fn unshieldable(path: &str) -> bool {
read_is_unshieldable(path)
}
pub(super) fn reads_to_model(paths: &[&str], scale: Scale) -> Vec<Capability> {
if paths.is_empty() {
return vec![reads_content(LocalLocus::Process, scale, "reads stdin")];
}
paths
.iter()
.map(|p| {
if *p == "-" {
reads_content(LocalLocus::Process, scale, "reads stdin (-)")
} else {
reads_path(p, scale, "reads file content to the model")
}
})
.collect()
}
pub(super) fn reads_content(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
let mut c = Capability::new(Operation::Observe);
c.locus.local = locus;
c.scale = scale;
c.disclosure.audience = DisclosureAudience::LocalProcess; c.because = because.to_string();
c
}
pub(super) fn destroys(locus: LocalLocus, scale: Scale) -> Capability {
let reversibility =
if locus >= LocalLocus::User && scale == Scale::Unbounded { Reversibility::Irreversible } else { Reversibility::Effortful };
writes(
Operation::Destroy,
locus,
scale,
reversibility,
PersistenceLevel::Transient, "rm deletes files (recoverable only from out-of-band backups; irreversible when it mass-deletes home/system)",
)
}
fn writes(
op: Operation,
locus: LocalLocus,
scale: Scale,
reversibility: Reversibility,
persistence: PersistenceLevel,
because: &str,
) -> Capability {
let mut c = Capability::new(op);
c.locus.local = locus;
c.scale = scale;
c.reversibility = reversibility;
c.persistence.level = persistence;
c.because = because.to_string();
c
}
pub(super) fn creates(locus: LocalLocus, scale: Scale) -> Capability {
writes(Operation::Create, locus, scale, Reversibility::Trivial, PersistenceLevel::Data, "creates a file or directory")
}
pub(super) fn overwrites(locus: LocalLocus, scale: Scale, no_clobber: bool) -> Capability {
let reversibility = if no_clobber { Reversibility::Trivial } else { Reversibility::Recoverable };
writes(
Operation::Create,
locus,
scale,
reversibility,
PersistenceLevel::Data,
"writes the destination; may overwrite existing content unless --no-clobber",
)
}
pub(super) fn writes_export_file(locus: LocalLocus) -> Capability {
writes(
Operation::Create,
locus,
Scale::Single,
Reversibility::Recoverable,
PersistenceLevel::Data,
"writes the export/dump output file (may overwrite existing content)",
)
}
pub(super) fn mutates(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
writes(Operation::Mutate, locus, scale, Reversibility::Recoverable, PersistenceLevel::Data, because)
}
pub(super) fn relocates(locus: LocalLocus, scale: Scale) -> Capability {
writes(
Operation::Mutate,
locus,
scale,
Reversibility::Trivial,
PersistenceLevel::Transient,
"mv removes the source from its old location (trivially reversible: mv back)",
)
}
pub(super) fn executes(locus: LocalLocus, trust: ExecutionTrust, because: &str) -> Capability {
let mut c = Capability::new(Operation::Execute);
c.locus.local = locus;
c.execution.trust = trust;
c.because = because.to_string();
c
}
pub(super) fn worst(because: &str) -> Profile {
Profile::of(vec![Capability::worst(because)])
}
pub(super) fn breadth_scale(operands: &[&str], recursive: bool) -> Scale {
if recursive {
Scale::Unbounded
} else if operands.len() > 1 || operands.iter().any(|p| p.contains(['*', '?', '['])) {
Scale::Bounded
} else {
Scale::Single
}
}
pub(super) fn observes(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
let mut c = Capability::new(Operation::Observe);
c.locus.local = locus;
c.scale = scale;
c.because = because.to_string();
c
}
pub(super) struct Placing {
pub face: super::locus::Face,
pub on_link: bool,
pub dest_is_entry: bool,
}
pub(super) fn transfer_profile(
sources: &[&str],
dest: &str,
scale: Scale,
source: Placing,
dest_face: super::locus::Face,
per_source: impl Fn(LocalLocus, Scale) -> Capability,
per_dest: impl Fn(LocalLocus, Scale) -> Capability,
) -> Profile {
let at = super::locus::face;
let mut caps: Vec<Capability> = sources
.iter()
.map(|s| {
let judge = || {
let mut c = per_source(at(s, source.face), scale);
if unclearable_read(s, scale) {
claims_secret_read(&mut c);
}
c
};
if source.on_link { crate::pathctx::on_the_link(judge) } else { judge() }
})
.collect();
let landing = sources
.iter()
.filter(|_| !source.dest_is_entry)
.filter_map(|s| received_name(s))
.map(|name| at(&format!("{}/{name}", dest.trim_end_matches('/')), dest_face))
.fold(at(dest, dest_face), LocalLocus::max);
caps.push(per_dest(landing, scale));
Profile::of(caps)
}
fn received_name(source: &str) -> Option<String> {
const UNNAMED: &str = ".names-the-copy-brings";
let trimmed = source.trim_end_matches('/');
if source.ends_with('/') || trimmed.is_empty() || trimmed == "." || trimmed.ends_with("/.") {
return Some(UNNAMED.to_string());
}
let name = trimmed.rsplit('/').next()?;
(name != ".." && !super::locus::is_unpinnable(name)).then(|| name.to_string())
}
pub(super) fn with_operands(
tokens: &[crate::parse::Token],
resolve: impl FnOnce(&[crate::parse::Token]) -> Option<Profile>,
) -> Option<Profile> {
let _tokens = crate::cst::opaque::glob::enter_tokens(tokens.iter().map(|token| token.as_str().to_string()).collect());
let _unresolved = crate::cst::opaque::glob::enter_unresolved();
resolve(tokens).map(|mut profile| {
if crate::cst::opaque::glob::take_unresolved() {
profile
.capabilities
.push(mutates(LocalLocus::Machine, Scale::Unbounded, "behavior: an operand still names a glob"));
}
profile
})
}
#[cfg(test)]
mod secret_read_tests {
use super::*;
use crate::engine::authoring::default_levels;
use crate::engine::testgen::arb_capability;
use proptest::prelude::*;
fn admitted_by(cap: &Capability) -> Vec<bool> {
default_levels().iter().map(|l| l.admits(&Profile::of(vec![cap.clone()]))).collect()
}
proptest! {
#[test]
fn a_secret_read_is_exposed_and_nothing_else_moves(cap in arb_capability()) {
let mut marked = cap.clone();
claims_secret_read(&mut marked);
prop_assert_eq!(marked.secret.level, SecretLevel::Reads);
prop_assert_eq!(marked.reversibility >= Reversibility::Exposed, cap.operation == Operation::Observe || cap.reversibility >= Reversibility::Exposed);
prop_assert!(marked.reversibility >= cap.reversibility);
let mut rest = cap.clone();
rest.secret.level = marked.secret.level;
rest.reversibility = marked.reversibility;
prop_assert_eq!(rest, marked);
}
#[test]
fn marking_a_secret_read_exposed_changes_no_default_level(cap in arb_capability()) {
let mut before = cap.clone();
before.secret.level = SecretLevel::Reads;
let mut after = cap;
claims_secret_read(&mut after);
prop_assert_eq!(admitted_by(&before), admitted_by(&after));
}
#[test]
fn a_read_is_exposed_exactly_when_it_claims_a_secret(
root in proptest::sample::select(vec!["", "./", "../", "~/", "~/.ssh/", "~/.aws/", "/etc/", "/tmp/", "$X/", "/usr/lib/"]),
name in "[a-z_.*]{1,10}",
scale in proptest::sample::select(Scale::all().to_vec()),
) {
let home = tempfile::tempdir().expect("home");
let _home = crate::pathctx::enter_home(home.path().to_str().expect("utf-8").to_string());
let path = format!("{root}{name}");
for c in [reads_path(&path, scale, "probe"), observes_path(&path, scale, "probe")] {
prop_assert_eq!(c.secret.level == SecretLevel::Reads, c.reversibility == Reversibility::Exposed, "{}", path);
}
}
}
#[test]
fn a_credential_store_read_is_exposed() {
let c = reads_path("~/.ssh/id_rsa", Scale::Single, "probe");
assert_eq!(c.secret.level, SecretLevel::Reads);
assert_eq!(c.reversibility, Reversibility::Exposed);
let plain = reads_path("./src/main.rs", Scale::Single, "probe");
assert_eq!(plain.reversibility, Reversibility::None);
}
#[test]
fn a_threshold_at_effortful_refuses_a_secret_read_on_reversibility_alone() {
let levels = crate::engine::authoring::build_level_set(
"[level.old]\n[[level.old.allow]]\noperation = [\"observe\"]\nreversibility = \"<= effortful\"\n",
)
.expect("compiles");
let old = &levels[0];
let read = reads_path("~/.ssh/id_rsa", Scale::Single, "probe");
assert!(!old.admits(&Profile::of(vec![read])), "a ceiling at effortful must refuse a secret read");
let plain = reads_path("./notes", Scale::Single, "probe");
assert!(old.admits(&Profile::of(vec![plain])));
}
}