diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..2ce6790 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git +target +docs +scripts +examples +data +config +*.db +*.parquet +.claude +.wolf +.env diff --git a/.gitea/ISSUE_TEMPLATE/bug.yml b/.gitea/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..c623425 --- /dev/null +++ b/.gitea/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,17 @@ +name: Report a bug +description: Something did not work as expected +labels: [bug] +body: + - type: textarea + id: what-happened + attributes: { label: "What happened?", description: "Steps to reproduce, expected behavior, and actual behavior." } + validations: { required: true } + - type: input + id: system + attributes: { label: "Operating system and Xexéu version", placeholder: "Ubuntu 24.04 / xexeu 0.1.0" } + - type: input + id: input + attributes: { label: "Target or configuration", placeholder: "CIDR / target specification, xexeu.toml configuration snippet, or scan profile" } + - type: textarea + id: log + attributes: { label: "Terminal output (xexeu doctor / scan / serve)", render: shell } diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..9bd2491 --- /dev/null +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +## What changes and why + +## Checklist +- [ ] `cargo fmt --all` and `cargo clippy --workspace --all-targets` pass without warnings +- [ ] `cargo test --workspace` passes +- [ ] Scan and detection changes carry deterministic evidence and preserve fixed-order output +- [ ] Commits follow Conventional Commits in English and code/comments are in English +- [ ] CHANGELOG updated (if there is a user-visible change) +- [ ] Documentation kept in the English/Portuguese pair diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..47540a6 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,75 @@ +name: CI + +on: + # Documentation-only or local agent state changes do not trigger CI jobs. + pull_request: + paths-ignore: ['**.md', 'docs/**', 'LICENSE*', '.gitignore', '.githooks/**', '.wolf/**', '.claude/**', '.opencode/**', '.codex/**', '.cursor/**', '.superpowers/**', '.superset/**', '.gitea/ISSUE_TEMPLATE/**', 'scripts/release-notes.sh', '.gitea/workflows/release.yml'] + workflow_call: + +concurrency: + group: ci-${{ gitea.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + CARGO_HOME: /opt/hostedtoolcache/cargo + RUSTUP_HOME: /opt/hostedtoolcache/rustup + +jobs: + lint: + name: Format and clippy + runs-on: linux-arm64 + env: + CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-lint + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: Workflows and templates (valid YAML) + run: | + python3 -c " + import glob, yaml + for f in glob.glob('.gitea/**/*.yml', recursive=True): + yaml.safe_load(open(f)) + " + - name: Docker compose config + run: docker compose config --quiet + - run: cargo fmt --all -- --check + - run: cargo clippy --workspace --all-targets + + test: + name: Tests (Linux) + runs-on: linux-arm64 + env: + CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-test + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - run: cargo test --workspace + + audit: + name: Dependency audit + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - name: cargo audit + run: | + command -v cargo-audit >/dev/null || cargo install cargo-audit --locked + cargo audit + + image: + name: Docker image (build and smoke test) + if: ${{ gitea.event_name == 'pull_request' }} + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - name: Build + run: docker build -t "xexeu-ci:${{ gitea.run_id }}" . + - name: Smoke test + run: scripts/smoke-image.sh "xexeu-ci:${{ gitea.run_id }}" + - name: Clean up + if: always() + run: docker rmi -f "xexeu-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..05fe9c8 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,180 @@ +name: Release + +# Publishes the multi-arch Xexéu image (linux/amd64 + linux/arm64) to the Gitea +# container registry. A merge into main publishes `edge`; a v* tag re-points the +# image already built for the same inputs to X.Y.Z, X.Y and latest (no rebuild) +# and creates the Gitea Release. Needs the secret REGISTRY_TOKEN (Gitea token +# with write:package) visible to this repository. +on: + push: + branches: [main] + tags: ['v*'] + workflow_dispatch: + +concurrency: + group: release-${{ gitea.ref }} + cancel-in-progress: false + +env: + REGISTRY: git.lucasrguerra.dev.br + +jobs: + # The image is built only from these paths, so their tree hashes identify it. + # When inputs- already exists (docs-only merge, workflow change, or a tag + # on a commit main already published), nothing is built or tested again. + plan: + name: Plan (reuse the published image?) + runs-on: linux-arm64 + outputs: + inputs: ${{ steps.plan.outputs.inputs }} + reuse: ${{ steps.plan.outputs.reuse }} + image: ${{ steps.plan.outputs.image }} + steps: + - uses: actions/checkout@v7 + - id: plan + env: + REPO: ${{ gitea.repository }} + run: | + inputs=$(git rev-parse HEAD:Dockerfile HEAD:.dockerignore HEAD:Cargo.toml HEAD:Cargo.lock \ + HEAD:crates HEAD:apps/gui/ui HEAD:logo.png | sha256sum | cut -c1-16) + ns="${REPO,,}" + token=$(curl -fsS "https://$REGISTRY/v2/token?service=container_registry&scope=repository:$ns:pull" | jq -r .token) + code=$(curl -s -o /dev/null -w '%{http_code}' -I \ + -H "Authorization: Bearer $token" \ + -H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json' \ + "https://$REGISTRY/v2/$ns/manifests/inputs-$inputs") + echo "inputs-$inputs -> HTTP $code" + reuse=false; [ "$code" = 200 ] && reuse=true + echo "inputs=$inputs" >> "$GITHUB_OUTPUT" + echo "reuse=$reuse" >> "$GITHUB_OUTPUT" + echo "image=$REGISTRY/$ns" >> "$GITHUB_OUTPUT" + + ci: + needs: plan + if: ${{ needs.plan.outputs.reuse != 'true' }} + uses: ./.gitea/workflows/ci.yml + + # Each architecture is built on a native runner (no QEMU) and pushed under a + # per-architecture tag; publish joins them into one manifest list. + build: + name: Build image (${{ matrix.arch }}) + needs: [plan, ci] + if: ${{ needs.plan.outputs.reuse != 'true' }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { arch: amd64, platform: linux/amd64, runner: linux-amd64 } + - { arch: arm64, platform: linux/arm64, runner: linux-arm64 } + steps: + - uses: actions/checkout@v7 + - uses: docker/setup-buildx-action@v4 + - uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + # Plain `docker buildx build` instead of docker/build-push-action: that + # action's upstream repo (~260MB of git history) reliably hangs the + # act runner's Go-based clone on the Hostinger host, even when curl/git + # to github.com are both fast. Same end result, no action to clone. + - name: Build and push (per architecture) + run: | + docker buildx build \ + --platform "${{ matrix.platform }}" \ + --push \ + -t "${{ needs.plan.outputs.image }}:build-${{ gitea.sha }}-${{ matrix.arch }}" \ + --cache-from "type=registry,ref=${{ needs.plan.outputs.image }}:buildcache-${{ matrix.arch }}" \ + --cache-to "type=registry,ref=${{ needs.plan.outputs.image }}:buildcache-${{ matrix.arch }},mode=max" \ + . + # Runs the image that was just pushed, on its own architecture. + - name: Smoke test + run: scripts/smoke-image.sh "${{ needs.plan.outputs.image }}:build-${{ gitea.sha }}-${{ matrix.arch }}" + + publish: + name: Publish tags + needs: [plan, build] + # build is skipped, not successful, when the image is reused. + if: ${{ !cancelled() && needs.plan.result == 'success' && (needs.build.result == 'success' || needs.plan.outputs.reuse == 'true') }} + runs-on: linux-arm64 + steps: + - uses: docker/setup-buildx-action@v4 + - uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + - name: Tags + id: meta + uses: docker/metadata-action@v6 + with: + images: ${{ needs.plan.outputs.image }} + flavor: latest=false + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable=${{ startsWith(gitea.ref, 'refs/tags/v') && !contains(gitea.ref_name, '-') }} + type=raw,value=edge,enable=${{ gitea.ref == 'refs/heads/main' }} + type=sha,format=long + - name: Apply tags + run: | + image='${{ needs.plan.outputs.image }}' + tags=$(jq -cr '.tags | map("-t " + .) | join(" ")' <<< '${{ steps.meta.outputs.json }}') + inputs='${{ needs.plan.outputs.inputs }}' + if [ '${{ needs.plan.outputs.reuse }}' = true ]; then + docker buildx imagetools create $tags "$image:inputs-$inputs" + else + docker buildx imagetools create $tags -t "$image:inputs-$inputs" \ + "$image:build-${{ gitea.sha }}-amd64" "$image:build-${{ gitea.sha }}-arm64" + fi + - name: Check architectures + run: | + docker buildx imagetools inspect "${{ needs.plan.outputs.image }}:inputs-${{ needs.plan.outputs.inputs }}" \ + --format '{{json .Manifest}}' \ + | jq -r '.manifests[] | select(.platform.os == "linux") | "\(.platform.os)/\(.platform.architecture)"' \ + | tee platforms.txt + grep -qx linux/amd64 platforms.txt && grep -qx linux/arm64 platforms.txt + - name: Summary + run: | + { echo "### Xexéu image published (linux/amd64, linux/arm64)"; echo; echo '```' + echo "${{ steps.meta.outputs.tags }}"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + + gitea-release: + name: Gitea release + needs: [plan, publish] + if: ${{ !cancelled() && needs.publish.result == 'success' && startsWith(gitea.ref, 'refs/tags/v') }} + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + - name: Build release CLI binary + run: | + cargo build --release --locked -p xexeu-cli + - name: Release + env: + TAG: ${{ gitea.ref_name }} + TOKEN: ${{ gitea.token }} + API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }} + IMAGE: ${{ needs.plan.outputs.image }} + run: | + if curl -fsS -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" >/dev/null 2>&1; then + echo "release $TAG already exists"; exit 0 + fi + { scripts/release-notes.sh "$TAG"; echo; echo '```bash'; echo "docker pull $IMAGE:${TAG#v}"; echo '```'; } > notes.md + pre=false; case "$TAG" in *-*) pre=true ;; esac + jq -n --arg tag "$TAG" --arg name "Xexéu ${TAG#v}" --rawfile body notes.md --argjson pre "$pre" \ + '{tag_name:$tag, name:$name, body:$body, prerelease:$pre}' > release.json + rel=$(curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" \ + -H 'Content-Type: application/json' -d @release.json) + rel_id=$(echo "$rel" | jq -r .id) + if [ -n "$rel_id" ] && [ "$rel_id" != "null" ]; then + asset_name="xexeu-${TAG#v}-linux-arm64" + cp target/release/xexeu "$asset_name" + curl -fsS -X POST "$API/releases/$rel_id/assets?name=$asset_name" \ + -H "Authorization: token $TOKEN" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @"$asset_name" >/dev/null || true + fi diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..a9bd69f --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Enforces Conventional Commits 1.0.0 and English-only commit messages. +set -euo pipefail + +msg_file="${1:?usage: commit-msg }" +python3 - "$msg_file" <<'PY' +import re, sys +from pathlib import Path + +raw = Path(sys.argv[1]).read_text(encoding="utf-8") +lines = [l for l in raw.splitlines() if not l.startswith("#")] +while lines and not lines[0].strip(): + lines.pop(0) +if not lines: + sys.exit("commit-msg: empty commit message") + +subject = lines[0].strip() +if subject.startswith(("Merge ", "Revert \"")): + sys.exit(0) + +conv_re = re.compile( + r"^(feat|fix|chore|ci|docs|refactor|test|perf|build|style|revert)(\([a-z0-9_./-]+\))?!?: .+$" +) +if not conv_re.match(subject): + sys.exit( + f"commit-msg: invalid Conventional Commit header: {subject!r}\n" + "Expected: [optional scope]: \n" + "Allowed types: feat, fix, chore, ci, docs, refactor, test, perf, build, style, revert" + ) + +body = "\n".join(lines) +cleaned = re.sub(r"\b(Guará|Sabiá|Acauã|Xexéu|Ciberfauna)\b", "", body) +pt_accents = re.search(r"[áàâãéêíóôõúçÁÀÂÃÉÊÍÓÔÕÚÇ]", cleaned) +pt_words = re.search( + r"\b(não|para|como|quando|então|pelos|pelas|pelo|pela|estão|está|também|versão|" + r"corrige|adiciona|atualiza|remove|padroniza|implementa|ajusta|arquivo|arquivos)\b", + cleaned, + re.I, +) +if pt_accents or pt_words: + sys.exit("commit-msg: commit messages must be written 100% in English.") +PY diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..fe370d7 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec "$(git rev-parse --show-toplevel)/scripts/verificar.sh" diff --git a/Dockerfile b/Dockerfile index 5676b9f..d0e99f5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,6 +12,8 @@ RUN apt-get update \ WORKDIR /src COPY Cargo.toml Cargo.lock ./ COPY crates crates +COPY apps apps +COPY logo.png ./ RUN cargo build --release --locked -p xexeu-cli # Runtime stage: Debian slim, the binary and CA certificates for the optional diff --git a/crates/xexeu-cli/src/main.rs b/crates/xexeu-cli/src/main.rs index 4dc4843..84e1cf7 100644 --- a/crates/xexeu-cli/src/main.rs +++ b/crates/xexeu-cli/src/main.rs @@ -17,11 +17,12 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{Mutex, RwLock}; use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus}; use xexeu_core::config::{GroupConfig, ValidationReport, XexeuConfig}; -use xexeu_core::diff::{diff_batch, DiffOptions, EventKind}; +use xexeu_core::diff::{diff_batch, CurrentState, DiffOptions, EventKind}; use xexeu_core::report::ExecutiveReport; use xexeu_core::scan::{ - discover_hosts_tcp, fingerprint_service, scan_hosts_tcp_connect, DiscoveryConfig, HostState, - PortScanConfig, PortState, PortTarget, DEFAULT_DISCOVERY_PORTS, + discover_hosts_tcp, fingerprint_service, scan_hosts_syn, scan_hosts_tcp_connect, + DiscoveryConfig, HostPortScanResult, HostState, PortScanConfig, PortState, PortTarget, + SynScanConfig, DEFAULT_DISCOVERY_PORTS, }; use xexeu_core::schedule::{next_runs, should_run_now, RunDecision, RunHistory}; use xexeu_core::storage::{SqliteStorage, Storage}; @@ -32,8 +33,6 @@ use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_re use xexeu_core::vuln::matcher::{match_banner, Confidence, Finding}; use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase}; -const DEFAULT_CONFIG: &str = "config/xexeu.toml"; - #[derive(Parser)] #[command( name = "xexeu", @@ -103,11 +102,17 @@ enum Command { format: String, #[arg(long, default_value = "data/xexeu")] data_dir: PathBuf, + #[arg(long)] + out: Option, }, /// Check the runtime environment. Doctor { #[arg(long)] json: bool, + #[arg(long, default_value = "config/xexeu.toml")] + config: PathBuf, + #[arg(long, default_value = "data/xexeu")] + data_dir: PathBuf, }, } @@ -191,8 +196,16 @@ async fn main() -> ExitCode { Command::Config { action } => match action { ConfigAction::Check { config } => run_config_check(&config), }, - Command::Doctor { json } => run_doctor(json), - Command::Export { .. } => not_implemented("export"), + Command::Doctor { + json, + config, + data_dir, + } => run_doctor(json, &config, &data_dir), + Command::Export { + format, + data_dir, + out, + } => run_export(&format, &data_dir, out.as_deref()), } } @@ -201,11 +214,6 @@ fn fail(message: &str) -> ExitCode { ExitCode::FAILURE } -fn not_implemented(command: &str) -> ExitCode { - eprintln!("{command}: não implementado ainda"); - ExitCode::FAILURE -} - fn validated_config(path: &Path) -> Result<(XexeuConfig, ValidationReport), String> { let raw = fs::read_to_string(path) .map_err(|error| format!("não foi possível ler {}: {error}", path.display()))?; @@ -389,18 +397,63 @@ async fn execute_scan_for_group( .map(|host| host.ip) .collect(); - let port_results = if alive.is_empty() { - Vec::new() - } else { - scan_hosts_tcp_connect( - &alive, - &ports, - &PortScanConfig { - timeout: Duration::from_millis(1200), - max_concurrency: concurrency.saturating_mul(4).max(16), - }, - ) + // `nativo` tries the raw-socket SYN engine first and only falls back to + // the unprivileged `nativo-sem-raw` TCP-connect engine when CAP_NET_RAW + // isn't actually usable (missing capability, or the raw socket fails to + // create for some other reason) — the engine mode actually used, not the + // one requested, is what gets recorded in the sweep manifest below, so an + // operator reading `/api/status` or the manifest never has to guess which + // mode really ran. + let wants_raw = profile.engine == "nativo"; + let (port_results, engine_used): (Vec, EngineMode) = if alive.is_empty() { + (Vec::new(), EngineMode::NativeWithoutRaw) + } else if wants_raw && xexeu_core::caps::has_net_raw() { + let syn_hosts = alive.clone(); + let syn_ports = ports.clone(); + let syn_config = SynScanConfig::default(); + let syn_result = tokio::task::spawn_blocking(move || { + scan_hosts_syn(&syn_hosts, &syn_ports, &syn_config) + }) .await + .map_err(|error| format!("tarefa de varredura SYN falhou: {error}"))?; + match syn_result { + Ok(results) => (results, EngineMode::Native), + Err(error) => { + eprintln!( + "aviso: varredura SYN falhou ({error}), recorrendo ao modo nativo-sem-raw" + ); + ( + scan_hosts_tcp_connect( + &alive, + &ports, + &PortScanConfig { + timeout: Duration::from_millis(1200), + max_concurrency: concurrency.saturating_mul(4).max(16), + }, + ) + .await, + EngineMode::NativeWithoutRaw, + ) + } + } + } else { + if wants_raw { + eprintln!( + "aviso: perfil '{profile_name}' pede o motor nativo, mas CAP_NET_RAW não está disponível; usando nativo-sem-raw" + ); + } + ( + scan_hosts_tcp_connect( + &alive, + &ports, + &PortScanConfig { + timeout: Duration::from_millis(1200), + max_concurrency: concurrency.saturating_mul(4).max(16), + }, + ) + .await, + EngineMode::NativeWithoutRaw, + ) }; let vuln_db = VulnDatabase::load_from_file(&data_dir.join("vuln_db.json")).unwrap_or_default(); @@ -456,7 +509,7 @@ async fn execute_scan_for_group( group.name.clone(), expansion.ranges().iter().map(ToString::to_string).collect(), profile_name, - EngineMode::NativeWithoutRaw, + engine_used, started_at, ); manifest.finish(SweepStatus::Complete, Utc::now()); @@ -814,6 +867,17 @@ async fn create_group_handler( "nome do grupo não pode ser vazio".to_string(), )); } + // `sweep` batches are written to `sweeps///`, so an unsafe + // name here (`/`, `..`) would only fail much later, when a sweep for this + // group actually runs. Reject it now, with a clear error, instead. + if xexeu_core::batch::safe_component(&group_name).is_err() { + return Err(( + StatusCode::BAD_REQUEST, + format!( + "nome do grupo `{group_name}` inválido: use apenas letras, números, `-`, `_` ou `.`" + ), + )); + } let mut config_guard = state.config.write().await; let mut draft = config_guard.clone(); @@ -871,6 +935,14 @@ async fn update_group_handler( "nome do grupo não pode ser vazio".to_string(), )); } + if xexeu_core::batch::safe_component(new_name).is_err() { + return Err(( + StatusCode::BAD_REQUEST, + format!( + "nome do grupo `{new_name}` inválido: use apenas letras, números, `-`, `_` ou `.`" + ), + )); + } if new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) { return Err(( @@ -940,7 +1012,27 @@ async fn delete_group_handler( Ok(StatusCode::OK) } +/// Escapes a CSV field per RFC 4180, and neutralizes CSV/formula injection +/// (OWASP's "CSV Injection"): a cell starting with `=`, `+`, `-`, `@` or a tab +/// is interpreted as a formula by Excel/LibreOffice/Sheets when the export is +/// opened, which could execute attacker-influenced content (a CVE +/// description pulled from the NVD feed, or an operator-controlled config +/// value). Prefixing it with a single quote forces every spreadsheet +/// application to treat it as plain text, same as GitHub's and Google's own +/// CSV export sanitization. fn csv_escape(s: &str) -> String { + let needs_formula_guard = s + .chars() + .next() + .is_some_and(|c| matches!(c, '=' | '+' | '-' | '@' | '\t')); + let s_owned; + let s = if needs_formula_guard { + s_owned = format!("'{s}"); + &s_owned + } else { + s + }; + if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') { let escaped = s.replace('"', "\"\""); format!("\"{escaped}\"") @@ -949,17 +1041,65 @@ fn csv_escape(s: &str) -> String { } } -async fn export_hosts_csv_handler( - State(state): State, -) -> Result { - let storage = state.storage.lock().await; - let current_state = storage.load_state(&[]).map_err(|error| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - format!("erro ao consultar estado: {error}"), - ) - })?; +#[derive(Serialize)] +struct HostDto { + asset_key: String, + network: String, + ip: String, + status: &'static str, + absences: u32, + first_seen: String, + last_seen: String, + ports: Vec, +} +#[derive(Serialize)] +struct PortDto { + protocol: String, + port: u16, + status: &'static str, + absences: u32, + first_seen: String, + last_seen: String, + product: Option, + version: Option, + cpe: Option, + findings: Vec, +} + +fn current_state_to_dtos(current_state: &CurrentState) -> Vec { + current_state + .assets + .iter() + .map(|asset| HostDto { + asset_key: asset.asset_key.clone(), + network: asset.network.clone(), + ip: asset.ip.to_string(), + status: asset.status.as_str(), + absences: asset.absences, + first_seen: asset.first_seen.to_rfc3339(), + last_seen: asset.last_seen.to_rfc3339(), + ports: asset + .ports + .iter() + .map(|port| PortDto { + protocol: port.protocol.clone(), + port: port.port, + status: port.status.as_str(), + absences: port.absences, + first_seen: port.first_seen.to_rfc3339(), + last_seen: port.last_seen.to_rfc3339(), + product: port.product.clone(), + version: port.version.clone(), + cpe: port.cpe.clone(), + findings: port.findings.clone(), + }) + .collect(), + }) + .collect() +} + +fn generate_hosts_csv(current_state: &CurrentState) -> String { let mut csv = String::new(); csv.push_str("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados\r\n"); @@ -1008,6 +1148,21 @@ async fn export_hosts_csv_handler( } } } + csv +} + +async fn export_hosts_csv_handler( + State(state): State, +) -> Result { + let storage = state.storage.lock().await; + let current_state = storage.load_state(&[]).map_err(|error| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("erro ao consultar estado: {error}"), + ) + })?; + + let csv = generate_hosts_csv(¤t_state); let timestamp = Utc::now().format("%Y%m%d-%H%M%S"); let disposition = format!("attachment; filename=\"xexeu-hosts-{timestamp}.csv\""); @@ -1141,32 +1296,6 @@ async fn export_changes_csv_handler( Ok((headers, csv)) } -#[derive(Serialize)] -struct HostDto { - asset_key: String, - network: String, - ip: String, - status: &'static str, - absences: u32, - first_seen: String, - last_seen: String, - ports: Vec, -} - -#[derive(Serialize)] -struct PortDto { - protocol: String, - port: u16, - status: &'static str, - absences: u32, - first_seen: String, - last_seen: String, - product: Option, - version: Option, - cpe: Option, - findings: Vec, -} - async fn hosts_handler( State(state): State, ) -> Result>, (StatusCode, String)> { @@ -1178,36 +1307,7 @@ async fn hosts_handler( ) })?; - let dtos = current_state - .assets - .into_iter() - .map(|asset| HostDto { - asset_key: asset.asset_key, - network: asset.network, - ip: asset.ip.to_string(), - status: asset.status.as_str(), - absences: asset.absences, - first_seen: asset.first_seen.to_rfc3339(), - last_seen: asset.last_seen.to_rfc3339(), - ports: asset - .ports - .into_iter() - .map(|port| PortDto { - protocol: port.protocol, - port: port.port, - status: port.status.as_str(), - absences: port.absences, - first_seen: port.first_seen.to_rfc3339(), - last_seen: port.last_seen.to_rfc3339(), - product: port.product, - version: port.version, - cpe: port.cpe, - findings: port.findings, - }) - .collect(), - }) - .collect(); - + let dtos = current_state_to_dtos(¤t_state); Ok(Json(dtos)) } @@ -1703,92 +1803,78 @@ async fn shutdown_signal() { } } -#[derive(Serialize)] -struct DoctorReport { - version: &'static str, - config: DoctorConfig, - root: bool, - net_raw: Option, -} - -#[derive(Serialize)] -struct DoctorConfig { - path: String, - exists: bool, - valid: bool, - error: Option, -} - -fn run_doctor(as_json: bool) -> ExitCode { - let path = Path::new(DEFAULT_CONFIG); - let exists = path.exists(); - let (valid, error) = if exists { - match fs::read_to_string(path) { - Ok(raw) => match XexeuConfig::load_validated(&raw) { - Ok(_) => (true, None), - Err(error) => (false, Some(error.to_string())), - }, - Err(error) => (false, Some(format!("não foi possível ler: {error}"))), - } - } else { - ( - false, - Some("arquivo de configuração não encontrado".to_string()), - ) - }; - - let report = DoctorReport { - version: env!("CARGO_PKG_VERSION"), - config: DoctorConfig { - path: path.display().to_string(), - exists, - valid, - error, - }, - // SAFETY: geteuid takes no arguments, cannot fail and only reads the process identity. - root: unsafe { libc::geteuid() == 0 }, - net_raw: net_raw_capability(), - }; +fn run_doctor(as_json: bool, config_path: &Path, data_dir: &Path) -> ExitCode { + let report = xexeu_core::doctor::run(config_path, data_dir); if as_json { match serde_json::to_string_pretty(&report) { Ok(json) => println!("{json}"), Err(error) => return fail(&format!("falha ao serializar o diagnóstico: {error}")), } - return ExitCode::SUCCESS; + } else { + print!("{}", report.render_table()); } - println!("xexeu {}", report.version); - match ( - &report.config.error, - report.config.exists, - report.config.valid, - ) { - (_, true, true) => println!("config {}: presente e válida", report.config.path), - (Some(error), true, false) => println!("config {}: inválida: {error}", report.config.path), - (Some(error), false, _) => println!("config {}: {error}", report.config.path), - _ => println!("config {}: inválida", report.config.path), + if report.ok { + ExitCode::SUCCESS + } else { + ExitCode::FAILURE } - println!("root: {}", yes_no(report.root)); - match report.net_raw { - Some(value) => println!("NET_RAW: {}", yes_no(value)), - None => println!("NET_RAW: desconhecido"), +} + +fn run_export(format: &str, data_dir: &Path, out_file: Option<&Path>) -> ExitCode { + let db_path = data_dir.join("xexeu.db"); + let storage = match SqliteStorage::open(&db_path) { + Ok(s) => s, + Err(err) => { + return fail(&format!( + "falha ao abrir banco em {}: {err}", + db_path.display() + )) + } + }; + + let state = match storage.load_state(&[]) { + Ok(s) => s, + Err(err) => return fail(&format!("falha ao carregar estado: {err}")), + }; + + let content = match format.to_ascii_lowercase().as_str() { + "json" => { + let dtos = current_state_to_dtos(&state); + match serde_json::to_string_pretty(&dtos) { + Ok(s) => s, + Err(err) => return fail(&format!("falha ao serializar JSON: {err}")), + } + } + "csv" => generate_hosts_csv(&state), + other => { + return fail(&format!( + "formato não suportado: '{other}' (use 'json' ou 'csv')" + )) + } + }; + + if let Some(path) = out_file { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + if let Err(e) = fs::create_dir_all(parent) { + return fail(&format!( + "falha ao criar diretório para {}: {e}", + path.display() + )); + } + } + } + if let Err(e) = fs::write(path, &content) { + return fail(&format!( + "falha ao salvar export em {}: {e}", + path.display() + )); + } + } else { + print!("{content}"); } ExitCode::SUCCESS } - -fn yes_no(value: bool) -> &'static str { - if value { - "sim" - } else { - "não" - } -} - -fn net_raw_capability() -> Option { - let status = fs::read_to_string("/proc/self/status").ok()?; - let line = status.lines().find(|line| line.starts_with("CapEff:"))?; - let mask = u64::from_str_radix(line.split_whitespace().nth(1)?, 16).ok()?; - Some(mask & (1 << 13) != 0) -} diff --git a/crates/xexeu-cli/tests/doctor_and_export_e2e.rs b/crates/xexeu-cli/tests/doctor_and_export_e2e.rs new file mode 100644 index 0000000..7174438 --- /dev/null +++ b/crates/xexeu-cli/tests/doctor_and_export_e2e.rs @@ -0,0 +1,199 @@ +use chrono::Utc; +use std::fs; +use std::process::Command; +use tempfile::TempDir; +use xexeu_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState}; +use xexeu_core::storage::{SqliteStorage, Storage}; +use xexeu_core::vuln::matcher::{Confidence, Finding, FindingType}; + +#[test] +fn doctor_command_json_and_table_and_invalid_config() { + let workspace = TempDir::new().expect("temporary directory"); + let valid_config = workspace.path().join("xexeu.toml"); + let invalid_config = workspace.path().join("invalid.toml"); + let data_dir = workspace.path().join("data"); + + fs::write( + &valid_config, + r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "servidores" +alvos = ["10.0.0.1"] +"#, + ) + .expect("write valid config"); + + fs::write(&invalid_config, "invalid toml content !!").expect("write invalid config"); + + // 1. Valid doctor in table mode + let output = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "doctor", + "--config", + valid_config.to_str().unwrap(), + "--data-dir", + data_dir.to_str().unwrap(), + ]) + .output() + .expect("run xexeu doctor"); + + assert!( + output.status.success(), + "expected success: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Xexéu v")); + assert!(stdout.contains("versao")); + assert!(stdout.contains("config")); + assert!(stdout.contains("sqlite")); + assert!(stdout.contains("Resultado: OK")); + + // 2. Valid doctor in JSON mode + let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "doctor", + "--json", + "--config", + valid_config.to_str().unwrap(), + "--data-dir", + data_dir.to_str().unwrap(), + ]) + .output() + .expect("run xexeu doctor --json"); + + assert!(output_json.status.success()); + let parsed: serde_json::Value = + serde_json::from_slice(&output_json.stdout).expect("parse json output"); + assert_eq!(parsed["ok"], true); + assert!(parsed["checks"].is_array()); + let checks = parsed["checks"].as_array().unwrap(); + assert!(checks + .iter() + .any(|c| c["name"] == "config" && c["status"] == "ok")); + assert!(checks + .iter() + .any(|c| c["name"] == "sqlite" && c["status"] == "ok")); + + // 3. Invalid doctor mode exits with error code 1 + let output_invalid = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "doctor", + "--config", + invalid_config.to_str().unwrap(), + "--data-dir", + data_dir.to_str().unwrap(), + ]) + .output() + .expect("run xexeu doctor with invalid config"); + + assert!(!output_invalid.status.success()); + let stdout_invalid = String::from_utf8_lossy(&output_invalid.stdout); + assert!(stdout_invalid.contains("Resultado: FALHA")); +} + +#[test] +fn export_command_json_and_csv_with_fixture() { + let workspace = TempDir::new().expect("temporary directory"); + let data_dir = workspace.path().join("data"); + fs::create_dir_all(&data_dir).expect("create data dir"); + + let db_path = data_dir.join("xexeu.db"); + let mut storage = SqliteStorage::open(&db_path).expect("open sqlite storage"); + + let now = Utc::now(); + let diff = DiffResult { + state: vec![AssetState { + asset_key: "dmz/10.0.0.42".to_string(), + network: "dmz".to_string(), + ip: "10.0.0.42".parse().unwrap(), + status: AssetStatus::Active, + absences: 0, + first_seen: now, + last_seen: now, + ports: vec![ServiceState { + protocol: "tcp".to_string(), + port: 80, + status: PortStatus::Open, + absences: 0, + first_seen: now, + last_seen: now, + product: Some("nginx".to_string()), + version: Some("1.18.0".to_string()), + cpe: Some("cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*".to_string()), + findings: vec![Finding { + tipo: FindingType::Cve, + id: "CVE-2021-23017".to_string(), + cvss: Some(7.5), + kev: false, + confianca: Confidence::Alto, + title: "1-byte memory overwrite in resolver".to_string(), + description: "A 1-byte memory overwrite vulnerability exists in resolver." + .to_string(), + evidencia: serde_json::json!({ "banner": "nginx 1.18.0" }), + }], + }], + }], + events: vec![], + }; + + storage + .apply_diff(&diff) + .expect("apply fixture state to database"); + + // 1. Export JSON to stdout + let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "export", + "--format", + "json", + "--data-dir", + data_dir.to_str().unwrap(), + ]) + .output() + .expect("run xexeu export --format json"); + + assert!( + output_json.status.success(), + "export json failed: {}", + String::from_utf8_lossy(&output_json.stderr) + ); + let parsed: serde_json::Value = + serde_json::from_slice(&output_json.stdout).expect("parse export json"); + assert!(parsed.is_array()); + let hosts = parsed.as_array().unwrap(); + assert_eq!(hosts.len(), 1); + assert_eq!(hosts[0]["ip"], "10.0.0.42"); + assert_eq!(hosts[0]["network"], "dmz"); + assert_eq!(hosts[0]["ports"][0]["port"], 80); + assert_eq!(hosts[0]["ports"][0]["product"], "nginx"); + assert_eq!(hosts[0]["ports"][0]["findings"][0]["id"], "CVE-2021-23017"); + + // 2. Export CSV to file with --out + let out_csv_file = workspace.path().join("export.csv"); + let output_csv = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "export", + "--format", + "csv", + "--data-dir", + data_dir.to_str().unwrap(), + "--out", + out_csv_file.to_str().unwrap(), + ]) + .output() + .expect("run xexeu export --format csv --out ..."); + + assert!(output_csv.status.success()); + let csv_content = fs::read_to_string(&out_csv_file).expect("read exported csv"); + assert!(csv_content.contains("Endereço IP,Grupo,Status do Host,Protocolo,Porta")); + assert!(csv_content.contains("10.0.0.42,dmz,ativo,tcp,80,aberta,nginx,1.18.0,cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*,7.5,1")); +} diff --git a/crates/xexeu-core/src/doctor.rs b/crates/xexeu-core/src/doctor.rs index 207cff3..01129cd 100644 --- a/crates/xexeu-core/src/doctor.rs +++ b/crates/xexeu-core/src/doctor.rs @@ -1,2 +1,484 @@ -//! Environment checks: effective capabilities, nmap availability, feed age and libduckdb linkage. -// TODO: implement doctor checks. +//! Environment checks: effective capabilities, configuration validity, SQLite access, +//! vulnerability database status, and feed synchronization age. + +use crate::config::XexeuConfig; +use crate::storage::SqliteStorage; +use crate::vuln::VulnDatabase; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::Path; +use std::time::SystemTime; + +/// Status for an individual environment check. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CheckStatus { + #[serde(rename = "ok")] + Ok, + #[serde(rename = "ausente")] + Ausente, + #[serde(rename = "pendente")] + Pendente, + #[serde(rename = "falha")] + Falha, + #[serde(rename = "nao_verificavel")] + NaoVerificavel, +} + +impl CheckStatus { + pub fn as_str(&self) -> &'static str { + match self { + Self::Ok => "ok", + Self::Ausente => "ausente", + Self::Pendente => "pendente", + Self::Falha => "falha", + Self::NaoVerificavel => "não verificável", + } + } +} + +/// An individual diagnosis check. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DoctorCheck { + pub name: String, + pub status: CheckStatus, + pub critical: bool, + pub detail: String, +} + +/// The complete diagnosis report of the runtime environment. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DoctorReport { + pub version: String, + pub ok: bool, + pub checks: Vec, +} + +impl DoctorReport { + /// Renders the diagnosis report as a formatted plain-text table. + pub fn render_table(&self) -> String { + let mut out = String::new(); + out.push_str(&format!( + "Xexéu v{} - Diagnóstico do Ambiente\n", + self.version + )); + out.push_str( + "================================================================================\n", + ); + out.push_str(&format!("{:<15} {:<15} {}\n", "Item", "Status", "Detalhe")); + out.push_str( + "--------------------------------------------------------------------------------\n", + ); + for check in &self.checks { + out.push_str(&format!( + "{:<15} {:<15} {}\n", + check.name, + check.status.as_str(), + check.detail + )); + } + out.push_str( + "--------------------------------------------------------------------------------\n", + ); + if self.ok { + out.push_str("Resultado: OK (ambiente apto para execução)\n"); + } else { + out.push_str("Resultado: FALHA (corrija os itens críticos marcados acima)\n"); + } + out + } +} + +/// Parses the `CapEff:` hex bitmask line from a Linux `/proc/self/status` formatted string. +pub fn parse_cap_eff_from_status(status_text: &str) -> Option { + for line in status_text.lines() { + if let Some(rest) = line.strip_prefix("CapEff:") { + let hex = rest.trim(); + return u64::from_str_radix(hex, 16).ok(); + } + } + None +} + +/// Parses the effective UID from the `Uid:` line of `/proc/self/status`. +pub fn parse_euid_from_status(status_text: &str) -> Option { + for line in status_text.lines() { + if let Some(rest) = line.strip_prefix("Uid:") { + let mut parts = rest.split_whitespace(); + let _real = parts.next()?; + let effective = parts.next()?; + return effective.parse().ok(); + } + } + None +} + +/// Checks whether `CAP_NET_RAW` (bit 13) is active in the capability bitmask. +pub fn has_net_raw_from_mask(mask: u64) -> bool { + const CAP_NET_RAW_BIT: u64 = 13; + (mask & (1 << CAP_NET_RAW_BIT)) != 0 +} + +/// Evaluates network raw capability given an optional `/proc/self/status` content and root indicator. +pub fn check_net_raw_simulated(status_content: Option<&str>, is_root: bool) -> DoctorCheck { + match status_content { + Some(content) => match parse_cap_eff_from_status(content) { + Some(mask) => { + let has_raw = has_net_raw_from_mask(mask); + if has_raw { + DoctorCheck { + name: "net_raw".to_string(), + status: CheckStatus::Ok, + critical: false, + detail: format!( + "CAP_NET_RAW ativo (varredura SYN raw disponível){}", + if is_root { ", rodando como root" } else { "" } + ), + } + } else { + DoctorCheck { + name: "net_raw".to_string(), + status: CheckStatus::Ausente, + critical: false, + detail: format!( + "sem CAP_NET_RAW (modo TCP connect / nativo-sem-raw ativo){}", + if is_root { + ", rodando como root sem cap" + } else { + "" + } + ), + } + } + } + None => DoctorCheck { + name: "net_raw".to_string(), + status: CheckStatus::NaoVerificavel, + critical: false, + detail: "não foi possível ler CapEff de /proc/self/status".to_string(), + }, + }, + None => DoctorCheck { + name: "net_raw".to_string(), + status: CheckStatus::NaoVerificavel, + critical: false, + detail: "não verificável fora do Linux (modo TCP connect / nativo-sem-raw)".to_string(), + }, + } +} + +/// Runs the complete environment diagnosis checks. +pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport { + let version = env!("CARGO_PKG_VERSION").to_string(); + let mut checks = Vec::new(); + + // 1. Binary version + checks.push(DoctorCheck { + name: "versao".to_string(), + status: CheckStatus::Ok, + critical: false, + detail: format!("xexeu v{version}"), + }); + + // 2. Configuration file check + if !config_path.exists() { + checks.push(DoctorCheck { + name: "config".to_string(), + status: CheckStatus::Ausente, + critical: true, + detail: format!( + "arquivo de configuração não encontrado em {}", + config_path.display() + ), + }); + } else { + match fs::read_to_string(config_path) { + Ok(raw) => match XexeuConfig::load_validated(&raw) { + Ok((cfg, _report)) => { + checks.push(DoctorCheck { + name: "config".to_string(), + status: CheckStatus::Ok, + critical: true, + detail: format!( + "presente e válida ({} grupos) em {}", + cfg.groups.len(), + config_path.display() + ), + }); + } + Err(e) => { + checks.push(DoctorCheck { + name: "config".to_string(), + status: CheckStatus::Falha, + critical: true, + detail: format!("inválida em {}: {e}", config_path.display()), + }); + } + }, + Err(e) => { + checks.push(DoctorCheck { + name: "config".to_string(), + status: CheckStatus::Falha, + critical: true, + detail: format!("erro ao ler {}: {e}", config_path.display()), + }); + } + } + } + + // 3. CAP_NET_RAW / root capability check + let status_str = fs::read_to_string("/proc/self/status").ok(); + let is_root = status_str + .as_deref() + .and_then(parse_euid_from_status) + .map(|uid| uid == 0) + .unwrap_or(false); + checks.push(check_net_raw_simulated(status_str.as_deref(), is_root)); + + // 4. Local SQLite storage check + let db_path = data_dir.join("xexeu.db"); + if let Some(parent) = db_path.parent() { + let _ = fs::create_dir_all(parent); + } + match SqliteStorage::open(&db_path) { + Ok(_) => { + checks.push(DoctorCheck { + name: "sqlite".to_string(), + status: CheckStatus::Ok, + critical: true, + detail: format!("banco SQLite acessível em {}", db_path.display()), + }); + } + Err(e) => { + checks.push(DoctorCheck { + name: "sqlite".to_string(), + status: CheckStatus::Falha, + critical: true, + detail: format!( + "falha ao acessar banco SQLite em {}: {e}", + db_path.display() + ), + }); + } + } + + // 5. Vulnerability database check + let vuln_db_path = data_dir.join("vuln_db.json"); + let mut vuln_db_mtime: Option = None; + + if !vuln_db_path.exists() { + checks.push(DoctorCheck { + name: "vuln_db".to_string(), + status: CheckStatus::Ausente, + critical: false, + detail: format!( + "base ausente em {} (execute 'xexeu feeds sync' ou 'import')", + vuln_db_path.display() + ), + }); + } else { + vuln_db_mtime = fs::metadata(&vuln_db_path) + .ok() + .and_then(|m| m.modified().ok()); + match VulnDatabase::load_from_file(&vuln_db_path) { + Ok(db) => { + checks.push(DoctorCheck { + name: "vuln_db".to_string(), + status: CheckStatus::Ok, + critical: false, + detail: format!( + "presente em {} ({} CVEs, {} no KEV)", + vuln_db_path.display(), + db.cve_count(), + db.kev_count() + ), + }); + } + Err(e) => { + checks.push(DoctorCheck { + name: "vuln_db".to_string(), + status: CheckStatus::Falha, + critical: false, + detail: format!( + "arquivo de vulnerabilidades inválido em {}: {e}", + vuln_db_path.display() + ), + }); + } + } + } + + // 6. Feeds sync age check + if let Some(mtime) = vuln_db_mtime { + let duration = SystemTime::now().duration_since(mtime).unwrap_or_default(); + let hours = duration.as_secs() / 3600; + let days = hours / 24; + let age_desc = if days > 0 { + format!("{days} dia(s) atrás") + } else if hours > 0 { + format!("{hours} hora(s) atrás") + } else { + let minutes = (duration.as_secs() % 3600) / 60; + format!("{minutes} minuto(s) atrás") + }; + + if days >= 7 { + checks.push(DoctorCheck { + name: "feeds_sync".to_string(), + status: CheckStatus::Pendente, + critical: false, + detail: format!("última sincronização há {age_desc} (recomendado atualizar)"), + }); + } else { + checks.push(DoctorCheck { + name: "feeds_sync".to_string(), + status: CheckStatus::Ok, + critical: false, + detail: format!("última sincronização há {age_desc}"), + }); + } + } else { + checks.push(DoctorCheck { + name: "feeds_sync".to_string(), + status: CheckStatus::Pendente, + critical: false, + detail: "sincronização de feeds pendente (nenhuma base encontrada)".to_string(), + }); + } + + let ok = checks + .iter() + .all(|c| !c.critical || c.status == CheckStatus::Ok); + + DoctorReport { + version, + ok, + checks, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn test_cap_eff_parsing_and_net_raw_simulation() { + // Bit 13 set: 1 << 13 = 0x2000 + let status_with_raw = "Name:\txexeu\nUid:\t0\t0\t0\t0\nCapEff:\t0000000000002000\n"; + assert_eq!(parse_cap_eff_from_status(status_with_raw), Some(0x2000)); + assert_eq!(parse_euid_from_status(status_with_raw), Some(0)); + assert!(has_net_raw_from_mask(0x2000)); + + let check_ok = check_net_raw_simulated(Some(status_with_raw), true); + assert_eq!(check_ok.status, CheckStatus::Ok); + assert!(check_ok.detail.contains("CAP_NET_RAW ativo")); + assert!(check_ok.detail.contains("rodando como root")); + + // Bit 13 cleared + let status_no_raw = + "Name:\txexeu\nUid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000000000\n"; + assert_eq!(parse_cap_eff_from_status(status_no_raw), Some(0)); + assert_eq!(parse_euid_from_status(status_no_raw), Some(1000)); + assert!(!has_net_raw_from_mask(0)); + + let check_ausente = check_net_raw_simulated(Some(status_no_raw), false); + assert_eq!(check_ausente.status, CheckStatus::Ausente); + assert!(check_ausente.detail.contains("TCP connect")); + + // Non-Linux or unparseable + let check_none = check_net_raw_simulated(None, false); + assert_eq!(check_none.status, CheckStatus::NaoVerificavel); + } + + #[test] + fn test_doctor_with_valid_and_invalid_config() { + let dir = tempdir().expect("tempdir"); + let data_dir = dir.path().join("data"); + let valid_config = dir.path().join("valid.toml"); + let invalid_config = dir.path().join("invalid.toml"); + let missing_config = dir.path().join("missing.toml"); + + fs::write( + &valid_config, + r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "servidores" +alvos = ["10.0.0.1"] +"#, + ) + .expect("write valid toml"); + + fs::write(&invalid_config, "not valid toml !!!").expect("write invalid toml"); + + // Valid config report + let report_valid = run(&valid_config, &data_dir); + assert!(report_valid.ok); + let config_check = report_valid + .checks + .iter() + .find(|c| c.name == "config") + .expect("config check present"); + assert_eq!(config_check.status, CheckStatus::Ok); + + // Invalid config report + let report_invalid = run(&invalid_config, &data_dir); + assert!(!report_invalid.ok); + let config_check = report_invalid + .checks + .iter() + .find(|c| c.name == "config") + .expect("config check present"); + assert_eq!(config_check.status, CheckStatus::Falha); + + // Missing config report + let report_missing = run(&missing_config, &data_dir); + assert!(!report_missing.ok); + let config_check = report_missing + .checks + .iter() + .find(|c| c.name == "config") + .expect("config check present"); + assert_eq!(config_check.status, CheckStatus::Ausente); + } + + #[test] + fn test_doctor_table_rendering() { + let dir = tempdir().expect("tempdir"); + let config_path = dir.path().join("xexeu.toml"); + let data_dir = dir.path().join("data"); + + fs::write( + &config_path, + r#" +[escopo] +autorizado = ["192.168.1.0/24"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "default" +alvos = ["192.168.1.1"] +"#, + ) + .expect("write toml"); + + let report = run(&config_path, &data_dir); + let table = report.render_table(); + assert!(table.contains("Xexéu v")); + assert!(table.contains("versao")); + assert!(table.contains("config")); + assert!(table.contains("sqlite")); + assert!(table.contains("Resultado: OK")); + } +} diff --git a/scripts/instalar-hooks.sh b/scripts/instalar-hooks.sh new file mode 100755 index 0000000..8978549 --- /dev/null +++ b/scripts/instalar-hooks.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Ativa os Git hooks do repositório (.githooks/pre-push e .githooks/commit-msg). +set -euo pipefail +cd "$(dirname "$0")/.." +git config core.hooksPath .githooks +echo "hooks ativados: git commit valida Conventional Commits e git push executa scripts/verificar.sh (desative com: git config --unset core.hooksPath)" diff --git a/scripts/release-notes.sh b/scripts/release-notes.sh new file mode 100755 index 0000000..b39d6d2 --- /dev/null +++ b/scripts/release-notes.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Prints release notes for a given tag: extracts the matching CHANGELOG.md +# section, or falls back to the commit log since the previous tag. +# +# scripts/release-notes.sh v1.2.3 +set -euo pipefail + +tag=${1:?usage: release-notes.sh } +version=${tag#v} + +section="" +if [ -f CHANGELOG.md ]; then + section=$(awk -v head="## [$version]" ' + index($0, head) == 1 { found = 1; next } + found && /^## \[/ { exit } + found && /^\[[^]]+\]: / { next } + found { print } + ' CHANGELOG.md) +fi + +if [ -n "$(printf '%s' "$section" | tr -d '[:space:]')" ]; then + printf '%s\n' "$section" +else + previous=$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true) + echo "## Changes${previous:+ since $previous}" + echo + git log --no-merges --format='- %s (%h)' "${previous:+$previous..}$tag" +fi diff --git a/scripts/smoke-image.sh b/scripts/smoke-image.sh new file mode 100755 index 0000000..e6a6cf8 --- /dev/null +++ b/scripts/smoke-image.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Smoke-tests a Xexéu image: the API and the dashboard answer, +# xexeu doctor reports ok, a HEALTHCHECK is declared and SIGTERM stops the daemon cleanly. +# Everything runs through `docker exec`, so no port has to be reachable from +# the CI job container. The container is always removed. +# +# scripts/smoke-image.sh +set -euo pipefail + +image=${1:?usage: smoke-image.sh } +name="xexeu-smoke-$$-$RANDOM" +trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT +fail() { echo "smoke: $*" >&2; docker logs "$name" >&2 2>&1 || true; exit 1; } + +docker run -d --name "$name" "$image" >/dev/null +for _ in $(seq 1 30); do + docker exec "$name" curl -fsS http://127.0.0.1:8788/api/health >/dev/null 2>&1 && break + sleep 1 +done +docker exec "$name" curl -fsS http://127.0.0.1:8788/api/health | grep -q '"status":"ok"' || fail "/api/health did not answer" +docker exec "$name" curl -fsS http://127.0.0.1:8788/ | grep -qi '/dev/null +code=$(docker inspect -f '{{.State.ExitCode}}' "$name") +[ "$code" = 0 ] || fail "exit code $code after SIGTERM (expected 0: SIGTERM must stop serve)" +echo "smoke: $image ok" diff --git a/scripts/verificar.sh b/scripts/verificar.sh new file mode 100755 index 0000000..5e4dcb1 --- /dev/null +++ b/scripts/verificar.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Verificação local: executa as mesmas checagens do CI antes do push. +# +# scripts/verificar.sh completo: fmt, clippy, scripts, workflows, semver, compose, testes +# scripts/verificar.sh --rapido pula a suíte de testes do workspace +# +set -uo pipefail +cd "$(dirname "$0")/.." +rapido=0 +[ "${1:-}" = "--rapido" ] || [ "${1:-}" = "--fast" ] && rapido=1 +failures=() +step() { # step "name" command... + local name="$1"; shift + printf '\n\033[1m== %s\033[0m\n' "$name" + if "$@"; then printf '\033[32mok\033[0m %s\n' "$name"; else printf '\033[31mFAILED\033[0m %s\n' "$name"; failures+=("$name"); fi +} + +step "formatting (cargo fmt)" cargo fmt --all -- --check +step "clippy (workspace, all targets)" env RUSTFLAGS="-D warnings" cargo clippy --workspace --all-targets + +step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do [ -f "$f" ] || continue; bash -n "$f" || exit 1; done' + +step "workflows and templates (valid YAML)" python3 -c " +import glob, yaml +for f in glob.glob('.gitea/**/*.yml', recursive=True): + yaml.safe_load(open(f)) +" + +step "brand assets" test -s logo.png + +step "consistent Semantic Versioning 2.0.0" python3 -c " +import re, sys +from pathlib import Path + +semver_re = re.compile( + r'^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)' + r'(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?' + r'(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$' +) + +def cargo_version(path): + m = re.search(r'^version\s*=\s*\"([^\"]+)\"', Path(path).read_text(), re.M) + if not m: + sys.exit(f'version not found in {path}') + return m.group(1) + +version = cargo_version('Cargo.toml') +if not semver_re.match(version): + sys.exit(f'invalid SemVer 2.0.0 version: {version}') +print(version) +" + +if command -v docker >/dev/null && docker compose version >/dev/null 2>&1; then + step "docker compose config" docker compose config --quiet +else + printf '\n(docker compose config: skipped, docker compose not available)\n' +fi + +if [ "$rapido" = 0 ]; then + step "tests (cargo test --workspace)" cargo test --workspace +fi + +printf '\n' +if [ ${#failures[@]} -eq 0 ]; then + printf '\033[32mall checks passed\033[0m: ready to push.\n' +else + printf '\033[31mfailed:\033[0m %s\n' "${failures[*]}" + exit 1 +fi