arctgz 0.9.0

A next‑generation archive format built with Rust. Super robust, cross‑platform, and designed for speed and safety.
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
---
title: "API Reference"
desc: "Complete reference of all public functions, types, and error variants in the arctgz library."
---

# API Reference

All public items are exported directly from the crate root.  
Import them with:

```rust
use arctgz::{
    init, compile, extract, verify, diff, patch,
    load_config, save_config, load_recipe, extract_recipe, execute_recipe,
    ArctgzConfig, ArctgzManifest, ArctgzRecipe, ArctgzDelta,
    FileEntry, RecipeStep, Compression, Encryption, DeltaOp,
    ArctgzError,
};
```

---

## Functions

### Project Initialization & Configuration

#### `init`

```rust
pub fn init(project_path: &Path, force: bool) -> Result<(), ArctgzError>
```

Creates a new arctgz project at `project_path`.

**Behaviour:**

- Rejects empty paths immediately.
- Resolves and canonicalizes `project_path`. The final canonical path **must** reside within the user's home directory (checked **before** and **after** directory creation to prevent TOCTOU attacks).
- If `project_path` already exists and is not a directory, an error is returned.
- If `force` is `false` and the directory is not empty, the operation is rejected.
- Creates the directory (and parents) if needed.
- **After** creating the directory, re‑canonicalizes the path to detect symlink‑based redirects. If the final path escapes the home directory, the newly created directory is **rolled back** (deleted) and `PathNotAllowed` is returned.
- Creates an empty `include/` subdirectory.
- Writes a default `arctgz.init` configuration file atomically (using `create_new` to detect pre‑existing files).

**Errors:**

- `InvalidPath` – empty path, or path exists but is a file.
- `PathNotAllowed` – path outside home directory (before or after creation).
- `DirectoryNotEmpty` – directory not empty and `force` is `false`.
- `AlreadyInitialized` – `arctgz.init` already exists in the directory.
- `Io` – other filesystem errors.

---

#### `load_config`

```rust
pub fn load_config(project_path: &Path) -> Result<ArctgzConfig, ArctgzError>
```

Reads and validates the `arctgz.init` file from a project directory.

**Errors:**

- `ConfigNotFound` – file does not exist.
- `ConfigLoadError` – read error or invalid JSON.
- `ConfigValidation` – invalid content (see `ArctgzConfig::validate`).

---

#### `save_config`

```rust
pub fn save_config(project_path: &Path, config: &ArctgzConfig) -> Result<(), ArctgzError>
```

Atomically writes a validated `ArctgzConfig` back to `arctgz.init`.

**Behaviour:**

- Validates the config before writing.
- Writes to a temporary file first, then renames it onto the target. If any step fails, the temporary file is removed.

**Errors:**

- `ConfigValidation` – config fails validation.
- `ConfigSaveError` – write or rename failure.
- `Io` – other I/O errors.

---

### Archive Operations

#### `compile`

```rust
pub fn compile(
    project_path: &Path,
    output_path: Option<&Path>,
    force: bool,
    private_key: Option<&[u8]>,
    password: Option<&str>,
) -> Result<PathBuf, ArctgzError>
```

Compiles the project into an `.artgz` archive.

**Behaviour:**

1. Loads configuration from `project_path/arctgz.init`.
2. Validates that all `include` glob patterns match at least one file (under `project_path/include/`). If any pattern yields zero matches, returns `IncludeFileNotFound`.
3. Collects files from `include/` using the glob patterns (plus the mandatory `arctgz.init` and optional `recipe.json` from the project root). Symbolic links are rejected (`SymlinkNotAllowed`). Empty directories that match a pattern are preserved as directory entries.
4. Computes SHA‑512 hashes of all files in **parallel** (via `rayon`).
5. Builds a `manifest.json` with size, hash, and directory flags.
6. Optionally signs the manifest with an Ed25519 private key (must be exactly 32 bytes; otherwise `KeyError`).
7. Compresses the tar stream (gzip or zstd, according to configuration).
8. If `config.encryption == Encryption::Aes256Gcm`, encrypts the entire archive with AES‑256‑GCM using the provided password. The password is required in this case.
9. Writes the final file atomically via a temporary file.

