a3s-use-core 0.2.2

Shared typed contracts for A3S Use domains
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
use serde::{Deserialize, Serialize};

use crate::{UseError, UseResult};

use super::host::{validate_request_identity, verify_capabilities, verify_supported_plan_schema};
use super::validation::valid_sha256;
use super::{
    canonical_digest, canonical_json, contract_error, parse_contract, PlanPolicyDecision,
    PluginDesiredState, PluginHostCapabilities, PluginHostPackageState, PluginHostPlanResult,
    PluginManagedScope, PluginOperationConfirmation, PluginOperationPlan, PluginPackageId,
};

pub const PLUGIN_HOST_APPLY_REQUEST_SCHEMA: &str = "a3s.use.plugin-host-apply-request.v1";
pub const PLUGIN_HOST_APPLY_RESULT_SCHEMA: &str = "a3s.use.plugin-host-apply-result.v1";
pub const PLUGIN_HOST_ENABLEMENT_REQUEST_SCHEMA: &str = "a3s.use.plugin-host-enablement-request.v1";
pub const PLUGIN_HOST_ENABLEMENT_RESULT_SCHEMA: &str = "a3s.use.plugin-host-enablement-result.v1";

const APPLY_REQUEST_ERROR: &str = "use.plugin.host_apply_request_invalid";
const APPLY_RESULT_ERROR: &str = "use.plugin.host_apply_result_invalid";
const ENABLEMENT_REQUEST_ERROR: &str = "use.plugin.host_enablement_request_invalid";
const ENABLEMENT_RESULT_ERROR: &str = "use.plugin.host_enablement_result_invalid";

/// Digest-only apply request for a plan already stored by the shared manager.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PluginHostApplyRequest {
    pub schema: String,
    pub request_id: String,
    pub assignment_generation: u64,
    pub capabilities_digest: String,
    pub scope: PluginManagedScope,
    pub package_id: PluginPackageId,
    pub operation_id: String,
    pub plan_digest: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirmation: Option<PluginOperationConfirmation>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PluginHostApplyResult {
    pub schema: String,
    pub request_id: String,
    pub assignment_generation: u64,
    pub capabilities_digest: String,
    pub scope: PluginManagedScope,
    pub package_id: PluginPackageId,
    pub operation_id: String,
    pub plan_digest: String,
    pub completed_at_ms: u64,
    pub operation_result_digest: String,
    pub state: PluginHostPackageState,
    pub replayed: bool,
}

/// Idempotent desired enablement change for one installed package generation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PluginHostEnablementRequest {
    pub schema: String,
    pub request_id: String,
    pub operation_id: String,
    pub assignment_generation: u64,
    pub capabilities_digest: String,
    pub scope: PluginManagedScope,
    pub package_id: PluginPackageId,
    pub expected_package_generation: u64,
    pub enabled: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PluginHostEnablementResult {
    pub schema: String,
    pub request_id: String,
    pub operation_id: String,
    pub assignment_generation: u64,
    pub capabilities_digest: String,
    pub scope: PluginManagedScope,
    pub package_id: PluginPackageId,
    pub completed_at_ms: u64,
    pub operation_result_digest: String,
    pub changed: bool,
    pub state: PluginHostPackageState,
    pub replayed: bool,
}

