Skip to main content

knos_oidc_interface/
lib.rs

1//! Read a token that knos-oidc verified. knos-oidc is a Solana program that checks the RS256 signature of an OIDC
2//! token (GitHub Actions, GitLab CI, any other RS256 issuer it admitted) on chain and leaves the result in an
3//! account it owns. Your program takes that account and reads the claims the issuer signed: which repository, which
4//! commit, which workflow, which audience. There is no CPI and no oracle.
5//!
6//! This crate has no dependency and does not allocate: bytes in, values out. It works with solana-program,
7//! pinocchio or anchor of any version, and off chain.
8//!
9//! There are two deployments of knos-oidc, and this crate reads the SECOND unless you name the first: `ID`,
10//! `Token::read` and `Token::read_any` are the second deployment's (`v2` is the same thing by name). It admits
11//! signing keys on GitHub's own signature, lets them expire and lets a guardian revoke them; it is upgradeable only
12//! through a multisig with a public 48-hour delay, until an outside review. The first deployment (`v1::ID`,
13//! `v1::read`) is immutable: no key of it expires and none can be revoked, so a program reads it only by naming it.
14//! A token account has the same layout under both; a token one deployment verified says nothing under the other.
15//!
16//! ```ignore
17//! let data = token_account.try_borrow_data()?;
18//! let tok = Token::read(&token_account.owner.to_bytes(), &data, clock.unix_timestamp).map_err(|_| MyError::Token)?;
19//! if tok.issuer() != ISSUER_GITHUB { return Err(MyError::Token.into()); }
20//! let repo = tok.claim_u64("repository_id").ok_or(MyError::Claims)?;
21//! ```
22#![no_std]
23#[cfg(feature = "alloc")]
24extern crate alloc;
25
26/// The knos-oidc program this crate reads by default: the second deployment (devnet), as bytes. A token account
27/// must be owned by it.
28pub const ID: [u8; 32] = [
29    0xdb, 0x45, 0x49, 0x36, 0x35, 0xef, 0x28, 0x0d, 0xfb, 0xbe, 0x73, 0x6a, 0x6d, 0xfa, 0xd8, 0xbc,
30    0xf8, 0x60, 0x38, 0xc2, 0xa5, 0x39, 0x74, 0xf7, 0x64, 0x1d, 0x78, 0x42, 0xb8, 0xaa, 0x41, 0x71,
31];
32/// The same address as Solana prints it.
33pub const ID_STR: &str = "FkwZdsYCmzicJMtHLTkPK76bYNVG4WNwkWJBiVWNtF3W";
34
35/// The second deployment of knos-oidc by name: the same address and the same reader as the crate's defaults, for a
36/// program that wants its choice written out.
37pub mod v2 {
38    use super::{Error, Token};
39
40    pub const ID: [u8; 32] = super::ID;
41    pub const ID_STR: &str = super::ID_STR;
42
43    /// `Token::read`: the account is owned by the second deployment, VERIFIED, at most `LATE` seconds past its
44    /// expiry, and not verified by a private key.
45    pub fn read<'a>(owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> {
46        Token::read_from(&ID, owner, data, now)
47    }
48}
49
50/// The first deployment of knos-oidc: immutable, with GitHub's and GitLab's keys of its day fixed in it, no expiry
51/// and no revocation. Nothing in this crate reads it unless you write `v1`.
52pub mod v1 {
53    use super::{Error, Token};
54
55    /// The first deployment's address (devnet), as bytes.
56    pub const ID: [u8; 32] = [
57        0x0d, 0xc9, 0x82, 0xa8, 0x4f, 0x3b, 0x4e, 0xae, 0x63, 0x8e, 0x01, 0x8f, 0xe3, 0x9a, 0x96, 0xd0,
58        0x6b, 0xd7, 0xe9, 0x53, 0x33, 0x1c, 0xda, 0x76, 0x0d, 0x51, 0x66, 0xb4, 0x0b, 0x34, 0x2b, 0xa3,
59    ];
60    /// The same address as Solana prints it.
61    pub const ID_STR: &str = "vpWym9azbPU5f2PH2a6n8c4RfmsyUeW2dMuWr1DSHcE";
62
63    /// The three checks against the first deployment: owned by `v1::ID`, VERIFIED, at most `LATE` past its expiry.
64    pub fn read<'a>(owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> {
65        Token::read_from(&ID, owner, data, now)
66    }
67}
68
69pub const ISSUER_GITHUB: u8 = 0;
70pub const ISSUER_GITLAB: u8 = 1;
71/// Any other RS256 issuer that the second deployment admitted on an attestation (RegisterIssuerKey). The number says
72/// only "not GitHub, not GitLab": which issuer is `Token::issuer_hash` (sha256 of its URL), and knos-oidc checked
73/// that the token's `iss` is that URL.
74pub const ISSUER_OTHER: u8 = 2;
75/// A PRIVATE key verified the token: a key some wallet registered itself, with no attestation (RegisterPrivateKey),
76/// for an issuer no public runner can reach. Nobody vouches for it. `Token::read` refuses such a token; a program
77/// that wants them reads with `Token::read_any` and accepts one only from a `registrant` it trusts for that purpose.
78pub const ISSUER_PRIVATE: u8 = 3;
79/// The `iss` claim of each numbered issuer, by its number.
80pub const ISSUERS: [&[u8]; 2] = [b"https://token.actions.githubusercontent.com", b"https://gitlab.com"];
81
82/// The longest token knos-oidc takes.
83pub const MAX_JWT: usize = 8192;
84/// How long after its `exp` a token is still accepted by knos-oidc and by `fresh`. The issuers' tokens live five
85/// minutes, which is shorter than it can take to land the transactions that verify one.
86pub const LATE: i64 = 3600;
87pub fn fresh(exp: i64, now: i64) -> bool { now < exp.saturating_add(LATE) }
88
89// token account: stage u8 (0 writing, 1 stepping, 2 VERIFIED), issuer u8, squarings done u8, limbs u8, jwt_len u16,
90// payload_off u16, payload_len u16, exp i64, key[32], payer[32], id[32], x (the running power, 512 bytes), jwt
91pub const T_STAGE: usize = 0;
92pub const T_ISSUER: usize = 1;
93pub const T_DONE: usize = 2;
94pub const T_LIMBS: usize = 3;
95pub const T_LEN: usize = 4;
96pub const T_POFF: usize = 6;
97pub const T_PLEN: usize = 8;
98pub const T_EXP: usize = 10;
99pub const T_KEY: usize = 18;
100pub const T_PAYER: usize = 50;
101pub const T_ID: usize = 82;
102pub const T_X: usize = 114;
103pub const T_JWT: usize = 626;
104pub const VERIFIED: u8 = 2;
105/// In a VERIFIED account whose issuer is ISSUER_OTHER or ISSUER_PRIVATE: sha256 of the issuer's URL, and for a
106/// private key the wallet that registered it (zero otherwise). They stand where the running power was.
107pub const T_IHASH: usize = T_X;
108pub const T_REGISTRANT: usize = T_X + 32;
109
110// key account (second deployment): state u8 (1 ready), issuer u8, limbs u8, bump u8, n0inv u32, active_at i64,
111// expires_at i64, flags u8, 15 zero bytes, then the modulus and R^2
112pub const K_STATE: usize = 0;
113pub const K_ACTIVE: usize = 8;
114pub const K_EXPIRES: usize = 16;
115pub const K_FLAGS: usize = 24;
116pub const K_HDR: usize = 40;
117pub const F_APPROVED: u8 = 1;
118pub const F_REVOKED: u8 = 2;
119pub const F_GENESIS: u8 = 4;
120pub const F_PRIVATE: u8 = 8;
121
122/// Why a token or a claim was refused. `code()` is the number to put in a program error: 61 to 63 are the codes
123/// knos-oidc's own claims reader returns for the same bytes.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125#[repr(u32)]
126pub enum Error {
127    /// The account is not owned by knos-oidc: anyone can create an account holding the same bytes.
128    NotOidc = 1,
129    /// Not a token account, or its signature has not been checked to the end.
130    NotVerified = 2,
131    /// More than `LATE` seconds past the token's `exp`.
132    Stale = 3,
133    /// A private key verified the token (`ISSUER_PRIVATE`): it is one wallet's word, and `Token::read` does not take
134    /// it. Read it with `Token::read_any` and check `registrant()`.
135    Private = 4,
136    /// Not the key account the token names, or not an account of the same knos-oidc.
137    Key = 68,
138    /// The key that verified the token is not active (the same codes as knos-oidc's Step: 76, 77, 78).
139    KeyNotActive = 76,
140    /// The key that verified the token has expired: nothing attested it for 30 days.
141    KeyExpired = 77,
142    /// The guardian (or a private key's registrant) revoked the key that verified the token.
143    KeyRevoked = 78,
144    /// The claims are not a JSON object.
145    Json = 61,
146    /// A claim that was asked for appears twice.
147    Duplicate = 62,
148    /// The claim is missing or of the wrong type.
149    Claim = 63,
150}
151impl Error {
152    pub const fn code(self) -> u32 { self as u32 }
153}
154
155/// What a token account holds once it is VERIFIED: the issuer's number, the expiry, and the decoded claims (JSON).
156#[derive(Clone, Copy, Debug)]
157pub struct Verified<'a> { pub issuer: u8, pub exp: i64, pub payload: &'a [u8] }
158/// None unless the account's bytes are a VERIFIED token. The caller must have checked the account's owner.
159pub fn verified(d: &[u8]) -> Option<Verified<'_>> {
160    if d.len() < T_JWT || d[T_STAGE] != VERIFIED { return None; }
161    let off = u16::from_le_bytes([d[T_POFF], d[T_POFF + 1]]) as usize;
162    let len = u16::from_le_bytes([d[T_PLEN], d[T_PLEN + 1]]) as usize;
163    let payload = d.get(off..off + len)?;
164    Some(Verified { issuer: d[T_ISSUER], exp: i64::from_le_bytes(d[T_EXP..T_EXP + 8].try_into().ok()?), payload })
165}
166
167/// A verified, fresh token. `read` does the three checks every consumer must do: the account is owned by knos-oidc
168/// (the second deployment, unless you read with `v1::read` or `read_from`), it is VERIFIED, and it is at most `LATE`
169/// seconds past its expiry (`now` is the chain's clock).
170///
171/// What remains your program's job, because knos-oidc only says the token is genuine:
172/// - the issuer (`issuer()`): GitHub and GitLab sign different claims;
173/// - the claims your statement depends on: the repository (`repository_id`), the workflow file and its commit
174///   (`job_workflow_ref`, `job_workflow_sha`), and `runner_environment` if a self-hosted runner must not count;
175/// - the audience: give your program its own prefix and require it, so a token minted for another program cannot
176///   be used with yours;
177/// - your own replay guard: the same verified token can be read by any program, any number of times, until an
178///   hour after its expiry. Bind the token to one action in the audience and record that the action was done.
179/// - if a revoked or expired signing key must stop its tokens at once: take the key account too and call
180///   `check_key`. Without it a token account is good for up to 25 hours after its key stopped.
181///
182/// `read` never returns a token that a PRIVATE key verified. `read_any` does, and then `is_private()` is the check
183/// your program must not forget: such a token is the word of `registrant()`, not of the issuer its claims name.
184#[derive(Clone, Copy, Debug)]
185pub struct Token<'a> { v: Verified<'a>, data: &'a [u8], program: [u8; 32] }
186impl<'a> Token<'a> {
187    /// The second deployment's token accounts (`ID`). For the first deployment, write `v1::read`.
188    pub fn read(owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> { Self::read_from(&ID, owner, data, now) }
189    /// The same three checks against one deployment of knos-oidc that you name: `ID` or `v1::ID`. A token that one
190    /// deployment verified says nothing under the other's address, so name exactly the one your program trusts.
191    /// A token that a private key verified is refused (`Error::Private`).
192    pub fn read_from(program: &[u8; 32], owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> {
193        let tok = Self::read_any_from(program, owner, data, now)?;
194        if tok.v.issuer > ISSUER_OTHER { return Err(Error::Private); }
195        Ok(tok)
196    }
197    /// `read`, and tokens that a private key verified too. Ask `is_private()` of what this returns.
198    pub fn read_any(owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> { Self::read_any_from(&ID, owner, data, now) }
199    pub fn read_any_from(program: &[u8; 32], owner: &[u8; 32], data: &'a [u8], now: i64) -> Result<Token<'a>, Error> {
200        if owner != program { return Err(Error::NotOidc); }
201        let v = verified(data).ok_or(Error::NotVerified)?;
202        if !fresh(v.exp, now) { return Err(Error::Stale); }
203        Ok(Token { v, data, program: *program })
204    }
205    /// ISSUER_GITHUB, ISSUER_GITLAB, ISSUER_OTHER (see `issuer_hash`) or ISSUER_PRIVATE (see `registrant`).
206    pub fn issuer(&self) -> u8 { self.v.issuer }
207    pub fn exp(&self) -> i64 { self.v.exp }
208    /// Whether a private key verified this token: a key a wallet registered itself, which nobody vouches for. The
209    /// claims may name any issuer, GitHub included; they are the registrant's word. True for any issuer number this
210    /// crate does not know, so that a newer kind of key is never taken for a public one.
211    pub fn is_private(&self) -> bool { self.v.issuer > ISSUER_OTHER }
212    /// The wallet that registered the private key; None for a token that is not private.
213    pub fn registrant(&self) -> Option<&'a [u8; 32]> {
214        if self.v.issuer != ISSUER_PRIVATE { return None; }
215        self.data[T_REGISTRANT..T_REGISTRANT + 32].try_into().ok()
216    }
217    /// sha256 of the issuer's URL, for ISSUER_OTHER and ISSUER_PRIVATE; None for GitHub and GitLab by number.
218    pub fn issuer_hash(&self) -> Option<&'a [u8; 32]> {
219        if self.v.issuer < ISSUER_OTHER { return None; }
220        self.data[T_IHASH..T_IHASH + 32].try_into().ok()
221    }
222    /// The address of the key account that verified the token.
223    pub fn key(&self) -> &'a [u8; 32] { self.data[T_KEY..T_KEY + 32].try_into().unwrap() }
224    /// Whether the key that verified the token may still verify at `now`, by knos-oidc's own rule. Pass the key
225    /// account: its address must be the one the token names and its owner the same knos-oidc. Second deployment
226    /// only (the first has no expiry and no revocation). Errors: `Key`, `KeyNotActive`, `KeyExpired`, `KeyRevoked`.
227    pub fn check_key(&self, key_address: &[u8; 32], key_owner: &[u8; 32], key_data: &[u8], now: i64) -> Result<(), Error> {
228        if key_address != self.key() || *key_owner != self.program || key_data.len() < K_HDR || key_data[K_STATE] != 1 { return Err(Error::Key); }
229        let at = |o: usize| i64::from_le_bytes(key_data[o..o + 8].try_into().unwrap());
230        key_usable(key_data[K_FLAGS], at(K_ACTIVE), at(K_EXPIRES), now)
231    }
232    /// The claims as the issuer signed them (a JSON object).
233    pub fn payload(&self) -> &'a [u8] { self.v.payload }
234    /// Several claims in one pass over the payload. A wanted claim that appears twice is an error.
235    pub fn claims<const N: usize>(&self, want: [&[u8]; N]) -> Result<[Option<Raw<'a>>; N], Error> { fields(self.v.payload, want) }
236    /// A string claim. None if it is absent, appears twice or is not a string.
237    pub fn claim(&self, name: &str) -> Option<Text<'a>> {
238        let [f] = self.claims([name.as_bytes()]).ok()?;
239        text(f).ok()
240    }
241    /// A non-negative integer claim, given as a number or as a string of digits (GitHub sends ids as strings).
242    pub fn claim_u64(&self, name: &str) -> Option<u64> {
243        let [f] = self.claims([name.as_bytes()]).ok()?;
244        number(f).ok()
245    }
246    /// The `aud` claim when it is one string, which is what GitHub Actions and GitLab CI sign.
247    pub fn audience(&self) -> Option<Text<'a>> { self.claim("aud") }
248}
249
250/// knos-oidc's rule for a ready key, from its flags and times: revoked first, then not active (not a genesis key,
251/// not approved, not private, or before its time), then expired.
252pub fn key_usable(flags: u8, active_at: i64, expires_at: i64, now: i64) -> Result<(), Error> {
253    if flags & F_REVOKED != 0 { return Err(Error::KeyRevoked); }
254    if flags & (F_GENESIS | F_APPROVED | F_PRIVATE) == 0 || now < active_at { return Err(Error::KeyNotActive); }
255    if now >= expires_at { return Err(Error::KeyExpired); }
256    Ok(())
257}
258
259fn ws(b: &[u8], mut i: usize) -> usize {
260    while i < b.len() && matches!(b[i], b' ' | b'\t' | b'\n' | b'\r') { i += 1; }
261    i
262}
263/// b[i] == '"': the string's raw content range and the index after its closing quote.
264fn jstr(b: &[u8], i: usize) -> Result<(usize, usize, usize), Error> {
265    if b.get(i) != Some(&b'"') { return Err(Error::Json); }
266    let mut k = i + 1;
267    while k < b.len() {
268        match b[k] {
269            b'\\' => k += 2,
270            b'"' => return Ok((i + 1, k, k + 1)),
271            _ => k += 1,
272        }
273    }
274    Err(Error::Json)
275}
276fn skip_value(b: &[u8], i: usize) -> Result<usize, Error> {
277    match b.get(i) {
278        Some(b'"') => Ok(jstr(b, i)?.2),
279        Some(b'{') | Some(b'[') => {
280            let mut depth = 0usize;
281            let mut k = i;
282            while k < b.len() {
283                match b[k] {
284                    b'"' => { k = jstr(b, k)?.2; continue; }
285                    b'{' | b'[' => depth += 1,
286                    b'}' | b']' => { depth -= 1; if depth == 0 { return Ok(k + 1); } }
287                    _ => {}
288                }
289                k += 1;
290            }
291            Err(Error::Json)
292        }
293        Some(_) => {
294            let mut k = i;
295            while k < b.len() && !matches!(b[k], b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r') { k += 1; }
296            if k == i { Err(Error::Json) } else { Ok(k) }
297        }
298        None => Err(Error::Json),
299    }
300}
301
302/// A claim's value as it stands in the JSON: the raw content of a string, or the raw token of a number/literal.
303#[derive(Clone, Copy, Debug)]
304pub struct Raw<'a> { pub bytes: &'a [u8], pub is_str: bool }
305
306/// Whether a key whose raw content is `raw` is the name `want` (printable ASCII), however it is spelled: a JSON
307/// reader that decodes escapes takes "a\u0075d" for "aud", so this one does too. An escape `unescape` refuses
308/// stands for a character no wanted name has.
309fn key_is(raw: &[u8], escaped: bool, want: &[u8]) -> bool {
310    if !escaped { return raw == want; }
311    let (mut i, mut k) = (0, 0);
312    while i < raw.len() {
313        let Ok((c, next)) = unescape(raw, i) else { return false };
314        if want.get(k) != Some(&c) { return false; }
315        i = next; k += 1;
316    }
317    k == want.len()
318}
319
320/// One pass over a flat JSON object: for each wanted top-level key, its value. A wanted key that appears twice is
321/// refused, the whole object must parse, and nothing may follow it. A key is compared as the text it spells (its
322/// escapes decoded), so that this reader and any other JSON reader find the same claim under the same name. The
323/// same code as the second knos-oidc's, so it gives the same answer on the same bytes.
324pub fn fields<'a, const N: usize>(b: &'a [u8], want: [&[u8]; N]) -> Result<[Option<Raw<'a>>; N], Error> {
325    let mut got: [Option<Raw<'a>>; N] = [None; N];
326    let mut i = ws(b, 0);
327    if b.get(i) != Some(&b'{') { return Err(Error::Json); }
328    i = ws(b, i + 1);
329    if b.get(i) != Some(&b'}') {
330        loop {
331            let (ks, ke, next) = jstr(b, i)?;
332            i = ws(b, next);
333            if b.get(i) != Some(&b':') { return Err(Error::Json); }
334            let vs = ws(b, i + 1);
335            let ve = skip_value(b, vs)?;
336            let key = &b[ks..ke];
337            let escaped = key.contains(&b'\\');
338            for (w, g) in want.iter().zip(got.iter_mut()) {
339                if key_is(key, escaped, w) {
340                    if g.is_some() { return Err(Error::Duplicate); }
341                    *g = Some(if b[vs] == b'"' { Raw { bytes: &b[vs + 1..ve - 1], is_str: true } } else { Raw { bytes: &b[vs..ve], is_str: false } });
342                }
343            }
344            i = ws(b, ve);
345            match b.get(i) {
346                Some(b',') => i = ws(b, i + 1),
347                Some(b'}') => break,
348                _ => return Err(Error::Json),
349            }
350        }
351    }
352    if ws(b, i + 1) != b.len() { return Err(Error::Json); }
353    Ok(got)
354}
355
356/// The byte at r[i] of a JSON string's raw content, decoded, and the index after it.
357fn unescape(r: &[u8], i: usize) -> Result<(u8, usize), Error> {
358    if r[i] != b'\\' { return Ok((r[i], i + 1)); }
359    match r.get(i + 1) {
360        Some(b'/') => Ok((b'/', i + 2)),
361        Some(b'\\') => Ok((b'\\', i + 2)),
362        Some(b'"') => Ok((b'"', i + 2)),
363        Some(b'u') => {
364            let h = r.get(i + 2..i + 6).ok_or(Error::Claim)?;
365            let mut v = 0u32;
366            for &c in h {
367                v = v << 4 | match c { b'0'..=b'9' => c - b'0', b'a'..=b'f' => c - b'a' + 10, b'A'..=b'F' => c - b'A' + 10, _ => return Err(Error::Claim) } as u32;
368            }
369            if !(0x20..0x7f).contains(&v) { return Err(Error::Claim); }
370            Ok((v as u8, i + 6))
371        }
372        _ => Err(Error::Claim),
373    }
374}
375
376/// A string claim's text, read without copying it. Its escapes were checked by `text`, so reading it cannot fail.
377#[derive(Clone, Copy, Debug)]
378pub struct Text<'a> { raw: &'a [u8], len: usize }
379impl<'a> Text<'a> {
380    /// The text's length in bytes, escapes decoded.
381    pub fn len(&self) -> usize { self.len }
382    pub fn is_empty(&self) -> bool { self.len == 0 }
383    pub fn bytes(&self) -> TextBytes<'a> { TextBytes { raw: self.raw, at: 0 } }
384    /// Whether the text is exactly `want` (a byte string or a str).
385    pub fn is(&self, want: impl AsRef<[u8]>) -> bool {
386        let w = want.as_ref();
387        match self.as_plain() {
388            Some(t) => t == w,
389            None => w.len() == self.len && self.bytes().eq(w.iter().copied()),
390        }
391    }
392    pub fn starts_with(&self, prefix: impl AsRef<[u8]>) -> bool {
393        let p = prefix.as_ref();
394        match self.as_plain() {
395            Some(t) => t.starts_with(p),
396            None => p.len() <= self.len && self.bytes().take(p.len()).eq(p.iter().copied()),
397        }
398    }
399    /// The text itself when the issuer wrote it with no escapes (the usual case), borrowed from the account.
400    pub fn as_plain(&self) -> Option<&'a [u8]> { if self.raw.len() == self.len { Some(self.raw) } else { None } }
401    /// Copies the text to the start of `out` and returns that part; None if `out` is too short.
402    pub fn copy_to<'b>(&self, out: &'b mut [u8]) -> Option<&'b [u8]> {
403        let o = out.get_mut(..self.len)?;
404        match self.as_plain() {
405            Some(t) => o.copy_from_slice(t),
406            None => for (d, s) in o.iter_mut().zip(self.bytes()) { *d = s; },
407        }
408        Some(o)
409    }
410    #[cfg(feature = "alloc")]
411    pub fn to_vec(&self) -> alloc::vec::Vec<u8> { self.bytes().collect() }
412}
413pub struct TextBytes<'a> { raw: &'a [u8], at: usize }
414impl Iterator for TextBytes<'_> {
415    type Item = u8;
416    fn next(&mut self) -> Option<u8> {
417        if self.at >= self.raw.len() { return None; }
418        let (c, next) = unescape(self.raw, self.at).ok()?;
419        self.at = next;
420        Some(c)
421    }
422}
423
424/// A string claim's text. JSON escapes for printable ASCII are decoded (\/ \\ \" and \u00XX), so a value compares
425/// equal however the issuer chose to escape it; any other escape is refused.
426pub fn text(f: Option<Raw<'_>>) -> Result<Text<'_>, Error> {
427    let r = match f { Some(r) if r.is_str => r.bytes, _ => return Err(Error::Claim) };
428    // the usual case has no escape: nothing to decode, and the text can be compared and copied as it stands
429    if !r.contains(&b'\\') { return Ok(Text { raw: r, len: r.len() }); }
430    let (mut i, mut len) = (0, 0);
431    while i < r.len() {
432        i = unescape(r, i)?.1;
433        len += 1;
434    }
435    Ok(Text { raw: r, len })
436}
437/// A non-negative integer claim, given as a JSON number or as a string of digits (GitHub sends ids as strings).
438/// No sign, no leading zero, no fraction; at most 18 digits.
439pub fn number(f: Option<Raw>) -> Result<u64, Error> {
440    let r = f.ok_or(Error::Claim)?;
441    parse_u64(r.bytes).ok_or(Error::Claim)
442}
443pub fn parse_u64(s: &[u8]) -> Option<u64> {
444    if s.is_empty() || s.len() > 18 || !s.iter().all(|c| c.is_ascii_digit()) || (s.len() > 1 && s[0] == b'0') { return None; }
445    Some(s.iter().fold(0u64, |a, c| a * 10 + (c - b'0') as u64))
446}
447
448// What an audience is usually made of: parts split on ':', lowercase hex, a Solana address.
449pub fn is_hex(s: &[u8], len: usize) -> bool { s.len() == len && s.iter().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) }
450pub fn unhex32(s: &[u8]) -> Option<[u8; 32]> {
451    if !is_hex(s, 64) { return None; }
452    let v = |c: u8| if c <= b'9' { c - b'0' } else { c - b'a' + 10 };
453    let mut o = [0u8; 32];
454    for (k, b) in o.iter_mut().enumerate() { *b = v(s[2 * k]) << 4 | v(s[2 * k + 1]); }
455    Some(o)
456}
457/// A canonical base58 32-byte public key (as Solana prints it); None for anything else.
458pub fn b58_32(s: &[u8]) -> Option<[u8; 32]> {
459    const A: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
460    if s.len() < 32 || s.len() > 44 { return None; }
461    let mut out = [0u8; 32];
462    for &c in s {
463        let mut carry = A.iter().position(|&x| x == c)? as u32;
464        for b in out.iter_mut().rev() {
465            carry += (*b as u32) * 58;
466            *b = carry as u8;
467            carry >>= 8;
468        }
469        if carry != 0 { return None; }
470    }
471    let ones = s.iter().take_while(|&&c| c == b'1').count();
472    let zeros = out.iter().take_while(|&&b| b == 0).count();
473    if ones != zeros { return None; }
474    Some(out)
475}
476/// Splits `s` on ':' into exactly N parts.
477pub fn parts<const N: usize>(s: &[u8]) -> Option<[&[u8]; N]> {
478    let mut out: [&[u8]; N] = [&[]; N];
479    let mut it = s.split(|&c| c == b':');
480    for o in out.iter_mut() { *o = it.next()?; }
481    if it.next().is_some() { return None; }
482    Some(out)
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    #[test]
490    fn the_id_is_the_deployed_address() {
491        assert_eq!(b58_32(ID_STR.as_bytes()), Some(ID));
492        assert_eq!(b58_32(v1::ID_STR.as_bytes()), Some(v1::ID));
493    }
494
495    #[test]
496    fn every_default_is_the_second_deployment_and_the_first_is_read_only_by_name() {
497        assert_eq!((ID_STR, v2::ID_STR, v1::ID_STR), ("FkwZdsYCmzicJMtHLTkPK76bYNVG4WNwkWJBiVWNtF3W", "FkwZdsYCmzicJMtHLTkPK76bYNVG4WNwkWJBiVWNtF3W",
498                                                       "vpWym9azbPU5f2PH2a6n8c4RfmsyUeW2dMuWr1DSHcE"));
499        assert!(v2::ID == ID && v1::ID != ID);
500        let (d, len) = account(ISSUER_GITHUB, br#"{"aud":"x","exp":1000}"#, 1000);
501        let d = &d[..len];
502        // an account the first deployment owns: every reader that does not say `v1` refuses it
503        assert_eq!(Token::read(&v1::ID, d, 1000).unwrap_err(), Error::NotOidc);
504        assert_eq!(Token::read_any(&v1::ID, d, 1000).unwrap_err(), Error::NotOidc);
505        assert_eq!(v2::read(&v1::ID, d, 1000).unwrap_err(), Error::NotOidc);
506        assert!(v1::read(&v1::ID, d, 1000).is_ok() && Token::read_from(&v1::ID, &v1::ID, d, 1000).is_ok());
507        // an account the second owns: read by every default, refused under the first's name
508        assert!(Token::read(&ID, d, 1000).is_ok() && Token::read_any(&ID, d, 1000).is_ok() && v2::read(&ID, d, 1000).is_ok());
509        assert_eq!(v1::read(&ID, d, 1000).unwrap_err(), Error::NotOidc);
510    }
511
512    #[test]
513    fn the_two_deployments_have_their_own_addresses_and_read_the_same_layout() {
514        assert_eq!(b58_32(v2::ID_STR.as_bytes()), Some(v2::ID));
515        assert_ne!(v2::ID, v1::ID);
516        // a VERIFIED token account, as small as one can be: the header, then the claims
517        let payload = br#"{"aud":"x","exp":1000}"#;
518        let mut d = [0u8; T_JWT + 22];
519        d[T_STAGE] = VERIFIED;
520        d[T_ISSUER] = ISSUER_GITLAB;
521        d[T_POFF..T_POFF + 2].copy_from_slice(&(T_JWT as u16).to_le_bytes());
522        d[T_PLEN..T_PLEN + 2].copy_from_slice(&(payload.len() as u16).to_le_bytes());
523        d[T_EXP..T_EXP + 8].copy_from_slice(&1000i64.to_le_bytes());
524        d[T_JWT..].copy_from_slice(payload);
525        // each reader takes its own deployment's account and refuses the other's
526        let tok = v2::read(&v2::ID, &d, 1000).unwrap();
527        assert!(tok.issuer() == ISSUER_GITLAB && tok.exp() == 1000 && tok.audience().unwrap().is("x") && tok.claim_u64("exp") == Some(1000));
528        assert_eq!(v2::read(&v1::ID, &d, 1000).unwrap_err(), Error::NotOidc);
529        assert_eq!(v1::read(&v2::ID, &d, 1000).unwrap_err(), Error::NotOidc);
530        assert!(v1::read(&v1::ID, &d, 1000).is_ok() && Token::read_from(&v2::ID, &v2::ID, &d, 1000).is_ok());
531        assert_eq!(Token::read_from(&v2::ID, &[0; 32], &d, 1000).unwrap_err(), Error::NotOidc);
532        // the other two checks are the same ones
533        assert_eq!(v2::read(&v2::ID, &d, 1000 + LATE).unwrap_err(), Error::Stale);
534        d[T_STAGE] = 1;
535        assert_eq!(v2::read(&v2::ID, &d, 1000).unwrap_err(), Error::NotVerified);
536    }
537
538    /// A VERIFIED token account of the second deployment, as small as one can be.
539    fn account(issuer: u8, payload: &[u8], exp: i64) -> ([u8; T_JWT + 160], usize) {
540        let mut d = [0u8; T_JWT + 160];
541        d[T_STAGE] = VERIFIED;
542        d[T_ISSUER] = issuer;
543        d[T_POFF..T_POFF + 2].copy_from_slice(&(T_JWT as u16).to_le_bytes());
544        d[T_PLEN..T_PLEN + 2].copy_from_slice(&(payload.len() as u16).to_le_bytes());
545        d[T_EXP..T_EXP + 8].copy_from_slice(&exp.to_le_bytes());
546        d[T_KEY..T_KEY + 32].copy_from_slice(&[9; 32]);
547        d[T_JWT..T_JWT + payload.len()].copy_from_slice(payload);
548        (d, T_JWT + payload.len())
549    }
550
551    #[test]
552    fn a_private_token_is_refused_by_read_and_marked_for_whoever_reads_any() {
553        // every claim is what GitHub would sign; a wallet's own key signed it and knos-oidc marked the account
554        let payload = br#"{"iss":"https://token.actions.githubusercontent.com","aud":"gate:release","repository_id":"1","exp":1000}"#;
555        let (mut d, len) = account(ISSUER_PRIVATE, payload, 1000);
556        d[T_IHASH..T_IHASH + 32].copy_from_slice(&[0xaa; 32]);
557        d[T_REGISTRANT..T_REGISTRANT + 32].copy_from_slice(&[0xbb; 32]);
558        let d = &d[..len];
559        assert_eq!(v2::read(&v2::ID, d, 1000).unwrap_err(), Error::Private);
560        assert_eq!(Token::read_from(&v2::ID, &v2::ID, d, 1000).unwrap_err(), Error::Private);
561        let tok = Token::read_any_from(&v2::ID, &v2::ID, d, 1000).unwrap();
562        assert!(tok.is_private() && tok.registrant() == Some(&[0xbb; 32]) && tok.issuer_hash() == Some(&[0xaa; 32]));
563        assert!(tok.issuer() == ISSUER_PRIVATE && tok.issuer() != ISSUER_GITHUB);
564        // The one way to be fooled: read_any, then the claims alone. Each of the two checks alone stops it.
565        let forgetful = |t: &Token| t.claim("iss").is_some_and(|i| i.is(ISSUERS[0])) && t.audience().is_some_and(|a| a.is("gate:release"));
566        assert!(forgetful(&tok));
567        let fooled_past_is_private = forgetful(&tok) && !tok.is_private();
568        let fooled_past_the_issuer = forgetful(&tok) && tok.issuer() == ISSUER_GITHUB;
569        assert!(!fooled_past_is_private);
570        assert!(!fooled_past_the_issuer);
571        // the other two checks of read_any are read's
572        assert_eq!(Token::read_any_from(&v2::ID, &[1; 32], d, 1000).unwrap_err(), Error::NotOidc);
573        assert_eq!(Token::read_any_from(&v2::ID, &v2::ID, d, 1000 + LATE).unwrap_err(), Error::Stale);
574        // a public token: not private, no registrant; GitHub and GitLab have no hash, any other issuer has one
575        for (issuer, hash) in [(ISSUER_GITHUB, None), (ISSUER_GITLAB, None), (ISSUER_OTHER, Some(&[0xaa; 32]))] {
576            let (mut d, len) = account(issuer, payload, 1000);
577            d[T_IHASH..T_IHASH + 32].copy_from_slice(&[0xaa; 32]);
578            let tok = v2::read(&v2::ID, &d[..len], 1000).unwrap();
579            assert!(!tok.is_private() && tok.registrant().is_none() && tok.issuer_hash() == hash && tok.issuer() == issuer && tok.key() == &[9; 32]);
580        }
581        // an issuer number from a later knos-oidc is never taken for a public one
582        for issuer in [4u8, 200, 255] {
583            let (d, len) = account(issuer, payload, 1000);
584            assert_eq!(v2::read(&v2::ID, &d[..len], 1000).unwrap_err(), Error::Private);
585            assert!(Token::read_any_from(&v2::ID, &v2::ID, &d[..len], 1000).unwrap().is_private());
586        }
587    }
588
589    #[test]
590    fn check_key_is_knos_oidcs_rule_on_the_key_account_the_token_names() {
591        let (d, len) = account(ISSUER_GITHUB, br#"{"exp":1000}"#, 1000);
592        let tok = v2::read(&v2::ID, &d[..len], 1000).unwrap();
593        let key = |state: u8, flags: u8, active: i64, expires: i64| {
594            let mut k = [0u8; K_HDR + 8];
595            k[K_STATE] = state; k[K_FLAGS] = flags;
596            k[K_ACTIVE..K_ACTIVE + 8].copy_from_slice(&active.to_le_bytes());
597            k[K_EXPIRES..K_EXPIRES + 8].copy_from_slice(&expires.to_le_bytes());
598            k
599        };
600        let good = key(1, F_GENESIS | F_APPROVED, 500, 2000);
601        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &good, 1000), Ok(()));
602        assert_eq!(tok.check_key(&[8; 32], &v2::ID, &good, 1000), Err(Error::Key));      // another key account
603        assert_eq!(tok.check_key(&[9; 32], &[7; 32], &good, 1000), Err(Error::Key));     // another program's account
604        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &good[..K_HDR - 1], 1000), Err(Error::Key));
605        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &key(0, F_GENESIS, 500, 2000), 1000), Err(Error::Key));
606        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &good, 499), Err(Error::KeyNotActive));
607        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &key(1, 0, 500, 2000), 1000), Err(Error::KeyNotActive));
608        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &good, 2000), Err(Error::KeyExpired));
609        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &key(1, F_APPROVED | F_REVOKED, 500, 2000), 1000), Err(Error::KeyRevoked));
610        assert_eq!(tok.check_key(&[9; 32], &v2::ID, &key(1, F_PRIVATE, 500, 2000), 1000), Ok(()));
611        assert_eq!((Error::Key.code(), Error::KeyNotActive.code(), Error::KeyExpired.code(), Error::KeyRevoked.code()), (68, 76, 77, 78));
612    }
613
614    #[test]
615    fn fields_reads_a_flat_object_in_one_pass() {
616        let b = br#" { "a" : "x" , "n":12, "t":true, "o":{"a":"inner","k":[1,"}"]}, "s":"7" } "#;
617        let [a, n, t, o, s, none] = fields(b, [b"a", b"n", b"t", b"o", b"s", b"zz"]).unwrap();
618        assert!(text(a).unwrap().is("x") && number(n) == Ok(12) && number(s) == Ok(7) && none.is_none());
619        assert!(!t.unwrap().is_str && t.unwrap().bytes == b"true" && o.unwrap().bytes == br#"{"a":"inner","k":[1,"}"]}"#);
620        assert_eq!(text(n).unwrap_err(), Error::Claim);      // a number is not a string
621        assert_eq!(number(t).unwrap_err(), Error::Claim);
622        assert!(fields(b"{}", [b"a"]).unwrap()[0].is_none());
623    }
624
625    #[test]
626    fn fields_refuses_what_knos_oidc_refuses() {
627        let json = |b: &[u8]| fields(b, [b"a"]).unwrap_err();
628        assert_eq!(json(br#"{"a":"x","a":"y"}"#), Error::Duplicate);
629        assert!(fields(br#"{"b":1,"b":2}"#, [b"a"]).is_ok());   // only a wanted key is checked for a second copy
630        // a key is the text it spells: a claim is found under an escaped spelling, and a second copy cannot hide behind one
631        let [a] = fields(br#"{"\u0061":"x"}"#, [b"a"]).unwrap();
632        assert!(text(a).unwrap().is("x"));
633        assert_eq!(json(br#"{"a":"x","\u0061":"y"}"#), Error::Duplicate);
634        assert!(fields(br#"{"\u0061b":"x","\n":1}"#, [b"a"]).unwrap()[0].is_none());
635        for bad in [&b""[..], b"[]", b"{", br#"{"a"}"#, br#"{"a":}"#, br#"{"a":"x"} x"#, br#"{"a":"x",}"#, br#"{"a":"x"#,
636                    br#"{"a":[1,2"#,br#"{a:1}"#, br#"{"a":1 "b":2}"#] {
637            assert_eq!(json(bad), Error::Json, "{:?}", core::str::from_utf8(bad));
638        }
639    }
640
641    #[test]
642    fn text_decodes_the_escapes_of_printable_ascii_and_no_other() {
643        let t = |b: &'static [u8]| text(fields(b, [b"a"]).unwrap()[0]);
644        let v = t(br#"{"a":"octo\/widgets \u0041\u007e \\ \" end"}"#).unwrap();
645        let want = br#"octo/widgets A~ \ " end"#;
646        assert!(v.is(want) && v.len() == want.len() && v.starts_with("octo/") && !v.starts_with("octo\\"));
647        assert!(v.as_plain().is_none() && !v.is(&want[1..]) && !v.is("") && !v.is_empty());
648        let mut buf = [0u8; 64];
649        assert_eq!(v.copy_to(&mut buf), Some(&want[..]));
650        assert!(v.copy_to(&mut buf[..want.len() - 1]).is_none());
651        assert_eq!(t(br#"{"a":"plain"}"#).unwrap().as_plain(), Some(&b"plain"[..]));
652        assert!(t(br#"{"a":""}"#).unwrap().is_empty());
653        for bad in [&br#"{"a":"\n"}"#[..], br#"{"a":"\u001f"}"#, br#"{"a":"\u007f"}"#, br#"{"a":"\u00e9"}"#, br#"{"a":"\u00g1"}"#, br#"{"a":"\u004"}"#] {
654            assert_eq!(t(bad).unwrap_err(), Error::Claim, "{:?}", core::str::from_utf8(bad));
655        }
656        assert_eq!(text(None).unwrap_err(), Error::Claim);
657    }
658
659    #[test]
660    fn numbers_and_the_parts_of_an_audience() {
661        assert_eq!(parse_u64(b"0"), Some(0));
662        assert_eq!(parse_u64(b"999999999999999999"), Some(999_999_999_999_999_999));
663        for bad in [&b""[..], b"01", b"-1", b"1.0", b"1e3", b"1234567890123456789", b" 1"] { assert_eq!(parse_u64(bad), None); }
664        assert_eq!(parts::<3>(b"knos:claim:abc"), Some([&b"knos"[..], b"claim", b"abc"]));
665        assert!(parts::<3>(b"knos:claim").is_none() && parts::<3>(b"a:b:c:d").is_none());
666        assert!(is_hex(&[b'a'; 40], 40) && !is_hex(&[b'A'; 40], 40) && !is_hex(&[b'a'; 39], 40));
667        assert_eq!(unhex32(&[b'f'; 64]), Some([0xff; 32]));
668        assert!(unhex32(&[b'f'; 63]).is_none());
669        assert_eq!(b58_32(b"11111111111111111111111111111111"), Some([0; 32]));
670        assert!(b58_32(b"1111111111111111111111111111111").is_none() && b58_32(b"0OIl").is_none());
671        assert!(fresh(100, 100 + LATE - 1) && !fresh(100, 100 + LATE) && fresh(i64::MAX, 0));
672        assert_eq!((Error::Json.code(), Error::Duplicate.code(), Error::Claim.code()), (61, 62, 63));
673    }
674}