| author | |
| committer | |
| log | bc97ccbb76c079f855e64b943306227f3cf9e5ce |
| tree | 561d16f5552668400a13321e5e2adb402f9a9cb9 |
| parent | 3adad9767eb19ab651b35e1f76b7f4a358df0225 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
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-astra21 files changed, 573 insertions(+), 27 deletions(-)
dashboard/src/computer.rs created+141| ... | ... | @@ -0,0 +1,141 @@ |
| 1 | use crate::*; | |
| 2 | use 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 | ||
| 12 | pub 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 | ||
| 23 | fn 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)] | |
| 38 | struct Computer; | |
| 39 | impl 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 | ||
| 116 | pub fn router(app: Arc<App>) -> Router { | |
| 117 | mcp::router(app, "computer", || Ok(Computer)) | |
| 118 | } | |
| 119 | ||
| 120 | #[cfg(test)] | |
| 121 | mod 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 | 34 | Some("vm.create" | "vm.media" | "vm.preset") |
| 35 | 35 | ) { |
| 36 | 36 | 910 |
| 37 | } else if request["operation"] == "vm.act" { | |
| 37 | } else if matches!(request["operation"].as_str(), Some("vm.act" | "vm.computer")) { | |
| 38 | 38 | 240 |
| 39 | 39 | } else if request["operation"] == "copyparty.manage" { |
| 40 | 40 | 310 |
dashboard/src/main.rs+2| ... | ... | @@ -4,6 +4,7 @@ mod auth; |
| 4 | 4 | mod atproto; |
| 5 | 5 | mod identity; |
| 6 | 6 | mod cache; |
| 7 | mod computer; | |
| 7 | 8 | mod core; |
| 8 | 9 | mod deploys; |
| 9 | 10 | mod files; |
| ... | ... | @@ -593,6 +594,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 593 | 594 | .nest_service("/assets", ServeDir::new(format!("{dist}/assets"))) |
| 594 | 595 | .with_state(app.clone()) |
| 595 | 596 | .merge(observability::router(app.clone())) |
| 597 | .merge(computer::router(app.clone())) | |
| 596 | 598 | .merge(shale::router(app.clone())) |
| 597 | 599 | .merge(relay::router(app.clone())) |
| 598 | 600 | .fallback_service( |
dashboard/src/mcp.rs+8-1| ... | ... | @@ -8,6 +8,7 @@ use sha2::{Digest, Sha256}; |
| 8 | 8 | use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; |
| 9 | 9 | |
| 10 | 10 | const CATALOGS: &[(&str, &str, &[&str])] = &[ |
| 11 | ("computer", "Computers", &["computer:read", "computer:control", "offline_access"]), | |
| 11 | 12 | ( |
| 12 | 13 | "observability", |
| 13 | 14 | "Logs and traces", |
| ... | ... | @@ -499,6 +500,8 @@ pub(crate) fn active_owner(app: &App, grant: &Value) -> Result<bool> { |
| 499 | 500 | }; |
| 500 | 501 | Ok(profile["enabled"] == true |
| 501 | 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 | 505 | && (grant["resource"] != app.mcp.resource("observability") |
| 503 | 506 | || array(&profile["groups"]) |
| 504 | 507 | .iter() |
| ... | ... | @@ -794,6 +797,10 @@ pub async fn manage( |
| 794 | 797 | } |
| 795 | 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 | 804 | } else if consent_resource == app.mcp.resource("observability") |
| 798 | 805 | && array(&me["sections"]).iter().any(|s| s == "admin") |
| 799 | 806 | && array(&owner["groups"]) |
| ... | ... | @@ -1062,7 +1069,7 @@ mod tests { |
| 1062 | 1069 | json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await; |
| 1063 | 1070 | let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state", |
| 1064 | 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 | 1073 | for (catalog, _, allowed) in CATALOGS { |
| 1067 | 1074 | request.insert("resource".into(), fixture.store.resource(catalog)); |
| 1068 | 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 | 16 | import "./MCP.css"; |
| 17 | 17 | |
| 18 | 18 | const descriptions: Record<Catalog, string> = { |
| 19 | computer: "Inspect and control selected virtual machines, run commands, and install guest software.", | |
| 19 | 20 | shale: "Read and edit issues across your Shale repositories.", |
| 20 | 21 | agents: "Connect to Codex and Claude Code on your machines.", |
| 21 | 22 | observability: "Read logs and traces from your services.", |
| ... | ... | @@ -148,9 +149,16 @@ export function MCP(props: { me: Me }) { |
| 148 | 149 | </Show> |
| 149 | 150 | <section class="mcp-panel"><h2>Connected clients</h2> |
| 150 | 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><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 | <div class="mcp-actions"><button class="button small" disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button> | |
| 152 | <div class="mcp-client-list"><For each={connections()}>{(client) => { | |
| 153 | let editButton!: HTMLButtonElement; | |
| 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 | 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 | 163 | await parseResponse(api.mcp.connections[":id"].$delete({ param: { id: client.id } })); if (editing() === client.id) setEditing(""); await refetch(); toast("Connection revoked"); |
| 156 | 164 | } })}>Revoke</button></div> |
| ... | ... | @@ -164,11 +172,11 @@ export function MCP(props: { me: Me }) { |
| 164 | 172 | try { await parseResponse(api.mcp.connections[":id"].$post({ param: { id: client.id }, json: { resources: selection() } })); setEditing(""); await refetch(); } |
| 165 | 173 | catch (error) { toast(reason(error)); } |
| 166 | 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 | 176 | </Show>} |
| 169 | 177 | </Loaded> |
| 170 | 178 | </div></Show> |
| 171 | </article>}</For></div> | |
| 179 | </article>; }}</For></div> | |
| 172 | 180 | </Show> |
| 173 | 181 | </section> |
| 174 | 182 | </>}</Show> |
dashboard/web/pages/MCPAccess.tsx+2-2| ... | ... | @@ -10,7 +10,7 @@ export function MCPAccess(props: { |
| 10 | 10 | disabled: boolean; |
| 11 | 11 | }) { |
| 12 | 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 | 14 | <Show when={props.catalog === "shale"}> |
| 15 | 15 | <div class="mcp-access-modes"> |
| 16 | 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 | 28 | props.onChange(checked ? [...selected, resource.id] : selected.filter((id) => id !== resource.id)); |
| 29 | 29 | }}><span>{resource.name}<Show when={resource.description}><small class="muted">{resource.description}</small></Show></span></Checkbox> |
| 30 | 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 | 32 | </Show> |
| 33 | 33 | </fieldset>; |
| 34 | 34 | } |
dashboard/web/pages/MCPConsent.tsx+3-2| ... | ... | @@ -58,10 +58,11 @@ export function MCPConsent() { |
| 58 | 58 | </>}> |
| 59 | 59 | {(data) => <> |
| 60 | 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 | 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 | 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 | 66 | <Show when={data().scopes.includes("shale:write")}><p>Create issues, comment, and edit issue titles and status</p></Show> |
| 66 | 67 | <Show when={data().scopes.includes("sessions:write")}><p>Send messages, start chats, and interrupt turns</p></Show> |
| 67 | 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 | export type Catalog = "shale" | "agents" | "observability"; | |
| 1 | export type Catalog = "shale" | "agents" | "observability" | "computer"; | |
| 2 | 2 | export type Access = "all" | string[]; |
| 3 | 3 | export type Resources = { id: string; name: string; description?: string }[]; |
| 4 | 4 |
tools/dashboard-host.py+2-2| ... | ... | @@ -186,9 +186,9 @@ class Host: |
| 186 | 186 | vms.validate(action, payload) |
| 187 | 187 | except ValueError as error: |
| 188 | 188 | raise Rejected(str(error)) from error |
| 189 | if action == "clipboard": | |
| 189 | if action in {"clipboard", "computer"}: | |
| 190 | 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 | 192 | try: |
| 193 | 193 | return vms.mac_vms.handle(action, payload) |
| 194 | 194 | except ValueError as error: |
tools/dashboard-stage-test.py+11-1| ... | ... | @@ -34,7 +34,7 @@ class PreviewBoundary(unittest.TestCase): |
| 34 | 34 | return json.loads(sent[4:]), host |
| 35 | 35 | |
| 36 | 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 | 38 | with self.subTest(operation=operation): |
| 39 | 39 | response, host = self.call({"operation": operation}) |
| 40 | 40 | self.assertEqual(response["status"], 403) |
| ... | ... | @@ -53,6 +53,16 @@ class PreviewBoundary(unittest.TestCase): |
| 53 | 53 | with self.assertRaisesRegex(ValueError, "invalid dashboard stage"): |
| 54 | 54 | stage.metadata(identity) |
| 55 | 55 | |
| 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 | 66 | def test_file_operations_cannot_name_production_or_account_dataset(self): |
| 57 | 67 | dataset = "globe/staging/dashboard-preview-12345678" |
| 58 | 68 | host = stage.PreviewHost({"clone": dataset}) |
tools/dashboard-stage.py+27-4| ... | ... | @@ -9,6 +9,7 @@ import secrets |
| 9 | 9 | import shlex |
| 10 | 10 | import shutil |
| 11 | 11 | import socket |
| 12 | import sqlite3 | |
| 12 | 13 | import subprocess |
| 13 | 14 | import sys |
| 14 | 15 | import threading |
| ... | ... | @@ -35,6 +36,10 @@ class PreviewHost(boundary.Host): |
| 35 | 36 | |
| 36 | 37 | def handle(self, request): |
| 37 | 38 | 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 | 43 | if operation == "shale.access": |
| 39 | 44 | service = request.get("service", "") |
| 40 | 45 | if not re.fullmatch(r"shale-preview-[0-9a-f]{8}", service): |
| ... | ... | @@ -86,11 +91,12 @@ def serve(stage): |
| 86 | 91 | if not slots.acquire(blocking=False): |
| 87 | 92 | connection.close() |
| 88 | 93 | 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 | 96 | work.add_done_callback(lambda _: slots.release()) |
| 91 | 97 | |
| 92 | 98 | |
| 93 | def stage(): | |
| 99 | def stage(computer=None): | |
| 94 | 100 | snowglobe.token() |
| 95 | 101 | site = json.loads(snowglobe.command("pkl", "eval", "-f", "json", str(snowglobe.REPO / "config/site.pkl"), capture=True).stdout) |
| 96 | 102 | site["hostRoot"] = str(Path(site["root"]) / "prod/dashboard") |
| ... | ... | @@ -107,6 +113,16 @@ def stage(): |
| 107 | 113 | saved = {"sourceId": "dashboard", "tasks": ["app"], "inputs": {}, "mount": str(root), |
| 108 | 114 | "clone": site["pool"] + "/staging/" + identity, "uid": snowglobe.identity("dashboard"), |
| 109 | 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 | 126 | nix = ["nix", "--extra-experimental-features", "nix-command flakes"] |
| 111 | 127 | package = "path:" + str(snowglobe.REPO) + "#dashboard-image" |
| 112 | 128 | image = subprocess.run([*nix, "eval", "--raw", package, "--apply", 'image: "${image.imageName}:${image.imageTag}"'], |
| ... | ... | @@ -166,13 +182,20 @@ def stage(): |
| 166 | 182 | *["--env=" + key + "=" + value for key, value in env.items()], image, "--preview-account", capture=True) |
| 167 | 183 | snowglobe.write_private(root / "access.json", imported.stdout) |
| 168 | 184 | runtime = "/run/snowglobe-preview/" + identity |
| 169 | host_environment = snowglobe.command("systemctl", "show", "snowglobe-host", "--property=Environment", "--value", capture=True).stdout | |
| 170 | host_path = next(value for value in shlex.split(host_environment) if value.startswith("PATH=")) | |
| 185 | computer_environment = [] | |
| 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 | 193 | host_python = snowglobe.command(*nix, "build", "--no-link", "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip() |
| 172 | 194 | subprocess.run(["systemctl", "stop", "snowglobe-preview-" + identity], capture_output=True) |
| 173 | 195 | snowglobe.command("systemd-run", "--collect", "--quiet", "--unit=snowglobe-preview-" + identity, |
| 174 | 196 | "--property=Restart=on-failure", "--property=MemoryMax=256M", "--property=TasksMax=32", |
| 175 | 197 | "--setenv=" + host_path, "--setenv=SNOWGLOBE_DOMAIN=" + site["domain"], |
| 198 | *computer_environment, | |
| 176 | 199 | host_python + "/bin/python3", str(Path(__file__).resolve()), "--serve", identity) |
| 177 | 200 | for _ in range(100): |
| 178 | 201 | if Path(runtime, "host.sock").exists(): |
tools/deploy.py+5| ... | ... | @@ -163,6 +163,7 @@ def upload(main=False): |
| 163 | 163 | def main(): |
| 164 | 164 | parser = argparse.ArgumentParser(description="Preview working changes and deploy main") |
| 165 | 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 | 167 | parser.add_argument("target", nargs="?") |
| 167 | 168 | parser.add_argument("--env", action="append", default=[]) |
| 168 | 169 | parser.add_argument("--file", type=Path) |
| ... | ... | @@ -170,6 +171,8 @@ def main(): |
| 170 | 171 | parser.add_argument("--backup") |
| 171 | 172 | parser.add_argument("--discard-writes", action="store_true") |
| 172 | 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 | 176 | if args.mode in {"stage", "allocate", "destroy", "secrets", "data-restore"} and (not args.target or not NAME.fullmatch(args.target)): |
| 174 | 177 | parser.error(f"{args.mode} requires a service or stage ID") |
| 175 | 178 | if args.mode == "rollback" and args.target and not RELEASE_ID.fullmatch(args.target): |
| ... | ... | @@ -202,6 +205,8 @@ def main(): |
| 202 | 205 | if args.mode == "stage": |
| 203 | 206 | release = upload() |
| 204 | 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 | 210 | run_logged("stage", args.target, f"python3 {REMOTE}/releases/{release}/tools/snowglobe.py stage {args.target}{overrides}") |
| 206 | 211 | elif args.mode == "secrets": |
| 207 | 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.""" | |
| 3 | from importlib import import_module | |
| 4 | import json | |
| 5 | import os | |
| 6 | from pathlib import Path | |
| 7 | import tempfile | |
| 8 | ||
| 9 | vm = import_module("mac-agent-vm") | |
| 10 | root = Path(__file__).resolve().parent | |
| 11 | identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip() | |
| 12 | print("Installing guest tools in " + identity, flush=True) | |
| 13 | source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]} | |
| 14 | vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", ''' | |
| 15 | import json, pathlib, subprocess, sys, tempfile | |
| 16 | files = json.load(sys.stdin) | |
| 17 | with 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) | |
| 26 | for 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) | |
| 36 | result = 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) | |
| 38 | value = json.loads(result.stdout) | |
| 39 | if 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.") | |
| 41 | print(json.dumps(value)) |
tools/mac-agent-gui.swift+4-1| ... | ... | @@ -81,7 +81,10 @@ case "screenshot": |
| 81 | 81 | else { fail("Could not create the output PNG.") } |
| 82 | 82 | CGImageDestinationAddImage(destination, image, nil) |
| 83 | 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]]) | |
| 85 | 88 | case "tree", "press": |
| 86 | 89 | guard AXIsProcessTrusted() else { fail("Accessibility permission is required.") } |
| 87 | 90 | 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 | 78 | `/var/lib/snowglobe/mac-vm/ssh_key` and a pinned host key in the adjacent |
| 79 | 79 | `known_hosts`. Both are root-only. The corresponding Mac `authorized_keys` |
| 80 | 80 | entry uses `restrict,command=` to invoke `mac-vm-bridge.py`; it grants no shell, |
| 81 | forwarding, PTY, arbitrary VM selection, or arbitrary guest command. Deploy the | |
| 82 | bridge and `mac-agent-vm.py` together under the VM home's `runtime/control` and | |
| 83 | keep that forced command pointed there, independent of an agent session. | |
| 81 | forwarding, PTY, or arbitrary VM selection. Its computer operation runs commands | |
| 82 | inside the fixed guest. Deploy the bridge and `mac-agent-vm.py` together under | |
| 83 | the VM home's `runtime/control` and keep that forced command pointed there, | |
| 84 | independent of an agent session. | |
| 84 | 85 | |
| 85 | 86 | The existing host sshd provides supervision. Each console connection creates |
| 86 | 87 | a 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 | 103 | also recovered without restarting the guest. The idle legacy tailnet relay |
| 103 | 104 | was retired; the actively used loopback recovery console was preserved. |
| 104 | 105 | |
| 106 | ## Computer MCP | |
| 107 | ||
| 108 | The `computer` MCP catalog uses the dashboard's OAuth flow. Grants select VMs | |
| 109 | owned by the account; every call rechecks the current owner, selected VM, and | |
| 110 | `computer:read` or `computer:control` scope. Infrastructure administrators do | |
| 111 | not bypass ownership. Read access provides status, screenshots, and AX trees; | |
| 112 | control also runs bounded zsh scripts with `agent-gui` input primitives and | |
| 113 | optional screenshots. The guest's passwordless sudo permits software setup. | |
| 114 | This managed devbox remains persistent. | |
| 115 | ||
| 116 | Install from this Mac while the guest is running: | |
| 117 | ||
| 118 | ```sh | |
| 119 | python3 tools/install-mac-computer.py | |
| 120 | python3 tools/deploy.py stage dashboard --computer m3-devbox | |
| 121 | ``` | |
| 122 | ||
| 123 | The installer compiles the GUI helper in the guest, installs the stdin/stdout | |
| 124 | worker, refreshes the restricted host bridge, and checks permissions. The | |
| 125 | worker serializes operations, caps command output, and kills the command's | |
| 126 | process group on timeout. Commands deliberately detached into another session | |
| 127 | can outlive a call; this is a development shell, not a process sandbox. | |
| 128 | Screenshot pixels include display bounds and scale for point-based input. | |
| 129 | ||
| 130 | Dashboard previews have no computer access by default. `--computer` explicitly | |
| 131 | attaches the real managed guest to the preview account; subsequent staging | |
| 132 | updates retain that attachment. Only the preview host's configuration remaps | |
| 133 | ownership. Its credentials grant access to the live guest, so keep them private. | |
| 134 | Destroying the preview removes its access. Production ownership is unchanged. | |
| 135 | ||
| 105 | 136 | ## Guest access |
| 106 | 137 | |
| 107 | 138 | `~/.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.""" | |
| 3 | from importlib import import_module | |
| 4 | import os | |
| 5 | import signal | |
| 6 | import subprocess | |
| 7 | import tempfile | |
| 8 | import unittest | |
| 9 | from pathlib import Path | |
| 10 | from unittest.mock import patch | |
| 11 | ||
| 12 | worker = import_module("mac-computer") | |
| 13 | bridge = import_module("mac-vm-bridge") | |
| 14 | ||
| 15 | ||
| 16 | class 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 | ||
| 77 | if __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.""" | |
| 3 | import base64 | |
| 4 | import fcntl | |
| 5 | import json | |
| 6 | import os | |
| 7 | from pathlib import Path | |
| 8 | import selectors | |
| 9 | import signal | |
| 10 | import subprocess | |
| 11 | import sys | |
| 12 | import tempfile | |
| 13 | import time | |
| 14 | ||
| 15 | GUI = "/usr/local/bin/agent-gui" | |
| 16 | ||
| 17 | ||
| 18 | def 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 | ||
| 114 | def 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 | ||
| 129 | if __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 | 4 | from importlib import import_module |
| 5 | 5 | import json |
| 6 | 6 | import os |
| 7 | import selectors | |
| 7 | 8 | import signal |
| 8 | 9 | import struct |
| 9 | 10 | import subprocess |
| 10 | 11 | import sys |
| 12 | import tempfile | |
| 13 | import time | |
| 11 | 14 | |
| 12 | 15 | vm = import_module("mac-agent-vm") |
| 13 | 16 | |
| ... | ... | @@ -41,6 +44,52 @@ def respond(value): |
| 41 | 44 | sys.stdout.buffer.flush() |
| 42 | 45 | |
| 43 | 46 | |
| 47 | def 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 | ||
| 44 | 93 | def lifecycle(action): |
| 45 | 94 | process = subprocess.Popen([sys.executable, vm.__file__, action], stdout=subprocess.DEVNULL, |
| 46 | 95 | start_new_session=True) |
| ... | ... | @@ -77,6 +126,10 @@ def main(): |
| 77 | 126 | vm.tart("exec", "-i", vm.NAME, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy", |
| 78 | 127 | input=value.encode(), capture_output=True, timeout=15) |
| 79 | 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 | 133 | elif action == "console" and set(request) == {"action"}: |
| 81 | 134 | with vm.guest_screen() as upstream: |
| 82 | 135 | respond({"value": None}) |
tools/mac-vms.py+5-3| ... | ... | @@ -9,7 +9,7 @@ import tempfile |
| 9 | 9 | |
| 10 | 10 | |
| 11 | 11 | CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null")) |
| 12 | CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard"] | |
| 12 | CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard", "computer"] | |
| 13 | 13 | CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json")) |
| 14 | 14 | |
| 15 | 15 | |
| ... | ... | @@ -42,7 +42,7 @@ def connect(request, timeout=10): |
| 42 | 42 | return data |
| 43 | 43 | |
| 44 | 44 | size, = struct.unpack("!I", read(4)) |
| 45 | if size > 65536: | |
| 45 | if size > (16 * 1024 * 1024 if request["action"] == "computer" else 65536): | |
| 46 | 46 | raise ValueError("The Mac response is too large.") |
| 47 | 47 | reply = json.loads(read(size)) |
| 48 | 48 | if "error" in reply: |
| ... | ... | @@ -113,10 +113,12 @@ def handle(action, payload): |
| 113 | 113 | return None |
| 114 | 114 | if action == "console": |
| 115 | 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 | 117 | request = {"action": payload["action"]} |
| 118 | 118 | elif action == "clipboard": |
| 119 | 119 | request = {"action": "clipboard", "text": payload["text"]} |
| 120 | elif action == "computer": | |
| 121 | request = {"action": "computer", "request": payload["request"]} | |
| 120 | 122 | else: |
| 121 | 123 | raise ValueError("This operation is unavailable for this Mac VM.") |
| 122 | 124 | with connect(request, timeout=220) as (value, _): |
tools/snowglobe.py+4-1| ... | ... | @@ -950,6 +950,7 @@ def main(): |
| 950 | 950 | ], |
| 951 | 951 | ) |
| 952 | 952 | parser.add_argument("name", nargs="?") |
| 953 | parser.add_argument("--computer") | |
| 953 | 954 | parser.add_argument("--base-domain") |
| 954 | 955 | parser.add_argument("--root") |
| 955 | 956 | parser.add_argument("--pool") |
| ... | ... | @@ -957,10 +958,12 @@ def main(): |
| 957 | 958 | parser.add_argument("--env", action="append", default=[]) |
| 958 | 959 | parser.add_argument("--key", action="append", default=[]) |
| 959 | 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 | 963 | if args.mode == "stage" and args.name == "dashboard": |
| 961 | 964 | if args.env or args.base_domain or args.root or args.pool or args.media_root: |
| 962 | 965 | parser.error("dashboard staging uses the host configuration") |
| 963 | __import__("dashboard-stage").stage() | |
| 966 | __import__("dashboard-stage").stage(args.computer) | |
| 964 | 967 | return |
| 965 | 968 | if args.mode == "destroy" and args.name and NAME.fullmatch(args.name): |
| 966 | 969 | saved = STATE / "stages" / f"{args.name}.json" |
tools/vms.py+3| ... | ... | @@ -77,6 +77,7 @@ ACTION_FIELDS = { |
| 77 | 77 | "library": None, "media": {"name", "image"}, |
| 78 | 78 | "preset": {"name", "id", "os", "description"}, |
| 79 | 79 | "clipboard": {"name", "text"}, |
| 80 | "computer": {"name", "request"}, | |
| 80 | 81 | "console": {"name"}, "serial": {"name"}, "guest": {"name"}, "owner": {"name"}, "access": {"name"}, "upload": {"volume", "size"}, |
| 81 | 82 | } |
| 82 | 83 | |
| ... | ... | @@ -164,6 +165,8 @@ def validate(action, payload): |
| 164 | 165 | if "name" not in payload: |
| 165 | 166 | raise ValueError("Enter a VM name.") |
| 166 | 167 | ensure_name(payload["name"]) |
| 168 | if action == "computer" and not isinstance(payload["request"], dict): | |
| 169 | raise ValueError("Send a computer operation.") | |
| 167 | 170 | if "description" in payload and (not isinstance(payload["description"], str) or len(payload["description"]) > 200): |
| 168 | 171 | raise ValueError("Keep the description under 200 characters.") |
| 169 | 172 | for field in ("autostart", "start", "disks"): |