Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
289 changes: 281 additions & 8 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sysdig-lsp"
version = "0.3.0"
version = "0.4.0"
edition = "2024"
authors = [ "Sysdig Inc." ]
readme = "README.md"
Expand All @@ -11,16 +11,21 @@ publish = false # We don't want to publish it to crates.io yet.

[dependencies]
async-trait = "0.1.85"
bollard = "0.18.1"
bytes = "1.10.1"
chrono = { version = "0.4.40", features = ["serde"] }
clap = { version = "4.5.34", features = ["derive"] }
dirs = "6.0.0"
futures = "0.3.31"
itertools = "0.14.0"
rand = "0.9.0"
regex = "1.11.1"
reqwest = "0.12.14"
semver = "1.0.26"
serde = { version = "1.0.219", features = ["alloc", "derive"] }
serde_json = "1.0.135"
serial_test = { version = "3.2.0", features = ["file_locks"] }
tar = "0.4.44"
thiserror = "2.0.12"
tokio = { version = "1.43.0", features = ["full"] }
tower-lsp = "0.20.0"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ helping you detect vulnerabilities and misconfigurations earlier in the developm

## Features

| Feature | **[VSCode Extension](https://github.com/sysdiglabs/vscode-extension)** | **Sysdig LSP** |
| Feature | **[VSCode Extension](https://github.com/sysdiglabs/vscode-extension)** | **[Sysdig LSP](./docs/features/README.md)** |
|---------------------------------|------------------------------------------------------------------------|----------------------------------------------------------|
| Scan base image in Dockerfile | Supported | [Supported](./docs/features/scan_base_image.md) (0.1.0+) |
| Code lens support | Supported | [Supported](./docs/features/code_lens.md) (0.2.0+) |
| Build and Scan Dockerfile | Supported | In roadmap |
| Build and Scan Dockerfile | Supported | [Supported](./docs/features/build_and_scan.md) (0.4.0+) |
| Layered image analysis | Supported | In roadmap |
| Docker-compose image analysis | Supported | In roadmap |
| K8s Manifest image analysis | Supported | In roadmap |
Expand Down
4 changes: 4 additions & 0 deletions docs/features/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ Sysdig LSP provides tools to integrate container security checks into your devel
- Displays actionable commands directly within the editor (e.g., initiating base image scans).
- Enables quick access to frequently performed actions.

## [Build and Scan](./build_and_scan.md)
- Builds and scans the entire final Dockerfile image used in production.
- Supports multi-stage Dockerfiles, analyzing final stage and explicitly copied artifacts from intermediate stages.

See the linked documents for more details.
Binary file added docs/features/build_and_scan.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 37 additions & 0 deletions docs/features/build_and_scan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Build and Scan

Sysdig LSP builds your entire Dockerfile and scans the resulting final image to identify vulnerabilities early in your development workflow.
This ensures the exact image used in production is secure and compliant.

> [!IMPORTANT]
> Sysdig LSP analyzes the fully built final image, including all instructions executed during the build process.
>
> In multi-stage Dockerfiles, only artifacts copied into the final stage using instructions like `COPY --from=build` are analyzed, as intermediate stages are not part of the final runtime environment.

![Sysdig LSP executing build and scan in idea-community](./build_and_scan.gif)

## Examples

### Single-stage Dockerfile (scanned entirely)

```dockerfile
# Base image and all instructions are scanned
FROM alpine:latest
RUN apk add --no-cache python3
COPY ./app /app
```

### Multi-stage Dockerfile (partially scanned)

```dockerfile
# Build stage (scanned only for artifacts copied to final stage)
FROM golang:1.19 AS build
RUN go build -o app main.go

# Final image (fully scanned)
FROM alpine:3.17
COPY --from=build /app /app
ENTRYPOINT ["/app"]
```

In this multi-stage Dockerfile, Sysdig LSP scans the complete final built image, including the final runtime stage (`alpine:3.17`) and any artifacts explicitly copied from previous stages (`golang:1.19`).
6 changes: 3 additions & 3 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

163 changes: 133 additions & 30 deletions src/app/commands.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
use std::{
path::{Path, PathBuf},
str::FromStr,
};

use tower_lsp::{
jsonrpc::{Error, ErrorCode, Result},
jsonrpc::{Error, Result},
lsp_types::{Diagnostic, DiagnosticSeverity, MessageType, Position, Range},
};

use super::{ImageScanner, InMemoryDocumentDatabase, LSPClient};
use super::{
ImageBuilder, ImageScanner, InMemoryDocumentDatabase, LSPClient, lsp_server::WithContext,
};

pub struct CommandExecutor<C> {
client: C,
Expand Down Expand Up @@ -59,36 +66,27 @@ impl<C> CommandExecutor<C>
where
C: LSPClient,
{
pub async fn scan_image_from_file<S: ImageScanner>(
pub async fn scan_image_from_file(
&self,
uri: &str,
line: u32,
image_scanner: &S,
image_scanner: &impl ImageScanner,
) -> Result<()> {
let document_text = self
.document_database
.read_document_text(uri)
.await
.ok_or_else(|| Error {
code: ErrorCode::InternalError,
message: "unable to obtain document to scan".into(),
data: None,
.ok_or_else(|| {
Error::internal_error().with_message("unable to obtain document to scan")
})?;

let image_for_selected_line =
self.image_from_line(line, &document_text)
.ok_or_else(|| Error {
code: ErrorCode::ParseError,
message: format!("unable to retrieve image for the selected line: {}", line)
.into(),
data: None,
})?;

let range_for_selected_line = document_text
.lines()
.nth(line as usize)
.map(|x| x.len() as u32)
.unwrap_or(u32::MAX);
self.image_from_line(line, &document_text).ok_or_else(|| {
Error::parse_error().with_message(format!(
"unable to retrieve image for the selected line: {}",
line
))
})?;

self.show_message(
MessageType::INFO,
Expand All @@ -99,11 +97,7 @@ where
let scan_result = image_scanner
.scan_image(image_for_selected_line)
.await
.map_err(|e| Error {
code: ErrorCode::InternalError,
message: e.to_string().into(),
data: None,
})?;
.map_err(|e| Error::internal_error().with_message(e.to_string()))?;

self.show_message(
MessageType::INFO,
Expand All @@ -112,11 +106,20 @@ where
.await;

let diagnostic = {
let range_for_selected_line = Range::new(
Position::new(line, 0),
Position::new(
line,
document_text
.lines()
.nth(line as usize)
.map(|x| x.len() as u32)
.unwrap_or(u32::MAX),
),
);

let mut diagnostic = Diagnostic {
range: Range {
start: Position::new(line, 0),
end: Position::new(line, range_for_selected_line),
},
range: range_for_selected_line,
severity: Some(DiagnosticSeverity::HINT),
message: "No vulnerabilities found.".to_owned(),
..Default::default()
Expand Down Expand Up @@ -145,4 +148,104 @@ where
.await;
self.publish_all_diagnostics().await
}

pub async fn build_and_scan_from_file(
&self,
uri: &Path,
line: u32,
image_builder: &impl ImageBuilder,
image_scanner: &impl ImageScanner,
) -> Result<()> {
let document_text = self
.document_database
.read_document_text(uri.to_str().unwrap_or_default())
.await
.ok_or_else(|| {
Error::internal_error().with_message("unable to obtain document to scan")
})?;

let uri_without_file_path = uri
.to_str()
.and_then(|s| s.strip_prefix("file://"))
.ok_or_else(|| {
Error::internal_error().with_message("unable to strip prefix file:// from uri")
})?;

self.show_message(
MessageType::INFO,
format!("Starting build of {}...", uri_without_file_path).as_str(),
)
.await;

let build_result = image_builder
.build_image(&PathBuf::from_str(uri_without_file_path).unwrap())
.await
.map_err(|e| Error::internal_error().with_message(e.to_string()))?;

self.show_message(
MessageType::INFO,
format!(
"Temporal image built '{}', starting scan...",
&build_result.image_name
)
.as_str(),
)
.await;

let scan_result = image_scanner
.scan_image(&build_result.image_name)
.await
.map_err(|e| Error::internal_error().with_message(e.to_string()))?;

self.show_message(
MessageType::INFO,
format!("Finished scan of {}.", &build_result.image_name).as_str(),
)
.await;

let diagnostic = {
let range_for_selected_line = Range::new(
Position::new(line, 0),
Position::new(
line,
document_text
.lines()
.nth(line as usize)
.map(|x| x.len() as u32)
.unwrap_or(u32::MAX),
),
);

let mut diagnostic = Diagnostic {
range: range_for_selected_line,
severity: Some(DiagnosticSeverity::HINT),
message: "No vulnerabilities found.".to_owned(),
..Default::default()
};

if scan_result.has_vulnerabilities() {
let v = &scan_result.vulnerabilities;
diagnostic.message = format!(
"Vulnerabilities found for Dockerfile in {}: {} Critical, {} High, {} Medium, {} Low, {} Negligible",
uri_without_file_path, v.critical, v.high, v.medium, v.low, v.negligible
);

diagnostic.severity = Some(if scan_result.is_compliant {
DiagnosticSeverity::INFORMATION
} else {
DiagnosticSeverity::ERROR
});
}

diagnostic
};

self.document_database
.remove_diagnostics(uri.to_str().unwrap())
.await;
self.document_database
.append_document_diagnostics(uri.to_str().unwrap(), &[diagnostic])
.await;
self.publish_all_diagnostics().await
}
}
Loading