exochain-node 0.2.1-beta

EXOCHAIN distributed node — single binary for joining and participating in the constitutional governance network
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Session proof-of-possession helpers for 0dentity.
//!
//! Session bootstrap and mutating authenticated requests are signed over
//! domain-tagged CBOR payloads so the same logical authorization challenge has
//! one deterministic byte representation.

#[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
use std::collections::BTreeMap;

use exo_core::types::{Did, Hash256, PublicKey, Signature};
use serde::Serialize;

pub(crate) const BOOTSTRAP_SIGNING_DOMAIN: &str = "exo.zerodentity.session_bootstrap.v1";
#[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
pub(crate) const CLAIM_SUBMISSION_SIGNING_DOMAIN: &str = "exo.zerodentity.claim_submission.v1";
pub(crate) const REQUEST_SIGNING_DOMAIN: &str = "exo.zerodentity.session_request.v1";
pub(crate) const SESSION_TOKEN_DOMAIN: &str = "exo.zerodentity.session_token.v1";
/// Domain-separation tag for the device/behavioral sample proof-of-
/// possession payload (VCG-009). Distinct from
/// [`CLAIM_SUBMISSION_SIGNING_DOMAIN`] because this payload binds different
/// content (sample bytes, not claim routing metadata) — a signature
/// produced for one must never verify against the other.
#[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
pub(crate) const DEVICE_BEHAVIORAL_SUBMISSION_SIGNING_DOMAIN: &str =
    "exo.zerodentity.device_behavioral_submission.v1";

#[derive(Serialize)]
struct BootstrapSigningPayload<'a> {
    domain: &'static str,
    challenge_id: &'a str,
    subject_did: &'a str,
    public_key: &'a PublicKey,
}

#[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
#[derive(Serialize)]
struct ClaimSubmissionSigningPayload<'a> {
    domain: &'static str,
    subject_did: &'a str,
    claim_type: &'a str,
    provider: Option<&'a str>,
    verification_channel: Option<&'a str>,
    created_ms: u64,
    public_key: &'a PublicKey,
}

/// Sample-bound proof-of-possession payload for device/behavioral ingestion
/// (VCG-009). Binds `subject_did`, all three sample fields
/// (`device_fingerprint`, `behavioral_hash`, `signal_hashes`), and the
/// signer's own `public_key` — so a signature only verifies for exactly
/// these sample bytes under exactly this DID. `claim_type`/`created_ms`/
/// `provider`/`consent_receipt_id` are deliberately NOT bound: they are
/// routing metadata or a capability reference checked separately by the
/// consent gate, not sample content.
///
/// `signal_hashes` is a `BTreeMap` so key iteration order is deterministic
/// (required for a canonical, reproducible signing payload) without any
/// extra sorting step.
#[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
#[derive(Serialize)]
struct DeviceBehavioralSubmissionSigningPayload<'a> {
    domain: &'static str,
    subject_did: &'a str,
    device_fingerprint: Option<&'a str>,
    behavioral_hash: Option<&'a str>,
    signal_hashes: &'a BTreeMap<String, String>,
    public_key: &'a PublicKey,
}

#[derive(Serialize)]
struct RequestSigningPayload<'a> {
    domain: &'static str,
    method: &'a str,
    path_and_query: &'a str,
    session_token: &'a str,
    nonce: &'a str,
    body_hash: &'a Hash256,
}

#[derive(Serialize)]
struct SessionTokenPayload<'a> {
    domain: &'static str,
    challenge_id: &'a str,
    subject_did: &'a str,
    public_key: &'a PublicKey,
    bootstrap_signature: &'a Signature,
    hmac_secret: &'a [u8; 32],
}

fn encode_cbor<T: Serialize>(payload: &T) -> Result<Vec<u8>, String> {
    let mut encoded = Vec::new();
    ciborium::into_writer(payload, &mut encoded)
        .map_err(|e| format!("canonical CBOR encoding failed: {e:?}"))?;
    Ok(encoded)
}

pub(crate) fn bootstrap_signing_payload(
    challenge_id: &str,
    subject_did: &Did,
    public_key: &PublicKey,
) -> Result<Vec<u8>, String> {
    encode_cbor(&BootstrapSigningPayload {
        domain: BOOTSTRAP_SIGNING_DOMAIN,
        challenge_id,
        subject_did: subject_did.as_str(),
        public_key,
    })
}

