heddle-api 0.31.0-alpha.41

Generated transport-neutral Rust types for the Heddle public API
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
//! Portable notification delivery gates. Hosts must run these before either
//! settings replacement or capability-authorized unsubscribe, then independently
//! check authorization, destination verification and expected_version. These
//! gates complement remaining stored-settings validation: hosts must also check
//! timezone, selectors, duplicate overrides and input budgets.

use crate::heddle::api::common::{CallFailureCode, ErrorReason};
use crate::heddle::api::v1alpha2::{
    EffectiveDelivery, NotificationPreferences, NotificationRule,
    SetNotificationPreferencesRequest, SpoolRef, UnsubscribeNotificationsRequest,
    effective_delivery::Source,
    notification_rule::{Channel, Delivery},
};

pub const MAX_EFFECTIVE_DELIVERIES: usize = 4096;
pub const MAX_NOTIFICATION_PREFERENCES_BYTES: usize = 1024 * 1024;
pub const LOCKED_EMAIL_KINDS: &[&str] = &["account_security", "security_surface"];

#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum NotificationValidationError {
    #[error("unknown channel or unspecified/unknown delivery")]
    InvalidRule,
    #[error("DIGEST requires the email channel")]
    DigestRequiresEmail,
    #[error("digest interval must be zero, one hour, one day or one week with zero nanos")]
    InvalidDigestInterval,
    #[error("security/recovery email must remain IMMEDIATE")]
    LockedEmail,
    #[error("unsubscribe requires DISABLED delivery")]
    UnsubscribeDelivery,
    #[error("notification preferences exceed the read projection bound")]
    ProjectionTooLarge,
    #[error("ancestor chain must be complete, acyclic and within the host's 64/128-node bound")]
    InvalidAncestry,
    #[error("invalid or unauthorized delivery provenance")]
    InvalidSource,
}

impl NotificationValidationError {
    pub const fn code(self) -> CallFailureCode {
        match self {
            Self::LockedEmail | Self::InvalidAncestry => CallFailureCode::FailedPrecondition,
            Self::ProjectionTooLarge => CallFailureCode::ResourceExhausted,
            _ => CallFailureCode::InvalidArgument,
        }
    }

    pub const fn reason(self) -> ErrorReason {
        match self {
            Self::LockedEmail | Self::InvalidAncestry => ErrorReason::PolicyDenied,
            Self::ProjectionTooLarge => ErrorReason::QuotaExceeded,
            _ => ErrorReason::FieldInvalid,
        }
    }
}

/// Check selector/channel semantics. Wildcard OFF rules that include locked
/// email kinds are rejected rather than silently overriding the user's request.
/// After enum validation, the email lock takes precedence over email-only DIGEST.
pub fn validate_notification_rule(
    rule: &NotificationRule,
) -> Result<(), NotificationValidationError> {
    let channel =
        Channel::try_from(rule.channel).map_err(|_| NotificationValidationError::InvalidRule)?;
    let delivery =
        Delivery::try_from(rule.delivery).map_err(|_| NotificationValidationError::InvalidRule)?;
    if delivery == Delivery::Unspecified {
        return Err(NotificationValidationError::InvalidRule);
    }
    let matches_locked = rule.kind.is_empty()
        || rule.kind == "*"
        || LOCKED_EMAIL_KINDS.contains(&rule.kind.as_str());
    if matches_locked
        && matches!(channel, Channel::Email | Channel::Unspecified)
        && delivery != Delivery::Immediate
    {
        return Err(NotificationValidationError::LockedEmail);
    }
    if delivery == Delivery::Digest && channel != Channel::Email {
        return Err(NotificationValidationError::DigestRequiresEmail);
    }
    Ok(())
}

pub fn validate_notification_preferences_write(
    request: &SetNotificationPreferencesRequest,
) -> Result<(), NotificationValidationError> {
    let preferences = request
        .preferences
        .as_ref()
        .ok_or(NotificationValidationError::InvalidRule)?;
    if let Some(interval) = &preferences.digest_interval {
        validate_digest_interval(interval)?;
    }
    for digest_override in &preferences.digest_overrides {
        let interval = digest_override
            .digest_interval
            .as_ref()
            .ok_or(NotificationValidationError::InvalidDigestInterval)?;
        validate_digest_interval(interval)?;
    }
    for rule in &preferences.rules {
        validate_notification_rule(rule)?;
    }
    Ok(())
}

