tf-types 0.1.4

Core semantic types, traits, and schemas powering the TrustForge protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! OAuth/GNAP bridge — verify a JWT bearer token using the in-house
//! `crate::jws` module,
//! against a static or remote JWKS, and project the verified claims into a
//! TrustForge actor identity + capabilities.
//!
//! Supports ES256 / ES384 / RS256 / RS384 / RS512 / EdDSA. Algorithm
//! confusion attacks (alg:none, HS256-with-RSA-key) are guarded by the
//! mandatory allow-list passed at bridge construction time.

use std::collections::HashMap;

use crate::jws::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::bridges::{Bridge, BridgeError, BridgeKind};
use crate::generated::{
    ActorIdentity, ActorIdentity_IdentityVersion, ActorType, AuthorityRoot, AuthorityRoot_Kind,
    PublicKey, PublicKey_Purpose, TrustLevel,
};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthBridgeConfig {
    pub bridge_id: String,
    pub trust_domain: String,
    pub jwks: Jwks,
    pub allowed_algorithms: Vec<String>,
    pub issuer: String,
    pub audience: Vec<String>,
    #[serde(default = "default_clock_tolerance")]
    pub clock_tolerance_seconds: u64,
}

fn default_clock_tolerance() -> u64 {
    60
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Jwks {
    pub keys: Vec<Jwk>,
}

/// Minimal JWK shape the bridge accepts. ES256/ES384 use x/y; RS* use n/e;
/// EdDSA uses crv=Ed25519 + x.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Jwk {
    pub kty: String,
    #[serde(default)]
    pub alg: Option<String>,
    #[serde(default)]
    pub kid: Option<String>,
    #[serde(default)]
    pub crv: Option<String>,
    #[serde(default)]
    pub x: Option<String>,
    #[serde(default)]
    pub y: Option<String>,
    #[serde(default)]
    pub n: Option<String>,
    #[serde(default)]
    pub e: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthClaims {
    pub iss: Option<String>,
    pub sub: Option<String>,
    pub aud: Option<Value>,
    pub exp: Option<u64>,
    pub iat: Option<u64>,
    pub scope: Option<Value>,
    #[serde(rename = "tf_actor_type", default)]
    pub tf_actor_type: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Clone, Debug)]
pub struct OAuthVerificationResult {
    pub identity: ActorIdentity,
    pub capabilities: Vec<String>,
    pub claims: OAuthClaims,
}

pub struct OAuthBridge {
    cfg: OAuthBridgeConfig,
}

impl OAuthBridge {
    pub fn new(cfg: OAuthBridgeConfig) -> Self {
        OAuthBridge { cfg }
    }

    pub fn verify_token(&self, token: &str) -> Result<OAuthVerificationResult, BridgeError> {
        if token.is_empty() {
            return Err(BridgeError::InvalidInput("empty token".into()));
        }
        let header = decode_header(token)
            .map_err(|e| BridgeError::Rejected(format!("malformed JWT: {}", e)))?;
        let alg = header
            .algorithm()
            .map_err(|e| BridgeError::Rejected(e.to_string()))?;
        let alg_name = alg.name().to_string();
        if !self
            .cfg
            .allowed_algorithms
            .iter()
            .any(|a| a.eq_ignore_ascii_case(&alg_name))
        {
            return Err(BridgeError::Rejected(format!(
                "algorithm {} not in allow-list",
                alg_name
            )));
        }

        let kid = header
            .kid
            .clone()
            .ok_or_else(|| BridgeError::Rejected("JWT header missing kid".into()))?;
        let jwk = self
            .cfg
            .jwks
            .keys
            .iter()
            .find(|k| k.kid.as_deref() == Some(&kid))
            .ok_or_else(|| BridgeError::Rejected(format!("no JWK with kid {}", kid)))?;
        let key = decoding_key_for(jwk)?;

        let mut validation = Validation::new(alg);
        validation.set_issuer(&[self.cfg.issuer.as_str()]);
        validation.set_audience(&self.cfg.audience);
        validation.leeway = self.cfg.clock_tolerance_seconds;
        validation.algorithms = vec![alg];

        let data = decode::<OAuthClaims>(token, &key, &validation)
            .map_err(|e| BridgeError::Rejected(format!("JWT verify failed: {}", e)))?;
        let claims = data.claims;
        let subject = claims
            .sub
            .clone()
            .ok_or_else(|| BridgeError::Rejected("JWT missing sub claim".into()))?;
        let actor_type_str = claims.tf_actor_type.as_deref().unwrap_or("human");
        let actor_type = match actor_type_str {
            "human" => ActorType::Human,
            "agent" => ActorType::Agent,
            "device" => ActorType::Device,
            "service" => ActorType::Service,
            "site" => ActorType::Site,
            "organization" => ActorType::Organization,
            other => {
                return Err(BridgeError::Rejected(format!(
                    "unsupported tf_actor_type: {}",
                    other
                )))
            }
        };
        let encoded_subject = encode_subject(&subject);
        let actor_id = format!(
            "tf:actor:{}:{}/{}",
            actor_type_str, self.cfg.trust_domain, encoded_subject
        );

        let identity = ActorIdentity {
            identity_version: ActorIdentity_IdentityVersion::V1,
            actor_id,
            actor_type,
            instance_id: None,
            public_keys: vec![project_jwk_to_public_key(jwk)?],
            trust_levels: vec![TrustLevel::T3],
            authority_roots: vec![AuthorityRoot {
                kind: AuthorityRoot_Kind::Organization,
                id: self.cfg.issuer.clone(),
            }],
            attestations: None,
            valid_from: claims
                .iat
                .map(timestamp)
                .unwrap_or_else(|| timestamp(now_unix())),
            valid_until: claims.exp.map(timestamp),
            revocation_ref: None,
            signature: None,
        };

        let capabilities = scopes_from_claims(&claims);

        Ok(OAuthVerificationResult {
            identity,
            capabilities,
            claims,
        })
    }
}

impl Bridge for OAuthBridge {
    fn bridge_id(&self) -> &str {
        &self.cfg.bridge_id
    }
    fn kind(&self) -> BridgeKind {
        BridgeKind::Oauth
    }
    fn trust_domain(&self) -> &str {
        &self.cfg.trust_domain
    }
}

fn decoding_key_for(jwk: &Jwk) -> Result<DecodingKey, BridgeError> {
    match jwk.kty.as_str() {
        "EC" => {
            let x = jwk
                .x
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("EC JWK missing x".into()))?;
            let y = jwk
                .y
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("EC JWK missing y".into()))?;
            DecodingKey::from_ec_components(x, y)
                .map_err(|e| BridgeError::InvalidInput(format!("bad EC components: {}", e)))
        }
        "RSA" => {
            let n = jwk
                .n
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("RSA JWK missing n".into()))?;
            let e = jwk
                .e
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("RSA JWK missing e".into()))?;
            DecodingKey::from_rsa_components(n, e)
                .map_err(|e| BridgeError::InvalidInput(format!("bad RSA components: {}", e)))
        }
        "OKP" => {
            let x = jwk
                .x
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("OKP JWK missing x".into()))?;
            DecodingKey::from_ed_components(x)
                .map_err(|e| BridgeError::InvalidInput(format!("bad OKP components: {}", e)))
        }
        other => Err(BridgeError::InvalidInput(format!(
            "unsupported kty {}",
            other
        ))),
    }
}

fn encode_subject(s: &str) -> String {
    // Percent-encode anything outside the unreserved RFC 3986 set so the
    // subject can be embedded in an actor URI path segment.
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char);
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

fn scopes_from_claims(claims: &OAuthClaims) -> Vec<String> {
    match &claims.scope {
        Some(Value::String(s)) => s.split_whitespace().map(str::to_string).collect(),
        Some(Value::Array(arr)) => arr
            .iter()
            .filter_map(|v| v.as_str().map(str::to_string))
            .collect(),
        _ => Vec::new(),
    }
}

fn timestamp(t: u64) -> String {
    // Format as RFC 3339 UTC.
    let datetime = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t);
    let secs = datetime
        .duration_since(std::time::UNIX_EPOCH)
        .expect("post-epoch")
        .as_secs() as i64;
    // Build YYYY-MM-DDTHH:MM:SSZ from secs without bringing chrono in.
    let (year, month, day, hour, minute, second) = secs_to_ymdhms(secs);
    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, month, day, hour, minute, second
    )
}

fn now_unix() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn secs_to_ymdhms(secs: i64) -> (i32, u32, u32, u32, u32, u32) {
    // Civil-from-days algorithm by Howard Hinnant.
    let days = secs.div_euclid(86_400);
    let time = secs.rem_euclid(86_400);
    let hour = (time / 3600) as u32;
    let minute = ((time % 3600) / 60) as u32;
    let second = (time % 60) as u32;

    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = if mp < 10 {
        (mp + 3) as u32
    } else {
        (mp - 9) as u32
    };
    let year = if m <= 2 { y + 1 } else { y };
    (year as i32, m, d, hour, minute, second)
}

pub fn parse_algorithm(name: &str) -> Result<Algorithm, BridgeError> {
    Algorithm::parse(name).map_err(|e| BridgeError::InvalidInput(e.to_string()))
}

