Repository navigation
Expand file tree
/
Copy pathdevstack.py
More file actions
executable file
·7249 lines (6401 loc) · 356 KB
/
Copy pathdevstack.py
File metadata and controls
executable file
·7249 lines (6401 loc) · 356 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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""devstack: build a reproducible incus-based dev + local app environment.
Phases (see DESIGN.md §8): base, app, proxy, standards, isolation, postgres.
Stdlib only, Python >= 3.11 (tomllib). Run it through the ./devstack launcher.
Layout of this file:
1. errors, small helpers 5. host/journal helpers (write + undo)
2. config schema + load/resolve 6. phases
3. logging 7. preflight, undo orchestration
4. command runner, state, journal 8. commands + CLI
"""
from __future__ import annotations
import argparse
import base64
import dataclasses
import datetime as dt
import difflib
import errno
import fcntl
import functools
import hashlib
import ipaddress
import json
import logging
import logging.handlers
import os
import platform
import pwd
import re
import secrets
import shlex
import shutil
import socket
import stat
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import time
import tomllib
import urllib.parse
from pathlib import Path, PurePosixPath
from typing import Any, Callable
VERSION = "1.0.0"
HERE = Path(__file__).resolve().parent
TEMPLATES = HERE / "templates"
TLD_FILE = HERE / "data" / "iana-tlds.txt"
# Trust roots checked in code. README.md and DESIGN.md describe each one; a unit test asserts
# every value below appears in those docs, so a bumped pin cannot silently go undocumented.
# Caddy: fingerprint of the signing key served at https://dl.cloudsmith.io/public/caddy/stable/gpg.key
# (install docs: https://caddyserver.com/docs/install#debian-ubuntu-raspbian).
CADDY_KEY_FPR = "65760C51EDEA2017CEA2CA15155B6D79CA56EA34"
# PGDG: https://www.postgresql.org/media/keys/ACCC4CF8.asc ("PostgreSQL Debian Repository"; the
# key id ACCC4CF8 is what https://wiki.postgresql.org/wiki/Apt tells you to import).
PGDG_KEY_FPR = "B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8"
# Node.js release keyring: pinned commit of https://github.com/nodejs/release-keys and the sha256 of
# gpg/pubring.kbx at that commit (a release signed by a newer releaser needs a bump).
NODE_KEYRING_COMMIT = "481637f813e912c4aa3622d7964ab426c97b8e8d"
NODE_KEYRING_SHA256 = "610b8d249da3d5733f5a128def2dd0294dbbf5b5713e6ca2529db8db419dee00"
# syft (SBOM generator, installed in the container) and grype (scanner, host-side). Pinned release
# plus the sha256 of each release tarball, from <tool>_<ver>_checksums.txt in the same GitHub release.
# A pinned hash is a smaller trust root than cosign would be (which needs a Fulcio/Rekor root and
# another binary), and strictly better than anchore's `curl | sh` installer.
SYFT_VERSION = "1.54.0"
SYFT_SHA256 = {"amd64": "54a87372498168b2d033e876fd41fa4e8035b872699e525a57046e1f2f09c860",
"arm64": "ee6d4566373a05b344bc6b5f1706f14419bf9338ba39ff686e247deefe9b8818"}
GRYPE_VERSION = "0.120.0"
GRYPE_SHA256 = {"amd64": "a5a1218dce63acdac152a6b3b5bb366e7267e36f4069848cf455543b3fa5700e",
"arm64": "bc0e52b1a0de37e2ff021c4924d689dce7dcff2e7d74b39aea16c0453e69be18"}
# gitleaks (secret scanner, host-side), pinned the same way. Its release tarballs say linux_x64, not
# amd64; GITLEAKS_ARCH maps host_arch() onto that name.
GITLEAKS_VERSION = "8.30.1"
GITLEAKS_SHA256 = {"amd64": "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb",
"arm64": "e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080"}
GITLEAKS_ARCH = {"amd64": "x64", "arm64": "arm64"}
# The project's dev toolchain, added by the app phase when it creates package.json. TypeScript is held at
# 6.0: typescript-eslint 8 (type-aware linting) supports `>=4.8.4 <6.1.0`, and plain `typescript` is
# 7.x now. @types/node follows node.version's major so the types match the runtime. The rest are
# left to pnpm, whose minimumReleaseAge (pnpm-workspace.yaml) keeps them at least a week old.
TYPESCRIPT_SPEC = "typescript@~6.0.3"
DEV_TOOLCHAIN = ("eslint", "@eslint/js", "typescript-eslint", "globals", "eslint-plugin-no-unsanitized",
"eslint-plugin-security", "@eslint-community/eslint-plugin-eslint-comments")
# Oldest pnpm with every setting the scaffolded pnpm-workspace.yaml uses (allowBuilds and
# blockExoticSubdeps arrived in 10.26).
PNPM_MIN = (10, 26, 0)
LEAKS_REPORT_KEEP = 10 # newest gitleaks reports kept in the state dir
LEAKS_MAX_FILE = 10 * 1024 * 1024 # working-tree files larger than this are not copied
# CycloneDX / SBOM handling. SBOM_CDX_VERSION is asserted on the parsed document: a syft upgrade that
# changes the spec version is a deliberate decision, not something to absorb silently.
SBOM_CDX_VERSION = "1.7"
SBOM_DIR_CONTAINER = "/var/tmp/devstack-sbom" # where syft writes inside the container
SBOM_KINDS = ("container", "app")
SBOM_REPORT_KEEP = 10 # newest grype reports kept in the state dir
GRYPE_DB_STALE_DAYS = 7
SEVERITIES = ("negligible", "low", "medium", "high", "critical")
log = logging.getLogger("devstack")
# ---------------------------------------------------------------------------
# 1. errors and small helpers
# ---------------------------------------------------------------------------
class DevstackError(Exception):
exit_code = 1
class ConfigError(DevstackError):
exit_code = 2
class PreflightError(DevstackError):
exit_code = 3
class NeedsInput(DevstackError):
exit_code = 4
class GateError(DevstackError):
"""A gate said no: `sbom check` found drift, or `sbom scan` found findings at sbom.fail_on.
Its own exit code so CI can tell "the gate says no" from "the tool broke"."""
exit_code = 5
class VerifyError(DevstackError):
pass
class CommandError(DevstackError):
def __init__(self, argv: list[str], returncode: int, output: str):
self.argv, self.returncode, self.output = argv, returncode, output
tail = "\n".join(output.strip().splitlines()[-30:])
super().__init__(
f"command failed (exit {returncode}): {short_cmd(argv)}" + (f"\n{tail}" if tail else "")
)
def now() -> str:
return dt.datetime.now().astimezone().isoformat(timespec="seconds")
def short_cmd(argv: list[str]) -> str:
if "-c" in argv:
i = argv.index("-c")
script = argv[i + 1] if i + 1 < len(argv) else ""
first = next((ln.strip() for ln in script.splitlines() if ln.strip()), "")
return shlex.join(argv[:i]) + f" -c '{first[:80]} …'"
return shlex.join(argv)
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode()).hexdigest()
def atomic_write(path: Path, content: str | bytes, mode: int = 0o644) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.devstack-tmp")
data = content.encode() if isinstance(content, str) else content
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "wb") as fh:
fh.write(data)
os.chmod(tmp, mode)
os.replace(tmp, path)
def bash(script: str, **vals: Any) -> str:
"""Fill @@KEY@@ placeholders in a bash script with shell-quoted values.
Lists become space-separated quoted words (use inside `arr=(@@X@@)`).
"""
def sub(m: re.Match) -> str:
key = m.group(1)
if key not in vals:
raise DevstackError(f"internal: script placeholder @@{key}@@ has no value")
v = vals[key]
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, (list, tuple)):
return " ".join(shlex.quote(str(x)) for x in v)
return shlex.quote(str(v))
return re.sub(r"@@([A-Z0-9_]+)@@", sub, textwrap.dedent(script).strip() + "\n")
def render(template: str, values: dict[str, Any]) -> str:
"""Render templates/<template>, replacing @@KEY@@ verbatim. Fails on unknown keys."""
text = (TEMPLATES / template).read_text()
def sub(m: re.Match) -> str:
key = m.group(1)
if key not in values:
raise DevstackError(f"template {template}: no value for @@{key}@@")
return str(values[key])
return re.sub(r"@@([A-Z0-9_]+)@@", sub, text)
def url_host(addr: str) -> str:
return f"[{addr}]" if ":" in addr else addr
# ---------------------------------------------------------------------------
# 2. configuration schema
# ---------------------------------------------------------------------------
@dataclasses.dataclass(frozen=True)
class Field:
key: str
kind: str # str | int | bool | strlist | intlist | strmap | mounts | runners
default: Any
help: str
choices: tuple = ()
path: bool = False
check: Callable[[Any], str | None] | None = None
@property
def section(self) -> str:
return self.key.split(".", 1)[0]
@property
def name(self) -> str:
return self.key.split(".", 1)[1]
def _match(pattern: str, what: str) -> Callable[[Any], str | None]:
rx = re.compile(pattern)
return lambda v: None if rx.fullmatch(str(v)) else f"must be {what}"
def _pnpm_version(v: str) -> str | None:
if v == "latest":
return None
m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", str(v))
if not m:
return "must be an exact version like 12.8.2 (or 'latest')"
if tuple(int(x) for x in m.groups()) < PNPM_MIN:
return (f"must be {'.'.join(map(str, PNPM_MIN))} or later: the scaffolded pnpm-workspace.yaml "
"uses allowBuilds and blockExoticSubdeps")
return None
def _rel_subpath(v: str) -> str | None:
pp = PurePosixPath(v)
return None if (v and not pp.is_absolute() and ".." not in pp.parts and not v.startswith("~")) \
else "must be a relative path inside the project (no '..', no leading '/' or '~')"
def _port(v: int) -> str | None:
return None if 1 <= v <= 65535 else "must be a TCP port (1-65535)"
def _ports(v: list[int]) -> str | None:
bad = [p for p in v if not 1 <= p <= 65535]
return f"invalid ports: {bad}" if bad else None
def _ipv4_or_auto(v: str) -> str | None:
if v == "auto":
return None
try:
ipaddress.IPv4Address(v)
return None
except ValueError:
return 'must be "auto" or an IPv4 address'
def _rel_paths(v: list[str]) -> str | None:
for x in v:
parts = x.split("/")
if not x or x.startswith("/") or ".." in parts:
return f"{x!r}: must be a relative path inside the project (no '..')"
return None
def _dev_servers(v: dict[str, str]) -> str | None:
for name, port in v.items():
if not re.fullmatch(r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?", name):
return f"{name!r}: must be a DNS label (lowercase letters, digits, '-')"
if not re.fullmatch(r"[0-9]{1,5}", port) or not 1024 <= int(port) <= 65535:
return f'{name} = {port!r}: must be a port from 1024 to 65535, as a string ("5173")'
return None
def _cidrs(v: list[str]) -> str | None:
for x in v:
try:
ipaddress.ip_network(x, strict=False)
except ValueError:
return f"{x!r} is not an IP network (CIDR)"
return None
HOSTNAME_RX = r"(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*"
SQL_IDENT_RX = r"[a-z_][a-z0-9_]{0,62}"
SECTIONS: dict[str, str] = {
"stack": "Identity of this environment. Every name below derives from stack.name by default, "
"so a second stack only needs a different name.",
"host": "Host-side state and dependency policy.",
"run": "Behaviour when something goes wrong.",
"logging": "Where log output goes. The log file always receives full debug output "
"(every command and its output, secrets redacted).",
"project": "The project folder, shared between host (you edit it) and container (it runs there).",
"container": "The incus container that holds the whole stack.",
"network": "The incus network ACL that keeps the whole container off the host and the LAN. Enforced "
"on the host, so nothing inside the container (not even root) can change it.",
"gpu": "Optional GPU passthrough into the container. Off by default.",
"snapshots": "incus snapshots taken before each phase; they are what makes container changes undoable.",
"ssh": "ssh access from the host (and VSCode Remote-SSH) into the container.",
"node": "Node.js inside the container (download verified with gpg + sha256).",
"dns": "Host DNS through dnsmasq. The host must already resolve through dnsmasq "
"(see index.html); devstack only adds/removes one drop-in file per stack.",
"site": "The app's public identity.",
"tls": "The local CA: its root key stays on the host and is limited to the dev domain; "
"Caddy only gets an intermediate. How the host trusts the root.",
"browser": "`devstack browse`: a Chromium confined to the dev domain, with its own profile and its own "
"trust in the dev CA. Pages the container serves are untrusted; open them here, not in your browser.",
"caddy": "Reverse proxy / static file server inside the container.",
"app": "The app service (scaffolded smoke-test server, systemd hardened), its network profile, its "
"data folder, and runners: socket-activated tools that may use the internet.",
"firewall": "ufw inside the container (phase isolation): what may come in. What services may reach "
"going out is app.profile.",
"isolation": "Fixed system users and groups for the services (phase isolation). Fixed ids keep file "
"owners on persistent volumes and let the egress profiles match a uid that never changes.",
"secrets": "Where generated secrets live inside the container (root-only, except that the dev group "
"can read the internal token).",
"checkpoint": "`devstack checkpoint`: undo everything after provisioning (an agent's changes, a bad "
"install) by restoring the container, its data volumes and the project together.",
"postgres": "Postgres, local-only, with its data on a separate incus volume that survives "
"undo/destroy/rebuild.",
"sbom": "Software bill of materials: a CycloneDX inventory generated by syft inside the container "
"and committed with the project, plus vulnerability scanning by grype on the host (its database "
"never enters the container).",
"leaks": "`devstack leaks scan`: secret scanning by gitleaks on the host, over the project's git "
"history and its uncommitted files. Only devstack's own gitleaks config is used; the project's "
"is writable from the container and is never read.",
}
DEFAULT_HEADERS = {
"Content-Security-Policy": (
"default-src 'self'; style-src 'self'; worker-src 'self' blob:; script-src 'self'; "
"img-src 'self' data:; frame-src 'self'; connect-src 'self'; font-src 'self'; "
"base-uri 'self'; form-action 'self'; frame-ancestors 'self'; media-src blob: 'self'; "
"object-src 'none'; upgrade-insecure-requests;"
),
"Referrer-Policy": "strict-origin-when-cross-origin",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Permissions-Policy": (
"accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), "
"microphone=(), payment=(), usb=(), interest-cohort=()"
),
}
SCHEMA: list[Field] = [
# stack
Field("stack.name", "str", "devbox",
"Short name of this environment (lowercase, digits, '-'). Used to derive container, "
"TLD, file and volume names. Must not clash with other containers, TLDs or files "
"already on the host.",
check=_match(r"[a-z][a-z0-9-]{1,29}", "2-30 chars: a-z, 0-9, '-', starting with a letter")),
# host
Field("host.state_dir", "str", "~/.local/state/devstack/{stack.name}",
"Journal, state, backups of replaced files, CA copy, lock file. Deleting it makes devstack "
"forget what it owns, so undo would no longer work.", path=True),
Field("host.install_missing", "bool", False,
"Non-interactive mode only: apt-install missing host tools instead of failing. "
"(Interactive mode asks.) Host packages are never removed by undo."),
# run
Field("run.on_failure", "str", "rollback",
"What to do when a step or verification fails in non-interactive mode. 'rollback' undoes "
"the failed phase (earlier phases stay); 'stop' leaves it for debugging "
"(clean up later with `devstack undo`). Interactive mode asks.",
choices=("rollback", "stop")),
# logging
Field("logging.target", "str", "both",
"Where logs go: 'stderr', 'file', 'both', or 'journald' (journalctl -t devstack-<name>). "
"With 'file' or 'journald' the terminal still shows warnings and errors.",
choices=("stderr", "file", "both", "journald")),
Field("logging.file", "str", "{host.state_dir}/devstack.log",
"Log file (appended). Always gets debug detail.", path=True),
Field("logging.level", "str", "info", "Terminal log level.",
choices=("debug", "info", "warning", "error")),
# project
Field("project.host_path", "str", "~/code/{stack.name}",
"Project folder on the host. Created if missing; existing files are never overwritten.",
path=True),
Field("project.container_path", "str", "/srv/{stack.name}",
"Where the project folder is mounted inside the container (idmapped, so files keep your "
"uid). Kept outside /home so Caddy and the hardened service can read it.", path=True),
Field("project.readonly_paths", "strlist", [],
"Extra files and folders inside the project to mount read-only in the container, so code running "
"there cannot edit what the host later runs, e.g. '.vscode' if you open the project on the host. "
"The whole .git is always read-only (the host runs git on it) and needs no entry here. Relative to "
"project.host_path. A path that doesn't exist yet is mounted by the next `up` once it does.",
check=_rel_paths),
Field("project.scaffold", "bool", True,
"Create the smoke-test app (server.ts, static/, error/, package.json, ...) in phase 'app'. "
"Existing files are kept. The project's dependencies are installed either way when node_modules "
"is missing."),
# container
Field("container.name", "str", "{stack.name}", "incus instance name.",
check=_match(r"[a-z][a-z0-9-]{0,62}", "a valid incus instance name")),
Field("container.image", "str", "images:debian/13",
"Image to launch. Debian 13 (trixie) by default: current stable. The container "
"shares the host kernel (and GPU driver, if passed through) whatever the image."),
Field("container.profiles", "strlist", ["default"], "incus profiles applied to the container."),
Field("container.storage_pool", "str", "default",
"Storage pool for the root disk and the Postgres data volume."),
Field("container.network", "str", "incusbr0", "Managed bridge the container's NIC is on."),
Field("container.nic_device", "str", "auto",
"Name of the NIC device to pin the IP on ('auto' = the nic device from the profile(s))."),
Field("container.ipv4", "str", "auto",
"Static IPv4 for the container. 'auto' keeps whatever DHCP hands out first and pins it.",
check=_ipv4_or_auto),
Field("container.user", "str", "dev",
"Login user inside the container (VSCode server, terminals, agents). Its sudo rights: "
"container.sudo. Deliberately a generic name, not your host login: only container.uid has "
"to line up with the host, and a host-derived name would end up in files you commit. "
"You never type it (the ssh config block carries it), so `ssh <ssh.host_alias>` just works.",
check=_match(r"[a-z_][a-z0-9_-]{0,31}", "a valid Linux user name")),
Field("container.uid", "str", "auto",
"uid of that user. 'auto' = your host uid, which makes the shared folder's ownership line up.",
check=_match(r"auto|[0-9]{1,7}", '"auto" or a number')),
Field("container.sudo", "str", "limited",
"What the container user may do as root. 'limited': only `sudo devstack-sync` (install listed apt "
"packages, restart the app/runners, reload Caddy), so nothing the user or an agent can edit runs as "
"root. 'full': passwordless sudo for everything (the user, and every agent running as it, is "
"root in the container; needs your OK). 'none': no sudo. Root for you is always "
"`incus exec <container> -- bash` from the host.",
choices=("limited", "full", "none")),
Field("container.cpu_limit", "str", "", "incus limits.cpu (e.g. '4'); empty = no limit."),
Field("container.memory_limit", "str", "", "incus limits.memory (e.g. '8GiB'); empty = no limit."),
Field("container.mounts", "mounts", [],
"Extra host folders to mount, e.g. a shared data folder. Each entry: name, source "
"(host path), path (container path), readonly (default false), shift (default true). "
"Entries added after the container exists are added by the next `up`."),
# network
Field("network.acl", "bool", True,
"Attach an incus network ACL to the container's NIC that rejects traffic to the host (except DNS and "
"DHCP on the bridge gateway), the LAN and other private ranges. Internet access stays."),
Field("network.acl_name", "str", "devstack-{stack.name}", "Name of that incus network ACL.",
check=_match(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}", "a valid incus ACL name")),
Field("network.allow_private", "strlist", [],
"CIDRs the container may still reach despite the ACL, e.g. ['192.168.1.20/32'] for a NAS. "
"Anything here needs your OK.", check=_cidrs),
# gpu
Field("gpu.enabled", "bool", False, "Pass the host GPU into the container."),
Field("gpu.pci", "str", "", "PCI address of one GPU (from `incus info --resources`); empty = all."),
Field("gpu.nvidia_runtime", "bool", True,
"Set nvidia.runtime=true so the host's NVIDIA userspace libs are injected "
"(requires nvidia-container-toolkit on the host)."),
# snapshots
Field("snapshots.mode", "str", "per-phase",
"'per-phase': snapshot before every phase after 'base' so it can be undone. "
"'off': no snapshots; then only `undo --all` can revert container changes.",
choices=("per-phase", "off")),
Field("snapshots.cleanup", "str", "manual",
"'manual': keep phase snapshots until `devstack snapshot prune`. 'auto': prune once `up` "
"finishes with everything verified. Pruned phases can only be undone with `undo --all`. "
"On the 'dir' storage driver every snapshot is a full rootfs copy.",
choices=("manual", "auto")),
Field("snapshots.prefix", "str", "devstack-pre-", "Name prefix of phase snapshots.",
check=_match(r"[a-z0-9][a-z0-9-]*", "lowercase letters, digits, '-'")),
# ssh
Field("ssh.key_path", "str", "~/.ssh/{container.name}_ed25519",
"Private key used for this container (created if missing).", path=True),
Field("ssh.key_passphrase", "str", "none",
"'none': key without passphrase (it only opens this local container). 'prompt': ssh-keygen "
"asks (interactive only; add it to your agent with ssh-add).",
choices=("none", "prompt")),
Field("ssh.reuse_existing_key", "bool", False,
"Allow using a key at ssh.key_path that devstack did not create (it is then never deleted)."),
Field("ssh.host_alias", "str", "{container.name}",
"Host alias for `ssh <alias>` and VSCode Remote-SSH.",
check=_match(r"[A-Za-z0-9._-]+", "letters, digits, '.', '_', '-'")),
Field("ssh.config_file", "str", "~/.ssh/config",
"ssh client config that gets a marked block for this stack.", path=True),
Field("ssh.known_hosts_file", "str", "~/.ssh/known_hosts.d/devstack-{stack.name}",
"Per-stack known_hosts file (pinned from incus, so no trust-on-first-use).", path=True),
# node
Field("node.version", "str", "24.20.0", "Exact Node.js version (verified with the release keys).",
check=_match(r"[0-9]+\.[0-9]+\.[0-9]+", "an exact version like 24.20.0")),
Field("node.pnpm_version", "str", "12.8.2",
"pnpm version for corepack (`corepack use pnpm@<v>` pins it, with its hash, in package.json's "
"packageManager). Exact and at least a week old, like the dependencies pnpm-workspace.yaml lets "
"in; 'latest' takes whatever was published last. 10.26.0 or later.", check=_pnpm_version),
Field("node.install_prefix", "str", "/usr/local", "Where the Node tarball is unpacked.", path=True),
# dns
Field("dns.tld", "str", "{container.name}",
"Dev TLD appended to site.hostname: app.example.com -> app.example.com.<tld>. "
"Empty = use site.hostname itself (single-domain override).",
check=_match(r"([a-z0-9-]+(\.[a-z0-9-]+)*)?", "a domain suffix like 'devbox' (or empty)")),
Field("dns.allow_public_tld", "bool", False,
"Allow dns.tld to be a real, delegated top-level domain (com, dev, app, ...). Off by default: "
"the wildcard would then stop every site under that TLD from resolving on this host. "
"Prefer 'internal' (reserved for private use) or any unused name."),
Field("dns.wildcard", "bool", True,
"address=/<tld>/ip: every name under the TLD goes to the container. False = exact "
"host-record lines only."),
Field("dns.extra_names", "strlist", [],
"Extra exact host names that should resolve to the container (host-record)."),
Field("dns.dnsmasq_dir", "str", "/etc/dnsmasq.d", "dnsmasq drop-in directory.", path=True),
Field("dns.dnsmasq_file", "str", "{dns.dnsmasq_dir}/devstack-{stack.name}.conf",
"The one file devstack writes for this stack.", path=True),
Field("dns.dnsmasq_service", "str", "dnsmasq", "systemd unit restarted after changes."),
# site
Field("site.hostname", "str", "app.example.com",
"The app's intended production hostname. Dev URL = https://<hostname>.<dns.tld>.",
check=_match(HOSTNAME_RX, "a lowercase hostname")),
# tls
Field("tls.host_ca_file", "str", "/usr/local/share/ca-certificates/devstack-{stack.name}.crt",
"Where devstack's local root CA (name-constrained to the dev domain) is installed on the host "
"(system trust store).", path=True,
check=_match(r"/usr/local/share/ca-certificates/.+\.crt",
"a .crt file under /usr/local/share/ca-certificates/")),
Field("tls.browser_trust", "str", "no",
"Also import the CA into your everyday browser's NSS db (~/.pki/nssdb, used by Chromium/Chrome). "
"'no' (default): only the dev browser (`devstack browse`) trusts it, from its own NSS db, so your "
"browser shows a certificate error on dev sites, a reminder that their pages are untrusted. "
"'auto' = import if certutil and the db exist, else print manual steps; 'yes' = import or fail.",
choices=("auto", "yes", "no")),
Field("tls.nss_db", "str", "~/.pki/nssdb", "NSS database directory.", path=True),
Field("tls.nss_nickname", "str", "devstack-{stack.name}", "Certificate nickname in the NSS db."),
# browser
Field("browser.binary", "str", "",
"Chromium (or Chrome) for `devstack browse`. Empty = the first of chromium, chromium-browser, "
"google-chrome-stable, google-chrome on PATH."),
# caddy
Field("caddy.manage_caddyfile", "bool", True,
"Generate <project>/infra/Caddyfile. Set false to maintain it yourself "
"(it must then exist before phase 'proxy')."),
Field("caddy.static_dir", "str", "{project.container_path}/static", "Static root.", path=True),
Field("caddy.error_dir", "str", "{project.container_path}/error", "Error / catch-all page root.",
path=True),
Field("caddy.admin", "str", "unix//run/caddy/admin.sock",
"Caddy's admin API (phase isolation). A unix socket in /run/caddy (mode 0700: caddy and root only), "
"so no local process can replace Caddy's config through the unauthenticated 127.0.0.1:2019.",
check=_match(r"unix//run/caddy/[A-Za-z0-9_.-]+\.sock",
"a socket under /run/caddy, e.g. unix//run/caddy/admin.sock")),
Field("caddy.headers", "strmap", DEFAULT_HEADERS,
"Security headers (phase standards). The error page's inline <style> hash is added to "
"style-src automatically."),
Field("caddy.same_origin", "str", "strict",
"Which browser requests the site accepts: the snippet devstack_same_origin, defined in the "
"root-owned /etc/caddy/Caddyfile and imported by every site block. 'strict': only the site's own "
"pages; a request a browser marks as coming from another site (a foreign Origin, or Sec-Fetch-Site "
"cross-site or same-site) gets a bare 403. Typed URLs, bookmarks and tools that send no browser "
"headers (curl, agents) pass. 'allow-navigation': also top-level GET navigations from other sites "
"(links in, OAuth or payment redirects back). 'off': no check. No CORS headers in any mode.",
choices=("strict", "allow-navigation", "off")),
Field("caddy.max_request_body", "str", "",
"Largest request body the site accepts (Caddy request_body max_size, e.g. '10MB', '4GiB'); "
"bigger requests get 413. Empty = no limit. Written into the generated Caddyfile only.",
check=_match(r"(|[1-9][0-9]*(B|[KMGT]i?B)?)", "empty or a size like 10MB or 4GiB")),
Field("caddy.dev_servers", "strmap", {},
"Dev servers in the container (Vite, Storybook, ...), each served by Caddy at https://<name>.<dev host>/ "
"with /api/* going to the app, so the page and its API share one origin. name = \"port\", e.g. "
"{ vite = \"5173\" }; the server listens on localhost in the container. Reach them with the dev "
"browser (`devstack browse vite`), not a forwarded port: it can't reach your host's loopback. No "
"security headers there: a dev server's inline scripts and HMR websocket would break the CSP.",
check=_dev_servers),
# app
Field("app.service_name", "str", "{stack.name}-app", "systemd unit name (without .service).",
check=_match(r"[a-zA-Z0-9_.@-]+", "a valid unit name")),
Field("app.bind", "str", "127.0.0.1", "Listen address. Loopback only, by design.",
choices=("127.0.0.1", "::1")),
Field("app.port", "int", 8080, "Listen port.", check=_port),
Field("app.entry", "str", "server.ts", "Entry file, relative to the project folder.",
check=_match(r"[A-Za-z0-9_./-]+", "a relative path")),
Field("app.profile", "str", "local",
"What the app may reach going out, enforced by nftables on its uid. 'local': loopback only "
"(Caddy, Postgres, runners), no DNS. 'internet': loopback plus the public internet (never the host "
"or private ranges). 'open': no restriction (needs your OK).",
choices=("local", "internet", "open")),
Field("app.data", "str", "volume",
"The app's writable data folder at /var/lib/<isolation.app_user> ($STATE_DIRECTORY in the app). "
"'volume': an incus custom volume (app.data_volume) that survives rebuilds like the Postgres data. "
"'host': a host folder (app.data_source); files in it belong to the service uid, so your host user "
"can't read them without sudo. 'none': the app has no writable folder.",
choices=("volume", "host", "none")),
Field("app.data_volume", "str", "{stack.name}-appdata",
"incus custom volume for app.data = 'volume'. Survives undo/destroy; only `--purge-data` deletes it.",
check=_match(r"[a-z0-9][a-z0-9-]*", "a valid volume name")),
Field("app.data_source", "str", "", "Host folder for app.data = 'host'.", path=True),
Field("app.data_adopt", "bool", False,
"Use an existing app.data_volume devstack did not create. Adopted volumes are never deleted."),
Field("app.data_backup_dir", "str", "~/.local/share/devstack/{stack.name}/backups",
"Host folder for `devstack data backup` archives.", path=True),
Field("app.data_backup_before_undo", "bool", True,
"Archive the app data automatically before undoing the isolation phase or destroying the container."),
Field("app.runners", "runners", [],
"Runners: tools that need the internet or parse untrusted files, without a daemon. Each entry: "
"name, command (project-relative, run as isolation.runner_user), port (127.0.0.1 only), and optionally "
"memory_max (default '1G'), runtime_max (default '1h'), max_connections (default 4). Every "
"connection to the port starts one job with the connection as stdin/stdout. Runners get the public "
"internet, no loopback, no secrets, and can only write <app data>/incoming. A new or changed "
"runner needs your OK."),
# firewall
Field("firewall.enabled", "bool", True, "Enable ufw in the container."),
Field("firewall.allow", "intlist", [22, 80, 443], "TCP ports allowed in.", check=_ports),
Field("firewall.deny", "intlist", [],
"Extra TCP ports denied (app.port, postgres.port and runner ports are always denied).", check=_ports),
# isolation
Field("isolation.system_uid_base", "int", 510,
"First of four fixed ids: app uid = base, runner uid/gid = base+1, data gid = base+2, dev gid = base+3. "
"Mid-range on purpose, like postgres.system_uid: Debian hands out system ids downward from 999.",
check=lambda v: None if 100 <= v <= 990 else "must be a system id (100-990)"),
Field("isolation.app_user", "str", "{stack.name}-app", "System user the app runs as.",
check=_match(r"[a-z_][a-z0-9_-]{0,31}", "a valid Linux user name (at most 32 chars)")),
Field("isolation.runner_user", "str", "{stack.name}-runner", "System user runner jobs run as.",
check=_match(r"[a-z_][a-z0-9_-]{0,31}", "a valid Linux user name (at most 32 chars)")),
Field("isolation.data_group", "str", "{stack.name}-data",
"Group that can read the app data (the app's group; the container user is a member).",
check=_match(r"[a-z_][a-z0-9_-]{0,31}", "a valid Linux group name (at most 32 chars)")),
Field("isolation.dev_group", "str", "{stack.name}-dev",
"Group that can read the internal token (for dev servers that call the API directly).",
check=_match(r"[a-z_][a-z0-9_-]{0,31}", "a valid Linux group name (at most 32 chars)")),
# secrets
Field("secrets.dir", "str", "/etc/app-secrets", "Root-only secrets folder in the container.",
path=True),
Field("secrets.token_file", "str", "internal-token.env",
"Caddy -> app shared token (INTERNAL_TOKEN=...).",
check=_match(r"[A-Za-z0-9_.-]+", "a file name")),
# checkpoint
Field("checkpoint.keep", "int", 1,
"How many checkpoints to keep. `checkpoint create` makes the new one first, then deletes the oldest "
"beyond this (after asking). On the 'dir' storage driver each one is a full copy of the container "
"and the data volumes.", check=lambda v: None if v >= 1 else "must be at least 1"),
Field("checkpoint.derived", "strlist", ["node_modules", "dist", "build", ".next", ".turbo", ".cache"],
"Ignored folders (any depth) a checkpoint leaves out because checkpoint.restore_command rebuilds them."),
Field("checkpoint.capture_max_mb", "int", 20,
"Ignored files outside checkpoint.derived (.env, local scratch data) are copied into the checkpoint "
"up to this many MB in all; the rest is listed as not captured.",
check=lambda v: None if v >= 0 else "must be 0 or more"),
Field("checkpoint.restore_command", "str", "test ! -f package.json || pnpm install --frozen-lockfile",
"Run in the project folder in the container (as the container user) after a restore, to rebuild "
"checkpoint.derived. Empty = nothing."),
# postgres
Field("postgres.enabled", "bool", True, "Run the postgres phase."),
Field("postgres.version", "int", 18, "Major version from apt.postgresql.org.",
check=lambda v: None if 13 <= v <= 40 else "must be a Postgres major version"),
Field("postgres.port", "int", 5432, "Port (loopback only).", check=_port),
Field("postgres.volume", "str", "{stack.name}-pgdata",
"incus custom volume mounted at /var/lib/postgresql. Survives undo/destroy; only "
"`--purge-data` deletes it.",
check=_match(r"[a-z0-9][a-z0-9-]*", "a valid volume name")),
Field("postgres.adopt_volume", "bool", False,
"Use an existing volume devstack did not create (e.g. after deleting the state dir). "
"Adopted volumes are never deleted by devstack."),
Field("postgres.system_uid", "int", 500,
"Fixed uid/gid of the postgres OS user, so data on a reused volume keeps its owner. "
"Mid-range on purpose: Debian hands out system ids downward from 999.",
check=lambda v: None if 100 <= v <= 999 else "must be a system uid (100-999)"),
Field("postgres.db", "str", "{stack.name_sql}", "App database name.",
check=_match(SQL_IDENT_RX, "a lowercase SQL identifier")),
Field("postgres.role", "str", "{stack.name_sql}_app", "App login role.",
check=_match(SQL_IDENT_RX, "a lowercase SQL identifier")),
Field("postgres.test_db", "str", "{postgres.db}_test",
"Empty database for integration tests, owned by the app role (\"\" = none). Not backed up. The "
"container user gets its URL as TEST_DATABASE_URL in ~/.config/devstack/<stack>.env.",
check=_match(f"({SQL_IDENT_RX})?", "a lowercase SQL identifier or empty")),
Field("postgres.env_file", "str", "postgres.env",
"Credentials file in secrets.dir (DATABASE_URL, PG* vars), given to the app unit.",
check=_match(r"[A-Za-z0-9_.-]+", "a file name")),
Field("postgres.write_pgpass", "bool", True,
"Write ~/.pgpass for the container user so `psql` just works."),
Field("postgres.backup_dir", "str", "~/.local/share/devstack/{stack.name}/backups",
"Host folder for `devstack db backup` dumps.", path=True),
Field("postgres.backup_before_undo", "bool", True,
"pg_dump automatically before undoing the postgres phase or destroying the container."),
# sbom
Field("sbom.enabled", "bool", True,
"Install syft in the container (phase base) and keep the CycloneDX files in sbom.dir current. "
"false = no download from GitHub during base, and no SBOM at all."),
Field("sbom.generate_on_up", "bool", True,
"Regenerate the SBOM at the end of a successful `up`. A failure there is a warning, never a "
"failed phase: `devstack sbom generate` redoes it."),
Field("sbom.dir", "str", "infra/sbom",
"Folder inside the project for the generated CycloneDX files (container.cdx.json, "
"app.cdx.json). Relative to the project folder, and committed with it.", check=_rel_subpath),
Field("sbom.app_source", "str", "lockfile",
"How the app inventory is taken. 'lockfile': scan the project without node_modules "
"(pnpm-lock.yaml is authoritative and deterministic). 'tree': also scan node_modules, for a "
"project whose packages the lockfile parser misses.", choices=("lockfile", "tree")),
Field("sbom.fail_on", "str", "",
"Lowest grype severity that makes `devstack sbom scan` exit 5. Empty = report only, never fail.",
choices=("", *SEVERITIES)),
Field("sbom.only_fixed", "bool", True,
"Count only vulnerabilities that have a fix available towards sbom.fail_on. On by default: "
"a finding with no fix is not actionable (Debian carries many), and gating on those makes "
"the gate permanently red. Everything is still reported either way."),
Field("sbom.ignore", "strlist", [],
"Vulnerability ids (CVE/GHSA) that `sbom scan` must not count towards sbom.fail_on. Each one "
"is a decision: record why in the project's README."),
Field("sbom.db_dir", "str", "{host.state_dir}/grype",
"Host folder for the grype binary and its vulnerability database (~1 GB). Never in the "
"project, and it survives undo/destroy like the other caches.", path=True),
# leaks
Field("leaks.history", "bool", True,
"`devstack leaks scan` covers every commit, not only the files as they are now. false = "
"uncommitted and current files only (faster on a long history)."),
Field("leaks.ignore", "strlist", [],
"Finding fingerprints (as `leaks scan` prints them) that must not fail the scan. Only for "
"false positives: a real secret is rotated, not ignored."),
Field("leaks.tool_dir", "str", "{host.state_dir}/gitleaks",
"Host folder for the gitleaks binary. Never in the project.", path=True),
]
FIELDS = {f.key: f for f in SCHEMA}
MOUNT_KEYS = {"name": str, "source": str, "path": str, "readonly": bool, "shift": bool}
RUNNER_KEYS = {"name": str, "command": str, "port": int, "memory_max": str, "runtime_max": str,
"max_connections": int}
RUNNER_DEFAULTS = {"memory_max": "1G", "runtime_max": "1h", "max_connections": 4}
RESERVED_DEVICES = {"project", "git", "pgdata", "appdata", "gpu"}
RO_DEVICE = re.compile(r"ro[0-9]+|ro-[0-9a-f]{12}") # project.readonly_paths devices (ro<N>: older devstack)
PLACEHOLDER = re.compile(r"\{([a-z_]+)\.([a-z_]+)\}")
def defaults() -> dict[str, Any]:
return {f.key: json.loads(json.dumps(f.default)) for f in SCHEMA}
@functools.lru_cache(maxsize=1)
def delegated_tlds() -> frozenset[str]:
try:
lines = TLD_FILE.read_text().split()
except OSError as e:
raise ConfigError(f"cannot read the bundled TLD list {TLD_FILE}: {e}") from None
tlds = frozenset(x.lower() for x in lines if not x.startswith("#"))
if len(tlds) < 1000:
raise ConfigError(f"{TLD_FILE} looks truncated ({len(tlds)} entries)")
return tlds
def public_tld_problem(tld: str) -> str | None:
"""Why `tld` would shadow real DNS names, or None. 'home.arpa' is reserved for home networks."""
tld = tld.lower().rstrip(".")
if not tld or tld == "home.arpa":
return None
last = tld.rsplit(".", 1)[-1]
if last in delegated_tlds():
what = "is a real top-level domain" if tld == last else f"ends in the real top-level domain '.{last}'"
return (f"{tld!r} {what}: the wildcard would make that name (and everything under it) resolve "
"to the container on this host. Use 'internal' or an unused name, or set "
"dns.allow_public_tld = true if you really mean it")
return None
def home_dir() -> Path: # noqa: N802
return Path(computed_values()["env.home"])
def computed_values() -> dict[str, str]:
pw = pwd.getpwuid(os.getuid())
return {"env.user": pw.pw_name, "env.uid": str(pw.pw_uid), "env.home": pw.pw_dir}
def type_check(f: Field, v: Any) -> str | None:
if f.kind == "str":
return None if isinstance(v, str) else "must be a string"
if f.kind == "int":
return None if isinstance(v, int) and not isinstance(v, bool) else "must be an integer"
if f.kind == "bool":
return None if isinstance(v, bool) else "must be true or false"
if f.kind == "strlist":
return None if isinstance(v, list) and all(isinstance(x, str) for x in v) else "must be a list of strings"
if f.kind == "intlist":
ok = isinstance(v, list) and all(isinstance(x, int) and not isinstance(x, bool) for x in v)
return None if ok else "must be a list of integers"
if f.kind == "strmap":
ok = isinstance(v, dict) and all(isinstance(k, str) and isinstance(x, str) for k, x in v.items())
return None if ok else "must be a table of strings"
if f.kind == "mounts":
if not isinstance(v, list):
return "must be an array of tables ([[container.mounts]])"
for i, m in enumerate(v):
if not isinstance(m, dict):
return f"entry {i} must be a table"
for k, x in m.items():
if k not in MOUNT_KEYS:
return f"entry {i}: unknown key '{k}' (allowed: {', '.join(MOUNT_KEYS)})"
if not isinstance(x, MOUNT_KEYS[k]):
return f"entry {i}: '{k}' has the wrong type"
for k in ("name", "source", "path"):
if k not in m:
return f"entry {i}: missing '{k}'"
return None
if f.kind == "runners":
if not isinstance(v, list):
return "must be an array of tables ([[app.runners]])"
for i, r in enumerate(v):
if not isinstance(r, dict):
return f"entry {i} must be a table"
for k, x in r.items():
if k not in RUNNER_KEYS:
return f"entry {i}: unknown key '{k}' (allowed: {', '.join(RUNNER_KEYS)})"
if not isinstance(x, RUNNER_KEYS[k]) or isinstance(x, bool):
return f"entry {i}: '{k}' has the wrong type"
for k in ("name", "command", "port"):
if k not in r:
return f"entry {i}: missing '{k}'"
return None
raise AssertionError(f.kind)
def normalize_runners(v: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Runner entries with every optional key filled in, in a fixed key order (so they compare equal)."""
return [{k: x[k] for k in RUNNER_KEYS if k in x} for x in ({**RUNNER_DEFAULTS, **r} for r in v)]
def parse_toml(path: Path) -> dict[str, Any]:
try:
data = tomllib.loads(path.read_text())
except FileNotFoundError:
raise ConfigError(f"config file not found: {path}") from None
except tomllib.TOMLDecodeError as e:
raise ConfigError(f"{path}: invalid TOML: {e}") from None
values = defaults()
errors = []
for section, table in data.items():
if section not in SECTIONS:
hint = difflib.get_close_matches(section, SECTIONS, n=1)
errors.append(f"unknown section [{section}]" + (f" (did you mean [{hint[0]}]?)" if hint else ""))
continue
if not isinstance(table, dict):
errors.append(f"'{section}' must be a table")
continue
for key, v in table.items():
full = f"{section}.{key}"
if full not in FIELDS:
hint = difflib.get_close_matches(full, FIELDS, n=1)
errors.append(f"unknown key {full}" + (f" (did you mean {hint[0]}?)" if hint else ""))
continue
err = type_check(FIELDS[full], v)
if err:
errors.append(f"{full}: {err}")
continue
values[full] = v
if errors:
raise ConfigError(f"{path}:\n " + "\n ".join(errors))
return values
def resolve(values: dict[str, Any]) -> dict[str, Any]:
"""Expand {section.key} placeholders (recursively, cycle-checked) and ~ in paths."""
computed = computed_values()
out: dict[str, Any] = {}
resolving: set[str] = set()
def get(key: str) -> Any:
if key in out:
return out[key]
if key in computed:
return computed[key]
if key == "stack.name_sql":
return str(get("stack.name")).replace("-", "_")
if key not in values:
raise ConfigError(f"unknown placeholder {{{key}}}")
if key in resolving:
raise ConfigError(f"placeholder cycle involving {key}")
resolving.add(key)
val = expand(values[key])
resolving.discard(key)
out[key] = val
return val
def expand(val: Any) -> Any:
if isinstance(val, str):
def sub(m: re.Match) -> str:
if m.group(1) not in SECTIONS and m.group(1) != "env":
return m.group(0) # not ours (e.g. a Caddy placeholder)
return str(get(f"{m.group(1)}.{m.group(2)}"))
return PLACEHOLDER.sub(sub, val)
if isinstance(val, list):
return [expand(x) for x in val]
if isinstance(val, dict):
return {k: expand(x) for k, x in val.items()}
return val
for key in values:
get(key)
for f in SCHEMA:
if f.path and out[f.key]:
out[f.key] = str(Path(out[f.key]).expanduser())
out["container.mounts"] = [
{**m, "source": str(Path(m["source"]).expanduser())} for m in out["container.mounts"]
]
out["app.runners"] = normalize_runners(out["app.runners"])
return out
def validate(v: dict[str, Any]) -> list[str]:
errors = []
for f in SCHEMA:
val = v[f.key]
if f.choices and val not in f.choices:
errors.append(f"{f.key} = {val!r}: must be one of {', '.join(f.choices)}")
if f.check:
err = f.check(val)
if err:
errors.append(f"{f.key} = {val!r}: {err}")
if f.path and val and not val.startswith("/"):
errors.append(f"{f.key} = {val!r}: must be an absolute path (after ~ expansion)")
taken = {v["app.port"]: "app.port", v["postgres.port"]: "postgres.port",
**{r["port"]: f"runner {r['name']}" for r in v["app.runners"] if isinstance(r, dict) and "port" in r}}
for name, port in v["caddy.dev_servers"].items():
if str(port).isdigit() and int(port) in taken:
errors.append(f"caddy.dev_servers: {name} = {port} is {taken[int(port)]}'s port")
names = [m["name"] for m in v["container.mounts"]]
if len(names) != len(set(names)) or RESERVED_DEVICES & set(names) or any(
RO_DEVICE.fullmatch(n) for n in names):
errors.append("container.mounts: names must be unique and not 'project', 'git', 'pgdata', 'appdata', "
"'gpu', 'ro<N>' or 'ro-<hex>'")
for m in v["container.mounts"]:
if not m["source"].startswith("/") or not m["path"].startswith("/"):
errors.append(f"container.mounts '{m['name']}': source and path must be absolute")
if Path(v["dns.dnsmasq_file"]).parent != Path(v["dns.dnsmasq_dir"]):
errors.append("dns.dnsmasq_file must be directly inside dns.dnsmasq_dir")
if not v["dns.dnsmasq_file"].endswith(".conf"):
errors.append("dns.dnsmasq_file should end in .conf")
if v["postgres.enabled"] and v["app.port"] == v["postgres.port"]:
errors.append("app.port and postgres.port must differ")
special = {v["app.port"]} | ({v["postgres.port"]} if v["postgres.enabled"] else set())
if special & set(v["firewall.allow"]):
errors.append("firewall.allow must not contain app.port or postgres.port (they stay internal)")
for name in v["dns.extra_names"]:
if not re.fullmatch(HOSTNAME_RX, name):
errors.append(f"dns.extra_names: {name!r} is not a valid hostname")
if v["project.container_path"] in ("/", "/srv", "/home", "/usr", "/etc", "/var"):
errors.append("project.container_path must be a dedicated folder")
if not v["dns.allow_public_tld"]:
problem = public_tld_problem(v["dns.tld"])
if problem:
errors.append(f"dns.tld = {problem}")
if v["app.data"] == "host" and not v["app.data_source"]:
errors.append('app.data = "host" needs app.data_source (a host folder)')
accounts = [v[k] for k in ("isolation.app_user", "isolation.runner_user", "isolation.data_group",
"isolation.dev_group")]
if len(set(accounts)) != len(accounts):
errors.append("isolation: app_user, runner_user, data_group and dev_group must all differ")
base = v["isolation.system_uid_base"]
if base <= v["postgres.system_uid"] <= base + 3:
errors.append(f"isolation.system_uid_base {base} overlaps postgres.system_uid {v['postgres.system_uid']} "
f"(the isolation ids are {base}-{base + 3})")
if v["postgres.test_db"] and v["postgres.test_db"] == v["postgres.db"]:
errors.append("postgres.test_db must differ from postgres.db (tests wipe it)")
errors += validate_runners(v)
return errors
RUNNER_NAME_RX = r"[a-z][a-z0-9-]{0,19}"
# Words of safe characters: nothing systemd's ExecStart= would expand ($, %), quote or split.
RUNNER_COMMAND_RX = r"[A-Za-z0-9_./=:@+-]+( [A-Za-z0-9_./=:@+-]+)*"
MEMORY_RX = r"[0-9]+[KMGT]?|[0-9]{1,2}%|infinity"
TIMESPAN_RX = r"[0-9]+(us|ms|s|min|m|h|d|w)?"
def validate_runners(v: dict[str, Any]) -> list[str]:
errors = []
runners = v["app.runners"]
reserved = {v["app.port"]: "app.port", 22: "ssh", 80: "Caddy", 443: "Caddy", 2019: "Caddy's default admin port"}
if v["postgres.enabled"]:
reserved[v["postgres.port"]] = "postgres.port"
seen_names: set[str] = set()
seen_ports: set[int] = set()
for r in runners:
missing = [k for k in ("name", "command", "port") if k not in r]
if missing:
errors.append(f"app.runners: an entry is missing {', '.join(missing)}")
continue
label = f"app.runners '{r['name']}'"
if not re.fullmatch(RUNNER_NAME_RX, r["name"]):
errors.append(f"{label}: name must be 1-20 chars: a-z, 0-9, '-', starting with a letter")
if r["name"] in seen_names:
errors.append(f"{label}: duplicate name")
seen_names.add(r["name"])
if not re.fullmatch(RUNNER_COMMAND_RX, r["command"]):
errors.append(f"{label}: command must be words of [A-Za-z0-9_./=:@+-] separated by single spaces "
"(no quotes, $ or %; put anything fancier in a script)")
if _port(r["port"]):
errors.append(f"{label}: port must be 1-65535")
elif r["port"] in reserved: