envorigin 1.6.0

Explain where environment variables come from in Docker Compose and GitHub Actions
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
//! LSP server: hover, go-to-definition, and live diagnostics for the four
//! configuration backends.
//!
//! The server routes each opened document to the matching analyzer by file
//! name. Unsaved buffer edits are analyzed in memory via the with_content
//! analyzer variants. Diagnostics mirror the
//! `audit` findings per variable: undefined interpolation references,
//! shadowed dead-code lines, sensitive values, and analyzer warnings.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;

use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService};

use crate::actions;
use crate::circleci;
use crate::gitlab;
use crate::model::{Diagnostic as EnvDiagnostic, Severity as EnvSeverity};
use crate::AnalyzeOptions;

#[derive(Debug, Clone)]
struct Symbol {
    name: String,
    /// 1-based line of the variable definition in the analyzed document.
    line: usize,
    state: String,
    /// Redacted or expression-form value.
    value: Option<String>,
    winner_label: String,
    winner_path: Option<std::path::PathBuf>,
    winner_line: Option<usize>,
}

#[derive(Debug, Clone)]
struct LspDiag {
    line: Option<usize>,
    severity: DiagnosticSeverity,
    code: String,
    message: String,
}

type SymbolTuple = (
    String,
    usize,
    String,
    Option<String>,
    String,
    Option<std::path::PathBuf>,
    Option<usize>,
);

#[derive(Debug, Clone, Default)]
struct LspAnalysis {
    symbols: Vec<Symbol>,
    diagnostics: Vec<LspDiag>,
}

pub struct Backend {
    client: Client,
    cache: Mutex<HashMap<Url, LspAnalysis>>,
}

fn severity(severity: EnvSeverity) -> DiagnosticSeverity {
    match severity {
        EnvSeverity::Info => DiagnosticSeverity::INFORMATION,
        EnvSeverity::Warning => DiagnosticSeverity::WARNING,
        EnvSeverity::Error => DiagnosticSeverity::ERROR,
    }
}

fn from_env_diag(diagnostic: &EnvDiagnostic) -> LspDiag {
    LspDiag {
        line: None,
        severity: severity(diagnostic.severity),
        code: diagnostic.code.clone(),
        message: diagnostic.message.clone(),
    }
}

