compose-lens 0.3.1

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
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
//! Caller-authorized service-environment and secret-value resolution.

use crate::diagnostic::{Diagnostic, DiagnosticCode, DiagnosticLabel, Severity};
use crate::interpolation::{EnvironmentProvider, EnvironmentValue, InterpolationInput, interpolate};
use crate::merge::EntrySyntax;
use crate::model::{BooleanValue, ComposeScalar, EnvironmentFileFormatKind, SecretDefinition};
use crate::project::{ProjectEnvironmentFile, ProjectResource, ProjectService, ProjectValue, ProjectView};
use crate::source::{SourceId, SourceSpan};
use std::collections::BTreeMap;
use std::fmt;

/// A required `env_file` was not supplied by the caller-authorized provider.
pub const ENVIRONMENT_FILE_UNAVAILABLE: DiagnosticCode = DiagnosticCode::new("compose.environment.file-unavailable");
/// A supplied `env_file` contains an entry `ComposeLens` cannot interpret safely.
pub const ENVIRONMENT_FILE_INVALID_ENTRY: DiagnosticCode =
    DiagnosticCode::new("compose.environment.file-invalid-entry");
/// The caller-authorized environment-file provider denied a request.
pub const ENVIRONMENT_FILE_DENIED: DiagnosticCode = DiagnosticCode::new("compose.environment.file-denied");
/// A selected secret source could not be resolved by the caller-authorized provider.
pub const SECRET_VALUE_UNAVAILABLE: DiagnosticCode = DiagnosticCode::new("compose.secret.value-unavailable");
/// A secret definition does not identify one resolvable source.
pub const SECRET_SOURCE_UNRESOLVED: DiagnosticCode = DiagnosticCode::new("compose.secret.source-unresolved");
/// The caller-authorized secret provider denied a request.
pub const SECRET_VALUE_DENIED: DiagnosticCode = DiagnosticCode::new("compose.secret.value-denied");

/// Parser mode selected by one effective Compose `env_file` declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EnvironmentFileMode {
    /// Compose syntax including quote, escape, and interpolation handling.
    Compose,
    /// Compose `format: raw`; retain the right-hand side literally.
    Raw,
}

/// One explicit request made to a caller-owned environment-file provider.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct EnvironmentFileRequest<'a> {
    path: &'a str,
    required: bool,
    mode: EnvironmentFileMode,
    source: SourceSpan,
    sensitive: bool,
}

impl fmt::Debug for EnvironmentFileRequest<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EnvironmentFileRequest")
            .field("path", &if self.sensitive { "<redacted>" } else { self.path })
            .field("required", &self.required)
            .field("mode", &self.mode)
            .field("source", &self.source)
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

impl<'a> EnvironmentFileRequest<'a> {
    /// Returns the authored path without opening or normalizing it.
    #[must_use]
    pub const fn path(&self) -> &'a str {
        self.path
    }

    /// Reports whether Compose requires this file to exist.
    #[must_use]
    pub const fn required(&self) -> bool {
        self.required
    }

    /// Returns the selected parser mode.
    #[must_use]
    pub const fn mode(&self) -> EnvironmentFileMode {
        self.mode
    }

    /// Returns the declaration source span.
    #[must_use]
    pub const fn source(&self) -> SourceSpan {
        self.source
    }

    /// Reports whether the path itself came from sensitive interpolation.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// UTF-8 environment-file content supplied through an explicit authorization boundary.
#[derive(Clone, PartialEq, Eq)]
pub struct EnvironmentFileContent {
    text: String,
    sensitive: bool,
}

impl fmt::Debug for EnvironmentFileContent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EnvironmentFileContent")
            .field("text", &if self.sensitive { "<redacted>" } else { &self.text })
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

impl EnvironmentFileContent {
    /// Creates non-sensitive content.
    #[must_use]
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            sensitive: false,
        }
    }

    /// Creates content whose derived values must remain redacted in debug output.
    #[must_use]
    pub fn sensitive(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            sensitive: true,
        }
    }

    /// Returns content after the caller explicitly crosses the sensitivity boundary.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.text
    }

    /// Reports whether derived values must be treated as sensitive.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// Bounded failure categories for a caller-owned environment-file provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EnvironmentFileLoadError {
    /// The caller did not authorize this request.
    Denied,
}

