use super::{
PermissionedProcessRunnerFactory, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
ProcessRunnerError, ProcessRunnerFuture,
};
use crate::{HostIntegration, PathAccess, PathAccessRule, PermissionRequest, RequestedCapability};
use merry_core::ApprovalScope;
use std::{
fmt,
path::PathBuf,
sync::{Arc, RwLock},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SessionGrantId(u64);
impl SessionGrantId {
#[must_use]
pub const fn as_u64(self) -> u64 {
self.0
}
#[must_use]
pub const fn from_u64(value: u64) -> Self {
Self(value)
}
}
impl fmt::Display for SessionGrantId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "grant-{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionPermissionGrantKind {
Path {
path: PathBuf,
access: PathAccess,
},
Network,
NetworkDomain(String),
HostIntegration(HostIntegration),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionPermissionGrant {
id: SessionGrantId,
kind: SessionPermissionGrantKind,
}
impl SessionPermissionGrant {
#[must_use]
pub const fn new(id: SessionGrantId, kind: SessionPermissionGrantKind) -> Self {
Self { id, kind }
}
#[must_use]
pub const fn id(&self) -> SessionGrantId {
self.id
}
#[must_use]
pub const fn kind(&self) -> &SessionPermissionGrantKind {
&self.kind
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessPathGrantConstraint {
Ordinary,
ProtectedMetadata,
}
#[derive(Debug, Clone)]
pub struct ProcessPathGrant {
rule: PathAccessRule,
constraint: ProcessPathGrantConstraint,
}
pub struct PreparedProcessPermission {
runner: Arc<dyn ProcessRunner>,
grants: Vec<ProcessPathGrant>,
}
impl PreparedProcessPermission {
#[must_use]
pub fn new(runner: Arc<dyn ProcessRunner>, grants: Vec<ProcessPathGrant>) -> Self {
Self { runner, grants }
}
}
impl ProcessPathGrant {
#[must_use]
pub fn new(rule: PathAccessRule, constraint: ProcessPathGrantConstraint) -> Self {
Self { rule, constraint }
}
}
#[derive(Debug, Clone, Default)]
pub struct ProcessSessionPermissionSnapshot {
path_rules: Vec<PathAccessRule>,
host_integrations: Vec<HostIntegration>,
network_allowed: bool,
allowed_domains: Vec<String>,
grants: Vec<SessionPermissionGrant>,
}
impl ProcessSessionPermissionSnapshot {
#[must_use]
pub fn path_rules(&self) -> &[PathAccessRule] {
&self.path_rules
}
#[must_use]
pub fn host_integrations(&self) -> &[HostIntegration] {
&self.host_integrations
}
#[must_use]
pub const fn network_allowed(&self) -> bool {
self.network_allowed
}
#[must_use]
pub fn allowed_domains(&self) -> &[String] {
&self.allowed_domains
}
#[must_use]
pub fn allows_domain(&self, host: &str) -> bool {
let Some(normalized) = crate::normalize_network_domain(host) else {
return false;
};
self.allowed_domains
.iter()
.any(|domain| domain == &normalized)
}
#[must_use]
pub fn grants(&self) -> &[SessionPermissionGrant] {
&self.grants
}
}
#[derive(Debug, Clone)]
struct ProcessSessionPermissionState {
next_id: u64,
path_grants: Vec<(SessionGrantId, PathAccessRule)>,
host_integrations: Vec<(SessionGrantId, HostIntegration)>,
network_grant_id: Option<SessionGrantId>,
domain_grants: Vec<(SessionGrantId, String)>,
}
impl Default for ProcessSessionPermissionState {
fn default() -> Self {
Self {
next_id: 1,
path_grants: Vec::new(),
host_integrations: Vec::new(),
network_grant_id: None,
domain_grants: Vec::new(),
}
}
}
impl ProcessSessionPermissionState {
fn allocate_id(&mut self) -> SessionGrantId {
let id = SessionGrantId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
id
}
fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
let mut state = Self::default();
if snapshot.network_allowed {
state.network_grant_id = Some(state.allocate_id());
}
state.retain_domains(snapshot.allowed_domains);
let mut integrations = snapshot.host_integrations;
integrations.sort_unstable();
integrations.dedup();
for integration in integrations {
let id = state.allocate_id();
state.host_integrations.push((id, integration));
}
for rule in snapshot.path_rules {
let id = state.allocate_id();
state.path_grants.push((id, rule));
}
normalize_grant_entries(&mut state.path_grants);
state
}
fn snapshot(&self) -> ProcessSessionPermissionSnapshot {
let path_rules = self
.path_grants
.iter()
.map(|(_, rule)| rule.clone())
.collect();
let host_integrations = self
.host_integrations
.iter()
.map(|(_, integration)| *integration)
.collect();
let network_allowed = self.network_grant_id.is_some();
let allowed_domains = self
.domain_grants
.iter()
.map(|(_, domain)| domain.clone())
.collect();
let grants = self.ordered_grants();
ProcessSessionPermissionSnapshot {
path_rules,
host_integrations,
network_allowed,
allowed_domains,
grants,
}
}
fn ordered_grants(&self) -> Vec<SessionPermissionGrant> {
let mut grants = Vec::with_capacity(
usize::from(self.network_grant_id.is_some())
+ self.domain_grants.len()
+ self.host_integrations.len()
+ self.path_grants.len(),
);
if let Some(id) = self.network_grant_id {
grants.push(SessionPermissionGrant::new(
id,
SessionPermissionGrantKind::Network,
));
}
for (id, domain) in &self.domain_grants {
grants.push(SessionPermissionGrant::new(
*id,
SessionPermissionGrantKind::NetworkDomain(domain.clone()),
));
}
for &(id, integration) in &self.host_integrations {
grants.push(SessionPermissionGrant::new(
id,
SessionPermissionGrantKind::HostIntegration(integration),
));
}
for (id, rule) in &self.path_grants {
grants.push(SessionPermissionGrant::new(
*id,
SessionPermissionGrantKind::Path {
path: rule.path().to_path_buf(),
access: rule.access(),
},
));
}
grants
}
fn retain_path_rules(&mut self, incoming: impl IntoIterator<Item = PathAccessRule>) {
for rule in incoming {
if self.path_grants.iter().any(|(_, existing)| {
rule.path().starts_with(existing.path()) && existing.access().covers(rule.access())
}) {
continue;
}
let id = self.allocate_id();
self.path_grants.push((id, rule));
}
normalize_grant_entries(&mut self.path_grants);
}
fn retain_host_integration(&mut self, integration: HostIntegration) {
if self
.host_integrations
.iter()
.any(|(_, existing)| *existing == integration)
{
return;
}
let id = self.allocate_id();
self.host_integrations.push((id, integration));
self.host_integrations
.sort_unstable_by_key(|(_, item)| *item);
}
fn retain_network(&mut self) {
if self.network_grant_id.is_none() {
self.network_grant_id = Some(self.allocate_id());
}
}
fn retain_domains(&mut self, incoming: impl IntoIterator<Item = String>) {
for domain in incoming {
let Some(normalized) = crate::normalize_network_domain(&domain) else {
continue;
};
if self
.domain_grants
.iter()
.any(|(_, existing)| existing == &normalized)
{
continue;
}
let id = self.allocate_id();
self.domain_grants.push((id, normalized));
}
self.domain_grants
.sort_by(|(_, left), (_, right)| left.cmp(right));
}
fn revoke(&mut self, id: SessionGrantId) -> bool {
if self.network_grant_id == Some(id) {
self.network_grant_id = None;
return true;
}
if let Some(index) = self
.domain_grants
.iter()
.position(|(entry_id, _)| *entry_id == id)
{
self.domain_grants.remove(index);
return true;
}
if let Some(index) = self
.host_integrations
.iter()
.position(|(entry_id, _)| *entry_id == id)
{
self.host_integrations.remove(index);
return true;
}
if let Some(index) = self
.path_grants
.iter()
.position(|(entry_id, _)| *entry_id == id)
{
self.path_grants.remove(index);
return true;
}
false
}
fn clear(&mut self) {
self.path_grants.clear();
self.host_integrations.clear();
self.network_grant_id = None;
self.domain_grants.clear();
}
}
#[derive(Debug, Clone)]
pub struct ProcessSessionPermissionView {
state: Arc<RwLock<ProcessSessionPermissionState>>,
}
impl ProcessSessionPermissionView {
pub fn snapshot(&self) -> Result<ProcessSessionPermissionSnapshot, ProcessRunnerError> {
self.state
.read()
.map(|state| state.snapshot())
.map_err(|_| {
ProcessRunnerError::infrastructure(
"runtime session permission state lock was poisoned",
)
})
}
}
#[derive(Debug, Clone, Default)]
pub struct ProcessSessionPermissions {
state: Arc<RwLock<ProcessSessionPermissionState>>,
}
impl ProcessSessionPermissions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
Self {
state: Arc::new(RwLock::new(ProcessSessionPermissionState::from_snapshot(
snapshot,
))),
}
}
pub fn from_inherited_view(
view: &ProcessSessionPermissionView,
) -> Result<Self, ProcessRunnerError> {
Ok(Self::from_snapshot(view.snapshot()?))
}
#[must_use]
pub fn view(&self) -> ProcessSessionPermissionView {
ProcessSessionPermissionView {
state: Arc::clone(&self.state),
}
}
pub fn grants(&self) -> Result<Vec<SessionPermissionGrant>, ProcessRunnerError> {
self.state
.read()
.map(|state| state.ordered_grants())
.map_err(|_| {
ProcessRunnerError::infrastructure(
"runtime session permission state lock was poisoned",
)
})
}
pub fn revoke(&self, id: SessionGrantId) -> Result<bool, ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
Ok(state.revoke(id))
}
#[must_use]
pub fn with_factory<Factory: PermissionedProcessRunnerFactory>(
self,
backend: Factory,
) -> SessionPermissionedProcessRunnerFactory<Factory> {
SessionPermissionedProcessRunnerFactory {
permissions: self,
backend,
}
}
pub fn clear(&self) -> Result<(), ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
state.clear();
Ok(())
}
pub fn revoke_denied_capabilities(
&self,
network_denied: bool,
denied_host_integrations: &[HostIntegration],
) -> Result<(), ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
if network_denied {
state.network_grant_id = None;
state.domain_grants.clear();
}
if !denied_host_integrations.is_empty() {
state
.host_integrations
.retain(|(_, integration)| !denied_host_integrations.contains(integration));
}
Ok(())
}
pub fn retain_path_grants(
&self,
grants: Vec<ProcessPathGrant>,
) -> Result<(), ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
state.retain_path_rules(grants.into_iter().filter_map(|grant| {
(grant.constraint == ProcessPathGrantConstraint::Ordinary
&& grant.rule.access() != PathAccess::Deny)
.then_some(grant.rule)
}));
Ok(())
}
pub fn retain_domain_grants(
&self,
domains: impl IntoIterator<Item = String>,
) -> Result<(), ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
state.retain_domains(domains);
Ok(())
}
fn retain(
&self,
request: &PermissionRequest,
grants: Vec<ProcessPathGrant>,
) -> Result<(), ProcessRunnerError> {
let mut state = self.state.write().map_err(|_| {
ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
})?;
state.retain_path_rules(grants.into_iter().filter_map(|grant| {
(grant.constraint == ProcessPathGrantConstraint::Ordinary
&& grant.rule.access() != PathAccess::Deny)
.then_some(grant.rule)
}));
let mut domains = Vec::new();
for capability in request.requested() {
match capability {
RequestedCapability::HostIntegration(integration) => {
state.retain_host_integration(*integration);
}
RequestedCapability::NetworkDomain(domain) => {
domains.push(domain.clone());
}
RequestedCapability::Network | RequestedCapability::Path(_) => {}
}
}
if !domains.is_empty() {
state.retain_domains(domains);
}
if request.requests_network() {
state.retain_network();
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct SessionPermissionedProcessRunnerFactory<Factory> {
permissions: ProcessSessionPermissions,
backend: Factory,
}
impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
#[must_use]
pub fn backend(&self) -> &Factory {
&self.backend
}
}
impl<Factory: PermissionedProcessRunnerFactory> PermissionedProcessRunnerFactory
for SessionPermissionedProcessRunnerFactory<Factory>
{
fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
self.backend.validate_request(request)
}
fn request_capabilities_are_satisfied(
&self,
request: &PermissionRequest,
) -> Result<bool, ProcessRunnerError> {
self.backend.request_capabilities_are_satisfied(request)
}
fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
self.backend.targets_protected_metadata(request)
}
fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
self.runner_for_decision(request, ApprovalScope::Once)
}
fn runner_for_decision(
&self,
request: &PermissionRequest,
scope: ApprovalScope,
) -> Arc<dyn ProcessRunner> {
let result = self
.backend
.prepare_approved_request(request)
.and_then(|prepared| {
if scope == ApprovalScope::Session {
self.permissions.retain(request, prepared.grants)?;
}
Ok(prepared.runner)
});
match result {
Ok(runner) => runner,
Err(error) => Arc::new(RejectedRunner(error)),
}
}
}
struct RejectedRunner(ProcessRunnerError);
impl ProcessRunner for RejectedRunner {
fn run<'a>(
&'a self,
_intent: ProcessActionIntent,
_context: ProcessRunnerContext,
) -> ProcessRunnerFuture<'a> {
Box::pin(async { Err(self.0.clone()) })
}
}
fn normalize_grant_entries(rules: &mut Vec<(SessionGrantId, PathAccessRule)>) {
rules.sort_by(|(left_id, left), (right_id, right)| {
left.path()
.components()
.count()
.cmp(&right.path().components().count())
.then_with(|| left.path().cmp(right.path()))
.then_with(|| {
(left.access() != PathAccess::ReadWrite)
.cmp(&(right.access() != PathAccess::ReadWrite))
})
.then_with(|| left_id.cmp(right_id))
});
let mut retained: Vec<(SessionGrantId, PathAccessRule)> = Vec::with_capacity(rules.len());
for (id, rule) in rules.drain(..) {
if !retained.iter().any(|(_, ancestor)| {
rule.path().starts_with(ancestor.path()) && ancestor.access().covers(rule.access())
}) {
retained.push((id, rule));
}
}
*rules = retained;
}
#[cfg(test)]
mod tests;