/// Project a JWK into the TrustForge `PublicKey` shape (raw bytes,
/// base64-encoded, with the algorithm name normalised to TrustForge's
/// vocabulary). Mirrors the TS `projectJwkToPublicKey`.
pub fn project_jwk_to_public_key(jwk: &Jwk) -> Result<PublicKey, BridgeError> {
    use crate::encoding::{STANDARD, URL_SAFE_NO_PAD};
    let key_id = jwk
        .kid
        .clone()
        .unwrap_or_else(|| "oauth-bridge-bearer".to_string());
    match jwk.kty.as_str() {
        "OKP" => {
            // Ed25519 — raw 32-byte x.
            let x = jwk
                .x
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("OKP JWK missing x".into()))?;
            let bytes = URL_SAFE_NO_PAD
                .decode(x)
                .map_err(|e| BridgeError::InvalidInput(format!("base64url x: {}", e)))?;
            Ok(PublicKey {
                key_id,
                algorithm: "ed25519".into(),
                public_key: STANDARD.encode(bytes),
                purpose: PublicKey_Purpose::Signing,
                valid_from: None,
                valid_until: None,
            })
        }
        "EC" => {
            let x = jwk
                .x
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("EC JWK missing x".into()))?;
            let y = jwk
                .y
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("EC JWK missing y".into()))?;
            let xb = URL_SAFE_NO_PAD
                .decode(x)
                .map_err(|e| BridgeError::InvalidInput(format!("base64url x: {}", e)))?;
            let yb = URL_SAFE_NO_PAD
                .decode(y)
                .map_err(|e| BridgeError::InvalidInput(format!("base64url y: {}", e)))?;
            let mut sec1 = Vec::with_capacity(1 + xb.len() + yb.len());
            sec1.push(0x04);
            sec1.extend_from_slice(&xb);
            sec1.extend_from_slice(&yb);
            let crv = jwk.crv.as_deref().unwrap_or("");
            let alg = match crv {
                "P-256" => "p256",
                "P-384" => "p384",
                "P-521" => "p521",
                _ => "ec",
            };
            Ok(PublicKey {
                key_id,
                algorithm: alg.into(),
                public_key: STANDARD.encode(sec1),
                purpose: PublicKey_Purpose::Signing,
                valid_from: None,
                valid_until: None,
            })
        }
        "RSA" => {
            let n = jwk
                .n
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("RSA JWK missing n".into()))?;
            let e = jwk
                .e
                .as_ref()
                .ok_or_else(|| BridgeError::InvalidInput("RSA JWK missing e".into()))?;
            let nb = URL_SAFE_NO_PAD
                .decode(n)
                .map_err(|err| BridgeError::InvalidInput(format!("base64url n: {}", err)))?;
            let eb = URL_SAFE_NO_PAD
                .decode(e)
                .map_err(|err| BridgeError::InvalidInput(format!("base64url e: {}", err)))?;
            let der = encode_rsa_spki(&nb, &eb);
            Ok(PublicKey {
                key_id,
                algorithm: "rsa".into(),
                public_key: STANDARD.encode(der),
                purpose: PublicKey_Purpose::Signing,
                valid_from: None,
                valid_until: None,
            })
        }
        other => Err(BridgeError::Unsupported(format!(
            "unsupported JWK kty: {}",
            other
        ))),
    }
}

fn encode_rsa_spki(n: &[u8], e: &[u8]) -> Vec<u8> {
    let rsa_public_key = der_sequence(&[der_integer(n), der_integer(e)]);
    let oid_rsa_encryption: [u8; 11] = [
        0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,
    ];
    let null_params: [u8; 2] = [0x05, 0x00];
    let alg_id = der_sequence(&[oid_rsa_encryption.to_vec(), null_params.to_vec()]);
    let mut bit_string_body = Vec::with_capacity(1 + rsa_public_key.len());
    bit_string_body.push(0x00);
    bit_string_body.extend_from_slice(&rsa_public_key);
    let mut bit_string = Vec::with_capacity(2 + bit_string_body.len());
    bit_string.push(0x03);
    bit_string.extend_from_slice(&der_len(bit_string_body.len()));
    bit_string.extend_from_slice(&bit_string_body);
    der_sequence(&[alg_id, bit_string])
}

fn der_sequence(parts: &[Vec<u8>]) -> Vec<u8> {
    let body: Vec<u8> = parts.iter().flat_map(|p| p.clone()).collect();
    let mut out = Vec::with_capacity(2 + body.len());
    out.push(0x30);
    out.extend_from_slice(&der_len(body.len()));
    out.extend_from_slice(&body);
    out
}

fn der_integer(bytes: &[u8]) -> Vec<u8> {
    let mut start = 0usize;
    while start < bytes.len() - 1 && bytes[start] == 0 {
        start += 1;
    }
    let payload = &bytes[start..];
    let needs_pad = payload[0] & 0x80 != 0;
    let len = payload.len() + if needs_pad { 1 } else { 0 };
    let mut out = Vec::with_capacity(2 + len);
    out.push(0x02);
    out.extend_from_slice(&der_len(len));
    if needs_pad {
        out.push(0x00);
    }
    out.extend_from_slice(payload);
    out
}

fn der_len(n: usize) -> Vec<u8> {
    if n < 0x80 {
        return vec![n as u8];
    }
    let mut bytes = Vec::new();
    let mut v = n;
    while v > 0 {
        bytes.insert(0, (v & 0xff) as u8);
        v >>= 8;
    }
    let mut out = Vec::with_capacity(1 + bytes.len());
    out.push(0x80 | bytes.len() as u8);
    out.extend_from_slice(&bytes);
    out
}