/// Supplies environment-file bytes without granting `ComposeLens` ambient filesystem access.
pub trait EnvironmentFileProvider {
    /// Returns `None` when the selected path is unavailable.
    ///
    /// # Errors
    ///
    /// Returns [`EnvironmentFileLoadError::Denied`] when the caller did not authorize the request.
    fn load(
        &self,
        request: &EnvironmentFileRequest<'_>,
    ) -> Result<Option<EnvironmentFileContent>, EnvironmentFileLoadError>;
}

/// One final effective service-environment value.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResolvedEnvironmentValue {
    /// A concrete, possibly empty value.
    Value(EnvironmentValue),
    /// A key-only entry whose caller-authorized host lookup was unavailable.
    Unset,
}

/// Where one final effective environment entry came from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResolvedEnvironmentOrigin {
    /// One caller-supplied environment file.
    File {
        /// Authored environment-file path.
        path: String,
        /// Path declaration source span.
        source: SourceSpan,
    },
    /// The service's explicit `environment` collection.
    Service {
        /// Mapping, list key/value, or list key-only syntax.
        syntax: EntrySyntax,
        /// Effective entry source span.
        source: SourceSpan,
    },
}

/// One effective service-environment entry, sorted by name in the result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedEnvironmentEntry {
    name: String,
    value: ResolvedEnvironmentValue,
    origin: ResolvedEnvironmentOrigin,
}

impl ResolvedEnvironmentEntry {
    /// Returns the variable name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns concrete or explicitly unset state.
    #[must_use]
    pub const fn value(&self) -> &ResolvedEnvironmentValue {
        &self.value
    }

    /// Returns the final value's source category and span.
    #[must_use]
    pub const fn origin(&self) -> &ResolvedEnvironmentOrigin {
        &self.origin
    }
}

/// Result of one explicit service-environment resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceEnvironmentResolution {
    entries: Vec<ResolvedEnvironmentEntry>,
    diagnostics: Vec<Diagnostic>,
}

impl ServiceEnvironmentResolution {
    /// Returns final entries in deterministic key order.
    #[must_use]
    pub fn entries(&self) -> &[ResolvedEnvironmentEntry] {
        &self.entries
    }

    /// Returns file-loading, parsing, and interpolation diagnostics.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether resolution emitted no error diagnostics.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
    }
}

/// Resolves one service's environment only through caller-owned providers.
///
/// Environment files are applied in declaration order, then service `environment` entries
/// override them. The result is sorted by key. Key-only entries remain explicitly unset when
/// the supplied environment provider has no value.
#[must_use]
pub fn resolve_service_environment(
    service: &ProjectService,
    environment: &dyn EnvironmentProvider,
    files: &dyn EnvironmentFileProvider,
) -> ServiceEnvironmentResolution {
    let mut entries = BTreeMap::new();
    let mut diagnostics = Vec::new();

    if let Some(environment_files) = service.environment_files() {
        for file in environment_files.value() {
            resolve_environment_file(file, environment, files, &mut entries, &mut diagnostics);
        }
    }

    if let Some(service_environment) = service.environment() {
        for entry in service_environment.value().entries() {
            let source = entry
                .value()
                .effective_source()
                .or_else(|| entry.name().effective_source())
                .unwrap_or_else(empty_span);
            let value = match entry.value().value() {
                ComposeScalar::Null => environment
                    .get(entry.name().value())
                    .map_or(ResolvedEnvironmentValue::Unset, ResolvedEnvironmentValue::Value),
                scalar => {
                    ResolvedEnvironmentValue::Value(scalar_environment_value(scalar, entry.value().is_sensitive()))
                }
            };
            entries.insert(
                entry.name().value().to_owned(),
                ResolvedEnvironmentEntry {
                    name: entry.name().value().to_owned(),
                    value,
                    origin: ResolvedEnvironmentOrigin::Service {
                        syntax: entry.syntax(),
                        source,
                    },
                },
            );
        }
    }

    ServiceEnvironmentResolution {
        entries: entries.into_values().collect(),
        diagnostics,
    }
}

