Skip to main content

bynk/
deploy.rs

1//! `bynk deploy` — provision persistent Cloudflare identity, then publish.
2//!
3//! The generated `wrangler.toml` is deliberately disposable. This module owns
4//! the small, committed `bynk.deploy.lock` ledger and materialises its KV ids
5//! into a freshly compiled worker immediately before Wrangler sees it.
6//!
7//! The command mints real Cloudflare resources and writes secrets, so it is
8//! split by concern rather than kept as one file — following the layout
9//! `bynk-emit/src/project.rs` established: this parent carries the shared
10//! imports, the `mod` declarations, and the re-exports external callers see,
11//! while each child opens with `use super::*;` and documents its own items.
12//!
13//! - `config.rs` — the generated `wrangler.toml` / build-output model. (The
14//!   `[env.<name>]` block a non-default `--env` needs is `bynk-emit`'s
15//!   `wrangler::environment`, which `apply.rs` calls.)
16//! - `graph.rs` — the binding graph, the upload order it forces, and the
17//!   deploy-time contract-skew check.
18//! - `ledger.rs` — the committed `bynk.deploy.lock`: what this project has
19//!   provisioned, the orphan diff against it, and `--prune`.
20//! - `pins.rs` — a declared foreign caller's pin (`bynk.foreign.toml`) and the
21//!   gate that refuses a build breaking it (I4, #1970).
22//! - `provisioning.rs` — every call out to the `wrangler` CLI.
23//! - `secrets.rs` — which secrets a run sets, and where each value comes from.
24//! - `plan.rs` — the plan/apply flow that drives all of the above, in `plan/`'s five children:
25//!   `run`, `model`, `keys`, `skew` and `messages`.
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::io::{self, IsTerminal, Write};
29use std::path::Path;
30use std::process::ExitCode;
31
32use bynk_check::contract_compat::{Compatibility, ServiceShape, check_call};
33use serde::{Deserialize, Serialize};
34
35use crate::cloudflare::{CloudflareApi, Exit, Failure, PushCall, VectorizeOp, Wrangler};
36use crate::doctor::{self, Capability, Context, DoctorOptions};
37#[cfg(test)]
38use crate::probe::Provenance;
39use crate::probe::{self, Toolbox};
40
41const LOCK_FILE: &str = "bynk.deploy.lock";
42// P7.4 (#1305): every non-test use of the placeholder now goes through
43// `bynk_emit::emitter::wrangler`'s own structural functions
44// (`materialise_kv_namespace_ids`/`kv_bindings_needing_ids`) —
45// this name survives only for `deploy/ledger.rs`'s own test fixtures, which
46// build a minimal `wrangler.toml` containing it.
47#[cfg(test)]
48use bynk_emit::emitter::wrangler::KV_NAMESPACE_ID_PLACEHOLDER;
49
50mod agent_move;
51mod apply;
52mod config;
53pub(crate) mod containers;
54mod declared;
55mod destinations;
56mod facts;
57mod first_deploy;
58mod gates;
59mod graph;
60mod hyperdrive;
61mod kind;
62mod ledger;
63mod linked;
64mod on_account;
65mod pins;
66mod plan;
67mod provisioning;
68mod revert;
69mod secrets;
70mod senders;
71mod vectorize;
72
73use agent_move::*;
74use apply::*;
75use config::*;
76use containers::*;
77use declared::*;
78use gates::*;
79use graph::*;
80use kind::*;
81use ledger::*;
82use linked::*;
83use pins::*;
84use plan::*;
85use provisioning::*;
86use secrets::*;
87use senders::*;
88use vectorize::*;
89
90// External facade: the paths `main.rs` and `dev.rs` already use must keep
91// resolving exactly as they did before the split.
92pub use ledger::{materialise_deploy_state, materialise_mtls_for_dev};
93pub(crate) use plan::conflicting_env_passthrough;
94pub use plan::{DeployFormat, DeployOptions, run};
95pub use revert::{RevertOptions, revert};
96// State-migrations S4 (#2259): `bynk migrate sweep` names deployed Workers as
97// `deploy` does, and mints its run's key as an edge key is minted.
98pub(crate) use config::deployed_worker_name;
99pub(crate) use config::{VectorizeDecl, project_resources};
100
101/// The Cloudflare script name of each Worker directory: what a Service Binding to it
102/// names (`name` in its `wrangler.toml`, else the directory).
103pub(crate) fn script_names_of(workers_dir: &Path, workers: &[String]) -> Vec<String> {
104    config::script_names(workers_dir, workers)
105        .into_keys()
106        .collect()
107}
108pub(crate) use secrets::mint_edge_key as mint_key;
109
110/// State-migrations S4 (#2259): for each Worker directory in `workers`, the
111/// environments `bynk.deploy.lock` at `project_root` records it as pushed in.
112/// A missing ledger records none.
113pub(crate) fn deployed_environments(
114    project_root: &Path,
115    workers: &[String],
116) -> Result<BTreeMap<String, Vec<String>>, String> {
117    let lock = read_lock(&project_root.join(LOCK_FILE))?;
118    Ok(workers
119        .iter()
120        .map(|w| (w.clone(), lock.deployed_environments(w)))
121        .collect())
122}
123
124/// I2 (#1971): for `bynk dev`, the names of the edge keys each built Worker
125/// holds, and (I3) its foreign callers' secrets (a Worker with none is absent), read from the build's own
126/// configurations as `bynk deploy` reads them. An edge between contexts whose
127/// names no key can be derived from is an error, as it is at deploy.
128pub(crate) fn local_edge_keys(
129    workers_dir: &Path,
130    workers: &[String],
131    model: &bynk_emit::emit_model::WorkersBuild,
132) -> Result<BTreeMap<String, Vec<String>>, String> {
133    let resources = project_resources(workers_dir, workers, model)?;
134    let edges = project_edges(&resources);
135    for edge in &edges {
136        edge.ends()?;
137    }
138    // I3 (#1971): and the secret of each foreign caller a Worker admits, so a
139    // local foreign caller signing under the local key is admitted too.
140    Ok(workers
141        .iter()
142        .map(|w| {
143            let mut keys = edge_keys_of(w, &edges);
144            keys.extend(
145                resources[w]
146                    .foreign_callers
147                    .iter()
148                    .map(|f| f.binding.clone()),
149            );
150            (w.clone(), keys)
151        })
152        .filter(|(_, keys)| !keys.is_empty())
153        .collect())
154}
155
156/// #3386: for `bynk dev`, the env binding of each `SignedCookie` actor's signing key, by built
157/// Worker (a Worker with none is absent), read from the build's own manifests as `bynk deploy`
158/// reads them. `dev` gives every one a local key derived from its name, so no operator invents a weak one locally.
159pub(crate) fn local_session_keys(
160    workers_dir: &Path,
161    workers: &[String],
162    model: &bynk_emit::emit_model::WorkersBuild,
163) -> Result<BTreeMap<String, Vec<String>>, String> {
164    let resources = project_resources(workers_dir, workers, model)?;
165    Ok(workers
166        .iter()
167        .map(|w| {
168            let names = resources[w].session_keys.iter().map(|k| k.binding.clone());
169            (w.clone(), names.collect::<Vec<_>>())
170        })
171        .filter(|(_, names)| !names.is_empty())
172        .collect())
173}
174
175/// The session key `bynk dev` uses for one binding (see [`local_session_keys`]).
176pub(crate) fn local_session_key(binding: &str) -> String {
177    secrets::local_session_key(binding)
178}
179
180#[cfg(test)]
181mod apply_tests;
182// Unix: it runs each call through the real adapter with `sh -c`, and pins the OS's own text for a
183// wrangler that cannot start.
184#[cfg(all(test, unix))]
185mod messages_tests;
186#[cfg(test)]
187mod snapshot_tests;
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use config::tests::project;
192    use ledger::tests::{lock_with_deployed, with_kv, with_kv_instance, with_queue};
193    use plan::tests::plan_of;
194    use secrets::tests::source;
195
196    fn names(v: &[&str]) -> Vec<String> {
197        v.iter().map(|s| s.to_string()).collect()
198    }
199
200    /// The guide's worked example: `commerce-orders` binds to
201    /// `commerce-payment`, which is the one with the KV namespace.
202    fn chain() -> BTreeMap<String, Resources> {
203        project(vec![
204            (
205                "commerce-orders",
206                Resources::default().binds(&["commerce-payment"]),
207            ),
208            ("commerce-payment", Resources::default().needs_kv()),
209        ])
210    }
211
212    /// The goldens live beside the integration ones (`tests/golden/`) and bless
213    /// identically — `BYNK_BLESS=1 cargo test -p bynk`. They are driven from
214    /// here rather than from `tests/` because `derive_plan` reads the ledger and
215    /// the binding graph, which are this module's private types: goldening the
216    /// output must not force them into the crate's public API.
217    fn bless_or_assert(name: &str, actual: &str) {
218        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
219            .join("tests/golden")
220            .join(name);
221        if std::env::var_os("BYNK_BLESS").is_some() {
222            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
223            std::fs::write(&path, actual).unwrap();
224            return;
225        }
226        let expected = std::fs::read_to_string(&path).unwrap_or_else(|_| {
227            panic!(
228                "missing golden {}; regenerate with BYNK_BLESS=1 cargo test -p bynk",
229                path.display()
230            )
231        });
232        assert_eq!(
233            actual, expected,
234            "golden {name} drifted; re-bless with BYNK_BLESS=1 cargo test -p bynk"
235        );
236    }
237
238    /// #601/#600: the plan is what `--dry-run` shows and the deploy guide
239    /// quotes, so it is pinned exactly — the `order` line (slice 2's
240    /// load-bearing claim), the queue and Durable Object lines (slice 1's, the
241    /// latter reshaped by #1796), and the
242    /// JSON shape, which is a documented machine-readable surface.
243    #[test]
244    fn golden_deploy_plan() {
245        let chain_order = names(&["commerce-payment", "commerce-orders"]);
246
247        let mut out = String::new();
248
249        // Slice 0's shape: one context, nothing recorded. No `order` line —
250        // there is no ordering claim to make about a single worker.
251        out.push_str("# one context, first deploy\n");
252        out.push_str(&plan_report(
253            &plan_of(
254                &names(&["api"]),
255                &project(vec![("api", Resources::default().needs_kv())]),
256                &DeployLock::default(),
257            ),
258            DeployFormat::Short,
259        ));
260
261        // The guide's worked example: payment first, because orders binds to it.
262        out.push_str("\n# several contexts, first deploy\n");
263        out.push_str(&plan_report(
264            &plan_of(&chain_order, &chain(), &DeployLock::default()),
265            DeployFormat::Short,
266        ));
267
268        // I3 (#1971): a context admitting two foreign callers lists each
269        // one's secret as managed, beside its edge keys.
270        out.push_str("\n# I3: foreign callers' secrets\n");
271        let mut foreign = chain();
272        foreign
273            .get_mut("commerce-payment")
274            .expect("the chain's callee")
275            .foreign_callers = vec![
276            ForeignCaller {
277                actor: "Ledger".into(),
278                binding: "LEDGER_CALL_KEY".into(),
279                worker: Some("ledger-svc".into()),
280            },
281            ForeignCaller {
282                actor: "Legacy".into(),
283                binding: "LEGACY_CALL_KEY".into(),
284                worker: None,
285            },
286        ];
287        out.push_str(&plan_report(
288            &plan_of(&chain_order, &foreign, &DeployLock::default()),
289            DeployFormat::Short,
290        ));
291
292        // A re-run re-pushes rather than skipping, so the word is `redeploy`
293        // and the namespace is reused. The ledger records the KV *before* the
294        // push (ADR 0180), so a deployed context always has its namespace
295        // recorded too — depict that state, not an unreachable one.
296        out.push_str("\n# several contexts, already live — a re-run re-pushes\n");
297        out.push_str(&plan_report(
298            &plan_of(
299                &chain_order,
300                &chain(),
301                &with_kv(
302                    lock_with_deployed(&["commerce-payment", "commerce-orders"]),
303                    "commerce-payment",
304                ),
305            ),
306            DeployFormat::Short,
307        ));
308
309        // Slice 1's kinds. The Durable Object line is advisory in both states, so it
310        // reads the same before and after — that sameness is the point, and the
311        // golden is where it is visible.
312        out.push_str("\n# slice 1: an agent and a queue, first deploy\n");
313        out.push_str(&plan_report(
314            &plan_of(
315                &names(&["jobs"]),
316                &project(vec![(
317                    "jobs",
318                    Resources::default()
319                        .needs_kv()
320                        .consumes(&["job-intake"])
321                        .exports(&["JobLedger"]),
322                )]),
323                &DeployLock::default(),
324            ),
325            DeployFormat::Short,
326        ));
327
328        out.push_str("\n# slice 1: the same context, already provisioned\n");
329        out.push_str(&plan_report(
330            &plan_of(
331                &names(&["jobs"]),
332                &project(vec![(
333                    "jobs",
334                    Resources::default()
335                        .needs_kv()
336                        .consumes(&["job-intake"])
337                        .exports(&["JobLedger"]),
338                )]),
339                &with_queue(with_kv(lock_with_deployed(&["jobs"]), "jobs"), "job-intake"),
340            ),
341            DeployFormat::Short,
342        ));
343
344        // Slice 3. The origin mark is the load-bearing part: `declared` is the
345        // compiler's word, `supplied` is the user's, and a reader must not take
346        // the absence of a `declared` line for "this context needs no secret".
347        out.push_str("\n# slice 3: a declared auth secret, and one the user supplied\n");
348        out.push_str(&plan_report(
349            &derive_plan(
350                &names(&["api"]),
351                &project(vec![(
352                    "api",
353                    Resources::default().declares(&["AUTH_JWT_SECRET"]),
354                )]),
355                &DeployLock::default(),
356                &source(&[("STRIPE_KEY", "sk_live_x")], &[]),
357                false,
358                "default",
359            ),
360            DeployFormat::Short,
361        ));
362
363        // `--force`: the action is `overwrite` rather than `set`. Presence is
364        // absent from the plan by design — it is a live question, and the plan
365        // is derived before auth so `--dry-run` stays offline.
366        out.push_str("\n# slice 3: --force overwrites rather than setting if absent\n");
367        out.push_str(&plan_report(
368            &derive_plan(
369                &names(&["api"]),
370                &project(vec![(
371                    "api",
372                    Resources::default().declares(&["AUTH_JWT_SECRET"]),
373                )]),
374                &lock_with_deployed(&["api"]),
375                &source(&[], &["PROBE_TOKEN"]),
376                true,
377                "default",
378            ),
379            DeployFormat::Short,
380        ));
381
382        // A supplied name goes to *every* context in the run: nothing says which
383        // contexts read a `bynk.Secrets` name. The plan lists it per context so
384        // that spread is visible rather than implied.
385        out.push_str("\n# slice 3: a supplied secret reaches every context\n");
386        out.push_str(&plan_report(
387            &derive_plan(
388                &chain_order,
389                &chain(),
390                &DeployLock::default(),
391                &source(&[("SHARED_KEY", "v")], &[]),
392                false,
393                "default",
394            ),
395            DeployFormat::Short,
396        ));
397
398        // The three classes side by side — the increment's whole surface. A
399        // reader must be able to tell the compiler's *required* knowledge
400        // (`declared`) from its *advisory* knowledge (`read`) from the user's
401        // word (`supplied`), because they fail differently.
402        out.push_str("\n# all three classes: declared (required), read (advisory), supplied\n");
403        out.push_str(&plan_report(
404            &derive_plan(
405                &names(&["api"]),
406                &project(vec![(
407                    "api",
408                    Resources::default()
409                        .declares(&["AUTH_JWT_SECRET"])
410                        .reads(&["STRIPE_KEY"]),
411                )]),
412                &DeployLock::default(),
413                &source(&[], &["PROBE_TOKEN"]),
414                false,
415                "default",
416            ),
417            DeployFormat::Short,
418        ));
419
420        out.push_str("\n# --format json\n");
421        out.push_str(&plan_report(
422            &plan_of(&chain_order, &chain(), &DeployLock::default()),
423            DeployFormat::Json,
424        ));
425
426        // A computed name: the list is not a census, and the JSON is where a CI
427        // job learns that rather than trusting a short list.
428        out.push_str("\n# --format json, a context that computes a secret name\n");
429        out.push_str(&plan_report(
430            &derive_plan(
431                &names(&["api"]),
432                &project(vec![(
433                    "api",
434                    Resources::default()
435                        .reads(&["WELL_KNOWN"])
436                        .reads_incompletely(),
437                )]),
438                &DeployLock::default(),
439                &SecretSource::default(),
440                false,
441                "default",
442            ),
443            DeployFormat::Json,
444        ));
445
446        // The JSON shape of slice 3's kinds — the surface a CI job reads to
447        // learn which names it must supply, and which the compiler already knows.
448        out.push_str("\n# --format json, with declared and supplied secrets\n");
449        out.push_str(&plan_report(
450            &derive_plan(
451                &names(&["api"]),
452                &project(vec![(
453                    "api",
454                    Resources::default().declares(&["AUTH_JWT_SECRET", "WH_SECRET"]),
455                )]),
456                &DeployLock::default(),
457                &source(&[("STRIPE_KEY", "sk_live_x")], &["PROBE_TOKEN"]),
458                false,
459                "default",
460            ),
461            DeployFormat::Json,
462        ));
463
464        // The JSON shape of slice 1's kinds — the surface a CI job reads to
465        // learn that the Durable Object namespaces are not ours to claim.
466        out.push_str("\n# --format json, with a queue and a durable object\n");
467        out.push_str(&plan_report(
468            &plan_of(
469                &names(&["jobs"]),
470                &project(vec![(
471                    "jobs",
472                    Resources::default()
473                        .consumes(&["job-intake"])
474                        .exports(&["JobLedger"]),
475                )]),
476                &DeployLock::default(),
477            ),
478            DeployFormat::Json,
479        ));
480
481        // S4b (#1967): derived KV instances. Each is its own namespace, titled
482        // `<worker>-<capability>`; the bare `KV` keeps its line as it was.
483        let cart = || {
484            project(vec![(
485                "shop-cart",
486                Resources::default()
487                    .needs_kv()
488                    .kv_instances(&["KV_PRICE_CACHE", "KV_SESSIONS"]),
489            )])
490        };
491        out.push_str("\n# S4b: the bare namespace and two derived instances, first deploy\n");
492        out.push_str(&plan_report(
493            &plan_of(&names(&["shop-cart"]), &cart(), &DeployLock::default()),
494            DeployFormat::Short,
495        ));
496
497        // A renamed capability (`Carts` → `PriceCache`) is a new binding: a
498        // create beside the reuse, and the old instance an orphan, never
499        // pruned without `--prune`'s confirmation. Under `--env staging` every
500        // title is qualified, the bare one's too (#2037); the recorded ids are
501        // reused, whatever their namespaces were titled when made.
502        out.push_str("\n# S4b: an instance renamed, under --env staging\n");
503        let mut staged = DeployLock::default();
504        staged.record_deployed("staging", "shop-cart", Some(Default::default()));
505        staged.record::<Kv>("staging", "shop-cart", "KV", KvNamespace::of("bare-id"));
506        staged.record::<Kv>(
507            "staging",
508            "shop-cart",
509            "KV_SESSIONS",
510            KvNamespace::of("sessions-id"),
511        );
512        staged.record::<Kv>(
513            "staging",
514            "shop-cart",
515            "KV_CARTS",
516            KvNamespace::of("carts-id"),
517        );
518        let cart_order = names(&["shop-cart"]);
519        let cart_resources = cart();
520        let renamed = derive_plan(
521            &cart_order,
522            &cart_resources,
523            &staged,
524            &SecretSource::default(),
525            false,
526            "staging",
527        );
528        out.push_str(&plan_report(&renamed, DeployFormat::Short));
529
530        out.push_str("\n# --format json, the same rename\n");
531        out.push_str(&plan_report(&renamed, DeployFormat::Json));
532
533        // #2028: under `--env staging` every Worker, binding target and queue
534        // is named as the push creates it, `-staging`, and so is the bare
535        // `KV`'s namespace title (#2037).
536        out.push_str("\n# --env staging: several contexts and a queue, first deploy\n");
537        let staging_resources = project(vec![
538            (
539                "commerce-orders",
540                Resources::default()
541                    .binds(&["commerce-payment"])
542                    .consumes(&["job-intake"]),
543            ),
544            ("commerce-payment", Resources::default().needs_kv()),
545        ]);
546        let staging = derive_plan(
547            &chain_order,
548            &staging_resources,
549            &DeployLock::default(),
550            &SecretSource::default(),
551            false,
552            "staging",
553        );
554        out.push_str(&plan_report(&staging, DeployFormat::Short));
555        out.push_str("\n# --format json, the same plan under --env staging\n");
556        out.push_str(&plan_report(&staging, DeployFormat::Json));
557
558        // #2037: the bare `KV`'s title, first deploy, default and staging. An
559        // account holds one namespace per title, so staging's is qualified
560        // and the default's is the title it has always had.
561        let bare = project(vec![("api", Resources::default().needs_kv())]);
562        let bare_order = names(&["api"]);
563        for environment in ["default", "staging"] {
564            out.push_str(&format!(
565                "\n# #2037: the bare namespace, first deploy, --env {environment}\n"
566            ));
567            out.push_str(&plan_report(
568                &derive_plan(
569                    &bare_order,
570                    &bare,
571                    &DeployLock::default(),
572                    &SecretSource::default(),
573                    false,
574                    environment,
575                ),
576                DeployFormat::Short,
577            ));
578        }
579
580        out.push_str("\n# S4b: a removed context's bare namespace and instance, both orphans\n");
581        out.push_str(&plan_report(
582            &plan_of(
583                &names(&["api"]),
584                &project(vec![("api", Resources::default())]),
585                &with_kv_instance(
586                    with_kv(DeployLock::default(), "gone"),
587                    "gone",
588                    "KV_SESSIONS",
589                ),
590            ),
591            DeployFormat::Short,
592        ));
593
594        // Interop I5 (#1972): Service Bindings to Workers outside the
595        // project, bound and never provisioned or ordered against.
596        out.push_str("\n# interop I5: a foreign Worker beside a project context\n");
597        let foreign = project(vec![
598            (
599                "shop-checkout",
600                Resources::default()
601                    .binds(&["shop-payment"])
602                    .foreign(&[("SERVICE_BILLING", "legacy-billing")]),
603            ),
604            ("shop-payment", Resources::default()),
605        ]);
606        let order = names(&["shop-payment", "shop-checkout"]);
607        out.push_str(&plan_report(
608            &plan_of(&order, &foreign, &DeployLock::default()),
609            DeployFormat::Short,
610        ));
611
612        bless_or_assert("deploy-plan.txt", &out);
613    }
614
615    /// #601 D4: a failure stops the run and names what did not land. The count
616    /// and the list must agree, and the context that just failed — already
617    /// reported on its own line — must not be listed again here.
618    #[test]
619    fn golden_deploy_stopped() {
620        let mut out = String::new();
621        out.push_str("# the last context failed: nothing was left to withhold\n");
622        out.push_str(&stopped_report("default", &[]));
623        out.push_str("# one context was left\n");
624        out.push_str(&stopped_report("default", &names(&["commerce-orders"])));
625        out.push_str("# several were left\n");
626        out.push_str(&stopped_report(
627            "default",
628            &names(&["commerce-orders", "commerce-shipping"]),
629        ));
630        // #2038: under `--env staging` each context is named as the plan's
631        // `order` line names it, `-staging`.
632        out.push_str("# --env staging: one context was left\n");
633        out.push_str(&stopped_report("staging", &names(&["commerce-orders"])));
634        out.push_str("# --env staging: several were left\n");
635        out.push_str(&stopped_report(
636            "staging",
637            &names(&["commerce-orders", "commerce-shipping"]),
638        ));
639        bless_or_assert("deploy-stopped.txt", &out);
640    }
641
642    /// D4 / #2038: `--context` refuses a Worker whose binding target has never
643    /// been deployed, naming both by their deployed name in the environment.
644    #[test]
645    fn golden_deploy_context_refusal() {
646        let mut out = String::new();
647        out.push_str("# one target never deployed\n");
648        out.push_str(&absent_dependencies_refusal(
649            "default",
650            "commerce-orders",
651            &names(&["commerce-payment"]),
652        ));
653        out.push_str("# two targets never deployed\n");
654        out.push_str(&absent_dependencies_refusal(
655            "default",
656            "commerce-orders",
657            &names(&["commerce-payment", "commerce-shipping"]),
658        ));
659        out.push_str("# --env staging: one target never deployed\n");
660        out.push_str(&absent_dependencies_refusal(
661            "staging",
662            "commerce-orders",
663            &names(&["commerce-payment"]),
664        ));
665        out.push_str("# --env staging: two targets never deployed\n");
666        out.push_str(&absent_dependencies_refusal(
667            "staging",
668            "commerce-orders",
669            &names(&["commerce-payment", "commerce-shipping"]),
670        ));
671        bless_or_assert("deploy-context-refusal.txt", &out);
672    }
673
674    /// #2077: `--context` refuses a callee whose new build no longer provides
675    /// what its live callers were compiled against, naming each caller, the
676    /// contract and both hashes; and warns of a caller it cannot check.
677    #[test]
678    fn golden_deploy_callee_contract_skew() {
679        fn skew(caller: &str, service: &str, expected: &str, provided: &str) -> CalleeSkew {
680            CalleeSkew {
681                caller: caller.into(),
682                dependency: "shop.payment".into(),
683                service: service.into(),
684                expected: expected.into(),
685                provided: provided.into(),
686                compat: None,
687            }
688        }
689        let one = [skew(
690            "shop-orders",
691            "authorise",
692            "febd15c2757b72e1",
693            "da0d725f3a004040",
694        )];
695        let several = [
696            skew(
697                "shop-orders",
698                "authorise",
699                "febd15c2757b72e1",
700                "da0d725f3a004040",
701            ),
702            skew("shop-refunds", "refund", "317bdd3de84d2176", "<absent>"),
703        ];
704        let mut out = String::new();
705        out.push_str("# one live caller on the old hash\n");
706        out.push_str(&callee_contract_skew_refusal(
707            "default",
708            "shop-payment",
709            &one,
710        ));
711        out.push_str("# two live callers, one service removed\n");
712        out.push_str(&callee_contract_skew_refusal(
713            "default",
714            "shop-payment",
715            &several,
716        ));
717        out.push_str("# --env staging: one live caller on the old hash\n");
718        out.push_str(&callee_contract_skew_refusal(
719            "staging",
720            "shop-payment",
721            &one,
722        ));
723        let orphaned = [skew(
724            "shop-legacy",
725            "authorise",
726            "febd15c2757b72e1",
727            "da0d725f3a004040",
728        )];
729        out.push_str("# a live caller of a context removed from the project\n");
730        out.push_str(&orphaned_caller_skew_refusal(
731            "default",
732            "shop-payment",
733            &orphaned,
734            ("npx", &|c: &str| c.to_string()),
735        ));
736        out.push_str("# --env staging: a live caller of a context removed from the project\n");
737        out.push_str(&orphaned_caller_skew_refusal(
738            "staging",
739            "shop-payment",
740            &orphaned,
741            ("npx", &|c: &str| c.to_string()),
742        ));
743        out.push_str("# a live caller recorded before expectations were\n");
744        out.push_str(&unrecorded_caller_warning(
745            "default",
746            "shop-payment",
747            "shop-orders",
748        ));
749        out.push_str("# --env staging: a live caller recorded before expectations were\n");
750        out.push_str(&unrecorded_caller_warning(
751            "staging",
752            "shop-payment",
753            "shop-orders",
754        ));
755        bless_or_assert("deploy-callee-contract-skew.txt", &out);
756    }
757
758    /// #2047: every other deploy message that names a Worker or suggests a
759    /// command, under the default environment and `--env staging`. A Worker
760    /// is named by its deployed name, and a suggested `bynk deploy` repeats
761    /// the run's `--env`.
762    #[test]
763    fn golden_deploy_env_messages() {
764        let edge = Edge {
765            caller: "commerce-orders".into(),
766            callee: "commerce-payment".into(),
767            caller_contexts: Vec::new(),
768            callee_contexts: Vec::new(),
769        };
770        let skews = vec![ContractSkew {
771            dependency: "commerce.payment".into(),
772            service: "authorise".into(),
773            expected: "aaaa".into(),
774            live: "bbbb".into(),
775            compat: None,
776        }];
777        let caller = ForeignCaller {
778            actor: "Ledger".into(),
779            binding: "LEDGER_CALL_KEY".into(),
780            worker: Some("ledger-svc".into()),
781        };
782        let rotating: BTreeMap<Edge, EdgeKey> = [(
783            edge.clone(),
784            EdgeKey::Set {
785                value: "minted-value".into(),
786                rotating: true,
787            },
788        )]
789        .into_iter()
790        .collect();
791        let mut out = String::new();
792        for environment in ["default", "staging"] {
793            let section = |out: &mut String, title: &str| {
794                out.push_str(&format!("# {title}, environment {environment}\n"));
795            };
796            section(&mut out, "contract skew refusal");
797            out.push_str(&contract_skew_refusal(
798                environment,
799                "commerce-orders",
800                &skews,
801            ));
802            section(&mut out, "edge key presence unknown");
803            out.push_str(&unknown_edge_key_notice(
804                environment,
805                "commerce-payment",
806                "BYNK_CALL_FROM_COMMERCE__ORDERS",
807                &edge,
808            ));
809            section(&mut out, "edge needs a key a --context run cannot copy");
810            out.push_str(
811                &decide_edge_key(
812                    &edge,
813                    Presence::Present,
814                    Presence::Absent,
815                    false,
816                    false,
817                    &mut || panic!("a refused edge mints nothing"),
818                    environment,
819                )
820                .expect_err("refused"),
821            );
822            out.push('\n');
823            section(&mut out, "interrupted rotation");
824            out.push_str(
825                &interrupted_rotation_hint(environment, &rotating, &names(&["commerce-payment"]))
826                    .expect("a rotation was interrupted"),
827            );
828            section(&mut out, "progress");
829            out.push_str(&deploying_notice(environment, "commerce-orders", 2, 2));
830            section(&mut out, "deployed but not recorded");
831            out.push_str(&unrecorded_deploy_failure(
832                environment,
833                "commerce-orders",
834                "bynk.deploy.lock",
835                "permission denied",
836            ));
837            section(&mut out, "foreign caller's secret may be set");
838            out.push_str(&foreign_binding_maybe_set_notice(
839                environment,
840                "commerce-orders",
841                &caller,
842            ));
843            section(&mut out, "foreign caller's binding refused");
844            out.push_str(&foreign_binding_refusal(
845                environment,
846                "commerce-orders",
847                &caller,
848                "the supplied value is empty — every call from it would be refused",
849            ));
850            section(&mut out, "foreign caller hand-off");
851            out.push_str(&foreign_hand_off(
852                environment,
853                "commerce-orders",
854                &caller,
855                "abc123",
856                "npx",
857            ));
858            section(&mut out, "unseen secret reads");
859            out.push_str(&unseen_reads_notice(environment, "commerce-orders"));
860            section(&mut out, "secret already set");
861            out.push_str(&kept_binding_notice(
862                environment,
863                "commerce-orders",
864                "API_KEY",
865            ));
866            section(&mut out, "optional read unsupplied");
867            out.push_str(&unsupplied_read_notice(
868                environment,
869                "commerce-orders",
870                "API_KEY",
871            ));
872            section(&mut out, "secret presence unknown");
873            out.push_str(&unknown_presence_notice(
874                environment,
875                "commerce-orders",
876                "AUTH_SECRET",
877            ));
878            section(&mut out, "secret put failed");
879            out.push_str(&binding_put_failure(
880                environment,
881                "commerce-orders",
882                "API_KEY",
883                "exit 1",
884            ));
885            out.push('\n');
886            section(&mut out, "declared secret missing");
887            out.push_str(&missing_binding_message(
888                environment,
889                "AUTH_SECRET",
890                Origin::Declared,
891                "commerce-orders",
892            ));
893            out.push('\n');
894        }
895        // Platform-independent by construction: the failed-push message needs
896        // a Unix `ExitStatus`, so it is pinned by
897        // `a_failed_push_names_the_deployed_worker` in provisioning.rs instead.
898        bless_or_assert("deploy-env-messages.txt", &out);
899    }
900
901    #[test]
902    fn the_stop_report_counts_only_what_is_left_and_agrees_with_its_list() {
903        // The regression: the slice reported `order[i..]`, which included the
904        // context that had just failed — so a 3-context run failing at the 2nd
905        // said "1 more context was not deployed: b, c", naming two.
906        for environment in ["default", "staging"] {
907            assert_eq!(
908                stopped_report(environment, &[]),
909                "",
910                "the failure itself is already reported"
911            );
912        }
913        for (environment, n) in ["default", "staging"]
914            .into_iter()
915            .flat_map(|environment| (1..5usize).map(move |n| (environment, n)))
916        {
917            let rest = names(&["c0", "c1", "c2", "c3"][..n]);
918            let report = stopped_report(environment, &rest);
919            let listed = report
920                .split(" not deployed: ")
921                .nth(1)
922                .and_then(|tail| tail.split(". Re-run").next())
923                .expect("the list sits between the count and the remedy");
924            assert_eq!(
925                listed.split(", ").count(),
926                n,
927                "the list names every withheld context: {report}"
928            );
929            let count = if n == 1 {
930                "1 more context was".to_string()
931            } else {
932                format!("{n} further contexts were")
933            };
934            assert!(
935                report.contains(&count),
936                "the count states the number it lists: {report}"
937            );
938        }
939    }
940}