Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

skills: Gmail helper calls the API via curl so it (#398)

Regan Bell1864c8affc37
diff --git a/skills-seed/google-workspace/scripts/gmail.py b/skills-seed/google-workspace/scripts/gmail.py
index 110c5a36c..f07d7018e 100755
--- a/skills-seed/google-workspace/scripts/gmail.py
+++ b/skills-seed/google-workspace/scripts/gmail.py
@@ -26,10 +26,9 @@ import html
import json
import os
import re
+import subprocess
import sys
-import urllib.error
import urllib.parse
-import urllib.request
from email.message import EmailMessage
from email.policy import SMTP
from email.utils import formataddr, getaddresses
@@ -42,19 +41,24 @@ def call(method: str, path: str, body: dict | None = None, query: dict | None =
tok = os.environ.get("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM", "")
if not tok:
sys.exit("no Gmail token: ask the user to connect Google")
- req = urllib.request.Request(
- url,
- data=json.dumps(body).encode() if body is not None else None,
- headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"},
- method=method,
- )
+ # curl, not urllib: the sandbox egress proxy is an https:// CONNECT proxy,
+ # which python's urllib cannot tunnel through.
+ cmd = ["curl", "-sS", "--max-time", "60", "-X", method,
+ "-H", f"Authorization: Bearer {tok}", "-H", "Content-Type: application/json",
+ "-w", "\n%{http_code}", url]
+ if body is not None:
+ cmd[1:1] = ["--data-binary", "@-"]
+ res = subprocess.run(cmd, input=json.dumps(body) if body is not None else None,
+ capture_output=True, text=True)
+ if res.returncode != 0:
+ sys.exit(f"gmail api unreachable on {method} {path}: {res.stderr.strip()[:500]}")
+ text, _, status = res.stdout.rpartition("\n")
+ if not status.startswith("2"):
+ sys.exit(f"gmail api {status} on {method} {path}: {text[:500]}")
try:
- with urllib.request.urlopen(req, timeout=60) as res:
- return json.load(res)
- except urllib.error.HTTPError as e:
- sys.exit(f"gmail api {e.code} on {method} {path}: {e.read().decode()[:500]}")
- except urllib.error.URLError as e:
- sys.exit(f"gmail api unreachable on {method} {path}: {e.reason}")
+ return json.loads(text)
+ except ValueError:
+ sys.exit(f"gmail api {status} on {method} {path}: non-json response: {text[:500]}")
def read_body(path: str) -> str:
diff --git a/test/gmail-mime.test.ts b/test/gmail-mime.test.ts
index e4ddbdf8d..0f6930b8a 100644
--- a/test/gmail-mime.test.ts
+++ b/test/gmail-mime.test.ts
@@ -1,6 +1,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
+import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
import { join } from "node:path";
const SCRIPT = join(process.cwd(), "skills-seed", "google-workspace", "scripts", "gmail.py");
@@ -73,3 +75,52 @@ test("intra-paragraph line breaks survive as <br> in the html mirror", { skip: !
assert.ok(html, "html part exists");
assert.ok(html.includes("Two lines<br>in one paragraph"), "intra-paragraph breaks become <br>");
});
+
+test(
+ "api calls go through curl, which can tunnel the sandbox's https CONNECT egress proxy",
+ { skip: !havePython },
+ () => {
+ const dir = mkdtempSync(join(tmpdir(), "gmail-curl-"));
+ const argsFile = join(dir, "args.json");
+ const stub = join(dir, "curl");
+ writeFileSync(
+ stub,
+ `#!/usr/bin/env python3\nimport json, sys\nbody = sys.stdin.read() if "@-" in sys.argv else ""\n` +
+ `json.dump({"argv": sys.argv[1:], "stdin": body}, open(${JSON.stringify(argsFile)}, "w"))\n` +
+ `print('{"id":"m1","threadId":"t1"}\\n200', end="")\n`,
+ );
+ chmodSync(stub, 0o755);
+ const out = execFileSync("python3", [SCRIPT, "send-draft", "d1"], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ PATH: `${dir}:${process.env.PATH}`,
+ VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM: "tok",
+ HTTPS_PROXY: "https://proxy.internal:3128",
+ },
+ });
+ assert.deepEqual(JSON.parse(out), { id: "m1", threadId: "t1" });
+ const recorded = JSON.parse(readFileSync(argsFile, "utf8"));
+ const sendUrl = recorded.argv.find((a: string) => a.startsWith("https://"));
+ assert.equal(sendUrl, "https://gmail.googleapis.com/gmail/v1/users/me/drafts/send");
+ assert.ok(recorded.argv.includes("Authorization: Bearer tok"));
+ assert.equal(recorded.stdin, '{"id": "d1"}');
+ },
+);
+
+test("non-2xx responses exit with the status and body excerpt", { skip: !havePython }, () => {
+ const dir = mkdtempSync(join(tmpdir(), "gmail-curl-"));
+ const stub = join(dir, "curl");
+ writeFileSync(
+ stub,
+ `#!/usr/bin/env python3\nimport sys\nsys.stdin.read()\nprint('{"error":"nope"}\\n403', end="")\n`,
+ );
+ chmodSync(stub, 0o755);
+ const res = spawnSync("python3", [SCRIPT, "send-draft", "d1"], {
+ encoding: "utf8",
+ env: { ...process.env, PATH: `${dir}:${process.env.PATH}`, VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM: "tok" },
+ });
+ assert.notEqual(res.status, 0);
+ assert.ok(res.stderr.includes("gmail api 403"));
+ assert.ok(res.stderr.includes("nope"));
+});