← back to the page

terraform/guard/lib.rs

the domain guard: no binding to another domain's data · 729 lines · compiled into this Worker from the repository as it is

1//! The domain guard: no Worker binds another domain's data.
2//!
3//! Every domain owns its D1 databases, R2 buckets, Durable Object
4//! namespaces, KV namespaces and queues (docs/domains/README.md); another
5//! domain uses them only through the owner's contract (a service binding or
6//! an API), never by binding them. This reads the Terraform files the way
7//! they're written here, works out for each data binding which Worker gets
8//! it and which domain owns what it points at (`domains.toml`), and the
9//! tests fail on any binding across domains that isn't on [`PENDING`].
10//!
11//! Who owns what:
12//! - an app's own `r2_buckets`, `d1_databases` and `durable_objects`
13//! (terraform/main.tf `local.apps`): the domain of its `crate_dir`; a
14//! database's `migrations_dir` must be in the same domain;
15//! - a module's own database: the domain of the `migrations_dir` its
16//! migrations module applies; a module's own bucket: its Worker's;
17//! - `cloudflare_*.app["<app>/<binding>"]`, `module.apps["<app>"]`: `<app>`'s;
18//! - `var.x` and `module.m.out`: followed to where they're set.
19//!
20//! A binding the guard can't follow fails the test with where it is: teach
21//! the guard the new shape rather than skipping it.
22
23use std::path::Path;
24
25#[cfg(test)]
26mod semgrep;
27
28/// Binding types that hold a domain's data.
29pub const DATA_TYPES: [&str; 5] = ["d1", "r2_bucket", "durable_object_namespace", "kv_namespace", "queue"];
30
31/// Bindings across domains that are known and being removed: (the Worker's
32/// crate, the binding, what its owner changes so it can go). The guard fails
33/// on any other, and on an entry here that is gone (take it off the list).
34/// Empty since 2026-12-04: every domain's data is bound to its own Workers
35/// only. It stays empty; a new crossing is a new contract, not an entry.
36pub const PENDING: &[(&str, &str, &str)] = &[];
37
38/// Paths to domains (`domains.toml`): the longest prefix wins, on whole
39/// path segments.
40pub struct Domains(Vec<(String, String)>);
41
42impl Domains {
43 pub fn parse(toml: &str) -> Domains {
44 let mut out = Vec::new();
45 let mut domain = String::new();
46 for line in toml.lines().map(|l| strip_comment(l).trim().to_string()) {
47 if let Some(d) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
48 domain = d.trim().to_string();
49 } else if line.starts_with("paths") && !domain.is_empty() {
50 out.extend(quoted(&line).into_iter().map(|p| (p.trim_end_matches('/').to_string(), domain.clone())));
51 }
52 }
53 Domains(out)
54 }
55
56 pub fn of(&self, path: &str) -> Option<&str> {
57 let path = path.trim_end_matches('/');
58 self.0
59 .iter()
60 .filter(|(p, _)| path == p || path.starts_with(&format!("{p}/")))
61 .max_by_key(|(p, _)| p.len())
62 .map(|(_, d)| d.as_str())
63 }
64}
65
66/// One app of `local.apps`.
67#[derive(Debug, Clone)]
68pub struct App {
69 pub name: String,
70 pub crate_dir: String,
71 /// Its `x = true` settings (`login_host`, `admin_only`, …).
72 pub flags: Vec<String>,
73 /// Its `d1_databases`' migrations folders.
74 pub migrations: Vec<String>,
75 /// Its `shared_buckets`: binding → `<app>/<binding>`.
76 pub shared: Vec<(String, String)>,
77}
78
79/// A data binding a Worker gets, and whose data it is.
80#[derive(Debug, Clone, PartialEq)]
81pub struct Binding {
82 /// The Worker's crate.
83 pub worker: String,
84 pub worker_domain: String,
85 pub name: String,
86 pub kind: String,
87 /// The domain that owns what it points at.
88 pub owner: String,
89 /// `file:line`.
90 pub at: String,
91}
92
93impl Binding {
94 pub fn crosses(&self) -> bool {
95 self.worker_domain != self.owner
96 }
97}
98
99/// A Terraform file, comments gone (lines kept, so line numbers hold).
100struct File {
101 /// Relative to terraform/, e.g. `modules/logging/main.tf`.
102 rel: String,
103 text: String,
104}
105
106impl File {
107 fn read(root: &Path, rel: &str) -> Result<File, String> {
108 let raw = std::fs::read_to_string(root.join("terraform").join(rel)).map_err(|e| format!("{rel}: {e}"))?;
109 Ok(File { rel: rel.into(), text: raw.lines().map(strip_comment).collect::<Vec<_>>().join("\n") })
110 }
111
112 fn line_of(&self, at: usize) -> usize {
113 self.text[..at].matches('\n').count() + 1
114 }
115
116 /// The module directory (`modules/<dir>/…`), if it's in one.
117 fn module_dir(&self) -> Option<&str> {
118 self.rel.strip_prefix("modules/")?.split('/').next()
119 }
120}
121
122/// The line without its `#` comment (a `#` inside a string stays).
123fn strip_comment(line: &str) -> &str {
124 let mut in_str = false;
125 let mut prev = ' ';
126 for (i, c) in line.char_indices() {
127 match c {
128 '"' if prev != '\\' => in_str = !in_str,
129 '#' if !in_str => return &line[..i],
130 _ => {}
131 }
132 prev = c;
133 }
134 line
135}
136
137/// Every `"…"` in `s`.
138fn quoted(s: &str) -> Vec<String> {
139 s.split('"').skip(1).step_by(2).map(str::to_string).collect()
140}
141
142/// From the opening bracket at `open`: the index just past its match
143/// (`{[(` against `}])`, strings skipped).
144fn close(s: &str, open: usize) -> Option<usize> {
145 let mut depth = 0i32;
146 let mut in_str = false;
147 let mut prev = ' ';
148 for (i, c) in s[open..].char_indices() {
149 if c == '"' && prev != '\\' {
150 in_str = !in_str;
151 } else if !in_str {
152 match c {
153 '{' | '[' | '(' => depth += 1,
154 '}' | ']' | ')' => {
155 depth -= 1;
156 if depth == 0 {
157 return Some(open + i + 1);
158 }
159 }
160 _ => {}
161 }
162 }
163 prev = c;
164 }
165 None
166}
167
168/// The span of the block that `header` (e.g. `module "apps"`) opens.
169fn block(s: &str, header: &str) -> Option<(usize, usize)> {
170 let at = s.find(header)?;
171 let open = at + s[at..].find('{')?;
172 Some((at, close(s, open)?))
173}
174
175fn is_ident(c: char) -> bool {
176 c.is_ascii_alphanumeric() || c == '_' || c == '-'
177}
178
179/// Where `key =` is assigned in `s` (whole word): the index after the `=`.
180fn assigns(s: &str, key: &str) -> Vec<usize> {
181 let mut out = Vec::new();
182 let mut from = 0;
183 while let Some(i) = s[from..].find(key) {
184 let at = from + i;
185 from = at + key.len();
186 if s[..at].chars().next_back().is_some_and(is_ident) {
187 continue;
188 }
189 let rest = &s[from..];
190 let t = rest.trim_start_matches([' ', '\t']);
191 if t.starts_with('=') && !t.starts_with("==") {
192 out.push(from + (rest.len() - t.len()) + 1);
193 }
194 }
195 out
196}
197
198/// The expression assigned to `key` at `at` (from [`assigns`]): to the end
199/// of the line, or across lines while brackets are open.
200fn expr_at(s: &str, at: usize) -> &str {
201 let t = s[at..].trim_start_matches([' ', '\t']);
202 let start = s.len() - t.len();
203 let line_end = s[start..].find('\n').map_or(s.len(), |e| start + e);
204 let mut depth = 0i32;
205 let mut in_str = false;
206 let mut prev = ' ';
207 for (i, c) in s[start..].char_indices() {
208 let at = start + i;
209 if c == '"' && prev != '\\' {
210 in_str = !in_str;
211 } else if !in_str {
212 match c {
213 '{' | '[' | '(' => depth += 1,
214 '}' | ']' | ')' => depth -= 1,
215 '\n' if depth <= 0 => return &s[start..at],
216 _ => {}
217 }
218 if depth < 0 {
219 return &s[start..at];
220 }
221 }
222 prev = c;
223 }
224 &s[start..line_end.max(start)]
225}
226
227/// The string assigned to `key` (first one).
228fn str_of(s: &str, key: &str) -> Option<String> {
229 assigns(s, key).into_iter().find_map(|at| {
230 let e = expr_at(s, at).trim();
231 e.strip_prefix('"').and_then(|e| e.split('"').next()).map(str::to_string)
232 })
233}
234
235/// The apps of `local.apps` in terraform/main.tf.
236pub fn apps(main_tf: &str) -> Result<Vec<App>, String> {
237 let text: String = main_tf.lines().map(strip_comment).collect::<Vec<_>>().join("\n");
238 let at = assigns(&text, "apps").into_iter().find(|&a| expr_at(&text, a).trim_start().starts_with('{')).ok_or("no `apps = {` in main.tf")?;
239 let open = at + text[at..].find('{').ok_or("apps")?;
240 let end = close(&text, open).ok_or("apps: unclosed")?;
241 let body = &text[open + 1..end - 1];
242 let mut out = Vec::new();
243 let mut i = 0;
244 while i < body.len() {
245 let rest = &body[i..];
246 let line = rest.lines().next().unwrap_or("");
247 let t = line.trim();
248 let name: String = t.chars().take_while(|&c| is_ident(c)).collect();
249 if !name.is_empty() && t[name.len()..].trim_start().starts_with("= {") {
250 let open = i + rest.find('{').ok_or("app")?;
251 let end = close(body, open).ok_or_else(|| format!("app {name}: unclosed"))?;
252 let a = &body[open..end];
253 let crate_dir = str_of(a, "crate_dir").ok_or_else(|| format!("app {name}: no crate_dir"))?;
254 let flags = a.lines().filter_map(|l| l.trim().strip_suffix("true")?.trim_end().strip_suffix('=').map(|k| k.trim().to_string())).collect();
255 let migrations = assigns(a, "migrations_dir").into_iter().filter_map(|at| quoted(expr_at(a, at)).into_iter().next()).collect();
256 let shared = assigns(a, "shared_buckets")
257 .into_iter()
258 .flat_map(|at| pairs(expr_at(a, at)))
259 .collect();
260 out.push(App { name, crate_dir, flags, migrations, shared });
261 i = end;
262 } else {
263 i += line.len() + 1;
264 }
265 }
266 Ok(out)
267}
268
269/// `KEY = "value"` pairs in `s`.
270fn pairs(s: &str) -> Vec<(String, String)> {
271 let mut out = Vec::new();
272 for at in s.match_indices('=').map(|(i, _)| i) {
273 let key: String = s[..at].trim_end().chars().rev().take_while(|&c| is_ident(c)).collect::<String>().chars().rev().collect();
274 let v = s[at + 1..].trim_start();
275 if let (false, Some(v)) = (key.is_empty(), v.strip_prefix('"').and_then(|v| v.split('"').next())) {
276 out.push((key, v.to_string()));
277 }
278 }
279 out
280}
281
282/// The audit: every data binding Terraform gives a Worker, with both
283/// domains. `root` is the repo root.
284pub fn audit(root: &Path) -> Result<Vec<Binding>, String> {
285 let domains = Domains::parse(&std::fs::read_to_string(root.join("docs/domains/domains.toml")).map_err(|e| e.to_string())?);
286 let main = std::fs::read_to_string(root.join("terraform/main.tf")).map_err(|e| e.to_string())?;
287 let g = Guard { root, domains, apps: apps(&main)? };
288 let mut out = Vec::new();
289 for a in &g.apps {
290 let wd = g.domain(&a.crate_dir)?;
291 for m in &a.migrations {
292 out.push(Binding { worker: a.crate_dir.clone(), worker_domain: wd.clone(), name: format!("d1_databases ({m})"), kind: "d1".into(), owner: g.domain(m)?, at: format!("main.tf apps.{}", a.name) });
293 }
294 for (binding, r) in &a.shared {
295 out.push(Binding { worker: a.crate_dir.clone(), worker_domain: wd.clone(), name: binding.clone(), kind: "r2_bucket".into(), owner: g.app_domain(r)?, at: format!("main.tf apps.{}", a.name) });
296 }
297 }
298 let mut dirs: Vec<String> = std::fs::read_dir(root.join("terraform/modules")).map_err(|e| e.to_string())?.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
299 dirs.sort();
300 for d in dirs {
301 let rel = format!("modules/{d}/main.tf");
302 if root.join("terraform").join(&rel).exists() {
303 out.extend(g.file_bindings(&File::read(root, &rel)?)?);
304 }
305 }
306 let root_file = File::read(root, "main.tf")?;
307 out.extend(g.file_bindings(&root_file)?);
308 Ok(out)
309}
310
311struct Guard<'a> {
312 root: &'a Path,
313 domains: Domains,
314 apps: Vec<App>,
315}
316
317impl Guard<'_> {
318 fn domain(&self, path: &str) -> Result<String, String> {
319 self.domains.of(path).map(str::to_string).ok_or_else(|| format!("{path}: no domain in domains.toml"))
320 }
321
322 fn app(&self, name: &str) -> Result<&App, String> {
323 self.apps.iter().find(|a| a.name == name).ok_or_else(|| format!("no app {name} in local.apps"))
324 }
325
326 /// The domain of `<app>/<binding>`'s or `<app>`'s app.
327 fn app_domain(&self, r: &str) -> Result<String, String> {
328 self.domain(&self.app(r.split('/').next().unwrap_or(r))?.crate_dir)
329 }
330
331 /// The crate of the Worker a module file deploys (its literal `crate_dir`).
332 fn file_worker(&self, f: &File) -> Result<String, String> {
333 let dirs: Vec<String> = assigns(&f.text, "crate_dir").into_iter().filter_map(|at| quoted(expr_at(&f.text, at)).into_iter().next()).collect();
334 match dirs.as_slice() {
335 [one] => Ok(one.clone()),
336 _ => Err(format!("{}: expected one literal crate_dir, found {}", f.rel, dirs.len())),
337 }
338 }
339
340 /// The data bindings literally written in `f`.
341 fn file_bindings(&self, f: &File) -> Result<Vec<Binding>, String> {
342 let s = &f.text;
343 let mut out = Vec::new();
344 for (at, _) in s.match_indices('{') {
345 let t = s[at + 1..].trim_start_matches([' ', '\t']);
346 if !t.starts_with("name") || !t["name".len()..].trim_start().starts_with('=') || t["name".len()..].trim_start().starts_with("==") {
347 continue;
348 }
349 let Some(end) = close(s, at) else { continue };
350 let lit = &s[at..end];
351 let Some(kind) = str_of(lit, "type") else { continue };
352 if !DATA_TYPES.contains(&kind.as_str()) {
353 continue;
354 }
355 let line_start = s[..at].rfind('\n').map_or(0, |i| i + 1);
356 let line = &s[line_start..s[at..].find('\n').map_or(s.len(), |e| at + e)];
357 let where_ = format!("{}:{}", f.rel, f.line_of(at));
358 let name_expr = assigns(lit, "name").first().map(|&a| expr_at(lit, a).split(',').next().unwrap_or("").trim().to_string()).unwrap_or_default();
359 // The Workers it goes to.
360 let workers: Vec<String> = if f.module_dir() == Some("environment") {
361 let inside = |h: &str| block(s, h).is_some_and(|(a, b)| a < at && at < b);
362 if inside("module \"admin_site\"") {
363 vec![self.file_worker(&File::read(self.root, "modules/admin-site/main.tf")?)?]
364 } else if inside("module \"apps\"") {
365 // An app's own data, by construction (and shared_buckets,
366 // checked against local.apps).
367 if line.contains("== each.key") || line.contains("each.value.durable_objects") || line.contains("each.value.shared_buckets") {
368 continue;
369 }
370 let flag = line.trim().strip_prefix("each.value.").and_then(|l| l.split([' ', '?', '&']).next()).ok_or_else(|| format!("{where_}: can't tell which apps get this"))?;
371 self.apps.iter().filter(|a| a.flags.iter().any(|f| f == flag)).map(|a| a.crate_dir.clone()).collect()
372 } else {
373 return Err(format!("{where_}: a data binding outside module \"apps\" and \"admin_site\""));
374 }
375 } else {
376 vec![self.file_worker(f)?]
377 };
378 // Whose data: `[for name, x in var.m : { name = name, … }]` over a
379 // map of `<app>/<binding>` refs gives one binding each.
380 let owners: Vec<(String, String)> = if !name_expr.starts_with('"') && line.contains("in var.") {
381 let v = word_after(line, "in var.").ok_or_else(|| format!("{where_}: var"))?;
382 let e = self.parent_arg(f, &v)?;
383 let p = pairs(&e).into_iter().filter(|(_, r)| r.contains('/')).collect::<Vec<_>>();
384 if p.is_empty() {
385 return Err(format!("{where_}: var.{v} holds no <app>/<binding> refs"));
386 }
387 p.into_iter().map(|(b, r)| Ok((b, self.app_domain(&r)?))).collect::<Result<_, String>>()?
388 } else if kind == "durable_object_namespace" && !lit.contains("script_name") {
389 // A class of the Worker's own.
390 continue;
391 } else {
392 vec![(name_expr.trim_matches('"').to_string(), self.owner(f, lit).map_err(|e| format!("{where_}: {e}"))?)]
393 };
394 for w in &workers {
395 let wd = self.domain(w)?;
396 for (name, owner) in &owners {
397 out.push(Binding { worker: w.clone(), worker_domain: wd.clone(), name: name.clone(), kind: kind.clone(), owner: owner.clone(), at: where_.clone() });
398 }
399 }
400 }
401 Ok(out)
402 }
403
404 /// The domain owning what expression `e` (in `f`) points at.
405 fn owner(&self, f: &File, e: &str) -> Result<String, String> {
406 for p in ["cloudflare_d1_database.app[\"", "cloudflare_r2_bucket.app[\"", "module.apps[\""] {
407 if let Some(i) = e.find(p) {
408 let r: String = e[i + p.len()..].chars().take_while(|&c| c != '"').collect();
409 return self.app_domain(&r);
410 }
411 }
412 for kind in ["cloudflare_d1_database", "cloudflare_r2_bucket", "cloudflare_queue", "cloudflare_workers_kv_namespace"] {
413 if let Some(n) = word_after(e, &format!("{kind}.")) {
414 return self.local_owner(f, kind, &n);
415 }
416 }
417 if let Some(v) = word_after(e, "var.") {
418 let parent = self.parent_arg(f, &v)?;
419 return self.owner(&File::read(self.root, "modules/environment/main.tf")?, &parent);
420 }
421 if let Some(m) = word_after(e, "module.") {
422 let out = word_after(e, &format!("module.{m}.")).ok_or_else(|| format!("module.{m}: which output?"))?;
423 let (a, b) = block(&f.text, &format!("module \"{m}\"")).ok_or_else(|| format!("{}: no module {m}", f.rel))?;
424 let src = str_of(&f.text[a..b], "source").ok_or_else(|| format!("module {m}: no source"))?;
425 let child = File::read(self.root, &format!("modules/{}/main.tf", src.trim_start_matches("../")))?;
426 let (a, b) = block(&child.text, &format!("output \"{out}\"")).ok_or_else(|| format!("{}: no output {out}", child.rel))?;
427 let at = assigns(&child.text[a..b], "value").into_iter().next().ok_or("output without value")?;
428 let v = expr_at(&child.text[a..b], at).to_string();
429 return self.owner(&child, &v);
430 }
431 Err(format!("can't follow `{}`", e.trim()))
432 }
433
434 /// A resource of `f`'s own: a database is its migrations folder's; else
435 /// it's the module's Worker's.
436 fn local_owner(&self, f: &File, kind: &str, n: &str) -> Result<String, String> {
437 let wanted = format!("{kind}.{n}.id");
438 for at in assigns(&f.text, "database_id") {
439 if expr_at(&f.text, at).trim() == wanted {
440 let module_start = f.text[..at].rfind("module \"").ok_or("database_id outside a module")?;
441 let end = close(&f.text, module_start + f.text[module_start..].find('{').ok_or("module")?).ok_or("module")?;
442 if let Some(m) = str_of(&f.text[module_start..end], "migrations_dir") {
443 return self.domain(&m);
444 }
445 }
446 }
447 self.domain(&self.file_worker(f).map_err(|e| format!("{kind}.{n}: no migrations and {e}"))?)
448 }
449
450 /// What the environment module passes as `var.<v>` to `f`'s module.
451 fn parent_arg(&self, f: &File, v: &str) -> Result<String, String> {
452 let dir = f.module_dir().ok_or_else(|| format!("{}: var.{v} outside a module", f.rel))?;
453 let env = File::read(self.root, "modules/environment/main.tf")?;
454 let mut from = 0;
455 while let Some(i) = env.text[from..].find("module \"") {
456 let at = from + i;
457 let open = at + env.text[at..].find('{').ok_or("module")?;
458 let end = close(&env.text, open).ok_or("module")?;
459 let body = &env.text[open..end];
460 if str_of(body, "source").as_deref() == Some(&format!("../{dir}")) {
461 let a = assigns(body, v).into_iter().find(|&a| body[..a].rfind('\n').is_some_and(|l| body[l..a].trim_start().starts_with(v))).ok_or_else(|| format!("environment: module ../{dir} isn't given {v}"))?;
462 return Ok(expr_at(body, a).to_string());
463 }
464 from = end;
465 }
466 Err(format!("environment: no module with source ../{dir}"))
467 }
468}
469
470/// The identifier right after `prefix` in `s`.
471fn word_after(s: &str, prefix: &str) -> Option<String> {
472 let i = s.find(prefix)?;
473 let w: String = s[i + prefix.len()..].chars().take_while(|&c| c.is_ascii_alphanumeric() || c == '_').collect();
474 (!w.is_empty()).then_some(w)
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 fn root() -> &'static Path {
482 Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/.."))
483 }
484
485 #[test]
486 fn no_worker_binds_another_domains_data() {
487 let all = audit(root()).unwrap();
488 assert!(all.len() >= 8, "the guard found too few bindings: {all:#?}");
489 let bad: Vec<String> = all
490 .iter()
491 .filter(|b| b.crosses() && !PENDING.iter().any(|(w, n, _)| *w == b.worker && *n == b.name))
492 .map(|b| format!("{} ({}) binds {} {} of {} at {}", b.worker, b.worker_domain, b.kind, b.name, b.owner, b.at))
493 .collect();
494 assert!(bad.is_empty(), "a Worker binds another domain's data; use the owner's contract (docs/domains/README.md):\n{}", bad.join("\n"));
495 }
496
497 #[test]
498 fn pending_is_current() {
499 let all = audit(root()).unwrap();
500 for (w, n, _) in PENDING {
501 assert!(all.iter().any(|b| b.crosses() && b.worker == *w && b.name == *n), "{w} no longer binds {n} across domains: take it off PENDING");
502 }
503 }
504
505 #[test]
506 fn known_bindings_are_found() {
507 let all = audit(root()).unwrap();
508 let has = |w: &str, n: &str, owner: &str| all.iter().any(|b| b.worker == w && b.name == n && b.owner == owner);
509 assert!(has("workers/internal/log-processor", "SECURITY", "ops"));
510 assert!(has("workers/internal/log-processor", "LOGS", "ops"));
511 assert!(has("workers/internal/opgg", "DB", "web"));
512 assert!(has("workers/admin/admin-site", "LOGS", "ops"));
513 assert!(has("workers/admin/admin-site", "SECURITY", "ops"));
514 assert!(has("workers/public/account", "ACCOUNTS", "identity"));
515 assert!(has("workers/public/chat", "d1_databases (workers/public/chat/migrations)", "chat"));
516 }
517
518 #[test]
519 fn domains_take_the_longest_whole_segment() {
520 let d = Domains::parse("[a]\npaths = [\"x\", \"x/y\"] # c\n[b]\npaths = [\"x/y/z\", \"q\"]\n");
521 assert_eq!(d.of("x/y/z/f.rs"), Some("b"));
522 assert_eq!(d.of("x/y/f.rs"), Some("a"));
523 assert_eq!(d.of("x/yz"), Some("a"));
524 assert_eq!(d.of("qq"), None);
525 }
526
527 #[test]
528 fn apps_are_read() {
529 let a = apps("locals {\n apps = {\n # c {\n one = {\n crate_dir = \"w/one\"\n login_host = true\n d1_databases = { DB = { name = \"o\", migrations_dir = \"w/one/m\" } }\n shared_buckets = { B = \"two/FILES\" }\n }\n two = {\n crate_dir = \"w/two\"\n }\n }\n}\n").unwrap();
530 assert_eq!(a.len(), 2);
531 assert_eq!((a[0].name.as_str(), a[0].crate_dir.as_str()), ("one", "w/one"));
532 assert_eq!(a[0].flags, vec!["login_host".to_string()]);
533 assert_eq!(a[0].migrations, vec!["w/one/m".to_string()]);
534 assert_eq!(a[0].shared, vec![("B".to_string(), "two/FILES".to_string())]);
535 assert!(a[1].flags.is_empty());
536 }
537
538 #[test]
539 fn comments_go_strings_stay() {
540 assert_eq!(strip_comment("a = \"#x\" # y"), "a = \"#x\" ");
541 assert_eq!(expr_at("k = concat([\n 1,\n], [2])\nnext", 3), "concat([\n 1,\n], [2])");
542 }
543
544 /// `cargo test -p domain-guard -- --ignored --nocapture`: the audit table.
545 #[test]
546 #[ignore]
547 fn table() {
548 println!("| Worker | Binding | Type | Owner | Worker's domain | Across | At |\n|---|---|---|---|---|---|---|");
549 for b in audit(root()).unwrap() {
550 println!("| {} | {} | {} | {} | {} | {} | {} |", b.worker, b.name, b.kind, b.owner, b.worker_domain, if b.crosses() { "yes" } else { "" }, b.at);
551 }
552 }
553
554 /// Every file under `dir` the app's pages come from (its Rust and
555 /// HTML), build output left out.
556 fn sources(dir: &Path) -> String {
557 let mut out = String::new();
558 let Ok(entries) = std::fs::read_dir(dir) else { return out };
559 for e in entries.flatten() {
560 let p = e.path();
561 let name = e.file_name().to_string_lossy().to_string();
562 if p.is_dir() {
563 if !["target", "build", "dist", "node_modules", "container", "migrations"].contains(&name.as_str()) {
564 out += &sources(&p);
565 }
566 } else if name.ends_with(".rs") || name.ends_with(".html") {
567 out += &std::fs::read_to_string(&p).unwrap_or_default();
568 }
569 }
570 out
571 }
572
573 /// A web app (one that serves pages) has a link preview (its picture,
574 /// pre-rendered, on home's static assets, and the tags through
575 /// `platform_auth`) and a favicon (the platform's postmark, the design
576 /// Worker's, passed on over DESIGN: `platform_auth::design_asset` or
577 /// `forward_design`): a link to it pasted anywhere shows what it is.
578 #[test]
579 fn every_web_app_has_a_preview_and_a_favicon() {
580 let main_tf = std::fs::read_to_string(root().join("terraform/main.tf")).unwrap();
581 let mut web: Vec<(String, String)> = apps(&main_tf).unwrap().into_iter().map(|a| (a.name, a.crate_dir)).collect();
582 web.push(("admin".into(), "workers/admin/admin-site".into()));
583 let mut bad = Vec::new();
584 let mut seen = 0;
585 for (name, dir) in &web {
586 let src = sources(&root().join(dir));
587 if !src.contains("text/html") && !src.contains("from_html") {
588 continue;
589 }
590 seen += 1;
591 if !root().join(format!("workers/public/home/media/preview/{name}.jpg")).is_file() {
592 bad.push(format!("{name}: no workers/public/home/media/preview/{name}.jpg (1200x630, pre-rendered)"));
593 }
594 if !src.contains("platform_auth::Preview {") {
595 bad.push(format!("{name}: no platform_auth::Preview for its pages"));
596 }
597 // Its pages link the icons, or it answers the paths browsers
598 // ask for on their own (/favicon.ico) from the design Worker.
599 if !src.contains("favicon") && !src.contains("ICON_LINKS") && !src.contains("platform_auth::design_asset") {
600 bad.push(format!("{name}: no favicon"));
601 }
602 if !src.contains("platform_auth::design_asset") && !src.contains("platform_auth::forward_design") {
603 bad.push(format!("{name}: doesn't pass the look (theme, icons) on to the design Worker"));
604 }
605 }
606 assert!(seen >= 7, "found only {seen} web apps");
607 assert!(bad.is_empty(), "web apps without a link preview or favicon:\n{}", bad.join("\n"));
608 }
609
610 /// The design Worker's folder.
611 const DESIGN: &str = "workers/internal/design";
612
613 /// Every `.rs` file and `Cargo.toml` in the repo (relative paths), build
614 /// output and the container servers' own workspaces left out.
615 fn rust_files(dir: &Path, rel: &str, out: &mut Vec<String>) {
616 let Ok(entries) = std::fs::read_dir(dir) else { return };
617 for e in entries.flatten() {
618 let name = e.file_name().to_string_lossy().to_string();
619 let r = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
620 if e.path().is_dir() {
621 if !name.starts_with('.') && !["target", "build", "dist", "node_modules", "container"].contains(&name.as_str()) {
622 rust_files(&e.path(), &r, out);
623 }
624 } else if name.ends_with(".rs") || name == "Cargo.toml" {
625 out.push(r);
626 }
627 }
628 }
629
630 /// The files an `include_bytes!` / `include_str!` in `src` (the file at
631 /// `rel`) names with a plain literal, relative to the repo root (`..`
632 /// resolved). `concat!(env!(…))` ones (a UI's build output) aren't.
633 fn includes(rel: &str, src: &str) -> Vec<String> {
634 let dir = rel.rsplit_once('/').map_or("", |(d, _)| d);
635 let mut out = Vec::new();
636 for mac in ["include_bytes!(\"", "include_str!(\""] {
637 for (i, _) in src.match_indices(mac) {
638 let lit: String = src[i + mac.len()..].chars().take_while(|&c| c != '"').collect();
639 let mut parts: Vec<&str> = dir.split('/').filter(|p| !p.is_empty()).collect();
640 for p in lit.split('/') {
641 match p {
642 ".." => {
643 parts.pop();
644 }
645 "." | "" => {}
646 p => parts.push(p),
647 }
648 }
649 out.push(parts.join("/"));
650 }
651 }
652 out
653 }
654
655 /// The look's files (theme.css, the switch's build in pkg/, the icons
656 /// and logo files in assets/) are compiled into the design Worker
657 /// alone: no other crate includes them or depends on the design
658 /// Worker, and none of them sits under crates/ (every Worker's build
659 /// inputs, terraform/scripts/build-worker.sh). So editing theme.css,
660 /// rebuilding the switch or redrawing an icon rebuilds and redeploys
661 /// the design Worker only. (The inline logo, `platform_theme::LOGO_SVG`,
662 /// is page markup, code in crates/platform-theme/src.)
663 #[test]
664 fn the_look_is_compiled_into_the_design_worker_only() {
665 let look = |p: &str| p == format!("{DESIGN}/theme.css") || p.starts_with(&format!("{DESIGN}/pkg/")) || p.starts_with(&format!("{DESIGN}/assets/"));
666 let mut files = Vec::new();
667 rust_files(root(), "", &mut files);
668 assert!(files.len() > 100, "found only {} Rust files", files.len());
669 let mut bad = Vec::new();
670 let mut in_design = 0;
671 for rel in &files {
672 let src = std::fs::read_to_string(root().join(rel)).unwrap_or_default();
673 if rel.ends_with("Cargo.toml") {
674 let deps_design = src.lines().any(|l| {
675 let l = strip_comment(l).trim();
676 l.contains("internal/design\"") || l.starts_with("design =") || l.starts_with("design.workspace")
677 });
678 if deps_design && rel != "Cargo.toml" && !rel.starts_with(DESIGN) {
679 bad.push(format!("{rel} depends on the design Worker"));
680 }
681 continue;
682 }
683 for inc in includes(rel, &src) {
684 if look(&inc) {
685 if rel.starts_with(&format!("{DESIGN}/")) {
686 in_design += 1;
687 } else {
688 bad.push(format!("{rel} compiles in {inc}"));
689 }
690 }
691 }
692 }
693 assert!(bad.is_empty(), "the look's files are the design Worker's alone:\n{}", bad.join("\n"));
694 assert!(in_design >= 9, "the design Worker includes only {in_design} of the look's files");
695 // None of them under crates/, which every Worker's build hashes.
696 let mut stray = Vec::new();
697 let mut walk = vec![root().join("crates")];
698 while let Some(d) = walk.pop() {
699 for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
700 let name = e.file_name().to_string_lossy().to_string();
701 if e.path().is_dir() {
702 if !["target", "build", "dist"].contains(&name.as_str()) {
703 walk.push(e.path());
704 }
705 } else if ["theme.css", "theme.js", "theme_bg.wasm", "favicon.svg", "logo-email.png"].contains(&name.as_str()) || (name.starts_with("icon-") && name.ends_with(".png")) {
706 stray.push(e.path().display().to_string());
707 }
708 }
709 }
710 assert!(stray.is_empty(), "the look's files belong in {DESIGN}: {stray:?}");
711 assert_eq!(includes("a/b/src/lib.rs", "include_bytes!(\"../theme.css\") include_str!(concat!(env!(\"X\"), \"/i\"))"), ["a/b/theme.css"]);
712 }
713
714 /// Every app and the admin site get DESIGN, the design Worker, by its
715 /// module's output (so it's there before they bind it).
716 #[test]
717 fn every_page_server_binds_the_design_worker() {
718 let env = std::fs::read_to_string(root().join("terraform/modules/environment/main.tf")).unwrap();
719 let (a, b) = block(&env, "module \"apps\"").unwrap();
720 assert!(env[a..b].lines().any(|l| l.trim() == "[{ name = \"DESIGN\", type = \"service\", service = module.design.script_name }],"), "module \"apps\": every app's DESIGN");
721 let (a, b) = block(&env, "module \"admin_site\"").unwrap();
722 assert!(env[a..b].contains("design_service = module.design.script_name"));
723 let admin = std::fs::read_to_string(root().join("terraform/modules/admin-site/main.tf")).unwrap();
724 assert!(admin.contains("{ name = \"DESIGN\", type = \"service\", service = var.design_service }"));
725 let design = std::fs::read_to_string(root().join("terraform/modules/design/main.tf")).unwrap();
726 assert!(design.contains(&format!("crate_dir = \"{DESIGN}\"")));
727 assert!(!design.lines().any(|l| l.trim_start().starts_with("hostname")), "internal: no hostname");
728 }
729}