cli

package
v0.511.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

README

CLI Module

CLI adapter layer for the DeltaScope application.

Files

File Responsibility
cli.go Bridges process execution into the testable CLI executor, normalizes legacy audit prefix flag forms without exposing them to Query Access, and maps unset Cobra usage errors (including prefixed flag forms) to exit 2, except query-access usage which stays 3
root.go Builds the Cobra root command and audit/query-access/other subcommand wiring, shared CLI option state, stable error/exit-code mapping, and root flags while keeping audit-only rendering/threshold flags local to audit
audit.go Implements the audit subcommand, rendering, Fail Threshold vs Verdict, and SQL input. Connection flags go through connresolve.Resolve. connresolve.Classify maps to existing CLI TLS/refusal/authentication sentences. Markdown unsupported/diagnostics come from markdown.Render; CLI only prepends Audit Context. Ask-password stays CLI-owned.
audit_metadata.go Bridges CLI metadata-aware options into auditmeta.Prepare, using the shared auditmeta opener instead of a CLI-local OpenDB fork, and attaches the shared offline context.note / context.unproven when existence was not checked
cli_impact_postgresql_tag_test.go Verifies PostgreSQL offline primary-key equality impact in CLI JSON output
query_access.go Implements the query-access analyze subcommand with -h/--help versus -H/--host, advertised Query Access exit table, flag-presence-aware --sql/--file/stdin loading, immediate explicit-empty validation with command-named query-access: SQL input must not be empty (exit 3, no stdin fallthrough), explicit dialect-specific MySQL/TiDB database/schema alias and default-qualifier binding with conflict rejection, dialect-aware connection flags, fixed JSON output, admission-based exit codes, identity-routed online analysis through attachOnlineQueryAccessSession (reuses OpenSession identity; no second probe), shared bounded connection/authentication/TLS translation, and the bounded PostgreSQL 17 requirement; audit-only --format/--fail-on are rejected as usage errors
query_access_test.go Verifies query-access help and flag ownership, advertised Query Access exit table, MySQL/TiDB database/schema aliases, request-default/catalog separation and conflicts, PostgreSQL connection preservation/version boundary, SQL input validation including command-named empty --sql (exit 3, no stdin read), fixed JSON output, admission exit codes, unified online routing, bounded failure presentation, close ownership, and no audit-field leakage
cli_host_help_flag_test.go Verifies audit and query-access analyze -h/--help print help and exit 0, -H/--host still bind host, and bare -h is not flag needs an argument
query_access_unified_entry_test.go Structurally verifies formatted runQueryAccessOnline source contains no product inspection or dialect-specific Query Access constructor/analysis calls, uses both unified SDK entry seams, and reuses Observed Server Identity
query_access_postgresql_online_recording_test.go Focused recording-driver proof that the CLI PostgreSQL unified online path delegates COUNT(1), closes its session once, maps bounded cancellation/closed-session/connection/catalog failures, and never sends user SQL, EXPLAIN, or prepare operations
query_access_e2e_mixed_literal_test.go Docker-backed built-binary smoke for admitted and fail-closed MySQL 8.4 and TiDB 8.5 Query Access routes, plus CLI default/offline indeterminate result and marker no-leak evidence
query_access_probe_boundary_no_leak_test.go No-leak regression for the MySQL/TiDB builtin-identity probe boundary on the CLI surface: asserts injected markers, identity facts, candidates, session/context, manifest, raw SQL, and severity are absent from stdout/stderr/JSON
query_access_postgresql_no_leak_test.go PostgreSQL 17 integration no-leak coverage for online COUNT(1), excluded shapes, and default-offline CLI paths
rules.go Implements rules list (with dialect/level/kind/category/search/format/limit filters) and rules explain <rule-id> on top of the shipped rule catalog, including text and JSON output
config.go Implements the config command group, including lint (semantic validation plus rule-level replacement-hazard warnings and --strict), show-default, and wiring for status
config_init.go Implements config init and emits a deterministic default YAML template with empty string params encoded as ""
config_init_test.go Verifies config init / show-default / shipped example YAML lint clean, encode empty strings as quoted YAML, preserve a hand-written full-spec override, and leave default-policy audit findings unchanged
config_status.go Implements config status <rule-id>, showing the effective ON/OFF state, Loaded, level, default/current snapshots, config effect, and FK-forbid suppression for one rule via the config status application service, with text and JSON output
capabilities.go Implements the capabilities summary command and shared rendering helpers for human/agent discovery of shipped dialects, modes, inputs, outputs, and public surfaces (cli, http, mcp, go-api)
ddl_coverage.go Implements the ddl-coverage command for querying the generated (embedded) DDL coverage catalog with text and JSON output, flag validation, filter rendering, and exit-2 catalog-unavailable mapping for a missing --catalog override
capability_surface.go Defines the pure-Go build capability surface and root CLI wording
capability_surface_pg.go Defines the PostgreSQL-tagged build capability surface and root CLI wording
version.go Implements the version subcommand with ASCII logo plus build-version and supported-dialect output; empty ldflags Version uses ReportedVersion()
version_test.go Verifies release ldflags keep the tag and untagged/empty Version uses ReportedVersion() instead of claiming DefaultVersion as the sole version
cli_test.go Verifies input modes including explicit empty/whitespace --sql fail-closed without reading stdin with audit: SQL input must not be empty (exit 2, distinct from Query Access), advertised audit exit table, Fail Threshold help that does not change Verdict, empty --file rejection, legacy audit prefix output/threshold flags, MySQL-style -H/-P/-u/-D connection/password UX, exit-code behavior, CLI JSON fail_on_triggered beside unchanged Verdict, capability/version wording surfaces, audit context output, explanation rendering in Markdown/JSON results, the user-facing Action Summary markdown contract (section presence, rule explain command, statement index, clean-result omission, JSON/quiet non-regression, and no severity field), compact and opt-in CLI JSON skipped-rule contracts, quiet JSON byte stability, non-JSON --include-skipped-rules byte-equality no-op, the aggregated rule-summary markdown contract (bounded ### Skip Reasons, no ## Skipped Rules section, no skipped rule IDs) and JSON rule-summary list preservation, github-summary format coverage (REJECT/PASS verdict, action summary, clean-result omission, no raw SQL, no severity, help advertising, unsupported-format messaging), and audit-only help advertising of all output formats; valid TLS CA loading accepts environment-dependent bounded runtime outcomes including connection refused, generic connection failure/timeout, and TLS verification/hostname failures
cli_offline_existence_test.go Locks offline ALTER DROP COLUMN / ALTER missing-table as pass, with existence-not-checked copy on markdown Action Summary, quiet [context], and JSON context.note / context.unproven, and documents that --quiet --format json keeps the JSON contract
cli_user_input_exit_test.go Verifies unknown flags and unparseable SQL exit 2, parser-error JSON keeps an empty verdict with diagnostics[].classification == parser_error, and existing format/dialect/missing-file user errors stay at exit 2
cli_metadata_connection_exit_test.go Verifies metadata-aware connection failures exit 3 with bounded refusal/dial/auth/timeout and TLS category messages, typed MySQL/pgx TLS signals, no-leak output, omitted password source after auth failure exits 2, and missing --password-env stays exit 2 without connecting
cli_unsupported_diagnostics_evidence_test.go Verifies mixed parser-error JSON/Markdown applies the review floor while preserving valid statements/findings, bounded diagnostic locations, exit 2, and no-leak behavior
cli_unsupported_verdict_floor_postgresql_tag_test.go Verifies PostgreSQL SELECT 1 JSON/Markdown render review and keep exit 1 with audited-only statement counts
ddl_coverage_test.go Verifies ddl-coverage command filtering, text/JSON output, empty results, invalid flags, no-leak sanity across all 400 catalog entries, embedded-catalog lookup from an empty working directory, and exit 2 when a --catalog override is missing
rules_catalog_test.go Verifies rules list filtering (dialect, level, kind, category, search, limit), rules explain detail output, text/JSON formats, invalid flags, empty results, no-severity sanity, and default-disabled dml.impact.* catalog rows
audit_metadata_test.go Verifies metadata-aware CLI wiring for dialect detection, MySQL/TiDB database/schema aliases and conflicts, schema inference, PostgreSQL schema/database usage validation, create-table partial behavior, dialect-aware port defaults, and metadata-connect-timeout flag validation
audit_dml_table_existence_test.go Verifies metadata-aware MySQL/TiDB INSERT/UPDATE/DELETE missing-target findings and their stable JSON shape
config_status_test.go Verifies config status text/JSON output, partial-replacement danger wording, disabled-rule wording, FK-forbid suppression wording, and error mapping (missing rule id, unknown rule, invalid format, invalid config) with no severity field
config_lint_test.go Verifies config lint warnings (level-only replacement hazard), Config OK / Config OK with warnings output and exit-code matrix, --strict, error precedence, deterministic warning ordering, existing invalid-value errors, and YAML-null string params still failing the type check, with no severity field

Exports

  • Run()
  • Execute(ctx, args, stdin, stdout, stderr) int

Dependencies

  • Upstream: cmd/deltascope
  • Downstream: bufio, encoding/json, internal/application/audit, internal/application/auditmeta, internal/application/configlint, internal/application/configstatus, internal/application/connresolve, internal/application/queryaccess, internal/domain/policy, internal/domain/report, internal/domain/rule/catalog, internal/domain/spec, internal/infrastructure/config/viper, internal/infrastructure/output/githubsummary, internal/infrastructure/output/json, internal/infrastructure/output/markdown, internal/interfaces/metadata, pkg/deltascope, github.com/spf13/cobra, golang.org/x/term

Notes

  • Online query-access analyze keeps connection/TLS/credential lifecycle in the CLI, canonicalizes MySQL/TiDB --database/--schema aliases and the missing request default qualifier, then passes the caller-owned pinned connection to the opaque unified SDK session without inspecting observed product or constraining the analysis request dialect. Reachable PostgreSQL identities outside PG17 return exit 3 with the fixed bounded message online PostgreSQL Query Access requires PostgreSQL 17; authentication, dial, timeout, and TLS mappings remain separate.
  • Query Access semantic breadth and detailed probe tests live in the unified SDK suite; this module retains only CLI-owned transport, sink, lifecycle, and real-route evidence.
  • deltascope --version prints the build version plus compiled dialect surface. Release ldflags print the tag; source and go install @main builds print ReportedVersion().
  • deltascope version prints the ASCII logo plus the same build version and compiled dialect surface.
  • Audit file, inline, and stdin SQL pass through the shared one-leading-UTF-8-BOM normalization before parsing.
  • A parser error in one bounded migration statement still renders audited siblings in source order, emits only the bad statement's safe diagnostic, and exits 2. If those siblings otherwise compute pass, JSON and Markdown render review; existing review/reject verdicts do not downgrade.

Update Rule

  • If members/interfaces/dependencies change, update this file in same change.

Documentation

Overview

Package cli exposes the command-line adapter for DeltaScope. input: audit command flags including -h/--help versus -H/--host, audit-local output format, skipped-rule detail, and fail threshold, whether --sql was explicitly provided, SQL text from flags/files/stdin, password prompt, connresolve Request fields, and application audit services output: rendered audit results and located diagnostics, audit-only output validation, command-named empty-SQL usage errors, advertised audit exit table, CLI JSON skipped-rule aggregation with optional stable per-rule details, CLI JSON fail_on_triggered beside unchanged Verdict, dialect-aware connection-option normalization with MySQL/TiDB catalog aliases and PostgreSQL schema/database validation, password resolution, offline existence caveats, and user-vs-runtime exit-code mapping through connresolve Connection Failure Class mapped to CLI TLS/refusal/authentication phrases pos: CLI audit command implementation above the application service and output renderers note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: metadata-aware audit connection options, SQL text, and the shared auditmeta opener output: resolved dialect/schema context including MySQL/TiDB catalog aliases, offline existence caveat fields, and provider wiring for metadata-aware CLI audits pos: CLI metadata-aware audit preparation between command flags and application requests note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: capability command invocations plus shipped product-surface metadata output: stable human-readable summaries of supported dialects, modes, inputs, outputs, and shipped surfaces across CLI, HTTP, MCP, and Go API entrypoints pos: CLI capability discovery command above the current shipped product surface note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: process control from cmd/deltascope, Cobra command execution requests, and legacy audit flag placement output: executable CLI behavior and stable process exit codes, including legacy audit flag normalization and Cobra usage-error mapping for audit and query-access command paths pos: interface adapter between process entrypoint and application services note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: config command invocations and YAML config files output: config lint results with validation errors and replacement warnings, default-config rendering, and rule config status wiring pos: CLI config command group for policy inspection and validation note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: config init command invocations and the built-in default policy model output: a lint-round-trippable YAML policy template for local users and automation pos: CLI config generation command for bootstrapping DeltaScope policy files note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: a rule ID, the global --config policy path, and the config status application service output: human and JSON status for one shipped rule under the default policy plus optional config, including Loaded and fk_forbid suppression pos: CLI config status command above the application config status use case note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: ddl-coverage command flags, LoadEmbeddedCatalog, and optional LoadCatalogFile path override output: filtered catalog entries rendered as human-readable text or machine-readable JSON pos: CLI ddl-coverage command for querying the generated DDL coverage catalog note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: query-access command flags including -h/--help versus -H/--host, dialect-aware connection and catalog/schema hints, flag-presence-aware SQL text from --sql/--file/stdin, and the unified public online query access API output: rendered offline or alias-bound identity-routed online query access results in JSON format, command-named empty-SQL usage errors, advertised Query Access exit table, exit-code mapping, and connresolve.Classify mapped to Query Access TLS/authentication sentences pos: CLI query-access command implementation above offline analysis and the opaque unified online session boundary note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: Cobra command construction inputs, process-like stdin/stdout/stderr dependencies, and shared CLI option state output: root command wiring for audit, query-access, rules, config, capabilities, ddl-coverage, and version subcommands, with audit-only rendering and threshold flags kept off the root pos: CLI command assembly and shared option definitions note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: rule catalog queries, CLI filters, and stdout/stderr command surfaces output: shipped-rule list, detail, and search rendering for CLI discovery workflows pos: CLI rule catalog command group above the explanation-oriented domain catalog note: if this file changes, update this header and module README.md.

Package cli exposes the command-line adapter for DeltaScope. input: version command invocations and the optional ldflags version variable output: a printable version string from release ldflags or Go build information pos: CLI metadata command implementation note: if this file changes, update this header and module README.md.

Index

Constants

This section is empty.

Variables

View Source
var Version string

Version is the optional ldflags-injected release version printed by the version command. Empty means the process reports Go build information.

Functions

func Execute

func Execute(ctx context.Context, args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) int

Execute runs the CLI using the supplied process-like dependencies.

func Run

func Run()

Run executes the CLI against the current process environment and exits.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL