libcnb 0.30.4

A framework for writing Cloud Native Buildpacks in Rust
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
// This lint triggers when both layer_dir and layers_dir are present which are quite common.
#![allow(clippy::similar_names)]

use crate::sbom::{Sbom, cnb_sbom_path};
use crate::util::{default_on_not_found, remove_dir_recursively};
use libcnb_common::toml_file::{TomlFileError, read_toml_file, write_toml_file};
use libcnb_data::layer::LayerName;
use libcnb_data::layer_content_metadata::{LayerContentMetadata, LayerTypes};
use libcnb_data::sbom::SBOM_FORMATS;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

pub(in crate::layer) fn read_layer<M: DeserializeOwned, P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
) -> Result<Option<ReadLayer<M>>, ReadLayerError> {
    let layer_dir_path = layers_dir.as_ref().join(layer_name.as_str());
    let layer_toml_path = layers_dir.as_ref().join(format!("{layer_name}.toml"));

    if !layer_dir_path.exists() && !layer_toml_path.exists() {
        return Ok(None);
    } else if !layer_dir_path.exists() && layer_toml_path.exists() {
        // This is a valid case according to the spec:
        // https://github.com/buildpacks/spec/blob/7b20dfa070ed428c013e61a3cefea29030af1732/buildpack.md#layer-types
        //
        // When launch = true, build = false, cache = false, the layer metadata will be restored but
        // not the layer itself. However, we choose to not support this case as of now. It would
        // complicate the API we need to expose to the user of libcnb as this case is very different
        // compared to all other combinations of launch, build and cache. It's the only case where
        // a cache = false layer restores some of its data between builds.
        //
        // To normalize, we remove the layer TOML file and treat the layer as non-existent.
        fs::remove_file(&layer_toml_path)?;
        return Ok(None);
    }

    // An empty layer content metadata file is valid and the CNB spec is not clear if the lifecycle
    // has to restore them if they're empty. This is especially important since the layer types
    // are removed from the file if it's restored. To normalize, we write an empty file if the layer
    // directory exists without the metadata file.
    if !layer_toml_path.exists() {
        fs::write(&layer_toml_path, "")?;
    }

    let layer_toml_contents = fs::read_to_string(&layer_toml_path)?;

    let layer_content_metadata = toml::from_str::<LayerContentMetadata<M>>(&layer_toml_contents)
        .map_err(ReadLayerError::LayerContentMetadataParseError)?;

    Ok(Some(ReadLayer {
        name: layer_name.clone(),
        path: layer_dir_path,
        metadata: layer_content_metadata,
    }))
}

pub(in crate::layer) struct ReadLayer<M> {
    pub(in crate::layer) name: LayerName,
    pub(in crate::layer) path: PathBuf,
    pub(in crate::layer) metadata: LayerContentMetadata<M>,
}

#[derive(thiserror::Error, Debug)]
pub enum ReadLayerError {
    #[error("Layer content metadata couldn't be parsed!")]
    LayerContentMetadataParseError(toml::de::Error),

    #[error("Unexpected I/O error while reading layer: {0}")]
    IoError(#[from] std::io::Error),
}

pub(in crate::layer) fn write_layer<M: Serialize, P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
    layer_content_metadata: &LayerContentMetadata<M>,
) -> Result<(), WriteLayerError> {
    let layer_dir = layers_dir.as_ref().join(layer_name.as_str());
    fs::create_dir_all(layer_dir)?;

    let layer_content_metadata_path = layers_dir.as_ref().join(format!("{layer_name}.toml"));

    write_toml_file(&layer_content_metadata, layer_content_metadata_path)
        .map_err(WriteLayerMetadataError::TomlFileError)
        .map_err(WriteLayerError::WriteLayerMetadataError)?;

    Ok(())
}

#[derive(thiserror::Error, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum WriteLayerError {
    #[error("{0}")]
    WriteLayerMetadataError(WriteLayerMetadataError),

    #[error("{0}")]
    ReplaceLayerSbomsError(ReplaceLayerSbomsError),

    #[error("{0}")]
    ReplaceLayerExecdProgramsError(ReplaceLayerExecdProgramsError),

    #[error("Unexpected I/O error while writing layer: {0}")]
    IoError(#[from] std::io::Error),
}

/// Does not error if the layer doesn't exist.
pub(in crate::layer) fn delete_layer<P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
) -> Result<(), DeleteLayerError> {
    let layer_dir = layers_dir.as_ref().join(layer_name.as_str());
    let layer_toml = layers_dir.as_ref().join(format!("{layer_name}.toml"));

    default_on_not_found(remove_dir_recursively(&layer_dir))?;
    default_on_not_found(fs::remove_file(layer_toml))?;

    Ok(())
}

