vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Generic authorization.
//!
//! The Engine provides the *mechanism*: operations, actor references, and an
//! injectable policy. It does not bake in Unix mode bits, UID/GID numbers, or
//! any OS-specific security model. The OS installs a policy that
//! gives its permission representation meaning.

use std::collections::BTreeMap;

use crate::core::metadata::Metadata;
use crate::core::object_id::ObjectId;
pub use crate::security::actor::ActorId;

/// An operation an actor may attempt on an object.
///
/// The Engine checks exactly one operation per API call, against the primary
/// target object of that call. Creating an object checks [`Operation::Create`]
/// against the destination directory; all other operations check the object
/// itself.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Operation {
    /// Creating a new object in a directory.
    Create,
    /// Reading an object's state (content, metadata, listing).
    Read,
    /// Writing or replacing an object's content.
    Write,
    /// Moving, renaming, attaching, or detaching an object.
    Move,
    /// Copying an object.
    Copy,
    /// Deleting an object.
    Delete,
    /// Changing metadata (authorization, extensions, timestamps).
    ChangeMetadata,
    /// Changing the object's owning principal.
    ///
    /// Kept distinct from [`Operation::ChangeMetadata`] so that policies can
    /// enforce stricter rules on ownership changes (for example, allowing only
    /// the root user to change an owner, as real operating systems do).
    ChangeOwner,
    /// Executing a file. The OS assigns meaning; the Engine checks it.
    Execute,
}

/// The result of an authorization decision.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AuthorizationResult {
    /// The operation is allowed.
    Allowed,
    /// The operation is denied, with an optional explanation.
    Denied {
        /// Why the operation was denied, if known.
        reason: Option<String>,
    },
}

impl AuthorizationResult {
    /// Returns `true` when the operation is allowed.
    pub fn is_allowed(&self) -> bool {
        matches!(self, Self::Allowed)
    }
}

/// The context of an object's parent, for policies that decide operations
/// against the parent directory (for example Unix move/delete rules).
#[derive(Clone, Debug)]
pub struct ParentReference<'a> {
    /// The parent object.
    pub object: ObjectId,
    /// The parent's metadata.
    pub metadata: &'a Metadata,
}

/// A request to authorize an operation.
#[derive(Clone, Debug)]
pub struct AuthorizationRequest<'a> {
    /// The actor attempting the operation, if any.
    pub actor: Option<ActorId>,
    /// The operation being attempted.
    pub operation: Operation,
    /// The primary target object.
    pub object: ObjectId,
    /// The target object's metadata, for the policy to inspect.
    pub metadata: &'a Metadata,
    /// The target object's parent, when it has one.
    ///
    /// Policies may inspect it to implement parent-directory semantics (for
    /// example write access on the containing directory for moves and
    /// deletions).
    pub parent: Option<ParentReference<'a>>,
}

/// A policy that decides whether operations are allowed.
///
/// Implementations must be shareable across threads ([`Send`] + [`Sync`]).
/// The OS layer provides the real policy; the Engine only consults it.
pub trait AuthorizationPolicy: Send + Sync {
    /// Decides whether the request is allowed.
    fn authorize(&self, request: &AuthorizationRequest<'_>) -> AuthorizationResult;
}

/// A policy that allows everything.
///
/// This is the default until the OS installs a real policy.
#[derive(Clone, Copy, Debug, Default)]
pub struct PermissivePolicy;

impl AuthorizationPolicy for PermissivePolicy {
    fn authorize(&self, _request: &AuthorizationRequest<'_>) -> AuthorizationResult {
        AuthorizationResult::Allowed
    }
}

/// Opaque authorization data attached to an object.
///
/// The Engine stores and returns this data without understanding it. The OS
/// encodes its permission representation (mode bits, ACLs, SIDs, ...) into it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AuthorizationData {
    fields: BTreeMap<String, String>,
}

impl AuthorizationData {
    /// Creates empty authorization data.
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a key/value pair, returning the previous value if any.
    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) -> Option<String> {
        self.fields.insert(key.into(), value.into())
    }

    /// Removes a key, returning its value if present.
    pub fn remove(&mut self, key: &str) -> Option<String> {
        self.fields.remove(key)
    }

    /// Returns the value for a key, if present.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.fields.get(key).map(String::as_str)
    }

    /// Returns all fields.
    pub fn fields(&self) -> &BTreeMap<String, String> {
        &self.fields
    }

    /// Returns `true` when there are no fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}