返回 CodeWhale
bundle.rs
1 //! Bundle rendering for `codewhale remote-setup`.
2 //!
3 //! Renders a self-contained deploy bundle to `--out`:
4 //! `runtime.env`, `<bridge>.env`, the runtime + bridge systemd units, and a
5 //! `RUNBOOK.md` with the exact remaining manual steps and first-pairing flow.
6 //!
7 //! Env files lead with `CODEWHALE_*` keys; `DEEPSEEK_*` are documented as legacy
8 //! aliases. The provider lives entirely in `runtime.env` (the bridge is pure
9 //! transport and never needs to know which provider is behind the runtime).
10
11 use std::path::{Path, PathBuf};
12
13 use anyhow::{Context, Result};
14
15 use super::registry::{BridgeSpec, CloudTarget, DeployInputs, InstallMethod, SecretStore};
16
17 /// Default runtime port the units and bundle use.
18 pub const DEFAULT_PORT: u16 = 7878;
19 /// Default worker count.
20 pub const DEFAULT_WORKERS: u32 = 2;
21 /// Default runtime URL the bridge talks to (loopback only).
22 pub const DEFAULT_RUNTIME_URL: &str = "http://127.0.0.1:7878";
23
24 /// Minimal provider facts the bundle needs, read from the existing
25 /// `codewhale_config::provider` registry (the single source of truth).
26 #[derive(Debug, Clone)]
27 pub struct ProviderInfo {
28 /// Canonical provider slug, e.g. `"deepseek"`.
29 pub slug: String,
30 /// Human-readable display name, e.g. `"DeepSeek"`.
31 pub display: String,
32 /// The provider's own API-key env var, e.g. `"DEEPSEEK_API_KEY"` (`env_keys[0]`).
33 pub key_var: String,
34 /// Provider default model, used as a comment hint in the bundle.
35 pub default_model: String,
36 }
37
38 impl ProviderInfo {
39 /// Resolve a [`ProviderInfo`] from a slug against the config provider registry.
40 #[must_use]
41 pub fn from_slug(slug: &str) -> Option<Self> {
42 let kind = codewhale_config::ProviderKind::parse(slug)?;
43 let p = codewhale_config::provider::provider_for_kind(kind);
44 let key_var = p.env_vars().first().copied().unwrap_or("CODEWHALE_API_KEY");
45 Some(Self {
46 slug: p.id().to_string(),
47 display: p.display_name().to_string(),
48 key_var: key_var.to_string(),
49 default_model: p.default_model().to_string(),
50 })
51 }
52 }
53
54 /// Everything needed to render a bundle. Constructed by the wizard (or directly
55 /// in tests). Secret *values* are placeholders the RUNBOOK tells the user to
56 /// replace; the only generated secret is the runtime token.
57 #[derive(Debug, Clone)]
58 pub struct BundleInputs {
59 pub cloud: &'static CloudTarget,
60 pub bridge: &'static BridgeSpec,
61 pub provider: ProviderInfo,
62 /// Model id to write (default `"auto"`).
63 pub model: String,
64 /// Generated runtime token shared by `runtime.env` and `<bridge>.env`.
65 pub runtime_token: String,
66 /// Provider API-key value (placeholder unless the user supplied one).
67 pub provider_key_value: String,
68 /// Bridge secret values keyed by env var (placeholder unless supplied).
69 pub bridge_secret_values: Vec<(String, String)>,
70 /// Allowlist string (comma-separated chat ids); may be empty for first pairing.
71 pub allowlist: String,
72 /// Runtime port.
73 pub port: u16,
74 /// Runtime worker count.
75 pub workers: u32,
76 /// Workspace path on the host.
77 pub workspace: String,
78 }
79
80 impl BundleInputs {
81 /// Build the [`DeployInputs`] the cloud `plan()` consumes.
82 #[must_use]
83 pub fn deploy_inputs(&self) -> DeployInputs {
84 DeployInputs {
85 bridge_slug: self.bridge.slug.to_string(),
86 provider_slug: self.provider.slug.to_string(),
87 region: self.cloud.default_region.to_string(),
88 instance_name: "codewhale-remote".to_string(),
89 image: "ghcr.io/codewhale-hq/codewhale:latest".to_string(),
90 }
91 }
92 }
93
94 /// A single rendered file: relative path within the bundle + contents.
95 #[derive(Debug, Clone, PartialEq, Eq)]
96 pub struct RenderedFile {
97 pub relative_path: String,
98 pub contents: String,
99 }
100
101 /// Render every bundle file in memory (no filesystem writes). Pure function —
102 /// used directly by tests so we never touch disk or run a command.
103 #[must_use]
104 pub fn render_bundle(inputs: &BundleInputs) -> Vec<RenderedFile> {
105 vec![
106 RenderedFile {
107 relative_path: "runtime.env".to_string(),
108 contents: render_runtime_env(inputs),
109 },
110 RenderedFile {
111 relative_path: format!("{}.env", inputs.bridge.slug),
112 contents: render_bridge_env(inputs),
113 },
114 RenderedFile {
115 relative_path: "codewhale-runtime.service".to_string(),
116 contents: render_runtime_unit(inputs),
117 },
118 RenderedFile {
119 relative_path: inputs.bridge.service_unit.to_string(),
120 contents: render_bridge_unit(inputs),
121 },
122 RenderedFile {
123 relative_path: "RUNBOOK.md".to_string(),
124 contents: render_runbook(inputs),
125 },
126 ]
127 }
128
129 /// Render the bundle to `out_dir`, creating it if needed. Returns the absolute
130 /// paths written, in render order.
131 pub fn write_bundle(inputs: &BundleInputs, out_dir: &Path) -> Result<Vec<PathBuf>> {
132 use std::io::Write as _;
133
134 let mut dir_builder = std::fs::DirBuilder::new();
135 dir_builder.recursive(true);
136 #[cfg(unix)]
137 {
138 use std::os::unix::fs::DirBuilderExt as _;
139 dir_builder.mode(0o700);
140 }
141 dir_builder
142 .create(out_dir)
143 .with_context(|| format!("creating bundle dir {}", out_dir.display()))?;
144 #[cfg(unix)]
145 {
146 use std::os::unix::fs::PermissionsExt as _;
147 std::fs::set_permissions(out_dir, std::fs::Permissions::from_mode(0o700))
148 .with_context(|| format!("restricting permissions on {}", out_dir.display()))?;
149 }
150
151 let mut written = Vec::new();
152 for file in render_bundle(inputs) {
153 let path = out_dir.join(&file.relative_path);
154 #[cfg(unix)]
155 let is_secret_env = file.relative_path.ends_with(".env");
156 let mut options = std::fs::OpenOptions::new();
157 options.write(true).create(true).truncate(true);
158 #[cfg(unix)]
159 if is_secret_env {
160 use std::os::unix::fs::OpenOptionsExt as _;
161 options.mode(0o600);
162 }
163 let mut handle = options
164 .open(&path)
165 .with_context(|| format!("opening {}", path.display()))?;
166 #[cfg(unix)]
167 if is_secret_env {
168 use std::os::unix::fs::PermissionsExt as _;
169 handle
170 .set_permissions(std::fs::Permissions::from_mode(0o600))
171 .with_context(|| format!("restricting permissions on {}", path.display()))?;
172 }
173 handle
174 .write_all(file.contents.as_bytes())
175 .with_context(|| format!("writing {}", path.display()))?;
176 written.push(path);
177 }
178 Ok(written)
179 }
180
181 // ---------------------------------------------------------------------------
182 // runtime.env — provider config lives here
183 // ---------------------------------------------------------------------------
184
185 fn render_runtime_env(i: &BundleInputs) -> String {
186 let mut out = String::new();
187 out.push_str("# Codewhale runtime config — generated by `codewhale remote-setup`.\n");
188 out.push_str("# Provider configuration lives here; the bridge is pure transport.\n");
189 out.push_str("# CODEWHALE_* keys are canonical. DEEPSEEK_* are read as legacy aliases.\n\n");
190
191 out.push_str(&format!("CODEWHALE_PROVIDER={}\n", i.provider.slug));
192 out.push_str(&format!(
193 "# Provider API key ({}). Replace the placeholder with your real key.\n",
194 i.provider.display
195 ));
196 out.push_str(&format!(
197 "{}={}\n",
198 i.provider.key_var, i.provider_key_value
199 ));
200 out.push_str(&format!(
201 "CODEWHALE_MODEL={} # provider default is {}\n",
202 i.model, i.provider.default_model
203 ));
204 out.push('\n');
205 out.push_str("# Shared auth token between the runtime and the bridge. Generated for you;\n");
206 out.push_str("# rotate it any time (keep runtime.env and the bridge env in sync).\n");
207 out.push_str(&format!("CODEWHALE_RUNTIME_TOKEN={}\n", i.runtime_token));
208 out.push_str(&format!("CODEWHALE_RUNTIME_PORT={}\n", i.port));
209 out.push_str(&format!("CODEWHALE_RUNTIME_WORKERS={}\n", i.workers));
210 out.push_str("RUST_LOG=info\n\n");
211
212 if i.provider.slug == "deepseek" {
213 out.push_str(
214 "# Legacy aliases (still honored): DEEPSEEK_RUNTIME_TOKEN, DEEPSEEK_API_KEY,\n",
215 );
216 out.push_str("# DEEPSEEK_RUNTIME_PORT, DEEPSEEK_RUNTIME_WORKERS.\n");
217 } else {
218 out.push_str("# Legacy aliases (still honored): DEEPSEEK_RUNTIME_TOKEN,\n");
219 out.push_str("# DEEPSEEK_RUNTIME_PORT, DEEPSEEK_RUNTIME_WORKERS.\n");
220 }
221 out
222 }
223
224 // ---------------------------------------------------------------------------
225 // <bridge>.env — transport only
226 // ---------------------------------------------------------------------------
227
228 fn render_bridge_env(i: &BundleInputs) -> String {
229 let mut out = String::new();
230 out.push_str(&format!(
231 "# Codewhale {} bridge config — generated by `codewhale remote-setup`.\n",
232 i.bridge.display
233 ));
234 out.push_str("# Transport only: forwards chat <-> the local runtime. No provider keys here.\n");
235 out.push_str("# CODEWHALE_* keys are canonical; DEEPSEEK_* are read as legacy aliases.\n\n");
236
237 out.push_str("# --- bridge credentials (replace placeholders) ---\n");
238 for (key, value) in &i.bridge_secret_values {
239 out.push_str(&format!("{key}={value}\n"));
240 }
241 out.push('\n');
242
243 out.push_str("# --- transport to the local runtime ---\n");
244 out.push_str(&format!("CODEWHALE_RUNTIME_URL={DEFAULT_RUNTIME_URL}\n"));
245 out.push_str("# Must match CODEWHALE_RUNTIME_TOKEN in runtime.env.\n");
246 out.push_str(&format!("CODEWHALE_RUNTIME_TOKEN={}\n", i.runtime_token));
247 out.push_str(&format!("CODEWHALE_WORKSPACE={}\n", i.workspace));
248 out.push_str(&format!("CODEWHALE_MODEL={}\n", i.model));
249 out.push_str("CODEWHALE_MODE=agent\n");
250 out.push_str("CODEWHALE_ALLOW_SHELL=true\n");
251 out.push_str("CODEWHALE_TRUST_MODE=false\n");
252 out.push_str("CODEWHALE_AUTO_APPROVE=false\n\n");
253
254 out.push_str("# --- pairing / allowlist ---\n");
255 out.push_str(&format!("{}\n", allowlist_lines(i)));
256
257 out.push_str("\n# --- bridge tuning ---\n");
258 out.push_str(&format!(
259 "{}_THREAD_MAP_PATH=/var/lib/codewhale-{}-bridge/thread-map.json\n",
260 bridge_env_prefix(i.bridge),
261 i.bridge.slug
262 ));
263 out.push_str(&format!(
264 "{}_ALLOW_GROUPS=false\n",
265 bridge_env_prefix(i.bridge)
266 ));
267 out.push_str(&format!(
268 "{}_REQUIRE_PREFIX_IN_GROUP=true\n",
269 bridge_env_prefix(i.bridge)
270 ));
271 out.push_str(&format!(
272 "{}_GROUP_PREFIX=/cw\n",
273 bridge_env_prefix(i.bridge)
274 ));
275 out.push_str(&format!(
276 "{}_MAX_REPLY_CHARS=3500\n",
277 bridge_env_prefix(i.bridge)
278 ));
279 if i.bridge.slug == "telegram" {
280 out.push_str("TELEGRAM_POLL_TIMEOUT_SECONDS=50\n");
281 }
282 out.push_str("CODEWHALE_TURN_TIMEOUT_MS=900000\n");
283 out
284 }
285
286 /// The chat allowlist uses a bridge-prefixed var (TELEGRAM_/FEISHU_); the deploy
287 /// examples key it per bridge, so mirror that.
288 fn allowlist_lines(i: &BundleInputs) -> String {
289 let prefix = bridge_env_prefix(i.bridge);
290 format!(
291 "# Comma-separated chat/user IDs allowed to control the runtime.\n# Leave empty only during first pairing, with {prefix}_ALLOW_UNLISTED=true.\n{prefix}_CHAT_ALLOWLIST={}\n{prefix}_ALLOW_UNLISTED=false",
292 i.allowlist
293 )
294 }
295
296 fn bridge_env_prefix(bridge: &BridgeSpec) -> &'static str {
297 match bridge.slug {
298 "telegram" => "TELEGRAM",
299 "feishu" => "FEISHU",
300 _ => "CODEWHALE",
301 }
302 }
303
304 // ---------------------------------------------------------------------------
305 // systemd units
306 // ---------------------------------------------------------------------------
307
308 fn render_runtime_unit(i: &BundleInputs) -> String {
309 format!(
310 "[Unit]\n\
311 Description=Codewhale Runtime API\n\
312 Wants=network-online.target\n\
313 After=network-online.target\n\n\
314 [Service]\n\
315 Type=simple\n\
316 User=codewhale\n\
317 Group=codewhale\n\
318 WorkingDirectory={workspace}\n\
319 # Legacy /etc/deepseek is loaded first for old installs; /etc/codewhale wins.\n\
320 EnvironmentFile=-/etc/deepseek/runtime.env\n\
321 EnvironmentFile=-/etc/codewhale/runtime.env\n\
322 ExecStart=/bin/sh -lc 'exec /home/codewhale/.cargo/bin/codewhale serve --http --host 127.0.0.1 --port \"${{CODEWHALE_RUNTIME_PORT:-${{DEEPSEEK_RUNTIME_PORT:-{port}}}}}\" --workers \"${{CODEWHALE_RUNTIME_WORKERS:-${{DEEPSEEK_RUNTIME_WORKERS:-{workers}}}}}\"'\n\
323 Restart=on-failure\n\
324 RestartSec=5\n\
325 NoNewPrivileges=true\n\
326 PrivateTmp=true\n\
327 ProtectSystem=full\n\
328 ReadWritePaths=/home/codewhale/.codewhale /home/codewhale/.deepseek {workspace}\n\n\
329 [Install]\n\
330 WantedBy=multi-user.target\n",
331 workspace = i.workspace,
332 port = i.port,
333 workers = i.workers,
334 )
335 }
336
337 fn render_bridge_unit(i: &BundleInputs) -> String {
338 format!(
339 "[Unit]\n\
340 Description=Codewhale {display} Phone Bridge\n\
341 Wants=network-online.target codewhale-runtime.service\n\
342 After=network-online.target codewhale-runtime.service\n\n\
343 [Service]\n\
344 Type=simple\n\
345 User=codewhale\n\
346 Group=codewhale\n\
347 WorkingDirectory={install_dir}\n\
348 # Legacy /etc/deepseek is loaded first for old installs; /etc/codewhale wins.\n\
349 EnvironmentFile=-/etc/deepseek/{slug}-bridge.env\n\
350 EnvironmentFile=-/etc/codewhale/{slug}-bridge.env\n\
351 ExecStart=/usr/bin/node {install_dir}/src/index.mjs\n\
352 Restart=on-failure\n\
353 RestartSec=5\n\
354 NoNewPrivileges=true\n\
355 PrivateTmp=true\n\
356 ProtectSystem=full\n\
357 ReadWritePaths=/var/lib/codewhale-{slug}-bridge\n\n\
358 [Install]\n\
359 WantedBy=multi-user.target\n",
360 display = i.bridge.display,
361 slug = i.bridge.slug,
362 install_dir = i.bridge.install_dir,
363 )
364 }
365
366 // ---------------------------------------------------------------------------
367 // RUNBOOK.md
368 // ---------------------------------------------------------------------------
369
370 fn render_runbook(i: &BundleInputs) -> String {
371 let mut out = String::new();
372 let plan = (i.cloud.plan)(&i.deploy_inputs());
373
374 out.push_str(&format!(
375 "# Codewhale remote-setup runbook — {} + {}\n\n",
376 i.cloud.display, i.bridge.display
377 ));
378 out.push_str("Generated by `codewhale remote-setup` (generate-only). Nothing was run on\n");
379 out.push_str("your behalf. Follow the steps below to stand the agent up.\n\n");
380
381 out.push_str("## What was generated\n\n");
382 out.push_str("| File | Purpose |\n|---|---|\n");
383 out.push_str(
384 "| `runtime.env` | Provider + runtime config (the only place the provider is set). |\n",
385 );
386 out.push_str(&format!(
387 "| `{}.env` | {} bridge transport config (token, allowlist, runtime URL). |\n",
388 i.bridge.slug, i.bridge.display
389 ));
390 out.push_str("| `codewhale-runtime.service` | systemd unit for the runtime API. |\n");
391 out.push_str(&format!(
392 "| `{}` | systemd unit for the {} bridge. |\n\n",
393 i.bridge.service_unit, i.bridge.display
394 ));
395
396 out.push_str("## 1. Fill in the secrets\n\n");
397 out.push_str(&format!(
398 "- In `runtime.env`, set `{}` to your real {} API key.\n",
399 i.provider.key_var, i.provider.display
400 ));
401 out.push_str(&format!("- {}\n", i.bridge.setup_hint));
402 out.push_str(&format!(
403 " Then set {} in `{}.env`.\n",
404 i.bridge
405 .secret_keys
406 .iter()
407 .map(|k| format!("`{k}`"))
408 .collect::<Vec<_>>()
409 .join(" and "),
410 i.bridge.slug
411 ));
412 out.push_str(
413 "- A random `CODEWHALE_RUNTIME_TOKEN` was generated and written to both `runtime.env`\n",
414 );
415 out.push_str(&format!(
416 " and `{}.env` (mode `0600`). Do not copy it into docs or command-line arguments;\n",
417 i.bridge.slug
418 ));
419 out.push_str(" rotate it any time, keeping both env files in sync.\n");
420 out.push_str(&format!(
421 "- Reference env template (every supported key, with comments): `{}`.\n\n",
422 i.bridge.env_template
423 ));
424
425 out.push_str("## 2. Provision the host\n\n");
426 out.push_str(&format!(
427 "Cloud: **{}** — install: {}, secrets: {}.\n\n",
428 i.cloud.display,
429 i.cloud.install.label(),
430 i.cloud.secret_store.label()
431 ));
432 out.push_str(&format!(
433 "Auto-provision (`--apply`) is **not yet implemented**. Run these `{}` steps\n",
434 i.cloud.cli_tool
435 ));
436 out.push_str("yourself (commands shown as data — review before running):\n\n");
437 for (n, step) in plan.iter().enumerate() {
438 out.push_str(&format!("{}. {}\n", n + 1, step.description));
439 out.push_str(&format!(
440 " ```sh\n {}\n ```\n",
441 step.display_command()
442 ));
443 }
444 out.push('\n');
445 if i.cloud.secret_store == SecretStore::KeyVault {
446 out.push_str("> The VM reads the provider key + runtime token from Key Vault via its\n");
447 out.push_str("> managed identity at boot — they are not baked into the image.\n\n");
448 }
449
450 out.push_str("## 3. Install the env files + units on the host\n\n");
451 out.push_str("```sh\nsudo install -d -m 750 /etc/codewhale\n");
452 out.push_str(&format!(
453 "sudo install -m 600 runtime.env /etc/codewhale/runtime.env\n\
454 sudo install -m 600 {slug}.env /etc/codewhale/{slug}-bridge.env\n\
455 sudo install -m 644 codewhale-runtime.service /etc/systemd/system/codewhale-runtime.service\n\
456 sudo install -m 644 {unit} /etc/systemd/system/{unit}\n\
457 sudo systemctl daemon-reload\n\
458 sudo systemctl enable --now codewhale-runtime {unit}\n```\n\n",
459 slug = i.bridge.slug,
460 unit = i.bridge.service_unit,
461 ));
462 if matches!(i.cloud.install, InstallMethod::NativeSystemd) {
463 out.push_str(&format!(
464 "The {} bridge is a zero-dep Node service; install it at `{}` (its\n",
465 i.bridge.display, i.bridge.install_dir
466 ));
467 out.push_str(&format!(
468 "`WorkingDirectory`) by copying `{}` there and running `npm install` if needed.\n\n",
469 i.bridge.package_dir
470 ));
471 }
472
473 out.push_str("## 4. First pairing\n\n");
474 match i.bridge.slug {
475 "telegram" => {
476 out.push_str("1. With `TELEGRAM_CHAT_ALLOWLIST` empty, temporarily set\n");
477 out.push_str(
478 " `TELEGRAM_ALLOW_UNLISTED=true`, restart the bridge, and DM your bot once.\n",
479 );
480 out.push_str(
481 "2. Read the chat id the bridge logs, add it to `TELEGRAM_CHAT_ALLOWLIST`,\n",
482 );
483 out.push_str(" set `TELEGRAM_ALLOW_UNLISTED=false`, and restart the bridge.\n");
484 }
485 "feishu" => {
486 out.push_str("1. With `FEISHU_CHAT_ALLOWLIST` empty, temporarily set\n");
487 out.push_str(
488 " `FEISHU_ALLOW_UNLISTED=true`, restart the bridge, and message the app once.\n",
489 );
490 out.push_str(
491 "2. Read the open id the bridge logs, add it to `FEISHU_CHAT_ALLOWLIST`,\n",
492 );
493 out.push_str(" set `FEISHU_ALLOW_UNLISTED=false`, and restart the bridge.\n");
494 }
495 _ => {
496 out.push_str("Pair by adding your chat id to the bridge allowlist, then disable\n");
497 out.push_str("unlisted access and restart the bridge.\n");
498 }
499 }
500 out.push('\n');
501
502 out.push_str("## 5. Verify\n\n");
503 out.push_str("```sh\nsudo systemctl status codewhale-runtime --no-pager\n");
504 out.push_str(&format!(
505 "sudo systemctl status {} --no-pager\n```\n\n",
506 i.bridge.service_unit
507 ));
508 out.push_str(
509 "Port 7878 stays bound to 127.0.0.1. To reach `/status` from a laptop, SSH-tunnel\n",
510 );
511 out.push_str("it (`ssh -L 7878:127.0.0.1:7878 <host>`) rather than opening the port.\n");
512 out
513 }
514
515 #[cfg(test)]
516 mod tests {
517 use super::*;
518 use crate::remote_setup::registry::{
519 AZURE, DIGITALOCEAN, FEISHU, LIGHTHOUSE, TELEGRAM, repo_root,
520 };
521
522 fn sample_inputs(
523 cloud: &'static CloudTarget,
524 bridge: &'static BridgeSpec,
525 provider_slug: &str,
526 ) -> BundleInputs {
527 let provider = ProviderInfo::from_slug(provider_slug)
528 .unwrap_or_else(|| panic!("provider {provider_slug} not in registry"));
529 let bridge_secret_values = bridge
530 .secret_keys
531 .iter()
532 .map(|k| {
533 (
534 (*k).to_string(),
535 format!("replace-{}", k.to_ascii_lowercase()),
536 )
537 })
538 .collect();
539 BundleInputs {
540 cloud,
541 bridge,
542 provider: provider.clone(),
543 model: "auto".to_string(),
544 // Fixed, clearly-fake token for deterministic tests (never executed).
545 runtime_token: "test-runtime-token-0000".to_string(),
546 provider_key_value: format!("replace-{}", provider.key_var.to_ascii_lowercase()),
547 bridge_secret_values,
548 allowlist: String::new(),
549 port: DEFAULT_PORT,
550 workers: DEFAULT_WORKERS,
551 workspace: "/opt/whalebro".to_string(),
552 }
553 }
554
555 #[test]
556 fn provider_info_reads_registry() {
557 let ds = ProviderInfo::from_slug("deepseek").unwrap();
558 assert_eq!(ds.slug, "deepseek");
559 assert_eq!(ds.key_var, "DEEPSEEK_API_KEY");
560 let oai = ProviderInfo::from_slug("openai").unwrap();
561 assert_eq!(oai.key_var, "OPENAI_API_KEY");
562 // Provider-registry aliases resolve to the canonical slug.
563 assert_eq!(
564 ProviderInfo::from_slug("nvidia").unwrap().slug,
565 "nvidia-nim"
566 );
567 assert_eq!(ProviderInfo::from_slug("kimi").unwrap().slug, "moonshot");
568 assert!(ProviderInfo::from_slug("not-a-provider").is_none());
569 }
570
571 #[test]
572 fn bundle_renders_expected_file_set() {
573 let inputs = sample_inputs(&LIGHTHOUSE, &FEISHU, "deepseek");
574 let files = render_bundle(&inputs);
575 let names: Vec<_> = files.iter().map(|f| f.relative_path.as_str()).collect();
576 assert!(names.contains(&"runtime.env"));
577 assert!(names.contains(&"feishu.env"));
578 assert!(names.contains(&"codewhale-runtime.service"));
579 assert!(names.contains(&"codewhale-feishu-bridge.service"));
580 assert!(names.contains(&"RUNBOOK.md"));
581 assert_eq!(files.len(), 5);
582 }
583
584 #[test]
585 fn runtime_and_bridge_share_the_token() {
586 let inputs = sample_inputs(&AZURE, &TELEGRAM, "openai");
587 let files = render_bundle(&inputs);
588 let runtime = &files
589 .iter()
590 .find(|f| f.relative_path == "runtime.env")
591 .unwrap()
592 .contents;
593 let bridge = &files
594 .iter()
595 .find(|f| f.relative_path == "telegram.env")
596 .unwrap()
597 .contents;
598 let token_line = format!("CODEWHALE_RUNTIME_TOKEN={}", inputs.runtime_token);
599 assert!(runtime.contains(&token_line), "runtime.env missing token");
600 assert!(bridge.contains(&token_line), "bridge env missing token");
601 }
602
603 #[test]
604 fn env_files_lead_with_codewhale_keys() {
605 let inputs = sample_inputs(&DIGITALOCEAN, &TELEGRAM, "deepseek");
606 let files = render_bundle(&inputs);
607 let runtime = &files
608 .iter()
609 .find(|f| f.relative_path == "runtime.env")
610 .unwrap()
611 .contents;
612 assert!(runtime.contains("CODEWHALE_PROVIDER=deepseek"));
613 assert!(runtime.contains("CODEWHALE_RUNTIME_TOKEN="));
614 assert!(runtime.contains("CODEWHALE_RUNTIME_PORT="));
615 // Provider key var present (DeepSeek doubles as canonical + legacy alias).
616 assert!(runtime.contains("DEEPSEEK_API_KEY="));
617 // Documents the legacy alias convention.
618 assert!(runtime.to_lowercase().contains("legacy alias"));
619
620 let bridge = &files
621 .iter()
622 .find(|f| f.relative_path == "telegram.env")
623 .unwrap()
624 .contents;
625 assert!(bridge.contains("CODEWHALE_RUNTIME_URL="));
626 assert!(bridge.contains("TELEGRAM_BOT_TOKEN="));
627 }
628
629 #[test]
630 fn runbook_is_non_empty_and_lists_the_plan() {
631 // DigitalOcean specifically: the RUNBOOK should carry the doctl plan.
632 let inputs = sample_inputs(&DIGITALOCEAN, &TELEGRAM, "deepseek");
633 let files = render_bundle(&inputs);
634 let runbook = &files
635 .iter()
636 .find(|f| f.relative_path == "RUNBOOK.md")
637 .unwrap()
638 .contents;
639 assert!(runbook.len() > 400, "RUNBOOK should be substantial");
640 assert!(runbook.contains("not yet implemented"));
641 assert!(runbook.contains("doctl"));
642 assert!(runbook.to_lowercase().contains("first pairing"));
643 assert!(
644 !runbook.contains(&inputs.runtime_token),
645 "RUNBOOK.md must never embed the raw runtime token"
646 );
647 }
648
649 #[test]
650 fn every_cloud_bridge_provider_triple_renders() {
651 // Cover the matrix per the RFC §Tests; assert CODEWHALE_* + matching token
652 // + non-empty RUNBOOK. No command is ever executed.
653 for cloud in &[LIGHTHOUSE, AZURE, DIGITALOCEAN] {
654 for bridge in &[FEISHU, TELEGRAM] {
655 for provider_slug in &["deepseek", "openai", "moonshot"] {
656 let inputs = sample_inputs(cloud, bridge, provider_slug);
657 let files = render_bundle(&inputs);
658 assert_eq!(files.len(), 5, "{}-{} file count", cloud.slug, bridge.slug);
659
660 let runtime = &files
661 .iter()
662 .find(|f| f.relative_path == "runtime.env")
663 .unwrap()
664 .contents;
665 assert!(runtime.contains(&format!("CODEWHALE_PROVIDER={provider_slug}")));
666 let token_line = format!("CODEWHALE_RUNTIME_TOKEN={}", inputs.runtime_token);
667 assert!(runtime.contains(&token_line));
668
669 let bridge_env = &files
670 .iter()
671 .find(|f| f.relative_path == format!("{}.env", bridge.slug))
672 .unwrap()
673 .contents;
674 assert!(bridge_env.contains(&token_line));
675
676 let runbook = &files
677 .iter()
678 .find(|f| f.relative_path == "RUNBOOK.md")
679 .unwrap()
680 .contents;
681 assert!(!runbook.is_empty());
682 assert!(
683 !runbook.contains(&inputs.runtime_token),
684 "RUNBOOK.md must not contain the raw runtime token"
685 );
686 }
687 }
688 }
689 }
690
691 #[test]
692 fn systemd_units_reference_codewhale_paths() {
693 let inputs = sample_inputs(&LIGHTHOUSE, &FEISHU, "deepseek");
694 let files = render_bundle(&inputs);
695 let unit = &files
696 .iter()
697 .find(|f| f.relative_path == "codewhale-runtime.service")
698 .unwrap()
699 .contents;
700 assert!(unit.contains("/etc/codewhale/runtime.env"));
701 assert!(!unit.contains("--auth-token"));
702 assert!(!unit.contains("CODEWHALE_RUNTIME_TOKEN"));
703 assert!(!unit.contains(&inputs.runtime_token));
704 // Legacy path still loaded first.
705 assert!(unit.contains("/etc/deepseek/runtime.env"));
706
707 let bridge_unit = &files
708 .iter()
709 .find(|f| f.relative_path == "codewhale-feishu-bridge.service")
710 .unwrap()
711 .contents;
712 assert!(bridge_unit.contains("/etc/codewhale/feishu-bridge.env"));
713 }
714
715 #[cfg(unix)]
716 #[test]
717 fn write_bundle_sets_restrictive_permissions_and_keeps_token_out_of_runbook() {
718 use std::os::unix::fs::PermissionsExt as _;
719
720 let tmp = tempfile::tempdir().unwrap();
721 let out_dir = tmp.path().join("bundle");
722 let inputs = sample_inputs(&LIGHTHOUSE, &TELEGRAM, "deepseek");
723 write_bundle(&inputs, &out_dir).unwrap();
724
725 let dir_mode = std::fs::metadata(&out_dir).unwrap().permissions().mode() & 0o777;
726 assert_eq!(dir_mode, 0o700);
727 for env_name in ["runtime.env", "telegram.env"] {
728 let mode = std::fs::metadata(out_dir.join(env_name))
729 .unwrap()
730 .permissions()
731 .mode()
732 & 0o777;
733 assert_eq!(mode, 0o600, "{env_name} must be 0600");
734 }
735 let runbook = std::fs::read_to_string(out_dir.join("RUNBOOK.md")).unwrap();
736 assert!(!runbook.contains(&inputs.runtime_token));
737 let unit = std::fs::read_to_string(out_dir.join("codewhale-runtime.service")).unwrap();
738 assert!(!unit.contains("--auth-token"));
739 assert!(!unit.contains(&inputs.runtime_token));
740 }
741
742 fn token_argument_line(text: &str) -> Option<usize> {
743 text.lines().position(|line| {
744 let flag_value = line.match_indices("--auth-token").any(|(at, flag)| {
745 let value = line[at + flag.len()..].trim_start_matches(['=', ' ', '\t']);
746 value.starts_with('$') || value.starts_with("\"$") || value.starts_with("'$")
747 });
748 let header_value = line.match_indices("-H ").any(|(at, flag)| {
749 let value = line[at + flag.len()..].trim_start_matches(['"', '\'']);
750 value.starts_with("Authorization: Bearer $")
751 });
752 flag_value || header_value
753 })
754 }
755
756 fn collect_text_files(dir: &Path, found: &mut Vec<PathBuf>) {
757 let Ok(entries) = std::fs::read_dir(dir) else {
758 return;
759 };
760 for entry in entries.flatten() {
761 let path = entry.path();
762 let name = entry.file_name();
763 let name = name.to_string_lossy();
764 if path.is_dir() {
765 if !matches!(name.as_ref(), "node_modules" | "target" | ".git" | ".state") {
766 collect_text_files(&path, found);
767 }
768 } else if entry
769 .metadata()
770 .map(|meta| meta.len() <= 4 * 1024 * 1024)
771 .unwrap_or(false)
772 {
773 found.push(path);
774 }
775 }
776 }
777
778 #[test]
779 fn token_argument_detector_flags_expansions_and_ignores_placeholders() {
780 assert!(token_argument_line("serve --auth-token \"$CODEWHALE_RUNTIME_TOKEN\"").is_some());
781 assert!(token_argument_line("serve --auth-token $TOKEN").is_some());
782 assert!(token_argument_line("serve --auth-token=\"${A:-${B}}\"").is_some());
783 assert!(token_argument_line(" --auth-token '$TOKEN' &").is_some());
784 assert!(token_argument_line("codewhale serve --http [--auth-token TOKEN]").is_none());
785 assert!(token_argument_line("leaves out `--auth-token` on purpose").is_none());
786 assert!(token_argument_line("no flag here").is_none());
787 assert!(
788 token_argument_line("curl -H \"Authorization: Bearer $CODEWHALE_RUNTIME_TOKEN\" url")
789 .is_some()
790 );
791 assert!(
792 token_argument_line(" -H 'Authorization: Bearer ${CODEWHALE_RUNTIME_TOKEN}' \\")
793 .is_some()
794 );
795 assert!(
796 token_argument_line(
797 "-H @<(printf 'Authorization: Bearer %s\\n' \"$CODEWHALE_RUNTIME_TOKEN\")"
798 )
799 .is_none()
800 );
801 assert!(token_argument_line("\"Authorization\": \"Bearer ${HF_TOKEN}\"").is_none());
802 }
803
804 #[test]
805 fn shipped_runtime_unit_starts_the_runtime_like_the_generated_unit() {
806 let generated = render_runtime_unit(&sample_inputs(&LIGHTHOUSE, &FEISHU, "deepseek"));
807 let shipped = std::fs::read_to_string(
808 repo_root().join("deploy/tencent-lighthouse/systemd/codewhale-runtime.service"),
809 )
810 .unwrap();
811 let exec_start = |unit: &str| {
812 unit.lines()
813 .find(|line| line.starts_with("ExecStart="))
814 .map(str::to_string)
815 };
816 assert!(exec_start(&shipped).is_some());
817 assert_eq!(exec_start(&shipped), exec_start(&generated));
818 }
819
820 #[test]
821 fn shipped_files_never_pass_the_runtime_token_as_an_argument() {
822 let root = repo_root();
823 let mut files = Vec::new();
824 for dir in [
825 "deploy",
826 "scripts",
827 "integrations",
828 "docs",
829 "web/lib/i18n/dictionaries",
830 ] {
831 collect_text_files(&root.join(dir), &mut files);
832 }
833 assert!(
834 files.len() > 100,
835 "expected to scan the shipped tree, found {} files",
836 files.len()
837 );
838 let offenders: Vec<String> = files
839 .iter()
840 .filter_map(|path| {
841 let text = std::fs::read_to_string(path).ok()?;
842 let line = token_argument_line(&text)?;
843 Some(format!(
844 "{}:{}",
845 path.strip_prefix(&root).unwrap_or(path).display(),
846 line + 1
847 ))
848 })
849 .collect();
850 assert!(
851 offenders.is_empty(),
852 "pass the runtime token through the environment or a header read from a file descriptor, never as a command-line value: {offenders:?}"
853 );
854 }
855 }
856
856 lines RUST