**Parameters:**

- `project_path` – root directory of the project.
- `output_path` – if `Some`, the path where the archive will be written; if `None`, defaults to `project_path/archive.artgz`.
- `force` – if `true`, overwrites an existing output file; otherwise returns `Io(AlreadyExists)`.
- `private_key` – 32‑byte Ed25519 signing key for signing the manifest; `None` disables signing.
- `password` – password for encryption (required if `encryption` is `Aes256Gcm`; ignored otherwise).

**Returns:** the actual path of the created archive.

**Errors:**

- `ConfigNotFound`, `ConfigLoadError`, `ConfigValidation` – config issues.
- `Io` – filesystem errors (missing `include/` directory, write failures, etc.).
- `SymlinkNotAllowed` – symbolic link encountered under `include/`.
- `IncludeFileNotFound` – a glob pattern matched no files, or the glob itself is invalid.
- `KeyError` – private key length is not 32 bytes.
- `EncryptionError` – password missing when encryption is required, or encryption operation fails.
- `SignatureError` – signing failure (unlikely).

---

#### `extract`

```rust
pub fn extract(
    archive_path: &Path,
    output_dir: &Path,
    force: bool,
    public_key: Option<&[u8]>,
    password: Option<&str>,
) -> Result<(), ArctgzError>
```

Extracts and verifies an archive.

**Behaviour:**

- Detects compression (gzip/zstd) and encryption (magic bytes `ARCT`).
- If encrypted, decrypts to a temporary file using the provided password. **Password is mandatory for encrypted archives.**
- Verifies the Ed25519 signature if a public key is given.
- Reads `manifest.json` and verifies every file entry:
  - Path safety (no absolute, `..`, empty, or `.`).
  - Entry type consistency (file vs directory).
  - Actual SHA‑512 hash and size must match the manifest exactly.
- If verification fails for any file, the partially extracted file is removed before returning the error.
- If `force` is `true`, existing files are overwritten; otherwise existing files cause `Io(AlreadyExists)`.
- Creates parent directories as needed.

**Parameters:**

- `archive_path` – path to the `.artgz` file.
- `output_dir` – destination directory.
- `force` – allow overwriting existing files.
- `public_key` – 32‑byte Ed25519 public key for signature verification; `None` skips verification.
- `password` – password for decryption; required if the archive is encrypted.

**Errors:**

- `ManifestNotFound` – archive does not contain `manifest.json`.
- `SignatureError` – signature missing (when key provided) or invalid.
- `EncryptionError` – wrong password, decryption failure, or unsupported archive version (see `decrypt_file` behaviour).
- `ChecksumMismatch` – hash or size mismatch for a file.
- `ExtractError` – unsafe path, type mismatch, or manifest/file count inconsistency.
- `Io` – filesystem errors.

---

#### `verify`

```rust
pub fn verify(
    archive_path: &Path,
    public_key: Option<&[u8]>,
    password: Option<&str>,
) -> Result<(), ArctgzError>
```

Standalone integrity check. Performs the same validation as `extract` but writes no files.

**Parameters:** same as `extract` (without `force` and `output_dir`).

**Errors:** same as `extract` (excluding `Io` related to file creation).

---

### Delta Patching

#### `diff`

```rust
pub fn diff(base_archive: &Path, target_archive: &Path) -> Result<ArctgzDelta, ArctgzError>
```

Computes a binary delta between two archives.

**Behaviour:**

- Reads both manifests.
- Compares file entries by path, size, hash, and directory flag.
- Generates `Add`, `Modify`, or `Delete` operations.
- Ignores metadata file `recipe.json` only; `arctgz.init` is **not** ignored and will be included in the delta if changed.

**Returns:** an `ArctgzDelta` containing the list of operations and manifest hashes.