/// Settings write gate with the resolved system-root identity. Hosts must use
/// this gate (or equivalent scope validation) to forbid system-root rules.
pub fn validate_notification_preferences_write_for_system_root(
    request: &SetNotificationPreferencesRequest,
    system_root: &SpoolRef,
) -> Result<(), NotificationValidationError> {
    validate_notification_preferences_write(request)?;
    if request.preferences.as_ref().is_some_and(|preferences| {
        preferences
            .rules
            .iter()
            .any(|rule| rule.spool.as_ref() == Some(system_root))
    }) {
        return Err(NotificationValidationError::InvalidRule);
    }
    Ok(())
}

fn validate_digest_interval(
    interval: &prost_types::Duration,
) -> Result<(), NotificationValidationError> {
    if interval.nanos != 0 || !matches!(interval.seconds, 0 | 3600 | 86400 | 604800) {
        return Err(NotificationValidationError::InvalidDigestInterval);
    }
    Ok(())
}

pub fn validate_unsubscribe_notifications(
    request: &UnsubscribeNotificationsRequest,
) -> Result<(), NotificationValidationError> {
    for rule in &request.rules {
        validate_notification_rule(rule)?;
        if rule.delivery != Delivery::Disabled as i32 {
            return Err(NotificationValidationError::UnsubscribeDelivery);
        }
    }
    Ok(())
}

/// Validate the documented bound before emitting a preferences read. Stored
/// rules and string lengths count toward the byte cap, not only resolved cells.
pub fn validate_notification_preferences_bound(
    preferences: &NotificationPreferences,
) -> Result<(), NotificationValidationError> {
    use prost::Message;
    if preferences.effective_delivery.len() > MAX_EFFECTIVE_DELIVERIES
        || preferences.encoded_len() > MAX_NOTIFICATION_PREFERENCES_BYTES
    {
        return Err(NotificationValidationError::ProjectionTooLarge);
    }
    Ok(())
}

/// Maximum nodes, including the event spool. Hosts with a 64-node bound pass 64.
pub const MAX_NOTIFICATION_ANCESTORS: usize = 128;

/// Trusted host-loaded ancestry, nearest first. The loader must verify parent
/// links and completeness before calling; never build this from client input or
/// omit unreadable ancestors. The optional shared system root is last.
#[derive(Clone, Debug)]
pub struct NotificationAncestor {
    pub spool: SpoolRef,
    pub readable: bool,
    pub system_root: bool,
}

fn validate_ancestry(
    cell: &EffectiveDelivery,
    ancestors: &[NotificationAncestor],
    ancestor_limit: usize,
) -> Result<(), NotificationValidationError> {
    if !matches!(ancestor_limit, 64 | MAX_NOTIFICATION_ANCESTORS)
        || ancestors.len() > ancestor_limit
        || cell.spool.as_ref() != ancestors.first().map(|level| &level.spool)
        || ancestors.iter().enumerate().any(|(i, level)| {
            level.spool.id.is_empty()
                || ancestors[..i]
                    .iter()
                    .any(|other| other.spool == level.spool)
                || (level.system_root && (i == 0 || i + 1 != ancestors.len()))
        })
    {
        return Err(NotificationValidationError::InvalidAncestry);
    }
    if ancestors.first().is_some_and(|level| !level.readable) {
        return Err(NotificationValidationError::InvalidSource);
    }
    Ok(())
}

