| 1 | package hostimage |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "encoding/xml" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "runtime" |
| 19 | "strings" |
| 20 | "testing" |
| 21 | |
| 22 | "github.com/sylvinus/agent-vm/internal/cage" |
| 23 | ) |
| 24 | |
| 25 | func TestMacSourceReadsIdentityWithoutUserFiles(t *testing.T) { |
| 26 | dir := t.TempDir() |
| 27 | path := filepath.Join(dir, "system.ipsw") |
| 28 | file, err := os.Create(path) |
| 29 | if err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | archive := zip.NewWriter(file) |
| 33 | manifest, _ := archive.Create("BuildManifest.plist") |
| 34 | fmt.Fprint(manifest, `<plist><dict><key>BuildIdentities</key><array><dict><key>ProductVersion</key><string>wrong</string></dict>`) |
| 35 | |
| 36 | fmt.Fprint(manifest, strings.Repeat(" ", 17<<20)) |
| 37 | fmt.Fprint(manifest, `</array><key>ProductVersion</key><string>26.5</string><key>ProductBuildVersion</key><string>25F71</string></dict></plist>`) |
| 38 | if err = archive.Close(); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | file.Close() |
| 42 | host := Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"} |
| 43 | plan, ok := localMacImage(host, dir) |
| 44 | if !ok || plan.Path != path { |
| 45 | t.Fatalf("source not found: %+v", plan) |
| 46 | } |
| 47 | prepared, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil) |
| 48 | if err != nil || !strings.HasPrefix(prepared.Digest, "sha256:") { |
| 49 | t.Fatalf("prepare: %+v %v", prepared, err) |
| 50 | } |
| 51 | host.Build = "25F84" |
| 52 | if _, ok := localMacImage(host, dir); ok { |
| 53 | t.Fatal("accepted different macOS build") |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestSourceRejectsUntrustedURLsAndUnsupportedSystems(t *testing.T) { |
| 58 | base := Plan{Host: Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"}, Version: "26.5", Build: "25F71", Format: "ipsw", Digest: "sha256:" + strings.Repeat("a", 64), URL: "https://updates.cdn-apple.com/system.ipsw"} |
| 59 | if err := base.Validate(); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | for _, url := range []string{"http://updates.cdn-apple.com/a", "https://updates.cdn-apple.com.evil.test/a", "https://[email protected]/a", "https://updates.cdn-apple.com:443/a"} { |
| 63 | plan := base |
| 64 | plan.URL = url |
| 65 | if err := plan.Validate(); err == nil { |
| 66 | t.Errorf("accepted %q", url) |
| 67 | } |
| 68 | } |
| 69 | base.Host.System = "arch-linux" |
| 70 | if err := base.Validate(); err == nil { |
| 71 | t.Fatal("accepted unsupported source") |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func TestMacCloneRequiresGuestFileSystemSupport(t *testing.T) { |
| 76 | for _, version := range []string{"14.7.6", "15.4", "26.3", "26.4", "26.5"} { |
| 77 | plan := Plan{Host: Identity{System: "macos", Version: version, Build: "fixture", Arch: "arm64"}, Version: version, |
| 78 | Build: "fixture", Format: "ipsw", Path: filepath.Join(t.TempDir(), "system.ipsw")} |
| 79 | err := plan.Validate() |
| 80 | allowed := version == "26.4" || version == "26.5" |
| 81 | if (err == nil) != allowed { |
| 82 | t.Fatalf("version %s: %v", version, err) |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | func TestSourceKeyAndSpaceAllowCompletedConcurrentDownload(t *testing.T) { |
| 88 | cache := t.TempDir() |
| 89 | plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Arch: "amd64", Edition: "Professional", Language: "en-US"}, Version: "25H2", Build: "26200.1", Format: "esd", URL: "http://dl.delivery.mp.microsoft.com/example.esd", Digest: "sha256:" + strings.Repeat("a", 64), Bytes: 10} |
| 90 | if err := plan.Validate(); err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | if err := os.WriteFile(plan.CachedPath(cache)+".partial", []byte("123456"), 0600); err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | if remaining := plan.RemainingBytes(cache); remaining != 4 { |
| 97 | t.Fatalf("remaining=%d", remaining) |
| 98 | } |
| 99 | ready := plan |
| 100 | ready.Path = plan.CachedPath(cache) |
| 101 | ready.Modified = 123 |
| 102 | if ready.Key() != plan.Key() { |
| 103 | t.Fatal("a completed cache invalidated the selected image") |
| 104 | } |
| 105 | if remaining := ready.RemainingBytes(cache); remaining != 0 { |
| 106 | t.Fatalf("ready remaining=%d", remaining) |
| 107 | } |
| 108 | plan.Digest = "" |
| 109 | if err := plan.Validate(); err == nil { |
| 110 | t.Fatal("accepted HTTP media without the HTTPS catalog digest") |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | func TestWindowsCatalogKeepsFeatureReleaseAndEdition(t *testing.T) { |
| 115 | var catalog windowsMediaCatalog |
| 116 | data := `<PublishedMedia><Files><File><FileName>26300.9457.26h2_release.esd</FileName><LanguageCode>zh-cn</LanguageCode><Edition>Professional</Edition><Architecture>x64</Architecture><Size>100</Size><Sha256>` + strings.Repeat("a", 64) + `</Sha256><FilePath>http://dl.delivery.mp.microsoft.com/windows.esd</FilePath></File></Files></PublishedMedia>` |
| 117 | if err := xml.Unmarshal([]byte(data), &catalog); err != nil { |
| 118 | t.Fatal(err) |
| 119 | } |
| 120 | host := Identity{System: "windows-11", Version: "26H2", Build: "26300.9711", Edition: "Professional", Language: "zh-CN", Arch: "amd64"} |
| 121 | plan, ok := selectWindowsMedia(catalog, host) |
| 122 | if !ok || plan.Build != "26300.9457" || plan.Version != "26H2" { |
| 123 | t.Fatalf("catalog match: %+v %v", plan, ok) |
| 124 | } |
| 125 | if err := plan.Validate(); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | host.Build = "26200.9711" |
| 129 | host.Version = "25H2" |
| 130 | if _, ok := selectWindowsMedia(catalog, host); ok { |
| 131 | t.Fatal("silently changed the Windows feature release") |
| 132 | } |
| 133 | host.Build = "26300.9711" |
| 134 | host.Edition = "Enterprise" |
| 135 | if _, ok := selectWindowsMedia(catalog, host); ok { |
| 136 | t.Fatal("silently changed the Windows edition") |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | func TestDownloadResumesAndRejectsWrongRange(t *testing.T) { |
| 141 | for _, wrong := range []bool{false, true} { |
| 142 | t.Run(fmt.Sprint(wrong), func(t *testing.T) { |
| 143 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 144 | if r.Header.Get("Range") != "bytes=3-" { |
| 145 | t.Error("did not request resume") |
| 146 | } |
| 147 | start := 3 |
| 148 | if wrong { |
| 149 | start = 2 |
| 150 | } |
| 151 | w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-5/6", start)) |
| 152 | w.WriteHeader(http.StatusPartialContent) |
| 153 | fmt.Fprint(w, "def") |
| 154 | })) |
| 155 | defer server.Close() |
| 156 | file, err := os.CreateTemp(t.TempDir(), "partial") |
| 157 | if err != nil { |
| 158 | t.Fatal(err) |
| 159 | } |
| 160 | defer file.Close() |
| 161 | file.WriteString("abc") |
| 162 | var progress bytes.Buffer |
| 163 | err = download(t.Context(), Plan{Host: Identity{System: "windows-11"}, URL: server.URL, Bytes: 6}, file, 3, &progress, nil) |
| 164 | if wrong { |
| 165 | if err == nil { |
| 166 | t.Fatal("accepted wrong range") |
| 167 | } |
| 168 | return |
| 169 | } |
| 170 | if err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | data, _ := os.ReadFile(file.Name()) |
| 174 | if string(data) != "abcdef" { |
| 175 | t.Fatalf("got %q", data) |
| 176 | } |
| 177 | if !strings.Contains(progress.String(), "CAGE_GUEST_BYTES windows-11 download 6 6") { |
| 178 | t.Fatalf("missing actual resumed byte progress: %s", progress.String()) |
| 179 | } |
| 180 | }) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestPrepareRejectsModifiedSourceAndPreservesIt(t *testing.T) { |
| 185 | dir := t.TempDir() |
| 186 | path := filepath.Join(dir, "system.esd") |
| 187 | os.WriteFile(path, []byte("original"), 0600) |
| 188 | info, _ := os.Stat(path) |
| 189 | digest := sha256.Sum256([]byte("original")) |
| 190 | plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"}, Version: "25H2", Build: "26200.8", Format: "esd", Path: path, Bytes: 8, Modified: info.ModTime().UnixNano(), Digest: "sha256:" + hex.EncodeToString(digest[:])} |
| 191 | os.WriteFile(path, []byte("tampered"), 0600) |
| 192 | if _, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil); err == nil { |
| 193 | t.Fatal("accepted changed source") |
| 194 | } |
| 195 | data, _ := os.ReadFile(path) |
| 196 | if string(data) != "tampered" { |
| 197 | t.Fatal("changed user's source") |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func TestPrepareRecoversOversizedPartialWithoutDiscardingIt(t *testing.T) { |
| 202 | cache := t.TempDir() |
| 203 | content := []byte("valid image") |
| 204 | digest := sha256.Sum256(content) |
| 205 | plan := Plan{ |
| 206 | Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"}, |
| 207 | Version: "25H2", Build: "26200.8", Format: "esd", Bytes: int64(len(content)), |
| 208 | URL: "http://dl.delivery.mp.microsoft.com/fixture.esd", Digest: "sha256:" + hex.EncodeToString(digest[:]), |
| 209 | } |
| 210 | partial := plan.CachedPath(cache) + ".partial" |
| 211 | bad := []byte("oversized incomplete response") |
| 212 | if err := os.WriteFile(partial, bad, 0600); err != nil { |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | requests := 0 |
| 216 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 217 | requests++ |
| 218 | if r.Header.Get("Range") != "" { |
| 219 | t.Error("retried using the oversized prefix") |
| 220 | } |
| 221 | _, _ = w.Write(content) |
| 222 | })) |
| 223 | defer server.Close() |
| 224 | transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { |
| 225 | return new(net.Dialer).DialContext(ctx, network, server.Listener.Addr().String()) |
| 226 | }} |
| 227 | defer transport.CloseIdleConnections() |
| 228 | for attempt := 0; attempt < 2; attempt++ { |
| 229 | ready, err := Prepare(t.Context(), cache, plan, io.Discard, transport) |
| 230 | if err != nil || ready.Digest != plan.Digest || ready.Path != plan.CachedPath(cache) { |
| 231 | t.Fatalf("retry did not prepare the original image: %+v %v", ready, err) |
| 232 | } |
| 233 | } |
| 234 | retained, err := filepath.Glob(partial + ".invalid-*") |
| 235 | if err != nil || len(retained) != 1 || requests != 1 { |
| 236 | t.Fatalf("retained=%v requests=%d error=%v", retained, requests, err) |
| 237 | } |
| 238 | data, err := os.ReadFile(retained[0]) |
| 239 | if err != nil || !bytes.Equal(data, bad) { |
| 240 | t.Fatal("discarded the failed response", err) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | func TestLiveHostSource(t *testing.T) { |
| 247 | dir := os.Getenv("CAGE_TEST_HOST_SOURCE") |
| 248 | if dir == "" { |
| 249 | t.Skip("set CAGE_TEST_HOST_SOURCE to a private test directory") |
| 250 | } |
| 251 | if !filepath.IsAbs(dir) { |
| 252 | t.Fatal("absolute test directory required") |
| 253 | } |
| 254 | host, err := Host(context.Background()) |
| 255 | if err != nil { |
| 256 | t.Fatal(err) |
| 257 | } |
| 258 | if IsLinux(host.System) { |
| 259 | t.Skip("Linux live source uses bundled template through the workbench") |
| 260 | } |
| 261 | var transport *http.Transport |
| 262 | if config := os.Getenv("CAGE_TEST_HOST_CONFIG"); config != "" { |
| 263 | cfg, err := cage.Load(config) |
| 264 | if err != nil { |
| 265 | t.Fatal(err) |
| 266 | } |
| 267 | egress, err := cage.NewEgress(cfg) |
| 268 | if err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | transport = &http.Transport{Proxy: nil, DialContext: egress.DialContext} |
| 272 | defer transport.CloseIdleConnections() |
| 273 | } |
| 274 | var roundTripper http.RoundTripper |
| 275 | if transport != nil { |
| 276 | roundTripper = transport |
| 277 | } |
| 278 | plan, err := Resolve(t.Context(), host, dir, dir, nil, roundTripper) |
| 279 | if err != nil { |
| 280 | t.Fatal(err) |
| 281 | } |
| 282 | data, _ := json.MarshalIndent(plan, "", " ") |
| 283 | t.Log(runtime.GOOS, string(data)) |
| 284 | if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | if os.Getenv("CAGE_TEST_HOST_SOURCE_DOWNLOAD") != "1" { |
| 288 | return |
| 289 | } |
| 290 | plan, err = Prepare(t.Context(), dir, plan, os.Stdout, roundTripper) |
| 291 | if err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | data, _ = json.MarshalIndent(plan, "", " ") |
| 295 | if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil { |
| 296 | t.Fatal(err) |
| 297 | } |
| 298 | } |