Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

4.2 KB
Raw Blame
pub mod repository;
use crate::domain::{ports::*, *};
use agent_fold::domain::log::AgentSessionId;
use async_trait::async_trait;
use entity_access::domain::models::{
    AccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,
};
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
pub const SESSION: &str = "00000000-0000-0000-0000-000000000001";
pub const USER: &str = "macro|[email protected]";
/// The session every fixture receipt and identity refers to.
pub fn session() -> AgentSessionId {
    SESSION.parse().unwrap()
}
/// The user every fixture receipt and identity refers to.
pub fn user() -> MacroUserIdStr<'static> {
    MacroUserIdStr::try_from(USER.to_owned()).unwrap()
}
pub struct TestAuthority(pub AtomicBool, pub Arc<repository::MemoryRepository>);
#[async_trait]
impl Authority for TestAuthority {
    async fn agent(&self, token: &str) -> Result<AgentIdentity, PreviewError> {
        if token != "session-secret" {
            return Err(PreviewError::Denied);
        }
        Ok(identity())
    }
    async fn viewer(
        &self,
        session: AgentSessionId,
        _: &MacroUserIdStr<'_>,
    ) -> Result<(), PreviewError> {
        self.active(session).await
    }
    async fn active(&self, _: AgentSessionId) -> Result<(), PreviewError> {
        if self.0.load(Ordering::SeqCst) {
            Ok(())
        } else {
            Err(PreviewError::Denied)
        }
    }
}
pub struct TestEvents;
#[async_trait]
impl Events for TestEvents {
    async fn changed(
        &self,
        _: &Preview,
        _: &[MacroUserIdStr<'static>],
    ) -> Result<(), PreviewError> {
        Ok(())
    }
}
pub fn identity() -> AgentIdentity {
    AgentIdentity {
        session: session(),
        owner: user(),
    }
}
pub fn receipt<T: RequiredPermission>(level: AccessLevel) -> EntityAccessReceipt<T> {
    EntityAccessReceipt::try_new_authenticated_user(
        user(),
        Entity {
            entity_id: SESSION.into(),
            entity_type: EntityType::AgentSession,
        },
        EntityPermission::AccessLevel {
            access_level: level,
        },
    )
    .unwrap()
}
pub fn fixture(ssh_port: u16) -> (PreviewService, Arc<TestAuthority>, russh::keys::PrivateKey) {
    fixture_with(ssh_port, |_| {})
}
/// Same fixture, with deployment settings adjusted before the service validates them.
pub fn fixture_with(
    ssh_port: u16,
    adjust: impl FnOnce(&mut Settings),
) -> (PreviewService, Arc<TestAuthority>, russh::keys::PrivateKey) {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("host_key");
    assert!(
        std::process::Command::new("ssh-keygen")
            .args(["-q", "-t", "ed25519", "-N", "", "-f"])
            .arg(&path)
            .status()
            .unwrap()
            .success()
    );
    let key = crate::inbound::ssh::host_key(&std::fs::read_to_string(path).unwrap()).unwrap();
    let store = Arc::new(repository::MemoryRepository::default());
    let authority = Arc::new(TestAuthority(AtomicBool::new(true), store.clone()));
    let mut settings = Settings {
        domain: "preview.test".into(),
        https_port: 443,
        local_ssh_fallback: false,
        ssh_proxy_host: None,
        ssh_host: "localhost".into(),
        ssh_port,
        host_key: crate::inbound::ssh::public_key(&key).unwrap(),
        app_origin: "https://macro.test".into(),
    };
    adjust(&mut settings);
    let replica = uuid::Uuid::now_v7();
    store.0.lock().unwrap().replicas.insert(
        replica,
        ("127.0.0.1:1".parse().unwrap(), repository::now() + 45000),
    );
    let service = PreviewService::new(
        settings,
        authority.clone(),
        Arc::new(TestEvents),
        store,
        replica,
        Arc::new(crate::outbound::peer::TcpPeerConnector),
    )
    .unwrap();
    (service, authority, key)
}
pub struct TcpTunnel(pub std::net::SocketAddr);
#[async_trait]
impl Tunnel for TcpTunnel {
    async fn open(&self) -> Result<Stream, PreviewError> {
        Ok(Box::new(
            tokio::net::TcpStream::connect(self.0)
                .await
                .map_err(|_| PreviewError::Unavailable)?,
        ))
    }
    async fn close(&self) {}
}