canic-host 0.109.3

Host-side App build, Fleet install, deployment, and release-set library for Canic workspaces
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
//! Module: install_root::fleet_install_session
//!
//! Responsibility: own the durable Fleet identity and install operation for one fresh install.
//! Does not own: Coordinator, Fleet Subnet Root, Store, Registry, or activation effects.
//! Boundary: exact same-release retries recover one immutable session before any paid effect.

#[cfg(test)]
mod tests;

use crate::{
    durable_io::{
        RegularFileLockError, RegularFileReadError, create_new_bytes_with_parents,
        lock_regular_file_with_parents, read_optional_regular_bytes,
    },
    entropy::{EntropyError, random_bytes_32},
    release_build::{
        FinalizedReleaseBuild, ReleaseBuildPlanError, ReleaseBuildPlanState,
        load_finalized_release_build,
    },
};
use std::{
    io,
    path::{Path, PathBuf},
};

use canic_core::ids::{
    AppId, CanonicalNetworkId, FleetBinding, FleetId, FleetKey, FleetName, ReleaseBuildId,
};
use serde::{Deserialize, Serialize};
use thiserror::Error as ThisError;

const SESSION_FILE: &str = "session.json";
const SESSION_LOCK_FILE: &str = "session.lock";
const SESSION_SCHEMA_VERSION: u32 = 1;
const MAX_SESSION_BYTES: usize = 16_384;

///
/// FleetInstallSession
///
/// Immutable pre-effect identity shared by every journal in one fresh Fleet install.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(super) struct FleetInstallSession {
    pub schema_version: u32,
    pub fleet_name: FleetName,
    pub fleet: FleetBinding,
    pub release_build_id: ReleaseBuildId,
    pub release_build_plan_digest: [u8; 32],
    pub release_set_manifest_digest: [u8; 32],
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: String,
    pub operation_id: [u8; 32],
}

///
/// PlanFleetInstallSessionRequest
///
/// Exact finalized authority required before allocating or recovering a Fleet identity.
///

pub(super) struct PlanFleetInstallSessionRequest<'a> {
    pub root: &'a Path,
    pub canonical_network_id: CanonicalNetworkId,
    pub fleet_name: FleetName,
    pub app: AppId,
    pub finalized_release_build: &'a FinalizedReleaseBuild,
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: &'a str,
}

/// Exact plan/release authority retained for same-release install recovery.
pub(super) struct RecoveredFleetInstallAuthority {
    pub session: FleetInstallSession,
    pub finalized_release_build: FinalizedReleaseBuild,
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: String,
}

///
/// FleetInstallSessionError
///
/// Typed failure while publishing or recovering immutable fresh-install identity.
///

#[derive(Debug, ThisError)]
pub(super) enum FleetInstallSessionError {
    #[error("Fleet install session already has different immutable authority: {path}")]
    ConflictingAuthority { path: PathBuf },

    #[error("failed to access Fleet install session {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error("invalid Fleet install session {path}: {reason}")]
    InvalidDocument { path: PathBuf, reason: String },

    #[error("Fleet install session is not a regular no-follow file: {path}")]
    UnsafeFile { path: PathBuf },

    #[error("Fleet install session lock is not a regular no-follow file: {path}")]
    UnsafeLock { path: PathBuf },

    #[error("cryptographic random source returned only {actual} of 32 required bytes")]
    ShortRandomRead { actual: usize },