#[derive(thiserror::Error, Debug)]
pub enum DeleteLayerError {
    #[error("I/O error while deleting layer: {0}")]
    IoError(#[from] std::io::Error),
}

pub(in crate::layer) fn replace_layer_metadata<M: Serialize, P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
    metadata: M,
) -> Result<(), WriteLayerMetadataError> {
    let layer_content_metadata_path = layers_dir.as_ref().join(format!("{layer_name}.toml"));

    let content_metadata = read_toml_file::<LayerContentMetadata>(&layer_content_metadata_path)?;

    write_toml_file(
        &LayerContentMetadata {
            types: content_metadata.types,
            metadata,
        },
        &layer_content_metadata_path,
    )
    .map_err(WriteLayerMetadataError::TomlFileError)
}

pub(in crate::layer) fn replace_layer_types<P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
    layer_types: LayerTypes,
) -> Result<(), WriteLayerMetadataError> {
    let layer_content_metadata_path = layers_dir.as_ref().join(format!("{layer_name}.toml"));

    let mut content_metadata =
        read_toml_file::<LayerContentMetadata>(&layer_content_metadata_path)?;
    content_metadata.types = Some(layer_types);

    write_toml_file(&content_metadata, &layer_content_metadata_path)
        .map_err(WriteLayerMetadataError::TomlFileError)
}

pub(crate) fn replace_layer_sboms<P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
    sboms: &[Sbom],
) -> Result<(), ReplaceLayerSbomsError> {
    let layers_dir = layers_dir.as_ref();

    if !layers_dir.join(layer_name.as_str()).is_dir() {
        return Err(ReplaceLayerSbomsError::MissingLayer(layer_name.clone()));
    }

    for format in SBOM_FORMATS {
        default_on_not_found(fs::remove_file(cnb_sbom_path(
            format, layers_dir, layer_name,
        )))?;
    }

    for sbom in sboms {
        fs::write(
            cnb_sbom_path(&sbom.format, layers_dir, layer_name),
            &sbom.data,
        )?;
    }

    Ok(())
}

#[derive(thiserror::Error, Debug)]
pub enum ReplaceLayerSbomsError {
    #[error("Layer doesn't exist: {0}")]
    MissingLayer(LayerName),

    #[error("Unexpected I/O error while replacing layer SBOMs: {0}")]
    IoError(#[from] std::io::Error),
}

pub(in crate::layer) fn replace_layer_exec_d_programs<P: AsRef<Path>>(
    layers_dir: P,
    layer_name: &LayerName,
    exec_d_programs: &HashMap<String, PathBuf>,
) -> Result<(), ReplaceLayerExecdProgramsError> {
    let layer_dir = layers_dir.as_ref().join(layer_name.as_str());

    if !layer_dir.is_dir() {
        return Err(ReplaceLayerExecdProgramsError::MissingLayer(
            layer_name.clone(),
        ));
    }

    let exec_d_dir = layer_dir.join("exec.d");

    if exec_d_dir.is_dir() {
        fs::remove_dir_all(&exec_d_dir)?;
    }

    if !exec_d_programs.is_empty() {
        fs::create_dir_all(&exec_d_dir)?;

        for (name, path) in exec_d_programs {
            // We could just try to copy the file here and let the call-site deal with the
            // I/O errors when the path does not exist. We're using an explicit error variant
            // for a missing exec.d binary makes it easier to debug issues with packaging
            // since the usage of exec.d binaries often relies on implicit packaging the
            // buildpack author might not be aware of.
            Some(&path)
                .filter(|path| path.exists())
                .ok_or_else(|| ReplaceLayerExecdProgramsError::MissingExecDFile(path.clone()))
                .and_then(|path| {
                    fs::copy(path, exec_d_dir.join(name))
                        .map_err(ReplaceLayerExecdProgramsError::IoError)
                })?;
        }
    }

    Ok(())
}

#[derive(thiserror::Error, Debug)]
pub enum ReplaceLayerExecdProgramsError {
    #[error("Unexpected I/O error while replacing layer execd programs: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Couldn't find exec.d file for copying: {0}")]
    MissingExecDFile(PathBuf),

