dmsg_protocol 0.1.1

Deterministic encoding, COSE document verification, and approval helpers for dMsg
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
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Agent Delegation 1.0 rules for hosted controllers and principal publication.
//!
//! Strict I-JSON, JCS, SHA3-256 event hashes and the Agent Delegation payload
//! rules come from the pinned `agent-protocols` SDK. This module adds dMsg's
//! hosted-signing policy and renders the principal document the directory
//! serves. It performs no network access and authorizes nothing by itself.
use crate::*;
use agent_protocols::{delegation as sdk, identity as sdk_id};
use dmsg_types::{agent::*, *};
use std::collections::BTreeSet;

/// Maximum display label length in bytes (64).
pub const MAX_CONTROLLER_NAME_BYTES: usize = 64;
/// Maximum scopes in a restricted ceiling (8).
pub const MAX_CEILING_SCOPES: usize = 8;
/// Maximum audiences in a restricted ceiling (4).
pub const MAX_CEILING_AUDIENCES: usize = 4;
/// Maximum bytes of one scope string (64).
pub const MAX_SCOPE_BYTES: usize = 64;
/// Maximum bytes of one audience string (256).
pub const MAX_AUDIENCE_BYTES: usize = 256;
/// Hosted signing accepts `created_at` at most this far in the past (60 s).
pub const EVENT_PAST_SKEW: u64 = 60 * SECOND;
/// Hosted signing accepts `created_at` at most this far in the future (5 s).
pub const EVENT_FUTURE_SKEW: u64 = 5 * SECOND;

fn sdk_error(error: agent_protocols::SdkError) -> Error {
    Error::InvalidInput(error.to_string())
}

fn millis(value: u64) -> Result<i64> {
    ensure_valid(value <= sdk_id::MAX_SAFE_NONCE, "timestamp")?;
    Ok(value as i64)
}

/// Agent ID (`did:agent:` + unpadded base64url) of a raw Ed25519 public key.
pub fn agent_id(public_key: &Hash) -> String {
    sdk_id::AgentId::from_public_key(public_key).to_string()
}

/// Validate a principal origin: an exact serialized HTTPS origin without a path.
///
/// # Errors
/// Anything else returns `Error::InvalidInput`.
pub fn validate_principal_origin(origin: &str) -> Result<()> {
    sdk_id::validate_origin(origin).map_err(sdk_error)
}

/// Canonical principal URL of an account: `origin/<account_id>`.
/// The origin must already satisfy [`validate_principal_origin`].
pub fn principal_id(origin: &str, account_id: &AccountId) -> String {
    format!("{origin}/{account_id}")
}

/// Required prefix of delegation IDs signed by an account's hosted keys.
/// The prefix routes credential reads to the account without a global index.
pub fn delegation_id_prefix(account_id: &AccountId) -> String {
    format!("{account_id}.")
}

/// SHA3-256 of exact event bytes: the 32-byte message a controller signs.
/// Only meaningful for bytes already accepted by [`parse_delegation_event`].
pub fn event_hash(bytes: &[u8]) -> Hash {
    use sha3::Digest;
    Hash::new(sha3::Sha3_256::digest(bytes).into())
}

/// Grant fields that hosted-signing policy checks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DelegationGrant {
    /// Granted scopes.
    pub scopes: Vec<String>,
    /// Granted relying-party audiences.
    pub audiences: Vec<String>,
    /// Optional validity start.
    pub not_before: Option<u64>,
    /// Optional validity end.
    pub expires_at: Option<u64>,
    /// JCS size of `constraints`, or zero when absent.
    pub constraints_bytes: usize,
}