/// Route a file to its analyzer and extract symbols + diagnostics.
fn analyze_file(
    path: &Path,
    content: Option<&str>,
) -> std::result::Result<LspAnalysis, Box<dyn std::error::Error>> {
    let file_name = path
        .file_name()
        .map(|name| name.to_string_lossy().to_string())
        .unwrap_or_default();
    let parent = path
        .parent()
        .map(|dir| dir.display().to_string())
        .unwrap_or_default();
    let workflow_dir = parent.ends_with(".github/workflows");
    let is_compose = matches!(
        file_name.as_str(),
        "compose.yaml" | "compose.yml" | "docker-compose.yaml" | "docker-compose.yml"
    );

    let mut analysis = LspAnalysis::default();
    let mut collect = |symbols: Vec<SymbolTuple>, diagnostics: Vec<LspDiag>| {
        analysis.symbols = symbols
            .into_iter()
            .map(
                |(name, line, state, value, winner_label, winner_path, winner_line)| Symbol {
                    name,
                    line,
                    state,
                    value,
                    winner_label,
                    winner_path,
                    winner_line,
                },
            )
            .collect();
        analysis.diagnostics = diagnostics;
    };

    if is_compose {
        let report = crate::analyze_with_content(
            &AnalyzeOptions {
                compose_file: path.to_path_buf(),
                docker_check: false,
                ..AnalyzeOptions::default()
            },
            content,
        )?;
        let mut symbols = Vec::new();
        let mut diagnostics = Vec::new();
        for diagnostic in &report.diagnostics {
            diagnostics.push(from_env_diag(diagnostic));
        }
        for service in &report.services {
            for variable in &service.variables {
                let line = variable
                    .winner
                    .as_ref()
                    .and_then(|winner| winner.line)
                    .unwrap_or(1);
                let winner_label = variable
                    .winner
                    .as_ref()
                    .map(|winner| format!("{:?} ({})", winner.kind, winner.label()))
                    .unwrap_or_else(|| "unknown source".to_string());
                let (winner_path, winner_line) = variable
                    .winner
                    .as_ref()
                    .map(|winner| (winner.path.clone(), winner.line))
                    .unwrap_or((None, None));
                symbols.push((
                    variable.variable.clone(),
                    line,
                    match variable.state {
                        crate::model::VariableState::Present => "set".to_string(),
                        crate::model::VariableState::Absent => "absent".to_string(),
                    },
                    variable.value.clone(),
                    winner_label,
                    winner_path,
                    winner_line,
                ));
                for diagnostic in &variable.diagnostics {
                    let mut diag = from_env_diag(diagnostic);
                    diag.line = Some(line);
                    diagnostics.push(diag);
                }
            }
        }
        collect(symbols, diagnostics);
    } else if workflow_dir && (file_name.ends_with(".yml") || file_name.ends_with(".yaml")) {
        let report = actions::analyze_workflow_with_content(path, None, content)?;
        let mut symbols = Vec::new();
        let mut diagnostics = Vec::new();
        for diagnostic in &report.diagnostics {
            diagnostics.push(from_env_diag(diagnostic));
        }
        for job in &report.jobs {
            for step in &job.steps {
                for diagnostic in &step.diagnostics {
                    // Step-level diagnostics (e.g. GITHUB_ENV runtime writes)
                    // anchor on the step's variable lines when possible.
                    let line = step
                        .variables
                        .first()
                        .and_then(|variable| {
                            variable.winner.as_ref().and_then(|winner| winner.line)
                        })
                        .unwrap_or(1);
                    let mut diag = from_env_diag(diagnostic);
                    diag.line = Some(line);
                    diagnostics.push(diag);
                }
            }
            for variable in job
                .variables
                .iter()
                .chain(job.steps.iter().flat_map(|step| step.variables.iter()))
            {
                let line = variable
                    .winner
                    .as_ref()
                    .and_then(|winner| winner.line)
                    .unwrap_or(1);
                let winner_label = variable
                    .winner
                    .as_ref()
                    .map(|winner| format!("{:?} ({})", winner.kind, winner.label()))
                    .unwrap_or_else(|| "unknown source".to_string());
                let (winner_path, winner_line) = variable
                    .winner
                    .as_ref()
                    .map(|winner| (winner.path.clone(), winner.line))
                    .unwrap_or((None, None));
                symbols.push((
                    variable.variable.clone(),
                    line,
                    match variable.state {
                        crate::model::VariableState::Present => "set".to_string(),
                        crate::model::VariableState::Absent => "absent".to_string(),
                    },
                    variable.value.clone(),
                    winner_label,
                    winner_path,
                    winner_line,
                ));
                for diagnostic in &variable.diagnostics {
                    let mut diag = from_env_diag(diagnostic);
                    diag.line = Some(line);
                    diagnostics.push(diag);
                }
            }
        }
        collect(symbols, diagnostics);
    } else if file_name == ".gitlab-ci.yml" {
        let report = gitlab::analyze_gitlab_with_content(path, content)?;
        let mut symbols = Vec::new();
        let mut diagnostics = Vec::new();
        for diagnostic in &report.diagnostics {
            diagnostics.push(from_env_diag(diagnostic));
        }
        let mut all: Vec<&gitlab::GitlabVariable> = report
            .global_variables
            .iter()
            .chain(report.jobs.iter().flat_map(|job| job.variables.iter()))
            .collect();
        all.sort_by_key(|variable| {
            variable
                .winner
                .as_ref()
                .and_then(|winner| winner.line)
                .unwrap_or(1)
        });
        all.dedup_by_key(|variable| variable.variable.clone());
        for variable in all {
            let line = variable
                .winner
                .as_ref()
                .and_then(|winner| winner.line)
                .unwrap_or(1);
            let winner_label = variable
                .winner
                .as_ref()
                .map(|winner| format!("{:?} ({})", winner.kind, winner.label()))
                .unwrap_or_else(|| "unknown source".to_string());
            let (winner_path, winner_line) = variable
                .winner
                .as_ref()
                .map(|winner| (winner.path.clone(), winner.line))
                .unwrap_or((None, None));
            symbols.push((
                variable.variable.clone(),
                line,
                match variable.state {
                    crate::model::VariableState::Present => "set".to_string(),
                    crate::model::VariableState::Absent => "absent".to_string(),
                },
                variable.value.clone(),
                winner_label,
                winner_path,
                winner_line,
            ));
            for diagnostic in &variable.diagnostics {
                let mut diag = from_env_diag(diagnostic);
                diag.line = Some(line);
                diagnostics.push(diag);
            }
        }
        collect(symbols, diagnostics);
    } else if file_name == "config.yml" && parent.ends_with(".circleci") {
        let report = circleci::analyze_circleci_with_content(path, content)?;
        let mut symbols = Vec::new();
        let mut diagnostics = Vec::new();
        for diagnostic in &report.diagnostics {
            diagnostics.push(from_env_diag(diagnostic));
        }
        for job in &report.jobs {
            for variable in &job.variables {
                let line = variable
                    .winner
                    .as_ref()
                    .and_then(|winner| winner.line)
                    .unwrap_or(1);
                let winner_label = variable
                    .winner
                    .as_ref()
                    .map(|winner| format!("{:?} ({})", winner.kind, winner.label()))
                    .unwrap_or_else(|| "unknown source".to_string());
                let (winner_path, winner_line) = variable
                    .winner
                    .as_ref()
                    .map(|winner| (winner.path.clone(), winner.line))
                    .unwrap_or((None, None));
                symbols.push((
                    variable.variable.clone(),
                    line,
                    match variable.state {
                        crate::model::VariableState::Present => "set".to_string(),
                        crate::model::VariableState::Absent => "absent".to_string(),
                    },
                    variable.value.clone(),
                    winner_label,
                    winner_path,
                    winner_line,
                ));
                for diagnostic in &variable.diagnostics {
                    let mut diag = from_env_diag(diagnostic);
                    diag.line = Some(line);
                    diagnostics.push(diag);
                }
            }
        }
        collect(symbols, diagnostics);
    } else {
        return Ok(LspAnalysis::default());
    }
    Ok(analysis)
}

