| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/pkg/sftp" |
| 19 | "github.com/sylvinus/agent-vm/internal/remotehost" |
| 20 | ) |
| 21 | |
| 22 | |
| 23 | |
| 24 | func TestNativeCloudShareGrantAndRevocation(t *testing.T) { |
| 25 | root, profile, home := t.TempDir(), t.TempDir(), t.TempDir() |
| 26 | t.Setenv("HOME", home) |
| 27 | t.Setenv("USERPROFILE", home) |
| 28 | t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) |
| 29 | t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local")) |
| 30 | if err := os.WriteFile(isolatedGitConfig(t), []byte("[safe]\n bareRepository = explicit\n"), 0600); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | token := randomToken() |
| 34 | peers := make(chan net.Conn, 1) |
| 35 | var lie atomic.Bool |
| 36 | cloud := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 37 | id := r.URL.Query().Get("id") |
| 38 | if r.URL.Path != "/api/projects/client-share" || len(id) != 32 || r.URL.RawQuery != "id="+id || strings.Contains(fmt.Sprint(r.Header), token) { |
| 39 | t.Errorf("cloud received unexpected route/credentials") |
| 40 | http.NotFound(w, r) |
| 41 | return |
| 42 | } |
| 43 | switch r.Method { |
| 44 | case http.MethodPost: |
| 45 | if r.Header.Get("Upgrade") != "cage-sftp-v1" || r.ContentLength != 0 { |
| 46 | t.Error("unexpected SFTP handshake") |
| 47 | return |
| 48 | } |
| 49 | conn, rw, err := w.(http.Hijacker).Hijack() |
| 50 | if err != nil { |
| 51 | t.Error(err) |
| 52 | return |
| 53 | } |
| 54 | fmt.Fprint(rw, "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: cage-sftp-v1\r\n\r\n") |
| 55 | rw.Flush() |
| 56 | peers <- conn |
| 57 | case http.MethodGet: |
| 58 | path := "/run/cage-client-projects/" + id |
| 59 | if lie.Load() { |
| 60 | path = root |
| 61 | } |
| 62 | jsonReply(w, map[string]string{"workspace": path}) |
| 63 | } |
| 64 | })) |
| 65 | defer cloud.Close() |
| 66 | ctx, cancel := context.WithCancel(t.Context()) |
| 67 | defer cancel() |
| 68 | session := &remotehost.Session{Origin: cloud.URL, Context: ctx, Transport: cloud.Client().Transport, Manifest: remotehost.PublicManifest{Capabilities: map[string]bool{"client_project_share": true}}} |
| 69 | g := newRemoteGateway(profile) |
| 70 | g.desktop = &desktopGateway{generation: "selected", active: &desktopTarget{mode: "remote", ctx: ctx, session: session}} |
| 71 | s := &Server{profile: profile, token: token, remote: g} |
| 72 | request := func(method, route, body, generation string) *httptest.ResponseRecorder { |
| 73 | r := httptest.NewRequest(method, "/api/client/"+route, strings.NewReader(body)) |
| 74 | r.Header.Set(connectionHeader, generation) |
| 75 | r.Header.Set("Content-Type", "application/json") |
| 76 | w := httptest.NewRecorder() |
| 77 | s.clientRequest(w, r) |
| 78 | return w |
| 79 | } |
| 80 | body := func(secret string) string { |
| 81 | data, _ := json.Marshal(map[string]any{"path": root, "readonly": false, "token": secret}) |
| 82 | return string(data) |
| 83 | } |
| 84 | if w := request("POST", "project-shares", body(""), "selected"); w.Code != http.StatusForbidden { |
| 85 | t.Fatal("browser without native authorization", w.Code) |
| 86 | } |
| 87 | if w := request("POST", "project-shares", body(token), "stale"); w.Code != http.StatusConflict { |
| 88 | t.Fatal("stale native picker", w.Code) |
| 89 | } |
| 90 | w := request("POST", "project-shares", body(token), "selected") |
| 91 | var grant ClientProjectShare |
| 92 | if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &grant) != nil { |
| 93 | t.Fatal("grant:", w.Code, w.Body.String()) |
| 94 | } |
| 95 | conn := <-peers |
| 96 | defer conn.Close() |
| 97 | conn.SetDeadline(time.Now().Add(5 * time.Second)) |
| 98 | peer, err := sftp.NewClientPipe(conn, conn) |
| 99 | if err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | defer peer.Close() |
| 103 | f, err := peer.Create("/source.txt") |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | if _, err = f.Write([]byte("written in cloud")); err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | if data, err := os.ReadFile(filepath.Join(root, "source.txt")); err != nil || string(data) != "written in cloud" { |
| 111 | t.Fatal("missing local write", err) |
| 112 | } |
| 113 | if err := exerciseProjectGitWrites(peer, ""); err != nil { |
| 114 | t.Fatal("cloud grant blocked project metadata writes", err) |
| 115 | } |
| 116 | if w := request("GET", "project-shares", "", "selected"); w.Code != 200 || !strings.Contains(w.Body.String(), grant.ID) { |
| 117 | t.Fatal("missing grant", w) |
| 118 | } |
| 119 | if w := request("DELETE", "project-shares/"+grant.ID, "", "selected"); w.Code != 200 { |
| 120 | t.Fatal("revoke:", w.Code) |
| 121 | } |
| 122 | if _, err = f.Write([]byte("post revoke")); err == nil { |
| 123 | t.Fatal("old file handle usable after revoke") |
| 124 | } |
| 125 | w = request("GET", "project-shares", "", "selected") |
| 126 | if strings.Contains(w.Body.String(), grant.ID) { |
| 127 | t.Fatal("revoked grant listed") |
| 128 | } |
| 129 | lie.Store(true) |
| 130 | if w = request("POST", "project-shares", body(token), "selected"); w.Code == 200 { |
| 131 | t.Fatal("cloud selected an arbitrary guest path") |
| 132 | } |
| 133 | conn = <-peers |
| 134 | defer conn.Close() |
| 135 | conn.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 136 | var buf [1]byte |
| 137 | if _, err = conn.Read(buf[:]); err != io.EOF { |
| 138 | t.Fatal("unconfirmed grant kept alive", err) |
| 139 | } |
| 140 | lie.Store(false) |
| 141 | if w = request("POST", "project-shares", body(token), "selected"); w.Code != 200 { |
| 142 | t.Fatal("re-grant", w.Code, w.Body.String()) |
| 143 | } |
| 144 | afterDisconnect := <-peers |
| 145 | defer afterDisconnect.Close() |
| 146 | cancel() |
| 147 | g.drainClosedClientShares() |
| 148 | afterDisconnect.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 149 | if _, err = afterDisconnect.Read(buf[:]); err != io.EOF { |
| 150 | t.Fatal("disconnected SFTP tunnel still accessible", err) |
| 151 | } |
| 152 | if len(g.clientShares) != 0 { |
| 153 | t.Fatal("disconnected grants retained") |
| 154 | } |
| 155 | } |