zizmor 1.24.1

Static analysis for GitHub Actions
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
//! zizmor's language server.

use std::str::FromStr;
use tokio::sync::RwLock;

use camino::{Utf8Path, Utf8PathBuf};
use thiserror::Error;
use tower_lsp_server::ls_types::{self, TextDocumentSyncKind};
use tower_lsp_server::{Client, LanguageServer, LspService, Server};

use crate::audit::AuditInput;
use crate::config::Config;
use crate::finding::location::Point;
use crate::finding::{Persona, Severity};
use crate::models::action::Action;
use crate::models::dependabot::Dependabot;
use crate::models::workflow::Workflow;
use crate::registry::input::{InputGroup, InputRegistry};
use crate::registry::{FindingRegistry, input::InputKey};
use crate::{AuditRegistry, AuditState};

#[derive(Debug, Error)]
#[error("LSP server error")]
pub(crate) struct Error {
    #[from]
    inner: anyhow::Error,
}

struct LspDocumentCommon {
    uri: ls_types::Uri,
    text: String,
    version: Option<i32>,
}

#[derive(Debug)]
struct Backend {
    audit_registry: AuditRegistry,
    client: Client,
    /// Currently opened workspace directories.
    /// These directories are used to discover configuration files that
    /// apply to audits.
    workspace_dirs: RwLock<Vec<Utf8PathBuf>>,
}

impl LanguageServer for Backend {
    async fn initialize(
        &self,
        params: ls_types::InitializeParams,
    ) -> tower_lsp_server::jsonrpc::Result<ls_types::InitializeResult> {
        if let Some(workspaces) = params.workspace_folders {
            for workspace in workspaces {
                let path = workspace.uri.path();
                if path.is_empty() {
                    self.client
                        .log_message(
                            ls_types::MessageType::WARNING,
                            format!(
                                "skipping workspace folder with empty path: {:?}",
                                workspace.uri
                            ),
                        )
                        .await;
                    continue;
                }

                let path = Utf8PathBuf::from_str(path.as_str()).map_err(|_| {
                    // TODO: Log warning instead of erroring here?
                    tower_lsp_server::jsonrpc::Error::invalid_params(format!(
                        "workspace folder path is not valid UTF-8: {:?}",
                        workspace.uri
                    ))
                })?;

                // TODO: Can this actually happen?
                if !path.is_dir() {
                    self.client
                        .log_message(
                            ls_types::MessageType::WARNING,
                            format!(
                                "skipping workspace folder that is not a directory: {}",
                                path
                            ),
                        )
                        .await;
                    continue;
                }

                self.workspace_dirs.write().await.push(path);
            }
        }

        Ok(ls_types::InitializeResult {
            server_info: Some(ls_types::ServerInfo {
                name: "zizmor (LSP)".into(),
                version: Some(env!("CARGO_PKG_VERSION").into()),
            }),
            capabilities: ls_types::ServerCapabilities {
                text_document_sync: Some(ls_types::TextDocumentSyncCapability::Kind(
                    ls_types::TextDocumentSyncKind::FULL,
                )),
                ..Default::default()
            },
        })
    }

