-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsecure.rs
More file actions
794 lines (728 loc) · 28.2 KB
/
Copy pathsecure.rs
File metadata and controls
794 lines (728 loc) · 28.2 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
//! Validated value-object newtypes ("parse, don't validate").
//!
//! This module provides small newtypes that wrap a `String` and can **only** be
//! constructed by running a structural validator from [`crate::validate`]. Once
//! a value has one of these types, it is guaranteed to have passed the relevant
//! path / identifier / ref security checks — so a safe-output tool that types a
//! field as, say, [`RelativeSafePath`] cannot hold an unvalidated, attacker
//! controlled path.
//!
//! Each newtype:
//!
//! - exposes a fallible [`parse`](RelativeSafePath::parse) constructor plus
//! `TryFrom<String>` / `TryFrom<&str>` / [`FromStr`](std::str::FromStr);
//! - validates **at deserialization time** via a hand-written `Deserialize`
//! impl, so invalid JSON/YAML input is rejected before any `validate()` pass;
//! - serializes transparently back to a plain string (`Serialize`) and reports a
//! plain string JSON schema (`JsonSchema`) so they are drop-in replacements for
//! `String` fields in MCP `Params` structs;
//! - derefs to `&str` and implements `AsRef<str>` / `AsRef<Path>` / `Display`.
//!
//! ## Choosing a type
//!
//! - [`RelativeSafePath`] — agent-supplied file paths inside the workspace
//! (allows hidden dotfiles like `.gitignore`; rejects traversal/absolute/`.git`).
//! - [`StrictRelativePath`] — like the above but every component must be a plain
//! segment (no leading `.`, no `:`); use for attachment/artifact staging.
//! - [`PathSegment`] — a single path segment / alias (e.g. a repo checkout alias).
//! - [`GitRefName`] — a git ref obeying `git check-ref-format`.
//! - [`BranchName`] — a git branch ref with extra length / leading-`-` / space rules.
//! - [`CommitSha`] — a full 40-character hex commit SHA.
//! - [`AzureDevOpsOrgUrl`] — an HTTPS Azure DevOps organization collection URL.
//! - [`ArtifactName`] — an ADO artifact / attachment name.
//! - [`Identifier`] — an engine agent/model identifier.
//! - [`AdoVariableName`] — an Azure DevOps pipeline or variable-group variable name.
//! - [`HostName`] — a DNS-style hostname.
//! - [`RegistryRef`] — a container-registry host or base path.
//! - [`AdoOrganization`] — an Azure DevOps Services organization name.
//! - [`AdoProject`] — an Azure DevOps project name or GUID.
//! - [`AdoRepository`] — an Azure DevOps repository name or GUID.
//! - [`AdoWorkItemFieldRef`] — an Azure DevOps work item field reference name.
//! - [`Version`] — a version string (`1.2.3`, `latest`).
//! - [`SemanticVersion`] — an exact semantic version (`1.2.3`, `2.0.0-beta.1`).
//!
//! New safe-output tools that accept paths or identifiers should type those
//! fields with these newtypes instead of raw `String` so the checks are applied
//! automatically and cannot be forgotten.
use std::path::Path;
use crate::validate;
/// Generate a validated string newtype ("parse, don't validate").
///
/// Expands to a `#[serde(transparent)]` tuple struct wrapping a `String` that
/// can only be constructed by running `$validate`, so an instance is a
/// type-level proof the value passed its structural security checks.
///
/// Parameters:
/// - `$name` — the generated newtype identifier.
/// - `$label` — a short noun (e.g. `"path"`, `"branch"`) interpolated into
/// validation error messages.
/// - `$validate` — an expression evaluating to a
/// `fn(&str, &str) -> anyhow::Result<()>` (value, label) that enforces the
/// rules; typically a function from [`crate::validate`].
///
/// Generated impls and why they exist:
/// - `Deserialize` (hand-written) runs `$validate`, so invalid JSON/YAML is
/// rejected at deserialization time rather than in a later `validate()` pass.
/// - `Serialize` / `JsonSchema` are transparent so the newtype is a drop-in
/// replacement for a `String` field in MCP `Params` (same wire/schema shape).
/// - `parse` / `TryFrom` / `FromStr` are the fallible constructors for code
/// paths that build values directly (e.g. tests, internal conversions).
/// - `Deref<Target=str>`, `AsRef<str>`, `AsRef<Path>`, `Display`, and
/// `From<$name> for String` make the validated value ergonomic to read.
macro_rules! validated_string {
(
$(#[$meta:meta])*
$name:ident, $label:literal, $validate:expr
) => {
$(#[$meta])*
#[derive(
Clone, Debug, PartialEq, Eq, Hash,
serde::Serialize, schemars::JsonSchema,
)]
#[serde(transparent)]
#[schemars(transparent)]
pub struct $name(String);
impl $name {
/// Parse and validate, returning the newtype on success.
pub fn parse(value: impl Into<String>) -> anyhow::Result<Self> {
let value = value.into();
let validate_fn: fn(&str, &str) -> anyhow::Result<()> = $validate;
validate_fn(&value, $label)?;
Ok(Self(value))
}
/// Borrow the validated value as a string slice.
pub fn as_str(&self) -> &str {
&self.0
}
/// Consume the newtype, returning the inner `String`.
pub fn into_inner(self) -> String {
self.0
}
}
impl std::ops::Deref for $name {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl AsRef<str> for $name {
fn as_ref(&self) -> &str {
&self.0
}
}
impl AsRef<Path> for $name {
fn as_ref(&self) -> &Path {
Path::new(&self.0)
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for $name {
type Error = anyhow::Error;
fn try_from(value: String) -> anyhow::Result<Self> {
Self::parse(value)
}
}
impl TryFrom<&str> for $name {
type Error = anyhow::Error;
fn try_from(value: &str) -> anyhow::Result<Self> {
Self::parse(value)
}
}
impl std::str::FromStr for $name {
type Err = anyhow::Error;
fn from_str(value: &str) -> anyhow::Result<Self> {
Self::parse(value)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let raw = String::deserialize(deserializer)?;
Self::parse(raw).map_err(serde::de::Error::custom)
}
}
impl From<$name> for String {
fn from(value: $name) -> String {
value.0
}
}
};
}
validated_string! {
/// A safe relative file path inside the workspace.
///
/// Allows hidden dotfiles (`.gitignore`); rejects empty, null bytes,
/// newlines, pipeline commands, absolute / Windows-drive paths, `..`
/// traversal, and any `.git` component. See
/// [`crate::validate::validate_relative_safe_path`].
RelativeSafePath, "path", validate::validate_relative_safe_path
}
validated_string! {
/// A safe relative path whose every component is a plain segment
/// (no leading `.`, no `:`). See
/// [`crate::validate::validate_relative_segment_path`].
StrictRelativePath, "path", validate::validate_relative_segment_path
}
validated_string! {
/// An absolute POSIX path inside a container.
///
/// Used for compiler-owned mount destinations. Rejects root, traversal,
/// empty/dot components, control characters, shell metacharacters, and
/// Docker's `:` mount separator.
ContainerAbsolutePath, "container path", |value: &str, label: &str| {
if !value.starts_with('/') || value == "/" {
anyhow::bail!("{label} must be an absolute POSIX path below `/`");
}
if value.ends_with('/')
|| !value
.chars()
.all(|character| character.is_ascii_alphanumeric() || "/._-".contains(character))
{
anyhow::bail!("{label} contains characters that are unsafe in a container mount");
}
if value
.split('/')
.skip(1)
.any(|segment| segment.is_empty() || segment == "." || segment == "..")
{
anyhow::bail!("{label} must not contain empty, `.` or `..` path components");
}
Ok(())
}
}
validated_string! {
/// A single safe path segment / alias (e.g. a repository checkout alias).
PathSegment, "segment", |value: &str, label: &str| {
if validate::is_safe_path_segment(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' is not a safe path segment \
(no empty, '..', path separators, or leading '.')"
)
}
}
}
validated_string! {
/// An Azure DevOps work item field reference name.
AdoWorkItemFieldRef, "work item field", validate::validate_ado_work_item_field_ref
}
validated_string! {
/// A git ref name obeying `git check-ref-format`.
GitRefName, "ref", validate::validate_git_ref_name
}
validated_string! {
/// A git branch ref with additional length / leading-`-` / space rules.
BranchName, "branch_name", |value: &str, label: &str| {
if value.is_empty() {
anyhow::bail!("{label} must not be empty");
}
if value.len() > 200 {
anyhow::bail!("{label} must be at most 200 characters");
}
if value.contains('\0') {
anyhow::bail!("{label} must not contain null bytes");
}
if value.starts_with('-') {
anyhow::bail!("{label} must not start with '-'");
}
if value.contains(' ') {
anyhow::bail!("{label} must not contain spaces");
}
validate::validate_git_ref_name(value, label)
}
}
validated_string! {
/// A full 40-character hex commit SHA.
CommitSha, "commit", validate::validate_commit_sha
}
validated_string! {
/// An HTTPS Azure DevOps organization collection URL.
AzureDevOpsOrgUrl, "Azure DevOps organization URL", validate::validate_ado_org_url
}
validated_string! {
/// An Azure DevOps artifact / attachment name.
ArtifactName, "artifact_name", |value: &str, label: &str| {
if value.len() > 100 {
anyhow::bail!("{label} must be at most 100 characters");
}
if value.starts_with('.') {
anyhow::bail!("{label} must not start with '.'");
}
if validate::is_valid_artifact_name(value) {
Ok(())
} else {
anyhow::bail!(
"{label} must be non-empty and contain only alphanumeric characters, '-', '_' or '.'"
)
}
}
}
validated_string! {
/// An engine agent / model identifier.
Identifier, "identifier", |value: &str, label: &str| {
if validate::is_valid_identifier(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be non-empty and contain only [A-Za-z0-9._:-]"
)
}
}
}
fn validate_temporary_id(value: &str, label: &str) -> anyhow::Result<()> {
let bare = value.strip_prefix('#').unwrap_or(value);
let Some(suffix) = bare.strip_prefix("aw_") else {
anyhow::bail!(
"{label} must use `#aw_` followed by 3-12 ASCII alphanumeric/underscore characters"
);
};
if !(3..=12).contains(&suffix.len())
|| !suffix
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
anyhow::bail!(
"{label} must use `#aw_` followed by 3-12 ASCII alphanumeric/underscore characters"
);
}
Ok(())
}
validated_string! {
/// A temporary GitHub issue identifier used to link safe outputs in one run.
GithubTemporaryId, "temporary_id", validate_temporary_id
}
validated_string! {
/// A temporary Azure DevOps work-item identifier used to link safe outputs in one run.
WorkItemTemporaryId, "temporary_id", validate_temporary_id
}
validated_string! {
/// A temporary Azure DevOps pull-request identifier used to link safe outputs in one run.
PullRequestTemporaryId, "temporary_id", validate_temporary_id
}
impl GithubTemporaryId {
/// Canonical map/reference form with the leading `#`.
pub fn canonical(&self) -> String {
if self.as_str().starts_with('#') {
self.as_str().to_string()
} else {
format!("#{}", self.as_str())
}
}
}
impl WorkItemTemporaryId {
/// Canonical map/reference form with the leading `#`.
pub fn canonical(&self) -> String {
if self.as_str().starts_with('#') {
self.as_str().to_string()
} else {
format!("#{}", self.as_str())
}
}
}
impl PullRequestTemporaryId {
/// Canonical map/reference form with the leading `#`.
pub fn canonical(&self) -> String {
if self.as_str().starts_with('#') {
self.as_str().to_string()
} else {
format!("#{}", self.as_str())
}
}
}
validated_string! {
/// An Azure DevOps pipeline or variable-group variable name.
///
/// Allows the alphanumeric, dot, underscore, and hyphen form accepted by
/// Azure DevOps macro references while rejecting expression syntax,
/// whitespace, control characters, and logging-command injection.
AdoVariableName, "Azure DevOps variable name", |value: &str, label: &str| {
if validate::is_valid_ado_variable_name(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must start with an ASCII alphanumeric or '_' and contain only [A-Za-z0-9._-]"
)
}
}
}
validated_string! {
/// A DNS-style hostname.
HostName, "hostname", |value: &str, label: &str| {
if validate::is_valid_hostname(value) {
Ok(())
} else {
anyhow::bail!("{label} '{value}' must be non-empty and contain only [A-Za-z0-9.-]")
}
}
}
validated_string! {
/// A version string (e.g. `1.2.3`, `latest`).
Version, "version", |value: &str, label: &str| {
if validate::is_valid_version(value) {
Ok(())
} else {
anyhow::bail!("{label} '{value}' must be non-empty and contain only [A-Za-z0-9._-]")
}
}
}
validated_string! {
/// An exact semantic version (e.g. `1.2.3`, `2.0.0-beta.1`).
SemanticVersion, "semantic version", |value: &str, label: &str| {
if semver::Version::parse(value).is_ok() {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be an exact semantic version such as '2.8.1'; \
npm tags and ranges are not allowed"
)
}
}
}
validated_string! {
/// An Azure DevOps Artifacts feed reference (`feed` or `project/feed`).
FeedRef, "feed", |value: &str, label: &str| {
if validate::is_valid_feed_ref(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be a feed name or 'project/feed' \
containing only [A-Za-z0-9._/-] (no '..', no leading/trailing '/')"
)
}
}
}
validated_string! {
/// An internal container-registry base path (host plus optional
/// namespace path, e.g. `myacr.azurecr.io/mirror`).
RegistryRef, "registry", |value: &str, label: &str| {
if validate::is_valid_registry_ref(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be a registry host or base path \
containing only [A-Za-z0-9._/-] (no '..', no '//', no \
leading/trailing '/')"
)
}
}
}
validated_string! {
/// An Azure DevOps service-connection name or GUID.
ServiceConnection, "service-connection", |value: &str, label: &str| {
if validate::is_valid_service_connection(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be non-empty, at most 256 characters, \
and free of quotes and control characters"
)
}
}
}
validated_string! {
/// An Azure DevOps Services organization name.
AdoOrganization, "organization", |value: &str, label: &str| {
let valid = !value.is_empty()
&& value.len() <= 64
&& !value.starts_with('-')
&& !value.ends_with('-')
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-');
if valid {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be 1-64 ASCII alphanumeric or '-' \
characters and must not start or end with '-'"
)
}
}
}
validated_string! {
/// An Azure DevOps project name or GUID.
AdoProject, "project", |value: &str, label: &str| {
let bytes = value.as_bytes();
let is_guid = bytes.len() == 36
&& bytes.iter().enumerate().all(|(index, byte)| {
if matches!(index, 8 | 13 | 18 | 23) {
*byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
let invalid_name_char = |c: char| {
c.is_control()
|| matches!(
c,
',' | '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|'
| ';' | '#' | '$' | '{' | '}' | '+' | '=' | '[' | ']'
)
};
let char_count = value.chars().count();
let is_name = char_count > 0
&& char_count <= 64
&& value.trim() == value
&& !value.starts_with('_')
&& !value.starts_with('.')
&& !value.ends_with('.')
&& !value.chars().any(invalid_name_char);
if is_guid || is_name {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be an Azure DevOps project name \
(1-64 characters, no reserved punctuation, leading '_' or \
leading/trailing '.') or a canonical GUID"
)
}
}
}
validated_string! {
/// An Azure DevOps repository name or GUID.
AdoRepository, "repository", |value: &str, label: &str| {
let bytes = value.as_bytes();
let is_guid = bytes.len() == 36
&& bytes.iter().enumerate().all(|(index, byte)| {
if matches!(index, 8 | 13 | 18 | 23) {
*byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
let invalid_name_char = |c: char| {
c.is_control()
|| matches!(
c,
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|'
| ';' | '#' | '$' | '{' | '}' | '[' | ']'
)
};
let char_count = value.chars().count();
let is_name = char_count > 0
&& char_count <= 64
&& value.trim() == value
&& !value.starts_with('.')
&& !value.ends_with('.')
&& !value.chars().any(invalid_name_char);
if is_guid || is_name {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be an Azure DevOps repository name \
(1-64 characters, no reserved punctuation or \
leading/trailing '.') or a canonical GUID"
)
}
}
}
validated_string! {
/// A canonical `8-4-4-4-12` hex GUID.
///
/// Used by the Azure DevOps policy proxy for project / repository /
/// resource-area identifiers, where a scope comparison must be an exact
/// match rather than a name lookup. See
/// [`crate::validate::is_valid_guid`].
Guid, "guid", |value: &str, label: &str| {
if validate::is_valid_guid(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be a canonical 8-4-4-4-12 hex GUID"
)
}
}
}
validated_string! {
/// An Azure resource (audience) URL passed to
/// `az account get-access-token --resource`. Validated to be a shell-safe,
/// URI-shaped value so it can be interpolated into the generated provider
/// token-mint bash script without escaping.
ProviderResourceUrl, "resource", |value: &str, label: &str| {
if validate::is_valid_provider_resource_url(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be a URI-shaped Azure resource audience \
(contain '://', at most 256 characters) composed only of \
[A-Za-z0-9._:/%~-] — no spaces, quotes, or shell metacharacters"
)
}
}
}
validated_string! {
/// An `engine.provider.base-url` value: either a literal `https://` URL (with
/// a host) or a value carrying an ADO `$(...)` macro. Validated at
/// deserialization so a malformed / non-https / injection-bearing base URL is
/// rejected before it can be rendered into `COPILOT_PROVIDER_BASE_URL` or have
/// its host extracted for the AWF network allowlist.
ProviderBaseUrl, "base-url", |value: &str, label: &str| {
if validate::is_valid_provider_base_url(value) {
Ok(())
} else {
anyhow::bail!(
"{label} '{value}' must be a literal https:// URL with a host \
(plaintext http:// is not allowed) or an ADO macro '$(VAR)'. \
It must not contain a template ('${{{{ }}}}') or runtime ('$[...]') \
expression, pipeline-command injection ('##vso['), or newlines."
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relative_safe_path_parses_and_rejects() {
assert!(RelativeSafePath::parse("src/main.rs").is_ok());
assert!(RelativeSafePath::parse(".gitignore").is_ok());
assert!(RelativeSafePath::parse("../escape").is_err());
assert!(RelativeSafePath::parse(".git/config").is_err());
assert_eq!(
RelativeSafePath::parse("a/b.txt").unwrap().as_str(),
"a/b.txt"
);
}
#[test]
fn strict_relative_path_is_stricter() {
assert!(StrictRelativePath::parse("a/b.txt").is_ok());
assert!(StrictRelativePath::parse(".hidden").is_err());
assert!(StrictRelativePath::parse("a:b").is_err());
}
#[test]
fn container_absolute_path_rules() {
assert!(ContainerAbsolutePath::parse("/var/run/ado-aw/azure").is_ok());
assert!(ContainerAbsolutePath::parse("/").is_err());
assert!(ContainerAbsolutePath::parse("relative/path").is_err());
assert!(ContainerAbsolutePath::parse("/var/run/../secret").is_err());
assert!(ContainerAbsolutePath::parse("/var//run").is_err());
assert!(ContainerAbsolutePath::parse("/var/run:rw").is_err());
assert!(ContainerAbsolutePath::parse("/var/$(TOKEN)").is_err());
for unsafe_path in [
"/var/run/token dir",
"/var/run/token\tdir",
"/var/run/'token'",
"/var/run/\"token\"",
"/var/run/token;command",
"/var/run/token|command",
"/var/run/token&command",
] {
assert!(
ContainerAbsolutePath::parse(unsafe_path).is_err(),
"{unsafe_path:?} must be rejected"
);
}
}
#[test]
fn path_segment_rejects_separators() {
assert!(PathSegment::parse("my-repo").is_ok());
assert!(PathSegment::parse("a/b").is_err());
assert!(PathSegment::parse("..").is_err());
assert!(PathSegment::parse(".hidden").is_err());
}
#[test]
fn branch_name_rules() {
assert!(BranchName::parse("feature/x").is_ok());
assert!(BranchName::parse("-bad").is_err());
assert!(BranchName::parse("has space").is_err());
assert!(BranchName::parse("a..b").is_err());
assert!(BranchName::parse("x".repeat(201).as_str()).is_err());
}
#[test]
fn commit_sha_rules() {
assert!(CommitSha::parse("0123456789abcdef0123456789abcdef01234567").is_ok());
assert!(CommitSha::parse("short").is_err());
}
#[test]
fn azure_devops_org_url_rules() {
assert!(AzureDevOpsOrgUrl::parse("https://dev.azure.com/myorg").is_ok());
assert!(AzureDevOpsOrgUrl::parse("https://myorg.visualstudio.com").is_ok());
assert!(AzureDevOpsOrgUrl::parse("https://attacker.example/myorg").is_err());
}
#[test]
fn artifact_name_rules() {
assert!(ArtifactName::parse("build-logs_1.0").is_ok());
assert!(ArtifactName::parse(".hidden").is_err());
assert!(ArtifactName::parse("has space").is_err());
assert!(ArtifactName::parse("a".repeat(101).as_str()).is_err());
}
#[test]
fn semantic_version_requires_an_exact_semver() {
assert!(SemanticVersion::parse("2.8.1").is_ok());
assert!(SemanticVersion::parse("3.0.0-beta.1").is_ok());
assert!(SemanticVersion::parse("latest").is_err());
assert!(SemanticVersion::parse("next").is_err());
assert!(SemanticVersion::parse("^2.8.0").is_err());
assert!(SemanticVersion::parse("2.8").is_err());
assert!(SemanticVersion::parse("v2.8.1").is_err());
assert!(SemanticVersion::parse("2.8.1; echo bad").is_err());
}
#[test]
fn ado_project_name_or_guid_rules() {
assert!(AdoProject::parse("Agent Playground").is_ok());
assert!(AdoProject::parse("12345678-1234-1234-1234-1234567890ab").is_ok());
assert!(AdoProject::parse("_reserved").is_err());
assert!(AdoProject::parse("bad/project").is_err());
assert!(AdoProject::parse("bad$(macro)").is_err());
assert!(AdoProject::parse("x".repeat(65)).is_err());
}
#[test]
fn ado_organization_rules() {
assert!(AdoOrganization::parse("contoso-dev").is_ok());
assert!(AdoOrganization::parse("-contoso").is_err());
assert!(AdoOrganization::parse("contoso/other").is_err());
assert!(AdoOrganization::parse("x".repeat(65)).is_err());
}
#[test]
fn ado_repository_name_or_guid_rules() {
assert!(AdoRepository::parse("Repo One").is_ok());
assert!(AdoRepository::parse("12345678-1234-1234-1234-1234567890ab").is_ok());
assert!(AdoRepository::parse("../repo").is_err());
assert!(AdoRepository::parse("bad/repo").is_err());
assert!(AdoRepository::parse("bad$(macro)").is_err());
}
#[test]
fn guid_accepts_only_the_canonical_form() {
assert!(Guid::parse("12345678-1234-1234-1234-1234567890ab").is_ok());
assert!(Guid::parse("12345678-1234-1234-1234-1234567890AB").is_ok());
assert!(Guid::parse("{12345678-1234-1234-1234-1234567890ab}").is_err());
assert!(Guid::parse("urn:uuid:12345678-1234-1234-1234-1234567890ab").is_err());
assert!(Guid::parse("12345678123412341234567890ab").is_err());
assert!(Guid::parse("12345678-1234-1234-1234-1234567890ag").is_err());
assert!(Guid::parse(" 12345678-1234-1234-1234-1234567890ab").is_err());
assert!(Guid::parse("").is_err());
}
#[test]
fn deserialize_validates() {
// Valid value round-trips.
let ok: RelativeSafePath = serde_json::from_str("\"src/lib.rs\"").unwrap();
assert_eq!(ok.as_str(), "src/lib.rs");
// Invalid value fails at deserialize time.
let err = serde_json::from_str::<RelativeSafePath>("\"../escape\"");
assert!(err.is_err());
}
#[test]
fn serialize_is_transparent() {
let p = RelativeSafePath::parse("a/b.txt").unwrap();
assert_eq!(serde_json::to_string(&p).unwrap(), "\"a/b.txt\"");
}
#[test]
fn json_schema_is_string() {
let schema = schemars::schema_for!(RelativeSafePath);
let json = serde_json::to_value(&schema).unwrap();
assert_eq!(json.get("type").and_then(|t| t.as_str()), Some("string"));
}
#[test]
fn usable_as_path() {
let p = RelativeSafePath::parse("a/b.txt").unwrap();
let joined = Path::new("/base").join(&p);
assert_eq!(joined, Path::new("/base/a/b.txt"));
}
}