feat(clients): sandbox: data plane (JWT proxy, CDP WebSocket), operations, SDK chunk shapes

Data plane per the computer use quickstart and SDK 2.6.0 source: signJwt
minted JWT, /cdp /tabs /cdp_ws_endpoint over HTTP with routing headers, CDP
over the live WsClient with capped reconnect. Operations methods wrapped,
input/output chunk shapes settled from the SDK, ComputerUse moved off execute.
Execution paths remain verified by Discovery, docs and SDK only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-24 05:30:44 +02:00
co-authored by Claude Sonnet 5.5
parent 29d775a923
commit 1c3fbe1899
33 changed files with 3031 additions and 185 deletions
+225
View File
@@ -0,0 +1,225 @@
#pragma once
// A test-owned loopback server for the sandbox data plane client: plain HTTP
// with keep-alive plus RFC 6455 upgrades, many connections, every request
// recorded. It is NOT a Google reply: it exists to prove client mechanics
// (header placement, framing, refresh, caps, reconnect). Nothing it answers is
// evidence about how Google's data plane behaves.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <atomic>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "../live/loopback.h"
namespace plane_test {
struct Req {
std::string method;
std::string target;
std::map<std::string, std::string> headers; // lower-case names
std::string body;
bool websocket = false;
std::string header(const std::string& name) const {
auto it = headers.find(name);
return it == headers.end() ? "" : it->second;
}
};
struct Res {
int status = 200;
std::string body;
std::string content_type = "application/json";
};
class Server {
public:
using Http = std::function<Res(const Req&)>;
// `index` counts websocket connections from 0.
using Ws = std::function<void(live_test::ServerConn&, int index)>;
Server(Http http, Ws ws = nullptr) : http_(std::move(http)), ws_(std::move(ws)) {
listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
sockaddr_in a{};
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
::bind(listen_fd_, (sockaddr*)&a, sizeof a);
::listen(listen_fd_, 16);
socklen_t len = sizeof a;
::getsockname(listen_fd_, (sockaddr*)&a, &len);
port_ = ntohs(a.sin_port);
acceptor_ = std::thread([this] { accept_loop(); });
}
~Server() {
stop_ = true;
if (acceptor_.joinable()) acceptor_.join();
for (auto& t : workers_) t.join();
::close(listen_fd_);
}
int port() const { return port_; }
std::string hostport() const { return "127.0.0.1:" + std::to_string(port_); }
std::string base_url() const { return "http://" + hostport(); }
std::vector<Req> requests() const {
std::lock_guard<std::mutex> l(mu_);
return seen_;
}
int ws_connections() const { return ws_count_; }
private:
void accept_loop() {
while (!stop_) {
pollfd p{listen_fd_, POLLIN, 0};
if (::poll(&p, 1, 50) != 1) continue;
int fd = ::accept(listen_fd_, nullptr, nullptr);
if (fd < 0) continue;
workers_.emplace_back([this, fd] { serve(fd); });
}
}
static bool read_head(int fd, std::string& buf, std::string& head, const std::atomic<bool>& stop) {
while (buf.find("\r\n\r\n") == std::string::npos) {
pollfd p{fd, POLLIN, 0};
if (::poll(&p, 1, 100) != 1) {
if (stop) return false;
continue;
}
char tmp[8192];
ssize_t n = ::recv(fd, tmp, sizeof tmp, 0);
if (n <= 0) return false;
buf.append(tmp, (std::size_t)n);
}
std::size_t end = buf.find("\r\n\r\n") + 4;
head = buf.substr(0, end);
buf.erase(0, end);
return true;
}
static std::string lower(std::string s) {
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
void serve(int fd) {
timeval tv{2, 0};
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
std::string buf, head;
while (!stop_ && read_head(fd, buf, head, stop_)) {
Req r;
std::size_t eol = head.find("\r\n");
std::string line = head.substr(0, eol);
std::size_t sp1 = line.find(' '), sp2 = line.find(' ', sp1 + 1);
r.method = line.substr(0, sp1);
r.target = line.substr(sp1 + 1, sp2 - sp1 - 1);
std::size_t pos = eol + 2;
while (pos < head.size()) {
std::size_t e = head.find("\r\n", pos);
if (e == pos || e == std::string::npos) break;
std::string h = head.substr(pos, e - pos);
std::size_t c = h.find(':');
if (c != std::string::npos) {
std::string v = h.substr(c + 1);
while (!v.empty() && v.front() == ' ') v.erase(0, 1);
r.headers[lower(h.substr(0, c))] = v;
}
pos = e + 2;
}
r.websocket = lower(r.header("upgrade")) == "websocket";
std::size_t want = r.header("content-length").empty() ? 0 : std::stoul(r.header("content-length"));
while (buf.size() < want) {
char tmp[8192];
ssize_t n = ::recv(fd, tmp, sizeof tmp, 0);
if (n <= 0) {
::close(fd);
return;
}
buf.append(tmp, (std::size_t)n);
}
r.body = buf.substr(0, want);
buf.erase(0, want);
{
std::lock_guard<std::mutex> l(mu_);
seen_.push_back(r);
}
if (r.websocket) {
upgrade(fd, r, head, buf);
return;
}
Res res = http_(r);
std::string out = "HTTP/1.1 " + std::to_string(res.status) + " X\r\nContent-Type: " +
res.content_type + "\r\nContent-Length: " + std::to_string(res.body.size()) +
"\r\nConnection: keep-alive\r\n\r\n" + res.body;
std::size_t sent = 0;
while (sent < out.size()) {
ssize_t n = ::send(fd, out.data() + sent, out.size() - sent, MSG_NOSIGNAL);
if (n <= 0) {
::close(fd);
return;
}
sent += (std::size_t)n;
}
}
::close(fd);
}
void upgrade(int fd, const Req& r, const std::string& head, const std::string& rest) {
int index = ws_count_++;
live_test::ServerConn conn;
conn.fd = fd;
conn.request = head;
if (!rest.empty()) conn.decoder.feed(rest.data(), rest.size());
std::string key = r.header("sec-websocket-key");
if (!ws_) {
conn.send_raw("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
::close(fd);
return;
}
Res gate;
gate.status = 101;
if (reject_ws_) gate = reject_ws_(r, index);
if (gate.status != 101) {
conn.send_raw("HTTP/1.1 " + std::to_string(gate.status) + " X\r\nContent-Length: 0\r\n\r\n");
::close(fd);
return;
}
conn.send_raw("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Accept: " + molo::google::live::WsHandshake::accept_for(key) +
"\r\n\r\n");
try {
ws_(conn, index);
} catch (...) {
}
::close(fd);
}
public:
// Optional gate run before the 101: return status != 101 to refuse.
std::function<Res(const Req&, int)> reject_ws_;
private:
Http http_;
Ws ws_;
int listen_fd_ = -1;
int port_ = 0;
std::atomic<bool> stop_{false};
std::atomic<int> ws_count_{0};
std::thread acceptor_;
std::vector<std::thread> workers_;
mutable std::mutex mu_;
std::vector<Req> seen_;
};
} // namespace plane_test
@@ -0,0 +1,787 @@
// Sandbox data plane: client mechanics against a test-owned loopback server
// (framing, header placement, JWT refresh, caps, reconnect). The server is not
// a Google reply and proves nothing about Google's behavior; what Google does
// is verified by Discovery and by the docs and SDK cited in SPEC.md.
#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "framework.h"
#include "clients/transports/http_transport.h"
#include "clients/transports/mock_transport.h"
#include "google/client.h"
#include "google/credentials.h"
#include "google/resource.h"
#include "google/sandbox/caps.h"
#include "google/sandbox/cdp_session.h"
#include "google/sandbox/chunk.h"
#include "security/crypto/Base64.h"
#include "google/sandbox/computer_use.h"
#include "google/sandbox/data_plane.h"
#include "google/sandbox/data_plane_connector.h"
#include "google/sandbox/jwt.h"
#include "google/sandbox/operations.h"
#include "google/sandbox/sandboxes.h"
#include "google/sandbox/stream_executor.h"
#include "loopback_plane.h"
using namespace molo::google;
using namespace molo::google::sandbox;
using molo::clients::body::Json;
using plane_test::Req;
using plane_test::Res;
using plane_test::Server;
#define ASSERT_INVALID_ARG(stmt) \
do { \
bool caught_ = false; \
try { \
stmt; \
} catch (const GoogleError& e) { \
caught_ = e.http_status() == 400 && e.status() == "INVALID_ARGUMENT"; \
} \
ASSERT_TRUE(caught_); \
} while (0)
namespace {
const std::string kSandbox =
"projects/p-1/locations/us-central1/reasoningEngines/123/sandboxEnvironments/456";
struct FakeTokens : ITokenSource {
std::atomic<int> generation{1};
std::atomic<int> invalidations{0};
std::string token() override { return "jwt-" + std::to_string(generation.load()); }
void invalidate() override {
++invalidations;
++generation;
}
};
DataPlaneTarget loopback_target(const Server& s, const std::string& token = "route-tok") {
SandboxEnvironment env;
env.routing_token = token;
env.state = "STATE_RUNNING";
return DataPlaneTarget::from_environment(env, "", s.hostport());
}
template <typename F>
bool throws_status(F&& f, int http, const std::string& status) {
try {
f();
} catch (const GoogleError& e) {
return e.http_status() == http && e.status() == status;
}
return false;
}
// Echoes a CDP reply for every message: {"id":N,"result":{"echo":"<method>"}}.
void echo_script(live_test::ServerConn& c, int) {
while (auto m = c.read_message()) {
Json doc = Json::parse(*m);
Json r = Json::object();
r.set("id", *doc.find("id"));
Json res = Json::object();
res.set("echo", *doc.find("method"));
if (auto* s = doc.find("sessionId")) res.set("sessionId", *s);
r.set("result", res);
c.send_text(r.dump());
}
}
} // namespace
TEST(sandbox_target, address_derivation_and_refusals) {
SandboxEnvironment env;
env.routing_token = "rt";
env.load_balancer_hostname = "lb.example.com";
env.load_balancer_ip = "10.1.2.3";
DataPlaneTarget t = DataPlaneTarget::from_environment(env);
ASSERT_EQ(t.http_base, std::string("https://lb.example.com"));
ASSERT_EQ(t.ws_base, std::string("wss://lb.example.com"));
ASSERT_EQ(t.port, std::string("8080"));
env.load_balancer_hostname.clear();
t = DataPlaneTarget::from_environment(env);
ASSERT_EQ(t.http_base, std::string("http://10.1.2.3")); // as the SDK does
ASSERT_EQ(t.ws_base, std::string("ws://10.1.2.3"));
t = DataPlaneTarget::from_environment(env, "psc.internal", "", "9000");
ASSERT_EQ(t.http_base, std::string("https://psc.internal"));
ASSERT_EQ(t.port, std::string("9000"));
// Loopback override only for loopback hosts.
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(env, "", "evil.example.com:80"));
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(env, "", "127.0.0.1"));
// Missing or unsafe routing token, no address, bad port.
SandboxEnvironment none;
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(none));
none.routing_token = "has space";
none.load_balancer_ip = "1.2.3.4";
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(none));
none.routing_token = "a,b";
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(none));
env.routing_token = "ok";
env.load_balancer_ip = "1.2.3.4/x";
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(env));
env.load_balancer_ip = "1.2.3.4";
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(env, "", "", "0"));
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(env, "", "", "70000"));
SandboxEnvironment private_sandbox; // VPC-SC: only a service attachment
private_sandbox.routing_token = "rt";
private_sandbox.service_attachment = "projects/x/regions/y/serviceAttachments/z";
ASSERT_INVALID_ARG(DataPlaneTarget::from_environment(private_sandbox));
}
TEST(sandbox_dataplane, headers_paths_and_bodies) {
Server server([](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"devtools/browser/abc"})";
else res.body = R"({"ok":true})";
return res;
});
auto tokens = std::make_shared<FakeTokens>();
DataPlane plane(loopback_target(server), tokens);
plane.health();
plane.create_tab();
plane.list_tabs();
plane.activate_tab("tab-1");
plane.close_tab("tab-1");
ASSERT_EQ(plane.cdp_ws_endpoint(), std::string("devtools/browser/abc"));
plane.cdp("Page.navigate", Json::parse(R"({"url":"https://example.com"})"));
plane.cdps({{"Page.reload", Json::object()}, {"Page.stopLoading", Json::object()}});
auto seen = server.requests();
ASSERT_EQ(seen.size(), 8u);
const char* want[8][2] = {{"GET", "/"}, {"POST", "/tabs"},
{"GET", "/tabs"}, {"POST", "/tabs/tab-1/activate"},
{"DELETE", "/tabs/tab-1"}, {"GET", "/cdp_ws_endpoint"},
{"POST", "/cdp"}, {"POST", "/cdps"}};
for (int i = 0; i < 8; ++i) {
ASSERT_EQ(seen[i].method, std::string(want[i][0]));
ASSERT_EQ(seen[i].target, std::string(want[i][1]));
// The three documented headers on every call.
ASSERT_EQ(seen[i].header("authorization"), std::string("Bearer jwt-1"));
ASSERT_EQ(seen[i].header("x-sandbox-routing-token"), std::string("route-tok"));
ASSERT_EQ(seen[i].header("x-sandbox-port"), std::string("8080"));
}
Json cdp = Json::parse(seen[6].body);
ASSERT_EQ(cdp.find("command")->as_string(), std::string("Page.navigate"));
ASSERT_EQ(cdp.find("params")->find("url")->as_string(), std::string("https://example.com"));
Json batch = Json::parse(seen[7].body);
ASSERT_EQ(batch.find("commands")->as_array().size(), 2u);
ASSERT_EQ(seen[6].header("content-type").substr(0, 16), std::string("application/json"));
ASSERT_EQ(tokens->invalidations.load(), 0);
}
TEST(sandbox_dataplane, validation_before_traffic) {
Server server([](const Req&) { return Res{}; });
DataPlane plane(loopback_target(server), std::make_shared<FakeTokens>());
ASSERT_INVALID_ARG(plane.activate_tab(""));
ASSERT_INVALID_ARG(plane.activate_tab("../x"));
ASSERT_INVALID_ARG(plane.close_tab("a/b"));
ASSERT_INVALID_ARG(plane.cdp("nodomain", Json::object()));
ASSERT_INVALID_ARG(plane.cdp("A.b.c", Json::object()));
ASSERT_INVALID_ARG(plane.cdp("Page.navigate", Json::array()));
ASSERT_INVALID_ARG(plane.cdps({}));
std::vector<CdpCommand> many(SandboxCaps::kMaxBatchCommands + 1, CdpCommand{"Page.reload", Json::object()});
ASSERT_INVALID_ARG(plane.cdps(many));
ASSERT_INVALID_ARG(DataPlane::validate_path("tabs"));
ASSERT_INVALID_ARG(DataPlane::validate_path("/a/../b"));
ASSERT_INVALID_ARG(plane.ws_url(""));
ASSERT_INVALID_ARG(plane.ws_url("wss://elsewhere/x"));
ASSERT_EQ(server.requests().size(), 0u);
}
TEST(sandbox_dataplane, jwt_refreshes_once_on_401) {
std::atomic<int> calls{0};
Server server([&](const Req& r) {
++calls;
Res res;
if (r.header("authorization") != "Bearer jwt-2") {
res.status = 401;
res.body = R"({"error":"expired"})";
} else {
res.body = R"({"ok":true})";
}
return res;
});
auto tokens = std::make_shared<FakeTokens>();
DataPlane plane(loopback_target(server), tokens);
DataPlaneReply r = plane.health();
ASSERT_EQ(r.status, 200);
ASSERT_EQ(calls.load(), 2);
ASSERT_EQ(tokens->invalidations.load(), 1);
ASSERT_EQ(plane.auth_refreshes(), 1);
ASSERT_EQ(server.requests()[0].header("authorization"), std::string("Bearer jwt-1"));
ASSERT_EQ(server.requests()[1].header("authorization"), std::string("Bearer jwt-2"));
}
TEST(sandbox_dataplane, persistent_401_is_not_retried_forever) {
Server server([](const Req&) {
Res res;
res.status = 401;
res.body = "no";
return res;
});
auto tokens = std::make_shared<FakeTokens>();
DataPlane plane(loopback_target(server), tokens);
ASSERT_TRUE(throws_status([&] { plane.health(); }, 401, "DATA_PLANE_401"));
ASSERT_EQ(server.requests().size(), 2u); // one try plus one refresh
ASSERT_EQ(tokens->invalidations.load(), 1);
}
TEST(sandbox_dataplane, errors_and_reply_cap) {
Server server([](const Req& r) {
Res res;
if (r.target == "/tabs") {
res.status = 500;
res.body = std::string(2000, 'x');
} else {
res.body = std::string(SandboxCaps::kMaxDataReplyBytes + 1, 'y');
}
return res;
});
DataPlane plane(loopback_target(server), std::make_shared<FakeTokens>());
try {
plane.list_tabs();
FAIL("a 500 must throw");
} catch (const GoogleError& e) {
ASSERT_EQ(e.http_status(), 500);
ASSERT_EQ(e.service(), std::string("sandbox-data-plane"));
ASSERT_TRUE(e.message().size() <= SandboxCaps::kMaxErrorExcerpt);
}
ASSERT_TRUE(throws_status([&] { plane.health(); }, 502, "TOO_BIG"));
}
TEST(sandbox_dataplane, unreachable_host_is_a_loud_502) {
SandboxEnvironment env;
env.routing_token = "rt";
DataPlaneTarget t = DataPlaneTarget::from_environment(env, "", "127.0.0.1:1");
DataPlane plane(t, std::make_shared<FakeTokens>(), nullptr, 2000);
ASSERT_TRUE(throws_status([&] { plane.health(); }, 502, "UNAVAILABLE"));
}
TEST(sandbox_jwt, claims_cache_and_refresh_margin) {
// The signer endpoint is a loopback stand-in so the cache and refresh logic
// runs through the real client. It says nothing about the real IAM API.
std::atomic<int> signs{0};
Server server([&](const Req&) {
++signs;
Res res;
res.body = R"({"keyId":"k","signedJwt":"signed-)" + std::to_string(signs.load()) + R"("})";
return res;
});
auto client = std::make_shared<GoogleClient>(
std::make_unique<molo::clients::transports::HttpTransport>(), Credentials::bearer("tok"));
std::atomic<long> now{1000};
ServiceEndpoint ep{"iamcredentials", server.base_url() + "/v1"};
IamJwtSource src(client, "sa@p.iam.gserviceaccount.com", 3600, [&] { return now.load(); }, ep);
ASSERT_EQ(src.token(), std::string("signed-1"));
ASSERT_EQ(src.token(), std::string("signed-1")); // cached
ASSERT_EQ(src.mints(), 1);
now = 1000 + 3600 - SandboxCaps::kJwtRefreshMarginSeconds - 1; // still outside the margin
ASSERT_EQ(src.token(), std::string("signed-1"));
now = 1000 + 3600 - SandboxCaps::kJwtRefreshMarginSeconds + 1; // inside: refresh
ASSERT_EQ(src.token(), std::string("signed-2"));
src.invalidate();
ASSERT_EQ(src.token(), std::string("signed-3"));
auto seen = server.requests();
ASSERT_EQ(seen[0].method, std::string("POST"));
ASSERT_EQ(seen[0].target, std::string("/v1/projects/-/serviceAccounts/sa@p.iam.gserviceaccount.com:signJwt"));
ASSERT_EQ(seen[0].header("authorization"), std::string("Bearer tok"));
Json body = Json::parse(seen[0].body);
Json claims = Json::parse(body.find("payload")->as_string());
ASSERT_EQ(claims.find("iss")->as_string(), std::string("sa@p.iam.gserviceaccount.com"));
ASSERT_EQ(claims.find("sub")->as_string(), std::string("sa@p.iam.gserviceaccount.com"));
ASSERT_EQ(claims.find("aud")->as_string(), std::string("https://aiplatform.googleapis.com/"));
ASSERT_EQ(claims.find("iat")->as_int(), 1000);
ASSERT_EQ(claims.find("exp")->as_int(), 4600);
ASSERT_TRUE(claims.find("nonce")->as_int() >= 1);
// Two mints use two different nonces.
Json c2 = Json::parse(Json::parse(seen[1].body).find("payload")->as_string());
ASSERT_TRUE(c2.find("nonce")->as_int() != claims.find("nonce")->as_int() ||
c2.find("iat")->as_int() != claims.find("iat")->as_int());
}
TEST(sandbox_jwt, validation) {
auto client = std::make_shared<GoogleClient>(std::make_unique<molo::clients::transports::MockTransport>(),
Credentials::bearer("tok"));
ASSERT_INVALID_ARG(IamJwtSource(client, "", 3600));
ASSERT_INVALID_ARG(IamJwtSource(client, "no-at-sign", 3600));
ASSERT_INVALID_ARG(IamJwtSource(client, "a@b@c", 3600));
ASSERT_INVALID_ARG(IamJwtSource(client, "a b@c.d", 3600));
ASSERT_INVALID_ARG(IamJwtSource(client, "a@c.d/../x", 3600));
ASSERT_INVALID_ARG(IamJwtSource(client, "a@c.d", 10));
ASSERT_INVALID_ARG(IamJwtSource(client, "a@c.d", 3601));
// No credential: the signer fails before traffic with the standard 503.
auto t = std::make_unique<molo::clients::transports::MockTransport>();
auto* mock = t.get();
auto bare = std::make_shared<GoogleClient>(std::move(t), nullptr);
IamJwtSource src(bare, "a@c.d", 3600);
ASSERT_TRUE(throws_status([&] { src.token(); }, 503, "NOT_CONFIGURED"));
ASSERT_EQ(mock->send_count(), 0u);
ASSERT_EQ(IamJwtSource::sign_path("a@c.d"), std::string("/projects/-/serviceAccounts/a@c.d:signJwt"));
}
TEST(sandbox_cdp, handshake_header_and_call_round_trip) {
Server server(
[](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"devtools/browser/xyz"})";
return res;
},
echo_script);
auto tokens = std::make_shared<FakeTokens>();
auto plane = std::make_shared<DataPlane>(loopback_target(server), tokens);
CdpSession cdp(plane);
cdp.connect();
ASSERT_TRUE(cdp.connected());
Json r = cdp.call("Page.navigate", Json::parse(R"({"url":"https://a.b"})"));
ASSERT_EQ(r.find("echo")->as_string(), std::string("Page.navigate"));
Json s = cdp.call("Page.reload", Json::object(), "sess-1");
ASSERT_EQ(s.find("sessionId")->as_string(), std::string("sess-1"));
auto seen = server.requests();
ASSERT_EQ(seen.size(), 2u); // GET /cdp_ws_endpoint, then the upgrade
ASSERT_EQ(seen[1].target, std::string("/devtools/browser/xyz"));
ASSERT_TRUE(seen[1].websocket);
ASSERT_EQ(seen[1].header("sec-websocket-protocol"), std::string("v1.stream, jwt-1, route-tok, 9222"));
ASSERT_EQ(seen[1].header("sec-websocket-version"), std::string("13"));
ASSERT_EQ(cdp.connects(), 1);
ASSERT_EQ(cdp.reconnects(), 0);
// Validation: nothing is sent.
ASSERT_INVALID_ARG(cdp.call("bad", Json::object()));
ASSERT_INVALID_ARG(cdp.call("Page.reload", Json::object(), "bad id!"));
ASSERT_INVALID_ARG(cdp.call("Page.reload", Json::object(), "", 5));
cdp.close();
ASSERT_TRUE(!cdp.connected());
}
TEST(sandbox_cdp, events_errors_timeout_and_event_cap) {
Server server(
[](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"ws/b"})";
return res;
},
[](live_test::ServerConn& c, int) {
while (auto m = c.read_message()) {
Json doc = Json::parse(*m);
std::string method = doc.find("method")->as_string();
if (method == "Test.silent") continue; // never answers
if (method == "Test.fail") {
c.send_text(R"({"id":)" + std::to_string(doc.find("id")->as_int()) +
R"(,"error":{"code":-32000,"message":"boom"}})");
continue;
}
if (method == "Test.flood") {
for (std::size_t i = 0; i < SandboxCaps::kMaxCdpEvents + 10; ++i)
c.send_text(R"({"method":"Test.event","params":{"n":)" + std::to_string(i) + "}}");
}
if (method == "Test.stale") c.send_text(R"({"id":9999,"result":{}})");
c.send_text(R"({"method":"Page.loadEventFired","params":{}})");
c.send_text(R"({"id":)" + std::to_string(doc.find("id")->as_int()) + R"(,"result":{"ok":true}})");
}
});
auto plane = std::make_shared<DataPlane>(loopback_target(server), std::make_shared<FakeTokens>());
CdpSession cdp(plane);
Json r = cdp.call("Test.go", Json::object());
ASSERT_TRUE(r.find("ok")->as_bool());
auto events = cdp.take_events();
ASSERT_EQ(events.size(), 1u);
ASSERT_EQ(events[0].find("method")->as_string(), std::string("Page.loadEventFired"));
ASSERT_TRUE(cdp.take_events().empty());
// CDP error object.
try {
cdp.call("Test.fail", Json::object());
FAIL("a CDP error must throw");
} catch (const GoogleError& e) {
ASSERT_EQ(e.status(), std::string("CDP_ERROR"));
ASSERT_EQ(e.message(), std::string("boom"));
}
// Unmatched ids are ignored, the right reply still arrives.
ASSERT_TRUE(cdp.call("Test.stale", Json::object()).find("ok")->as_bool());
cdp.take_events();
// Deadline.
ASSERT_TRUE(throws_status([&] { cdp.call("Test.silent", Json::object(), "", 300); }, 504,
"DEADLINE_EXCEEDED"));
// Event cap: oldest are dropped and counted.
cdp.call("Test.flood", Json::object());
ASSERT_TRUE(cdp.take_events().size() <= SandboxCaps::kMaxCdpEvents);
ASSERT_TRUE(cdp.dropped_events() >= 10);
}
TEST(sandbox_cdp, wait_event_and_attach_first_page) {
Server server(
[](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"ws/b"})";
return res;
},
[](live_test::ServerConn& c, int) {
while (auto m = c.read_message()) {
Json doc = Json::parse(*m);
std::string method = doc.find("method")->as_string();
std::string id = std::to_string(doc.find("id")->as_int());
if (method == "Target.getTargets")
c.send_text(R"({"id":)" + id +
R"(,"result":{"targetInfos":[{"type":"service_worker","targetId":"w"},{"type":"page","targetId":"T1"}]}})");
else if (method == "Target.attachToTarget") {
bool flat = doc.find("params")->find("flatten")->as_bool();
std::string tid = doc.find("params")->find("targetId")->as_string();
c.send_text(R"({"id":)" + id + R"(,"result":{"sessionId":")" + (flat ? tid + "-S" : "x") + R"("}})");
} else if (method == "Page.enable") {
c.send_text(R"({"method":"Page.frameNavigated","params":{}})");
c.send_text(R"({"id":)" + id + R"(,"result":{}})");
}
}
});
auto plane = std::make_shared<DataPlane>(loopback_target(server), std::make_shared<FakeTokens>());
CdpSession cdp(plane);
ASSERT_EQ(cdp.attach_first_page(), std::string("T1-S"));
cdp.call("Page.enable", Json::object(), "T1-S");
Json ev = cdp.wait_event("Page.frameNavigated", 1000); // already buffered
ASSERT_EQ(ev.find("method")->as_string(), std::string("Page.frameNavigated"));
ASSERT_TRUE(throws_status([&] { cdp.wait_event("Page.never", 300); }, 504, "DEADLINE_EXCEEDED"));
}
TEST(sandbox_cdp, reconnect_uses_a_fresh_jwt_and_is_capped) {
std::atomic<int> endpoint_calls{0};
Server server(
[&](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") {
++endpoint_calls;
res.body = R"({"endpoint":"ws/b"})";
}
return res;
},
[](live_test::ServerConn& c, int) {
// Answer one command, then drop the connection (no close frame needed).
if (auto m = c.read_message()) {
Json doc = Json::parse(*m);
c.send_text(R"({"id":)" + std::to_string(doc.find("id")->as_int()) + R"(,"result":{"ok":true}})");
}
c.read_message(); // wait for the next command and hang up mid-call
});
auto tokens = std::make_shared<FakeTokens>();
auto plane = std::make_shared<DataPlane>(loopback_target(server), tokens);
CdpSession cdp(plane);
ASSERT_TRUE(cdp.call("A.one", Json::object()).find("ok")->as_bool());
// The server hangs up while this call waits: loud loss, no replay.
ASSERT_TRUE(throws_status([&] { cdp.call("A.two", Json::object()); }, 502, "CDP_CONNECTION_LOST"));
ASSERT_TRUE(!cdp.connected());
ASSERT_EQ(plane->tokens().token(), std::string("jwt-1"));
// Next call reconnects with a fresh JWT.
ASSERT_TRUE(cdp.call("A.three", Json::object()).find("ok")->as_bool());
ASSERT_EQ(cdp.reconnects(), 1);
ASSERT_EQ(tokens->invalidations.load(), 1);
auto seen = server.requests();
std::string second_upgrade;
for (const Req& r : seen)
if (r.websocket) second_upgrade = r.header("sec-websocket-protocol");
ASSERT_EQ(second_upgrade, std::string("v1.stream, jwt-2, route-tok, 9222"));
ASSERT_EQ(endpoint_calls.load(), 2); // the endpoint is re-resolved
// Keep losing the connection: the reconnect budget is a hard cap.
bool limited = false;
for (int i = 0; i < 8 && !limited; ++i) {
try {
cdp.call("A.more", Json::object());
} catch (const GoogleError& e) {
limited = e.status() == "CDP_RECONNECT_LIMIT";
}
}
ASSERT_TRUE(limited);
ASSERT_EQ(cdp.reconnects(), SandboxCaps::kMaxCdpReconnects);
}
TEST(sandbox_cdp, upgrade_refusal_refreshes_once_then_fails) {
Server server(
[](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"ws/b"})";
return res;
},
echo_script);
server.reject_ws_ = [](const Req& r, int) {
Res g;
g.status = r.header("sec-websocket-protocol").find("jwt-2") != std::string::npos ? 101 : 401;
return g;
};
auto tokens = std::make_shared<FakeTokens>();
CdpSession cdp(std::make_shared<DataPlane>(loopback_target(server), tokens));
cdp.connect(); // 401 once, fresh JWT, accepted
ASSERT_TRUE(cdp.connected());
ASSERT_EQ(tokens->invalidations.load(), 1);
Server deny([](const Req& r) {
Res res;
if (r.target == "/cdp_ws_endpoint") res.body = R"({"endpoint":"ws/b"})";
return res;
}, echo_script);
deny.reject_ws_ = [](const Req&, int) {
Res g;
g.status = 403;
return g;
};
CdpSession denied(std::make_shared<DataPlane>(loopback_target(deny), std::make_shared<FakeTokens>()));
ASSERT_TRUE(throws_status([&] { denied.connect(); }, 403, "CDP_UNAUTHORIZED"));
}
namespace {
// A connector whose control plane read is local: the sandbox resource points
// at the loopback server. Everything after that (JWT, headers, routes) is real.
class LoopbackConnector : public DataPlaneConnector {
public:
LoopbackConnector(std::shared_ptr<GoogleClient> client, DataPlaneOptions options,
std::shared_ptr<ITokenSource> tokens, std::string state = "STATE_RUNNING")
: DataPlaneConnector(std::move(client), std::move(options), std::move(tokens)),
state_(std::move(state)) {}
protected:
SandboxEnvironment environment(const std::string& name) const override {
SandboxEnvironment e;
e.name = name;
e.state = state_;
e.routing_token = "route-tok";
e.load_balancer_hostname = "unused.invalid";
return e;
}
private:
std::string state_;
};
std::shared_ptr<GoogleClient> bearer_client() {
return std::make_shared<GoogleClient>(std::make_unique<molo::clients::transports::HttpTransport>(),
Credentials::bearer("tok"));
}
} // namespace
TEST(sandbox_computer, actions_over_the_data_plane) {
// 1x1 transparent PNG.
const std::string png =
"\x89PNG\r\n\x1a\n" + std::string("0123456789", 10);
Server server([&](const Req& r) {
Res res;
Json body = r.body.empty() ? Json::object() : Json::parse(r.body);
const Json* cmd = body.find("command");
if (cmd && cmd->as_string() == "Page.captureScreenshot")
res.body = R"({"result":{"data":")" + molo::security::crypto::Base64::encode(png) + R"("}})";
else
res.body = R"({"result":{"frameId":"F"}})";
return res;
});
DataPlaneOptions opt;
opt.service_account_email = "sa@p.iam.gserviceaccount.com";
opt.loopback_override = server.hostport();
auto connector = std::make_shared<LoopbackConnector>(bearer_client(), opt, std::make_shared<FakeTokens>());
ComputerUse cu(bearer_client(), connector);
ActionResult nav = cu.navigate(kSandbox, "https://example.com");
ASSERT_EQ(nav.result.find("frameId")->as_string(), std::string("F"));
cu.click(kSandbox, 10, 20);
cu.type_text(kSandbox, "hello");
ActionResult shot = cu.screenshot(kSandbox);
ASSERT_EQ(shot.screenshot_png, png);
auto seen = server.requests();
ASSERT_EQ(seen.size(), 5u); // navigate, press, release, insertText, screenshot
for (const Req& r : seen) {
ASSERT_EQ(r.method, std::string("POST"));
ASSERT_EQ(r.target, std::string("/cdp"));
ASSERT_EQ(r.header("authorization"), std::string("Bearer jwt-1"));
}
ASSERT_EQ(Json::parse(seen[0].body).find("command")->as_string(), std::string("Page.navigate"));
ASSERT_EQ(Json::parse(seen[1].body).find("params")->find("type")->as_string(), std::string("mousePressed"));
ASSERT_EQ(Json::parse(seen[2].body).find("params")->find("type")->as_string(), std::string("mouseReleased"));
ASSERT_EQ(Json::parse(seen[3].body).find("command")->as_string(), std::string("Input.insertText"));
ASSERT_EQ(Json::parse(seen[4].body).find("params")->find("format")->as_string(), std::string("png"));
}
TEST(sandbox_computer, tabs_and_health_and_guards) {
Server server([](const Req& r) {
Res res;
res.body = r.target == "/" ? "healthy" : R"([{"id":"t1"}])";
return res;
});
DataPlaneOptions opt;
opt.service_account_email = "sa@p.iam.gserviceaccount.com";
opt.loopback_override = server.hostport();
auto connector = std::make_shared<LoopbackConnector>(bearer_client(), opt, std::make_shared<FakeTokens>());
ComputerUse cu(bearer_client(), connector);
ASSERT_EQ(cu.health(kSandbox).find("body")->as_string(), std::string("healthy"));
ASSERT_EQ(cu.list_tabs(kSandbox).find("reply")->as_array().size(), 1u);
cu.create_tab(kSandbox);
cu.activate_tab(kSandbox, "t1");
cu.close_tab(kSandbox, "t1");
ASSERT_INVALID_ARG(cu.activate_tab(kSandbox, "../x"));
ASSERT_INVALID_ARG(cu.command(kSandbox, "nope", Json::object()));
ASSERT_EQ(server.requests().size(), 5u);
// A sandbox that is not running never reaches the data plane.
auto paused = std::make_shared<LoopbackConnector>(bearer_client(), opt, std::make_shared<FakeTokens>(),
"STATE_PAUSED");
ComputerUse cu2(bearer_client(), paused);
ASSERT_TRUE(throws_status([&] { cu2.health(kSandbox); }, 409, "FAILED_PRECONDITION"));
ASSERT_EQ(server.requests().size(), 5u);
}
TEST(sandbox_computer, no_credential_and_no_signer_are_503_before_traffic) {
auto t = std::make_unique<molo::clients::transports::MockTransport>();
auto* mock = t.get();
auto bare = std::make_shared<GoogleClient>(std::move(t), nullptr);
ComputerUse cu(bare, std::make_shared<DataPlaneConnector>(bare, DataPlaneOptions{}));
ASSERT_TRUE(throws_status([&] { cu.navigate(kSandbox, "https://example.com"); }, 503, "NOT_CONFIGURED"));
ASSERT_TRUE(throws_status([&] { cu.list_tabs(kSandbox); }, 503, "NOT_CONFIGURED"));
ASSERT_TRUE(throws_status([&] { cu.open_cdp(kSandbox); }, 503, "NOT_CONFIGURED"));
ASSERT_INVALID_ARG(cu.navigate("x", "https://example.com"));
ASSERT_EQ(mock->send_count(), 0u);
// A credential but no service account to sign with: 503 too, still no traffic.
auto t2 = std::make_unique<molo::clients::transports::MockTransport>();
auto* mock2 = t2.get();
auto cred = std::make_shared<GoogleClient>(std::move(t2), Credentials::bearer("tok"));
ComputerUse cu2(cred, std::make_shared<DataPlaneConnector>(cred, DataPlaneOptions{}));
ASSERT_TRUE(throws_status([&] { cu2.screenshot(kSandbox); }, 503, "NOT_CONFIGURED"));
ASSERT_EQ(mock2->send_count(), 0u);
}
TEST(sandbox_bidi, streamed_reply_over_the_real_transport) {
// Mechanics of the streamed POST: path, version, bearer header, array
// stream decoding, event cap. The reply text is the test's own.
Server server([](const Req&) {
Res res;
Chunk a;
a.mime_type = "application/json";
a.data = R"({"stdout":"one\n","returncode":0})";
Chunk f;
f.mime_type = "text/plain";
f.data = "file body";
f.attributes["file_name"] = "out.txt";
res.body = "[{\"outputs\":[" + a.to_json().dump() + "]},{\"outputs\":[" + f.to_json().dump() + "]}]";
return res;
});
auto client = bearer_client();
StreamExecutor stream(client);
stream.use_base_url(server.base_url());
int events = 0;
ExecutionResult r = stream.run(kSandbox, ChunkCodec::shell_inputs("echo one", "", 5),
[&](const std::vector<Chunk>&) {
++events;
return true;
});
ASSERT_EQ(events, 2);
ASSERT_EQ(r.std_out, std::string("one\n"));
ASSERT_EQ(r.files.size(), 1u);
auto seen = server.requests();
ASSERT_EQ(seen[0].method, std::string("POST"));
ASSERT_EQ(seen[0].target, "/v1beta1/" + kSandbox + ":bidiExecute");
ASSERT_EQ(seen[0].header("authorization"), std::string("Bearer tok"));
Json body = Json::parse(seen[0].body);
ASSERT_EQ(body.find("inputs")->as_array().size(), 3u);
ASSERT_INVALID_ARG(stream.use_base_url("ftp://x"));
}
TEST(sandbox_operations, paths_and_validation) {
Server server([](const Req& r) {
Res res;
if (r.target.find("/operations?") != std::string::npos)
res.body = R"({"operations":[{"name":"x/operations/1","done":true}]})";
else
res.body = R"({"name":"n","done":true})";
return res;
});
Operations ops(bearer_client());
ops.use_base_url(server.base_url());
const std::string snap =
"projects/p-1/locations/us-central1/reasoningEngines/123/sandboxEnvironmentSnapshots/8";
const std::string tmpl =
"projects/p-1/locations/us-central1/reasoningEngines/123/sandboxEnvironmentTemplates/7";
ASSERT_TRUE(ops.get(kSandbox + "/operations/99").done);
ASSERT_TRUE(ops.wait(snap + "/operations/5", 30).done);
ops.cancel(tmpl + "/operations/6");
ops.remove(kSandbox + "/operations/7");
ASSERT_EQ(ops.list(kSandbox, 10).size(), 1u);
auto seen = server.requests();
ASSERT_EQ(seen.size(), 5u);
ASSERT_EQ(seen[0].target, "/v1/" + kSandbox + "/operations/99");
ASSERT_EQ(seen[1].method, std::string("POST"));
ASSERT_EQ(seen[1].target, "/v1/" + snap + "/operations/5:wait?timeout=30s");
ASSERT_EQ(seen[2].target, "/v1/" + tmpl + "/operations/6:cancel");
ASSERT_EQ(seen[3].method, std::string("DELETE"));
ASSERT_EQ(seen[4].target, "/v1beta1/" + kSandbox + "/operations?pageSize=10");
ASSERT_INVALID_ARG(ops.get(kSandbox));
ASSERT_INVALID_ARG(ops.get(kSandbox + "/operations/"));
ASSERT_INVALID_ARG(ops.get("projects/p/operations/1"));
ASSERT_INVALID_ARG(ops.wait(kSandbox + "/operations/1", 0));
ASSERT_INVALID_ARG(ops.wait(kSandbox + "/operations/1", SandboxCaps::kMaxOperationWaitSeconds + 1));
ASSERT_INVALID_ARG(ops.list("projects/p-1/locations/us-central1/reasoningEngines/123"));
ASSERT_INVALID_ARG(ops.list(kSandbox, 101));
ASSERT_EQ(server.requests().size(), 5u);
auto names = SandboxNames::parse_operation(snap + "/operations/5");
ASSERT_EQ(names.family, std::string("sandboxEnvironmentSnapshots"));
ASSERT_EQ(names.id, std::string("5"));
}
namespace {
bool live_ready() {
return std::getenv("MOLO_LIVE_NET") &&
(!Credentials::env().empty() || !Credentials::env("GOOGLE_ACCESS_TOKEN").empty() ||
!Credentials::env("GOOGLE_APPLICATION_CREDENTIALS").empty()) &&
!CloudContext::from_env().project.empty();
}
} // namespace
TEST(google_live_sandbox, operations_read_only) {
// Read-only: operations of resources that cannot exist. Observed 2026-10-24:
// list answers 200 {} (empty), get answers 404 NOT_FOUND "Operation ... not found."
if (!live_ready()) {
std::cout << "SKIP google_live_sandbox.operations_read_only (set MOLO_LIVE_NET=1, "
"a Google credential and GOOGLE_CLOUD_PROJECT)\n";
return;
}
CloudContext ctx = CloudContext::from_env();
std::string engine = ctx.child("reasoningEngines", "1234567890123456789");
Operations ops(GoogleClient::from_env());
ASSERT_TRUE(ops.list(engine + "/sandboxEnvironments/1234567890123456789").empty());
for (const char* family : {"sandboxEnvironments", "sandboxEnvironmentTemplates",
"sandboxEnvironmentSnapshots"}) {
try {
ops.get(engine + "/" + family + "/1234567890123456789/operations/1");
FAIL("an operation that cannot exist must not be found");
} catch (const GoogleError& e) {
std::cout << " live: " << family << " " << e.http_status() << " " << e.status() << "\n";
ASSERT_EQ(e.http_status(), 404);
ASSERT_EQ(e.status(), std::string("NOT_FOUND"));
ASSERT_TRUE(e.message().find("Operation") != std::string::npos);
}
}
}
TEST(google_live_sandbox, sign_jwt_probe) {
// signJwt creates no cloud resource; it signs a small claim set with the
// service account. Observed 2026-10-24: 403 because the IAM Credentials API
// is not enabled on the project (route, path and body shape were accepted
// far enough to reach that check). With the API enabled and
// roles/iam.serviceAccountTokenCreator this returns a three part JWT.
if (!live_ready()) {
std::cout << "SKIP google_live_sandbox.sign_jwt_probe (set MOLO_LIVE_NET=1, "
"a Google credential and GOOGLE_CLOUD_PROJECT)\n";
return;
}
DataPlaneOptions o = DataPlaneOptions::from_env();
if (o.service_account_email.empty()) {
std::cout << "SKIP google_live_sandbox.sign_jwt_probe (no service account email)\n";
return;
}
IamJwtSource src(GoogleClient::from_env(), o.service_account_email);
try {
std::string jwt = src.token();
ASSERT_EQ(std::count(jwt.begin(), jwt.end(), '.'), 2);
std::cout << " live: signJwt returned a JWT\n";
} catch (const GoogleError& e) {
std::cout << " live: signJwt " << e.http_status() << " " << e.status() << "\n";
ASSERT_TRUE(e.http_status() == 403 || e.http_status() == 400);
}
}
+76 -13
View File
@@ -373,27 +373,89 @@ TEST(sandbox_bodies, snapshot_and_template) {
}
TEST(sandbox_bodies, execute_inputs) {
Json req = ChunkCodec::request({ChunkCodec::code_input("print(1)", {{"a.txt", "hi"}})});
// Code: one JSON chunk {"code"}, then one chunk per file (SDK shape).
std::vector<Chunk> code = ChunkCodec::code_inputs(
"print(1)", {{"a.txt", "hi", ""}, {"b.bin", "x", "application/x-test"}});
ASSERT_EQ(code.size(), 3u);
Json req = ChunkCodec::request(code);
expect_keys_declared(req, "sandbox.execute");
const Json& chunk = req.find("inputs")->as_array().front();
ASSERT_EQ(chunk.find("mimeType")->as_string(), std::string("application/json"));
// data is base64 on the wire: it must not be the plain JSON text.
ASSERT_TRUE(chunk.find("data")->as_string().find('{') == std::string::npos);
Chunk back = Chunk::from_json(chunk);
Json payload = Json::parse(back.data);
Json payload = Json::parse(Chunk::from_json(chunk).data);
ASSERT_EQ(payload.find("code")->as_string(), std::string("print(1)"));
ASSERT_EQ(payload.find("files")->as_array().size(), 1u);
Json sh = Json::parse(ChunkCodec::shell_input("ls", "/workspace", 5).data);
ASSERT_EQ(sh.find("command")->as_string(), std::string("ls"));
ASSERT_EQ(sh.find("timeout")->as_int(), 5);
Json cdp = Json::parse(ChunkCodec::cdp_input("Page.navigate", ComputerUse::navigate_params("https://a.b")).data);
ASSERT_EQ(cdp.find("command")->as_string(), std::string("Page.navigate"));
ASSERT_EQ(cdp.find("params")->find("url")->as_string(), std::string("https://a.b"));
ASSERT_TRUE(payload.find("files") == nullptr);
ASSERT_EQ(code[1].mime_type, std::string("text/plain"));
ASSERT_EQ(code[1].data, std::string("hi"));
ASSERT_EQ(code[1].attributes.at("file_name"), std::string("a.txt"));
ASSERT_EQ(code[2].mime_type, std::string("application/x-test"));
// The file name attribute is base64 on the wire too (Discovery: format byte).
Json wire = req.find("inputs")->as_array()[1];
ASSERT_EQ(wire.find("metadata")->find("attributes")->find("file_name")->as_string(),
std::string("YS50eHQ="));
// Shell: request URI, port, then the JSON command (SDK execute_bash).
std::vector<Chunk> sh = ChunkCodec::shell_inputs("ls", "/workspace", 5);
ASSERT_EQ(sh.size(), 3u);
ASSERT_EQ(sh[0].mime_type, std::string("application/x.sandbox-request-uri"));
ASSERT_EQ(sh[0].data, std::string("/exec"));
ASSERT_EQ(sh[1].mime_type, std::string("application/x.sandbox-request-port"));
ASSERT_EQ(sh[1].data, std::string("8080"));
Json cmd = Json::parse(sh[2].data);
ASSERT_EQ(cmd.find("command")->as_string(), std::string("ls"));
ASSERT_EQ(cmd.find("cwd")->as_string(), std::string("/workspace"));
ASSERT_EQ(cmd.find("timeout")->as_int(), 5);
ASSERT_INVALID(ChunkCodec::request({}));
std::vector<Chunk> many(SandboxCaps::kMaxInputChunks + 1);
ASSERT_INVALID(ChunkCodec::request(many));
Json m = ComputerUse::mouse_params("mousePressed", 3, 4);
ASSERT_EQ(m.find("type")->as_string(), std::string("mousePressed"));
ASSERT_EQ(m.find("x")->as_int(), 3);
}
TEST(sandbox_codec, shell_and_code_outputs_decode) {
// Output shapes from the docs and SDK (msg_out/msg_err, stdout/stderr/returncode),
// built here with our own encoder: this proves the decoder, not Google.
auto reply_of = [](const Json& payload) {
Json outs = Json::array();
outs.push(Chunk::json_payload(payload).to_json());
Json r = Json::object();
r.set("outputs", outs);
return r;
};
Json sh = Json::parse(R"({"stdout":"hi\n","stderr":"e","returncode":2,"duration_ms":8})");
ExecutionResult a = ChunkCodec::decode(reply_of(sh));
ASSERT_EQ(a.std_out, std::string("hi\n"));
ASSERT_EQ(a.std_err, std::string("e"));
ASSERT_EQ(*a.exit_status, 2);
ASSERT_EQ(a.duration_ms, 8);
ASSERT_TRUE(!a.ok());
Json code = Json::parse(R"({"msg_out":"o","msg_err":"","output_files":[{"name":"f.txt","content":"aGk="}]})");
ExecutionResult b = ChunkCodec::decode(reply_of(code));
ASSERT_EQ(b.std_out, std::string("o"));
ASSERT_EQ(b.files.size(), 1u);
ASSERT_EQ(b.files[0].content, std::string("hi"));
// A non-base64 attribute value is skipped loudly, never guessed.
Json bad = Json::object();
bad.set("mimeType", Json("text/plain"));
bad.set("data", Json("aGk="));
Json attrs = Json::object();
attrs.set("file_name", Json("not base64!"));
Json meta = Json::object();
meta.set("attributes", attrs);
bad.set("metadata", meta);
Json outs = Json::array();
outs.push(bad);
Json r = Json::object();
r.set("outputs", outs);
ExecutionResult c = ChunkCodec::decode(r);
ASSERT_TRUE(c.files.empty());
ASSERT_EQ(c.skipped.size(), 1u);
}
TEST(sandbox_codec, chunk_round_trip_with_attributes) {
Chunk c;
c.mime_type = "text/plain";
@@ -507,7 +569,7 @@ TEST(sandbox_requests, shapes_over_a_failing_transport) {
seen = probe([](const auto& c) { Sandboxes(c).pause(kSandbox); });
ASSERT_EQ(seen[0].target, "/v1/" + kSandbox + ":pause");
seen = probe([](const auto& c) { StreamExecutor(c).run(kSandbox, {ChunkCodec::shell_input("ls", "", 5)}); });
seen = probe([](const auto& c) { StreamExecutor(c).run(kSandbox, ChunkCodec::shell_inputs("ls", "", 5)); });
ASSERT_TRUE(!seen.empty());
ASSERT_EQ(seen[0].target, "/v1beta1/" + kSandbox + ":bidiExecute");
}
@@ -521,9 +583,10 @@ TEST(sandbox_calls, table_is_well_formed) {
ASSERT_TRUE(std::string(c.path).rfind("{+", 0) == 0);
std::string v = c.version;
ASSERT_TRUE(v == "v1" || v == "v1beta1");
ASSERT_TRUE(std::string(c.rpc).rfind("aiplatform.projects.locations.reasoningEngines.", 0) == 0);
ASSERT_TRUE(std::string(c.rpc).rfind("aiplatform.projects.locations.reasoningEngines.", 0) == 0 ||
std::string(c.rpc) == "iamcredentials.projects.serviceAccounts.signJwt");
}
ASSERT_EQ(sizeof(kDeclaredCalls) / sizeof(kDeclaredCalls[0]), 18u);
ASSERT_EQ(sizeof(kDeclaredCalls) / sizeof(kDeclaredCalls[0]), 34u);
}
TEST(google_live_sandbox, read_only_probe) {