-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod_file.rs
More file actions
1139 lines (1028 loc) · 38.3 KB
/
Copy pathmod_file.rs
File metadata and controls
1139 lines (1028 loc) · 38.3 KB
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `akua.toml` — the human-edited manifest.
//!
//! Spec: [`docs/lockfile-format.md §akua.toml`](../../../docs/lockfile-format.md).
//!
//! Two-file package manager split inherited from Go (intent + evidence),
//! with TOML format borrowed from Cargo because our dep forms are richer
//! than go.mod's directives can express cleanly. Companion file is
//! [`crate::lock_file`] (`akua.lock`).
//!
//! This module is **pure parsing and serialization**. No network, no fs
//! walks, no resolution. Digest resolution lives elsewhere.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// The top-level shape of an `akua.toml` file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AkuaManifest {
pub package: PackageSection,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<WorkspaceSection>,
/// Supply-chain signing policy. When `[signing].cosign_public_key`
/// is set, every OCI dep must pull with a matching cosign
/// signature or the resolver fails. Absent section → cosign
/// verification is off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signing: Option<SigningSection>,
/// Dependencies keyed by local alias (the name as it appears in `import`
/// statements). `BTreeMap` canonicalizes order alphabetically on
/// serialize — the on-disk order is not preserved across round-trip.
#[serde(default)]
pub dependencies: BTreeMap<String, Dependency>,
}
/// `[signing]` table. exposes keyed cosign verification
/// only. Keyless (fulcio + rekor) will land a sibling field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SigningSection {
/// Filesystem path to a PEM-encoded P-256 cosign public key,
/// relative to the workspace root. Applies to every OCI dep in
/// this manifest (verify path).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cosign_public_key: Option<String>,
/// Filesystem path to a PEM-encoded P-256 cosign private key
/// (unencrypted PKCS#8), relative to the workspace root. When
/// set, `akua publish` signs every published artifact by
/// default. Absent → publish unsigned.
///
/// Store with restrictive filesystem perms (0600). Passphrase /
/// HSM support is a follow-up slice.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cosign_private_key: Option<String>,
}
/// `[package]` table.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PackageSection {
pub name: String,
pub version: String,
pub edition: String,
/// When `false`, unsigned deps are permitted in `akua.lock`. Default `true`.
#[serde(default = "default_strict_signing")]
pub strict_signing: bool,
}
fn default_strict_signing() -> bool {
true
}
/// `[workspace]` table, present in monorepos.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkspaceSection {
/// Glob patterns resolving to member package directories.
#[serde(default)]
pub members: Vec<String>,
}
/// A single dependency. Form is discriminated by which source-type field is
/// set (`oci` / `git` / `path` / `repo`). Exactly one must be present; more
/// than one present is a validation error.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(Default))]
pub struct Dependency {
/// OCI ref. Exclusive with `git`, `path`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oci: Option<String>,
/// Git URL. Exclusive with `oci`, `path`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub git: Option<String>,
/// Local filesystem path. Exclusive with `oci`, `git`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
/// HTTPS Helm-repo URL (the `index.yaml` lives at `<repo>/index.yaml`).
/// Exclusive with `oci`, `git`, `path`. Pairs with `chart`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repo: Option<String>,
/// Chart entry name within a `repo`'s `index.yaml`. Required for
/// `repo` deps; unused by other sources.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chart: Option<String>,
/// Version constraint (semver exact or range). Required for `oci`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Git tag. Set for `git` deps to pin a specific release.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
/// Git commit SHA. Alternative to `tag` for `git` deps.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rev: Option<String>,
/// Local-fork override. Keeps the `oci` / `git` ref recorded as the
/// canonical source; resolves from `replace.path` at build time instead.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replace: Option<Replace>,
}
/// Local-fork override.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Replace {
pub path: String,
}
/// The source form discriminant, computed from which field is set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencySource {
Oci,
Git,
Path,
Helm,
}
/// Typed projection of a [`Dependency`]'s source form. Returned by
/// [`Dependency::spec`] post-validation; field shapes encode the
/// validate-enforced invariants (OCI deps have a version; git deps
/// have at least one of tag/rev; helm deps have chart + version) so
/// consumers don't re-prove them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencySpec<'a> {
Path {
declared: &'a str,
},
Oci {
oci: &'a str,
version: &'a str,
},
Git {
git: &'a str,
tag: Option<&'a str>,
rev: Option<&'a str>,
},
Helm {
repo: &'a str,
chart: &'a str,
version: &'a str,
},
}
impl<'a> DependencySpec<'a> {
/// `tag` if set, else `rev`. Manifest validation guarantees one of
/// the two is `Some` for git deps, so the [`Option`] in the return
/// is purely for the non-Git arms (always `None`).
pub fn tag_or_rev(&self) -> Option<&'a str> {
match self {
DependencySpec::Git { tag, rev, .. } => tag.or(*rev),
_ => None,
}
}
}
/// Errors produced by this module.
#[derive(Debug, thiserror::Error)]
pub enum ManifestError {
#[error("toml parse error: {0}")]
Parse(#[from] toml::de::Error),
#[error("toml serialize error: {0}")]
Serialize(#[from] toml::ser::Error),
#[error("dependency `{name}`: exactly one of oci / git / path must be set, got {count}")]
AmbiguousSource { name: String, count: usize },
#[error("dependency `{name}`: oci dep requires a version")]
OciMissingVersion { name: String },
#[error("dependency `{name}`: git dep requires either tag or rev")]
GitMissingTagOrRev { name: String },
#[error("dependency `{name}`: path dep must not set version / tag / rev")]
PathHasPin { name: String },
#[error("[package].edition must start with `akua.dev/`, got `{0}`")]
BadEdition(String),
#[error("[package].name must be a valid KCL identifier, got `{0}`")]
BadPackageName(String),
#[error(
"dependency `{name}`: git URL must not embed credentials (`user:pass@`). \
Pass credentials via the SDK `auth` parameter or the CLI `--auth` flag."
)]
GitUrlHasUserInfo { name: String },
#[error("dependency `{name}`: helm-repo dep requires a `chart`")]
HelmMissingChart { name: String },
#[error("dependency `{name}`: helm-repo dep requires a `version`")]
HelmMissingVersion { name: String },
#[error(
"dependency `{name}`: repo URL must not embed credentials (`user:pass@`). \
Pass credentials via the SDK `auth` parameter or the CLI `--auth` flag."
)]
HelmUrlHasUserInfo { name: String },
#[error(
"dependency `{name}`: `chart` value `{chart}` must be a plain chart name \
(no path separators or `..`)"
)]
HelmChartInvalid { name: String, chart: String },
#[error(
"dependency `{name}`: oci URL must not embed credentials (`user:pass@`). \
Pass credentials via the SDK `auth` parameter or the CLI `--auth` flag."
)]
OciUrlHasUserInfo { name: String },
}
impl ManifestError {
/// Stable error-code constant for this variant. Defaults to
/// `E_MANIFEST_PARSE`; specific variants that have their own
/// documented code override here so agents can branch precisely.
pub fn structured_code(&self) -> &'static str {
use crate::cli_contract::codes;
match self {
ManifestError::GitUrlHasUserInfo { .. } => codes::E_MANIFEST_GIT_USERINFO,
ManifestError::HelmMissingChart { .. } => codes::E_MANIFEST_HELM_MISSING_CHART,
ManifestError::HelmMissingVersion { .. } => codes::E_MANIFEST_HELM_MISSING_VERSION,
ManifestError::HelmUrlHasUserInfo { .. } => codes::E_MANIFEST_HELM_USERINFO,
ManifestError::HelmChartInvalid { .. } => codes::E_MANIFEST_HELM_CHART_INVALID,
ManifestError::OciUrlHasUserInfo { .. } => codes::E_MANIFEST_OCI_USERINFO,
_ => codes::E_MANIFEST_PARSE,
}
}
}
/// Result of loading an `akua.toml` from disk. Distinguishes the file
/// being absent (workspace not set up) from other I/O errors, and
/// preserves the file path on parse errors for diagnostics.
#[derive(Debug, thiserror::Error)]
pub enum ManifestLoadError {
#[error("akua.toml not found at {path}")]
Missing { path: std::path::PathBuf },
#[error("i/o error reading {path}: {source}")]
Io {
path: std::path::PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to parse {path}: {source}")]
Parse {
path: std::path::PathBuf,
#[source]
source: ManifestError,
},
}
impl ManifestLoadError {
/// Map to a [`StructuredError`] with the right CLI-contract code,
/// the file path, and the default docs URL. Callers layer on their
/// own `.with_suggestion(...)` where the UX differs by verb.
pub fn to_structured(&self) -> crate::cli_contract::StructuredError {
use crate::cli_contract::{codes, StructuredError};
match self {
ManifestLoadError::Missing { path } => {
StructuredError::new(codes::E_MANIFEST_MISSING, "akua.toml not found")
.with_path(path.display().to_string())
.with_default_docs()
}
ManifestLoadError::Io { path, source } => {
StructuredError::new(codes::E_IO, source.to_string())
.with_path(path.display().to_string())
.with_default_docs()
}
ManifestLoadError::Parse { path, source } => {
StructuredError::new(source.structured_code(), source.to_string())
.with_path(path.display().to_string())
.with_default_docs()
}
}
}
/// `true` when the underlying cause is a system-side I/O failure
/// (disk gone, permission denied) rather than a user mistake.
/// Callers route this to [`crate::ExitCode::SystemError`].
pub fn is_system(&self) -> bool {
matches!(self, ManifestLoadError::Io { .. })
}
}
impl AkuaManifest {
/// Parse an `akua.toml` from a string.
pub fn parse(s: &str) -> Result<Self, ManifestError> {
let manifest: AkuaManifest = toml::from_str(s)?;
manifest.validate()?;
Ok(manifest)
}
/// Load `akua.toml` from a workspace directory. Maps filesystem
/// NotFound to [`ManifestLoadError::Missing`] so callers can
/// distinguish "no manifest" from "disk broke."
pub fn load(workspace: &std::path::Path) -> Result<Self, ManifestLoadError> {
let path = workspace.join("akua.toml");
let content = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(ManifestLoadError::Missing { path });
}
Err(e) => return Err(ManifestLoadError::Io { path, source: e }),
};
Self::parse(&content).map_err(|source| ManifestLoadError::Parse { path, source })
}
/// Serialize back to canonical TOML. Fields in deterministic order;
/// dependencies alphabetical (BTreeMap guarantees this).
pub fn to_toml(&self) -> Result<String, ManifestError> {
Ok(toml::to_string_pretty(self)?)
}
/// Cross-field validation that serde's structural parse can't catch on
/// its own.
pub fn validate(&self) -> Result<(), ManifestError> {
if !self.package.edition.starts_with("akua.dev/") {
return Err(ManifestError::BadEdition(self.package.edition.clone()));
}
if !is_valid_package_name(&self.package.name) {
return Err(ManifestError::BadPackageName(self.package.name.clone()));
}
for (name, dep) in &self.dependencies {
dep.validate(name)?;
}
Ok(())
}
}
impl Dependency {
/// Which source form is this? `Some` when exactly one of `oci` /
/// `git` / `path` / `repo` is set; `None` when zero or more than
/// one are set (which is a validation error handled by [`validate`]).
pub fn source(&self) -> Option<DependencySource> {
match (
self.oci.is_some(),
self.git.is_some(),
self.path.is_some(),
self.repo.is_some(),
) {
(true, false, false, false) => Some(DependencySource::Oci),
(false, true, false, false) => Some(DependencySource::Git),
(false, false, true, false) => Some(DependencySource::Path),
(false, false, false, true) => Some(DependencySource::Helm),
_ => None,
}
}
/// Typed projection of the dep's source. Caller must have
/// validated; reach for [`source`] when working with raw input.
///
/// # Panics
///
/// Panics on an unvalidated manifest (zero / multiple sources, OCI
/// without version, git without tag-or-rev). `AkuaManifest::load`
/// runs validation; direct `Dependency` construction outside tests
/// must call [`validate`] first.
pub fn spec(&self) -> DependencySpec<'_> {
match (
self.path.as_deref(),
self.oci.as_deref(),
self.git.as_deref(),
self.repo.as_deref(),
) {
(Some(declared), None, None, None) => DependencySpec::Path { declared },
(None, Some(oci), None, None) => DependencySpec::Oci {
oci,
version: self.version.as_deref().expect(
"Dependency::spec called on an unvalidated manifest — call validate() first",
),
},
(None, None, Some(git), None) => DependencySpec::Git {
git,
tag: self.tag.as_deref(),
rev: self.rev.as_deref(),
},
(None, None, None, Some(repo)) => DependencySpec::Helm {
repo,
chart: self.chart.as_deref().expect(
"Dependency::spec called on an unvalidated manifest — call validate() first",
),
version: self.version.as_deref().expect(
"Dependency::spec called on an unvalidated manifest — call validate() first",
),
},
_ => unreachable!(
"Dependency::spec called on an unvalidated manifest — call validate() first"
),
}
}
/// Full validation. Callers pass the local alias so errors name the dep.
pub fn validate(&self, name: &str) -> Result<(), ManifestError> {
let Some(source) = self.source() else {
let count = self.oci.is_some() as usize
+ self.git.is_some() as usize
+ self.path.is_some() as usize
+ self.repo.is_some() as usize;
return Err(ManifestError::AmbiguousSource {
name: name.to_string(),
count,
});
};
match source {
DependencySource::Oci if self.version.is_none() => {
Err(ManifestError::OciMissingVersion {
name: name.to_string(),
})
}
DependencySource::Oci
if crate::host_auth::url_has_userinfo(
self.oci.as_deref().expect("oci source set"),
) =>
{
Err(ManifestError::OciUrlHasUserInfo {
name: name.to_string(),
})
}
DependencySource::Git if self.tag.is_none() && self.rev.is_none() => {
Err(ManifestError::GitMissingTagOrRev {
name: name.to_string(),
})
}
DependencySource::Git
if crate::host_auth::url_has_userinfo(
self.git.as_deref().expect("git source set"),
) =>
{
Err(ManifestError::GitUrlHasUserInfo {
name: name.to_string(),
})
}
DependencySource::Path
if self.version.is_some() || self.tag.is_some() || self.rev.is_some() =>
{
Err(ManifestError::PathHasPin {
name: name.to_string(),
})
}
DependencySource::Helm if self.chart.is_none() => {
Err(ManifestError::HelmMissingChart {
name: name.to_string(),
})
}
DependencySource::Helm if self.version.is_none() => {
Err(ManifestError::HelmMissingVersion {
name: name.to_string(),
})
}
DependencySource::Helm
if crate::host_auth::url_has_userinfo(
self.repo.as_deref().expect("repo source set"),
) =>
{
Err(ManifestError::HelmUrlHasUserInfo {
name: name.to_string(),
})
}
DependencySource::Helm => {
// chart is Some at this point (HelmMissingChart arm above).
let chart = self.chart.as_deref().expect("chart validated present");
if is_path_traversal_chart_name(chart) {
return Err(ManifestError::HelmChartInvalid {
name: name.to_string(),
chart: chart.to_string(),
});
}
Ok(())
}
_ => Ok(()),
}
}
}
/// Map a dep key to a legal KCL identifier by replacing every char
/// outside `[A-Za-z0-9_]` with `_`. Dep keys allow `-` (and validate
/// as Cargo/npm-style names), but KCL identifiers don't — a module
/// written to `cnpg-operator.k` binds its symbols under the literal
/// `cnpg-operator`, which `import charts.cnpg_operator` can't see.
/// Sanitizing at every site that turns a dep key into a KCL module /
/// alias name keeps the on-disk module name aligned with the `import`
/// alias the user has to write.
///
/// Every char outside `[A-Za-z0-9_]` maps to `_`. A KCL identifier may
/// not start with a digit, and [`is_valid_package_name`] permits
/// digit-leading dep keys (e.g. `01-foo`), so a leading digit is
/// prefixed with `_` (`01-foo` → `_01_foo`).
pub fn kcl_ident(name: &str) -> String {
let mut out: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' {
c
} else {
'_'
}
})
.collect();
if out.starts_with(|c: char| c.is_ascii_digit()) {
out.insert(0, '_');
}
out
}
/// True when a helm `chart` value contains path separators or `..`
/// segments that could be path-joined into the chart cache to escape
/// its directory. A chart name must be a plain single-component name
/// (e.g. `temporal`, `nginx`); it never contains `/`, `\`, or `..`.
fn is_path_traversal_chart_name(chart: &str) -> bool {
chart.contains('/') || chart.contains('\\') || chart.contains("..")
}
/// Package name rules (aligned with Cargo / npm / poetry conventions):
/// - non-empty
/// - ASCII alphanumeric, `-`, `_` only
/// - must not start with `-` (registry ergonomics)
///
/// Digit-prefixed names are permitted (e.g. `01-hello-webapp`).
pub fn is_valid_package_name(s: &str) -> bool {
let mut chars = s.chars();
let Some(first) = chars.next() else {
return false;
};
if first == '-' {
return false;
}
if !(first.is_ascii_alphanumeric() || first == '_') {
return false;
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
/// Lifted from `examples/01-hello-webapp/akua.toml`.
const EXAMPLE_01: &str = r#"
[package]
name = "01-hello-webapp"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
nginx = { oci = "oci://registry-1.docker.io/bitnamicharts/nginx", version = "18.2.0" }
"#;
/// Exercises workspace + multiple deps + mixed sources.
const EXAMPLE_WORKSPACE: &str = r#"
[package]
name = "acme-platform"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[workspace]
members = ["./apps/*", "./policies/*"]
[dependencies]
k8s = { oci = "oci://ghcr.io/kcl-lang/k8s", version = "1.31.2" }
cnpg = { oci = "oci://ghcr.io/cloudnative-pg/charts/cluster", version = "0.20.0" }
our-glue = { oci = "oci://pkg.acme.internal/glue", version = "0.3.0", replace = { path = "../glue-fork" } }
local-dev = { path = "../shared" }
from-git = { git = "https://github.com/foo/bar", tag = "v1.2.3" }
"#;
#[test]
fn parses_minimal_example() {
let m = AkuaManifest::parse(EXAMPLE_01).expect("parse");
assert_eq!(m.package.name, "01-hello-webapp");
assert_eq!(m.package.version, "0.1.0");
assert_eq!(m.package.edition, "akua.dev/v1alpha1");
assert!(m.package.strict_signing);
assert!(m.workspace.is_none());
assert_eq!(m.dependencies.len(), 1);
let nginx = m.dependencies.get("nginx").expect("nginx dep");
assert_eq!(
nginx.oci.as_deref(),
Some("oci://registry-1.docker.io/bitnamicharts/nginx")
);
assert_eq!(nginx.version.as_deref(), Some("18.2.0"));
assert!(nginx.git.is_none());
assert!(nginx.path.is_none());
}
#[test]
fn parses_workspace_with_mixed_sources() {
let m = AkuaManifest::parse(EXAMPLE_WORKSPACE).expect("parse");
assert_eq!(
m.workspace.as_ref().unwrap().members,
vec!["./apps/*".to_string(), "./policies/*".to_string()]
);
assert_eq!(m.dependencies.len(), 5);
assert_eq!(
m.dependencies["our-glue"].replace.as_ref().unwrap().path,
"../glue-fork"
);
assert_eq!(
m.dependencies["local-dev"].source().unwrap(),
DependencySource::Path
);
assert_eq!(
m.dependencies["from-git"].source().unwrap(),
DependencySource::Git
);
assert_eq!(
m.dependencies["k8s"].source().unwrap(),
DependencySource::Oci
);
}
#[test]
fn round_trips_canonical_form() {
let original = AkuaManifest::parse(EXAMPLE_WORKSPACE).expect("parse");
let serialized = original.to_toml().expect("serialize");
let reparsed = AkuaManifest::parse(&serialized).expect("reparse");
assert_eq!(original, reparsed, "round-trip should preserve structure");
}
#[test]
fn rejects_ambiguous_source() {
let bad = r#"
[package]
name = "bad"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
twosrc = { oci = "oci://foo", git = "https://example.com/bar", version = "1.0.0", tag = "v1" }
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("twosrc"), "error should name the dep: {msg}");
assert!(msg.contains("exactly one"), "err: {msg}");
}
#[test]
fn rejects_oci_without_version() {
let bad = r#"
[package]
name = "bad"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
bare = { oci = "oci://foo" }
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::OciMissingVersion { ref name } if name == "bare"),
"expected OciMissingVersion, got {err:?}"
);
}
#[test]
fn rejects_git_without_tag_or_rev() {
let bad = r#"
[package]
name = "bad"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
bare-git = { git = "https://github.com/foo/bar" }
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::GitMissingTagOrRev { ref name } if name == "bare-git"),
"expected GitMissingTagOrRev, got {err:?}"
);
}
#[test]
fn rejects_git_url_with_userinfo() {
let bad = r#"
[package]
name = "fine"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
upstream = { git = "https://alice:secret@example.com/foo/bar", tag = "v1" }
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::GitUrlHasUserInfo { ref name } if name == "upstream"),
"expected GitUrlHasUserInfo, got {err:?}"
);
assert_eq!(
err.structured_code(),
crate::cli_contract::codes::E_MANIFEST_GIT_USERINFO
);
}
#[test]
fn accepts_git_url_with_at_in_path() {
// `@` outside the authority is fine — only authority `@` is
// userinfo. Paths can legally contain `@` though it's unusual.
let ok = r#"
[package]
name = "fine"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
upstream = { git = "https://example.com/foo/bar@v1.git", tag = "v1" }
"#;
AkuaManifest::parse(ok).unwrap();
}
#[test]
fn rejects_path_with_version() {
let bad = r#"
[package]
name = "bad"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
pinned-path = { path = "../foo", version = "1.0.0" }
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::PathHasPin { ref name } if name == "pinned-path"),
"expected PathHasPin, got {err:?}"
);
}
#[test]
fn rejects_bad_edition() {
let bad = r#"
[package]
name = "fine"
version = "0.1.0"
edition = "cargo/v1"
[dependencies]
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::BadEdition(ref e) if e == "cargo/v1"),
"expected BadEdition, got {err:?}"
);
}
#[test]
fn rejects_bad_package_name_has_space() {
let bad = r#"
[package]
name = "has space"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::BadPackageName(ref n) if n == "has space"),
"expected BadPackageName, got {err:?}"
);
}
#[test]
fn package_name_validation() {
// Allowed
assert!(is_valid_package_name("webapp"));
assert!(is_valid_package_name("web-app"));
assert!(is_valid_package_name("web_app_123"));
assert!(is_valid_package_name("_leading_underscore"));
assert!(is_valid_package_name("01-hello-webapp")); // digit-prefix OK
assert!(is_valid_package_name("9starts-with-digit"));
// Disallowed
assert!(!is_valid_package_name(""));
assert!(!is_valid_package_name("-leading-hyphen"));
assert!(!is_valid_package_name("has space"));
assert!(!is_valid_package_name("has.dot"));
}
#[test]
fn kcl_ident_sanitizes_separators() {
assert_eq!(kcl_ident("cnpg-operator"), "cnpg_operator");
// Idempotent / unchanged on already-legal identifiers.
assert_eq!(kcl_ident("traefik"), "traefik");
assert_eq!(kcl_ident("web_app_123"), "web_app_123");
// Collapses other separators a dep key might carry.
assert_eq!(kcl_ident("a.b"), "a_b");
assert_eq!(kcl_ident("a-b.c"), "a_b_c");
// A leading digit is illegal in a KCL identifier, so it's prefixed
// with `_` (digit-leading dep keys are otherwise permitted).
assert_eq!(kcl_ident("01-hello-webapp"), "_01_hello_webapp");
assert_eq!(kcl_ident("9lives"), "_9lives");
}
#[test]
fn kcl_ident_collision_is_detectable() {
// Two distinct dep keys that sanitize to the same identifier —
// the materializers reject this rather than overwrite a module.
assert_eq!(kcl_ident("a-b"), kcl_ident("a_b"));
assert_ne!("a-b", "a_b");
}
#[test]
fn rejects_bad_package_name_leading_hyphen() {
let bad = r#"
[package]
name = "-bad-name"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
[dependencies]
"#;
let err = AkuaManifest::parse(bad).unwrap_err();
assert!(
matches!(err, ManifestError::BadPackageName(ref n) if n == "-bad-name"),
"expected BadPackageName, got {err:?}"
);
}
#[test]
fn strict_signing_defaults_to_true() {
let m = AkuaManifest::parse(EXAMPLE_01).expect("parse");
assert!(m.package.strict_signing);
}
#[test]
fn strict_signing_can_be_disabled() {
let s = r#"
[package]
name = "unsigned-ok"
version = "0.1.0"
edition = "akua.dev/v1alpha1"
strict_signing = false
[dependencies]
"#;
let m = AkuaManifest::parse(s).expect("parse");
assert!(!m.package.strict_signing);
}
#[test]
fn spec_projects_path_dep() {
let dep = Dependency {
path: Some("./local".to_string()),
..Default::default()
};
assert!(matches!(dep.spec(), DependencySpec::Path { declared } if declared == "./local"));
}
#[test]
fn spec_projects_oci_dep_with_version() {
let dep = Dependency {
oci: Some("oci://ghcr.io/acme/app".to_string()),
version: Some("1.0.0".to_string()),
..Default::default()
};
match dep.spec() {
DependencySpec::Oci { oci, version } => {
assert_eq!(oci, "oci://ghcr.io/acme/app");
assert_eq!(version, "1.0.0");
}
other => panic!("expected Oci, got {other:?}"),
}
}
/// `Dependency::spec` documents that OCI without a version panics
/// (manifest validation rejects this shape upstream). Pin the
/// contract so the `version: &str` field on `DependencySpec::Oci`
/// can't be silently downgraded back to `Option`.
#[test]
#[should_panic(expected = "unvalidated manifest")]
fn spec_panics_on_oci_without_version() {
let dep = Dependency {
oci: Some("oci://ghcr.io/acme/app".to_string()),
..Default::default()
};
let _ = dep.spec();
}
#[test]
fn spec_projects_git_dep_exposes_tag_and_rev_separately() {
let dep = Dependency {
git: Some("https://github.com/foo/bar".to_string()),
tag: Some("v1.0.0".to_string()),
rev: Some("abc123".to_string()),
..Default::default()
};
match dep.spec() {
DependencySpec::Git { git, tag, rev } => {
assert_eq!(git, "https://github.com/foo/bar");
assert_eq!(tag, Some("v1.0.0"));
assert_eq!(rev, Some("abc123"));
}
other => panic!("expected Git, got {other:?}"),
}
}
#[test]
fn spec_tag_or_rev_prefers_tag() {
let dep = Dependency {
git: Some("https://github.com/foo/bar".to_string()),
tag: Some("v1.0.0".to_string()),
rev: Some("abc123".to_string()),
..Default::default()
};
assert_eq!(dep.spec().tag_or_rev(), Some("v1.0.0"));
}
#[test]
fn spec_tag_or_rev_falls_back_to_rev_when_tag_absent() {
let dep = Dependency {
git: Some("https://github.com/foo/bar".to_string()),
rev: Some("abc123".to_string()),
..Default::default()
};
assert_eq!(dep.spec().tag_or_rev(), Some("abc123"));
}
/// `Dependency::spec` is documented as panicking on an unvalidated
/// manifest — the `_ => unreachable!` arm. This test pins that
/// contract so a regression is caught immediately.
#[test]
#[should_panic(expected = "unvalidated manifest")]
fn spec_panics_on_ambiguous_source() {
let dep = Dependency {
path: Some("./local".to_string()),
oci: Some("oci://ghcr.io/acme/app".to_string()),
..Default::default()
};
let _ = dep.spec();
}
#[test]
fn repo_dep_is_helm_source() {
let dep = Dependency {
repo: Some("https://go.temporal.io/helm-charts".into()),
chart: Some("temporal".into()),
version: Some("0.62.0".into()),
..Default::default()
};
assert_eq!(dep.source(), Some(DependencySource::Helm));
dep.validate("temporal").expect("valid helm dep");
match dep.spec() {
DependencySpec::Helm {
repo,
chart,
version,
} => {
assert_eq!(repo, "https://go.temporal.io/helm-charts");
assert_eq!(chart, "temporal");
assert_eq!(version, "0.62.0");
}
other => panic!("expected Helm, got {other:?}"),
}
}
#[test]
fn helm_dep_requires_chart_and_version() {
let no_chart = Dependency {
repo: Some("https://r".into()),
version: Some("1.0.0".into()),
..Default::default()
};
assert!(matches!(
no_chart.validate("x"),
Err(ManifestError::HelmMissingChart { .. })