impl PluginHostApplyRequest {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_contract(
            input,
            "plugin host apply request",
            APPLY_REQUEST_ERROR,
            Self::validate,
        )
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != PLUGIN_HOST_APPLY_REQUEST_SCHEMA {
            return Err(apply_request_error(
                "The plugin host apply request schema is unsupported.",
            ));
        }
        validate_request_identity(
            &self.request_id,
            self.assignment_generation,
            &self.capabilities_digest,
            &self.scope,
        )
        .map_err(|_| {
            apply_request_error("The plugin host apply request identity or scope is invalid.")
        })?;
        PluginOperationPlan::validate_operation_id(&self.operation_id).map_err(|_| {
            apply_request_error("The plugin host apply operation identity is invalid.")
        })?;
        if !valid_sha256(&self.plan_digest) {
            return Err(apply_request_error(
                "The plugin host apply request plan digest is invalid.",
            ));
        }
        if let Some(confirmation) = &self.confirmation {
            confirmation.validate().map_err(|_| {
                apply_request_error("The plugin host apply confirmation is invalid.")
            })?;
            if confirmation.operation_id != self.operation_id
                || confirmation.plan_digest != self.plan_digest
            {
                return Err(apply_request_error(
                    "The confirmation does not bind the requested operation and plan digest.",
                ));
            }
        }
        Ok(())
    }

    pub fn validate_for_plan(
        &self,
        plan: &PluginHostPlanResult,
        capabilities: &PluginHostCapabilities,
    ) -> UseResult<()> {
        self.validate_for_capabilities(capabilities)?;
        plan.validate()?;
        verify_supported_plan_schema(capabilities, &plan.plan.plan.schema)?;
        if self.assignment_generation != plan.assignment_generation
            || self.capabilities_digest != plan.capabilities_digest
            || self.scope != plan.scope
            || self.package_id != plan.package_id
            || self.operation_id != plan.plan.plan.operation_id
            || self.plan_digest != plan.plan.plan_digest
        {
            return Err(UseError::new(
                "use.plugin.host_apply_request_mismatch",
                "The plugin host apply request does not bind the exact reviewed plan.",
            ));
        }
        match (plan.plan.plan.authority.decision, &self.confirmation) {
            (PlanPolicyDecision::Allow, None) | (PlanPolicyDecision::Ask, Some(_)) => Ok(()),
            (PlanPolicyDecision::Deny, _) => Err(UseError::new(
                "use.plugin.plan_denied",
                "Policy denies applying the plugin operation plan.",
            )),
            _ => Err(UseError::new(
                "use.plugin.plan_confirmation_mismatch",
                "The apply request confirmation does not match the plan's policy decision.",
            )),
        }
    }

    /// Validate the request against the exact host contract selected by its
    /// capability digest and managed-scope fence.
    pub fn validate_for_capabilities(
        &self,
        capabilities: &PluginHostCapabilities,
    ) -> UseResult<()> {
        self.validate()?;
        verify_capabilities(&self.capabilities_digest, &self.scope, capabilities)
    }

    /// Perform the canonical lifetime and confirmation check at the host clock.
    pub fn verify_apply_for_plan(
        &self,
        plan: &PluginHostPlanResult,
        capabilities: &PluginHostCapabilities,
        now_ms: u64,
    ) -> UseResult<()> {
        self.validate_for_plan(plan, capabilities)?;
        plan.plan.verify_confirmed_apply(
            &self.operation_id,
            &self.plan_digest,
            self.confirmation.as_ref(),
            now_ms,
        )
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(self, "plugin host apply request", APPLY_REQUEST_ERROR)
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(canonical_digest(&self.canonical_bytes()?))
    }
}

impl PluginHostApplyResult {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_contract(
            input,
            "plugin host apply result",
            APPLY_RESULT_ERROR,
            Self::validate,
        )
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != PLUGIN_HOST_APPLY_RESULT_SCHEMA
            || self.completed_at_ms == 0
            || !valid_sha256(&self.operation_result_digest)
            || !valid_sha256(&self.plan_digest)
        {
            return Err(apply_result_error(
                "The plugin host apply result schema, time, or digest is invalid.",
            ));
        }
        validate_request_identity(
            &self.request_id,
            self.assignment_generation,
            &self.capabilities_digest,
            &self.scope,
        )
        .map_err(|_| {
            apply_result_error("The plugin host apply result identity or scope is invalid.")
        })?;
        PluginOperationPlan::validate_operation_id(&self.operation_id).map_err(|_| {
            apply_result_error("The plugin host apply result operation identity is invalid.")
        })?;
        self.state
            .validate()
            .map_err(|_| apply_result_error("The applied plugin state is invalid."))
    }

    pub fn validate_for(
        &self,
        request: &PluginHostApplyRequest,
        capabilities: &PluginHostCapabilities,
    ) -> UseResult<()> {
        self.validate()?;
        request.validate()?;
        verify_capabilities(&self.capabilities_digest, &self.scope, capabilities)?;
        if self.request_id != request.request_id
            || self.assignment_generation != request.assignment_generation
            || self.capabilities_digest != request.capabilities_digest
            || self.scope != request.scope
            || self.package_id != request.package_id
            || self.operation_id != request.operation_id
            || self.plan_digest != request.plan_digest
        {
            return Err(UseError::new(
                "use.plugin.host_apply_result_mismatch",
                "The plugin host apply result does not bind the exact request.",
            ));
        }
        Ok(())
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(self, "plugin host apply result", APPLY_RESULT_ERROR)
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(canonical_digest(&self.canonical_bytes()?))
    }
}

