跳到主要内容

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

浏览文件

validate.go

801 行 · 32.0 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limayaml
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "net"
11 "os"
12 "path"
13 "path/filepath"
14 "regexp"
15 "runtime"
16 "slices"
17 "strconv"
18 "strings"
19 "unicode"
20
21 "github.com/docker/go-units"
22 "github.com/sirupsen/logrus"
23
24 "github.com/lima-vm/lima/v2/pkg/identifiers"
25 "github.com/lima-vm/lima/v2/pkg/limatype"
26 "github.com/lima-vm/lima/v2/pkg/localpathutil"
27 "github.com/lima-vm/lima/v2/pkg/networks"
28 "github.com/lima-vm/lima/v2/pkg/osutil"
29 "github.com/lima-vm/lima/v2/pkg/version"
30 "github.com/lima-vm/lima/v2/pkg/version/versionutil"
31)
32
33func Validate(y *limatype.LimaYAML, warn bool) error {
34 var errs error
35
36 if len(y.Base) > 0 {
37 errs = errors.Join(errs, errors.New("field `base` must be empty for YAML validation"))
38 }
39
40 if y.MinimumLimaVersion != nil {
41 if _, err := versionutil.Parse(*y.MinimumLimaVersion); err != nil {
42 errs = errors.Join(errs, fmt.Errorf("field `minimumLimaVersion` must be a semvar value, got %#q: %w", *y.MinimumLimaVersion, err))
43 }
44 // Unparsable version.Version (like commit hashes or "<unknown>") is treated as "latest/greatest"
45 // and will pass all version comparisons, allowing development builds to work.
46 if !versionutil.GreaterEqual(version.Version, *y.MinimumLimaVersion) {
47 errs = errors.Join(errs, fmt.Errorf("template requires Lima version %#q; this is only %#q", *y.MinimumLimaVersion, version.Version))
48 }
49 }
50
51 switch *y.OS {
52 case limatype.LINUX, limatype.DARWIN, limatype.FREEBSD:
53 case limatype.WINDOWS:
54 if *y.VMType != limatype.QEMU {
55 errs = errors.Join(errs, fmt.Errorf("currently Windows guest is only supported on %#q; got %#q", limatype.QEMU, *y.VMType))
56 }
57 if !slices.Contains([]limatype.Arch{limatype.X8664, limatype.AARCH64}, *y.Arch) {
58 errs = errors.Join(errs, fmt.Errorf("currently Windows guest is only supported on [%#q, %#q]; got %#q", limatype.X8664, limatype.AARCH64, *y.Arch))
59 }
60 default:
61 errs = errors.Join(errs, fmt.Errorf("field `os` must be one of %#q; got %#q", limatype.OSTypes, *y.OS))
62 }
63 if !slices.Contains(limatype.ArchTypes, *y.Arch) {
64 errs = errors.Join(errs, fmt.Errorf("field `arch` must be one of %v; got %#q", limatype.ArchTypes, *y.Arch))
65 }
66
67 if y.Video.Display != nil && *y.Video.Display == "offscreen" && (*y.OS != limatype.DARWIN || y.VMType == nil || *y.VMType != limatype.VZ) {
68 errs = errors.Join(errs, errors.New("video.display offscreen requires a macOS guest with the VZ driver"))
69 }
70
71 if y.User.Shell != nil {
72 shell := *y.User.Shell
73 if *y.OS == limatype.WINDOWS {
74 if !IsSupportedWindowsShell(shell) {
75 errs = errors.Join(errs, fmt.Errorf("field `user.shell` must be one of %v for Windows guest, got %#q", SupportedWindowsShells, shell))
76 }
77 } else if !path.IsAbs(shell) {
78 errs = errors.Join(errs, fmt.Errorf("field `user.shell` must be an absolute path, got %#q", shell))
79 }
80 }
81
82 if len(y.Images) == 0 {
83 errs = errors.Join(errs, errors.New("field `images` must be set"))
84 }
85 for i, f := range y.Images {
86 err := validateFileObject(f.File, fmt.Sprintf("images[%d]", i))
87 if err != nil {
88 errs = errors.Join(errs, err)
89 }
90 if f.Kernel != nil {
91 err := validateFileObject(f.Kernel.File, fmt.Sprintf("images[%d].kernel", i))
92 if err != nil {
93 errs = errors.Join(errs, err)
94 }
95 if f.Kernel.Arch != f.Arch {
96 errs = errors.Join(errs, fmt.Errorf("images[%d].kernel has unexpected architecture %#q, must be %#q", i, f.Kernel.Arch, f.Arch))
97 }
98 }
99 if f.Initrd != nil {
100 err := validateFileObject(*f.Initrd, fmt.Sprintf("images[%d].initrd", i))
101 if err != nil {
102 errs = errors.Join(errs, err)
103 }
104 if f.Initrd.Arch != f.Arch {
105 errs = errors.Join(errs, fmt.Errorf("images[%d].initrd has unexpected architecture %#q, must be %#q", i, f.Initrd.Arch, f.Arch))
106 }
107 }
108 }
109
110 if *y.CPUs == 0 {
111 errs = errors.Join(errs, errors.New("field `cpus` must be set"))
112 }
113
114 if _, err := units.RAMInBytes(*y.Memory); err != nil {
115 errs = errors.Join(errs, fmt.Errorf("field `memory` has an invalid value: %w", err))
116 }
117
118 if _, err := units.RAMInBytes(*y.Disk); err != nil {
119 errs = errors.Join(errs, fmt.Errorf("field `disk` has an invalid value: %w", err))
120 }
121
122 for i, disk := range y.AdditionalDisks {
123 if err := identifiers.Validate(disk.Name); err != nil {
124 errs = errors.Join(errs, fmt.Errorf("field `additionalDisks[%d].name is invalid`: %w", i, err))
125 }
126 }
127
128 for i, f := range y.Mounts {
129 if !filepath.IsAbs(f.Location) && !strings.HasPrefix(f.Location, "~") {
130 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].location` must be an absolute path, got %#q",
131 i, f.Location))
132 }
133 // f.Location has already been expanded in FillDefaults(), but that function cannot return errors.
134 loc, err := localpathutil.Expand(f.Location)
135 if err != nil {
136 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].location` refers to an unexpandable path: %#q: %w", i, f.Location, err))
137 }
138 st, err := os.Stat(loc)
139 if err != nil {
140 if !errors.Is(err, os.ErrNotExist) {
141 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].location` refers to an inaccessible path: %#q: %w", i, f.Location, err))
142 }
143 if warn {
144 logrus.Warnf("field `mounts[%d].location` refers to a non-existent directory: %#q:", i, f.Location)
145 }
146 } else if !st.IsDir() {
147 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].location` refers to a non-directory path: %#q: %w", i, f.Location, err))
148 }
149
150 switch *f.MountPoint {
151 case "/", "/bin", "/dev", "/etc", "/home", "/opt", "/sbin", "/tmp", "/usr", "/var":
152 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].mountPoint` must not be a system path such as /etc or /usr", i))
153 // home directory defined in "cidata.iso:/user-data"
154 case *y.User.Home:
155 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].mountPoint` is the reserved internal home directory %#q", i, *y.User.Home))
156 }
157 // There is no tilde-expansion for guest filenames
158 if strings.HasPrefix(*f.MountPoint, "~") {
159 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].mountPoint` must not start with `~`", i))
160 }
161
162 if _, err := units.RAMInBytes(*f.NineP.Msize); err != nil {
163 errs = errors.Join(errs, fmt.Errorf("field `msize` has an invalid value: %w", err))
164 }
165 }
166
167 if *y.SSH.LocalPort != 0 {
168 if err := validatePort("ssh.localPort", *y.SSH.LocalPort); err != nil {
169 errs = errors.Join(errs, err)
170 }
171 }
172
173 if y.MountType != nil {
174 switch *y.MountType {
175 case limatype.REVSSHFS, limatype.NINEP, limatype.VIRTIOFS, limatype.WSLMount:
176 default:
177 errs = errors.Join(errs, fmt.Errorf("field `mountType` must be %#q or %#q or %#q, or %#q, got %#q", limatype.REVSSHFS, limatype.NINEP, limatype.VIRTIOFS, limatype.WSLMount, *y.MountType))
178 }
179
180 if slices.Contains(y.MountTypesUnsupported, *y.MountType) {
181 errs = errors.Join(errs, fmt.Errorf("field `mountType` must not be one of %v (`mountTypesUnsupported`), got %#q", y.MountTypesUnsupported, *y.MountType))
182 }
183 }
184
185 if err := validateReadonlyNames(y); err != nil {
186 errs = errors.Join(errs, err)
187 }
188
189 if warn && runtime.GOOS != "linux" {
190 for i, mount := range y.Mounts {
191 if mount.Virtiofs.QueueSize != nil {
192 logrus.Warnf("field mounts[%d].virtiofs.queueSize is only supported on Linux", i)
193 }
194 }
195 }
196
197 // y.Firmware.LegacyBIOS is ignored for aarch64, but not a fatal error.
198
199 for i, p := range y.Provision {
200 if p.File != nil {
201 if p.File.URL != "" {
202 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].file.url` must be empty during validation (script should already be embedded)", i))
203 }
204 if p.File.Digest != nil {
205 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].file.digest` support is not yet implemented", i))
206 }
207 }
208 switch p.Mode {
209 case limatype.ProvisionModeSystem, limatype.ProvisionModeUser, limatype.ProvisionModeBoot, limatype.ProvisionModeData, limatype.ProvisionModeDependency, limatype.ProvisionModeAnsible, limatype.ProvisionModeYQ:
210 default:
211 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].mode` must one of %#q, %#q, %#q, %#q, %#q, %#q, or %#q",
212 i, limatype.ProvisionModeSystem, limatype.ProvisionModeUser, limatype.ProvisionModeBoot, limatype.ProvisionModeData, limatype.ProvisionModeDependency, limatype.ProvisionModeAnsible, limatype.ProvisionModeYQ))
213 }
214 if p.Mode != limatype.ProvisionModeDependency && p.SkipDefaultDependencyResolution != nil {
215 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].mode` cannot set skipDefaultDependencyResolution, only valid on scripts of type %#q",
216 i, limatype.ProvisionModeDependency))
217 }
218
219 if *y.OS == limatype.WINDOWS && (p.Mode == limatype.ProvisionModeAnsible || p.Mode == limatype.ProvisionModeBoot || p.Mode == limatype.ProvisionModeYQ) {
220 errs = errors.Join(errs, fmt.Errorf("provision mode %#q is not supported on Windows VM", p.Mode))
221 }
222
223 // This can lead to fatal Panic if p.Path is nil, better to return an error here
224 switch p.Mode {
225 case limatype.ProvisionModeData, limatype.ProvisionModeYQ:
226 if p.Path == nil {
227 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].path` must not be empty when mode is %#q", i, p.Mode))
228 return errs
229 }
230 if !path.IsAbs(*p.Path) {
231 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].path` must be an absolute path", i))
232 }
233 if p.Mode == limatype.ProvisionModeData && p.Content == nil {
234 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].content` must not be empty when mode is %#q", i, p.Mode))
235 }
236 if p.Mode == limatype.ProvisionModeYQ && p.Expression == nil {
237 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].expression` must not be empty when mode is %#q", i, p.Mode))
238 }
239 // FillDefaults makes sure that p.Permissions is not nil
240 if _, err := strconv.ParseInt(*p.Permissions, 8, 64); err != nil {
241 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].permissions` must be an octal number: %w", i, err))
242 }
243 default:
244 if (p.Script == nil || *p.Script == "") && p.Mode != limatype.ProvisionModeAnsible {
245 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].script` must not be empty", i))
246 }
247 if p.Content != nil {
248 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].content` can only be set when mode is %#q", i, limatype.ProvisionModeData))
249 }
250 if p.Overwrite != nil {
251 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].overwrite` can only be set when mode is %#q", i, limatype.ProvisionModeData))
252 }
253 if p.Owner != nil {
254 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].owner` can only be set when mode is %#q", i, limatype.ProvisionModeData))
255 }
256 if p.Path != nil {
257 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].path` can only be set when mode is %#q, or %#q", i, limatype.ProvisionModeData, limatype.ProvisionModeYQ))
258 }
259 if p.Permissions != nil {
260 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].permissions` can only be set when mode is %#q, or %#q", i, limatype.ProvisionModeData, limatype.ProvisionModeYQ))
261 }
262 if p.Format != nil {
263 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].format` can only be set when mode is %#q", i, limatype.ProvisionModeYQ))
264 }
265 }
266 if p.Playbook != "" {
267 if p.Mode != limatype.ProvisionModeAnsible {
268 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].playbook can only be set when mode is %#q", i, limatype.ProvisionModeAnsible))
269 }
270 if p.Script != nil && *p.Script != "" {
271 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].script must be empty if playbook is set", i))
272 }
273 playbook := p.Playbook
274 if _, err := os.Stat(playbook); err != nil {
275 errs = errors.Join(errs, fmt.Errorf("field `provision[%d].playbook` refers to an inaccessible path: %#q: %w", i, playbook, err))
276 }
277 logrus.Warnf("provision mode %#q is deprecated, use `ansible-playbook %#q` instead", limatype.ProvisionModeAnsible, playbook)
278 }
279 if p.Script != nil {
280 if strings.Contains(*p.Script, "LIMA_CIDATA") {
281 logrus.Warn("provisioning scripts should not reference the LIMA_CIDATA variables")
282 }
283 }
284 }
285 needsContainerdArchives := (y.Containerd.User != nil && *y.Containerd.User) || (y.Containerd.System != nil && *y.Containerd.System)
286 if needsContainerdArchives {
287 if len(y.Containerd.Archives) == 0 {
288 errs = errors.Join(errs, errors.New("field `containerd.archives` must be provided"))
289 }
290 for i, f := range y.Containerd.Archives {
291 err := validateFileObject(f, fmt.Sprintf("containerd.archives[%d]", i))
292 if err != nil {
293 errs = errors.Join(errs, err)
294 }
295 }
296 }
297 for i, p := range y.Probes {
298 if p.File != nil {
299 if p.File.URL != "" {
300 errs = errors.Join(errs, fmt.Errorf("field `probe[%d].file.url` must be empty during validation (script should already be embedded)", i))
301 }
302 if p.File.Digest != nil {
303 errs = errors.Join(errs, fmt.Errorf("field `probe[%d].file.digest` support is not yet implemented", i))
304 }
305 }
306 if p.Script != nil && !strings.HasPrefix(*p.Script, "#!") {
307 errs = errors.Join(errs, fmt.Errorf("field `probe[%d].script` must start with a '#!' line", i))
308 }
309 switch p.Mode {
310 case limatype.ProbeModeReadiness:
311 default:
312 errs = errors.Join(errs, fmt.Errorf("field `probe[%d].mode` can only be %#q", i, limatype.ProbeModeReadiness))
313 }
314 }
315 for i, rule := range y.PortForwards {
316 field := fmt.Sprintf("portForwards[%d]", i)
317 if *rule.GuestIPMustBeZero && !rule.GuestIP.Equal(net.IPv4zero) {
318 errs = errors.Join(errs, fmt.Errorf("field `%s.guestIPMustBeZero` can only be true when field `%s.guestIP` is 0.0.0.0", field, field))
319 }
320 if rule.GuestPort != 0 {
321 if rule.GuestSocket != "" {
322 errs = errors.Join(errs, fmt.Errorf("field `%s.guestPort` must be 0 when field `%s.guestSocket` is set", field, field))
323 }
324 if rule.GuestPort != rule.GuestPortRange[0] {
325 errs = errors.Join(errs, fmt.Errorf("field `%s.guestPort` must match field `%s.guestPortRange[0]`", field, field))
326 }
327 // redundant validation to make sure the error contains the correct field name
328 if err := validatePort(field+".guestPort", rule.GuestPort); err != nil {
329 errs = errors.Join(errs, err)
330 }
331 }
332 if rule.HostPort != 0 {
333 if rule.HostSocket != "" {
334 errs = errors.Join(errs, fmt.Errorf("field `%s.hostPort` must be 0 when field `%s.hostSocket` is set", field, field))
335 }
336 if rule.HostPort != rule.HostPortRange[0] {
337 errs = errors.Join(errs, fmt.Errorf("field `%s.hostPort` must match field `%s.hostPortRange[0]`", field, field))
338 }
339 // redundant validation to make sure the error contains the correct field name
340 if err := validatePort(field+".hostPort", rule.HostPort); err != nil {
341 errs = errors.Join(errs, err)
342 }
343 }
344 for j := range 2 {
345 if err := validatePort(fmt.Sprintf("%s.guestPortRange[%d]", field, j), rule.GuestPortRange[j]); err != nil {
346 errs = errors.Join(errs, err)
347 }
348 if rule.HostSocket == "" {
349 if err := validatePort(fmt.Sprintf("%s.hostPortRange[%d]", field, j), rule.HostPortRange[j]); err != nil {
350 errs = errors.Join(errs, err)
351 }
352 }
353 }
354 if rule.GuestPortRange[0] > rule.GuestPortRange[1] {
355 errs = errors.Join(errs, fmt.Errorf("field `%s.guestPortRange[1]` must be greater than or equal to field `%s.guestPortRange[0]`", field, field))
356 }
357 if rule.HostPortRange[0] > rule.HostPortRange[1] {
358 errs = errors.Join(errs, fmt.Errorf("field `%s.hostPortRange[1]` must be greater than or equal to field `%s.hostPortRange[0]`", field, field))
359 }
360 if rule.GuestSocket != "" {
361 if !path.IsAbs(rule.GuestSocket) {
362 errs = errors.Join(errs, fmt.Errorf("field `%s.guestSocket` must be an absolute path, but is %#q", field, rule.GuestSocket))
363 }
364 if rule.HostSocket == "" && rule.HostPortRange[1]-rule.HostPortRange[0] > 0 {
365 errs = errors.Join(errs, fmt.Errorf("field `%s.guestSocket` can only be mapped to a single port or socket. not a range", field))
366 }
367 }
368 if rule.HostSocket != "" {
369 if !filepath.IsAbs(rule.HostSocket) {
370 // should be unreachable because FillDefault() will prepend the instance directory to relative names
371 errs = errors.Join(errs, fmt.Errorf("field `%s.hostSocket` must be an absolute path, but is %#q", field, rule.HostSocket))
372 }
373 if rule.GuestSocket == "" && rule.GuestPortRange[1]-rule.GuestPortRange[0] > 0 {
374 errs = errors.Join(errs, fmt.Errorf("field `%s.hostSocket` can only be mapped from a single port or socket. not a range", field))
375 }
376 } else if rule.GuestPortRange[1]-rule.GuestPortRange[0] != rule.HostPortRange[1]-rule.HostPortRange[0] {
377 errs = errors.Join(errs, fmt.Errorf("field `%s.hostPortRange` must specify the same number of ports as field `%s.guestPortRange`", field, field))
378 }
379
380 if len(rule.HostSocket) >= osutil.UnixPathMax {
381 errs = errors.Join(errs, fmt.Errorf("field `%s.hostSocket` must be less than UNIX_PATH_MAX=%d characters, but is %d",
382 field, osutil.UnixPathMax, len(rule.HostSocket)))
383 }
384 switch rule.Proto {
385 case limatype.ProtoTCP, limatype.ProtoUDP, limatype.ProtoAny:
386 default:
387 errs = errors.Join(errs, fmt.Errorf("field `%s.proto` must be %#q, %#q, or %#q", field, limatype.ProtoTCP, limatype.ProtoUDP, limatype.ProtoAny))
388 }
389 if rule.Reverse && rule.GuestSocket == "" {
390 errs = errors.Join(errs, fmt.Errorf("field `%s.reverse` must be %t", field, false))
391 }
392 if rule.Reverse && rule.HostSocket == "" {
393 errs = errors.Join(errs, fmt.Errorf("field `%s.reverse` must be %t", field, false))
394 }
395 // Not validating that the various GuestPortRanges and HostPortRanges are not overlapping. Rules will be
396 // processed sequentially and the first matching rule for a guest port determines forwarding behavior.
397 }
398 for i, rule := range y.CopyToHost {
399 field := fmt.Sprintf("CopyToHost[%d]", i)
400 if rule.GuestFile != "" {
401 if !path.IsAbs(rule.GuestFile) {
402 errs = errors.Join(errs, fmt.Errorf("field `%s.guest` must be an absolute path, but is %#q", field, rule.GuestFile))
403 }
404 }
405 if rule.HostFile != "" {
406 if !filepath.IsAbs(rule.HostFile) {
407 errs = errors.Join(errs, fmt.Errorf("field `%s.host` must be an absolute path, but is %#q", field, rule.HostFile))
408 }
409 }
410 }
411
412 if y.VMType != nil && *y.VMType == limatype.HCS {
413 if y.HostResolver.Enabled != nil && *y.HostResolver.Enabled && len(y.DNS) > 0 {
414 errs = errors.Join(errs, errors.New("field `dns` must be empty when field `HostResolver.Enabled` is true"))
415 }
416 } else {
417 if HostResolverEnabled(y) && len(y.DNS) > 0 {
418 errs = errors.Join(errs, errors.New("field `dns` must be empty when field `HostResolver.Enabled` is true"))
419 }
420 }
421
422 err := validateNetwork(y)
423 if err != nil {
424 errs = errors.Join(errs, err)
425 }
426
427 if warn {
428 warnExperimental(y)
429 }
430
431 // Validate Param settings
432 // Names must start with a letter, followed by any number of letters, digits, or underscores
433 validParamName := regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`)
434 for param, value := range y.Param {
435 if !validParamName.MatchString(param) {
436 errs = errors.Join(errs, fmt.Errorf("param %#q name does not match regex %#q", param, validParamName.String()))
437 }
438 for _, r := range value {
439 if !unicode.IsPrint(r) && r != '\t' && r != ' ' {
440 errs = errors.Join(errs, fmt.Errorf("param %#q value contains unprintable character %#q", param, r))
441 }
442 }
443 }
444
445 // passwordlessSudo: true is not supported on macOS guests yet (lock_passwd unimplemented,
446 // account creation requires a password, and the same account backs the GUI session)
447 if y.OS != nil && *y.OS == limatype.DARWIN &&
448 y.User.PasswordlessSudo != nil && *y.User.PasswordlessSudo {
449 errs = errors.Join(errs, errors.New("`user.passwordlessSudo: true` is not supported on macOS guests"))
450 }
451 if y.VMType != nil && *y.VMType == limatype.WSL2 &&
452 y.User.PasswordlessSudo != nil && !*y.User.PasswordlessSudo {
453 errs = errors.Join(errs, errors.New("`user.passwordlessSudo: false` is not supported on WSL2 guest"))
454 }
455 // GHSA-2j9v-p4xj-cjw2 constraint: require plain mode when passwordless sudo is disabled
456 if y.User.PasswordlessSudo != nil && !*y.User.PasswordlessSudo {
457 if y.OS == nil || *y.OS != limatype.DARWIN {
458 if y.Plain == nil || !*y.Plain {
459 errs = errors.Join(errs, errors.New("`user.passwordlessSudo: false` requires `plain: true`"))
460 }
461 }
462 }
463 if y.Plain != nil && *y.Plain {
464 const portRangeWarnThreshold = 10
465 for i, rule := range y.PortForwards {
466 guestRange := rule.GuestPortRange[1] - rule.GuestPortRange[0] + 1
467 hostRange := rule.HostPortRange[1] - rule.HostPortRange[0] + 1
468 if guestRange > portRangeWarnThreshold || hostRange > portRangeWarnThreshold {
469 logrus.Warnf("[plain mode] portForwards[%d] covers a range of more than %d ports (guest: %d, host: %d). All ports will be forwarded unconditionally, which may be inefficient.", i, portRangeWarnThreshold, guestRange, hostRange)
470 }
471 }
472 }
473 if y.TPM != nil && *y.TPM {
474 switch *y.Arch {
475 case limatype.X8664, limatype.AARCH64, limatype.ARMV7L, limatype.RISCV64:
476 // supported
477 default:
478 errs = errors.Join(errs, fmt.Errorf("field `tpm` is not supported on architecture %#q", *y.Arch))
479 }
480 }
481
482 if y.Audio.Interface != nil {
483 if *y.Audio.Interface != "" && *y.Audio.Interface != "hda" && *y.Audio.Interface != "virtio" {
484 return fmt.Errorf("invalid audio.interface %q, must be \"hda\" or \"virtio\"", *y.Audio.Interface)
485 }
486 }
487
488 return errs
489}
490
491var SupportedWindowsShells = []string{"cmd.exe", "powershell.exe", "pwsh.exe"}
492
493func IsSupportedWindowsShell(shell string) bool {
494 // Normalize both forward and backward slashes since Windows-style paths may
495 // be validated on a non-Windows host.
496 if i := strings.LastIndexAny(shell, `/\`); i >= 0 {
497 shell = shell[i+1:]
498 }
499 for _, s := range SupportedWindowsShells {
500 if strings.EqualFold(shell, s) {
501 return true
502 }
503 }
504 return false
505}
506
507func validateFileObject(f limatype.File, fieldName string) error {
508 var errs error
509 if !strings.Contains(f.Location, "://") {
510 if _, err := localpathutil.Expand(f.Location); err != nil {
511 errs = errors.Join(errs, fmt.Errorf("field `%s.location` refers to an invalid local file path: %#q: %w", fieldName, f.Location, err))
512 }
513 // f.Location does NOT need to be accessible, so we do NOT check os.Stat(f.Location)
514 }
515 if !slices.Contains(limatype.ArchTypes, f.Arch) {
516 errs = errors.Join(errs, fmt.Errorf("field `arch` must be one of %v; got %#q", limatype.ArchTypes, f.Arch))
517 }
518 if f.Digest != "" {
519 if err := f.Digest.Validate(); err != nil {
520 errs = errors.Join(errs, fmt.Errorf("field `%s.digest` is invalid: %s: %w", fieldName, f.Digest.String(), err))
521 }
522 }
523 return errs
524}
525
526func validateNetwork(y *limatype.LimaYAML) error {
527 var errs error
528 interfaceName := make(map[string]int)
529 for i, nw := range y.Networks {
530 field := fmt.Sprintf("networks[%d]", i)
531 switch {
532 case nw.Lima != "":
533 nwCfg, err := networks.LoadConfig()
534 if err != nil {
535 return err
536 }
537 if nwCfg.Check(nw.Lima) != nil {
538 errs = errors.Join(errs, fmt.Errorf("field `%s.lima` references network %#q which is not defined in networks.yaml", field, nw.Lima))
539 }
540 usernet, err := nwCfg.Usernet(nw.Lima)
541 if err != nil {
542 return err
543 }
544 if !usernet && runtime.GOOS != "darwin" {
545 errs = errors.Join(errs, fmt.Errorf("field `%s.lima` is only supported on macOS right now", field))
546 }
547 if nw.Socket != "" {
548 errs = errors.Join(errs, fmt.Errorf("field `%s.lima` and field `%s.socket` are mutually exclusive", field, field))
549 }
550 if nw.VZNAT != nil && *nw.VZNAT {
551 errs = errors.Join(errs, fmt.Errorf("field `%s.lima` and field `%s.vzNAT` are mutually exclusive", field, field))
552 }
553 case nw.Socket != "":
554 if nw.VZNAT != nil && *nw.VZNAT {
555 errs = errors.Join(errs, fmt.Errorf("field `%s.socket` and field `%s.vzNAT` are mutually exclusive", field, field))
556 }
557 if fi, err := os.Stat(nw.Socket); err != nil && !errors.Is(err, os.ErrNotExist) {
558 errs = errors.Join(errs, err)
559 } else if err == nil && fi.Mode()&os.ModeSocket == 0 {
560 errs = errors.Join(errs, fmt.Errorf("field `%s.socket` %#q points to a non-socket file", field, nw.Socket))
561 }
562 case nw.VZNAT != nil && *nw.VZNAT:
563 if nw.Lima != "" {
564 errs = errors.Join(errs, fmt.Errorf("field `%s.vzNAT` and field `%s.lima` are mutually exclusive", field, field))
565 }
566 if nw.Socket != "" {
567 errs = errors.Join(errs, fmt.Errorf("field `%s.vzNAT` and field `%s.socket` are mutually exclusive", field, field))
568 }
569 default:
570 errs = errors.Join(errs, fmt.Errorf("field `%s.lima` or field `%s.socket must be set", field, field))
571 }
572 if nw.MACAddress != "" {
573 hw, err := net.ParseMAC(nw.MACAddress)
574 if err != nil {
575 errs = errors.Join(errs, fmt.Errorf("field `vmnet.mac` invalid: %w", err))
576 }
577 if len(hw) != 6 {
578 errs = errors.Join(errs, fmt.Errorf("field `%s.macAddress` must be a 48 bit (6 bytes) MAC address; actual length of %#q is %d bytes", field, nw.MACAddress, len(hw)))
579 }
580 }
581 // FillDefault() will make sure that nw.Interface is not the empty string
582 if len(nw.Interface) >= 16 {
583 errs = errors.Join(errs, fmt.Errorf("field `%s.interface` must be less than 16 bytes, but is %d bytes: %#q", field, len(nw.Interface), nw.Interface))
584 }
585 if strings.ContainsAny(nw.Interface, " \t\n/") {
586 errs = errors.Join(errs, fmt.Errorf("field `%s.interface` must not contain whitespace or slashes", field))
587 }
588 if nw.Interface == networks.SlirpNICName {
589 errs = errors.Join(errs, fmt.Errorf("field `%s.interface` must not be set to %#q because it is reserved for slirp", field, networks.SlirpNICName))
590 }
591 if prev, ok := interfaceName[nw.Interface]; ok {
592 errs = errors.Join(errs, fmt.Errorf("field `%s.interface` value %#q has already been used by field `networks[%d].interface`", field, nw.Interface, prev))
593 }
594 interfaceName[nw.Interface] = i
595 }
596
597 return errs
598}
599
600// validateParamIsUsed checks if the keys in the `param` field are used in any script, probe, copyToHost, or portForward.
601// It should be called before the `y` parameter is passed to FillDefault() that execute template.
602func validateParamIsUsed(y *limatype.LimaYAML) error {
603 for key := range y.Param {
604 re, err := regexp.Compile(`{{[^}]*\.Param\.` + key + `[^}]*}}|\bPARAM_` + key + `\b`)
605 if err != nil {
606 return fmt.Errorf("field to compile regexp for key %#q: %w", key, err)
607 }
608 keyIsUsed := false
609 for _, p := range y.Provision {
610 for _, ptr := range []*string{p.Script, p.Content, p.Expression, p.Owner, p.Path, p.Permissions} {
611 if ptr != nil && re.MatchString(*ptr) {
612 keyIsUsed = true
613 break
614 }
615 }
616 if p.Playbook != "" {
617 playbook, err := os.ReadFile(p.Playbook)
618 if err != nil {
619 return err
620 }
621 if re.Match(playbook) {
622 keyIsUsed = true
623 break
624 }
625 }
626 }
627 for _, p := range y.Probes {
628 if p.Script != nil && re.MatchString(*p.Script) {
629 keyIsUsed = true
630 break
631 }
632 }
633 for _, p := range y.CopyToHost {
634 if re.MatchString(p.GuestFile) || re.MatchString(p.HostFile) {
635 keyIsUsed = true
636 break
637 }
638 }
639 for _, p := range y.PortForwards {
640 if re.MatchString(p.GuestSocket) || re.MatchString(p.HostSocket) {
641 keyIsUsed = true
642 break
643 }
644 }
645 for _, p := range y.Mounts {
646 if re.MatchString(p.Location) {
647 keyIsUsed = true
648 break
649 }
650 if p.MountPoint != nil && re.MatchString(*p.MountPoint) {
651 keyIsUsed = true
652 break
653 }
654 }
655 if key == "internal_netplanOptional" { // consumed by the cidata network-config template
656 keyIsUsed = true
657 }
658 if !keyIsUsed {
659 return fmt.Errorf("field `param` key %#q is not used in any provision, probe, copyToHost, or portForward", key)
660 }
661 }
662 return nil
663}
664
665// validateReadonlyNames rejects configurations where `sshfs.readonlyNames` would not be enforced on the host.
666// Every mount must use the builtin SFTP driver, as the OpenSSH sftp-server lets a compromised guest
667// access any host path, including the read-only ones of the other mounts.
668func validateReadonlyNames(y *limatype.LimaYAML) error {
669 used := slices.ContainsFunc(y.Mounts, func(m limatype.Mount) bool { return len(m.SSHFS.ReadonlyNames) > 0 })
670 if !used {
671 return nil
672 }
673 var errs error
674 if y.MountType == nil || *y.MountType != limatype.REVSSHFS {
675 errs = errors.Join(errs, fmt.Errorf("field `mounts[*].sshfs.readonlyNames` requires `mountType` to be %#q", limatype.REVSSHFS))
676 }
677 for i, m := range y.Mounts {
678 if m.SSHFS.SFTPDriver == nil || *m.SSHFS.SFTPDriver != limatype.SFTPDriverBuiltin {
679 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.sftpDriver` must be %#q when any mount sets `sshfs.readonlyNames`", i, limatype.SFTPDriverBuiltin))
680 }
681 for _, name := range m.SSHFS.ReadonlyNames {
682 if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
683 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.readonlyNames` must contain file names, got %#q", i, name))
684 }
685 }
686 }
687 // A writable mount of a folder holding another writable mount reaches
688 // its files too: it has to protect the same names.
689 for i, outer := range y.Mounts {
690 for j, inner := range y.Mounts {
691 if i == j || outer.Writable == nil || !*outer.Writable || inner.Writable == nil || !*inner.Writable ||
692 !isWithin(outer.Location, inner.Location) {
693 continue
694 }
695 for _, name := range inner.SSHFS.ReadonlyNames {
696 if !slices.Contains(outer.SSHFS.ReadonlyNames, name) {
697 errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.readonlyNames` must contain %#q, as the writable mount `mounts[%d]` inside it does", i, name, j))
698 }
699 }
700 }
701 }
702 return errs
703}
704
705// isWithin reports whether the folder child is parent or under it. Case is
706// ignored where the file systems usually do.
707func isWithin(parent, child string) bool {
708 if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
709 parent, child = strings.ToLower(parent), strings.ToLower(child)
710 }
711 rel, err := filepath.Rel(parent, child)
712 return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
713}
714
715func validatePort(field string, port int) error {
716 switch {
717 case port < 0:
718 return fmt.Errorf("field `%s` must be > 0", field)
719 case port == 0:
720 return fmt.Errorf("field `%s` must be set", field)
721 case port == 22:
722 return fmt.Errorf("field `%s` must not be 22", field)
723 case port > 65535:
724 return fmt.Errorf("field `%s` must be < 65536", field)
725 }
726 return nil
727}
728
729func warnExperimental(y *limatype.LimaYAML) {
730 if *y.OS == limatype.WINDOWS {
731 logrus.Warnf("`os: %s` is experimental", limatype.WINDOWS)
732 }
733 if *y.MountType == limatype.VIRTIOFS && runtime.GOOS == "linux" {
734 logrus.Warn("`mountType: virtiofs` on Linux is experimental")
735 }
736 switch *y.Arch {
737 case limatype.RISCV64, limatype.ARMV7L, limatype.S390X, limatype.PPC64LE:
738 logrus.Warnf("`arch: %s ` is experimental", *y.Arch)
739 }
740 if y.Video.Display != nil && strings.Contains(*y.Video.Display, "vnc") {
741 logrus.Warn("`video.display: vnc` is experimental")
742 }
743 if y.Audio.Device != nil && *y.Audio.Device != "" {
744 logrus.Warn("`audio.device` is experimental")
745 if y.Audio.Interface != nil && *y.Audio.Interface != "" {
746 logrus.Warn("`audio.interface` is experimental")
747 }
748 }
749 if y.Audio.Microphone != nil && *y.Audio.Microphone {
750 logrus.Warn("`audio.microphone` is experimental")
751 }
752 if y.MountInotify != nil && *y.MountInotify {
753 logrus.Warn("`mountInotify` is experimental")
754 }
755 if y.User.PasswordlessSudo != nil && !*y.User.PasswordlessSudo {
756 if y.OS == nil || *y.OS != limatype.DARWIN {
757 logrus.Warn("`user.passwordlessSudo: false` is experimental")
758 }
759 }
760 if y.User.PasswordlessSudo != nil && !*y.User.PasswordlessSudo && len(y.Param) > 0 {
761 logrus.Warn("`param` still relies on sudo internally, it may not work as expected when `user.passwordlessSudo: false` is set")
762 }
763}
764
765// ValidateAgainstLatestConfig validates the values between the latest YAML and the updated(New) YAML.
766// This validates configuration rules that disallow certain changes, such as shrinking the disk.
767func ValidateAgainstLatestConfig(ctx context.Context, yNew, yLatest []byte) error {
768 var n limatype.LimaYAML
769 var errs error
770
771 // Load the latest YAML and fill in defaults
772 l, err := LoadWithWarnings(ctx, yLatest, "")
773 if err != nil {
774 errs = errors.Join(errs, err)
775 }
776 if err := Unmarshal(yNew, &n, "Unmarshal new YAML bytes"); err != nil {
777 errs = errors.Join(errs, err)
778 }
779
780 // Handle editing the template without a disk value
781 if n.Disk == nil || l.Disk == nil {
782 return errs
783 }
784
785 // Disk value must be provided, as it is required when creating an instance.
786 nDisk, err := units.RAMInBytes(*n.Disk)
787 if err != nil {
788 errs = errors.Join(errs, err)
789 }
790 lDisk, err := units.RAMInBytes(*l.Disk)
791 if err != nil {
792 errs = errors.Join(errs, err)
793 }
794
795 // Reject shrinking disk
796 if nDisk < lDisk {
797 errs = errors.Join(errs, fmt.Errorf("field `disk`: shrinking the disk (%v --> %v) is not supported", *l.Disk, *n.Disk))
798 }
799
800 return errs
801}