#[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
pub(crate) fn claim_submission_signing_payload(
    subject_did: &Did,
    claim_type: &str,
    provider: Option<&str>,
    verification_channel: Option<&str>,
    created_ms: u64,
    public_key: &PublicKey,
) -> Result<Vec<u8>, String> {
    encode_cbor(&ClaimSubmissionSigningPayload {
        domain: CLAIM_SUBMISSION_SIGNING_DOMAIN,
        subject_did: subject_did.as_str(),
        claim_type,
        provider,
        verification_channel,
        created_ms,
        public_key,
    })
}

/// Builds the canonical, domain-separated CBOR bytes that a device/
/// behavioral sample submission (VCG-009) must be signed over. Every sample
/// field is bound so that swapping any one of them invalidates the
/// signature — see [`DeviceBehavioralSubmissionSigningPayload`] for the
/// binding rationale.
#[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
pub(crate) fn device_behavioral_submission_signing_payload(
    subject_did: &Did,
    device_fingerprint: Option<&str>,
    behavioral_hash: Option<&str>,
    signal_hashes: &BTreeMap<String, String>,
    public_key: &PublicKey,
) -> Result<Vec<u8>, String> {
    encode_cbor(&DeviceBehavioralSubmissionSigningPayload {
        domain: DEVICE_BEHAVIORAL_SUBMISSION_SIGNING_DOMAIN,
        subject_did: subject_did.as_str(),
        device_fingerprint,
        behavioral_hash,
        signal_hashes,
        public_key,
    })
}

pub(crate) fn request_signing_payload(
    method: &str,
    path_and_query: &str,
    session_token: &str,
    nonce: &str,
    body_hash: &Hash256,
) -> Result<Vec<u8>, String> {
    encode_cbor(&RequestSigningPayload {
        domain: REQUEST_SIGNING_DOMAIN,
        method,
        path_and_query,
        session_token,
        nonce,
        body_hash,
    })
}

pub(crate) fn session_token_from_bootstrap(
    challenge_id: &str,
    subject_did: &Did,
    public_key: &PublicKey,
    bootstrap_signature: &Signature,
    hmac_secret: &[u8; 32],
) -> Result<String, String> {
    let encoded = encode_cbor(&SessionTokenPayload {
        domain: SESSION_TOKEN_DOMAIN,
        challenge_id,
        subject_did: subject_did.as_str(),
        public_key,
        bootstrap_signature,
        hmac_secret,
    })?;
    Ok(hex::encode(Hash256::digest(&encoded).as_bytes()))
}

pub(crate) fn public_key_from_hex(value: &str) -> Result<PublicKey, String> {
    let bytes = hex::decode(value).map_err(|_| "public_key must be hex".to_owned())?;
    if bytes.len() != 32 {
        return Err(format!("public_key must be 32 bytes, got {}", bytes.len()));
    }
    if bytes.iter().all(|byte| *byte == 0) {
        return Err("public_key must not be all zero".to_owned());
    }

    let mut public_key = [0u8; 32];
    public_key.copy_from_slice(&bytes);
    Ok(PublicKey::from_bytes(public_key))
}

pub(crate) fn signature_from_hex(value: &str) -> Result<Signature, String> {
    let bytes = hex::decode(value).map_err(|_| "signature must be hex".to_owned())?;
    if bytes.len() != 64 {
        return Err(format!("signature must be 64 bytes, got {}", bytes.len()));
    }

    let mut signature = [0u8; 64];
    signature.copy_from_slice(&bytes);
    Ok(Signature::from_bytes(signature))
}

pub(crate) fn did_from_public_key(public_key: &PublicKey) -> Result<Did, String> {
    let key_hash = Hash256::digest(public_key.as_bytes());
    let method_specific = bs58::encode(key_hash.as_bytes()).into_string();
    Did::new(&format!("did:exo:{method_specific}"))
        .map_err(|e| format!("public key DID derivation failed: {e}"))
}

