mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
devvm agent import wrote each settings file into the store as it read it, so a file that failed to read partway (changed since it was listed, or past the bounds) left the store half replaced. The import now reads and writes every agent's settings into a staging folder of the agent's store first (.devvm-import-<random>, beside the agent's folder, so no VM mounts it), and only once all of them are staged, and the run isn't interrupted, moves each file into place, prunes what the home folder no longer has and then saves the logins. A failure or an interrupt while staging leaves the store as it was: the staging folder goes, through discard, or through a cleanup for an interrupted run, which reaches it by a root of its own. A failure after that (a rename, a login) can still leave the store partly replaced, which internals/agents.md says. A killed import's leftover staging folder counts as nothing of the agent's (inStore), so it never makes the import ask, and the next import of that agent takes it out first (sweepStages). The import's bounds on an agent's own folder now match devvm agent save's: the walk counts every entry it meets, links, sockets and FIFOs included, not only the folders and files it keeps, and a file of more than 16 MiB, as listed or as read, fails the import as the 128 MiB does. Claude Code's plugin records are copied with the store's longer paths, and what the copy grows counts against the same bounds (hostAgent.grew), naming the folder, or the link a file came through, so the store never gets more than the import checked. The two handles on an agent's folder, the os.Root it lists through and the folder opened one folder at a time that it reads through, are checked to be one folder (sameFolder), failing the import otherwise. A VM state the import can't read is a warning (agent_import_states_unread), naming the file, rather than silently dropping that VM from the project-inside warnings and the link checks; the follower takes the VMs the import read at its start instead of reading them again. state.WriteFileIn and writeFileMode share one tail (finishTemp). clearKind takes the root the import opened once, rather than opening the store for every path, and pruneStore's walk is pruneIn, which the import calls on the same root. Cursor's changing verbs (proxy's cursorChanges), checked again against the 1,463 methods of DashboardService, AutomationsService and BackgroundComposerService in 2026.11.17-f532c45, read and not run. generate goes: it matched only GenerateGrokCollectionDescription, which only returns a draft, and GenerateTeamGrokBotScimIdpSigningKey, which cursorCredential refuses anyway; no other method changes between refused and passed. test stays, justified in its comment: it matches TestAutomationFilter, a dry run that only reads, but also TestTeamCustomerTelemetryDestinationConnection, which has Cursor's servers send a request with any headers to any address. park, hand, decline, replace and resend match only methods that cursorCredential refuses too (as rotate, link and invite do), and stay, justified in the comment, for the methods Cursor adds. Every cursorRoutes path the CLI's login goes to is checked against the proxy by agentlogin's TestCursorCapture (proxy can't import agentlogin, which imports it); TestCursorChangingVerbs now says so. devvm agent login on a terminal saves the terminal's state before the login (ui.Terminal, through vm.Env.Terminal, which now returns a restore) and puts it back once the login and endLogin are done, or in a UI cleanup if the run ends first, so an ssh that a signal killed in raw mode doesn't leave the host terminal raw. Tests that fail without their fix: TestAgentImportFailsWhole (a failed import leaves the store's own files and no staging folder), TestAgentImportTooMuch (rewritten: its dead want field gone; exactly 20,000 entries and 128 MiB list whole, one more entry or byte fails, a link and a FIFO count, a file of 16 MiB and a byte fails), TestAgentImportPluginsGrow, TestSameFolder (the helper, and the import with its folder swapped between the two opens), TestAgentImportStageLeftover, TestAgentImportInterrupted (the ctx check before apply, and the interrupt cleanup on its own), TestAgentImportProjectInside (beside a broken state), TestCursorChangingVerbs (GenerateGrokCollectionDescription passes), TestAgentLoginTerminal (put back once, after the login ended, interrupted included), TestTerminalRestores. Tests that pin what already held: TestNarrowNotesBesideBroken (devvm network's -g allowlists beside a VM state that can't be read), TestWriteFileIn (a failed rename leaves no temporary file), and TestCursorChangingVerbs' TestTeamCustomerTelemetryDestinationConnection. The finder now checks fst with found, so nilaway no longer reports fst's flow, and all of fst's lines in its baseline go. Docs: using/coding-agents.md, internals/agents.md, internals/network.md; CHANGELOG. Co-Authored-By: Claude Opus 5.5 <[email protected]>
382 lines
21 KiB
Go
382 lines
21 KiB
Go
package proxy
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
"testing/iotest"
|
|
)
|
|
|
|
// Cursor's hosts are its API's, its agent's (api5's, every one of them) and its indexing's.
|
|
func TestCursorHost(t *testing.T) {
|
|
for host, want := range map[string]bool{
|
|
"api2.cursor.sh": true, "api5.cursor.sh": true, "agent.api5.cursor.sh": true, "agentn.us.api5.cursor.sh": true,
|
|
"repo42.cursor.sh": true, "api3.cursor.sh": false, "cursor.sh": false, "xapi5.cursor.sh": false,
|
|
"api2.cursor.sh.example.com": false, "localhost": false,
|
|
} {
|
|
if cursorHost(host) != want {
|
|
t.Errorf("cursorHost(%s) = %v", host, !want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// On Cursor's hosts the proxy refuses every request below /auth/ but its login's poll, a GET to
|
|
// api2's /auth/poll, which it captures; the RPCs that make a credential; a part of a reply
|
|
// (Range); and any path it can't read as the hosts do. The agent's RPCs pass.
|
|
func TestCursorMints(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
host, method, path string
|
|
refused bool
|
|
}{
|
|
{"api2.cursor.sh", "GET", "/auth/poll?uuid=u&verifier=v", false},
|
|
{"api2.cursor.sh", "GET", "/AUTH/Poll", false},
|
|
{"api2.cursor.sh", "POST", "/auth/poll", true},
|
|
{"api2.cursor.sh", "GET", "/auth/exchange_user_api_key", true},
|
|
{"api2.cursor.sh", "POST", "/auth", true},
|
|
{"api5.cursor.sh", "GET", "/auth/poll", true},
|
|
{"agent.api5.cursor.sh", "GET", "/auth/poll?uuid=u&verifier=v", true},
|
|
{"agentn.us.api5.cursor.sh", "POST", "/Auth/x", true},
|
|
{"api2.cursor.sh", "GET", "/x;/../auth/poll", true},
|
|
{"api2.cursor.sh", "GET", "/x/..%2fauth/poll", true},
|
|
{"api2.cursor.sh", "GET", "/auth%2fpoll", true},
|
|
{"api2.cursor.sh", "GET", "/x/../auth/poll", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.ChatService./StreamChat", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.ChatService%20/StreamChat", true},
|
|
{"api2.cursor.sh", "POST", "/aé/StreamChat", true},
|
|
{"api2.cursor.sh", "POST", `/x\auth/poll`, true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/StreamChat", false},
|
|
{"agent.api5.cursor.sh", "POST", "/agent.v1.AgentService/Run", false},
|
|
{"api2.cursor.sh", "GET", "/authx/poll", false},
|
|
{"repo42.cursor.sh", "POST", "/auth/poll", true},
|
|
{"repo42.cursor.sh", "POST", "/aiserver.v1.RepositoryService/SyncMerkleSubtree", false},
|
|
// The RPCs that make or show a credential, by name, and in any service whatever says so;
|
|
// the CLI's own pass.
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/MintRealtimeVoiceSecret", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/CreateUserApiKey", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/RotateServiceToken", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/GetMcpOAuthTokens", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.dashboardservice/createteamapikey", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/KeyringGetSecret", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/RefreshGithubAccessTokenInBackgroundComposer", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/CreateLoginLink", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/GetSessionCookie", true},
|
|
{"agent.api5.cursor.sh", "POST", "/agent.v1.AgentService/InviteMember", true},
|
|
{"repo42.cursor.sh", "POST", "/aiserver.v1.RepositoryService/GetUploadKey", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/GetMe", false},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/GetUserPrivacyMode", false},
|
|
// Changes to the account that outlast the VM: by name, and by a changing verb in the
|
|
// account's services; reading them passes.
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/InstallUserPlugin", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AutomationsService/ApplyAutomationSpec", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AutomationsService/EnableAutomation", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/StartBackgroundComposerFromSnapshot", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/SetTeamEnvironmentJson", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/UpdateTeamMember", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/AddTeamRepo", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/TestBedrockCredentials", true},
|
|
// Every method of the account's services whose verb is clone, commit, generate, mute,
|
|
// unmute, reindex or retry, none of which the CLI calls (2026.11.17-f532c45, read, not run).
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AutomationsService/RetryAutomationRun", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/CommitBackgroundComposer", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/MuteBackgroundComposers", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/UnmuteBackgroundComposers", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/CloneGrokCollection", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/CommitOrganizationNetworkBlocklistUpload", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/GenerateTeamGrokBotScimIdpSigningKey", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/ReindexAndApplyTeamMarketplaceChanges", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/ReindexGrokCollectionDocument", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/RetrySandMessagesPermission", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/RetryTeamXaiMembershipHold", true},
|
|
// The cloud agents' own endpoints, such as the worker's identity tokens, on every host.
|
|
{"api2.cursor.sh", "POST", "/cloud-agent/identity-token/worker", true},
|
|
{"agent.api5.cursor.sh", "GET", "/Cloud-Agent/anything", true},
|
|
// The same verbs outside the account's services pass, as the CLI's own calls do.
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AiService/GenerateCommitMessage", false},
|
|
{"repo42.cursor.sh", "POST", "/aiserver.v1.RepositoryService/ReindexRepository", false},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AutomationsService/ListAutomations", false},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.BackgroundComposerService/ListBackgroundComposers", false},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.DashboardService/SubmitFeedback", false},
|
|
// The agent store, every method of it, on every host, in any case: its token, its reads
|
|
// and its writes.
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/MintAgentStoreToken", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/PresignAgentStoreReads", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/ListAgentStoreDirectory", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/CheckAgentStoreVersions", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/RecordAgentStoreListingVersionAudit", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/PresignAgentStoreWrites", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/CompleteAgentStoreMultipartWrites", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/AbortAgentStoreMultipartWrites", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/DeleteAgentStoreFiles", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/RmdirAgentStore", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/WriteAgentStoreDocument", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/ShareAgentStore", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.agentstoreservice/listagentstoredirectory", true},
|
|
{"agent.api5.cursor.sh", "POST", "/aiserver.v1.AgentStoreService/ListAgentStoreDirectory", true},
|
|
// Any version or package of a store's service, as defence in depth.
|
|
{"api2.cursor.sh", "POST", "/aiserver.v2.AgentStoreService/ListAgentStoreDirectory", true},
|
|
{"api2.cursor.sh", "POST", "/agent.v1.AgentStoreV2Service/Read", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.agentstoresharingservice/List", true},
|
|
{"api2.cursor.sh", "POST", "/aiserver.v1.AgentService/ListAgentStoreDirectory", false},
|
|
} {
|
|
u, err := url.Parse("https://" + tc.host + tc.path)
|
|
if err != nil {
|
|
u = &url.URL{Path: tc.path}
|
|
}
|
|
r := &http.Request{Method: tc.method, URL: u, Header: http.Header{}}
|
|
if got := cursorMints(tc.host, r); (got != "") != tc.refused {
|
|
t.Errorf("cursorMints(%s %s%s) = %q, want refused %v", tc.method, tc.host, tc.path, got, tc.refused)
|
|
}
|
|
}
|
|
for _, p := range cursorMinting {
|
|
if cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: p}, Header: http.Header{}}) == "" {
|
|
t.Errorf("%s passes", p)
|
|
}
|
|
}
|
|
ranged := &http.Request{Method: http.MethodPost, URL: &url.URL{Path: "/aiserver.v1.AiService/StreamChat"}, Header: http.Header{"Range": {"bytes=10-20"}}}
|
|
if cursorMints(cursorAPI, ranged) == "" {
|
|
t.Error("a Range passes")
|
|
}
|
|
}
|
|
|
|
// In the account's services, a method for each verb that a check of the pinned release
|
|
// (2026.11.17-f532c45, read, not run) found changing something is refused, and the CLI calls none
|
|
// of them. The CLI's own calls in those services pass, Submit's and Resolve's among them, which is
|
|
// why neither verb is refused, and so does a method that only reads, which no verb matches. Every
|
|
// path the CLI's login goes to (agentlogin's cursorRoutes) passes too, which agentlogin's
|
|
// TestCursorCapture checks, as this package can't import agentlogin, which imports it.
|
|
func TestCursorChangingVerbs(t *testing.T) {
|
|
const d, b, a = "/aiserver.v1.DashboardService/", "/aiserver.v1.BackgroundComposerService/", "/aiserver.v1.AutomationsService/"
|
|
for _, p := range []string{
|
|
d + "MergeOrganizationIdentityProvider", b + "ForkBackgroundComposer", b + "WriteMachineTextFile",
|
|
b + "PinBackgroundComposers", b + "UnpinBackgroundComposers", a + "RerunGrokBotAutomationFromCard",
|
|
d + "ConfirmGithubInstallation", d + "RequestOrganizationGroupAnthropicEfs", b + "ReleasePrivateWorkerClaim",
|
|
b + "AcquireAgentStoreFileLock", d + "ActivatePromotion", d + "DeactivateGrokAdminGuardrail",
|
|
d + "NotifyBugbotTeamAdmins", b + "MakePRBackgroundComposer", b + "OpenPRBackgroundComposer",
|
|
d + "EnsureXaiCursorTeamForMerge", d + "ParkUnifyGrokOAuthForAppSheet", d + "CopyOrganizationTeamSettingsToTeam",
|
|
d + "BulkMoveOrganizationMembers", d + "AdvanceXaiUnificationIntent", b + "AbortAgentStoreMultipartWrites",
|
|
b + "WakeBackgroundComposer", b + "SnapshotAndSaveEnvironment", b + "SeedStagedProjects",
|
|
b + "ReplyToReviewThread", d + "OptOutNewPricing", d + "HandOffMcpOAuthCode", b + "FailPrivateWorkerClaim",
|
|
d + "UseSandBankedReset", d + "SkipPrivacyModeGracePeriod", d + "DecideAppReviewOverride",
|
|
b + "UnshareBackgroundComposerArtifact", b + "UndeleteAgentStoreFiles", d + "UnpublishPlugin",
|
|
d + "UnprepareXaiCursorTeamMergeCheckout", b + "UnresolveReviewThread", d + "EnrollInGlassEarlyPreview",
|
|
d + "UnenrollFromGlassEarlyPreview", d + "UpgradeToYearly", d + "SuspendTeamServiceAccount",
|
|
d + "SwitchTeamPrivacyMode", b + "DuplicateEnvironment", b + "DismissStagedProject",
|
|
b + "DeregisterPrivateWorkerPool", b + "DeliverMainBotEvalEvent", b + "DeclineProjectInvite",
|
|
b + "ConvertPullRequestFromDraft", b + "CloseEventSubscription", d + "AppendRsiRecord", d + "ExecuteSandMcpTool",
|
|
d + "ProvisionUnifyGrokAccount", b + "MutateProjectTrackedTasks", b + "InjectBackgroundComposerContext",
|
|
d + "FinishSetupGithubEnterpriseApp", d + "FinalizeIndividualUnification", a + "ReassignAutomationOwner",
|
|
b + "ReinstallProjectSlackApp", d + "RejectPlugin", b + "RenewAgentStoreFileLock", b + "ReorderPendingFollowup",
|
|
b + "ReparentBackgroundComposer", d + "ReplaceTeamLlmGatewayCredential", d + "ResendTeamPendingInvite",
|
|
b + "RmdirAgentStore", d + "ReportGrokCreditPackPurchase", d + "RecordSandAuditEvents",
|
|
} {
|
|
if cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: p}, Header: http.Header{}}) == "" {
|
|
t.Errorf("%s passes", p)
|
|
}
|
|
}
|
|
for _, p := range []string{
|
|
a + "ValidateAutomationSpec", d + "ResolvePluginsByRef", d + "SubmitFeedback", d + "SubmitFeedbackAnon",
|
|
d + "GetEffectiveUserPlugins", b + "GetBackgroundComposerStatus", b + "ListPrivateWorkers",
|
|
// A method that only reads, which no verb matches: it drafts a description and only returns it.
|
|
d + "GenerateGrokCollectionDescription",
|
|
} {
|
|
if got := cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: p}, Header: http.Header{}}); got != "" {
|
|
t.Errorf("%s refused: %s", p, got)
|
|
}
|
|
}
|
|
// test refuses TestAutomationFilter, which only reads, for this one, which has Cursor's servers
|
|
// send a request anywhere.
|
|
if cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: d + "TestTeamCustomerTelemetryDestinationConnection"}, Header: http.Header{}}) == "" {
|
|
t.Error("TestTeamCustomerTelemetryDestinationConnection passes")
|
|
}
|
|
}
|
|
|
|
// What of a request to a Cursor host asks for a compressed reply goes: HTTP's, Connect's and
|
|
// gRPC's.
|
|
func TestCursorUnencoded(t *testing.T) {
|
|
h := http.Header{"Accept-Encoding": {"br"}, "Connect-Accept-Encoding": {"gzip"}, "Grpc-Accept-Encoding": {"gzip"}, "Content-Type": {"application/proto"}}
|
|
cursorUnencoded(h)
|
|
if len(h) != 1 || h.Get("Content-Type") == "" {
|
|
t.Errorf("left %v", h)
|
|
}
|
|
}
|
|
|
|
// cursorJWT is a JWT as a Cursor host could hand one out, in a protobuf field.
|
|
const cursorJWT = "\x0a\x40eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4In0.real-signature\x10"
|
|
|
|
// A Cursor host's reply passes as it comes, from a server through Go's transport as the proxy's
|
|
// forwarder has it: gzipped (which Go undoes, its length unknown), chunked, or with no length at
|
|
// all, and is cut off at the read that would complete a JWT's start, even split across chunks, with
|
|
// none of the token's claims or signature passed. Before that, what came passes. (A unary reply's
|
|
// body: a stream's is read message by message, TestCursorStreams.)
|
|
func TestCursorReplyScans(t *testing.T) {
|
|
s := &server{captures: newCaptures(nil, nil)}
|
|
before := strings.Repeat("x", 5000) + "eyJ"
|
|
var gotAE string
|
|
// In memory: its client's transport reaches it whatever the host.
|
|
srv := httptest.NewTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotAE = r.Header.Get("Accept-Encoding")
|
|
w.Header().Set("Content-Type", "application/proto")
|
|
body := before + strings.TrimPrefix(cursorJWT, "\x0a\x40eyJ")
|
|
switch r.URL.Path {
|
|
case "/gzip":
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
gz := gzip.NewWriter(w)
|
|
_, _ = io.WriteString(gz, body)
|
|
_ = gz.Close()
|
|
case "/chunked": // the JWT's start split across the chunks
|
|
for i := 0; i < len(body); i += 7 {
|
|
_, _ = io.WriteString(w, body[i:min(i+7, len(body))])
|
|
w.(http.Flusher).Flush()
|
|
}
|
|
case "/plain":
|
|
_, _ = io.WriteString(w, "\x0a\x03abc")
|
|
}
|
|
}))
|
|
tr := srv.Client().Transport
|
|
for _, p := range []string{"/gzip", "/chunked"} {
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://cursor.test"+p, nil)
|
|
req.Header.Set("Accept-Encoding", "br") // the VM's
|
|
cursorUnencoded(req.Header)
|
|
resp, err := tr.RoundTrip(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := s.cursorReply(resp); err != nil {
|
|
t.Fatalf("%s: %v", p, err)
|
|
}
|
|
// Read a byte at a time, the hardest split: the JWT's header passes, harmless, and the
|
|
// read that would complete its claims' start fails.
|
|
got, err := io.ReadAll(iotest.OneByteReader(resp.Body))
|
|
_ = resp.Body.Close()
|
|
body := before + strings.TrimPrefix(cursorJWT, "\x0a\x40eyJ")
|
|
if !errors.Is(err, errCaptureRefused) || strings.Contains(string(got), "eyJzdWIi") || strings.Contains(string(got), "real-signature") ||
|
|
!strings.HasPrefix(body, string(got)) || len(got) < len(before) {
|
|
t.Errorf("%s: read %d bytes (%q…), %v", p, len(got), got[max(0, len(got)-20):], err)
|
|
}
|
|
if gotAE == "br" {
|
|
t.Errorf("%s: the server was asked for br", p)
|
|
}
|
|
}
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://cursor.test/plain", nil)
|
|
resp, err := tr.RoundTrip(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if err := s.cursorReply(resp); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if b, err := io.ReadAll(resp.Body); err != nil || !bytes.Equal(b, []byte("\x0a\x03abc")) {
|
|
t.Errorf("a reply without a JWT: %q, %v", b, err)
|
|
}
|
|
}
|
|
|
|
// A Cursor host's reply that the proxy can't read is refused: a part of one (206), one encoded as
|
|
// the request didn't ask, by HTTP, Connect or gRPC, and a redirect to a token.
|
|
func TestCursorReplyRefuses(t *testing.T) {
|
|
s := &server{captures: newCaptures(nil, nil)}
|
|
for name, h := range map[string]http.Header{
|
|
"a part": {},
|
|
"br": {"Content-Encoding": {"br"}},
|
|
"Connect's gzip": {"Connect-Content-Encoding": {"gzip"}},
|
|
"gRPC's gzip": {"Grpc-Encoding": {"gzip"}},
|
|
"a token in its redirect": {"Location": {"https://cursor.com/x#t=eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4In0.sig"}},
|
|
"a token in its redirect.": {"Location": {"/x?t=eyJhbGciOiJSUzI1NiJ9.eyJzdWIi"}},
|
|
} {
|
|
code := http.StatusOK
|
|
if name == "a part" {
|
|
code = http.StatusPartialContent
|
|
}
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://api2.cursor.sh/aiserver.v1.AiService/X", nil)
|
|
resp := &http.Response{StatusCode: code, Header: h, Body: io.NopCloser(strings.NewReader("ok")), Request: req}
|
|
if err := s.cursorReply(resp); !errors.Is(err, errCaptureRefused) {
|
|
t.Errorf("%s: %v", name, err)
|
|
}
|
|
}
|
|
for name, h := range map[string]http.Header{
|
|
"identity": {"Connect-Content-Encoding": {"identity"}},
|
|
"a redirect": {"Location": {"https://cursor.com/settings"}},
|
|
} {
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://api2.cursor.sh/aiserver.v1.AiService/X", nil)
|
|
resp := &http.Response{StatusCode: http.StatusOK, Header: h, Body: io.NopCloser(strings.NewReader("ok")), Request: req}
|
|
if err := s.cursorReply(resp); err != nil {
|
|
t.Errorf("%s: %v", name, err)
|
|
}
|
|
_ = resp.Body.Close()
|
|
}
|
|
}
|
|
|
|
// The agent store gets nothing from a VM, and its token never reaches one: a request to mint it is
|
|
// refused, and a reply that holds one, from that method or any other, is cut off at it. Every
|
|
// method cursorPersists names is refused too.
|
|
func TestCursorStoreToken(t *testing.T) {
|
|
const mint = "/aiserver.v1.AgentStoreService/MintAgentStoreToken"
|
|
if cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: mint}, Header: http.Header{}}) == "" {
|
|
t.Error("minting the store's token passes")
|
|
}
|
|
s := &server{captures: newCaptures(nil, nil)}
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://"+cursorAPI+mint, nil)
|
|
resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(cursorJWT)), Request: req}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if err := s.cursorReply(resp); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if b, err := io.ReadAll(resp.Body); !errors.Is(err, errCaptureRefused) || strings.Contains(string(b), "real-signature") {
|
|
t.Errorf("the store's token: %q, %v", b, err)
|
|
}
|
|
for _, p := range cursorPersists {
|
|
if cursorMints(cursorAPI, &http.Request{Method: http.MethodPost, URL: &url.URL{Path: p}, Header: http.Header{}}) == "" {
|
|
t.Errorf("%s passes", p)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A Cursor host's reply sets no cookie, and holds no token in any header, its name or its value,
|
|
// nor in the trailers that come after its body, as HTTP/2 and gRPC send them: the body's end fails,
|
|
// so ReverseProxy, which copies the trailers after it, never sends them.
|
|
func TestCursorReplyHeaders(t *testing.T) {
|
|
s := &server{captures: newCaptures(nil, nil)}
|
|
const tok = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4In0.sig"
|
|
reply := func(h http.Header) *http.Response {
|
|
req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://agent.api5.cursor.sh/agent.v1.AgentService/Run", nil)
|
|
return &http.Response{StatusCode: http.StatusOK, Header: h, Body: io.NopCloser(strings.NewReader("ok")), Request: req, Trailer: http.Header{}}
|
|
}
|
|
ok := reply(http.Header{"Set-Cookie": {"session=x"}, "X-Request-Id": {"abc"}})
|
|
if err := s.cursorReply(ok); err != nil || ok.Header.Get("Set-Cookie") != "" || ok.Header.Get("X-Request-ID") != "abc" {
|
|
t.Errorf("a plain reply: %v, %v", err, ok.Header)
|
|
}
|
|
_ = ok.Body.Close()
|
|
for _, h := range []http.Header{{"X-Session": {tok}}, {"Grpc-Message": {"token " + tok}}, {"X-" + tok: {"1"}}} {
|
|
r := reply(h)
|
|
if err := s.cursorReply(r); !errors.Is(err, errCaptureRefused) {
|
|
t.Errorf("a token in %v: %v", h, err)
|
|
}
|
|
_ = r.Body.Close()
|
|
}
|
|
// Trailers: filled in once the body has ended, as Go's transport does.
|
|
trailed := reply(http.Header{})
|
|
if err := s.cursorReply(trailed); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
trailed.Trailer.Set("Grpc-Status-Details-Bin", tok)
|
|
if _, err := io.ReadAll(trailed.Body); !errors.Is(err, errCaptureRefused) {
|
|
t.Errorf("a token in a trailer: %v", err)
|
|
}
|
|
_ = trailed.Body.Close()
|
|
clean := reply(http.Header{})
|
|
if err := s.cursorReply(clean); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
clean.Trailer.Set("Grpc-Status", "0")
|
|
if b, err := io.ReadAll(clean.Body); err != nil || string(b) != "ok" {
|
|
t.Errorf("plain trailers: %q, %v", b, err)
|
|
}
|
|
_ = clean.Body.Close()
|
|
}
|