/// Resolve one cell from validated settings and trusted complete ancestry.
/// Defaults and effective email cadence are host-owned inputs. Routing and read
/// provenance use the same result; unreadability never changes selection.
/// This plans a projection; hosts still enforce authorization and persist writes.
pub fn resolve_notification_delivery(
    rules: &[NotificationRule],
    cell: &EffectiveDelivery,
    ancestors: &[NotificationAncestor],
    ancestor_limit: usize,
    default_delivery: Delivery,
    digest_enabled: bool,
) -> Result<EffectiveDelivery, NotificationValidationError> {
    validate_ancestry(cell, ancestors, ancestor_limit)?;
    let channel =
        Channel::try_from(cell.channel).map_err(|_| NotificationValidationError::InvalidRule)?;
    if channel == Channel::Unspecified
        || matches!(cell.kind.as_str(), "" | "*")
        || !matches!(cell.actor_origin.as_str(), "" | "human" | "agent")
        || default_delivery == Delivery::Unspecified
        || (default_delivery == Delivery::Digest && channel != Channel::Email)
    {
        return Err(NotificationValidationError::InvalidRule);
    }
    for rule in rules {
        validate_notification_rule(rule)?;
        if ancestors
            .iter()
            .any(|level| level.system_root && rule.spool.as_ref() == Some(&level.spool))
        {
            return Err(NotificationValidationError::InvalidRule);
        }
    }
    let mut selected = None;
    for (i, level) in ancestors
        .iter()
        .enumerate()
        .filter(|(_, level)| !level.system_root)
    {
        if let Some(rule) = best_notification_rule(rules, cell, Some(&level.spool)) {
            let source = if i == 0 {
                Source::Rule
            } else {
                Source::Inherited
            };
            let source_spool = (i > 0 && level.readable).then(|| level.spool.clone());
            selected = Some((rule.delivery, source, source_spool));
            break;
        }
    }
    if selected.is_none() {
        selected = best_notification_rule(rules, cell, None).map(|rule| {
            (
                rule.delivery,
                if cell.spool.is_some() {
                    Source::Account
                } else {
                    Source::Rule
                },
                None,
            )
        });
    }
    let (mut delivery, source, source_spool) =
        selected.unwrap_or((default_delivery as i32, Source::Default, None));
    let locked = channel == Channel::Email && LOCKED_EMAIL_KINDS.contains(&cell.kind.as_str());
    if locked {
        delivery = Delivery::Immediate as i32;
    } else if delivery == Delivery::Digest as i32 && !digest_enabled {
        delivery = Delivery::Disabled as i32;
    }
    Ok(EffectiveDelivery {
        kind: cell.kind.clone(),
        spool: cell.spool.clone(),
        actor_origin: cell.actor_origin.clone(),
        channel: cell.channel,
        delivery,
        source: source as i32,
        locked,
        source_spool,
    })
}

fn best_notification_rule<'a>(
    rules: &'a [NotificationRule],
    cell: &EffectiveDelivery,
    spool: Option<&SpoolRef>,
) -> Option<&'a NotificationRule> {
    let mut best: Option<(u8, &NotificationRule)> = None;
    for rule in rules {
        let exact_kind = !matches!(rule.kind.as_str(), "" | "*");
        let exact_channel = rule.channel != Channel::Unspecified as i32;
        let exact_origin = !matches!(rule.actor_origin.as_str(), "" | "any");
        if rule.spool.as_ref() != spool
            || (exact_kind && rule.kind != cell.kind)
            || (exact_channel && rule.channel != cell.channel)
            || (exact_origin && rule.actor_origin != cell.actor_origin)
        {
            continue;
        }
        let score = u8::from(exact_kind) * 4 + u8::from(exact_channel) * 2 + u8::from(exact_origin);
        if best.is_none_or(|(previous, _)| score > previous) {
            best = Some((score, rule));
        }
    }
    best.map(|(_, rule)| rule)
}

/// Validate provenance before emitting a cell. Hosts must additionally compare
/// against their resolved result: this gate checks disclosure, not rule storage.
pub fn validate_effective_delivery_source(
    cell: &EffectiveDelivery,
    ancestors: &[NotificationAncestor],
    ancestor_limit: usize,
) -> Result<(), NotificationValidationError> {
    validate_ancestry(cell, ancestors, ancestor_limit)?;
    let valid = match Source::try_from(cell.source) {
        Ok(Source::Rule | Source::Default) => cell.source_spool.is_none(),
        Ok(Source::Account) => cell.spool.is_some() && cell.source_spool.is_none(),
        Ok(Source::Inherited) => {
            cell.spool.is_some()
                && ancestors.iter().skip(1).any(|level| {
                    !level.system_root
                        && match &cell.source_spool {
                            Some(spool) => level.readable && spool == &level.spool,
                            None => !level.readable,
                        }
                })
        }
        _ => false,
    };
    if valid {
        Ok(())
    } else {
        Err(NotificationValidationError::InvalidSource)
    }
}