fn symbol_at_line(analysis: &LspAnalysis, line: u32) -> Option<&Symbol> {
    analysis
        .symbols
        .iter()
        .find(|symbol| symbol.line == line as usize + 1)
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                definition_provider: Some(OneOf::Left(true)),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        let _ = self
            .client
            .log_message(MessageType::INFO, "envorigin LSP ready")
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let content = params.text_document.text.clone();
        self.analyze_and_publish(&params.text_document.uri, Some(&content))
            .await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        // FULL sync: the last change carries the entire buffer.
        let content = params
            .content_changes
            .last()
            .map(|change| change.text.clone());
        self.analyze_and_publish(&params.text_document.uri, content.as_deref())
            .await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        self.analyze_and_publish(&params.text_document.uri, None)
            .await;
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let cache = self.cache.lock().unwrap();
        let Some(analysis) = cache.get(&uri) else {
            return Ok(None);
        };
        let Some(symbol) = symbol_at_line(analysis, position.line) else {
            return Ok(None);
        };
        let value = symbol
            .value
            .as_deref()
            .map(|value| format!(" = `{value}`"))
            .unwrap_or_default();
        let markdown = format!(
            "`{}` · {}{}\n\n{}",
            symbol.name, symbol.state, value, symbol.winner_label
        );
        Ok(Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: markdown,
            }),
            range: Some(Range {
                start: Position {
                    line: position.line,
                    character: 0,
                },
                end: Position {
                    line: position.line,
                    character: 0,
                },
            }),
        }))
    }

    async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Result<Option<GotoDefinitionResponse>> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let cache = self.cache.lock().unwrap();
        let Some(analysis) = cache.get(&uri) else {
            return Ok(None);
        };
        let Some(symbol) = symbol_at_line(analysis, position.line) else {
            return Ok(None);
        };
        let Some((path, line)) = symbol.winner_path.as_ref().zip(symbol.winner_line) else {
            return Ok(None);
        };
        let Ok(target_uri) = Url::from_file_path(path) else {
            return Ok(None);
        };
        Ok(Some(GotoDefinitionResponse::Scalar(Location {
            uri: target_uri,
            range: Range {
                start: Position {
                    line: line.saturating_sub(1) as u32,
                    character: 0,
                },
                end: Position {
                    line: line.saturating_sub(1) as u32,
                    character: 0,
                },
            },
        })))
    }
}