    async fn initialized(&self, _: ls_types::InitializedParams) {
        let selectors = vec![
            // Auditable inputs.
            ls_types::DocumentFilter {
                language: Some("yaml".into()),
                scheme: None,
                pattern: Some("**/.github/workflows/*.{yml,yaml}".into()),
            },
            ls_types::DocumentFilter {
                language: Some("yaml".into()),
                scheme: None,
                pattern: Some("**/action.{yml,yaml}".into()),
            },
            ls_types::DocumentFilter {
                language: Some("yaml".into()),
                scheme: None,
                pattern: Some("**/.github/dependabot.{yml,yaml}".into()),
            },
            // Config files.
            // TODO: Right now these are disabled, but at some point we might want to independently
            // monitor these and only reload the configuration when they change.
            //
            // ls_types::DocumentFilter {
            //     language: Some("yaml".into()),
            //     scheme: None,
            //     pattern: Some("**/zizmor.yml".into()),
            // },
            // ls_types::DocumentFilter {
            //     language: Some("yaml".into()),
            //     scheme: None,
            //     pattern: Some("**/.github/zizmor.yml".into()),
            // },
        ];

        // Register our capabilities with the client.
        // Clients like the VS Code extension should do this for us, but we
        // also explicitly request these capabilities in case the client/integration
        // neglects to.
        self.client
            .register_capability(vec![
                ls_types::Registration {
                    id: "zizmor-didopen".into(),
                    method: "textDocument/didOpen".into(),
                    register_options: Some(
                        serde_json::to_value(ls_types::TextDocumentRegistrationOptions {
                            document_selector: Some(selectors.clone()),
                        })
                        .expect("failed to serialize LSP document registration options"),
                    ),
                },
                ls_types::Registration {
                    id: "zizmor-didchange".into(),
                    method: "textDocument/didChange".into(),
                    register_options: Some(
                        serde_json::to_value(ls_types::TextDocumentChangeRegistrationOptions {
                            document_selector: Some(selectors.clone()),
                            sync_kind: TextDocumentSyncKind::FULL,
                        })
                        .expect("failed to serialize LSP document registration options"),
                    ),
                },
                ls_types::Registration {
                    id: "zizmor-didsave".into(),
                    method: "textDocument/didSave".into(),
                    register_options: Some(
                        serde_json::to_value(ls_types::TextDocumentSaveRegistrationOptions {
                            include_text: Some(true),
                            text_document_registration_options:
                                ls_types::TextDocumentRegistrationOptions {
                                    document_selector: Some(selectors.clone()),
                                },
                        })
                        .expect("failed to serialize LSP document registration options"),
                    ),
                },
                ls_types::Registration {
                    id: "zizmor-didclose".into(),
                    method: "textDocument/didClose".into(),
                    register_options: Some(
                        serde_json::to_value(ls_types::TextDocumentRegistrationOptions {
                            document_selector: Some(selectors),
                        })
                        .expect("failed to serialize LSP document registration options"),
                    ),
                },
            ])
            .await
            .expect("failed to register text document capabilities with the LSP client");

        self.client
            .log_message(ls_types::MessageType::INFO, "server initialized!")
            .await;

        self.client
            .log_message(
                ls_types::MessageType::INFO,
                format!(
                    "server workspace_dirs: {:?}",
                    self.workspace_dirs.read().await.as_slice()
                ),
            )
            .await;
    }

    async fn shutdown(&self) -> tower_lsp_server::jsonrpc::Result<()> {
        tracing::debug!("graceful shutdown requested");
        Ok(())
    }

    async fn did_open(&self, params: ls_types::DidOpenTextDocumentParams) {
        tracing::debug!("did_open: {:?}", params);
        self.perform(LspDocumentCommon {
            uri: params.text_document.uri,
            text: params.text_document.text,
            version: Some(params.text_document.version),
        })
        .await;
    }

    async fn did_change(&self, params: ls_types::DidChangeTextDocumentParams) {
        tracing::debug!("did_change: {:?}", params);
        let mut params = params;
        let Some(change) = params.content_changes.pop() else {
            return;
        };

        self.perform(LspDocumentCommon {
            uri: params.text_document.uri,
            text: change.text,
            version: Some(params.text_document.version),
        })
        .await;
    }

    async fn did_save(&self, params: ls_types::DidSaveTextDocumentParams) {
        tracing::debug!("did_save: {:?}", params);
        if let Some(text) = params.text {
            self.perform(LspDocumentCommon {
                uri: params.text_document.uri,
                text,
                version: None,
            })
            .await;
        }
    }
}