fn resolve_environment_file(
    file: &ProjectValue<ProjectEnvironmentFile>,
    environment: &dyn EnvironmentProvider,
    files: &dyn EnvironmentFileProvider,
    entries: &mut BTreeMap<String, ResolvedEnvironmentEntry>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let (path, required, mode, source, sensitive) = match file.value() {
        ProjectEnvironmentFile::Short(path) => (
            path.as_str(),
            true,
            EnvironmentFileMode::Compose,
            file.effective_source().unwrap_or_else(empty_span),
            file.is_sensitive(),
        ),
        ProjectEnvironmentFile::Long(long) => {
            let Some(path) = long.path() else {
                return;
            };
            let required = match long.required().map(ProjectValue::value) {
                Some(BooleanValue::Literal(value)) => *value,
                _ => true,
            };
            let mode = match long.format().map(ProjectValue::value) {
                Some(format) if format.kind() == EnvironmentFileFormatKind::Raw => EnvironmentFileMode::Raw,
                _ => EnvironmentFileMode::Compose,
            };
            (
                path.value().as_str(),
                required,
                mode,
                path.effective_source().unwrap_or_else(empty_span),
                path.is_sensitive(),
            )
        }
    };
    let request = EnvironmentFileRequest {
        path,
        required,
        mode,
        source,
        sensitive,
    };
    let content = match files.load(&request) {
        Ok(Some(content)) => content,
        Ok(None) => {
            if required {
                diagnostics.push(diagnostic_at(
                    ENVIRONMENT_FILE_UNAVAILABLE,
                    Severity::Error,
                    "required environment file was not supplied by the caller-authorized provider",
                    source,
                    "required environment file declared here",
                ));
            }
            return;
        }
        Err(EnvironmentFileLoadError::Denied) => {
            diagnostics.push(diagnostic_at(
                ENVIRONMENT_FILE_DENIED,
                Severity::Error,
                "caller-owned environment-file provider denied the request",
                source,
                "environment file requested here",
            ));
            return;
        }
    };
    parse_environment_file(&request, &content, environment, entries, diagnostics);
}

fn parse_environment_file(
    request: &EnvironmentFileRequest<'_>,
    content: &EnvironmentFileContent,
    environment: &dyn EnvironmentProvider,
    entries: &mut BTreeMap<String, ResolvedEnvironmentEntry>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for raw_line in content.expose().lines() {
        let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let (name, raw_value) = line
            .split_once('=')
            .map_or((trimmed, None), |(name, value)| (name.trim(), Some(value)));
        if !valid_environment_name(name) {
            diagnostics.push(diagnostic_at(
                ENVIRONMENT_FILE_INVALID_ENTRY,
                Severity::Error,
                "environment file contains an invalid variable name",
                request.source,
                "environment file declared here",
            ));
            continue;
        }
        let value = match raw_value {
            None => environment
                .get(name)
                .map_or(ResolvedEnvironmentValue::Unset, ResolvedEnvironmentValue::Value),
            Some(raw_value) => {
                let Ok(decoded) = decode_environment_file_value(raw_value, request.mode) else {
                    diagnostics.push(diagnostic_at(
                        ENVIRONMENT_FILE_INVALID_ENTRY,
                        Severity::Error,
                        "environment file contains an unterminated quoted value",
                        request.source,
                        "environment file declared here",
                    ));
                    continue;
                };
                let (value, interpolate_value) = decoded;
                let value = if interpolate_value {
                    let input = if content.is_sensitive() {
                        InterpolationInput::new(&value, request.source).sensitive()
                    } else {
                        InterpolationInput::new(&value, request.source)
                    };
                    let interpolation = interpolate(input, environment);
                    diagnostics.extend(interpolation.diagnostics().iter().cloned());
                    if interpolation.is_sensitive() {
                        EnvironmentValue::sensitive(interpolation.resolved())
                    } else {
                        EnvironmentValue::plain(interpolation.resolved())
                    }
                } else if content.is_sensitive() {
                    EnvironmentValue::sensitive(value)
                } else {
                    EnvironmentValue::plain(value)
                };
                ResolvedEnvironmentValue::Value(value)
            }
        };
        entries.insert(
            name.to_owned(),
            ResolvedEnvironmentEntry {
                name: name.to_owned(),
                value,
                origin: ResolvedEnvironmentOrigin::File {
                    path: request.path.to_owned(),
                    source: request.source,
                },
            },
        );
    }
}

