authoravatarclover caruso<git@paperclover.net>2026-10-21 19:30:36-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-24 19:01:23-07:00
logbc97ccbb76c079f855e64b943306227f3cf9e5ce
tree561d16f5552668400a13321e5e2adb402f9a9cb9
parent3adad9767eb19ab651b35e1f76b7f4a358df0225
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add owner-scoped computer MCP for the Mac devbox

Expose screenshots, accessibility inspection, and bounded guest scripts through per-VM OAuth grants. Install the Mac guest worker and provide explicit preview access to the configured devbox. Verify ownership, scopes, revocation, desktop input, and process timeout cleanup. Assisted-by: gpt-6-astra

21 files changed, 573 insertions(+), 27 deletions(-)

dashboard/src/computer.rs created+141
...@@ -0,0 +1,141 @@
1use crate::*;
2use rmcp::{
3 ErrorData, RoleServer, ServerHandler,
4 model::{
5 CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock,
6 ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
7 ToolAnnotations,
8 },
9 service::RequestContext,
10};
11
12pub async fn resources(owner: &Value) -> Result<Vec<Value>> {
13 let domains = host::call(json!({"operation":"vm.domains"})).await?;
14 Ok(array(&domains)
15 .iter()
16 .filter(|vm| {
17 vm["owner"] == owner["id"] && array(&vm["capabilities"]).iter().any(|c| c == "computer")
18 })
19 .map(|vm| json!({"id":vm["name"],"name":vm["name"],"description":vm["description"]}))
20 .collect())
21}
22
23fn permitted(grant: &Value, vm: &str, scope: &str, owner: &Value) -> Result<()> {
24 if !array(&grant["scopes"]).iter().any(|s| s == scope)
25 || !array(&grant["resources"]).iter().any(|id| id == vm)
26 || owner["owner"].as_str().is_none()
27 || owner["owner"] != grant["user"]
28 {
29 return Err(Error::new(
30 403,
31 "This VM is outside the connection's access. Update access in MCP settings.",
32 ));
33 }
34 Ok(())
35}
36
37#[derive(Clone)]
38struct Computer;
39impl ServerHandler for Computer {
40 fn get_info(&self) -> ServerConfig {
41 ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
42 }
43 async fn list_tools(
44 &self,
45 _: Option<PaginatedRequestParams>,
46 _: RequestContext<RoleServer>,
47 ) -> std::result::Result<ListToolsResult, ErrorData> {
48 let tools = [
49 ("computer_list", "List granted VMs with computer-use support.", json!({}), json!([])),
50 ("computer_status", "Check a VM's desktop permissions and scripting capabilities.", json!({"vm":{"type":"string"}}), json!(["vm"])),
51 ("computer_shot", "Capture the selected VM's current desktop as an image.", json!({"vm":{"type":"string"}}), json!(["vm"])),
52 ("computer_ui", "Read a bounded macOS accessibility tree, including roles, values, bounds and available actions. Use an application PID to inspect that app, or omit it for the frontmost app. Read a fresh tree before using its child paths.", json!({"vm":{"type":"string"},"pid":{"type":"integer","minimum":1}}), json!(["vm"])),
53 ("computer_exec", "Run a zsh script inside the selected Mac VM's logged-in desktop. Returns exit status, stdout/stderr (64 KiB each), and optionally a screenshot. Batch actions into one script. Use /usr/local/bin/agent-gui tree [PID], press PID 0.1.2, click X Y, key CODE [command|shift|option|control], and type - (UTF-8 stdin). Coordinates use macOS screen points; compare screenshot dimensions with display bounds before pixel input. sudo -n is available for guest setup. Timeout kills the script process group. For long-lived apps, redirect stdin/stdout/stderr before backgrounding. Never assume a timed-out command did not run.", json!({"vm":{"type":"string"},"script":{"type":"string","maxLength":65536},"timeout_ms":{"type":"integer","minimum":1,"maximum":180000,"default":60000},"screenshot":{"type":"boolean","default":true}}), json!(["vm","script"])),
54 ].into_iter().map(|(name, description, properties, required)| {
55 Tool::new(name, description, json!({"type":"object","properties":properties,"required":required,"additionalProperties":false}).as_object().unwrap().clone())
56 .with_annotations(ToolAnnotations::new().read_only(name != "computer_exec"))
57 }).collect();
58 Ok(ListToolsResult {
59 tools,
60 ttl_ms: Some(0),
61 cache_scope: Some(CacheScope::Private),
62 ..Default::default()
63 })
64 }
65 async fn call_tool(
66 &self,
67 request: CallToolRequestParams,
68 context: RequestContext<RoleServer>,
69 ) -> std::result::Result<CallToolResponse, ErrorData> {
70 let result: Result<Value> = async {
71 let grant = &context.extensions.get::<axum::http::request::Parts>()
72 .and_then(|p| p.extensions.get::<mcp::Grant>())
73 .ok_or_else(|| Error::new(401, "This connection expired. Connect again."))?.0;
74 let mut arguments = request.arguments.unwrap_or_default();
75 if request.name == "computer_list" {
76 if !arguments.is_empty() { return Err(Error::new(400, "This tool takes no arguments.")); }
77 return Ok(json!({"computers":resources(&json!({"id":grant["user"]})).await?.into_iter()
78 .filter(|vm| array(&grant["resources"]).iter().any(|id| id == &vm["id"])).collect::<Vec<_>>()}));
79 }
80 let vm = arguments.remove("vm").and_then(|v| v.as_str().map(str::to_owned))
81 .filter(|s| !s.is_empty() && s.len() <= 63)
82 .ok_or_else(|| Error::new(400, "Choose a granted VM."))?;
83 if !array(&grant["resources"]).iter().any(|id| id == &vm) {
84 return Err(Error::new(403, "Choose a VM granted to this connection."));
85 }
86 let scope = if request.name == "computer_exec" { "computer:control" } else { "computer:read" };
87 let owner = host::call(json!({"operation":"vm.owner","payload":{"name":vm}})).await?;
88 permitted(grant, &vm, scope, &owner)?;
89 let operation = match request.name.as_ref() {
90 "computer_status" => json!({"action":"status"}),
91 "computer_shot" => json!({"action":"shot"}),
92 "computer_ui" => json!({"action":"ui","pid":arguments.remove("pid")}),
93 "computer_exec" => json!({"action":"exec", "script":arguments.remove("script"),
94 "timeout_ms":arguments.remove("timeout_ms").unwrap_or(json!(60000)),
95 "screenshot":arguments.remove("screenshot").unwrap_or(json!(true))}),
96 _ => return Err(Error::new(404, "No tool with that name.")),
97 };
98 if !arguments.is_empty() { return Err(Error::new(400, "Use the fields listed for this tool.")); }
99 host::call(json!({"operation":"vm.computer","payload":{"name":vm,"request":operation}})).await
100 }.await;
101 Ok(match result {
102 Ok(mut value) => {
103 let png = value.as_object_mut().and_then(|v| v.remove("png"));
104 let mut content = vec![ContentBlock::text(value.to_string())];
105 if let Some(png) = png.and_then(|v| v.as_str().map(str::to_owned)) {
106 content.push(ContentBlock::image(png, "image/png"));
107 }
108 CallToolResult::success(content)
109 }
110 Err(error) => CallToolResult::error(vec![ContentBlock::text(error.message)]),
111 }
112 .into())
113 }
114}
115
116pub fn router(app: Arc<App>) -> Router {
117 mcp::router(app, "computer", || Ok(Computer))
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123 #[test]
124 fn control_requires_the_current_owner_selected_vm_and_scope() {
125 let grant = json!({"user":"clover","scopes":["computer:read"],"resources":["m3-devbox"]});
126 let owner = json!({"owner":"clover","ownerOnly":true});
127 assert!(permitted(&grant, "m3-devbox", "computer:read", &owner).is_ok());
128 assert!(permitted(&grant, "m3-devbox", "computer:control", &owner).is_err());
129 assert!(permitted(&grant, "other", "computer:read", &owner).is_err());
130 assert!(
131 permitted(
132 &grant,
133 "m3-devbox",
134 "computer:read",
135 &json!({"owner":"another-user"})
136 )
137 .is_err()
138 );
139 assert!(permitted(&grant, "m3-devbox", "computer:read", &Value::Null).is_err());
140 }
141}
dashboard/src/host.rs+1-1
...@@ -34,7 +34,7 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {...@@ -34,7 +34,7 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {
34 Some("vm.create" | "vm.media" | "vm.preset")34 Some("vm.create" | "vm.media" | "vm.preset")
35 ) {35 ) {
36 91036 910
37 } else if request["operation"] == "vm.act" {37 } else if matches!(request["operation"].as_str(), Some("vm.act" | "vm.computer")) {
38 24038 240
39 } else if request["operation"] == "copyparty.manage" {39 } else if request["operation"] == "copyparty.manage" {
40 31040 310
dashboard/src/main.rs+2
...@@ -4,6 +4,7 @@ mod auth;...@@ -4,6 +4,7 @@ mod auth;
4mod atproto;4mod atproto;
5mod identity;5mod identity;
6mod cache;6mod cache;
7mod computer;
7mod core;8mod core;
8mod deploys;9mod deploys;
9mod files;10mod files;
...@@ -593,6 +594,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {...@@ -593,6 +594,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
593 .nest_service("/assets", ServeDir::new(format!("{dist}/assets")))594 .nest_service("/assets", ServeDir::new(format!("{dist}/assets")))
594 .with_state(app.clone())595 .with_state(app.clone())
595 .merge(observability::router(app.clone()))596 .merge(observability::router(app.clone()))
597 .merge(computer::router(app.clone()))
596 .merge(shale::router(app.clone()))598 .merge(shale::router(app.clone()))
597 .merge(relay::router(app.clone()))599 .merge(relay::router(app.clone()))
598 .fallback_service(600 .fallback_service(
dashboard/src/mcp.rs+8-1
...@@ -8,6 +8,7 @@ use sha2::{Digest, Sha256};...@@ -8,6 +8,7 @@ use sha2::{Digest, Sha256};
8use std::os::unix::fs::{DirBuilderExt, PermissionsExt};8use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
99
10const CATALOGS: &[(&str, &str, &[&str])] = &[10const CATALOGS: &[(&str, &str, &[&str])] = &[
11 ("computer", "Computers", &["computer:read", "computer:control", "offline_access"]),
11 (12 (
12 "observability",13 "observability",
13 "Logs and traces",14 "Logs and traces",
...@@ -499,6 +500,8 @@ pub(crate) fn active_owner(app: &App, grant: &Value) -> Result<bool> {...@@ -499,6 +500,8 @@ pub(crate) fn active_owner(app: &App, grant: &Value) -> Result<bool> {
499 };500 };
500 Ok(profile["enabled"] == true501 Ok(profile["enabled"] == true
501 && !guest::is_guest(&profile)502 && !guest::is_guest(&profile)
503 && (grant["resource"] != app.mcp.resource("computer")
504 || array(&profile["groups"]).iter().any(|role| matches!(role["name"].as_str(), Some("vm" | "infra-admin"))))
502 && (grant["resource"] != app.mcp.resource("observability")505 && (grant["resource"] != app.mcp.resource("observability")
503 || array(&profile["groups"])506 || array(&profile["groups"])
504 .iter()507 .iter()
...@@ -794,6 +797,10 @@ pub async fn manage(...@@ -794,6 +797,10 @@ pub async fn manage(
794 }797 }
795 Err(error) => return Err(error),798 Err(error) => return Err(error),
796 }799 }
800 } else if consent_resource == app.mcp.resource("computer")
801 && array(&me["sections"]).iter().any(|s| s == "vms")
802 {
803 computer::resources(&owner).await?
797 } else if consent_resource == app.mcp.resource("observability")804 } else if consent_resource == app.mcp.resource("observability")
798 && array(&me["sections"]).iter().any(|s| s == "admin")805 && array(&me["sections"]).iter().any(|s| s == "admin")
799 && array(&owner["groups"])806 && array(&owner["groups"])
...@@ -1062,7 +1069,7 @@ mod tests {...@@ -1062,7 +1069,7 @@ mod tests {
1062 json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await;1069 json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await;
1063 let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state",1070 let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state",
1064 "code_challenge":"AdJpfUsRa6XMg54f2khmgo2onMwePN3vmU9DOOoaTzo","code_challenge_method":"S256",1071 "code_challenge":"AdJpfUsRa6XMg54f2khmgo2onMwePN3vmU9DOOoaTzo","code_challenge_method":"S256",
1065 "redirect_uri":uri,"scope":"observability:read offline_access sessions:read sessions:write shale:read shale:write"}));1072 "redirect_uri":uri,"scope":"observability:read offline_access sessions:read sessions:write shale:read shale:write computer:read computer:control"}));
1066 for (catalog, _, allowed) in CATALOGS {1073 for (catalog, _, allowed) in CATALOGS {
1067 request.insert("resource".into(), fixture.store.resource(catalog));1074 request.insert("resource".into(), fixture.store.resource(catalog));
1068 let response = fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap();1075 let response = fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap();
dashboard/web/pages/MCP.tsx+13-5
...@@ -16,6 +16,7 @@ import type { Access, Catalog } from "../types/mcp.ts";...@@ -16,6 +16,7 @@ import type { Access, Catalog } from "../types/mcp.ts";
16import "./MCP.css";16import "./MCP.css";
1717
18const descriptions: Record<Catalog, string> = {18const descriptions: Record<Catalog, string> = {
19 computer: "Inspect and control selected virtual machines, run commands, and install guest software.",
19 shale: "Read and edit issues across your Shale repositories.",20 shale: "Read and edit issues across your Shale repositories.",
20 agents: "Connect to Codex and Claude Code on your machines.",21 agents: "Connect to Codex and Claude Code on your machines.",
21 observability: "Read logs and traces from your services.",22 observability: "Read logs and traces from your services.",
...@@ -148,9 +149,16 @@ export function MCP(props: { me: Me }) {...@@ -148,9 +149,16 @@ export function MCP(props: { me: Me }) {
148 </Show>149 </Show>
149 <section class="mcp-panel"><h2>Connected clients</h2>150 <section class="mcp-panel"><h2>Connected clients</h2>
150 <Show when={connections().length} fallback={<p class="muted">No clients connected. Add the connector URL to your AI client to get started.</p>}>151 <Show when={connections().length} fallback={<p class="muted">No clients connected. Add the connector URL to your AI client to get started.</p>}>
151 <div class="mcp-client-list"><For each={connections()}>{(client) => <article class="mcp-client">152 <div class="mcp-client-list"><For each={connections()}>{(client) => {
152 <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("sessions:write") ? "Session control" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div>153 let editButton!: HTMLButtonElement;
153 <div class="mcp-actions"><button class="button small" disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button>154 const cancel = () => { setEditing(""); editButton.focus(); };
155 return <article class="mcp-client" onKeyDown={(event) => {
156 if (event.key === "Escape" && editing() === client.id && !busy()) {
157 event.preventDefault(); event.stopPropagation(); cancel();
158 }
159 }}>
160 <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("computer:control") ? "VM control and commands" : client.scopes.includes("sessions:write") ? "Session control" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div>
161 <div class="mcp-actions"><button ref={editButton} class="button small" aria-expanded={editing() === client.id} disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button>
154 <button class="button small" disabled={busy()} onClick={() => showConfirmDialog({ title: "Revoke this connection?", description: `${client.name} will lose access immediately.`, confirmLabel: "Revoke", destructive: true, onConfirm: async () => {162 <button class="button small" disabled={busy()} onClick={() => showConfirmDialog({ title: "Revoke this connection?", description: `${client.name} will lose access immediately.`, confirmLabel: "Revoke", destructive: true, onConfirm: async () => {
155 await parseResponse(api.mcp.connections[":id"].$delete({ param: { id: client.id } })); if (editing() === client.id) setEditing(""); await refetch(); toast("Connection revoked");163 await parseResponse(api.mcp.connections[":id"].$delete({ param: { id: client.id } })); if (editing() === client.id) setEditing(""); await refetch(); toast("Connection revoked");
156 } })}>Revoke</button></div>164 } })}>Revoke</button></div>
...@@ -164,11 +172,11 @@ export function MCP(props: { me: Me }) {...@@ -164,11 +172,11 @@ export function MCP(props: { me: Me }) {
164 try { await parseResponse(api.mcp.connections[":id"].$post({ param: { id: client.id }, json: { resources: selection() } })); setEditing(""); await refetch(); }172 try { await parseResponse(api.mcp.connections[":id"].$post({ param: { id: client.id }, json: { resources: selection() } })); setEditing(""); await refetch(); }
165 catch (error) { toast(reason(error)); }173 catch (error) { toast(reason(error)); }
166 finally { setBusy(false); }174 finally { setBusy(false); }
167 }}>Save access</button><button class="button" disabled={busy()} onClick={() => setEditing("")}>Cancel</button></div>175 }}>Save access</button><button class="button" disabled={busy()} onClick={cancel}>Cancel</button></div>
168 </Show>}176 </Show>}
169 </Loaded>177 </Loaded>
170 </div></Show>178 </div></Show>
171 </article>}</For></div>179 </article>; }}</For></div>
172 </Show>180 </Show>
173 </section>181 </section>
174 </>}</Show>182 </>}</Show>
dashboard/web/pages/MCPAccess.tsx+2-2
...@@ -10,7 +10,7 @@ export function MCPAccess(props: {...@@ -10,7 +10,7 @@ export function MCPAccess(props: {
10 disabled: boolean;10 disabled: boolean;
11}) {11}) {
12 return <fieldset class="mcp-access" disabled={props.disabled}>12 return <fieldset class="mcp-access" disabled={props.disabled}>
13 <legend>{props.catalog === "shale" ? "Repositories" : props.catalog === "agents" ? "Machines" : "Services"}</legend>13 <legend>{props.catalog === "computer" ? "Virtual machines" : props.catalog === "shale" ? "Repositories" : props.catalog === "agents" ? "Machines" : "Services"}</legend>
14 <Show when={props.catalog === "shale"}>14 <Show when={props.catalog === "shale"}>
15 <div class="mcp-access-modes">15 <div class="mcp-access-modes">
16 <label><input type="radio" name="repository-access" checked={props.value === "all"} onChange={() => props.onChange("all")} />16 <label><input type="radio" name="repository-access" checked={props.value === "all"} onChange={() => props.onChange("all")} />
...@@ -28,7 +28,7 @@ export function MCPAccess(props: {...@@ -28,7 +28,7 @@ export function MCPAccess(props: {
28 props.onChange(checked ? [...selected, resource.id] : selected.filter((id) => id !== resource.id));28 props.onChange(checked ? [...selected, resource.id] : selected.filter((id) => id !== resource.id));
29 }}><span>{resource.name}<Show when={resource.description}><small class="muted">{resource.description}</small></Show></span></Checkbox>29 }}><span>{resource.name}<Show when={resource.description}><small class="muted">{resource.description}</small></Show></span></Checkbox>
30 }</For></div>30 }</For></div>
31 <Show when={!props.resources.length}><p class="muted">{props.catalog === "agents" ? "No machines linked. Link a machine in MCP settings before connecting a client." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show>31 <Show when={!props.resources.length}><p class="muted">{props.catalog === "computer" ? "No supported VMs belong to your account." : props.catalog === "agents" ? "No machines linked. Link a machine in MCP settings before connecting a client." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show>
32 </Show>32 </Show>
33 </fieldset>;33 </fieldset>;
34}34}
dashboard/web/pages/MCPConsent.tsx+3-2
...@@ -58,10 +58,11 @@ export function MCPConsent() {...@@ -58,10 +58,11 @@ export function MCPConsent() {
58 </>}>58 </>}>
59 {(data) => <>59 {(data) => <>
60 <h1 id="connection-title">Connect {data().client}</h1>60 <h1 id="connection-title">Connect {data().client}</h1>
61 <p class="mcp-approval-intro">{data().catalog === "shale" ? "Grant access to Shale issues." : data().catalog === "agents" ? "Grant access to your local agents." : "Grant access to logs and traces."}</p>61 <p class="mcp-approval-intro">{data().catalog === "computer" ? "Grant access to selected virtual machines." : data().catalog === "shale" ? "Grant access to Shale issues." : data().catalog === "agents" ? "Grant access to your local agents." : "Grant access to logs and traces."}</p>
62 <dl class="mcp-request-identity"><div><dt>Signed in as</dt><dd>{data().account}</dd></div><div><dt>Return to</dt><dd>{data().redirectHost}</dd></div></dl>62 <dl class="mcp-request-identity"><div><dt>Signed in as</dt><dd>{data().account}</dd></div><div><dt>Return to</dt><dd>{data().redirectHost}</dd></div></dl>
63 <div class="mcp-permissions"><h2>Requested access</h2>63 <div class="mcp-permissions"><h2>Requested access</h2>
64 <p>{data().catalog === "shale" ? "Read issues and comments" : data().catalog === "agents" ? "Read saved chats" : "Read logs and traces"}</p>64 <p>{data().catalog === "computer" ? "Read VM status, screenshots, and application controls" : data().catalog === "shale" ? "Read issues and comments" : data().catalog === "agents" ? "Read saved chats" : "Read logs and traces"}</p>
65 <Show when={data().scopes.includes("computer:control")}><p>Control the desktop, run commands, and install software inside the selected VMs</p></Show>
65 <Show when={data().scopes.includes("shale:write")}><p>Create issues, comment, and edit issue titles and status</p></Show>66 <Show when={data().scopes.includes("shale:write")}><p>Create issues, comment, and edit issue titles and status</p></Show>
66 <Show when={data().scopes.includes("sessions:write")}><p>Send messages, start chats, and interrupt turns</p></Show>67 <Show when={data().scopes.includes("sessions:write")}><p>Send messages, start chats, and interrupt turns</p></Show>
67 <Show when={data().scopes.includes("offline_access")}><p>Stay connected without signing in again</p></Show>68 <Show when={data().scopes.includes("offline_access")}><p>Stay connected without signing in again</p></Show>
dashboard/web/types/mcp.ts+1-1
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1export type Catalog = "shale" | "agents" | "observability";1export type Catalog = "shale" | "agents" | "observability" | "computer";
2export type Access = "all" | string[];2export type Access = "all" | string[];
3export type Resources = { id: string; name: string; description?: string }[];3export type Resources = { id: string; name: string; description?: string }[];
44
tools/dashboard-host.py+2-2
...@@ -186,9 +186,9 @@ class Host:...@@ -186,9 +186,9 @@ class Host:
186 vms.validate(action, payload)186 vms.validate(action, payload)
187 except ValueError as error:187 except ValueError as error:
188 raise Rejected(str(error)) from error188 raise Rejected(str(error)) from error
189 if action == "clipboard":189 if action in {"clipboard", "computer"}:
190 if not vms.mac_vms.CONFIG or payload["name"] != vms.mac_vms.CONFIG["name"]:190 if not vms.mac_vms.CONFIG or payload["name"] != vms.mac_vms.CONFIG["name"]:
191 raise Rejected("Use this VM's screen clipboard.")191 raise Rejected("This VM does not support this guest operation.")
192 try:192 try:
193 return vms.mac_vms.handle(action, payload)193 return vms.mac_vms.handle(action, payload)
194 except ValueError as error:194 except ValueError as error:
tools/dashboard-stage-test.py+11-1
...@@ -34,7 +34,7 @@ class PreviewBoundary(unittest.TestCase):...@@ -34,7 +34,7 @@ class PreviewBoundary(unittest.TestCase):
34 return json.loads(sent[4:]), host34 return json.loads(sent[4:]), host
3535
36 def test_denies_host_mutations_and_vm_streams_before_dispatch(self):36 def test_denies_host_mutations_and_vm_streams_before_dispatch(self):
37 for operation in ["vm.create", "vm.start", "vm.console", "vm.serial", "vm.guest", "vm.upload", "storage.destroy", "deploy.start", "deploy.secret.get", "shale.write", "copyparty.manage", []]:37 for operation in ["vm.create", "vm.start", "vm.console", "vm.serial", "vm.guest", "vm.upload", "vm.computer", "vm.owner", "storage.destroy", "deploy.start", "deploy.secret.get", "shale.write", "copyparty.manage", []]:
38 with self.subTest(operation=operation):38 with self.subTest(operation=operation):
39 response, host = self.call({"operation": operation})39 response, host = self.call({"operation": operation})
40 self.assertEqual(response["status"], 403)40 self.assertEqual(response["status"], 403)
...@@ -53,6 +53,16 @@ class PreviewBoundary(unittest.TestCase):...@@ -53,6 +53,16 @@ class PreviewBoundary(unittest.TestCase):
53 with self.assertRaisesRegex(ValueError, "invalid dashboard stage"):53 with self.assertRaisesRegex(ValueError, "invalid dashboard stage"):
54 stage.metadata(identity)54 stage.metadata(identity)
5555
56 def test_attached_computer_cannot_target_another_vm(self):
57 host = stage.PreviewHost({"clone": "globe/staging/fixture", "computer": "mac-fixture"})
58 with patch.object(boundary.Host, "handle", return_value={"ok": True}) as call:
59 for operation in ["vm.computer", "vm.owner"]:
60 with self.assertRaises(boundary.dashboard_runs.Error):
61 host.handle({"operation": operation, "payload": {"name": "personal"}})
62 call.assert_not_called()
63 self.assertEqual(host.handle({"operation": operation, "payload": {"name": "mac-fixture"}}), {"ok": True})
64 call.reset_mock()
65
56 def test_file_operations_cannot_name_production_or_account_dataset(self):66 def test_file_operations_cannot_name_production_or_account_dataset(self):
57 dataset = "globe/staging/dashboard-preview-12345678"67 dataset = "globe/staging/dashboard-preview-12345678"
58 host = stage.PreviewHost({"clone": dataset})68 host = stage.PreviewHost({"clone": dataset})
tools/dashboard-stage.py+27-4
...@@ -9,6 +9,7 @@ import secrets...@@ -9,6 +9,7 @@ import secrets
9import shlex9import shlex
10import shutil10import shutil
11import socket11import socket
12import sqlite3
12import subprocess13import subprocess
13import sys14import sys
14import threading15import threading
...@@ -35,6 +36,10 @@ class PreviewHost(boundary.Host):...@@ -35,6 +36,10 @@ class PreviewHost(boundary.Host):
3536
36 def handle(self, request):37 def handle(self, request):
37 operation = request.get("operation") if isinstance(request, dict) else None38 operation = request.get("operation") if isinstance(request, dict) else None
39 if operation in {"vm.computer", "vm.owner"}:
40 payload = request.get("payload")
41 if not self.stage.get("computer") or not isinstance(payload, dict) or payload.get("name") != self.stage["computer"]:
42 raise boundary.dashboard_runs.Error(403, "Choose the VM explicitly attached to this preview.")
38 if operation == "shale.access":43 if operation == "shale.access":
39 service = request.get("service", "")44 service = request.get("service", "")
40 if not re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):45 if not re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):
...@@ -86,11 +91,12 @@ def serve(stage):...@@ -86,11 +91,12 @@ def serve(stage):
86 if not slots.acquire(blocking=False):91 if not slots.acquire(blocking=False):
87 connection.close()92 connection.close()
88 continue93 continue
89 work = workers.submit(boundary.serve_connection, connection, host, saved["uid"], OPERATIONS)94 operations = OPERATIONS | {"vm.computer", "vm.owner"} if saved.get("computer") else OPERATIONS
95 work = workers.submit(boundary.serve_connection, connection, host, saved["uid"], operations)
90 work.add_done_callback(lambda _: slots.release())96 work.add_done_callback(lambda _: slots.release())
9197
9298
93def stage():99def stage(computer=None):
94 snowglobe.token()100 snowglobe.token()
95 site = json.loads(snowglobe.command("pkl", "eval", "-f", "json", str(snowglobe.REPO / "config/site.pkl"), capture=True).stdout)101 site = json.loads(snowglobe.command("pkl", "eval", "-f", "json", str(snowglobe.REPO / "config/site.pkl"), capture=True).stdout)
96 site["hostRoot"] = str(Path(site["root"]) / "prod/dashboard")102 site["hostRoot"] = str(Path(site["root"]) / "prod/dashboard")
...@@ -107,6 +113,16 @@ def stage():...@@ -107,6 +113,16 @@ def stage():
107 saved = {"sourceId": "dashboard", "tasks": ["app"], "inputs": {}, "mount": str(root),113 saved = {"sourceId": "dashboard", "tasks": ["app"], "inputs": {}, "mount": str(root),
108 "clone": site["pool"] + "/staging/" + identity, "uid": snowglobe.identity("dashboard"),114 "clone": site["pool"] + "/staging/" + identity, "uid": snowglobe.identity("dashboard"),
109 "stageIsolation": "fresh"} if created else metadata(identity)115 "stageIsolation": "fresh"} if created else metadata(identity)
116 if computer:
117 saved["computer"] = computer
118 host_environment = shlex.split(snowglobe.command("systemctl", "show", "snowglobe-host", "--property=Environment", "--value", capture=True).stdout)
119 host_path = next(value for value in host_environment if value.startswith("PATH="))
120 mac = None
121 if saved.get("computer"):
122 configured = next((value.partition("=")[2] for value in host_environment if value.startswith("SNOWGLOBE_MAC_VM=")), "null")
123 mac = json.loads(configured)
124 if not mac or mac["name"] != saved["computer"]:
125 raise ValueError("Choose the configured managed Mac VM for this preview.")
110 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]126 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]
111 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"127 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"
112 image = subprocess.run([*nix, "eval", "--raw", package, "--apply", 'image: "${image.imageName}:${image.imageTag}"'],128 image = subprocess.run([*nix, "eval", "--raw", package, "--apply", 'image: "${image.imageName}:${image.imageTag}"'],
...@@ -166,13 +182,20 @@ def stage():...@@ -166,13 +182,20 @@ def stage():
166 *["--env=" + key + "=" + value for key, value in env.items()], image, "--preview-account", capture=True)182 *["--env=" + key + "=" + value for key, value in env.items()], image, "--preview-account", capture=True)
167 snowglobe.write_private(root / "access.json", imported.stdout)183 snowglobe.write_private(root / "access.json", imported.stdout)
168 runtime = "/run/snowglobe-preview/" + identity184 runtime = "/run/snowglobe-preview/" + identity
169 host_environment = snowglobe.command("systemctl", "show", "snowglobe-host", "--property=Environment", "--value", capture=True).stdout185 computer_environment = []
170 host_path = next(value for value in shlex.split(host_environment) if value.startswith("PATH="))186 if mac:
187 with sqlite3.connect(f"file:{root / 'data/accounts.sqlite'}?mode=ro", uri=True) as accounts:
188 owner = accounts.execute("SELECT id FROM users WHERE username='preview'").fetchone()
189 if not owner:
190 raise ValueError("The preview account is unavailable.")
191 mac["owner"] = owner[0]
192 computer_environment.append("--setenv=SNOWGLOBE_MAC_VM=" + json.dumps(mac))
171 host_python = snowglobe.command(*nix, "build", "--no-link", "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip()193 host_python = snowglobe.command(*nix, "build", "--no-link", "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip()
172 subprocess.run(["systemctl", "stop", "snowglobe-preview-" + identity], capture_output=True)194 subprocess.run(["systemctl", "stop", "snowglobe-preview-" + identity], capture_output=True)
173 snowglobe.command("systemd-run", "--collect", "--quiet", "--unit=snowglobe-preview-" + identity,195 snowglobe.command("systemd-run", "--collect", "--quiet", "--unit=snowglobe-preview-" + identity,
174 "--property=Restart=on-failure", "--property=MemoryMax=256M", "--property=TasksMax=32",196 "--property=Restart=on-failure", "--property=MemoryMax=256M", "--property=TasksMax=32",
175 "--setenv=" + host_path, "--setenv=SNOWGLOBE_DOMAIN=" + site["domain"],197 "--setenv=" + host_path, "--setenv=SNOWGLOBE_DOMAIN=" + site["domain"],
198 *computer_environment,
176 host_python + "/bin/python3", str(Path(__file__).resolve()), "--serve", identity)199 host_python + "/bin/python3", str(Path(__file__).resolve()), "--serve", identity)
177 for _ in range(100):200 for _ in range(100):
178 if Path(runtime, "host.sock").exists():201 if Path(runtime, "host.sock").exists():
tools/deploy.py+5
...@@ -163,6 +163,7 @@ def upload(main=False):...@@ -163,6 +163,7 @@ def upload(main=False):
163def main():163def main():
164 parser = argparse.ArgumentParser(description="Preview working changes and deploy main")164 parser = argparse.ArgumentParser(description="Preview working changes and deploy main")
165 parser.add_argument("mode", choices=["stage", "publish", "prod", "rollback", "history", "backups", "data-restore", "bootstrap", "allocate", "destroy", "secrets"])165 parser.add_argument("mode", choices=["stage", "publish", "prod", "rollback", "history", "backups", "data-restore", "bootstrap", "allocate", "destroy", "secrets"])
166 parser.add_argument("--computer", help="Give a dashboard preview access to this managed Mac VM")
166 parser.add_argument("target", nargs="?")167 parser.add_argument("target", nargs="?")
167 parser.add_argument("--env", action="append", default=[])168 parser.add_argument("--env", action="append", default=[])
168 parser.add_argument("--file", type=Path)169 parser.add_argument("--file", type=Path)
...@@ -170,6 +171,8 @@ def main():...@@ -170,6 +171,8 @@ def main():
170 parser.add_argument("--backup")171 parser.add_argument("--backup")
171 parser.add_argument("--discard-writes", action="store_true")172 parser.add_argument("--discard-writes", action="store_true")
172 args = parser.parse_args()173 args = parser.parse_args()
174 if args.computer and (args.mode != "stage" or args.target != "dashboard" or not NAME.fullmatch(args.computer)):
175 parser.error("--computer requires stage dashboard and a VM name")
173 if args.mode in {"stage", "allocate", "destroy", "secrets", "data-restore"} and (not args.target or not NAME.fullmatch(args.target)):176 if args.mode in {"stage", "allocate", "destroy", "secrets", "data-restore"} and (not args.target or not NAME.fullmatch(args.target)):
174 parser.error(f"{args.mode} requires a service or stage ID")177 parser.error(f"{args.mode} requires a service or stage ID")
175 if args.mode == "rollback" and args.target and not RELEASE_ID.fullmatch(args.target):178 if args.mode == "rollback" and args.target and not RELEASE_ID.fullmatch(args.target):
...@@ -202,6 +205,8 @@ def main():...@@ -202,6 +205,8 @@ def main():
202 if args.mode == "stage":205 if args.mode == "stage":
203 release = upload()206 release = upload()
204 overrides = "".join(f" --env {shlex.quote(value)}" for value in args.env)207 overrides = "".join(f" --env {shlex.quote(value)}" for value in args.env)
208 if args.computer:
209 overrides += " --computer " + shlex.quote(args.computer)
205 run_logged("stage", args.target, f"python3 {REMOTE}/releases/{release}/tools/snowglobe.py stage {args.target}{overrides}")210 run_logged("stage", args.target, f"python3 {REMOTE}/releases/{release}/tools/snowglobe.py stage {args.target}{overrides}")
206 elif args.mode == "secrets":211 elif args.mode == "secrets":
207 release = upload()212 release = upload()
tools/install-mac-computer.py created+41
...@@ -0,0 +1,41 @@
1#!/usr/bin/env python3
2"""Install computer-use support in the existing managed Mac guest and bridge."""
3from importlib import import_module
4import json
5import os
6from pathlib import Path
7import tempfile
8
9vm = import_module("mac-agent-vm")
10root = Path(__file__).resolve().parent
11identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()
12print("Installing guest tools in " + identity, flush=True)
13source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}
14vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", '''
15import json, pathlib, subprocess, sys, tempfile
16files = json.load(sys.stdin)
17with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
18 root = pathlib.Path(temporary)
19 for name, content in files.items():
20 (root / name).write_text(content)
21 subprocess.run(["/usr/bin/swiftc", "-O", str(root / "mac-agent-gui.swift"), "-o", str(root / "agent-gui")], check=True)
22 subprocess.run(["sudo", "-n", "mkdir", "-p", "/usr/local/libexec"], check=True)
23 for source, destination in [("mac-computer.py", "/usr/local/libexec/snowglobe-computer.py"), ("agent-gui", "/usr/local/bin/agent-gui")]:
24 subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / source), destination], check=True)
25''', input=json.dumps(source).encode(), timeout=180)
26for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:
27 target = vm.ROOT / "runtime/control" / name
28 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:
29 pending = Path(outgoing.name)
30 outgoing.write((root / name).read_bytes())
31 try:
32 pending.chmod(target.stat().st_mode & 0o777)
33 os.replace(pending, target)
34 finally:
35 pending.unlink(missing_ok=True)
36result = vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
37 input=b'{"action":"status"}', capture_output=True, timeout=15)
38value = json.loads(result.stdout)
39if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]):
40 raise SystemExit("The guest needs computer-use permissions; check its System Settings.")
41print(json.dumps(value))
tools/mac-agent-gui.swift+4-1
...@@ -81,7 +81,10 @@ case "screenshot":...@@ -81,7 +81,10 @@ case "screenshot":
81 else { fail("Could not create the output PNG.") }81 else { fail("Could not create the output PNG.") }
82 CGImageDestinationAddImage(destination, image, nil)82 CGImageDestinationAddImage(destination, image, nil)
83 guard CGImageDestinationFinalize(destination) else { fail("Could not write the output PNG.") }83 guard CGImageDestinationFinalize(destination) else { fail("Could not write the output PNG.") }
84 output(["width": image.width, "height": image.height, "path": arguments[1]])84 let bounds = CGDisplayBounds(CGMainDisplayID())
85 output(["width": image.width, "height": image.height, "path": arguments[1],
86 "bounds": [bounds.origin.x, bounds.origin.y, bounds.width, bounds.height],
87 "scale": [Double(image.width) / bounds.width, Double(image.height) / bounds.height]])
85case "tree", "press":88case "tree", "press":
86 guard AXIsProcessTrusted() else { fail("Accessibility permission is required.") }89 guard AXIsProcessTrusted() else { fail("Accessibility permission is required.") }
87 let app: AXUIElement90 let app: AXUIElement
tools/mac-agent-vm.md+34-3
...@@ -78,9 +78,10 @@ Snow Globe connects to the Mac's existing SSH service with a dedicated key at...@@ -78,9 +78,10 @@ Snow Globe connects to the Mac's existing SSH service with a dedicated key at
78`/var/lib/snowglobe/mac-vm/ssh_key` and a pinned host key in the adjacent78`/var/lib/snowglobe/mac-vm/ssh_key` and a pinned host key in the adjacent
79`known_hosts`. Both are root-only. The corresponding Mac `authorized_keys`79`known_hosts`. Both are root-only. The corresponding Mac `authorized_keys`
80entry uses `restrict,command=` to invoke `mac-vm-bridge.py`; it grants no shell,80entry uses `restrict,command=` to invoke `mac-vm-bridge.py`; it grants no shell,
81forwarding, PTY, arbitrary VM selection, or arbitrary guest command. Deploy the81forwarding, PTY, or arbitrary VM selection. Its computer operation runs commands
82bridge and `mac-agent-vm.py` together under the VM home's `runtime/control` and82inside the fixed guest. Deploy the bridge and `mac-agent-vm.py` together under
83keep that forced command pointed there, independent of an agent session.83the VM home's `runtime/control` and keep that forced command pointed there,
84independent of an agent session.
8485
85The existing host sshd provides supervision. Each console connection creates86The existing host sshd provides supervision. Each console connection creates
86a fresh, pinned guest SSH tunnel, authenticates Screen Sharing on the Mac,87a fresh, pinned guest SSH tunnel, authenticates Screen Sharing on the Mac,
...@@ -102,6 +103,36 @@ video stream without reconnecting. A deliberately closed viewer connection...@@ -102,6 +103,36 @@ video stream without reconnecting. A deliberately closed viewer connection
102also recovered without restarting the guest. The idle legacy tailnet relay103also recovered without restarting the guest. The idle legacy tailnet relay
103was retired; the actively used loopback recovery console was preserved.104was retired; the actively used loopback recovery console was preserved.
104105
106## Computer MCP
107
108The `computer` MCP catalog uses the dashboard's OAuth flow. Grants select VMs
109owned by the account; every call rechecks the current owner, selected VM, and
110`computer:read` or `computer:control` scope. Infrastructure administrators do
111not bypass ownership. Read access provides status, screenshots, and AX trees;
112control also runs bounded zsh scripts with `agent-gui` input primitives and
113optional screenshots. The guest's passwordless sudo permits software setup.
114This managed devbox remains persistent.
115
116Install from this Mac while the guest is running:
117
118```sh
119python3 tools/install-mac-computer.py
120python3 tools/deploy.py stage dashboard --computer m3-devbox
121```
122
123The installer compiles the GUI helper in the guest, installs the stdin/stdout
124worker, refreshes the restricted host bridge, and checks permissions. The
125worker serializes operations, caps command output, and kills the command's
126process group on timeout. Commands deliberately detached into another session
127can outlive a call; this is a development shell, not a process sandbox.
128Screenshot pixels include display bounds and scale for point-based input.
129
130Dashboard previews have no computer access by default. `--computer` explicitly
131attaches the real managed guest to the preview account; subsequent staging
132updates retain that attachment. Only the preview host's configuration remaps
133ownership. Its credentials grant access to the live guest, so keep them private.
134Destroying the preview removes its access. Production ownership is unchanged.
135
105## Guest access136## Guest access
106137
107`~/.local/bin/code-vm` links to the installed `runtime/control/code-vm` under138`~/.local/bin/code-vm` links to the installed `runtime/control/code-vm` under
tools/mac-computer-test.py created+78
...@@ -0,0 +1,78 @@
1#!/usr/bin/env python3
2"""Disposable command, timeout, output-bound and protocol tests."""
3from importlib import import_module
4import os
5import signal
6import subprocess
7import tempfile
8import unittest
9from pathlib import Path
10from unittest.mock import patch
11
12worker = import_module("mac-computer")
13bridge = import_module("mac-vm-bridge")
14
15
16class ComputerTests(unittest.TestCase):
17 def run_script(self, script, timeout=3000):
18 return worker.execute({"action": "exec", "script": script, "timeout_ms": timeout, "screenshot": False})
19
20 def test_commands_preserve_unicode_exit_status_and_limit_output(self):
21 result = self.run_script("printf 'Clover 🦊 日本語'; printf 'diagnostic' >&2; exit 7")
22 self.assertEqual(result, {"exit": 7, "stdout": "Clover 🦊 日本語", "stderr": "diagnostic"})
23 result = self.run_script("/usr/bin/python3 -c 'print(\"x\" * 200000)'")
24 self.assertEqual(len(result["stdout"]), 65536)
25 self.assertEqual(result["truncated"], ["stdout"])
26 self.assertEqual(result["exit"], 0)
27
28 def test_timeout_kills_the_script_group(self):
29 killpg = os.killpg
30 def cleanup(args, **kwargs):
31 self.assertEqual(args[:5], ["/usr/bin/sudo", "-n", "/bin/kill", "-KILL", "--"])
32 killpg(-int(args[-1]), signal.SIGKILL)
33 return subprocess.CompletedProcess(args, 0)
34 with patch.object(worker.subprocess, "run", side_effect=cleanup), \
35 patch.object(worker.os, "killpg", side_effect=PermissionError):
36 result = self.run_script("sleep 30 &\nprintf '%s' $!\nwait", 250)
37 self.assertTrue(result["timed_out"])
38 self.assertEqual(result["exit"], -signal.SIGKILL)
39 pid = int(result["stdout"])
40 state = subprocess.run(["ps", "-p", str(pid), "-o", "stat="], capture_output=True, text=True).stdout.strip()
41 self.assertTrue(not state or state.startswith("Z"), state)
42
43 def test_delayed_child_output_is_collected(self):
44 result = self.run_script("(sleep .3; printf 'late child') &")
45 self.assertEqual(result, {"exit": 0, "stdout": "late child", "stderr": ""})
46
47 def test_capture_failure_preserves_command_result(self):
48 for failure in [subprocess.TimeoutExpired("capture", 15), OSError("capture failed")]:
49 with patch.object(worker.subprocess, "run", side_effect=failure):
50 result = worker.execute({"action": "exec", "script": "printf completed; exit 7", "timeout_ms": 3000, "screenshot": True})
51 self.assertEqual(result["exit"], 7)
52 self.assertEqual(result["stdout"], "completed")
53 self.assertIn("capture_error", result)
54
55 def test_invalid_requests_never_run_commands(self):
56 requests = [[], {"action": []}, {"action": "status", "command": "id"},
57 {"action": "ui", "pid": True}, {"action": "ui", "pid": -1}]
58 for field, value in [("script", ""), ("script", "a" * 65537), ("timeout_ms", True),
59 ("timeout_ms", 180001), ("screenshot", "yes")]:
60 requests.append({"action": "exec", "script": "id", "timeout_ms": 1000, "screenshot": False, field: value})
61 with patch.object(worker.subprocess, "Popen") as start:
62 for request in requests:
63 with self.subTest(request=str(request)[:100]), self.assertRaises(ValueError):
64 worker.execute(request)
65 start.assert_not_called()
66
67 def test_bridge_bounds_guest_output_and_rejects_nonobjects(self):
68 with tempfile.TemporaryDirectory() as directory:
69 tart = Path(directory) / "tart"
70 for output, message in [("print('x' * (17 * 1024 * 1024))", "too large"), ("print('[]')", "incomplete")]:
71 tart.write_text("#!/usr/bin/python3\n" + output + "\n")
72 tart.chmod(0o700)
73 with patch.object(bridge.vm, "TART", tart), self.assertRaisesRegex(ValueError, message):
74 bridge.computer({"action": "status"})
75
76
77if __name__ == "__main__":
78 unittest.main()
tools/mac-computer.py created+135
...@@ -0,0 +1,135 @@
1#!/usr/bin/env python3
2"""Computer operations in the logged-in Mac guest, over stdin/stdout."""
3import base64
4import fcntl
5import json
6import os
7from pathlib import Path
8import selectors
9import signal
10import subprocess
11import sys
12import tempfile
13import time
14
15GUI = "/usr/local/bin/agent-gui"
16
17
18def execute(request):
19 if not isinstance(request, dict):
20 raise ValueError("Send a computer operation.")
21 action = request.get("action")
22 fields = {"status": {"action"}, "shot": {"action"}, "ui": {"action", "pid"},
23 "exec": {"action", "script", "timeout_ms", "screenshot"}}
24 if not isinstance(action, str) or action not in fields or set(request) != fields[action]:
25 raise ValueError("Use the fields listed for this computer operation.")
26 if action == "ui" and (request["pid"] is not None and (type(request["pid"]) is not int or request["pid"] <= 0)):
27 raise ValueError("Choose a positive application PID, or omit it for the active app.")
28 if action == "exec":
29 if not isinstance(request["script"], str) or not 1 <= len(request["script"].encode()) <= 65536:
30 raise ValueError("Provide a script of at most 64 KiB.")
31 if type(request["timeout_ms"]) is not int or not 1 <= request["timeout_ms"] <= 180000:
32 raise ValueError("Choose a timeout between 1 and 180000 milliseconds.")
33 if type(request["screenshot"]) is not bool:
34 raise ValueError("Choose whether to return a screenshot.")
35 if action == "status":
36 result = subprocess.run([GUI, "status"], capture_output=True, timeout=10, check=True)
37 return {"permissions": json.loads(result.stdout), "hostname": os.uname().nodename,
38 "platform": "macos", "script": "zsh", "max_timeout_ms": 180000}
39 if action == "ui":
40 args = [GUI, "tree"] + ([] if request["pid"] is None else [str(request["pid"])])
41 result = subprocess.run(args, capture_output=True, timeout=15, check=True)
42 if len(result.stdout) > 2 * 1024 * 1024:
43 raise ValueError("The UI tree is too large. Select an application PID.")
44 return {"tree": json.loads(result.stdout)}
45 with tempfile.TemporaryDirectory(prefix="snowglobe-computer-") as directory:
46 reply = {}
47 if action == "exec":
48 script = Path(directory) / "script"
49 script.write_text(request["script"])
50 with script.open("rb") as source, selectors.DefaultSelector() as selector:
51 process = subprocess.Popen(["/bin/zsh", "-s"], stdin=source,
52 stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
53 streams = {"stdout": bytearray(), "stderr": bytearray()}
54 truncated = []
55 for name in streams:
56 stream = getattr(process, name)
57 os.set_blocking(stream.fileno(), False)
58 selector.register(stream, selectors.EVENT_READ, name)
59 deadline = time.monotonic() + request["timeout_ms"] / 1000
60 try:
61 while True:
62 if time.monotonic() >= deadline:
63 reply["timed_out"] = True
64 break
65 events = selector.select(min(.1, max(0, deadline - time.monotonic())))
66 for key, _ in events:
67 data = os.read(key.fd, 65536)
68 if not data:
69 selector.unregister(key.fileobj)
70 continue
71 output = streams[key.data]
72 remaining = 65536 - len(output)
73 output.extend(data[:remaining])
74 if len(data) > remaining and key.data not in truncated:
75 truncated.append(key.data)
76 if process.poll() is not None and not selector.get_map():
77 break
78 finally:
79 if process.poll() is None or reply.get("timed_out"):
80 try:
81 cleanup = subprocess.run(["/usr/bin/sudo", "-n", "/bin/kill", "-KILL", "--", "-" + str(process.pid)],
82 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
83 if cleanup.returncode:
84 reply["cleanup_error"] = "Privileged cleanup failed. Check for remaining child processes."
85 except (OSError, subprocess.SubprocessError):
86 reply["cleanup_error"] = "Privileged cleanup failed. Check for remaining child processes."
87 try:
88 os.killpg(process.pid, signal.SIGKILL)
89 except (ProcessLookupError, PermissionError):
90 pass
91 process.wait()
92 process.stdout.close()
93 process.stderr.close()
94 reply.update(exit=process.returncode, **{k: bytes(v).decode("utf-8", "replace") for k, v in streams.items()})
95 if truncated:
96 reply["truncated"] = truncated
97 if action == "shot" or request.get("screenshot"):
98 shot = Path(directory) / "screen.png"
99 try:
100 result = subprocess.run([GUI, "screenshot", str(shot)], capture_output=True, timeout=15, check=True)
101 if shot.stat().st_size > 8 * 1024 * 1024:
102 reply["capture_error"] = "The screenshot exceeds 8 MiB. Reduce the guest display resolution."
103 else:
104 reply.update(json.loads(result.stdout))
105 reply.pop("path", None)
106 reply["png"] = base64.b64encode(shot.read_bytes()).decode("ascii")
107 except subprocess.TimeoutExpired:
108 reply["capture_error"] = "Screen capture timed out. Check the guest's screen recording permission."
109 except (OSError, ValueError, subprocess.SubprocessError):
110 reply["capture_error"] = "Screen capture failed. Check the guest's screen recording permission."
111 return reply
112
113
114def main():
115 raw = sys.stdin.buffer.read(524289)
116 if len(raw) > 524288:
117 raise ValueError("The computer request is too large.")
118 request = json.loads(raw)
119 lock_path = Path.home() / "Library/Caches/net.paperclover.computer.lock"
120 descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
121 with os.fdopen(descriptor, "w") as lock:
122 try:
123 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
124 except BlockingIOError:
125 raise ValueError("Another computer operation is running. Wait for it to finish.")
126 return execute(request)
127
128
129if __name__ == "__main__":
130 try:
131 print(json.dumps(main(), ensure_ascii=True))
132 except ValueError as error:
133 print(json.dumps({"error": str(error)}))
134 except (OSError, subprocess.SubprocessError):
135 print(json.dumps({"error": "The guest operation failed. Check its arguments, permissions, and connection."}))
tools/mac-vm-bridge.py+53
...@@ -4,10 +4,13 @@ import fcntl...@@ -4,10 +4,13 @@ import fcntl
4from importlib import import_module4from importlib import import_module
5import json5import json
6import os6import os
7import selectors
7import signal8import signal
8import struct9import struct
9import subprocess10import subprocess
10import sys11import sys
12import tempfile
13import time
1114
12vm = import_module("mac-agent-vm")15vm = import_module("mac-agent-vm")
1316
...@@ -41,6 +44,52 @@ def respond(value):...@@ -41,6 +44,52 @@ def respond(value):
41 sys.stdout.buffer.flush()44 sys.stdout.buffer.flush()
4245
4346
47def computer(request):
48 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
49 source.write(json.dumps(request).encode())
50 source.seek(0)
51 process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/usr/bin/python3",
52 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
53 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
54 output = bytearray()
55 errors = 0
56 selector.register(process.stdout, selectors.EVENT_READ, True)
57 selector.register(process.stderr, selectors.EVENT_READ, False)
58 deadline = time.monotonic() + 205
59 try:
60 while selector.get_map():
61 remaining = deadline - time.monotonic()
62 if remaining <= 0:
63 raise ValueError("The guest command timed out. Check its status before retrying.")
64 for key, _ in selector.select(remaining):
65 data = os.read(key.fd, 65536)
66 if not data:
67 selector.unregister(key.fileobj)
68 elif key.data:
69 output.extend(data)
70 else:
71 errors += len(data)
72 if len(output) > 16 * 1024 * 1024 or errors > 65536:
73 raise ValueError("The computer response is too large.")
74 if process.wait(timeout=max(.001, deadline - time.monotonic())):
75 raise ValueError("The Mac guest did not answer. Check its agent and retry.")
76 value = json.loads(output)
77 if not isinstance(value, dict):
78 raise ValueError("The Mac guest returned an incomplete response.")
79 if "error" in value:
80 raise ValueError(str(value["error"]))
81 return value
82 finally:
83 if process.poll() is None:
84 try:
85 os.killpg(process.pid, signal.SIGKILL)
86 except ProcessLookupError:
87 pass
88 process.wait()
89 process.stdout.close()
90 process.stderr.close()
91
92
44def lifecycle(action):93def lifecycle(action):
45 process = subprocess.Popen([sys.executable, vm.__file__, action], stdout=subprocess.DEVNULL,94 process = subprocess.Popen([sys.executable, vm.__file__, action], stdout=subprocess.DEVNULL,
46 start_new_session=True)95 start_new_session=True)
...@@ -77,6 +126,10 @@ def main():...@@ -77,6 +126,10 @@ def main():
77 vm.tart("exec", "-i", vm.NAME, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",126 vm.tart("exec", "-i", vm.NAME, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",
78 input=value.encode(), capture_output=True, timeout=15)127 input=value.encode(), capture_output=True, timeout=15)
79 respond({"value": None})128 respond({"value": None})
129 elif action == "computer" and set(request) == {"action", "request"}:
130 if not isinstance(request["request"], dict):
131 raise ValueError("Send a computer operation.")
132 respond({"value": computer(request["request"])})
80 elif action == "console" and set(request) == {"action"}:133 elif action == "console" and set(request) == {"action"}:
81 with vm.guest_screen() as upstream:134 with vm.guest_screen() as upstream:
82 respond({"value": None})135 respond({"value": None})
tools/mac-vms.py+5-3
...@@ -9,7 +9,7 @@ import tempfile...@@ -9,7 +9,7 @@ import tempfile
99
1010
11CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))11CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))
12CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard"]12CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard", "computer"]
13CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json"))13CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json"))
1414
1515
...@@ -42,7 +42,7 @@ def connect(request, timeout=10):...@@ -42,7 +42,7 @@ def connect(request, timeout=10):
42 return data42 return data
4343
44 size, = struct.unpack("!I", read(4))44 size, = struct.unpack("!I", read(4))
45 if size > 65536:45 if size > (16 * 1024 * 1024 if request["action"] == "computer" else 65536):
46 raise ValueError("The Mac response is too large.")46 raise ValueError("The Mac response is too large.")
47 reply = json.loads(read(size))47 reply = json.loads(read(size))
48 if "error" in reply:48 if "error" in reply:
...@@ -113,10 +113,12 @@ def handle(action, payload):...@@ -113,10 +113,12 @@ def handle(action, payload):
113 return None113 return None
114 if action == "console":114 if action == "console":
115 return {"remote": True}115 return {"remote": True}
116 if action == "act" and payload["action"] in CAPABILITIES:116 if action == "act" and payload["action"] in {"start", "shutdown", "reboot", "suspend", "resume"}:
117 request = {"action": payload["action"]}117 request = {"action": payload["action"]}
118 elif action == "clipboard":118 elif action == "clipboard":
119 request = {"action": "clipboard", "text": payload["text"]}119 request = {"action": "clipboard", "text": payload["text"]}
120 elif action == "computer":
121 request = {"action": "computer", "request": payload["request"]}
120 else:122 else:
121 raise ValueError("This operation is unavailable for this Mac VM.")123 raise ValueError("This operation is unavailable for this Mac VM.")
122 with connect(request, timeout=220) as (value, _):124 with connect(request, timeout=220) as (value, _):
tools/snowglobe.py+4-1
...@@ -950,6 +950,7 @@ def main():...@@ -950,6 +950,7 @@ def main():
950 ],950 ],
951 )951 )
952 parser.add_argument("name", nargs="?")952 parser.add_argument("name", nargs="?")
953 parser.add_argument("--computer")
953 parser.add_argument("--base-domain")954 parser.add_argument("--base-domain")
954 parser.add_argument("--root")955 parser.add_argument("--root")
955 parser.add_argument("--pool")956 parser.add_argument("--pool")
...@@ -957,10 +958,12 @@ def main():...@@ -957,10 +958,12 @@ def main():
957 parser.add_argument("--env", action="append", default=[])958 parser.add_argument("--env", action="append", default=[])
958 parser.add_argument("--key", action="append", default=[])959 parser.add_argument("--key", action="append", default=[])
959 args = parser.parse_args()960 args = parser.parse_args()
961 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
962 parser.error("--computer requires stage dashboard")
960 if args.mode == "stage" and args.name == "dashboard":963 if args.mode == "stage" and args.name == "dashboard":
961 if args.env or args.base_domain or args.root or args.pool or args.media_root:964 if args.env or args.base_domain or args.root or args.pool or args.media_root:
962 parser.error("dashboard staging uses the host configuration")965 parser.error("dashboard staging uses the host configuration")
963 __import__("dashboard-stage").stage()966 __import__("dashboard-stage").stage(args.computer)
964 return967 return
965 if args.mode == "destroy" and args.name and NAME.fullmatch(args.name):968 if args.mode == "destroy" and args.name and NAME.fullmatch(args.name):
966 saved = STATE / "stages" / f"{args.name}.json"969 saved = STATE / "stages" / f"{args.name}.json"
tools/vms.py+3
...@@ -77,6 +77,7 @@ ACTION_FIELDS = {...@@ -77,6 +77,7 @@ ACTION_FIELDS = {
77 "library": None, "media": {"name", "image"},77 "library": None, "media": {"name", "image"},
78 "preset": {"name", "id", "os", "description"},78 "preset": {"name", "id", "os", "description"},
79 "clipboard": {"name", "text"},79 "clipboard": {"name", "text"},
80 "computer": {"name", "request"},
80 "console": {"name"}, "serial": {"name"}, "guest": {"name"}, "owner": {"name"}, "access": {"name"}, "upload": {"volume", "size"},81 "console": {"name"}, "serial": {"name"}, "guest": {"name"}, "owner": {"name"}, "access": {"name"}, "upload": {"volume", "size"},
81}82}
8283
...@@ -164,6 +165,8 @@ def validate(action, payload):...@@ -164,6 +165,8 @@ def validate(action, payload):
164 if "name" not in payload:165 if "name" not in payload:
165 raise ValueError("Enter a VM name.")166 raise ValueError("Enter a VM name.")
166 ensure_name(payload["name"])167 ensure_name(payload["name"])
168 if action == "computer" and not isinstance(payload["request"], dict):
169 raise ValueError("Send a computer operation.")
167 if "description" in payload and (not isinstance(payload["description"], str) or len(payload["description"]) > 200):170 if "description" in payload and (not isinstance(payload["description"], str) or len(payload["description"]) > 200):
168 raise ValueError("Keep the description under 200 characters.")171 raise ValueError("Keep the description under 200 characters.")
169 for field in ("autostart", "start", "disks"):172 for field in ("autostart", "start", "disks"):