Skip to main content

bynk_emit/emitter/
secrets.rs

1//! `bynk-secrets.json` generation per Worker (v0.172, ADR 0195).
2//!
3//! The **declared** secret names a context's handlers will read from `env` at
4//! runtime — an `actor`'s `auth = Bearer(secret = "…")` / `Signature(secret =
5//! "…")`, including the members of a multi-actor sum. `deploy` reads this file
6//! to know which secrets it must see set before it pushes.
7//!
8//! The file carries **two kinds of knowledge, which are not equally strong**
9//! (ADR 0196):
10//!
11//! - `declared` — an `actor`'s auth secret. A literal fixed at parse time,
12//!   required at compile time, and **fail-closed**: unset, the Worker answers
13//!   401 to every request. `deploy` refuses to ship without a value.
14//! - `read` — a literal `bynk.Secrets` name (`Secrets.get("X")`). `get` returns
15//!   `Option`, so absence is a legitimate handled outcome — these are
16//!   **advisory**, and `deploy` warns rather than failing.
17//!
18//! And `read_complete`, which is the honesty. `Secrets.get` takes an ordinary
19//! `String` expression, so a computed name is invisible to any pass: where one
20//! is seen, the context warns (`bynk.secrets.computed_name`) and this flag goes
21//! false. So does composing an adapter provider `given` `bynk`'s `Secrets`
22//! (#1976): its binding is TypeScript, and reads names no pass can see.
23//! `declared` is a **floor, not a census** (ADR 0195 D2); `read` is a census
24//! only while `read_complete` holds, and says so when it does not.
25//!
26//! Why a file rather than an API: the driver has two compile paths, and under a
27//! `bynkc` override the compiler is a child process handing back an exit status
28//! — there is no in-memory model to consult. A name the compiler knows must
29//! reach the driver in the build output, or not at all (ADR 0195 D5).
30//!
31//! P5.5 (`design/tracks/semantics-in-the-checker.md` §6, §9): the checking
32//! half — `SecretReads`, the `Secrets.get` AST walk, and the
33//! `bynk.secrets.computed_name` diagnostic itself — moved to
34//! `bynk_check::secrets`, a real gap this track's settling pass had not
35//! scoped (see that module's own doc). What stays here is emission-only:
36//! rendering the manifest `bynk deploy` reads, which is not this crate's
37//! business to ask `bynk-check` to do.
38
39use std::collections::BTreeSet;
40
41use bynk_project::json_string;
42
43use bynk_check::actors::SumMemberSeam;
44use bynk_check::secrets::SecretReads;
45
46use bynk_check::symbols::UnitTable;
47
48/// The file the driver reads, beside each Worker's `wrangler.toml`.
49pub const SECRETS_MANIFEST: &str = "bynk-secrets.json";
50
51/// The manifest schema version. Bumped only by a breaking shape change; the
52/// driver refuses a version it does not know rather than guessing, as the
53/// deploy ledger does.
54///
55/// **2** (v0.173, ADR 0196) added `read` and `read_complete`. The bump is
56/// deliberate rather than a default-on-absence read: a v1 manifest carries no
57/// evidence either way about computed names, and defaulting `read_complete` to
58/// `true` for it would be the manifest's one claim that could be silently wrong.
59const MANIFEST_VERSION: u32 = 2;
60
61/// Every secret name this context's handlers will read from `env`.
62///
63/// Enumerated over exactly the handlers the entry emitter lowers seams for
64/// (`table.services`, which is where a `from websocket` service lives too), and
65/// resolved with exactly the same `bynk_check::actors` functions — so the
66/// manifest cannot describe a Worker other than the one emitted beside it. An
67/// actor that is declared but named by no handler's `by` clause resolves no
68/// seam and contributes nothing: the Worker never reads it.
69///
70/// `Oidc` names no secret — its trust root is the provider's published JWKS, not
71/// a shared value — and a sum's `None` member (a catch-all such as `Visitor`)
72/// verifies nothing. Both are skipped rather than defaulted: inventing a name
73/// for them would ask the user to set a secret that nothing reads.
74///
75/// I3 (#1971): a `Foreign` actor's secret is **not** declared here, on purpose.
76/// A declared secret is the user's to supply, and `deploy` prompts for one it
77/// lacks; a foreign caller's is minted by `deploy` and handed to the foreign
78/// Worker's operator ([`foreign_callers`]). None of the resolvers above match a
79/// `Foreign` actor, and a test pins that.
80pub(crate) fn declared_secrets(table: &UnitTable) -> BTreeSet<String> {
81    let mut names = BTreeSet::new();
82    for handler in table.services.values().flat_map(|s| s.handlers.iter()) {
83        if let Some(seam) = bynk_check::actors::bearer_seam_for(handler, &table.actors) {
84            names.insert(seam.secret);
85        }
86        if let Some(seam) = bynk_check::actors::signature_seam_for(handler, &table.actors) {
87            names.insert(seam.secret);
88        }
89        for member in bynk_check::actors::sum_members_for(handler, &table.actors)
90            .into_iter()
91            .flatten()
92        {
93            match member.seam {
94                SumMemberSeam::Bearer { secret, .. } => {
95                    names.insert(secret);
96                }
97                SumMemberSeam::Signature(seam) => {
98                    names.insert(seam.secret);
99                }
100                SumMemberSeam::None => {}
101            }
102        }
103    }
104    names
105}
106
107/// #3386: the `SignedCookie` actors this context's handlers are guarded by or issue for, each
108/// with the env binding of its signing key, by actor name. Unlike an `actor`'s auth secret, a
109/// session key is **not** declared for the user to supply: `deploy` mints it when it is unset,
110/// and `bynk dev` uses a per-run one. (The optional `previous` key is the operator's, so it is
111/// not listed.) Every `SignedCookie` actor of the context counts, so a context that only issues
112/// the cookie (a login service) still gets its key.
113pub(crate) fn session_keys(table: &UnitTable) -> Vec<(String, String)> {
114    let mut keys: Vec<(String, String)> = table
115        .actors
116        .values()
117        .filter_map(|a| bynk_check::actors::signed_cookie_seam_of(a, None))
118        .map(|s| (s.actor, s.secret))
119        .collect();
120    keys.sort();
121    keys.dedup();
122    keys
123}
124
125/// I3 (#1971): the foreign callers this context's `on call` handlers admit, by
126/// actor name, each with the secret its calls verify under and the foreign
127/// Worker's name when declared. `deploy` mints each secret, sets it on this
128/// Worker, and prints the command that hands it to the foreign Worker.
129pub(crate) fn foreign_callers(table: &UnitTable) -> Vec<bynk_check::actors::ForeignCaller> {
130    let mut callers: Vec<bynk_check::actors::ForeignCaller> = Vec::new();
131    for handler in table.services.values().flat_map(|s| s.handlers.iter()) {
132        for f in bynk_check::actors::call_admission_for(handler, &table.actors)
133            .map(|a| a.foreign)
134            .unwrap_or_default()
135        {
136            if !callers.iter().any(|g| g.actor == f.actor) {
137                callers.push(f);
138            }
139        }
140    }
141    callers.sort_by(|a, b| a.actor.cmp(&b.actor));
142    callers
143}
144
145/// The reads half of what a Worker knows about its own `bynk.Secrets` use —
146/// `declared_secrets`'s counterpart, read from the AST rather than derived
147/// from actor bindings. The walk itself, its `bynk.secrets.computed_name`
148/// diagnostic, and the `reads_secrets_of_bynk` capability-resolution guard
149/// live in `bynk_check::secrets` (P5.5); the Worker-wide closure — handlers
150/// plus every provider the composition root builds, and the adapter-binding
151/// case no pass can see (#1976) — is [`bynk_check::secrets::worker_secret_reads`].
152/// `run_checks` raises the warnings, via
153/// `bynk_check::project_model::phase_secrets_computed_name`, per file.
154pub fn secret_reads(
155    context: &str,
156    unit_tables: &std::collections::HashMap<String, UnitTable>,
157    unit_consumes: &std::collections::HashMap<String, Vec<String>>,
158    unit_consumes_aliases: &std::collections::HashMap<
159        String,
160        std::collections::HashMap<String, String>,
161    >,
162    unit_flattened: &std::collections::HashMap<String, std::collections::HashMap<String, String>>,
163) -> SecretReads {
164    bynk_check::secrets::worker_secret_reads(
165        context,
166        unit_tables,
167        unit_consumes,
168        unit_consumes_aliases,
169        unit_flattened,
170    )
171}
172
173/// Render the manifest for a context, or `None` when there is nothing to say.
174///
175/// Emitted when **anything** is known ([DECISION E]): a declared secret, a read
176/// name, or the fact that a name is computed. Slice 3's rule — emit only for a
177/// non-empty `declared` — would have stayed silent for a context that reads
178/// secrets but declares none, which is exactly the context this file now exists
179/// to describe.
180pub fn emit_secrets_manifest(table: &UnitTable, reads: &SecretReads) -> Option<String> {
181    SecretsParts::of(table, reads).render()
182}
183
184/// What one context says about its secrets, before it is rendered, so a
185/// `[deploy.workers.<key>]` group's members (one Worker, one file) can be merged
186/// (#3562).
187#[derive(Debug, Clone, Default)]
188pub struct SecretsParts {
189    declared: BTreeSet<String>,
190    names: BTreeSet<String>,
191    /// Whether `names` is every name read (a vacuous `true` for none).
192    complete: bool,
193    foreign: Vec<bynk_check::actors::ForeignCaller>,
194    session: Vec<(String, String)>,
195}
196
197impl SecretsParts {
198    pub fn of(table: &UnitTable, reads: &SecretReads) -> Self {
199        Self {
200            declared: declared_secrets(table),
201            names: reads.names.clone(),
202            complete: reads.complete,
203            foreign: foreign_callers(table),
204            session: session_keys(table),
205        }
206    }
207
208    /// One Worker's secrets: the union of its members'. The names are read from
209    /// one `env`, so a name any member reads is read by the Worker, and the census
210    /// is complete only if every member's is.
211    pub fn merged(parts: impl IntoIterator<Item = Self>) -> Self {
212        let mut all = Self {
213            complete: true,
214            ..Self::default()
215        };
216        for part in parts {
217            all.declared.extend(part.declared);
218            all.names.extend(part.names);
219            all.complete &= part.complete;
220            for f in part.foreign {
221                if !all.foreign.contains(&f) {
222                    all.foreign.push(f);
223                }
224            }
225            all.session.extend(part.session);
226        }
227        all.session.sort();
228        all.session.dedup();
229        all
230    }
231
232    pub fn render(&self) -> Option<String> {
233        render(
234            &self.declared,
235            &SecretReads {
236                names: self.names.clone(),
237                complete: self.complete,
238            },
239            &self.foreign,
240            &self.session,
241        )
242    }
243}
244
245/// Render a resolved name set. Split from the derivation so the file's shape is
246/// tested without building a project model.
247///
248/// Absent rather than empty: a project with no declared secret must not grow a
249/// file into every worker directory for a feature it does not use — and "no
250/// file" is the same answer as "an empty list" to a driver that must tolerate a
251/// build tree from a compiler predating this file anyway.
252fn render(
253    declared: &BTreeSet<String>,
254    reads: &SecretReads,
255    foreign: &[bynk_check::actors::ForeignCaller],
256    session: &[(String, String)],
257) -> Option<String> {
258    // `complete` is the third thing worth saying: a context that reads one
259    // computed name and nothing else knows something — that it does not know —
260    // and the file has to carry it or the driver cannot.
261    if declared.is_empty()
262        && reads.names.is_empty()
263        && reads.complete
264        && foreign.is_empty()
265        && session.is_empty()
266    {
267        return None;
268    }
269    // #3386: `session` likewise only when there is one, additive within version 2.
270    let session = if session.is_empty() {
271        String::new()
272    } else {
273        let rendered: Vec<String> = session
274            .iter()
275            .map(|(actor, secret)| {
276                format!(
277                    "    {{ \"actor\": {}, \"secret\": {} }}",
278                    json_string(actor),
279                    json_string(secret)
280                )
281            })
282            .collect();
283        format!(",\n  \"session\": [\n{}\n  ]", rendered.join(",\n"))
284    };
285    // I3 (#1971): `foreign` only when there is one. It is additive within
286    // version 2 rather than a version 3: a manifest without it says, truly,
287    // that the context admits no foreign caller, so an older file reads the
288    // same as before and every existing manifest stays byte-identical.
289    let foreign = if foreign.is_empty() {
290        String::new()
291    } else {
292        let rendered: Vec<String> = foreign
293            .iter()
294            .map(|f| {
295                let worker = f
296                    .worker
297                    .as_ref()
298                    .map(|w| format!(", \"worker\": {}", json_string(w)))
299                    .unwrap_or_default();
300                format!(
301                    "    {{ \"actor\": {}, \"secret\": {}{worker} }}",
302                    json_string(&f.actor),
303                    json_string(&f.secret)
304                )
305            })
306            .collect();
307        format!(",\n  \"foreign\": [\n{}\n  ]", rendered.join(",\n"))
308    };
309    // Hand-rendered rather than via serde: this crate does not depend on
310    // serde_json, and the shape is a handful of fields.
311    Some(format!(
312        "{{\n  \"version\": {MANIFEST_VERSION},\n  \"declared\": {},\n  \"read\": {},\n  \"read_complete\": {}{foreign}{session}\n}}\n",
313        json_array(declared),
314        json_array(&reads.names),
315        reads.complete,
316    ))
317}
318
319/// A JSON array of names, one per line, or `[]`.
320fn json_array(names: &BTreeSet<String>) -> String {
321    if names.is_empty() {
322        return "[]".to_string();
323    }
324    let rendered: Vec<String> = names
325        .iter()
326        .map(|n| format!("    {}", json_string(n)))
327        .collect();
328    format!("[\n{}\n  ]", rendered.join(",\n"))
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    fn set(names: &[&str]) -> BTreeSet<String> {
336        names.iter().map(|n| n.to_string()).collect()
337    }
338
339    #[test]
340    fn a_session_key_is_listed_beside_the_declared_secrets_not_among_them() {
341        let session = [("User".to_string(), "SESSION_KEY".to_string())];
342        let text =
343            render(&set(&[]), &reads(&[], true), &[], &session).expect("a session key renders");
344        assert_eq!(
345            text,
346            "{\n  \"version\": 2,\n  \"declared\": [],\n  \"read\": [],\n  \"read_complete\": true,\n  \"session\": [\n    { \"actor\": \"User\", \"secret\": \"SESSION_KEY\" }\n  ]\n}\n"
347        );
348        // Declared secrets are the operator's to supply; the session key is not one of them.
349        assert!(!text.contains("\"declared\": [\n"));
350    }
351
352    #[test]
353    fn a_name_is_escaped_as_a_json_string() {
354        assert_eq!(json_string("AUTH_JWT_SECRET"), "\"AUTH_JWT_SECRET\"");
355        // A secret name is a Bynk string literal, so it is arbitrary text; the
356        // manifest must stay parseable rather than usually-parseable.
357        assert_eq!(json_string("a\"b"), "\"a\\\"b\"");
358        assert_eq!(json_string("a\\b"), "\"a\\\\b\"");
359        assert_eq!(json_string("a\nb"), "\"a\\nb\"");
360        assert_eq!(json_string("a\u{1}b"), "\"a\\u0001b\"");
361    }
362
363    fn reads(names: &[&str], complete: bool) -> SecretReads {
364        SecretReads {
365            names: set(names),
366            complete,
367        }
368    }
369
370    /// [DECISION E]: the file appears when **anything** is known, and only then.
371    #[test]
372    fn a_manifest_appears_when_anything_is_known_and_not_otherwise() {
373        // Nothing at all — no file. A project with no secrets must not grow one
374        // into every worker directory.
375        assert_eq!(render(&set(&[]), &reads(&[], true), &[], &[]), None);
376
377        // A read with no declared secret is exactly the context slice 3's rule
378        // would have stayed silent about — and exactly the one worth describing.
379        assert!(render(&set(&[]), &reads(&["API_KEY"], true), &[], &[]).is_some());
380
381        // Knowing that you *don't* know is knowledge too: a context whose only
382        // secret is computed still emits, or the driver cannot say its list is
383        // incomplete.
384        assert!(render(&set(&[]), &reads(&[], false), &[], &[]).is_some());
385    }
386
387    /// The committed shape, byte for byte — it is a file a reviewer reads in a
388    /// fixture diff and a driver parses. Asserted here rather than round-tripped
389    /// through a parser because this crate deliberately carries three
390    /// dependencies and `serde_json` is not among them; that the bytes *parse*
391    /// is asserted driver-side, where the reader lives.
392    #[test]
393    fn the_manifest_is_sorted_and_pinned() {
394        // A `BTreeSet` orders the names, so the file is byte-stable for a given
395        // context rather than dependent on handler iteration order.
396        assert_eq!(
397            render(
398                &set(&["B_SECRET", "A_SECRET"]),
399                &reads(&["R"], true),
400                &[],
401                &[]
402            )
403            .expect("a non-empty set renders"),
404            "{\n  \"version\": 2,\n  \"declared\": [\n    \"A_SECRET\",\n    \"B_SECRET\"\n  ],\n  \
405             \"read\": [\n    \"R\"\n  ],\n  \"read_complete\": true\n}\n",
406        );
407        // The empty-list and false-flag shapes, which the fixtures also carry.
408        assert_eq!(
409            render(&set(&["ONLY"]), &reads(&[], false), &[], &[]).expect("renders"),
410            "{\n  \"version\": 2,\n  \"declared\": [\n    \"ONLY\"\n  ],\n  \
411             \"read\": [],\n  \"read_complete\": false\n}\n",
412        );
413    }
414
415    /// I3 (#1971): foreign callers, and only foreign callers, make a file, with
416    /// the worker named where it was declared.
417    #[test]
418    fn foreign_callers_are_listed_apart_from_declared_secrets() {
419        let foreign = vec![
420            bynk_check::actors::ForeignCaller {
421                actor: "Ledger".into(),
422                secret: "LEDGER_CALL_KEY".into(),
423                worker: Some("ledger-svc".into()),
424            },
425            bynk_check::actors::ForeignCaller {
426                actor: "Legacy".into(),
427                secret: "LEGACY_CALL_KEY".into(),
428                worker: None,
429            },
430        ];
431        assert_eq!(
432            render(&set(&[]), &reads(&[], true), &foreign, &[]).expect("a foreign caller renders"),
433            "{\n  \"version\": 2,\n  \"declared\": [],\n  \"read\": [],\n  \"read_complete\": true,\n  \
434             \"foreign\": [\n    { \"actor\": \"Ledger\", \"secret\": \"LEDGER_CALL_KEY\", \"worker\": \"ledger-svc\" },\n    \
435             { \"actor\": \"Legacy\", \"secret\": \"LEGACY_CALL_KEY\" }\n  ]\n}\n",
436        );
437    }
438
439    /// #3562: a group's members share one Worker and one `env`, so its manifest
440    /// is the union of theirs, and its census is complete only if every member's is.
441    #[test]
442    fn a_groups_secrets_are_the_union_of_its_members() {
443        let part = |declared: &[&str], read: &[&str], complete: bool| SecretsParts {
444            declared: declared.iter().map(|s| s.to_string()).collect(),
445            names: read.iter().map(|s| s.to_string()).collect(),
446            complete,
447            foreign: Vec::new(),
448            session: Vec::new(),
449        };
450        let merged =
451            SecretsParts::merged([part(&["A"], &["x"], true), part(&["B"], &["y", "x"], true)])
452                .render()
453                .unwrap();
454        assert!(
455            merged.contains("\"A\"") && merged.contains("\"B\""),
456            "{merged}"
457        );
458        assert!(merged.contains("\"read_complete\": true"), "{merged}");
459        let incomplete = SecretsParts::merged([part(&[], &["x"], true), part(&[], &[], false)])
460            .render()
461            .unwrap();
462        assert!(
463            incomplete.contains("\"read_complete\": false"),
464            "{incomplete}"
465        );
466    }
467}