/// A strictly parsed Agent Delegation event and its SHA3-256 event hash.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DelegationEvent {
    /// SHA3-256 of the exact event bytes: the 32-byte message that is signed.
    pub hash: Hash,
    /// Raw Ed25519 public key of `actor`.
    pub actor: Hash,
    /// Signer-chosen creation time.
    pub created_at: u64,
    /// Agent Identity nonce of the actor.
    pub nonce: u64,
    /// Principal named by the payload.
    pub principal_id: String,
    /// Delegation ID named by the payload.
    pub id: String,
    /// Grant fields, or None for `delegation.revoke`.
    pub grant: Option<DelegationGrant>,
}

/// Strictly parse one Agent Delegation event from its exact JCS bytes.
///
/// Rejects anything but the six Agent Identity event fields, duplicate member
/// names, unpaired surrogates, unsafe integers, noncanonical text, unknown or
/// explicitly null payload members, and payloads that break Agent Delegation
/// Section 7. The bytes must be the JCS form, so their SHA3-256 is the event hash.
///
/// # Errors
/// Oversized input returns `Error::QuotaExceeded`, a foreign protocol or type
/// `Error::UnsupportedProtocol`, and any other violation `Error::InvalidInput`.
pub fn parse_delegation_event(bytes: &[u8]) -> Result<DelegationEvent> {
    ensure(bytes.len() <= MAX_AGENT_EVENT_BYTES, Error::QuotaExceeded)?;
    let text = std::str::from_utf8(bytes).map_err(|_| invalid("event is not UTF-8"))?;
    let value = sdk_id::parse_strict_json(text).map_err(sdk_error)?;
    let event: sdk_id::Event<sdk::DelegationPayload> =
        serde_json::from_value(value).map_err(|error| Error::InvalidInput(error.to_string()))?;
    ensure(
        event.protocol == AGENT_DELEGATION_PROTOCOL,
        Error::UnsupportedProtocol,
    )?;
    sdk_id::validate_event_fields(&event, &[]).map_err(sdk_error)?;
    // Typed re-encoding drops unknown payload members and explicit nulls, so the
    // exact-bytes comparison also closes the payload object.
    ensure_valid(
        sdk_id::canonical_event_bytes(&event).map_err(sdk_error)? == bytes,
        "event is not canonical JCS",
    )?;
    // Validates the nonce range; equals event_hash(bytes) for canonical bytes.
    let hash = sdk_id::event_hash_bytes(&event).map_err(sdk_error)?;
    let created_at = u64::try_from(event.created_at).map_err(|_| invalid("created_at"))?;
    let actor = event.actor.public_key_bytes().map_err(sdk_error)?;
    let (principal_id, id, grant) = match (event.kind.as_str(), &event.payload) {
        (sdk::DELEGATION_GRANT, sdk::DelegationPayload::Grant(payload)) => {
            sdk::validate_delegation_grant_payload(payload, Some(event.created_at))
                .map_err(sdk_error)?;
            let constraints_bytes = match &payload.constraints {
                Some(constraints) => serde_jcs::to_vec(constraints)
                    .map_err(|error| Error::InvalidInput(error.to_string()))?
                    .len(),
                None => 0,
            };
            let time = |value: Option<i64>| {
                value
                    .map(|t| u64::try_from(t).map_err(|_| invalid("timestamp")))
                    .transpose()
            };
            (
                payload.principal_id.clone(),
                payload.id.clone(),
                Some(DelegationGrant {
                    scopes: payload.scopes.clone(),
                    audiences: payload.audiences.clone(),
                    not_before: time(payload.not_before)?,
                    expires_at: time(payload.expires_at)?,
                    constraints_bytes,
                }),
            )
        }
        (sdk::DELEGATION_REVOKE, sdk::DelegationPayload::Revoke(payload)) => {
            sdk::validate_delegation_revoke_payload(payload).map_err(sdk_error)?;
            (payload.principal_id.clone(), payload.id.clone(), None)
        }
        (sdk::DELEGATION_GRANT | sdk::DELEGATION_REVOKE, _) => {
            return Err(invalid("event type does not match its payload"))
        }
        _ => return Err(Error::UnsupportedProtocol),
    };
    Ok(DelegationEvent {
        hash: Hash::new(hash),
        actor: Hash::new(actor),
        created_at,
        nonce: event.nonce,
        principal_id,
        id,
        grant,
    })
}