pub(crate) fn public_key_from_session_bytes(value: &[u8]) -> Result<PublicKey, String> {
    if value.len() != 32 {
        return Err(format!(
            "session public key must be 32 bytes, got {}",
            value.len()
        ));
    }
    if value.iter().all(|byte| *byte == 0) {
        return Err("session public key must not be all zero".to_owned());
    }

    let mut public_key = [0u8; 32];
    public_key.copy_from_slice(value);
    Ok(PublicKey::from_bytes(public_key))
}

#[cfg(test)]
mod tests {
    use std::fmt::Debug;

    use exo_core::types::Hash256;

    use super::*;

    fn must<T, E: Debug>(result: Result<T, E>) -> T {
        match result {
            Ok(value) => value,
            Err(error) => panic!("unexpected error: {error:?}"),
        }
    }

    fn did() -> Did {
        must(Did::new("did:exo:session-auth"))
    }

    fn public_key() -> PublicKey {
        PublicKey::from_bytes([7u8; 32])
    }

    #[test]
    fn bootstrap_payload_is_deterministic() {
        let first = must(bootstrap_signing_payload(
            "challenge-1",
            &did(),
            &public_key(),
        ));
        let second = must(bootstrap_signing_payload(
            "challenge-1",
            &did(),
            &public_key(),
        ));
        assert_eq!(first, second);
    }

    #[test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    fn did_derivation_is_deterministic_and_did_formatted() {
        let first = must(did_from_public_key(&public_key()));
        let second = must(did_from_public_key(&public_key()));

        assert_eq!(first, second);
        assert!(first.as_str().starts_with("did:exo:"));
    }

    #[test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    fn claim_submission_payload_is_domain_separated_and_deterministic() {
        let did = did();
        let first = must(claim_submission_signing_payload(
            &did,
            "Email",
            None,
            Some("Email"),
            123,
            &public_key(),
        ));
        let second = must(claim_submission_signing_payload(
            &did,
            "Email",
            None,
            Some("Email"),
            123,
            &public_key(),
        ));
        let different_time = must(claim_submission_signing_payload(
            &did,
            "Email",
            None,
            Some("Email"),
            124,
            &public_key(),
        ));

        assert_eq!(first, second);
        assert_ne!(first, different_time);
        assert!(
            first
                .windows(CLAIM_SUBMISSION_SIGNING_DOMAIN.len())
                .any(|w| { w == CLAIM_SUBMISSION_SIGNING_DOMAIN.as_bytes() })
        );
    }

    #[test]
    fn request_payload_changes_with_nonce_and_body() {
        let body_a = Hash256::digest(b"a");
        let body_b = Hash256::digest(b"b");
        let first = must(request_signing_payload(
            "POST", "/path", "token", "nonce-1", &body_a,
        ));
        let different_nonce = must(request_signing_payload(
            "POST", "/path", "token", "nonce-2", &body_a,
        ));
        let different_body = must(request_signing_payload(
            "POST", "/path", "token", "nonce-1", &body_b,
        ));

        assert_ne!(first, different_nonce);
        assert_ne!(first, different_body);
    }

    #[test]
    fn session_token_is_deterministic_and_bound_to_bootstrap_material() {
        let did = did();
        let public_key = public_key();
        let signature = Signature::from_bytes([9u8; 64]);
        let secret = [8u8; 32];

        let first = must(session_token_from_bootstrap(
            "challenge-1",
            &did,
            &public_key,
            &signature,
            &secret,
        ));
        let second = must(session_token_from_bootstrap(
            "challenge-1",
            &did,
            &public_key,
            &signature,
            &secret,
        ));
        let different_challenge = must(session_token_from_bootstrap(
            "challenge-2",
            &did,
            &public_key,
            &signature,
            &secret,
        ));
        let different_signature = must(session_token_from_bootstrap(
            "challenge-1",
            &did,
            &public_key,
            &Signature::from_bytes([10u8; 64]),
            &secret,
        ));

        assert_eq!(first, second);
        assert_eq!(first.len(), 64);
        assert_ne!(first, different_challenge);
        assert_ne!(first, different_signature);
    }

    #[test]
    fn parsers_reject_wrong_lengths_and_zero_key() {
        assert!(public_key_from_hex(&hex::encode([0u8; 32])).is_err());
        assert!(public_key_from_hex(&hex::encode([1u8; 31])).is_err());
        assert!(signature_from_hex(&hex::encode([1u8; 63])).is_err());
    }
}