impl Backend {
    async fn audit_inner(&self, params: LspDocumentCommon) -> anyhow::Result<()> {
        tracing::debug!("analyzing: {:?} (version={:?})", params.uri, params.version);
        let path = Utf8Path::new(params.uri.path().as_str());
        let input = if matches!(path.file_name(), Some("action.yml" | "action.yaml")) {
            AuditInput::from(Action::from_string(
                params.text,
                InputKey::local("lsp".into(), path, None),
            )?)
        } else if matches!(path.file_name(), Some("dependabot.yml")) {
            AuditInput::from(Dependabot::from_string(
                params.text,
                InputKey::local("lsp".into(), path, None),
            )?)
        } else if matches!(path.extension(), Some("yml" | "yaml")) {
            AuditInput::from(Workflow::from_string(
                params.text,
                InputKey::local("lsp".into(), path, None),
            )?)
        } else {
            anyhow::bail!("asked to audit unexpected file: {path}");
        };

        // Try to find a configuration file for this audit.
        // The approach below is probably wrong: we scan each workspace directory
        // in order and use the first configuration we find. Instead, we should
        // probably find the configuration file that is in the "closest"
        // workspace to the file being audited.
        let config = {
            let mut config = Config::default();
            let workspace_dirs = self.workspace_dirs.read().await;

            for dir in workspace_dirs.as_slice() {
                match Config::discover_local(dir.as_path()).await {
                    Ok(Some(cfg)) => {
                        config = cfg;
                        break;
                    }
                    Ok(None) => continue,
                    Err(e) => {
                        self.client
                            .log_message(
                                ls_types::MessageType::WARNING,
                                format!(
                                    "failed to load configuration from workspace dir {}: {e}",
                                    dir.as_str()
                                ),
                            )
                            .await;
                    }
                }
            }

            config
        };

        let mut group = InputGroup::new(config);
        group.register_input(input)?;
        let mut input_registry = InputRegistry::new();
        input_registry.groups.insert("lsp".into(), group);

        let mut registry = FindingRegistry::new(&input_registry, None, None, Persona::Regular);

        for (input_key, input) in input_registry.iter_inputs() {
            for (ident, audit) in self.audit_registry.iter_audits() {
                registry.extend(
                    audit
                        .audit(ident, input, input_registry.get_config(input_key.group()))
                        .await?,
                );
            }
        }

        let diagnostics = registry
            .findings()
            .iter()
            .map(|finding| {
                let primary = finding.primary_location();
                ls_types::Diagnostic {
                    range: ls_types::Range {
                        start: primary.concrete.location.start_point.into(),
                        end: primary.concrete.location.end_point.into(),
                    },
                    severity: Some(finding.determinations.severity.into()),
                    code: Some(ls_types::NumberOrString::String(finding.ident.into())),
                    code_description: Some(ls_types::CodeDescription {
                        href: ls_types::Uri::from_str(finding.url)
                            .expect("finding contains an invalid URL somehow"),
                    }),
                    source: Some("zizmor".into()),
                    message: finding.desc.into(),
                    // TODO: Plumb non-primary locations here, maybe?
                    related_information: None,
                    tags: None,
                    data: None,
                }
            })
            .collect::<Vec<_>>();

        self.client
            .publish_diagnostics(params.uri, diagnostics, params.version)
            .await;

        Ok(())
    }

    /// Perform an event, as driven by the LSP client.
    async fn perform(&self, params: LspDocumentCommon) {
        if let Err(e) = self.audit_inner(params).await {
            self.client
                .log_message(ls_types::MessageType::ERROR, format!("audit failed: {e}"))
                .await;
        }
    }
}

impl From<Severity> for ls_types::DiagnosticSeverity {
    fn from(value: Severity) -> Self {
        // TODO: Does this mapping make sense?
        match value {
            Severity::Informational => ls_types::DiagnosticSeverity::INFORMATION,
            Severity::Low => ls_types::DiagnosticSeverity::WARNING,
            Severity::Medium => ls_types::DiagnosticSeverity::WARNING,
            Severity::High => ls_types::DiagnosticSeverity::ERROR,
        }
    }
}

impl From<Point> for ls_types::Position {
    fn from(value: Point) -> Self {
        Self {
            line: value.row as u32,
            character: value.column as u32,
        }
    }
}

pub(crate) async fn run() -> Result<(), Error> {
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();

    let state = AuditState::default();

    let audits = AuditRegistry::default_audits(&state)?;
    let (service, socket) = LspService::new(|client| Backend {
        audit_registry: audits,
        client,
        workspace_dirs: RwLock::new(vec![]),
    });

    Server::new(stdin, stdout, socket).serve(service).await;

    Ok(())
}