/// dMsg hosted-signing policy for one parsed event.
///
/// The controller must be current and be the actor; the payload must name this
/// principal and an ID under the account prefix; `created_at` must be within
/// `[now - 60 s, now + 5 s]` and not before `valid_from`. A grant must stay
/// within a restricted ceiling, carry `expires_at` at most 366 days after
/// `created_at`, and keep `constraints` within 4 KiB. Revocation lineage and
/// credential state are checked by the delegation service at acceptance.
///
/// # Errors
/// A retired or foreign controller returns `Error::Forbidden`, mismatched
/// identities `Error::IntegrityFailed`, a stale or future time `Error::Expired`,
/// and a policy violation `Error::InvalidInput`.
pub fn check_hosted_event(
    event: &DelegationEvent,
    account_id: &AccountId,
    principal_id: &str,
    controller: &HostedController,
    now: u64,
) -> Result<()> {
    ensure(controller.retired_at.is_none(), Error::Forbidden)?;
    ensure(
        event.actor == controller.public_key && event.principal_id == principal_id,
        Error::IntegrityFailed,
    )?;
    ensure_valid(
        event
            .id
            .strip_prefix(&delegation_id_prefix(account_id))
            .is_some_and(|suffix| !suffix.is_empty()),
        "delegation id must start with the account prefix",
    )?;
    ensure(
        event.created_at >= controller.valid_from
            && event.created_at.saturating_add(EVENT_PAST_SKEW) >= now
            && event.created_at <= now.saturating_add(EVENT_FUTURE_SKEW),
        Error::Expired,
    )?;
    if let Some(grant) = &event.grant {
        if let DelegationAuthority::Restricted { scopes, audiences } = &controller.delegation {
            ensure(
                grant.scopes.iter().all(|s| scopes.contains(s))
                    && grant.audiences.iter().all(|a| audiences.contains(a)),
                Error::Forbidden,
            )?;
        }
        ensure_valid(
            grant.expires_at.is_some_and(|expires_at| {
                expires_at > event.created_at && expires_at - event.created_at <= MAX_GRANT_LIFETIME
            }),
            "grant expires_at is required within 366 days",
        )?;
        ensure_valid(
            grant.constraints_bytes <= MAX_GRANT_CONSTRAINTS_BYTES,
            "grant constraints are too large",
        )?;
    }
    Ok(())
}

fn validate_authority(authority: &DelegationAuthority) -> Result<()> {
    let DelegationAuthority::Restricted { scopes, audiences } = authority else {
        return Ok(());
    };
    let unique = |values: &[String]| {
        let mut seen = BTreeSet::new();
        values.iter().all(|value| seen.insert(value))
    };
    ensure_valid(
        (1..=MAX_CEILING_SCOPES).contains(&scopes.len())
            && (1..=MAX_CEILING_AUDIENCES).contains(&audiences.len())
            && unique(scopes)
            && unique(audiences)
            && scopes
                .iter()
                .all(|s| s.len() <= MAX_SCOPE_BYTES && !s.trim().is_empty() && s != "*")
            && audiences.iter().all(|a| a.len() <= MAX_AUDIENCE_BYTES),
        "delegation ceiling",
    )?;
    for audience in audiences {
        sdk::validate_audience(audience).map_err(sdk_error)?;
    }
    Ok(())
}

/// Validate a controller label: 1..64 bytes, not blank, no control characters.
///
/// # Errors
/// Invalid labels return `Error::InvalidInput`.
pub fn validate_controller_name(name: &str) -> Result<()> {
    ensure_valid(
        !name.trim().is_empty()
            && name.len() <= MAX_CONTROLLER_NAME_BYTES
            && !name.chars().any(char::is_control),
        "controller name",
    )
}