**Errors:** same as `read_manifest` (I/O, JSON, etc.).

---

#### `patch`

```rust
pub fn patch(
    base_archive: &Path,
    target_archive: &Path,
    delta: &ArctgzDelta,
    output_path: &Path,
    private_key: Option<&[u8]>,
) -> Result<(), ArctgzError>
```

Applies a previously computed delta to produce a new archive identical to the target.

**Behaviour (security‑hardened):**

1. Reads the base archive manifest and verifies its hash matches `delta.base_manifest_hash`. If not, returns `DeltaError`.
2. Reads the target archive manifest and **also** verifies its hash against `delta.target_manifest_hash`. If mismatch, the operation is rejected – this ensures the delta is applied to the exact intended target.
3. Builds a new manifest from the base entries, keeping unchanged files, deleting removed ones, and taking modified/added entries from the delta.
4. For each file that is _copied from the base archive_ (unchanged):
   - Reads exactly `expected.size + 1` bytes to detect hidden trailing data. If the actual length is not exactly `expected.size`, the patch fails.
   - Computes SHA‑512 and verifies it against the base manifest. Mismatch results in `ChecksumMismatch`.
5. For each file _copied from the target archive_ (modified or added):
   - Verifies the size and **also recomputes SHA‑512** against the entry in the new manifest (which originates from the target). If it does not match, `ChecksumMismatch` is returned. This prevents corrupted or tampered data from being injected during patching.
6. The new manifest is written and optionally signed.
7. The result is written atomically.

**Parameters:**

- `base_archive` – path to the base archive.
- `target_archive` – path to the target archive (used as source for modified/added files).
- `delta` – the delta returned by `diff`.
- `output_path` – where to write the patched archive.
- `private_key` – optional signing key for the new manifest.

**Errors:**

- `DeltaError` – manifest hash mismatch (base or target), missing entries, or unexpected file sizes.
- `ChecksumMismatch` – file content integrity failure.
- `Io`, `KeyError`, `SignatureError` – as in `compile`.

---

### Recipe Management

#### `load_recipe`

```rust
pub fn load_recipe(project_path: &Path) -> Result<Option<ArctgzRecipe>, ArctgzError>
```

Loads and validates `recipe.json` from a project directory. Returns `None` if the file is absent.

**Errors:** `Io`, `Json`, `RecipeInvalid`.

---

#### `extract_recipe`

```rust
pub fn extract_recipe(archive_path: &Path) -> Result<ArctgzRecipe, ArctgzError>
```

Extracts and validates the embedded `recipe.json` from an archive (handles compression and encryption transparently).

**Errors:**

- `RecipeNotFound` – no `recipe.json` in the archive.
- `Io`, `Json`, `RecipeInvalid`.

---

#### `execute_recipe`

```rust
pub fn execute_recipe(
    output_dir: &Path,
    recipe: &ArctgzRecipe,
    force: bool,
) -> Result<(), ArctgzError>
```

Runs the steps of a recipe inside `output_dir`.

**Supported steps:**

- `Copy { from, to }` – copies `from` to `to` (both relative to `output_dir`). Directories are copied recursively.
- `MkDir { path }` – creates a directory (and parents).
- `Chmod { path, mode }` – sets Unix permissions (octal mode). Returns an error on non‑Unix platforms.
- `Remove { path }` – deletes a file or directory (directory must be empty).

All paths are validated against traversal attacks (`..`, absolute, empty, or `.`).  
`force` controls whether existing destinations are overwritten or cause an error.

**Errors:**

- `RecipeInvalid` – invalid step or path.
- `RecipeExecutionError` – step failed (e.g., missing source, permission denied).
- `Io` – filesystem errors.

---

## Types

### `ArctgzConfig`

```rust
pub struct ArctgzConfig {
    pub name: String,
    pub version: String,
    pub include: Vec<String>,
    pub compression: Compression,
    pub encryption: Encryption,
}
```

