跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

defaults_test.go

1111 行 · 33.6 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limayaml
5
6import (
7 "fmt"
8 "net"
9 "os"
10 "path"
11 "path/filepath"
12 "runtime"
13 "slices"
14 "strconv"
15 "testing"
16
17 "github.com/google/go-cmp/cmp"
18 "github.com/google/go-cmp/cmp/cmpopts"
19 "github.com/sirupsen/logrus"
20 "gotest.tools/v3/assert"
21
22 "github.com/lima-vm/lima/v2/pkg/fsutil"
23 "github.com/lima-vm/lima/v2/pkg/limatype"
24 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
25 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
26 "github.com/lima-vm/lima/v2/pkg/osutil"
27 "github.com/lima-vm/lima/v2/pkg/version"
28)
29
30func TestExistingLimaVersion(t *testing.T) {
31 t.Run("instance does not exist yet", func(t *testing.T) {
32 assert.Equal(t, ExistingLimaVersion(t.TempDir()), version.Version)
33 })
34
35 t.Run("version has been recorded", func(t *testing.T) {
36 instDir := createInstanceDir(t, map[string]string{filenames.LimaVersion: "1.2.3\n"})
37 assert.Equal(t, ExistingLimaVersion(instDir), "1.2.3")
38 })
39
40 // Instances created before Lima v0.20 have no lima-version file. Reporting the current
41 // version for them would move the guest home directory to a path that doesn't exist.
42 t.Run("instance predates the version file", func(t *testing.T) {
43 instDir := createInstanceDir(t, nil)
44 assert.Equal(t, ExistingLimaVersion(instDir), "")
45
46 user := osutil.LimaUser(t.Context(), ExistingLimaVersion(instDir), false, nil)
47 assert.Equal(t, user.HomeDir, "/home/{{.User}}.linux")
48 })
49}
50
51// createInstanceDir returns a directory that IsExistingInstanceDir recognizes as an
52// existing instance, populated with files.
53func createInstanceDir(t *testing.T, files map[string]string) string {
54 t.Helper()
55 instDir := t.TempDir()
56 // The host agent log is one of the files that identify an existing instance.
57 assert.NilError(t, os.WriteFile(filepath.Join(instDir, filenames.HostAgentStdoutLog), nil, 0o644))
58 for name, content := range files {
59 assert.NilError(t, os.WriteFile(filepath.Join(instDir, name), []byte(content), 0o644))
60 }
61 return instDir
62}
63
64func TestFillDefault(t *testing.T) {
65 logrus.SetLevel(logrus.DebugLevel)
66 var d, y, o limatype.LimaYAML
67
68 opts := []cmp.Option{
69 // Consider nil slices and empty slices to be identical
70 cmpopts.EquateEmpty(),
71 }
72
73 var arch limatype.Arch
74 switch runtime.GOARCH {
75 case "amd64":
76 arch = limatype.X8664
77 case "arm64":
78 arch = limatype.AARCH64
79 case "arm":
80 if runtime.GOOS != "linux" {
81 t.Skipf("unsupported GOOS: %s", runtime.GOOS)
82 }
83 if arm := limatype.Goarm(); arm < 7 {
84 t.Skipf("unsupported GOARM: %d", arm)
85 }
86 arch = limatype.ARMV7L
87 case "ppc64le":
88 arch = limatype.PPC64LE
89 case "riscv64":
90 arch = limatype.RISCV64
91 case "s390x":
92 arch = limatype.S390X
93 default:
94 t.Skipf("unknown GOARCH: %s", runtime.GOARCH)
95 }
96
97 hostHome, err := os.UserHomeDir()
98 assert.NilError(t, err)
99 limaHome, err := dirnames.LimaDir()
100 assert.NilError(t, err)
101 user := osutil.LimaUser(t.Context(), "0.0.0", false, nil)
102 user.HomeDir = fmt.Sprintf("/home/%s.guest", user.Username)
103 uid, err := strconv.ParseUint(user.Uid, 10, 32)
104 assert.NilError(t, err)
105
106 instName := "instance"
107 instDir := filepath.Join(limaHome, instName)
108 filePath := filepath.Join(instDir, filenames.LimaYAML)
109
110 // Builtin default values
111 builtin := limatype.LimaYAML{
112 OS: new(limatype.LINUX),
113 Arch: new(arch),
114 CPUs: new(defaultCPUs()),
115 Memory: new(defaultMemoryAsString()),
116 Disk: new(defaultDiskSizeAsString()),
117 GuestInstallPrefix: new(defaultGuestInstallPrefix()),
118 UpgradePackages: new(false),
119 Containerd: limatype.Containerd{
120 System: new(false),
121 User: new(true),
122 Archives: defaultContainerdArchives(),
123 },
124 SSH: limatype.SSH{
125 LocalPort: new(0),
126 LoadDotSSHPubKeys: new(false),
127 ForwardAgent: new(false),
128 ForwardX11: new(false),
129 ForwardX11Trusted: new(false),
130 },
131 TimeZone: new(hostTimeZone()),
132 Firmware: limatype.Firmware{
133 LegacyBIOS: new(false),
134 },
135 Audio: limatype.Audio{
136 Device: new(""),
137 Interface: new(""),
138 Microphone: new(false),
139 },
140 Video: limatype.Video{
141 Display: new("none"),
142 },
143 HostResolver: limatype.HostResolver{
144 Enabled: nil,
145 IPv6: new(false),
146 },
147 PropagateProxyEnv: new(true),
148 CACertificates: limatype.CACertificates{
149 RemoveDefaults: new(false),
150 },
151 NestedVirtualization: new(false),
152 Plain: new(false),
153 User: limatype.User{
154 Name: new(user.Username),
155 Comment: new(user.Name),
156 Home: new(user.HomeDir),
157 Shell: new("/bin/bash"),
158 UID: new(uint32(uid)),
159 PasswordlessSudo: new(true),
160 },
161 TPM: new(false),
162 }
163
164 defaultPortForward := limatype.PortForward{
165 GuestIP: IPv4loopback1,
166 GuestIPMustBeZero: new(false),
167 GuestPortRange: [2]int{1, 65535},
168 HostIP: IPv4loopback1,
169 HostPortRange: [2]int{1, 65535},
170 Proto: limatype.ProtoAny,
171 Reverse: false,
172 }
173
174 // ------------------------------------------------------------------------------------
175 // Builtin defaults are set when y is (mostly) empty
176
177 // All these slices and maps are empty in "builtin". Add minimal entries here to see that
178 // their values are retained and defaults for their fields are applied correctly.
179 y = limatype.LimaYAML{
180 HostResolver: limatype.HostResolver{
181 Hosts: map[string]string{
182 "MY.Host": "host.lima.internal",
183 },
184 },
185 Mounts: []limatype.Mount{
186 //nolint:usetesting // We need the OS temp directory name here; it is not used to create temp files for testing
187 {Location: filepath.Clean(os.TempDir())},
188 {Location: filepath.Clean("{{.Dir}}/{{.Param.ONE}}"), MountPoint: new("/mnt/{{.Param.ONE}}")},
189 },
190 MountType: new(limatype.NINEP),
191 Provision: []limatype.Provision{
192 {Script: new("#!/bin/true # {{.Param.ONE}}")},
193 },
194 Probes: []limatype.Probe{
195 {Script: new("#!/bin/false # {{.Param.ONE}}")},
196 },
197 Networks: []limatype.Network{
198 {Lima: "shared"},
199 },
200 DNS: []net.IP{
201 net.ParseIP("1.0.1.0"),
202 },
203 PortForwards: []limatype.PortForward{
204 {},
205 {GuestPort: 80},
206 {GuestPort: 8080, HostPort: 8888},
207 {
208 GuestSocket: "{{.Home}} | {{.UID}} | {{.User}} | {{.Param.ONE}}",
209 HostSocket: "{{.Home}} | {{.Dir}} | {{.Name}} | {{.UID}} | {{.User}} | {{.Param.ONE}}",
210 },
211 },
212 CopyToHost: []limatype.CopyToHost{
213 {
214 GuestFile: "{{.Home}} | {{.UID}} | {{.User}} | {{.Param.ONE}}",
215 HostFile: "{{.Home}} | {{.Dir}} | {{.Name}} | {{.UID}} | {{.User}} | {{.Param.ONE}}",
216 },
217 },
218 Env: map[string]string{
219 "ONE": "Eins",
220 },
221 Param: map[string]string{
222 "ONE": "Eins",
223 },
224 CACertificates: limatype.CACertificates{
225 Files: []string{"ca.crt"},
226 Certs: []string{
227 "-----BEGIN CERTIFICATE-----\nYOUR-ORGS-TRUSTED-CA-CERT\n-----END CERTIFICATE-----\n",
228 },
229 },
230 TimeZone: new("Antarctica/Troll"),
231 }
232
233 expect := builtin
234 // VMType should remain nil when not explicitly set (will be resolved by ValidateVMType later)
235 expect.VMType = nil
236 expect.HostResolver.Hosts = map[string]string{
237 "MY.Host": "host.lima.internal",
238 }
239
240 expect.Mounts = slices.Clone(y.Mounts)
241 expect.Mounts[0].MountPoint = new(expect.Mounts[0].Location)
242 if runtime.GOOS == "windows" {
243 mountLocation, err := fsutil.WindowsSubsystemPath(t.Context(), expect.Mounts[0].Location)
244 if err == nil {
245 expect.Mounts[0].MountPoint = new(mountLocation)
246 }
247 }
248 expect.Mounts[0].Writable = new(false)
249 expect.Mounts[0].SSHFS.Cache = new(true)
250 expect.Mounts[0].SSHFS.FollowSymlinks = new(false)
251 expect.Mounts[0].SSHFS.SFTPDriver = new("")
252 expect.Mounts[0].NineP.SecurityModel = new(Default9pSecurityModel)
253 expect.Mounts[0].NineP.ProtocolVersion = new(Default9pProtocolVersion)
254 expect.Mounts[0].NineP.Msize = new(Default9pMsize)
255 expect.Mounts[0].NineP.Cache = new(Default9pCacheForRO)
256 expect.Mounts[0].Virtiofs.QueueSize = nil
257 // Only missing Mounts field is Writable, and the default value is also the null value: false
258 expect.Mounts[1].Location = filepath.Join(instDir, y.Param["ONE"])
259 expect.Mounts[1].MountPoint = new(path.Join("/mnt", y.Param["ONE"]))
260 expect.Mounts[1].Writable = new(false)
261 expect.Mounts[1].SSHFS.Cache = new(true)
262 expect.Mounts[1].SSHFS.FollowSymlinks = new(false)
263 expect.Mounts[1].SSHFS.SFTPDriver = new("")
264 expect.Mounts[1].NineP.SecurityModel = new(Default9pSecurityModel)
265 expect.Mounts[1].NineP.ProtocolVersion = new(Default9pProtocolVersion)
266 expect.Mounts[1].NineP.Msize = new(Default9pMsize)
267 expect.Mounts[1].NineP.Cache = new(Default9pCacheForRO)
268 expect.Mounts[1].Virtiofs.QueueSize = nil
269
270 expect.MountType = new(limatype.NINEP)
271
272 expect.MountInotify = new(false)
273
274 expect.Provision = slices.Clone(y.Provision)
275 expect.Provision[0].Mode = limatype.ProvisionModeSystem
276 expect.Provision[0].Script = new("#!/bin/true # Eins")
277
278 expect.Probes = slices.Clone(y.Probes)
279 expect.Probes[0].Mode = limatype.ProbeModeReadiness
280 expect.Probes[0].Description = "user probe 1/1"
281 expect.Probes[0].Script = new("#!/bin/false # Eins")
282
283 expect.Networks = slices.Clone(y.Networks)
284 expect.Networks[0].MACAddress = MACAddress(fmt.Sprintf("%s#%d", filePath, 0))
285 expect.Networks[0].Interface = "lima0"
286 expect.Networks[0].Metric = new(uint32(100))
287
288 expect.DNS = slices.Clone(y.DNS)
289 expect.PortForwards = []limatype.PortForward{
290 defaultPortForward,
291 defaultPortForward,
292 defaultPortForward,
293 defaultPortForward,
294 }
295 expect.CopyToHost = []limatype.CopyToHost{
296 {},
297 }
298
299 // Setting GuestPort and HostPort for DeepEqual(), but they are not supposed to be used
300 // after FillDefault() has been called and the ...PortRange fields have been set.
301 expect.PortForwards[1].GuestPort = 80
302 expect.PortForwards[1].GuestPortRange = [2]int{80, 80}
303 expect.PortForwards[1].HostPortRange = expect.PortForwards[1].GuestPortRange
304
305 expect.PortForwards[2].GuestPort = 8080
306 expect.PortForwards[2].GuestPortRange = [2]int{8080, 8080}
307 expect.PortForwards[2].HostPort = 8888
308 expect.PortForwards[2].HostPortRange = [2]int{8888, 8888}
309
310 expect.PortForwards[3].HostPortRange = [2]int{0, 0}
311 expect.PortForwards[3].GuestSocket = fmt.Sprintf("%s | %s | %s | %s", user.HomeDir, user.Uid, user.Username, y.Param["ONE"])
312 expect.PortForwards[3].HostSocket = fmt.Sprintf("%s | %s | %s | %s | %s | %s", hostHome, instDir, instName, currentUser.Uid, currentUser.Username, y.Param["ONE"])
313
314 expect.CopyToHost[0].GuestFile = fmt.Sprintf("%s | %s | %s | %s", user.HomeDir, user.Uid, user.Username, y.Param["ONE"])
315 expect.CopyToHost[0].HostFile = fmt.Sprintf("%s | %s | %s | %s | %s | %s", hostHome, instDir, instName, currentUser.Uid, currentUser.Username, y.Param["ONE"])
316
317 expect.Env = y.Env
318
319 expect.Param = y.Param
320
321 expect.CACertificates = limatype.CACertificates{
322 RemoveDefaults: new(false),
323 Files: []string{"ca.crt"},
324 Certs: []string{
325 "-----BEGIN CERTIFICATE-----\nYOUR-ORGS-TRUSTED-CA-CERT\n-----END CERTIFICATE-----\n",
326 },
327 }
328
329 expect.TimeZone = y.TimeZone
330 // Set firmware expectations to match what FillDefault actually does
331 // FillDefault uses the builtin default values, which include LegacyBIOS: new(false)
332 expect.Firmware = limatype.Firmware{
333 LegacyBIOS: new(false), // This matches what FillDefault actually sets
334 Images: nil,
335 }
336
337 expect.NestedVirtualization = new(false)
338 expect.TPM = new(false)
339
340 FillDefault(t.Context(), &y, &limatype.LimaYAML{}, &limatype.LimaYAML{}, filePath, false)
341 assert.DeepEqual(t, &y, &expect, opts...)
342
343 filledDefaults := y
344
345 // ------------------------------------------------------------------------------------
346 // User-provided defaults should override any builtin defaults
347
348 // Choose values that are different from the "builtin" defaults
349
350 // Calling filepath.Abs() to add a drive letter on Windows
351 varLog, _ := filepath.Abs("/var/log")
352 d = limatype.LimaYAML{
353 // Remove driver-specific VMType from defaults test
354 OS: new("unknown"),
355 Arch: new("unknown"),
356 CPUs: new(7),
357 Memory: new("5GiB"),
358 Disk: new("105GiB"),
359 AdditionalDisks: []limatype.Disk{
360 {Name: "data"},
361 },
362 GuestInstallPrefix: new("/opt"),
363 UpgradePackages: new(true),
364 Containerd: limatype.Containerd{
365 System: new(true),
366 User: new(false),
367 Archives: []limatype.File{
368 {Location: "/tmp/nerdctl.tgz"},
369 },
370 },
371 SSH: limatype.SSH{
372 LocalPort: new(888),
373 LoadDotSSHPubKeys: new(false),
374 ForwardAgent: new(true),
375 ForwardX11: new(false),
376 ForwardX11Trusted: new(false),
377 },
378 TimeZone: new("Zulu"),
379 Firmware: limatype.Firmware{
380 LegacyBIOS: new(true),
381 // Remove driver-specific firmware images from defaults
382 },
383 Audio: limatype.Audio{
384 Device: new("coreaudio"),
385 Interface: new("virtio"),
386 Microphone: new(true),
387 },
388 Video: limatype.Video{
389 Display: new("cocoa"),
390 // Remove driver-specific VNC configuration
391 },
392 HostResolver: limatype.HostResolver{
393 Enabled: new(false),
394 IPv6: new(true),
395 Hosts: map[string]string{
396 "default": "localhost",
397 },
398 },
399 PropagateProxyEnv: new(false),
400
401 Mounts: []limatype.Mount{
402 {
403 Location: varLog,
404 Writable: new(false),
405 },
406 },
407 Provision: []limatype.Provision{
408 {
409 Script: new("#!/bin/true"),
410 Mode: limatype.ProvisionModeUser,
411 },
412 },
413 Probes: []limatype.Probe{
414 {
415 Script: new("#!/bin/false"),
416 Mode: limatype.ProbeModeReadiness,
417 Description: "User Probe",
418 },
419 },
420 Networks: []limatype.Network{
421 {
422 MACAddress: "11:22:33:44:55:66",
423 Interface: "def0",
424 Metric: new(uint32(50)),
425 },
426 },
427 DNS: []net.IP{
428 net.ParseIP("1.1.1.1"),
429 },
430 PortForwards: []limatype.PortForward{{
431 GuestIP: IPv4loopback1,
432 GuestIPMustBeZero: new(false),
433 GuestPort: 80,
434 GuestPortRange: [2]int{80, 80},
435 HostIP: IPv4loopback1,
436 HostPort: 80,
437 HostPortRange: [2]int{80, 80},
438 Proto: limatype.ProtoTCP,
439 }},
440 CopyToHost: []limatype.CopyToHost{{}},
441 Env: map[string]string{
442 "ONE": "one",
443 "TWO": "two",
444 },
445 Param: map[string]string{
446 "ONE": "one",
447 "TWO": "two",
448 },
449 CACertificates: limatype.CACertificates{
450 RemoveDefaults: new(true),
451 Certs: []string{
452 "-----BEGIN CERTIFICATE-----\nYOUR-ORGS-TRUSTED-CA-CERT\n-----END CERTIFICATE-----\n",
453 },
454 },
455 NestedVirtualization: new(true),
456 User: limatype.User{
457 Name: new("xxx"),
458 Comment: new("Foo Bar"),
459 Home: new("/tmp"),
460 Shell: new("/bin/tcsh"),
461 UID: new(uint32(8080)),
462 PasswordlessSudo: new(false),
463 },
464 VMOpts: limatype.VMOpts{
465 "qemu": map[string]any{
466 "minimumVersion": "9.1.0",
467 },
468 },
469 TPM: new(true),
470 }
471
472 expect = d
473 // VMType should remain nil when not explicitly set
474 expect.VMType = nil
475 // Also verify that archive arch is filled in
476 expect.Containerd.Archives = slices.Clone(d.Containerd.Archives)
477 expect.Containerd.Archives[0].Arch = *d.Arch
478 expect.Mounts = slices.Clone(d.Mounts)
479 expect.Mounts[0].MountPoint = new(expect.Mounts[0].Location)
480 if runtime.GOOS == "windows" {
481 mountLocation, err := fsutil.WindowsSubsystemPath(t.Context(), expect.Mounts[0].Location)
482 if err == nil {
483 expect.Mounts[0].MountPoint = new(mountLocation)
484 }
485 }
486 expect.Mounts[0].SSHFS.Cache = new(true)
487 expect.Mounts[0].SSHFS.FollowSymlinks = new(false)
488 expect.Mounts[0].SSHFS.SFTPDriver = new("")
489 expect.Mounts[0].NineP.SecurityModel = new(Default9pSecurityModel)
490 expect.Mounts[0].NineP.ProtocolVersion = new(Default9pProtocolVersion)
491 expect.Mounts[0].NineP.Msize = new(Default9pMsize)
492 expect.Mounts[0].NineP.Cache = new(Default9pCacheForRO)
493 expect.Mounts[0].Virtiofs.QueueSize = nil
494 expect.HostResolver.Hosts = map[string]string{
495 "default": d.HostResolver.Hosts["default"],
496 }
497 // Remove driver-specific mount type from defaults test
498 expect.MountType = nil
499 expect.MountInotify = new(false)
500 expect.CACertificates.RemoveDefaults = new(true)
501 expect.CACertificates.Certs = []string{
502 "-----BEGIN CERTIFICATE-----\nYOUR-ORGS-TRUSTED-CA-CERT\n-----END CERTIFICATE-----\n",
503 }
504
505 expect.Plain = new(false)
506 expect.TPM = new(true)
507
508 y = limatype.LimaYAML{}
509 FillDefault(t.Context(), &y, &d, &limatype.LimaYAML{}, filePath, false)
510 assert.DeepEqual(t, &y, &expect, opts...)
511
512 dExpected := expect
513
514 // ------------------------------------------------------------------------------------
515 // User-provided defaults should not override user-provided config values
516
517 y = filledDefaults
518 y.DNS = []net.IP{net.ParseIP("8.8.8.8")}
519 y.AdditionalDisks = []limatype.Disk{{Name: "overridden"}}
520 y.User.Home = new("/root")
521 y.VMOpts = limatype.VMOpts{
522 "vz": map[string]any{
523 "diskImageFormat": "raw",
524 },
525 }
526
527 expect = y
528
529 expect.Provision = slices.Concat(y.Provision, dExpected.Provision)
530 expect.Probes = slices.Concat(y.Probes, dExpected.Probes)
531 expect.PortForwards = slices.Concat(y.PortForwards, dExpected.PortForwards)
532 expect.CopyToHost = slices.Concat(y.CopyToHost, dExpected.CopyToHost)
533 expect.Containerd.Archives = slices.Concat(y.Containerd.Archives, dExpected.Containerd.Archives)
534 expect.Containerd.Archives[2].Arch = *expect.Arch
535 expect.AdditionalDisks = slices.Concat(y.AdditionalDisks, dExpected.AdditionalDisks)
536 expect.Firmware.Images = slices.Concat(y.Firmware.Images, dExpected.Firmware.Images)
537
538 // Mounts and Networks start with lowest priority first, so higher priority entries can overwrite
539 expect.Mounts = slices.Concat(dExpected.Mounts, y.Mounts)
540 expect.Networks = slices.Concat(dExpected.Networks, y.Networks)
541
542 expect.HostResolver.Hosts["default"] = dExpected.HostResolver.Hosts["default"]
543
544 // The user-provided default is applied when the config doesn't specify it.
545 expect.HostResolver.Enabled = dExpected.HostResolver.Enabled
546
547 // "TWO" does not exist in filledDefaults.Env, so is set from dExpected.Env
548 expect.Env["TWO"] = dExpected.Env["TWO"]
549
550 expect.Param["TWO"] = dExpected.Param["TWO"]
551
552 expect.VMOpts = limatype.VMOpts{
553 "qemu": dExpected.VMOpts["qemu"],
554 "vz": y.VMOpts["vz"],
555 }
556
557 t.Logf("d.vmType=%v, y.vmType=%v, expect.vmType=%v", d.VMType, y.VMType, expect.VMType)
558
559 FillDefault(t.Context(), &y, &d, &limatype.LimaYAML{}, filePath, false)
560 assert.DeepEqual(t, &y, &expect, opts...)
561
562 // ------------------------------------------------------------------------------------
563 // User-provided overrides should override user-provided config settings
564
565 o = limatype.LimaYAML{
566 // Remove driver-specific VMType from override test
567 OS: new(limatype.LINUX),
568 Arch: new(arch),
569 CPUs: new(12),
570 Memory: new("7GiB"),
571 Disk: new("117GiB"),
572 AdditionalDisks: []limatype.Disk{
573 {Name: "test"},
574 },
575 GuestInstallPrefix: new("/usr"),
576 UpgradePackages: new(true),
577 Containerd: limatype.Containerd{
578 System: new(true),
579 User: new(false),
580 Archives: []limatype.File{
581 {
582 Arch: arch,
583 Location: "/tmp/nerdctl.tgz",
584 Digest: "$DIGEST",
585 },
586 },
587 },
588 SSH: limatype.SSH{
589 LocalPort: new(4433),
590 LoadDotSSHPubKeys: new(true),
591 ForwardAgent: new(true),
592 ForwardX11: new(false),
593 ForwardX11Trusted: new(false),
594 },
595 TimeZone: new("Universal"),
596 Firmware: limatype.Firmware{
597 LegacyBIOS: new(true),
598 },
599 Audio: limatype.Audio{
600 Device: new("coreaudio"),
601 Interface: new("hda"),
602 Microphone: new(true),
603 },
604 Video: limatype.Video{
605 Display: new("cocoa"),
606 // Remove driver-specific VNC configuration
607 },
608 HostResolver: limatype.HostResolver{
609 Enabled: new(false),
610 IPv6: new(false),
611 Hosts: map[string]string{
612 "override.": "underflow",
613 },
614 },
615 PropagateProxyEnv: new(false),
616
617 Mounts: []limatype.Mount{
618 {
619 Location: varLog,
620 Writable: new(true),
621 SSHFS: limatype.SSHFS{
622 Cache: new(false),
623 FollowSymlinks: new(true),
624 ReadonlyNames: []string{".git"},
625 },
626 NineP: limatype.NineP{
627 SecurityModel: new("mapped-file"),
628 ProtocolVersion: new("9p2000"),
629 Msize: new("8KiB"),
630 Cache: new("none"),
631 },
632 Virtiofs: limatype.Virtiofs{
633 QueueSize: new(2048),
634 },
635 },
636 },
637 MountInotify: new(true),
638 Provision: []limatype.Provision{
639 {
640 Script: new("#!/bin/true"),
641 Mode: limatype.ProvisionModeSystem,
642 },
643 },
644 Probes: []limatype.Probe{
645 {
646 Script: new("#!/bin/false"),
647 Mode: limatype.ProbeModeReadiness,
648 Description: "Another Probe",
649 },
650 },
651 Networks: []limatype.Network{
652 {
653 Lima: "shared",
654 MACAddress: "10:20:30:40:50:60",
655 Interface: "def1",
656 Metric: new(uint32(25)),
657 },
658 {
659 Lima: "bridged",
660 Interface: "def0",
661 },
662 },
663 DNS: []net.IP{
664 net.ParseIP("2.2.2.2"),
665 },
666 PortForwards: []limatype.PortForward{{
667 GuestIP: IPv4loopback1,
668 GuestIPMustBeZero: new(false),
669 GuestPort: 88,
670 GuestPortRange: [2]int{88, 88},
671 HostIP: IPv4loopback1,
672 HostPort: 8080,
673 HostPortRange: [2]int{8080, 8080},
674 Proto: limatype.ProtoTCP,
675 }},
676 CopyToHost: []limatype.CopyToHost{{}},
677 Env: map[string]string{
678 "TWO": "deux",
679 "THREE": "trois",
680 },
681 Param: map[string]string{
682 "TWO": "deux",
683 "THREE": "trois",
684 },
685 CACertificates: limatype.CACertificates{
686 RemoveDefaults: new(true),
687 },
688 NestedVirtualization: new(false),
689 User: limatype.User{
690 Name: new("foo"),
691 Comment: new("foo bar baz"),
692 Home: new("/override"),
693 Shell: new("/bin/sh"),
694 UID: new(uint32(1122)),
695 PasswordlessSudo: new(true),
696 },
697 VMOpts: limatype.VMOpts{
698 "vz": map[string]any{
699 "rosetta": map[string]any{
700 "enabled": true,
701 "binfmt": true,
702 },
703 },
704 },
705 }
706
707 y = filledDefaults
708
709 expect = o
710
711 expect.Provision = slices.Concat(o.Provision, y.Provision, dExpected.Provision)
712 expect.Probes = slices.Concat(o.Probes, y.Probes, dExpected.Probes)
713 expect.PortForwards = slices.Concat(o.PortForwards, y.PortForwards, dExpected.PortForwards)
714 expect.CopyToHost = slices.Concat(o.CopyToHost, y.CopyToHost, dExpected.CopyToHost)
715 expect.Containerd.Archives = slices.Concat(o.Containerd.Archives, y.Containerd.Archives, dExpected.Containerd.Archives)
716 expect.Containerd.Archives[3].Arch = *expect.Arch
717 expect.AdditionalDisks = slices.Concat(o.AdditionalDisks, y.AdditionalDisks, dExpected.AdditionalDisks)
718 expect.Firmware.Images = slices.Concat(o.Firmware.Images, y.Firmware.Images, dExpected.Firmware.Images)
719
720 expect.HostResolver.Hosts["default"] = dExpected.HostResolver.Hosts["default"]
721 expect.HostResolver.Hosts["MY.Host"] = dExpected.HostResolver.Hosts["host.lima.internal"]
722
723 // o.Mounts just makes dExpected.Mounts[0] writable because the Location matches
724 expect.Mounts = slices.Concat(dExpected.Mounts, y.Mounts)
725 expect.Mounts[0].Writable = new(true)
726 expect.Mounts[0].SSHFS.Cache = new(false)
727 expect.Mounts[0].SSHFS.FollowSymlinks = new(true)
728 expect.Mounts[0].SSHFS.ReadonlyNames = []string{".git"}
729 expect.Mounts[0].NineP.SecurityModel = new("mapped-file")
730 expect.Mounts[0].NineP.ProtocolVersion = new("9p2000")
731 expect.Mounts[0].NineP.Msize = new("8KiB")
732 expect.Mounts[0].NineP.Cache = new("none")
733 expect.Mounts[0].Virtiofs.QueueSize = new(2048)
734
735 expect.MountType = new(limatype.NINEP)
736 expect.MountInotify = new(true)
737
738 // o.Networks[1] is overriding the dExpected.Networks[0].Lima entry for the "def0" interface
739 expect.Networks = slices.Concat(dExpected.Networks, y.Networks, []limatype.Network{o.Networks[0]})
740 expect.Networks[0].Lima = o.Networks[1].Lima
741
742 // Only highest prio DNS are retained
743 expect.DNS = slices.Clone(o.DNS)
744
745 // ONE remains from filledDefaults.Env; the rest are set from o
746 expect.Env["ONE"] = y.Env["ONE"]
747
748 expect.Param["ONE"] = y.Param["ONE"]
749
750 expect.CACertificates.RemoveDefaults = new(true)
751 expect.CACertificates.Files = []string{"ca.crt"}
752 expect.CACertificates.Certs = []string{
753 "-----BEGIN CERTIFICATE-----\nYOUR-ORGS-TRUSTED-CA-CERT\n-----END CERTIFICATE-----\n",
754 }
755
756 expect.Plain = new(false)
757
758 expect.NestedVirtualization = new(false)
759
760 expect.VMOpts = limatype.VMOpts{
761 "qemu": dExpected.VMOpts["qemu"],
762 "vz": map[string]any{
763 "rosetta": map[string]any{
764 "enabled": true,
765 "binfmt": true,
766 },
767 },
768 }
769 expect.TPM = new(false)
770
771 FillDefault(t.Context(), &y, &d, &o, filePath, false)
772 assert.DeepEqual(t, &y, &expect, opts...)
773}
774
775func TestContainerdDefault(t *testing.T) {
776 archives := defaultContainerdArchives()
777 assert.Assert(t, len(archives) > 0)
778}
779
780func TestStaticPortForwarding(t *testing.T) {
781 tests := []struct {
782 name string
783 config limatype.LimaYAML
784 expected []limatype.PortForward
785 }{
786 {
787 name: "plain mode with static port forwards",
788 config: limatype.LimaYAML{
789 Plain: new(true),
790 PortForwards: []limatype.PortForward{
791 {
792 GuestPort: 8080,
793 HostPort: 8080,
794 Static: true,
795 },
796 {
797 GuestPort: 9000,
798 HostPort: 9000,
799 Static: false,
800 },
801 {
802 GuestPort: 8081,
803 HostPort: 8081,
804 },
805 },
806 },
807 expected: []limatype.PortForward{
808 {
809 GuestPort: 8080,
810 HostPort: 8080,
811 Static: true,
812 },
813 },
814 },
815 {
816 name: "non-plain mode with static port forwards",
817 config: limatype.LimaYAML{
818 Plain: new(false),
819 PortForwards: []limatype.PortForward{
820 {
821 GuestPort: 8080,
822 HostPort: 8080,
823 Static: true,
824 },
825 {
826 GuestPort: 9000,
827 HostPort: 9000,
828 Static: false,
829 },
830 },
831 },
832 expected: []limatype.PortForward{
833 {
834 GuestPort: 8080,
835 HostPort: 8080,
836 Static: true,
837 },
838 {
839 GuestPort: 9000,
840 HostPort: 9000,
841 Static: false,
842 },
843 },
844 },
845 {
846 name: "plain mode with no static port forwards",
847 config: limatype.LimaYAML{
848 Plain: new(true),
849 PortForwards: []limatype.PortForward{
850 {
851 GuestPort: 8080,
852 HostPort: 8080,
853 Static: false,
854 },
855 {
856 GuestPort: 9000,
857 HostPort: 9000,
858 },
859 },
860 },
861 expected: []limatype.PortForward{},
862 },
863 }
864
865 for _, tt := range tests {
866 t.Run(tt.name, func(t *testing.T) {
867 fixUpForPlainMode(&tt.config)
868
869 if *tt.config.Plain {
870 for _, pf := range tt.config.PortForwards {
871 if !pf.Static {
872 t.Errorf("Non-static port forward found in plain mode: %+v", pf)
873 }
874 }
875 }
876
877 assert.Equal(t, len(tt.config.PortForwards), len(tt.expected),
878 "Expected %d port forwards, got %d", len(tt.expected), len(tt.config.PortForwards))
879
880 for i, expected := range tt.expected {
881 if i >= len(tt.config.PortForwards) {
882 t.Errorf("Missing port forward at index %d", i)
883 continue
884 }
885 actual := tt.config.PortForwards[i]
886 assert.Equal(t, expected.Static, actual.Static,
887 "Port forward %d: expected Static=%v, got %v", i, expected.Static, actual.Static)
888 assert.Equal(t, expected.GuestPort, actual.GuestPort,
889 "Port forward %d: expected GuestPort=%d, got %d", i, expected.GuestPort, actual.GuestPort)
890 assert.Equal(t, expected.HostPort, actual.HostPort,
891 "Port forward %d: expected HostPort=%d, got %d", i, expected.HostPort, actual.HostPort)
892 }
893 })
894 }
895}
896
897func TestMountTag(t *testing.T) {
898 tests := []struct {
899 name string
900 location string
901 mountPoint string
902 }{
903 {"home directory", "/Users/testuser", "/Users/testuser"},
904 {"nested path", "/Users/testuser/Development/project", "/mnt/project"},
905 {"root path", "/", "/mnt/root"},
906 {"tmp directory", "/tmp/lima", "/tmp/lima"},
907 }
908
909 for _, tt := range tests {
910 t.Run(tt.name, func(t *testing.T) {
911 tag := MountTag(tt.location, tt.mountPoint)
912 assert.Assert(t, len(tag) > 5 && tag[:5] == "lima-")
913 assert.Assert(t, len(tag) <= 36)
914 assert.Equal(t, tag, MountTag(tt.location, tt.mountPoint))
915 })
916 }
917}
918
919func TestMountTagUniqueness(t *testing.T) {
920 mounts := []struct{ location, mountPoint string }{
921 {"/Users/user1", "/Users/user1"},
922 {"/Users/user2", "/Users/user2"},
923 {"/home/user1", "/home/user1"},
924 {"/mnt/data", "/mnt/data"},
925 {"/tmp/lima", "/tmp/lima"},
926 }
927 tags := make(map[string]bool)
928 for _, m := range mounts {
929 tag := MountTag(m.location, m.mountPoint)
930 assert.Assert(t, !tags[tag], "tag collision: %s", tag)
931 tags[tag] = true
932 }
933}
934
935func TestMountTagDuplicateLocation(t *testing.T) {
936 location := "/Users/testuser"
937 tag1 := MountTag(location, "/home/user")
938 tag2 := MountTag(location, "/mnt/home-writable")
939 assert.Assert(t, tag1 != tag2)
940}
941
942// TestContainerdUserDefaultPerOS verifies that FillDefault only enables
943// containerd.user=true on Linux guests for x86_64 and aarch64. nerdctl is a Linux-only runtime,
944// so non-Linux guests (Darwin, FreeBSD) must default to false regardless
945// of the host architecture. Regression test for issue #5037.
946func TestContainerdUserDefaultPerOS(t *testing.T) {
947 cases := []struct {
948 os limatype.OS
949 arch limatype.Arch
950 want bool
951 }{
952 {limatype.LINUX, limatype.X8664, true},
953 {limatype.LINUX, limatype.AARCH64, true},
954 {limatype.LINUX, limatype.RISCV64, false},
955 {limatype.LINUX, limatype.ARMV7L, false},
956 {limatype.DARWIN, limatype.AARCH64, false},
957 {limatype.DARWIN, limatype.X8664, false},
958 {limatype.FREEBSD, limatype.X8664, false},
959 {limatype.FREEBSD, limatype.AARCH64, false},
960 }
961 for _, tc := range cases {
962 t.Run(fmt.Sprintf("%s/%s", tc.os, tc.arch), func(t *testing.T) {
963 y := limatype.LimaYAML{
964 OS: new(tc.os),
965 Arch: new(tc.arch),
966 }
967 var d, o limatype.LimaYAML
968 FillDefault(t.Context(), &y, &d, &o, "", false)
969 assert.Assert(t, y.Containerd.User != nil, "Containerd.User must be set after FillDefault")
970 assert.Equal(t, *y.Containerd.User, tc.want,
971 "Containerd.User default for OS=%s Arch=%s", tc.os, tc.arch)
972 })
973 }
974}
975
976// TestContainerdUserExplicitOverride verifies FillDefault respects an
977// explicit containerd.user=true value even on non-Linux guests.
978func TestContainerdUserExplicitOverride(t *testing.T) {
979 y := limatype.LimaYAML{
980 OS: new(limatype.DARWIN),
981 Arch: new(limatype.AARCH64),
982 Containerd: limatype.Containerd{
983 User: new(true),
984 },
985 }
986 var d, o limatype.LimaYAML
987 FillDefault(t.Context(), &y, &d, &o, "", false)
988 assert.Assert(t, y.Containerd.User != nil)
989 assert.Equal(t, *y.Containerd.User, true,
990 "explicit Containerd.User=true must be preserved on non-Linux guests")
991}
992
993func TestUnmarshalImageVariant(t *testing.T) {
994 yamlBytes := []byte(`
995images:
996- location: "server-img.img"
997 variant: "server"
998- location: "minimal-img.img"
999 variant: "minimal"
1000`)
1001 var y limatype.LimaYAML
1002 err := Unmarshal(yamlBytes, &y, "test")
1003 assert.NilError(t, err)
1004 assert.Equal(t, len(y.Images), 2)
1005 assert.Equal(t, y.Images[0].Variant, "server")
1006 assert.Equal(t, y.Images[1].Variant, "minimal")
1007}
1008
1009func TestUnmarshalImageArchVariant(t *testing.T) {
1010 yamlBytes := []byte(`
1011images:
1012- location: "amd64-img.img"
1013 arch: "x86_64"
1014 variant: "server"
1015- location: "amd64v3-img.img"
1016 arch: "x86_64"
1017 variant: "server"
1018 archVariant: "v3"
1019`)
1020 var y limatype.LimaYAML
1021 err := Unmarshal(yamlBytes, &y, "test")
1022 assert.NilError(t, err)
1023 assert.Equal(t, len(y.Images), 2)
1024 assert.Equal(t, y.Images[0].ArchVariant, "")
1025 assert.Equal(t, y.Images[1].ArchVariant, "v3")
1026}
1027
1028func TestDefaultSelectedImageIsStandard(t *testing.T) {
1029 // Verify that the default order of the images in the standard template
1030 // places standard/server before minimal so standard users don't regress.
1031 data, err := os.ReadFile("../../templates/_images/ubuntu-24.04.yaml")
1032 assert.NilError(t, err)
1033 var y limatype.LimaYAML
1034 err = Unmarshal(data, &y, "ubuntu-24.04.yaml")
1035 assert.NilError(t, err)
1036 var foundServer, foundMinimal bool
1037 for _, img := range y.Images {
1038 switch img.Variant {
1039 case "server":
1040 foundServer = true
1041 assert.Assert(t, !foundMinimal, "standard/server images must be listed before minimal images to prevent fallback regressions")
1042 case "minimal":
1043 foundMinimal = true
1044 }
1045 }
1046 assert.Assert(t, foundServer, "should have found standard/server images")
1047 assert.Assert(t, foundMinimal, "should have found minimal images")
1048}
1049
1050func TestFillDefaultUserPasswordlessSudo(t *testing.T) {
1051 baseY := func() *limatype.LimaYAML {
1052 return &limatype.LimaYAML{
1053 OS: new(limatype.LINUX),
1054 Arch: new(limatype.X8664),
1055 }
1056 }
1057 t.Run("fallback to true", func(t *testing.T) {
1058 y, d, o := baseY(), &limatype.LimaYAML{}, &limatype.LimaYAML{}
1059 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1060 assert.Assert(t, y.User.PasswordlessSudo != nil)
1061 assert.Equal(t, *y.User.PasswordlessSudo, true)
1062 })
1063 t.Run("default propagates", func(t *testing.T) {
1064 y, d, o := baseY(), &limatype.LimaYAML{User: limatype.User{PasswordlessSudo: new(false)}}, &limatype.LimaYAML{}
1065 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1066 assert.Equal(t, *y.User.PasswordlessSudo, false)
1067 })
1068 t.Run("yaml wins over default", func(t *testing.T) {
1069 y, d, o := baseY(), &limatype.LimaYAML{User: limatype.User{PasswordlessSudo: new(true)}}, &limatype.LimaYAML{}
1070 y.User.PasswordlessSudo = new(false)
1071 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1072 assert.Equal(t, *y.User.PasswordlessSudo, false)
1073 })
1074 t.Run("override wins", func(t *testing.T) {
1075 y, d, o := baseY(), &limatype.LimaYAML{}, &limatype.LimaYAML{User: limatype.User{PasswordlessSudo: new(false)}}
1076 y.User.PasswordlessSudo = new(true)
1077 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1078 assert.Equal(t, *y.User.PasswordlessSudo, false)
1079 })
1080}
1081
1082func TestValidatePasswordlessSudoRequiresPlain(t *testing.T) {
1083 y, d, o := &limatype.LimaYAML{}, &limatype.LimaYAML{}, &limatype.LimaYAML{}
1084 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1085 y.Images = []limatype.Image{
1086 {
1087 File: limatype.File{
1088 Location: "https://example.com/dummy.img",
1089 Arch: limatype.X8664,
1090 },
1091 },
1092 }
1093 y.User.PasswordlessSudo = new(false)
1094 y.Plain = new(false) // plain is false, which violates the GHSA constraint
1095 err := Validate(y, false)
1096 assert.ErrorContains(t, err, "`user.passwordlessSudo: false` requires `plain: true`")
1097 y.Plain = new(true)
1098 errValid := Validate(y, false)
1099 assert.NilError(t, errValid)
1100}
1101
1102func TestValidatePasswordlessSudoFalseNoPlainRequiredOnMacOS(t *testing.T) {
1103 y, d, o := &limatype.LimaYAML{}, &limatype.LimaYAML{}, &limatype.LimaYAML{}
1104 y.OS = new(limatype.DARWIN)
1105 FillDefault(t.Context(), y, d, o, "test.yaml", false)
1106 y.Images = []limatype.Image{
1107 {File: limatype.File{Location: "https://example.com/dummy.img", Arch: limatype.AARCH64}},
1108 }
1109 err := Validate(y, false)
1110 assert.NilError(t, err)
1111}