impl Backend {
    async fn analyze_and_publish(&self, uri: &Url, buffer: Option<&str>) {
        let Some(path) = uri.to_file_path().ok() else {
            return;
        };
        // Unsaved buffer edits are analyzed in memory; relative references
        // (env_file, includes, env files) still resolve against the real
        // file location.
        let analysis = analyze_file(&path, buffer).unwrap_or_default();
        {
            let mut cache = self.cache.lock().unwrap();
            cache.insert(uri.clone(), analysis.clone());
        }
        let diagnostics: Vec<Diagnostic> = analysis
            .diagnostics
            .iter()
            .map(|diag| Diagnostic {
                range: Range {
                    start: Position {
                        line: diag.line.unwrap_or(1).saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: diag.line.unwrap_or(1).saturating_sub(1) as u32,
                        character: 0,
                    },
                },
                severity: Some(diag.severity),
                code: Some(NumberOrString::String(diag.code.clone())),
                message: diag.message.clone(),
                ..Default::default()
            })
            .collect();
        self.client
            .publish_diagnostics(uri.clone(), diagnostics, None)
            .await;
    }
}

pub fn run_lsp() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    runtime.block_on(async {
        let stdin = tokio::io::stdin();
        let stdout = tokio::io::stdout();
        let (service, socket) = LspService::new(|client| Backend {
            client,
            cache: Mutex::new(HashMap::new()),
        });
        tower_lsp::Server::new(stdin, stdout, socket)
            .serve(service)
            .await;
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn actions_branch_includes_step_diagnostics() {
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/actions/.github/workflows/workflow.yaml");
        let content = std::fs::read_to_string(&path).unwrap();
        let report =
            crate::actions::analyze_workflow_with_content(&path, None, Some(&content)).unwrap();
        let steps = report.jobs.iter().flat_map(|job| &job.steps).count();
        let step_diags: Vec<&str> = report
            .jobs
            .iter()
            .flat_map(|job| job.steps.iter().flat_map(|step| step.diagnostics.iter()))
            .map(|diag| diag.code.as_str())
            .collect();
        assert_eq!(steps, 5, "expected 5 steps, jobs={}", report.jobs.len());
        assert!(
            step_diags.contains(&"github-env-runtime"),
            "step diagnostics missing, got {step_diags:?}"
        );
        let analysis = analyze_file(&path, Some(&content)).unwrap();
        let codes: Vec<&str> = analysis
            .diagnostics
            .iter()
            .map(|diag| diag.code.as_str())
            .collect();
        assert!(
            codes.contains(&"github-env-runtime"),
            "step diagnostics missing, got {codes:?}"
        );
    }

    #[test]
    fn gitlab_branch_includes_report_diagnostics() {
        let path =
            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/gitlab/.gitlab-ci.yml");
        let content = std::fs::read_to_string(&path).unwrap();
        let analysis = analyze_file(&path, Some(&content)).unwrap();
        let codes: Vec<&str> = analysis
            .diagnostics
            .iter()
            .map(|diag| diag.code.as_str())
            .collect();
        assert!(codes.contains(&"gitlab-include-external"), "got {codes:?}");
    }
}