Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

6.3 KB
Raw Blame
use super::*;
use crate::agent_bridge::{handle_connection, ok_json};
use serde_json::{json, Value};
use std::io::Read;
use std::os::windows::io::AsRawHandle;
use std::ptr::{addr_of_mut, null_mut};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient};
use windows::Win32::Security::Authorization::{
    GetSecurityInfo, SE_FILE_OBJECT, SE_KERNEL_OBJECT, SE_OBJECT_TYPE,
};
use windows::Win32::Security::{
    GetAce, GetSecurityDescriptorControl, ACCESS_ALLOWED_ACE, DACL_SECURITY_INFORMATION,
    SE_DACL_PROTECTED,
};
use windows::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;

fn assert_private_acl(object: &impl AsRawHandle, kind: SE_OBJECT_TYPE) -> Result<()> {
    let mut acl = null_mut();
    let mut descriptor = PSECURITY_DESCRIPTOR::default();
    // GetSecurityInfo returns one allocation; the DACL and ACE point into it.
    unsafe {
        GetSecurityInfo(
            HANDLE(object.as_raw_handle()),
            kind,
            DACL_SECURITY_INFORMATION,
            None,
            None,
            Some(&mut acl),
            None,
            Some(&mut descriptor),
        )
        .ok()?;
        let _allocation = Owned::new(HLOCAL(descriptor.0));
        assert!(!acl.is_null(), "a null DACL permits everyone");
        assert_eq!(
            (*acl).AceCount,
            1,
            "only the process user should have an ACE"
        );
        let mut entry = null_mut();
        GetAce(acl, 0, &mut entry)?;
        let ace = entry.cast::<ACCESS_ALLOWED_ACE>();
        assert_eq!((*ace).Header.AceType as u32, ACCESS_ALLOWED_ACE_TYPE);
        assert_eq!(
            sid_string(PSID(addr_of_mut!((*ace).SidStart).cast()))?,
            current_user_sid()?
        );
        if kind == SE_FILE_OBJECT {
            let mut control = 0;
            GetSecurityDescriptorControl(descriptor, &mut control, &mut 0)?;
            assert_ne!(
                control & SE_DACL_PROTECTED.0,
                0,
                "must exclude inherited grants"
            );
        }
    }
    Ok(())
}

#[test]
fn discovery_replaces_the_old_file_with_a_private_one() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let path = dir.path().join("agent-bridge.json");
    std::fs::write(&path, "previous launch")?;
    let mut old = File::open(&path)?;
    write_discovery_file(&path, "this launch")?;
    assert_private_acl(&File::open(&path)?, SE_FILE_OBJECT)?;
    assert_eq!(std::fs::read_to_string(&path)?, "this launch");
    let mut contents = String::new();
    old.read_to_string(&mut contents)?;
    assert_eq!(
        contents, "previous launch",
        "readers see a complete generation"
    );
    Ok(())
}

#[tokio::test]
async fn first_and_replacement_pipe_instances_are_private() -> Result<()> {
    let mut listener = PipeListener::bind()?;
    assert_private_acl(&listener.pending, SE_KERNEL_OBJECT)?;
    let _client = ClientOptions::new().open(&listener.name)?;
    let _connected = listener.accept().await?;
    assert_private_acl(&listener.pending, SE_KERNEL_OBJECT)?;
    let err = listener
        .security
        .create_pipe(&listener.name, true)
        .unwrap_err();
    assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
    Ok(())
}

/// Read through EOF, so an extra response or a connection left open fails the test.
async fn exchange(mut client: NamedPipeClient, request: Value) -> Result<Value> {
    client.write_all(format!("{request}\n").as_bytes()).await?;
    let mut response = String::new();
    client.read_to_string(&mut response).await?;
    assert!(response.ends_with('\n'));
    assert_eq!(response.lines().count(), 1);
    Ok(serde_json::from_str(&response)?)
}

#[tokio::test]
async fn bad_token_is_rejected_before_dispatch() -> Result<()> {
    let mut listener = PipeListener::bind()?;
    let client = ClientOptions::new().open(&listener.name)?;
    let server = listener.accept().await?;
    let serve = handle_connection(server, "right", |_| async {
        panic!("unauthenticated command")
    });
    let call = exchange(client, json!({"token":"wrong", "cmd":"start"}));
    let ((), reply) = tokio::time::timeout(Duration::from_secs(5), async {
        tokio::try_join!(serve, call)
    })
    .await??;
    assert_eq!(reply["ok"], false);
    assert_eq!(reply["error"]["code"], "unauthorized");
    Ok(())
}

#[tokio::test]
async fn start_and_stop_round_trip_on_separate_connections() -> Result<()> {
    let mut listener = PipeListener::bind()?;
    let name = listener.name.clone();
    let token = random_token();
    // Stand in for the recorder: exercise framing, auth and handoff without a
    // display, a consent dialog or a recording of the machine running the tests.
    let serve = async {
        let mut active = None;
        for _ in 0..2 {
            handle_connection(listener.accept().await?, &token, |req| {
                std::future::ready(match req.cmd.as_str() {
                    "start" => {
                        assert_eq!(req.max_sec, Some(10));
                        assert!(active.replace("take-1").is_none());
                        ok_json(json!({"state":"recording", "recordingId":active}))
                    }
                    "stop" => ok_json(json!({"recordingId":active.take().expect("start first")})),
                    _ => panic!("unexpected command"),
                })
            })
            .await?;
        }
        Ok::<(), anyhow::Error>(())
    };
    let call = async {
        let started = exchange(
            ClientOptions::new().open(&name)?,
            json!({
                "cmd":"start", "token":token, "maxSec":10
            }),
        )
        .await?;
        let stopped = exchange(
            ClientOptions::new().open(&name)?,
            json!({
                "cmd":"stop", "token":token
            }),
        )
        .await?;
        assert_eq!(started["ok"], true);
        assert_eq!(started["data"]["state"], "recording");
        assert_eq!(stopped["ok"], true);
        assert_eq!(stopped["data"]["recordingId"], "take-1");
        assert_eq!(
            stopped["data"]["recordingId"],
            started["data"]["recordingId"]
        );
        Ok(())
    };
    tokio::time::timeout(Duration::from_secs(5), async {
        tokio::try_join!(serve, call)
    })
    .await??;
    Ok(())
}