/// Validate the invariants of a principal state before it is committed or published.
///
/// Generations are unique and ascending, record counts are bounded, a key
/// appears once, current records carry no retirement fields, retirement and
/// compromise intervals are ordered, every `supersedes` entry names an earlier
/// record, and every timestamp is at or before `updated_at`.
///
/// # Errors
/// Violations return `Error::InvalidInput` or, for count limits, `Error::QuotaExceeded`.
pub fn validate_principal_state(state: &PrincipalState) -> Result<()> {
    ensure(
        state.controllers.len() <= MAX_CONTROLLER_RECORDS
            && state
                .controllers
                .iter()
                .filter(|c| c.retired_at.is_none())
                .count()
                <= MAX_CURRENT_CONTROLLERS,
        Error::QuotaExceeded,
    )?;
    millis(state.updated_at)?;
    let mut keys = BTreeSet::new();
    for (index, c) in state.controllers.iter().enumerate() {
        ensure_valid(
            c.generation > 0
                && index
                    .checked_sub(1)
                    .is_none_or(|p| state.controllers[p].generation < c.generation)
                && keys.insert(c.public_key),
            "controller generation/key",
        )?;
        crate::validate_ed25519_key(c.public_key.as_slice())?;
        if let Some(name) = &c.name {
            validate_controller_name(name)?;
        }
        validate_authority(&c.delegation)?;
        ensure_valid(c.valid_from <= state.updated_at, "valid_from")?;
        match c.retired_at {
            Some(retired_at) => ensure_valid(
                c.valid_from <= retired_at
                    && retired_at <= state.updated_at
                    && c.invalid_from
                        .is_none_or(|t| c.valid_from <= t && t <= retired_at),
                "retirement interval",
            )?,
            None => ensure_valid(c.invalid_from.is_none(), "current controller")?,
        }
        let mut seen = BTreeSet::new();
        for generation in &c.supersedes {
            ensure_valid(
                seen.insert(*generation)
                    && state.controllers[..index]
                        .iter()
                        .any(|p| p.generation == *generation && p.valid_from < c.valid_from),
                "supersedes",
            )?;
        }
    }
    Ok(())
}

fn principal_type(value: &PrincipalType) -> &'static str {
    match value {
        PrincipalType::Person => "person",
        PrincipalType::Organization => "organization",
        PrincipalType::Team => "team",
        PrincipalType::Project => "project",
        PrincipalType::Other => "other",
    }
}

/// Render the exact JCS principal document the directory serves for an account.
///
/// The document names `principal_origin/<account_id>` as its `id`, lists
/// current and retired hosted controllers with the configured `source`, the
/// configured `delegation_query_url`, and one `profile` link. It is checked with
/// the SDK's `validate_principal_document` before the bytes are returned.
///
/// # Errors
/// Invalid state or configuration returns `Error::InvalidInput` or `Error::QuotaExceeded`.
pub fn render_principal_document(
    config: &DirectoryInit,
    account_id: &AccountId,
    state: &PrincipalState,
) -> Result<Vec<u8>> {
    validate_principal_state(state)?;
    let key = |generation: u32| {
        state
            .controllers
            .iter()
            .find(|c| c.generation == generation)
            .map(|c| sdk_id::AgentId::from_public_key(&c.public_key))
            .ok_or_else(|| invalid("supersedes"))
    };
    let mut controllers = Vec::new();
    let mut retired_controllers = Vec::new();
    for c in &state.controllers {
        let record = sdk::Controller {
            id: sdk_id::AgentId::from_public_key(&c.public_key),
            source: config.controller_source.clone(),
            valid_from: millis(c.valid_from)?,
            name: c.name.clone(),
            delegation: Some(match &c.delegation {
                DelegationAuthority::Unrestricted => {
                    sdk::DelegationAuthority::Unrestricted("*".into())
                }
                DelegationAuthority::Restricted { scopes, audiences } => {
                    sdk::DelegationAuthority::Restricted(sdk::DelegationPolicy {
                        scopes: scopes.clone(),
                        audiences: audiences.clone(),
                    })
                }
            }),
            supersedes: (!c.supersedes.is_empty())
                .then(|| c.supersedes.iter().map(|g| key(*g)).collect::<Result<_>>())
                .transpose()?,
            retired_at: c.retired_at.map(millis).transpose()?,
            invalid_from: c.invalid_from.map(millis).transpose()?,
        };
        if c.retired_at.is_some() {
            retired_controllers.push(record);
        } else {
            controllers.push(record);
        }
    }
    let document = sdk::PrincipalDocument {
        id: principal_id(&config.principal_origin, account_id),
        kind: Some(principal_type(&state.principal_type).into()),
        name: None,
        description: None,
        avatar_url: None,
        aliases: vec![],
        links: vec![sdk::PrincipalLink {
            name: "dMsg".into(),
            url: format!("{}{account_id}", config.profile_url_prefix),
            rel: "profile".into(),
        }],
        protocol: AGENT_DELEGATION_PROTOCOL.into(),
        controllers,
        retired_controllers,
        delegation_query_url: Some(config.delegation_query_url.clone()),
        updated_at: millis(state.updated_at)?,
        extra: Default::default(),
    };
    sdk::validate_principal_document(&document).map_err(sdk_error)?;
    serde_jcs::to_vec(&document).map_err(|error| Error::InvalidInput(error.to_string()))
}

