vicanso/diving-rs
À propos
Exploring each layer in a docker image, it's fast and simple
Systèmes et infrastructureProgression mesurée des étoiles
- in 24h
- 0
- in 7 days
- +2
- in 15 days
- +2
- in 1 month
- Historique en cours
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
README.md
Originaldiving-rs
中文 · Desktop Tour · Quick Start · CLI & TUI · Web & MCP · CI Gate · Configuration · Rust Library
Dive into every container image layer — find wasted space, leaked secrets, and runtime mismatches in seconds.
Meet Diving Desktop, a fast native Rust app built on NSH (zero Electron, zero browser overhead) for macOS, Windows, and Linux — paired with a standalone CLI/TUI, Web/MCP server, CI gate, and diving-core Rust library. No Docker daemon required.
https://github.com/user-attachments/assets/fd78f12f-468c-4c63-9b37-f8e23ee5762d
Why diving
- Native Desktop (
Diving Desktop) — pure Rust workbench with#N→1layer timeline, virtualized file trees, interactive treemap, rich file previews, and built-in GitHub Releases updates. - Any Source, Zero Daemon — pulls directly from Docker Hub,
ghcr.io,quay.io, or private V2 registries (resumable downloads + content-addressable cache), plus localdocker://,podman://, macOS Applecontainer://, andfile://.tar/ OCI layouts. - Space & Layer Diagnostics — efficiency score, wasted bytes (
written in layer X, deleted/overwritten in layer Y), cross-layerblake3duplicates, package caches, unstripped binaries, and Dockerfile linting. - Security & Runtime Hygiene — flags leaked secret files (
.env, SSH/cloud keys), inline tokens inside small text/config files (≤ 1 MiB), credential keys inENV/labels,setuid/world-writable/root risks, and ELFglibc/muslmismatches. - Diff, CI Gate & AI Alerts — compare tags, local builds, or architectures (
diving diff), enforce thresholds in GitHub Actions / GitLab CI (CI=true), or push AI optimization reports to WeCom, Feishu, DingTalk, Slack, and custom webhooks.
Scope note: diving inspects image structure, wasted space, file paths, metadata, and small text/config contents (
≤ 1 MiB) — it does not scan CVEs. Pair it with Trivy or Grype for vulnerability coverage.
Diving Desktop Tour
- Layer Timeline (
#N→1), Virtual File Tree & Command Inspector — opens with the newest layer first (#N→1, toggleable to#1→N), layer filters (All,Files,> 1 MB),+/~/−op badges, size/keyword filters, and an auto-formatted Dockerfile Command Inspector (Wrap/Rawtoggles):

- Rich File Preview & Auto-Formatted Code — inspect raster images (PNG, JPEG, GIF, WebP, BMP, ICO, AVIF, TIFF), SVG, nested archives (TAR, ZIP, JAR, APK), structured binaries (ELF, Wasm, SQLite, Mach-O, Java
.class, fonts, PDF), media headers, and hex dumps, plus automatic formatting for minified JSON, JS/TS/JSX/TSX, CSS, and HTML/XML with a Formatted / Raw toggle:

- Interactive Treemap — two-level squarified treemap and sortable table of the final container filesystem, colored by top contributing layers with click-to-drill-down breadcrumbs:

- Findings & Reconstructed Dockerfile — ranked optimization cards with estimated savings, wasted space attribution, secret warnings, cross-layer duplicates, unstripped binaries, and the reconstructed
Dockerfile(Wrap/Raw+ENV/LABELmetadata):

- Release-over-Release Image Diff — compare two images, local builds, or architectures side by side with
diff_idslayer matching, directory deltas, added/removed/resized files, config & runtime parity checks, and new vs. resolved findings:

- Local Runtime Picker & Private Registries — browse local Docker, Podman, and macOS Apple Container (
container://) images (Mod + Shift + O) with installed-first runtime ordering, sortable columns (Repository:Tag,Image ID,Created,Size), hover tooltips for long repository names, and single-image deletion. Configure per-domain credentials, bearer tokens, custom headers, plain HTTP, and custom CA/TLS rules in Private Registries (Mod + ,, saved to~/.diving/registries.ymlwith0600permissions):

Quick Start
1. Diving Desktop
Download prebuilt packages from GitHub Releases (or rolling Nightly builds):
- macOS (Universal):
Diving-macos-universal.dmg/Diving-macos-universal.tar.gz - Windows (
x86_64/aarch64):Diving-windows-<arch>.zip/Diving-windows-<arch>-setup.exe - Linux (
x86_64/aarch64):Diving-linux-<arch>.tar.gz
Or run/package from source (requires NSH 0.7.2):
make dev-app # run Diving Desktop locally on macOS
make package-macos # build Diving.app into app/.nsh/out/
See app/README.md for desktop architecture and full keyboard shortcuts.
2. CLI and TUI
# Install prebuilt binary or via Cargo
curl -fsSL https://raw.githubusercontent.com/vicanso/diving-rs/main/install.sh | sh
cargo install diving
# Analyze registry, platform (x86_64/aarch64 aliases accepted), digest, local runtimes, or tar/OCI
diving redis:alpine
diving redis:alpine?arch=arm/v7
diving redis@sha256:<digest>
diving docker://redis:alpine
diving podman://localhost/myapp:dev
diving container://redis:alpine # macOS Apple Container CLI
diving file:///tmp/redis.tar?arch=arm64 # docker save tar / OCI archive / OCI layout
# Export reports & compare images (content-matched via diff_ids; shared layers download once)
diving redis:alpine -o result.json # or result.md / `-o -` (`--no-skip-base`, `--no-verify-dup`)
diving myimage:latest --summary summary.md
diving diff myapp:1.4 myapp:1.5 # or `diving diff --archs amd64,arm64 myapp:latest`
Inside the TUI (layers default to #N→1): r toggles layer order, 1 filters modified/removed files, 2 filters files ≥ 1 MB, / searches, Esc / 0 resets, and q quits.
AI reports & chat notifications (OpenAI-compatible, WeCom, Feishu, DingTalk, Slack, Webhook)
Pass --ai-api-key ($OPENAI_API_KEY) to skip the TUI and print a prioritized DevSecOps report (including entrypoint scripts read from the layers and version-over-version history under ~/.diving/ai_history/). Configure one or more notification channels (priority: CLI flag → env var → config.yml) to push the AI report or summary instead of opening the TUI:
diving redis:alpine --ai-api-key sk-xxxx --ai-base-url https://your-gateway/v1 --ai-model gpt-4o --lang zh
diving redis:alpine --feishu-webhook HOOK_ID --feishu-secret SECRET --public-url https://diving.example.com
| Flag | Env Var | Config Key | Notes |
|---|---|---|---|
--ai-api-key |
OPENAI_API_KEY |
— | Enables AI analysis (CLI/env only, never HTTP query params) |
--ai-base-url |
OPENAI_BASE_URL |
— | Default https://api.openai.com/v1 (or full .../chat/completions) |
--ai-model |
OPENAI_MODEL |
— | Default gpt-4o |
--ai-system-prompt |
OPENAI_SYSTEM_PROMPT |
— | Replaces built-in DevSecOps prompt |
--no-ai-history |
— | — | Skip baseline comparison for one run (still refreshes snapshot) |
--lang |
DIVING_LANG |
— | en or zh |
--wecom-webhook |
WECOM_WEBHOOK |
wecom_webhook |
WeCom bot key or URL (~4096-byte markdown limit) |
--feishu-webhook / --feishu-secret |
FEISHU_WEBHOOK / FEISHU_SECRET |
feishu_webhook / feishu_secret |
Feishu hook ID or URL + optional signing secret |
--dingtalk-webhook / --dingtalk-secret |
DINGTALK_WEBHOOK / DINGTALK_SECRET |
dingtalk_webhook / dingtalk_secret |
DingTalk access_token or URL + optional SEC... secret |
--slack-webhook |
SLACK_WEBHOOK |
slack_webhook |
Slack Incoming Webhook URL |
--notify-webhook / --notify-webhook-secret |
NOTIFY_WEBHOOK / NOTIFY_WEBHOOK_SECRET |
notify_webhook / notify_webhook_secret |
JSON POST (event: "analysis.completed"), optional HMAC X-Diving-Signature |
--public-url |
DIVING_PUBLIC_URL |
public_url |
Base URL for clickable Web UI links inside messages |
3. Web and MCP Server
Run the standalone Axum web UI, REST API, Streamable HTTP MCP server (/mcp), and registry webhook runner (vicanso/diving or diving-web --listen 0.0.0.0:8080):
mkdir -p $PWD/diving && chown -R 1000:1000 $PWD/diving
docker run -d --restart=always -p 7001:7001 -v $PWD/diving:/home/rust/.diving --name diving vicanso/diving
# Connect Claude Code / MCP clients directly
claude mcp add --transport http diving http://127.0.0.1:7001/mcp
Open http://127.0.0.1:7001/ in your browser (click MCP in the header for auto-filled client snippets).
HTTP API endpoints, MCP tools, access tokens & inbound registry webhooks
- REST API (protect
/api/*with--api-token/$DIVING_API_TOKENviaAuthorization: BearerorX-API-Key):GET /api/analyze?image=...&format=json|markdown|summary&skipBase=true&includeTree=true&noVerifyDup=false&lang=enGET /api/manifest?image=...— fast layer list from manifest + config aloneGET /api/diff?base=...&target=...&format=json|markdown&baseLayerMode=auto|force|off|skip:NGET /api/file?digest=<layer_digest>&file=<path>&GET /api/file-preview?digest=<layer_digest>&file=<path>GET /ping— returnspong(container runs as UID1000:1000ondebian:trixie-slim, UTC timestamps, nocurl/wget)
- MCP (
/mcp) — tools:analyze_image,get_findings,list_files,read_file(≤ 256 KiB, registry images),diff_images,latest_images(1-based layer numbers; streams progress notifications every 10s when requested). Default allows loopbackHostheaders only; for remote access set--mcp-token/$DIVING_MCP_TOKENormcp_allowed_hosts: [diving.example.com]("*"disables;--no-mcpturns off). - Inbound Registry Webhook (
POST /api/webhook) — responds202 Accepted, invalidates cache, analyzes in background, and pushes to outbound channels:- Auto-detects Generic JSON (
{"image":"org/app:v1"}or{"images":[...],"archs":["amd64","arm64"],"lang":"zh"}), Harbor (PUSH_ARTIFACT/pushImage), Docker Hub / Aliyun ACR / Tencent TCR (push_data+repository), and Docker Registry v2 (events[]). - Optional query params:
?token=,?registry=,?arch=,?lang=. - Secure with
--webhook-token/$DIVING_WEBHOOK_TOKEN(Authorization,X-Webhook-Token,X-Gitlab-Token,X-Hub-Signature-256, or?token=). Without a token, only loopback/RFC1918 peers are accepted unlesswebhook_allow_public: true(--no-webhookdisables).
- Auto-detects Generic JSON (
CI Gate
Set CI=true to print the report and enforce thresholds (exits 0 pass, 1 gate failed, 2 diving/config/pull error). Use --summary <file> for PR comments or job summaries.
# GitHub Action (installs diving, runs gate or diff, appends job summary)
- uses: vicanso/diving-rs@main
with:
image: ghcr.io/org/app:${{ github.sha }}
config: .diving.yml
summary-file: diving-summary.md
- if: always() && github.event_name == 'pull_request'
run: gh pr comment ${{ github.event.number }} --body-file diving-summary.md
env:
GH_TOKEN: ${{ github.token }}
| Option | Default | Meaning |
|---|---|---|
lowest_efficiency |
0.95 |
Minimum efficiency score (0–1) |
highest_wasted_bytes |
20971520 (20 MB) |
Maximum wasted bytes |
highest_user_wasted_percent |
0.1 |
Maximum wasted ratio (0–1) |
highest_image_size |
— (off) | Maximum uncompressed image size (e.g. 500MB) |
highest_size_increase |
— (off) | diving diff only: max target − base growth (e.g. 50MB) |
fail_on_severity |
— (off) | Fail on recommendations at/above high, medium, low, or info |
ignore_recommendations |
[] |
Recommendation IDs excluded from fail_on_severity |
GitHub Action inputs, GitLab CI example & all recommendation IDs
GitHub Action Inputs: image (required), base (runs diving diff when set), config, output (.json/.md), summary-file (pass an explicit path to read after step failure), job-summary (true), version (latest or e.g. v0.12.3), args (e.g. --lang zh).
GitLab CI:
image-check:
image: debian:bookworm-slim
variables: { REGISTRY_USERNAME: $CI_REGISTRY_USER, REGISTRY_PASSWORD: $CI_REGISTRY_PASSWORD }
before_script:
- apt-get update && apt-get install -y --no-install-recommends curl ca-certificates
- curl -fsSL https://raw.githubusercontent.com/vicanso/diving-rs/main/install.sh | sh
script: [ 'diving "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" --summary diving-summary.md' ]
artifacts: { when: always, paths: [diving-summary.md] }
Recommendation IDs (for ignore_recommendations):
- High:
secfiles(leaked secret files),secmeta(ENV/label/Dockerfile secret keys),worldread(world-readable secrets),runtimecompat(entrypoint libc mismatch; medium for musl-on-glibc) - Medium:
pkgcache(pkg manager caches),devart(dev artifacts),runasroot(runs as root),setuid(setuid/setgid),worldwrite(world-writable files),wasted(>10% high, else medium) - Low / Scaled:
crossdup(low; ≥5 MB medium; ≥50 MB high),unstripped(low; ≥10 MB medium),oversized/dflint(low or medium),layercount,junk,slimbase,buildonly,doclocale,logtemp,toolchain,nohealthcheck,cacheorder - Info:
bigfiles,netreclaim
Configuration
Config lives at ~/.diving/config.yml (override with -c/--config or $DIVING_CONFIG, which requires the file to exist and parses as YAML). Desktop Private Registries writes ~/.diving/registries.yml (0600) and merges over config.yml registries (exact host wins over longest *.domain, supports ${ENV_VAR}). Custom sensitive-file rules live in ~/.diving/sensitive-files. Caches under ~/.diving/layers/ and ~/.diving/analysis/ are content-addressable (Docker-Content-Digest + arch), auto-resume downloads, and fall back to stale snapshots (staleAsOf) when a registry is unreachable/5xx/429 (never on 401/403/404 or under CI=true).
Full config.yml options, registries.yml & sensitive-files reference
layer_path: ~/.diving/layers
analysis_path: ~/.diving/analysis
layer_ttl: 90d
cleanup_interval_hours: 1
layer_concurrency: 8 # default min(layers, 2 * CPUs); worker_threads defaults to CPUs (`threads` fallback)
max_layer_cache_size: 10GB # LRU eviction cap for layer cache (unset = TTL only)
max_download_file_size: 100MB # /api/file cap
analysis_memory_ttl: 1m # Web/Desktop in-memory TTL (`0s` = off)
max_concurrent_analyses: 8 # Web max concurrent image analyses
registry_allowlist: # non-empty restricts Web/MCP hosts + local-file/local-docker/local-podman/local-container
- index.docker.io
- ghcr.io
mcp_allowed_hosts: [diving.example.com] # extra /mcp Host headers (`*` disables; ignored with --mcp-token)
webhook_token: topsecret # or --webhook-token / $DIVING_WEBHOOK_TOKEN
webhook_allow_public: false
registries:
- host: "*.corp.internal"
username: "${REGISTRY_USER}"
password: "${REGISTRY_PASSWORD}"
headers: { X-Gateway-Token: "${GATEWAY_TOKEN}" }
insecure_http: false
insecure_skip_tls_verify: false
ca_cert: ~/.diving/certs/corp-root-ca.pem
~/.diving/sensitive-files: one rule per line (<glob>, <glob> | <reason>, or !<glob> to ignore across both path and ≤ 1 MiB content scanning; case-insensitive, * matches across /, also tested against filename alone):
**/*.vault-token | Vault token
!**/.env.example
!**/testdata/**
Rust Library
Embed the pure async engine without CLI, TUI, Axum, or implicit ~/.diving I/O (CacheConfig::ephemeral(), local sources & ~/.docker/config.json disabled by default, singleflight enabled):
use diving_core::{to_markdown, AnalyzeOptions, Analyzer, CacheConfig, Lang};
#[tokio::main]
async fn main() -> diving_core::Result<()> {
let analyzer = Analyzer::builder().cache(CacheConfig::ephemeral()).build()?;
let result = analyzer.analyze("redis:alpine", AnalyzeOptions::default().lang(Lang::En)).await?;
println!("{}", to_markdown(&result, true, Lang::En));
Ok(())
}
See crates/diving-core/README.md for the full library guide (diving-core = "0.12.3").
License
Licensed under the Apache License 2.0.
Explorer des projets similaires
Chargement…