fn decode_environment_file_value(raw: &str, mode: EnvironmentFileMode) -> Result<(String, bool), ()> {
    if mode == EnvironmentFileMode::Raw {
        return Ok((raw.to_owned(), false));
    }
    let value = raw.trim();
    if let Some(quoted) = value.strip_prefix('\'') {
        let Some(quoted) = quoted.strip_suffix('\'') else {
            return Err(());
        };
        return Ok((quoted.replace("\\'", "'"), false));
    }
    if let Some(quoted) = value.strip_prefix('"') {
        let Some(quoted) = quoted.strip_suffix('"') else {
            return Err(());
        };
        let mut decoded = String::with_capacity(quoted.len());
        let mut characters = quoted.chars();
        while let Some(character) = characters.next() {
            if character != '\\' {
                decoded.push(character);
                continue;
            }
            match characters.next() {
                Some('n') => decoded.push('\n'),
                Some('r') => decoded.push('\r'),
                Some('t') => decoded.push('\t'),
                Some('\\') | None => decoded.push('\\'),
                Some('"') => decoded.push('"'),
                Some(other) => {
                    decoded.push('\\');
                    decoded.push(other);
                }
            }
        }
        return Ok((decoded, true));
    }
    let value = value.find(" #").map_or(value, |comment| value[..comment].trim_end());
    Ok((value.to_owned(), true))
}

fn valid_environment_name(name: &str) -> bool {
    !name.is_empty()
        && !name
            .chars()
            .any(|character| character == '=' || character == '\0' || character.is_whitespace())
}

fn scalar_environment_value(value: &ComposeScalar, sensitive: bool) -> EnvironmentValue {
    let value = match value {
        ComposeScalar::Null => String::new(),
        ComposeScalar::Boolean(value) => value.to_string(),
        ComposeScalar::Number(value) | ComposeScalar::String(value) => value.clone(),
    };
    if sensitive {
        EnvironmentValue::sensitive(value)
    } else {
        EnvironmentValue::plain(value)
    }
}

/// One top-level Compose secret's selected native source.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SecretSource {
    /// Caller-owned file path.
    File(String),
    /// Caller-owned host environment-variable name.
    Environment(String),
    /// Platform-managed external secret name.
    External(String),
    /// Opaque provider driver name.
    Driver(String),
}

/// One explicit request to a caller-owned secret provider.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretRequest {
    name: String,
    source: SecretSource,
    source_span: SourceSpan,
}

impl SecretRequest {
    /// Returns the Compose secret name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the source `ComposeLens` selected without reading it.
    #[must_use]
    pub const fn source(&self) -> &SecretSource {
        &self.source
    }

    /// Returns the source declaration span.
    #[must_use]
    pub const fn source_span(&self) -> SourceSpan {
        self.source_span
    }
}

/// Secret payload exposed only through an explicit accessor and always redacted in `Debug`.
#[derive(Clone, PartialEq, Eq)]
pub struct SecretValue(String);

impl fmt::Debug for SecretValue {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("SecretValue(<redacted>)")
    }
}

impl SecretValue {
    /// Wraps a caller-authorized secret payload.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the payload after the caller explicitly crosses the sensitivity boundary.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }
}

/// Bounded failure categories for a caller-owned secret provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SecretResolveError {
    /// The caller did not authorize this request.
    Denied,
}

/// Resolves selected secret sources without granting `ComposeLens` ambient access.
pub trait SecretProvider {
    /// Returns `None` when the provider cannot resolve the selected source.
    ///
    /// # Errors
    ///
    /// Returns [`SecretResolveError::Denied`] when the caller did not authorize the request.
    fn resolve(&self, request: &SecretRequest) -> Result<Option<SecretValue>, SecretResolveError>;
}

/// One caller-authorized resolved top-level secret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedSecret {
    request: SecretRequest,
    value: SecretValue,
}