/// Validate a directory configuration without accessing any canister.
///
/// Requires a valid issuer namespace, 1..16 distinct authenticated user homes,
/// HTTPS origins for principals and controller source, an HTTPS query URL, an
/// HTTPS profile prefix ending in `/`, and 0..8 domain names.
///
/// # Errors
/// Invalid configuration returns `Error::InvalidInput` or `Error::AuthRequired`.
pub fn validate_directory_init(config: &DirectoryInit) -> Result<()> {
    validate_namespace(&config.issuer_namespace)?;
    ensure_valid(
        (1..=16).contains(&config.user_homes.len())
            && config.custom_domains.len() <= 8
            && config.custom_domains.iter().all(|d| {
                !d.is_empty()
                    && d.len() <= 253
                    && d.bytes().all(|b| {
                        b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-'
                    })
            }),
        "directory homes/domains",
    )?;
    for (index, home) in config.user_homes.iter().enumerate() {
        authenticated(*home)?;
        ensure_valid(!config.user_homes[..index].contains(home), "duplicate home")?;
    }
    validate_principal_origin(&config.principal_origin)?;
    sdk_id::validate_origin(&config.controller_source).map_err(sdk_error)?;
    for url in [&config.delegation_query_url, &config.profile_url_prefix] {
        let parsed = url::Url::parse(url).map_err(|_| invalid("directory URL"))?;
        ensure_valid(
            parsed.scheme() == "https"
                && parsed.as_str() == url.as_str()
                && parsed.query().is_none()
                && parsed.fragment().is_none(),
            "directory URL",
        )?;
    }
    ensure_valid(config.profile_url_prefix.ends_with('/'), "profile prefix")
}

/// Digest committing to an account-ID allocator's deployment namespace.
///
/// The first five bytes are the allocator fingerprint embedded at bytes 4..9 of
/// every account ID the user home allocates, which lets the directory route an
/// account to the home that created it.
pub fn account_allocator_digest(
    environment: &Environment,
    namespace: &str,
    canister: candid::Principal,
) -> Hash {
    digest(
        "dmsg/account-id-generator/v1",
        &("dmsg", environment, namespace, canister),
    )
}

/// Whether an account ID was allocated by the home with this allocator digest.
pub fn allocated_by(account_id: &AccountId, allocator_digest: &Hash) -> bool {
    account_id.as_slice()[4..9] == allocator_digest[..5]
}

#[cfg(test)]
#[path = "agent_tests.rs"]
mod tests;