    #[error("Layer doesn't exist: {0}")]
    MissingLayer(LayerName),
}

#[derive(thiserror::Error, Debug)]
pub enum WriteLayerMetadataError {
    #[error("Unexpected I/O error while writing layer metadata: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Error while writing layer content metadata TOML: {0}")]
    TomlFileError(#[from] TomlFileError),
}

#[derive(thiserror::Error, Debug)]
pub enum LayerError {
    #[error("{0}")]
    ReadLayerError(#[from] ReadLayerError),
    #[error("{0}")]
    WriteLayerError(#[from] WriteLayerError),
    #[error("{0}")]
    DeleteLayerError(#[from] DeleteLayerError),
    #[error("Cannot read generic layer metadata: {0}")]
    CouldNotReadGenericLayerMetadata(TomlFileError),
    #[error("Cannot read layer {0} after creating it")]
    CouldNotReadLayerAfterCreate(LayerName),
    #[error("Unexpected I/O error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("Unexpected missing layer")]
    UnexpectedMissingLayer,
}

#[cfg(test)]
mod test {
    use crate::layer::ReadLayerError;
    use libcnb_data::generic::GenericMetadata;
    use libcnb_data::layer_content_metadata::{LayerContentMetadata, LayerTypes};
    use libcnb_data::layer_name;
    use serde::Deserialize;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn read_layer() {
        #[derive(Deserialize, Debug, Eq, PartialEq)]
        struct TestLayerMetadata {
            version: String,
            sha: String,
        }

        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();
        let layer_dir = layers_dir.join(layer_name.as_str());

        fs::create_dir_all(&layer_dir).unwrap();
        fs::write(
            layers_dir.join(format!("{layer_name}.toml")),
            r#"
            [types]
            launch = true
            build = false
            cache = true

            [metadata]
            version = "1.0"
            sha = "2608a36467a6fec50be1672bfbf88b04b9ec8efaafa58c71d9edf73519ed8e2c"
            "#,
        )
        .unwrap();

        let layer_data = super::read_layer::<TestLayerMetadata, _>(layers_dir, &layer_name)
            .unwrap()
            .unwrap();

        assert_eq!(layer_data.path, layer_dir);

        assert_eq!(layer_data.name, layer_name);

        assert_eq!(
            layer_data.metadata.types,
            Some(LayerTypes {
                launch: true,
                build: false,
                cache: true
            })
        );

        assert_eq!(
            layer_data.metadata.metadata,
            TestLayerMetadata {
                version: String::from("1.0"),
                sha: String::from(
                    "2608a36467a6fec50be1672bfbf88b04b9ec8efaafa58c71d9edf73519ed8e2c"
                )
            }
        );
    }

    #[test]
    fn read_malformed_toml_layer() {
        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();
        let layer_dir = layers_dir.join(layer_name.as_str());

        fs::create_dir_all(layer_dir).unwrap();
        fs::write(
            layers_dir.join(format!("{layer_name}.toml")),
            r"
            [types
            build = true
            launch = true
            cache = true
            ",
        )
        .unwrap();

        match super::read_layer::<GenericMetadata, _>(layers_dir, &layer_name) {
            Err(ReadLayerError::LayerContentMetadataParseError(toml_error)) => {
                assert_eq!(toml_error.span(), Some(19..19));
            }
            _ => panic!("Expected ReadLayerError::LayerContentMetadataParseError!"),
        }
    }

    #[test]
    fn read_incompatible_metadata_layer() {
        #[derive(Deserialize, Debug, Eq, PartialEq)]
        struct TestLayerMetadata {
            version: String,
            sha: String,
        }

        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();
        let layer_dir = layers_dir.join(layer_name.as_str());

        fs::create_dir_all(layer_dir).unwrap();
        fs::write(
            layers_dir.join(format!("{layer_name}.toml")),
            r#"
            [types]
            build = true
            launch = true
            cache = true

            [metadata]
            version = "1.0"
            "#,
        )
        .unwrap();

        match super::read_layer::<TestLayerMetadata, _>(layers_dir, &layer_name) {
            Err(ReadLayerError::LayerContentMetadataParseError(toml_error)) => {
                assert_eq!(toml_error.span(), Some(110..120));
            }
            _ => panic!("Expected ReadLayerError::LayerContentMetadataParseError!"),
        }
    }

    #[test]
    fn read_layer_without_layer_directory() {
        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();
        let layer_dir = layers_dir.join(layer_name.as_str());

        fs::create_dir_all(layer_dir).unwrap();

        match super::read_layer::<GenericMetadata, _>(layers_dir, &layer_name) {
            Ok(Some(layer_data)) => {
                assert_eq!(
                    layer_data.metadata,
                    LayerContentMetadata {
                        types: None,
                        metadata: None
                    }
                );
            }
            _ => panic!("Expected Ok(Some(_)!"),
        }
    }

    #[test]
    fn read_layer_without_layer_content_metadata() {
        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();

        fs::write(layers_dir.join(format!("{layer_name}.toml")), "").unwrap();

        match super::read_layer::<GenericMetadata, _>(layers_dir, &layer_name) {
            Ok(None) => {}
            _ => panic!("Expected Ok(None)!"),
        }
    }

    #[test]
    fn read_nonexistent_layer() {
        let layer_name = layer_name!("foo");
        let temp_dir = tempdir().unwrap();
        let layers_dir = temp_dir.path();

        match super::read_layer::<GenericMetadata, _>(layers_dir, &layer_name) {
            Ok(None) => {}
            _ => panic!("Expected Ok(None)!"),
        }
    }
}