/// Choose scopes BEFORE expanding the kind/origin/channel matrix. The host
/// supplies current readable IDs; rule-free descendants never enter this list.
pub fn notification_projection_scopes(
    request: &crate::heddle::api::v1alpha2::ObserveNotificationsRequest,
    rules: &[NotificationRule],
    readable: &[SpoolRef],
) -> Result<Vec<Option<SpoolRef>>, NotificationValidationError> {
    if let Some(spool) = &request.effective_delivery_spool {
        if !request.include_preferences || spool.id.is_empty() || !readable.contains(spool) {
            return Err(NotificationValidationError::InvalidSource);
        }
        return Ok(vec![Some(spool.clone())]);
    }
    let mut scopes = vec![None];
    for rule in rules {
        if let Some(spool) = &rule.spool
            && readable.contains(spool)
            && !scopes.contains(&Some(spool.clone()))
        {
            scopes.push(Some(spool.clone()));
        }
    }
    Ok(scopes)
}

/// Plan an atomic replacement. Readability and stored settings must be loaded
/// under the same lock/CAS as commit. Clear is caller-account authority only.
/// Host validates storage quotas AFTER preservation, not projection budgets.
pub fn replace_notification_preferences(
    stored: &NotificationPreferences,
    request: &SetNotificationPreferencesRequest,
    readable: &[SpoolRef],
) -> Result<NotificationPreferences, NotificationValidationError> {
    validate_notification_preferences_write(request)?;
    let mut next = request
        .preferences
        .clone()
        .ok_or(NotificationValidationError::InvalidRule)?;
    if next.rules.iter().any(|rule| {
        rule.spool
            .as_ref()
            .is_some_and(|spool| !readable.contains(spool))
    }) || next.digest_overrides.iter().any(|item| {
        item.spool
            .as_ref()
            .is_none_or(|spool| !readable.contains(spool))
    }) {
        return Err(NotificationValidationError::InvalidSource);
    }
    if !request.clear_unreadable_scopes {
        next.rules.extend(
            stored
                .rules
                .iter()
                .filter(|rule| {
                    rule.spool
                        .as_ref()
                        .is_some_and(|spool| !readable.contains(spool))
                })
                .cloned(),
        );
        next.digest_overrides.extend(
            stored
                .digest_overrides
                .iter()
                .filter(|item| {
                    item.spool
                        .as_ref()
                        .is_some_and(|spool| !readable.contains(spool))
                })
                .cloned(),
        );
    }
    next.effective_delivery.clear();
    next.next_digest_at = None;
    for item in &mut next.digest_overrides {
        item.next_digest_at = None;
    }
    Ok(next)
}

/// Invitation-only routing: recipient binding authorizes delivery even without
/// spool read. In particular Decline to a departed inviter MUST use account
/// scope, never InvalidSource and never weaken the ordinary provenance gate.
pub fn resolve_invitation_notification_delivery(
    rules: &[NotificationRule],
    cell: &EffectiveDelivery,
    ancestors: &[NotificationAncestor],
    ancestor_limit: usize,
    default_delivery: Delivery,
    digest_enabled: bool,
) -> Result<EffectiveDelivery, NotificationValidationError> {
    if !matches!(
        cell.kind.as_str(),
        "spool_invitation" | "spool_invitation_declined"
    ) {
        return Err(NotificationValidationError::InvalidRule);
    }
    if cell.spool.is_some() && ancestors.first().is_some_and(|level| !level.readable) {
        let account = EffectiveDelivery {
            spool: None,
            ..cell.clone()
        };
        return resolve_notification_delivery(
            rules,
            &account,
            &[],
            ancestor_limit,
            default_delivery,
            digest_enabled,
        );
    }
    resolve_notification_delivery(
        rules,
        cell,
        ancestors,
        ancestor_limit,
        default_delivery,
        digest_enabled,
    )
}