Project configuration. Serialised as JSON with `deny_unknown_fields`.

**Validation (`validate` method):**

- `name` – alphanumeric plus `-` and `_`, max 255 chars.
- `version` – strict semver.
- `include` – relative glob patterns, max 100 entries, each must be a relative path without `..` and non‑empty after trimming.
- `compression` – `Gzip` or `Zstd`.
- `encryption` – `None` or `Aes256Gcm`.

Default (created by `init`):  
`name` = `"untitled"`, `version` = `"0.1.0"`, `include` = `[]`, `compression` = `Gzip`, `encryption` = `None`.

---

### `ArctgzManifest`

```rust
pub struct ArctgzManifest {
    pub name: String,
    pub version: String,
    pub created: DateTime<Utc>,
    pub compression: Compression,
    pub files: BTreeMap<String, FileEntry>,
    pub signature: Option<String>,
}
```

Embedded in every archive as `manifest.json`.

- `signature` – hex‑encoded Ed25519 signature of the manifest computed **without** the `signature` field.

---

### `FileEntry`

```rust
pub struct FileEntry {
    pub size: u64,
    pub sha512: String,
    pub is_dir: bool,
}
```

Describes a file or directory entry in the manifest.

---

### `ArctgzRecipe`

```rust
pub struct ArctgzRecipe {
    pub name: String,
    pub version: String,
    pub steps: Vec<RecipeStep>,
}
```

Post‑extraction recipe.

---

### `RecipeStep`

```rust
pub enum RecipeStep {
    Copy   { from: String, to: String },
    MkDir  { path: String },
    Chmod  { path: String, mode: String },
    Remove { path: String },
}
```

Deserialised with `#[serde(tag = "action")]`.

---

### `Compression`

```rust
pub enum Compression {
    Gzip,
    Zstd,
}
```

Default: `Gzip`.

---

### `Encryption`

```rust
pub enum Encryption {
    None,
    Aes256Gcm,
}
```

Default: `None`.

---

### `ArctgzDelta`

```rust
pub struct ArctgzDelta {
    pub base_name: String,
    pub base_version: String,
    pub target_name: String,
    pub target_version: String,
    pub base_manifest_hash: String,
    pub target_manifest_hash: String,
    pub operations: Vec<DeltaOp>,
}
```

Represents the difference between two archives.

- `base_manifest_hash` / `target_manifest_hash` – hex‑encoded SHA‑512 of the respective manifest (with `signature` field omitted).

---

### `DeltaOp`

```rust
pub enum DeltaOp {
    Add    { path: String, size: u64, sha512: String, is_dir: bool },
    Modify { path: String, size: u64, sha512: String, is_dir: bool },
    Delete { path: String },
}
```

Serialised with `#[serde(tag = "op")]`.

---

## Error Types

### `ArctgzError`

All possible errors returned by the library.

```rust
pub enum ArctgzError {
    Io(std::io::Error),
    Json(serde_json::Error),
    AlreadyInitialized,
    InvalidPath(String),
    PathNotAllowed(String),
    DirectoryNotEmpty(String),
    ConfigValidation(String),
    ConfigNotFound(String),
    ConfigLoadError(String),
    ConfigSaveError(String),
    SymlinkNotAllowed(String),
    IncludeFileNotFound(String),
    ManifestNotFound,
    ChecksumMismatch(String, String, String),
    ExtractError(String),
    RecipeNotFound,
    RecipeInvalid(String),
    RecipeExecutionError(String),
    VerifyError(String),
    SignatureError(String),
    KeyError(String),
    DeltaError(String),
    EncryptionError(String),
}
```

- `Io` and `Json` are transparently converted from the underlying error types via `From`.
- `ChecksumMismatch` contains: `(path, expected_hash_or_description, actual_hash)`.
- `EncryptionError` now also carries version mismatch errors (unsupported archive version) in its message.

---

For practical examples, see the [Usage](usage.html) page. For configuration details, check [Configuration](configuration.html).