Skip to main content

bynk/
token.rs

1//! `bynk token` (#2869): mint a credential for the project's own `Bearer`
2//! actor, for calling a guarded route by hand — `curl` under `bynk dev`, or a
3//! smoke test against a deployment.
4//!
5//! The actor declares everything a minter needs: `auth = Bearer(secret =
6//! "<ENV>")`, HS256, and `sub` as the identity. This signs the token exactly as
7//! the emitted verifier (`bynk-emit/src/emitter/runtime/auth.ts`) and the test
8//! runtime's signer (`runtime/src/testing/jwt_signer.ts`) do — the same header, the
9//! same `sub`/`exp` claims, the same unpadded base64url — so the actor's seam
10//! accepts it. It is a different command from `bynk org token mint`, which
11//! mints a registry publish token.
12//!
13//! The secret is read from the environment, under the name the actor declares,
14//! and nowhere else: it is never an argument (it would show in a process
15//! listing), and it is never printed or put in an error. Only the token goes to
16//! stdout, so `$(bynk token Reader --sub me)` works.
17
18use bynk_driver::emsg;
19use std::collections::BTreeMap;
20use std::path::Path;
21use std::process::ExitCode;
22use std::time::{SystemTime, UNIX_EPOCH};
23
24use bynk_check::actors::Scheme;
25use bynk_syntax::ast::{ActorDecl, CommonsItem, SourceUnit, TypeDecl, TypeRef};
26
27/// The default lifetime, in seconds: short, so a hand-minted token is not a
28/// long-lived credential by accident.
29pub const DEFAULT_LIFETIME_SECS: u64 = 3600;
30/// The longest lifetime (and the furthest `--not-before`) `bynk token` signs.
31pub const MAX_LIFETIME_SECS: u64 = 365 * 86_400;
32/// How far in the past `--expired` puts `exp`. The emitted verifier allows no
33/// clock skew, but a deployment's clock may differ from this machine's, so the
34/// token is expired by a margin no reasonable skew closes.
35pub const EXPIRED_BY_SECS: u64 = 3600;
36
37/// What the user asked for, as the CLI parsed it.
38#[derive(Debug, Default)]
39pub struct Request<'a> {
40    pub actor: Option<&'a str>,
41    pub sub: Option<&'a str>,
42    pub lifetime: Option<&'a str>,
43    pub expired: bool,
44    pub not_before: Option<&'a str>,
45    /// `--claim name[=value]`, as written.
46    pub claims: &'a [String],
47}
48
49/// Claims `bynk token` owns: the identity and the time claims.
50const RESERVED_CLAIMS: &[&str] = &["sub", "iat", "exp", "nbf", "iss", "aud"];
51
52/// `bynk token`: list the project's Bearer actors, or mint one's token.
53pub fn run(root: &Path, req: &Request) -> ExitCode {
54    match run_inner(root, req) {
55        Ok(out) => {
56            println!("{out}");
57            ExitCode::SUCCESS
58        }
59        Err(e) => {
60            emsg!("bynk: error: {e}");
61            ExitCode::FAILURE
62        }
63    }
64}
65
66fn run_inner(root: &Path, req: &Request) -> Result<String, String> {
67    // Reject a bad lifetime before the (slower) project analysis.
68    let lifetime = match req.lifetime {
69        Some(s) => parse_duration(s, "--lifetime")?,
70        None => DEFAULT_LIFETIME_SECS,
71    };
72    let not_before = req
73        .not_before
74        .map(|s| parse_duration(s, "--not-before"))
75        .transpose()?;
76    let extra = parse_claims(req.claims)?;
77
78    let analysis = crate::openapi::analyse(root);
79    let errors = crate::openapi::errors_of(&analysis);
80    if !errors.is_empty() {
81        let mut msg = String::from("the project does not check; fix these first:");
82        for e in &errors {
83            msg.push_str("\n  ");
84            msg.push_str(e);
85        }
86        return Err(msg);
87    }
88    let actors = collect_actors(root, &analysis);
89
90    let Some(name) = req.actor else {
91        return Ok(list(&actors));
92    };
93    let found = resolve(&actors, name)?;
94    // A refinement signs with its base actor's secret and identity.
95    let signer = match &found.base {
96        Some(base) => base,
97        None => found,
98    };
99    let env_var = bearer_env_var(found, signer)?;
100    let sub = req
101        .sub
102        .ok_or_else(|| format!("`--sub <ID>` is required to mint a token for `{name}`"))?;
103    validate_sub(signer, sub)?;
104
105    let mut claims = refinement_claims(found)?;
106
107    let secret = match std::env::var(&env_var) {
108        Ok(v) if !v.is_empty() => v,
109        _ => {
110            return Err(format!(
111                "`{env_var}` is not set (or is empty): it is the secret the `{name}` actor \
112                 declares, and `bynk token` reads it from the environment — never an argument"
113            ));
114        }
115    };
116
117    let now = unix_now()?;
118    let (nbf, exp) = if req.expired {
119        (None, now.saturating_sub(EXPIRED_BY_SECS))
120    } else {
121        let nbf = not_before.map(|d| now + d);
122        (nbf, nbf.unwrap_or(now) + lifetime)
123    };
124    // The refinement's witness claims, then `--claim`s, which win: a hand-given
125    // claim can withhold or change one to test the seam's 403.
126    for (name, value) in extra {
127        claims.retain(|(n, _)| *n != name);
128        claims.push((name, value));
129    }
130    Ok(mint_with(&secret, sub, nbf, exp, &claims))
131}
132
133/// `name` (the claim `true`, as the `system` harness signs a present claim) or
134/// `name=value` (a string).
135fn parse_claims(raw: &[String]) -> Result<Vec<(String, serde_json::Value)>, String> {
136    let mut out: Vec<(String, serde_json::Value)> = Vec::new();
137    for r in raw {
138        let (name, value) = match r.split_once('=') {
139            Some((n, v)) => (n, serde_json::Value::String(v.to_string())),
140            None => (r.as_str(), serde_json::Value::Bool(true)),
141        };
142        if name.is_empty() {
143            return Err(format!(
144                "`--claim {r}` names no claim: write `--claim name` or `--claim name=value`"
145            ));
146        }
147        if RESERVED_CLAIMS.contains(&name) {
148            return Err(format!(
149                "`--claim {name}` is reserved: `bynk token` signs `sub`, `iat`, `exp`, `nbf`, \
150                 `iss` and `aud` itself (use `--sub`, `--lifetime`, `--expired` or \
151                 `--not-before`)"
152            ));
153        }
154        if out.iter().any(|(n, _)| n == name) {
155            return Err(format!("`--claim {name}` is given more than once"));
156        }
157        out.push((name.to_string(), value));
158    }
159    Ok(out)
160}
161
162/// The claims a refinement actor's predicate needs, as the `system` test
163/// harness signs them (`bynk_check::actors::claim_witness`); none for a plain
164/// actor.
165fn refinement_claims(f: &Found) -> Result<Vec<(String, serde_json::Value)>, String> {
166    use bynk_check::actors::WitnessValue;
167    let Some(r) = &f.decl.refinement else {
168        return Ok(Vec::new());
169    };
170    let name = &f.decl.name.name;
171    let pred = bynk_check::actors::parse_claim_predicate(&r.predicate).map_err(|_| {
172        format!(
173            "`{name}`'s predicate uses more than `hasClaim`, `claimEquals`, `&&`, `||` and `!`, \
174             so `bynk token` cannot tell which claims satisfy it; mint with the base actor `{}` \
175             and pass the claims with `--claim`",
176            r.base.name
177        )
178    })?;
179    let witness = bynk_check::actors::claim_witness(&pred).ok_or_else(|| {
180        format!("no set of claims satisfies `{name}`'s predicate, so no token can pass its seam")
181    })?;
182    if let Some((n, _)) = witness
183        .iter()
184        .find(|(n, _)| RESERVED_CLAIMS.contains(&n.as_str()))
185    {
186        return Err(format!(
187            "`{name}`'s predicate needs the claim `{n}`, which `bynk token` signs itself (from \
188             `--sub` and the time flags), so it cannot carry the value the predicate asks for"
189        ));
190    }
191    Ok(witness
192        .into_iter()
193        .map(|(n, v)| {
194            let v = match v {
195                WitnessValue::True => serde_json::Value::Bool(true),
196                WitnessValue::Str(s) => serde_json::Value::String(s),
197            };
198            (n, v)
199        })
200        .collect())
201}
202
203// ---------------------------------------------------------------------
204// The project's actors
205// ---------------------------------------------------------------------
206
207/// One declared actor, with what resolving its identity type needs.
208struct Found {
209    unit: String,
210    decl: ActorDecl,
211    /// The types visible to the actor's unit, by name.
212    types: BTreeMap<String, TypeDecl>,
213    /// The base actor, for a refinement (`actor Admin = User where …`).
214    base: Option<Box<Found>>,
215}
216
217/// `unit_sources` paths are project-relative, so they resolve against `root`.
218fn collect_actors(root: &Path, analysis: &bynk_ide::ProjectDiagnostics) -> Vec<Found> {
219    // Every unit's own items: actors, and types for a commons-declared identity.
220    let mut own: BTreeMap<String, (Vec<ActorDecl>, BTreeMap<String, TypeDecl>)> = BTreeMap::new();
221    for (unit, paths) in &analysis.unit_sources {
222        for path in paths {
223            let Ok(src) = std::fs::read_to_string(root.join(path)) else {
224                continue;
225            };
226            let Ok(tokens) = bynk_syntax::lexer::tokenize(&src) else {
227                continue;
228            };
229            let Ok(parsed) = bynk_syntax::parser::parse_unit(&tokens, &src) else {
230                continue;
231            };
232            let items = match parsed {
233                SourceUnit::Context(c) => c.items,
234                SourceUnit::Commons(c) => c.items,
235                _ => continue,
236            };
237            let entry = own.entry(unit.clone()).or_default();
238            for item in items {
239                match item {
240                    CommonsItem::Actor(a) => entry.0.push(a),
241                    CommonsItem::Type(t) => {
242                        entry.1.insert(t.name.name.clone(), t);
243                    }
244                    _ => {}
245                }
246            }
247        }
248    }
249    let mut out = Vec::new();
250    for (unit, (actors, own_types)) in &own {
251        // The unit's combined view (its own, `uses`d and consumed types) when
252        // the analysis has one; its own declarations otherwise.
253        let mut types: BTreeMap<String, TypeDecl> = own_types.clone();
254        if let Some(info) = analysis.boundary_info.get(unit) {
255            for (n, t) in &info.types {
256                types.entry(n.clone()).or_insert_with(|| (**t).clone());
257            }
258        }
259        for a in actors {
260            let base = a.refinement.as_ref().and_then(|r| {
261                let b = actors.iter().find(|b| b.name.name == r.base.name)?;
262                Some(Box::new(Found {
263                    unit: unit.clone(),
264                    decl: b.clone(),
265                    types: types.clone(),
266                    base: None,
267                }))
268            });
269            out.push(Found {
270                unit: unit.clone(),
271                decl: a.clone(),
272                types: types.clone(),
273                base,
274            });
275        }
276    }
277    out.sort_by(|a, b| (&a.unit, &a.decl.name.name).cmp(&(&b.unit, &b.decl.name.name)));
278    out
279}
280
281fn scheme_of(a: &ActorDecl) -> Option<Scheme> {
282    Scheme::from_name(a.auth.as_ref()?.name.as_str())
283}
284
285fn qualified(f: &Found) -> String {
286    format!("{}.{}", f.unit, f.decl.name.name)
287}
288
289/// The Bearer actors, one per line with the secret each reads. Names only: no
290/// secret value is ever read here.
291fn list(actors: &[Found]) -> String {
292    let rows: Vec<(String, String)> = actors
293        .iter()
294        .filter(|f| f.base.is_none() && scheme_of(&f.decl) == Some(Scheme::Bearer))
295        .filter_map(|f| {
296            let var = f.decl.scheme_arg("secret")?.value.as_str()?.to_string();
297            Some((qualified(f), var))
298        })
299        .collect();
300    if rows.is_empty() {
301        return "no Bearer actors in this project".to_string();
302    }
303    let width = rows.iter().map(|(a, _)| a.len()).max().unwrap_or(0);
304    let mut out = String::from("Bearer actors (mint with `bynk token <ACTOR> --sub <ID>`):");
305    for (actor, var) in rows {
306        out.push_str(&format!("\n  {actor:<width$}  reads ${var}"));
307    }
308    out
309}
310
311/// The actor `name` names — `Actor` or `unit.Actor` — or why it names none.
312fn resolve<'a>(actors: &'a [Found], name: &str) -> Result<&'a Found, String> {
313    let hits: Vec<&Found> = actors
314        .iter()
315        .filter(|f| f.decl.name.name == name || qualified(f) == name)
316        .collect();
317    match hits.as_slice() {
318        [one] => Ok(one),
319        [] => {
320            let known: Vec<String> = actors.iter().map(|f| f.decl.name.name.clone()).collect();
321            Err(if known.is_empty() {
322                format!("no actor `{name}`: the project declares no actors")
323            } else {
324                format!(
325                    "no actor `{name}`; the project declares {}",
326                    known.join(", ")
327                )
328            })
329        }
330        many => Err(format!(
331            "`{name}` is declared in more than one context; name one of {}",
332            many.iter()
333                .map(|f| qualified(f))
334                .collect::<Vec<_>>()
335                .join(", ")
336        )),
337    }
338}
339
340/// The env var the secret of `f` (the actor itself, or a refinement's base) is
341/// read from, or why `requested` is not mintable.
342fn bearer_env_var(requested: &Found, f: &Found) -> Result<String, String> {
343    let name = &f.decl.name.name;
344    if f.decl.refinement.is_some() {
345        return Err(format!(
346            "`{}` refines `{name}`, itself a refinement: `bynk token` follows one level only. \
347             Mint with the base actor and pass the claims with `--claim`",
348            requested.decl.name.name
349        ));
350    }
351    match scheme_of(&f.decl) {
352        Some(Scheme::Bearer) => f
353            .decl
354            .scheme_arg("secret")
355            .and_then(|a| a.value.as_str())
356            .map(str::to_string)
357            .ok_or_else(|| format!("`{name}` names no signing secret")),
358        Some(Scheme::Signature) => Err(format!(
359            "`{name}` is a `Signature` actor, which `bynk token` does not support: it \
360             authenticates a request by an HMAC over that request's body, so there is no \
361             standalone credential to mint — the signature depends on the body being sent"
362        )),
363        Some(Scheme::Oidc) => Err(format!(
364            "`{name}` is an `Oidc` actor, which `bynk token` does not support: its tokens are \
365             minted by the identity provider and signed with the provider's private key, which \
366             the project does not hold"
367        )),
368        Some(other) => Err(format!(
369            "`{name}` uses `auth = {}`, which `bynk token` does not support: it mints \
370             credentials for `Bearer` actors only",
371            other.as_str()
372        )),
373        None => Err(format!(
374            "`{name}` declares no `auth` scheme: `bynk token` mints credentials for `Bearer` \
375             actors only"
376        )),
377    }
378}
379
380/// `--sub` must be a value the actor's identity type admits — the emitted seam
381/// answers `401` to a `sub` that fails the refinement — and non-empty, which the
382/// verifier requires of any `sub`.
383fn validate_sub(f: &Found, sub: &str) -> Result<(), String> {
384    let name = &f.decl.name.name;
385    if sub.is_empty() {
386        return Err(format!(
387            "`--sub` is empty: the verifier refuses a token with no `sub`, so no `{name}` seam \
388             would accept it"
389        ));
390    }
391    let Some(TypeRef::Named(id)) = &f.decl.identity else {
392        return Ok(());
393    };
394    let Some(decl) = f.types.get(&id.name) else {
395        return Ok(());
396    };
397    if let Some(pred) = bynk_check::checker::string_refinement_violation(decl, sub) {
398        return Err(format!(
399            "`--sub {sub:?}` is not a valid `{}` (the `{name}` actor's identity): it fails \
400             `{}`, so the seam would answer 401",
401            id.name,
402            pred.name()
403        ));
404    }
405    Ok(())
406}
407
408// ---------------------------------------------------------------------
409// Durations
410// ---------------------------------------------------------------------
411
412/// `30s`, `15m`, `1h`, `30d`: a positive whole number and a unit, at most a year.
413fn parse_duration(s: &str, flag: &str) -> Result<u64, String> {
414    let bad = || {
415        format!(
416            "{flag} `{s}` is not a duration: write a whole number and a unit, like `90s`, `15m`, \
417             `1h` or `30d`"
418        )
419    };
420    let split = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(bad)?;
421    let (digits, unit) = s.split_at(split);
422    let n: u64 = digits.parse().map_err(|_| bad())?;
423    let mult = match unit {
424        "s" => 1,
425        "m" => 60,
426        "h" => 3600,
427        "d" => 86_400,
428        _ => return Err(bad()),
429    };
430    let secs = n.checked_mul(mult).ok_or_else(bad)?;
431    if secs == 0 {
432        return Err(format!("{flag} `{s}` must be longer than zero"));
433    }
434    if secs > MAX_LIFETIME_SECS {
435        return Err(format!(
436            "{flag} `{s}` is longer than the 365 days `bynk token` signs: a hand-minted token \
437             should be short-lived"
438        ));
439    }
440    Ok(secs)
441}
442
443fn unix_now() -> Result<u64, String> {
444    SystemTime::now()
445        .duration_since(UNIX_EPOCH)
446        .map(|d| d.as_secs())
447        .map_err(|_| "the system clock is before 1970".to_string())
448}
449
450// ---------------------------------------------------------------------
451// Signing
452// ---------------------------------------------------------------------
453
454/// An HS256 JWT over `{sub, exp[, nbf]}`. The header and claim order match
455/// `jwt_signer.ts`'s `JSON.stringify` output, so a token is byte-comparable
456/// with the test runtime's.
457pub fn mint(secret: &str, sub: &str, nbf: Option<u64>, exp: u64) -> String {
458    mint_with(secret, sub, nbf, exp, &[])
459}
460
461/// [`mint`] with extra claims, appended after `exp`/`nbf` in the order given.
462pub fn mint_with(
463    secret: &str,
464    sub: &str,
465    nbf: Option<u64>,
466    exp: u64,
467    claims: &[(String, serde_json::Value)],
468) -> String {
469    let header = r#"{"alg":"HS256","typ":"JWT"}"#;
470    let sub_json = serde_json::to_string(sub).expect("a string serialises");
471    let mut payload = format!(r#"{{"sub":{sub_json},"exp":{exp}"#);
472    if let Some(nbf) = nbf {
473        payload.push_str(&format!(r#","nbf":{nbf}"#));
474    }
475    for (name, value) in claims {
476        let name = serde_json::to_string(name).expect("a string serialises");
477        payload.push_str(&format!(",{name}:{value}"));
478    }
479    payload.push('}');
480    let signing_input = format!(
481        "{}.{}",
482        b64url(header.as_bytes()),
483        b64url(payload.as_bytes())
484    );
485    let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, secret.as_bytes());
486    let sig = ring::hmac::sign(&key, signing_input.as_bytes());
487    format!("{signing_input}.{}", b64url(sig.as_ref()))
488}
489
490/// Unpadded base64url (RFC 4648 §5), as the verifier's decoder reads it.
491fn b64url(bytes: &[u8]) -> String {
492    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
493    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
494    for chunk in bytes.chunks(3) {
495        let n = (u32::from(chunk[0]) << 16)
496            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
497            | u32::from(*chunk.get(2).unwrap_or(&0));
498        for i in 0..=chunk.len() {
499            out.push(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char);
500        }
501    }
502    out
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    #[test]
510    fn base64url_matches_the_rfc_vectors_unpadded() {
511        assert_eq!(b64url(b""), "");
512        assert_eq!(b64url(b"f"), "Zg");
513        assert_eq!(b64url(b"fo"), "Zm8");
514        assert_eq!(b64url(b"foo"), "Zm9v");
515        assert_eq!(b64url(b"foob"), "Zm9vYg");
516        assert_eq!(b64url(&[0xfb, 0xff]), "-_8");
517    }
518
519    /// RFC 7515 §A.1's HS256 example: the signing input and key are the RFC's, so
520    /// this pins the HMAC and the base64url independently of the verifier.
521    #[test]
522    fn hmac_matches_rfc_7515_a1() {
523        let key_b64 = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow";
524        // The RFC's key is raw bytes; decode our own encoding of it to compare.
525        let mut bytes = Vec::new();
526        let mut acc = 0u32;
527        let mut bits = 0;
528        for c in key_b64.chars() {
529            let v = match c {
530                'A'..='Z' => c as u32 - 'A' as u32,
531                'a'..='z' => c as u32 - 'a' as u32 + 26,
532                '0'..='9' => c as u32 - '0' as u32 + 52,
533                '-' => 62,
534                _ => 63,
535            };
536            acc = (acc << 6) | v;
537            bits += 6;
538            if bits >= 8 {
539                bits -= 8;
540                bytes.push((acc >> bits) as u8);
541                acc &= (1 << bits) - 1;
542            }
543        }
544        let input = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
545        let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, &bytes);
546        let sig = ring::hmac::sign(&key, input.as_bytes());
547        assert_eq!(
548            b64url(sig.as_ref()),
549            "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
550        );
551    }
552
553    #[test]
554    fn durations_parse_and_refuse() {
555        assert_eq!(parse_duration("90s", "--lifetime"), Ok(90));
556        assert_eq!(parse_duration("15m", "--lifetime"), Ok(900));
557        assert_eq!(parse_duration("1h", "--lifetime"), Ok(3600));
558        assert_eq!(parse_duration("365d", "--lifetime"), Ok(MAX_LIFETIME_SECS));
559        for bad in [
560            "",
561            "h",
562            "30",
563            "0s",
564            "1.5h",
565            "-1h",
566            "3w",
567            "366d",
568            "99999999999999999999d",
569        ] {
570            assert!(parse_duration(bad, "--lifetime").is_err(), "{bad:?}");
571        }
572    }
573
574    #[test]
575    fn payload_order_matches_the_test_signer() {
576        let t = mint("k", "me", None, 5);
577        let payload = t.split('.').nth(1).unwrap();
578        assert_eq!(payload, b64url(br#"{"sub":"me","exp":5}"#));
579        let t = mint("k", "me", Some(3), 5);
580        assert_eq!(
581            t.split('.').nth(1).unwrap(),
582            b64url(br#"{"sub":"me","exp":5,"nbf":3}"#)
583        );
584    }
585}