-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyolofile.rugo
More file actions
501 lines (485 loc) · 16.3 KB
/
Copy pathyolofile.rugo
File metadata and controls
501 lines (485 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# yolofile.rugo — Yolofile parsing and front matter validation.
#
# A Yolofile is a plain bash script (run as root inside the guest) that
# yolo may use as the per-CWD provisioner. It can optionally start with a
# YAML-ish front matter block declaring VM-creation overrides (image,
# cpus, memory, disk-size, backend, gui, ai-agent) plus an optional free-form
# `description` for documentation. See docs/05-yolofile.md.
#
# This module owns:
# - locating the Yolofile (path / exists)
# - parsing front matter + extracting the bash body (parse_content)
# - validating front matter into typed overrides (validate)
#
# What it does NOT own:
# - applying the overrides to module-level globals — Rugo can't mutate a
# different module's top-level vars, so the caller does that.
# - hashing the bash body for the .applied marker — that lives in
# yolo.rugo's resolve_provisioner.
use "os"
use "str"
use "color"
use "conv"
use "filepath"
# Constant filename. Kept here (rather than in yolo.rugo) because nothing
# outside this module needs to know it by name.
FILENAME = "Yolofile"
# ---------------- Logging ----------------
# Same `[yolo]` tag as the rest so error messages look uniform. Duplicated
# rather than imported to keep the module self-contained, mirroring the
# pattern used in backends/matchlock.rugo and backends/podman.rugo.
def _log(msg)
prefix = color.dim("[yolo]")
puts "#{prefix} #{msg}"
end
def _warn(msg)
prefix = color.dim("[yolo]")
puts "#{prefix} #{color.yellow(msg)}"
end
def _err(msg)
prefix = color.dim("[yolo]")
puts "#{prefix} #{color.red(msg)}"
end
# ---------------- Disk size parsing ----------------
# Duplicated from cli.rugo (small, pure, stable). Used by validate() for
# memory: / disk-size: front matter values. We could `require "cli"` to
# share, but that introduces a sibling-module dependency for a 30-line
# helper — not worth it.
def _parse_size(s)
if s == ""
return ""
end
lower = str.lower(s)
if str.ends_with(lower, "b")
lower = str.slice(lower, 0, len(lower) - 1)
end
multiplier = 1
unit_len = 0
if str.ends_with(lower, "g")
multiplier = 1024
unit_len = 1
elsif str.ends_with(lower, "m")
multiplier = 1
unit_len = 1
end
num_str = lower
if unit_len > 0
num_str = str.slice(lower, 0, len(lower) - unit_len)
end
if num_str == ""
return ""
end
n = try conv.to_i(num_str) or -1
if n <= 0
return ""
end
return conv.to_s(n * multiplier)
end
# ---------------- Port publishing ----------------
# Duplicated from cli.rugo (small, pure, stable). A published port spec flows
# verbatim into the host-side `matchlock run -p …` / `podman run -p …` command
# lines, so the digits-only + single-':' shape is a security property as much
# as a format check — it blocks shell injection via front matter (which may
# come from an untrusted `--yolofile URL`).
def _valid_port(s)
if s == "" || len(s) > 5
return false
end
for ch in str.chars(s)
if ch < "0" || ch > "9"
return false
end
end
n = try conv.to_i(s) or -1
if n < 1 || n > 65535
return false
end
return true
end
# Normalize a publish spec `[HOST_PORT:]GUEST_PORT` to canonical
# `HOST_PORT:GUEST_PORT`. A bare `PORT` expands to `PORT:PORT`. Returns "" if
# malformed.
def _normalize_publish(s)
t = str.trim(s)
if t == ""
return ""
end
idx = str.index(t, ":")
if idx < 0
if !_valid_port(t)
return ""
end
return t + ":" + t
end
host = str.slice(t, 0, idx)
guest = str.slice(t, idx + 1, len(t))
if str.index(guest, ":") >= 0
return ""
end
if !_valid_port(host) || !_valid_port(guest)
return ""
end
return host + ":" + guest
end
# ---------------- Mount specs ----------------
# Parse a single bind-mount spec `HOST:GUEST[:MODE]` into {host, guest, mode,
# err}. Mirrors cli.parse_mount (duplicated, small/pure/stable, to keep modules
# standalone). Only validates *syntax*: path resolution, the matchlock
# under-/work constraint, and the front-matter host-containment gate all live
# in yolo.rugo, which knows $PWD / the workspace / the --allow-absolute-mounts
# flag. MODE is restricted to a fixed ro/rw allowlist so it can never reach the
# host shell as free text.
def _parse_mount(s)
bad = {host: "", guest: "", mode: "", err: ""}
t = str.trim(s)
if t == ""
bad.err = "empty mount spec"
return bad
end
parts = str.split(t, ":")
n = len(parts)
if n < 2 || n > 3
bad.err = "expected HOST:GUEST[:MODE]"
return bad
end
host = str.trim(parts[0])
guest = str.trim(parts[1])
mode = "rw"
if n == 3
mode = str.lower(str.trim(parts[2]))
end
if host == "" || guest == ""
bad.err = "HOST and GUEST must both be non-empty"
return bad
end
# Reject commas in paths: the container backend renders mounts as
# `--mount type=bind,source=HOST,target=GUEST`, where comma separates
# options — a path containing ',' could otherwise smuggle in extra mount
# options.
if str.index(host, ",") >= 0 || str.index(guest, ",") >= 0
bad.err = "',' is not allowed in a mount path"
return bad
end
if mode != "ro" && mode != "rw"
bad.err = "MODE must be 'ro' or 'rw'"
return bad
end
return {host: host, guest: guest, mode: mode, err: ""}
end
# ---------------- File location ----------------
def path
return filepath.join(os.cwd(), FILENAME)
end
def exists
return os.file_exists(path())
end
def exists_at(p)
return os.file_exists(p)
end
# ---------------- Front matter parsing ----------------
# Strip optional surrounding double or single quotes from a value. Used when
# parsing values like `image: "fedora:44"`.
def _unquote(s)
if len(s) >= 2
first = str.slice(s, 0, 1)
last = str.slice(s, len(s) - 1, len(s))
if (first == "\"" && last == "\"") || (first == "'" && last == "'")
return str.slice(s, 1, len(s) - 1)
end
end
return s
end
# Conservative allowlist for OCI image references used in front matter.
# Front matter is repo-controlled and flows into the host-side `matchlock
# run` shell command, so any value that ends up there must be tightly
# bounded: we reject quotes, whitespace, $, backticks, semicolons, and
# anything else that could escape the surrounding double quotes in the
# rendered script. This is stricter than what OCI technically allows but
# covers the universe of reasonable image references (registries, ports,
# tags, digests).
def _valid_image_ref(s)
if s == ""
return false
end
for ch in str.chars(s)
is_letter = (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")
is_digit = ch >= "0" && ch <= "9"
is_safe = ch == "." || ch == "_" || ch == "-" || ch == "/" || ch == ":" || ch == "@" || ch == "+"
if !is_letter && !is_digit && !is_safe
return false
end
end
return true
end
# Parse YAML-ish front matter from a Yolofile. The front matter, if present,
# is delimited by `---` lines at the very top of the file:
#
# ---
# image: fedora:44
# cpus: 4
# memory: 4G
# disk-size: 64G
# ---
# #!/usr/bin/env bash
# ...
#
# Returns {fm: {normalized_key => value, ...}, body: "rest of file", err: ""}.
# Keys are lowercased and `-` is rewritten to `_`. Values are trimmed and
# have optional surrounding quotes stripped. Lines starting with `#` and
# blank lines inside the front matter block are ignored. `mount:` may be
# repeated (one mount per line); every other key is last-wins. If the file
# does not start with `---`, the fast path returns {fm: {}, body: content,
# err: ""}
# so the bash body is bit-identical (and its sha256 unchanged) for existing
# pre-front-matter Yolofiles. An opening `---` without a matching closing
# `---` is an error — better than executing `---` as bash.
def parse_content(content)
if !str.starts_with(content, "---")
return {fm: {}, body: content, err: ""}
end
# The "---" must be a full line (followed by \n, \r\n, or EOF).
if len(content) > 3
c3 = str.slice(content, 3, 4)
if c3 != "\n" && c3 != "\r"
return {fm: {}, body: content, err: ""}
end
end
lines = []
for line in str.each_line(content)
lines = append(lines, str.trim_suffix(line, "\r"))
end
fm = {}
i = 1
closed = false
while i < len(lines)
t = str.trim(lines[i])
if t == "---"
closed = true
i = i + 1
break
end
if t != "" && !str.starts_with(t, "#")
idx = str.index(t, ":")
if idx > 0
k = str.lower(str.trim(str.slice(t, 0, idx)))
k = str.replace(k, "-", "_")
v = _unquote(str.trim(str.slice(t, idx + 1, len(t))))
# `mount:` is the one repeatable key: write one mount per line and
# they accumulate (joined with "\n", split back apart in validate()).
# Every other key keeps last-wins semantics.
if k == "mount" && fm[k] != nil && fm[k] != ""
fm[k] = fm[k] + "\n" + v
else
fm[k] = v
end
end
end
i = i + 1
end
if !closed
return {fm: {}, body: "", err: "front matter opens with '---' but is missing a closing '---' delimiter"}
end
body_lines = []
while i < len(lines)
body_lines = append(body_lines, lines[i])
i = i + 1
end
return {fm: fm, body: str.join(body_lines, "\n"), err: ""}
end
# Convenience: read the Yolofile from cwd and parse it. Returns the same
# shape as parse_content(). Caller is responsible for checking exists()
# first; this will raise if the file is missing.
def read_and_parse
return parse_content(os.read_file(path()))
end
# ---------------- Front matter validation ----------------
# Precedence (top wins): CLI flag > Yolofile front matter > $YOLO_* env vars
# > built-in defaults. This module only produces the "Yolofile front matter"
# slice; the caller (yolo.rugo main) does the actual precedence merge
# because module functions can't mutate yolo.rugo's top-level vars.
#
# `backends` is the BACKENDS hash (used for backend: validation).
# `ai_agents` is the AI_AGENTS hash (used for ai-agent: validation).
# `default_ai_agent` is the default agent name (substituted for ai-agent: true).
#
# Returns a hash of resolved overrides; on validation failure, prints a
# message and exits the process (same hard-fail semantics as the original).
def validate(fm, backends, ai_agents, default_ai_agent)
out = {image: "", cpus: "", mem_mb: "", disk_mb: "", agent: "", agent_set: false, backend: "", gui: false, gui_set: false, audio: false, audio_set: false, publish: [], mounts: [], privileged: false, privileged_set: false}
# `description` is accepted as free-form, self-documenting metadata. yolo
# never reads, validates, or displays it — it exists so authors can annotate
# a Yolofile without tripping the unknown-key warning below. It lives in
# `known` only (intentionally absent from `out`): there is no behaviour
# attached to it.
known = {"image" => true, "cpus" => true, "memory" => true, "disk_size" => true, "disk" => true, "disk_mb" => true, "ai_agent" => true, "backend" => true, "gui" => true, "audio" => true, "publish" => true, "mount" => true, "privileged" => true, "description" => true}
for k in fm
if known[k] != true
_warn("Yolofile: ignoring unknown front matter key '#{k}'")
end
end
v_image = fm["image"]
if v_image != nil && v_image != ""
if !_valid_image_ref(v_image)
_err("Yolofile: invalid 'image' value: '#{v_image}' (rejected — only [A-Za-z0-9._/:@+-] allowed in image references via front matter)")
os.exit(2)
end
out.image = v_image
end
v_cpus = fm["cpus"]
if v_cpus != nil && v_cpus != ""
n = try conv.to_i(v_cpus) or -1
if n <= 0
_err("Yolofile: invalid 'cpus' value: '#{v_cpus}' (expected a positive integer)")
os.exit(2)
end
out.cpus = conv.to_s(n)
end
v_mem = fm["memory"]
if v_mem != nil && v_mem != ""
sz = _parse_size(v_mem)
if sz == ""
_err("Yolofile: invalid 'memory' value: '#{v_mem}' (expected e.g. 4G, 2048M, or a bare MiB integer)")
os.exit(2)
end
out.mem_mb = sz
end
ds = ""
v_ds = fm["disk_size"]
v_d = fm["disk"]
v_dmb = fm["disk_mb"]
if v_ds != nil && v_ds != ""
ds = v_ds
elsif v_d != nil && v_d != ""
ds = v_d
elsif v_dmb != nil && v_dmb != ""
ds = v_dmb
end
if ds != ""
sz = _parse_size(ds)
if sz == ""
_err("Yolofile: invalid 'disk-size' value: '#{ds}' (expected e.g. 32G, 16384, etc.)")
os.exit(2)
end
out.disk_mb = sz
end
v_backend = fm["backend"]
if v_backend != nil && v_backend != ""
if backends[v_backend] == nil
names = []
for n in backends
names = append(names, n)
end
known_list = str.join(names, ", ")
_err("Yolofile: unknown 'backend' value: '#{v_backend}' (known: #{known_list})")
os.exit(2)
end
out.backend = v_backend
end
v_gui = fm["gui"]
if v_gui != nil && v_gui != ""
lv = str.lower(v_gui)
if lv == "true" || lv == "yes" || lv == "1" || lv == "on"
out.gui = true
out.gui_set = true
elsif lv == "false" || lv == "no" || lv == "0" || lv == "off"
out.gui = false
out.gui_set = true
else
_err("Yolofile: invalid 'gui' value: '#{v_gui}' (expected true/false)")
os.exit(2)
end
end
v_audio = fm["audio"]
if v_audio != nil && v_audio != ""
lv = str.lower(v_audio)
if lv == "true" || lv == "yes" || lv == "1" || lv == "on"
out.audio = true
out.audio_set = true
elsif lv == "false" || lv == "no" || lv == "0" || lv == "off"
out.audio = false
out.audio_set = true
else
_err("Yolofile: invalid 'audio' value: '#{v_audio}' (expected true/false)")
os.exit(2)
end
end
# `privileged` is matchlock-only. It is validated as a bool here; the
# backend-compatibility check ("privileged requires matchlock") lives in
# yolo.rugo, which is where the effective backend is resolved (it can come
# from a sticky binding, --backend, YOLO_BACKEND, or this Yolofile).
v_priv = fm["privileged"]
if v_priv != nil && v_priv != ""
lv = str.lower(v_priv)
if lv == "true" || lv == "yes" || lv == "1" || lv == "on"
out.privileged = true
out.privileged_set = true
elsif lv == "false" || lv == "no" || lv == "0" || lv == "off"
out.privileged = false
out.privileged_set = true
else
_err("Yolofile: invalid 'privileged' value: '#{v_priv}' (expected true/false)")
os.exit(2)
end
end
v_publish = fm["publish"]
if v_publish != nil && v_publish != ""
# Front matter can't express lists, so accept a comma-separated value:
# publish: 8080, 8443:443
for part in str.split(v_publish, ",")
if str.trim(part) != ""
spec = _normalize_publish(part)
if spec == ""
_err("Yolofile: invalid 'publish' value: '#{str.trim(part)}' (expected [HOST:]GUEST ports 1-65535, comma-separated)")
os.exit(2)
end
out.publish = append(out.publish, spec)
end
end
end
# `mount:` is repeatable — one bind-mount per line. parse_content joins the
# repeated lines with "\n"; we split them back apart here. Comma is NOT a
# separator (and is rejected inside a path by _parse_mount), so a guest/host
# path may not contain ','.
# mount: ./data:data
# mount: ./conf:etc/app:ro
# Only the syntax is validated here. yolo.rugo resolves each host/guest to an
# absolute path, enforces the matchlock-under-/work rule, and applies the
# host-containment gate (Yolofile mounts must stay inside $PWD unless
# --allow-absolute-mounts) — none of which this pure module can see.
v_mount = fm["mount"]
if v_mount != nil && v_mount != ""
for part in str.split(v_mount, "\n")
if str.trim(part) != ""
m = _parse_mount(part)
if m.err != ""
_err("Yolofile: invalid 'mount' value: '#{str.trim(part)}' (#{m.err})")
os.exit(2)
end
out.mounts = append(out.mounts, {host: m.host, guest: m.guest, mode: m.mode})
end
end
end
v_agent = fm["ai_agent"]
if v_agent != nil
if v_agent == "" || v_agent == "none" || v_agent == "false"
out.agent = ""
out.agent_set = true
elsif v_agent == "default" || v_agent == "true"
out.agent = default_ai_agent
out.agent_set = true
else
if ai_agents[v_agent] == nil
names = []
for n in ai_agents
names = append(names, n)
end
known_list = str.join(names, ", ")
_err("Yolofile: unknown 'ai-agent' value: '#{v_agent}' (known: #{known_list})")
os.exit(2)
end
out.agent = v_agent
out.agent_set = true
end
end
return out
end