    #[error(transparent)]
    ReleaseBuild(#[from] ReleaseBuildPlanError),
}

/// Publish or recover the exact pre-effect identity for one fresh Fleet install.
pub(super) fn plan_fleet_install_session(
    request: PlanFleetInstallSessionRequest<'_>,
) -> Result<FleetInstallSession, FleetInstallSessionError> {
    let finalized = load_finalized_release_build(
        request.root,
        request.finalized_release_build.record.release_build_id,
    )?;
    if finalized.record != request.finalized_release_build.record
        || finalized.plan_hash != request.finalized_release_build.plan_hash
    {
        return Err(FleetInstallSessionError::ConflictingAuthority {
            path: request.finalized_release_build.path.clone(),
        });
    }
    let ReleaseBuildPlanState::Finalized {
        release_set_manifest_digest,
    } = finalized.record.state
    else {
        unreachable!("load_finalized_release_build admits only finalized records");
    };

    let path = session_path(
        request.root,
        request.canonical_network_id,
        &request.fleet_name,
    );
    let _lock = lock_session(&path)?;
    if let Some(session) = load_optional_session(&path)? {
        if session_matches_request(
            &session,
            &request,
            finalized.plan_hash,
            release_set_manifest_digest,
        ) {
            return Ok(session);
        }
        return Err(FleetInstallSessionError::ConflictingAuthority { path });
    }

    let session = FleetInstallSession {
        schema_version: SESSION_SCHEMA_VERSION,
        fleet_name: request.fleet_name.clone(),
        fleet: FleetBinding {
            fleet: FleetKey {
                canonical_network_id: request.canonical_network_id,
                fleet_id: FleetId::from_generated_bytes(random_identity_bytes()?),
            },
            app: request.app.clone(),
        },
        release_build_id: finalized.record.release_build_id,
        release_build_plan_digest: finalized.plan_hash,
        release_set_manifest_digest,
        decision_release_build_id: request.decision_release_build_id,
        fresh_fleet_plan_digest: request.fresh_fleet_plan_digest.to_string(),
        operation_id: random_identity_bytes()?,
    };
    let bytes = encode_session(&path, &session)?;
    if let Err(source) = create_new_bytes_with_parents(&path, &bytes) {
        if source.kind() == io::ErrorKind::AlreadyExists {
            if let Some(observed) = load_optional_session(&path)?
                && session_matches_request(
                    &observed,
                    &request,
                    finalized.plan_hash,
                    release_set_manifest_digest,
                )
            {
                return Ok(observed);
            }
            return Err(FleetInstallSessionError::ConflictingAuthority { path });
        }
        return Err(FleetInstallSessionError::Io { path, source });
    }

    let observed = load_optional_session(&path)?.ok_or_else(|| {
        invalid(
            &path,
            "published Fleet install session could not be read back",
        )
    })?;
    if observed != session {
        return Err(invalid(
            &path,
            "published Fleet install session differs from planned authority",
        ));
    }
    Ok(observed)
}

/// Recover the original decision binding plus finalized artifacts for exact resume.
pub(super) fn recover_fleet_install_session_authority(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let path = session_path(root, canonical_network_id, fleet_name);
    let _lock = lock_session(&path)?;
    inspect_fleet_install_session_authority_at_path(
        root,
        &path,
        canonical_network_id,
        fleet_name,
        app,
    )
}

/// Inspect exact retained install authority without creating a recovery lock or other file.
pub(super) fn inspect_fleet_install_session_authority(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let path = session_path(root, canonical_network_id, fleet_name);
    inspect_fleet_install_session_authority_at_path(
        root,
        &path,
        canonical_network_id,
        fleet_name,
        app,
    )
}

fn inspect_fleet_install_session_authority_at_path(
    root: &Path,
    path: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let Some(session) = load_optional_session(path)? else {
        return Ok(None);
    };
    if session.fleet_name != *fleet_name
        || session.fleet.fleet.canonical_network_id != canonical_network_id
        || session.fleet.app != *app
    {
        return Err(FleetInstallSessionError::ConflictingAuthority {
            path: path.to_path_buf(),
        });
    }

    let finalized = load_finalized_release_build(root, session.release_build_id)?;
    let ReleaseBuildPlanState::Finalized {
        release_set_manifest_digest,
    } = finalized.record.state
    else {
        unreachable!("load_finalized_release_build admits only finalized records");
    };
    if session.release_build_plan_digest != finalized.plan_hash
        || session.release_set_manifest_digest != release_set_manifest_digest
    {
        return Err(invalid(
            path,
            "session release-build evidence differs from its finalized authority",
        ));
    }

    Ok(Some(RecoveredFleetInstallAuthority {
        finalized_release_build: finalized,
        decision_release_build_id: session.decision_release_build_id,
        fresh_fleet_plan_digest: session.fresh_fleet_plan_digest.clone(),
        session,
    }))
}

fn session_matches_request(
    session: &FleetInstallSession,
    request: &PlanFleetInstallSessionRequest<'_>,
    release_build_plan_digest: [u8; 32],
    release_set_manifest_digest: [u8; 32],
) -> bool {
    session.schema_version == SESSION_SCHEMA_VERSION
        && session.fleet_name == request.fleet_name
        && session.fleet.fleet.canonical_network_id == request.canonical_network_id
        && session.fleet.app == request.app
        && session.release_build_id == request.finalized_release_build.record.release_build_id
        && session.release_build_plan_digest == release_build_plan_digest
        && session.release_set_manifest_digest == release_set_manifest_digest
        && session.decision_release_build_id == request.decision_release_build_id
        && session.fresh_fleet_plan_digest == request.fresh_fleet_plan_digest
}

fn encode_session(
    path: &Path,
    session: &FleetInstallSession,
) -> Result<Vec<u8>, FleetInstallSessionError> {
    validate_session(path, session)?;
    let mut bytes = serde_json::to_vec_pretty(session)
        .map_err(|error| invalid(path, format!("could not encode JSON: {error}")))?;
    bytes.push(b'\n');
    if bytes.len() > MAX_SESSION_BYTES {
        return Err(invalid(path, "session exceeds its byte bound"));
    }
    Ok(bytes)
}

fn load_optional_session(
    path: &Path,
) -> Result<Option<FleetInstallSession>, FleetInstallSessionError> {
    let bytes = match read_optional_regular_bytes(path) {
        Ok(bytes) => bytes,
        Err(RegularFileReadError::NotRegular) => {
            return Err(FleetInstallSessionError::UnsafeFile {
                path: path.to_path_buf(),
            });
        }
        Err(RegularFileReadError::Io(source)) => {
            return Err(FleetInstallSessionError::Io {
                path: path.to_path_buf(),
                source,
            });
        }
    };
    let Some(bytes) = bytes else {
        return Ok(None);
    };
    if bytes.len() > MAX_SESSION_BYTES {
        return Err(invalid(path, "session exceeds its byte bound"));
    }
    let session = serde_json::from_slice::<FleetInstallSession>(&bytes)
        .map_err(|error| invalid(path, error.to_string()))?;
    validate_session(path, &session)?;
    if encode_session(path, &session)? != bytes {
        return Err(invalid(path, "JSON bytes are not canonical"));
    }
    Ok(Some(session))
}

fn validate_session(
    path: &Path,
    session: &FleetInstallSession,
) -> Result<(), FleetInstallSessionError> {
    if session.schema_version != SESSION_SCHEMA_VERSION {
        return Err(invalid(path, "unsupported schema version"));
    }
    if session.fleet_name.as_str().is_empty() {
        return Err(invalid(path, "Fleet name must not be empty"));
    }
    if session.operation_id == [0; 32] {
        return Err(invalid(path, "operation identity must not be zero"));
    }
    if !is_canonical_sha256(&session.fresh_fleet_plan_digest) {
        return Err(invalid(
            path,
            "fresh-Fleet plan digest must contain 64 lowercase hexadecimal characters",
        ));
    }
    if session
        .decision_release_build_id
        .is_some_and(|release_build_id| release_build_id != session.release_build_id)
    {
        return Err(invalid(
            path,
            "decision release build differs from finalized install release build",
        ));
    }
    Ok(())
}

fn is_canonical_sha256(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn session_path(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
) -> PathBuf {
    root.join(".canic")
        .join("recovery")
        .join("fleet-install-sessions")
        .join(canonical_network_id.to_string())
        .join(fleet_name.as_str())
        .join(SESSION_FILE)
}

fn lock_session(path: &Path) -> Result<std::fs::File, FleetInstallSessionError> {
    let lock_path = path.with_file_name(SESSION_LOCK_FILE);
    lock_regular_file_with_parents(&lock_path).map_err(|error| match error {
        RegularFileLockError::NotRegular => FleetInstallSessionError::UnsafeLock {
            path: lock_path.clone(),
        },
        RegularFileLockError::Io(source) => FleetInstallSessionError::Io {
            path: lock_path.clone(),
            source,
        },
        #[cfg(windows)]
        RegularFileLockError::UnsupportedPlatform => FleetInstallSessionError::Io {
            path: lock_path,
            source: io::Error::new(
                io::ErrorKind::Unsupported,
                "Fleet install session locking is unsupported on Windows",
            ),
        },
    })
}

fn random_identity_bytes() -> Result<[u8; 32], FleetInstallSessionError> {
    random_bytes_32().map_err(|error| match error {
        EntropyError::Io(source) => FleetInstallSessionError::Io {
            path: PathBuf::from("<operating-system entropy>"),
            source,
        },
        EntropyError::ShortRead { actual } => FleetInstallSessionError::ShortRandomRead { actual },
    })
}

fn invalid(path: &Path, reason: impl Into<String>) -> FleetInstallSessionError {
    FleetInstallSessionError::InvalidDocument {
        path: path.to_path_buf(),
        reason: reason.into(),
    }
}