impl PluginHostEnablementRequest {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_contract(
            input,
            "plugin host enablement request",
            ENABLEMENT_REQUEST_ERROR,
            Self::validate,
        )
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != PLUGIN_HOST_ENABLEMENT_REQUEST_SCHEMA
            || self.expected_package_generation == 0
        {
            return Err(enablement_request_error(
                "The plugin host enablement request schema or generation is invalid.",
            ));
        }
        validate_request_identity(
            &self.request_id,
            self.assignment_generation,
            &self.capabilities_digest,
            &self.scope,
        )
        .map_err(|_| {
            enablement_request_error(
                "The plugin host enablement request identity or scope is invalid.",
            )
        })?;
        PluginOperationPlan::validate_operation_id(&self.operation_id).map_err(|_| {
            enablement_request_error("The plugin host enablement operation identity is invalid.")
        })
    }

    pub fn validate_for_capabilities(
        &self,
        capabilities: &PluginHostCapabilities,
    ) -> UseResult<()> {
        self.validate()?;
        verify_capabilities(&self.capabilities_digest, &self.scope, capabilities)
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(
            self,
            "plugin host enablement request",
            ENABLEMENT_REQUEST_ERROR,
        )
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(canonical_digest(&self.canonical_bytes()?))
    }
}

impl PluginHostEnablementResult {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_contract(
            input,
            "plugin host enablement result",
            ENABLEMENT_RESULT_ERROR,
            Self::validate,
        )
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != PLUGIN_HOST_ENABLEMENT_RESULT_SCHEMA
            || self.completed_at_ms == 0
            || !valid_sha256(&self.operation_result_digest)
        {
            return Err(enablement_result_error(
                "The plugin host enablement result schema, time, or digest is invalid.",
            ));
        }
        validate_request_identity(
            &self.request_id,
            self.assignment_generation,
            &self.capabilities_digest,
            &self.scope,
        )
        .map_err(|_| {
            enablement_result_error(
                "The plugin host enablement result identity or scope is invalid.",
            )
        })?;
        PluginOperationPlan::validate_operation_id(&self.operation_id).map_err(|_| {
            enablement_result_error("The plugin host enablement operation identity is invalid.")
        })?;
        self.state
            .validate()
            .map_err(|_| enablement_result_error("The enabled plugin state is invalid."))?;
        if self.state.desired == PluginDesiredState::Absent {
            return Err(enablement_result_error(
                "Enablement cannot return an absent desired package state.",
            ));
        }
        Ok(())
    }

    pub fn validate_for(
        &self,
        request: &PluginHostEnablementRequest,
        capabilities: &PluginHostCapabilities,
    ) -> UseResult<()> {
        self.validate()?;
        request.validate_for_capabilities(capabilities)?;
        verify_capabilities(&self.capabilities_digest, &self.scope, capabilities)?;
        let expected_desired = if request.enabled {
            PluginDesiredState::Enabled
        } else {
            PluginDesiredState::InstalledDisabled
        };
        let generation = self.state.package_generation.ok_or_else(|| {
            UseError::new(
                "use.plugin.host_enablement_result_mismatch",
                "Enablement did not return an installed package generation.",
            )
        })?;
        let generation_matches = if self.changed {
            generation > request.expected_package_generation
        } else {
            generation == request.expected_package_generation
        };
        if self.request_id != request.request_id
            || self.operation_id != request.operation_id
            || self.assignment_generation != request.assignment_generation
            || self.capabilities_digest != request.capabilities_digest
            || self.scope != request.scope
            || self.package_id != request.package_id
            || self.state.desired != expected_desired
            || !generation_matches
        {
            return Err(UseError::new(
                "use.plugin.host_enablement_result_mismatch",
                "The plugin host enablement result does not bind the exact request and generation.",
            ));
        }
        Ok(())
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(
            self,
            "plugin host enablement result",
            ENABLEMENT_RESULT_ERROR,
        )
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(canonical_digest(&self.canonical_bytes()?))
    }
}

fn apply_request_error(message: impl Into<String>) -> UseError {
    contract_error(APPLY_REQUEST_ERROR, message)
}

fn apply_result_error(message: impl Into<String>) -> UseError {
    contract_error(APPLY_RESULT_ERROR, message)
}

fn enablement_request_error(message: impl Into<String>) -> UseError {
    contract_error(ENABLEMENT_REQUEST_ERROR, message)
}

fn enablement_result_error(message: impl Into<String>) -> UseError {
    contract_error(ENABLEMENT_RESULT_ERROR, message)
}