impl ResolvedSecret {
    /// Returns the source request retained as provenance.
    #[must_use]
    pub const fn request(&self) -> &SecretRequest {
        &self.request
    }

    /// Returns the protected payload wrapper.
    #[must_use]
    pub const fn value(&self) -> &SecretValue {
        &self.value
    }
}

/// Result of one explicit top-level secret-resolution operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretResolution {
    secrets: Vec<ResolvedSecret>,
    diagnostics: Vec<Diagnostic>,
}

impl SecretResolution {
    /// Returns resolved secrets in deterministic Compose-name order.
    #[must_use]
    pub fn secrets(&self) -> &[ResolvedSecret] {
        &self.secrets
    }

    /// Returns unavailable, ambiguous, or denied-source diagnostics.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether resolution emitted no error diagnostics.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
    }
}

/// Resolves top-level secret definitions only through a caller-owned provider.
#[must_use]
pub fn resolve_project_secrets(project: &ProjectView, provider: &dyn SecretProvider) -> SecretResolution {
    let mut resources: Vec<_> = project.secrets().iter().collect();
    resources.sort_by(|left, right| left.name().value().cmp(right.name().value()));
    let mut secrets = Vec::new();
    let mut diagnostics = Vec::new();
    for resource in resources {
        let Some(request) = secret_request(resource) else {
            let span = resource.definition().effective_source().unwrap_or_else(empty_span);
            diagnostics.push(diagnostic_at(
                SECRET_SOURCE_UNRESOLVED,
                Severity::Error,
                "secret definition must select exactly one caller-resolvable source",
                span,
                "secret source cannot be selected here",
            ));
            continue;
        };
        match provider.resolve(&request) {
            Ok(Some(value)) => secrets.push(ResolvedSecret { request, value }),
            Ok(None) => diagnostics.push(diagnostic_at(
                SECRET_VALUE_UNAVAILABLE,
                Severity::Error,
                "secret payload was not supplied by the caller-authorized provider",
                request.source_span,
                "secret source declared here",
            )),
            Err(SecretResolveError::Denied) => diagnostics.push(diagnostic_at(
                SECRET_VALUE_DENIED,
                Severity::Error,
                "caller-owned secret provider denied the request",
                request.source_span,
                "secret source requested here",
            )),
        }
    }
    SecretResolution { secrets, diagnostics }
}

fn secret_request(resource: &ProjectResource<SecretDefinition>) -> Option<SecretRequest> {
    let definition = resource.definition().value();
    let mut sources = Vec::new();
    if let Some(file) = definition.file() {
        sources.push((SecretSource::File(file.value().clone()), file.span()));
    }
    if let Some(environment) = definition.environment() {
        sources.push((
            SecretSource::Environment(environment.value().clone()),
            environment.span(),
        ));
    }
    if let Some(driver) = definition.driver() {
        sources.push((SecretSource::Driver(driver.value().clone()), driver.span()));
    }
    if let Some(external) = definition
        .external()
        .filter(|external| external.is_explicitly_external())
    {
        let (name, span) = definition
            .custom_name()
            .map(|name| (name.value().clone(), name.span()))
            .or_else(|| {
                external
                    .name_mapping()
                    .and_then(|mapping| mapping.name().map(|name| (name.value().clone(), name.span())))
            })
            .unwrap_or_else(|| {
                (
                    resource.name().value().to_owned(),
                    external.name_mapping().map_or_else(
                        || resource.definition().effective_source().unwrap_or_else(empty_span),
                        crate::model::ExternalNameMapping::span,
                    ),
                )
            });
        sources.push((SecretSource::External(name), span));
    }
    if sources.len() != 1 {
        return None;
    }
    let (source, source_span) = sources.pop()?;
    Some(SecretRequest {
        name: resource.name().value().to_owned(),
        source,
        source_span,
    })
}

fn diagnostic_at(
    code: DiagnosticCode,
    severity: Severity,
    message: &'static str,
    source: SourceSpan,
    label: &'static str,
) -> Diagnostic {
    Diagnostic::new(code, severity, message).with_label(DiagnosticLabel::primary(source, label))
}

fn empty_span() -> SourceSpan {
    SourceSpan::from_valid_offsets(SourceId::new(0), 0, 0)
}