diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..82811a9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,25 @@ +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: weekly + groups: + go-minor-patch: + patterns: + - "*" + update-types: + - minor + - patch + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions-minor-patch: + patterns: + - "*" + update-types: + - minor + - patch diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml new file mode 100644 index 0000000..415aaeb --- /dev/null +++ b/.github/workflows/bench.yml @@ -0,0 +1,81 @@ +name: bench + +# Timing benchmarks are reported, not gated: a CI runner is too noisy for a +# fixed time budget. Both sides run on the SAME runner, so benchstat can tell +# whether a change is real without a committed baseline from someone's laptop. +# Behavior is gated separately by the golden tests inside `go test ./...`. +on: + pull_request: + paths: + - 'internal/**/*.go' + - 'Makefile' + - 'go.mod' + - 'go.sum' + - '.github/workflows/bench.yml' + workflow_dispatch: + +permissions: + contents: read + +env: + GO_VERSION: '1.27.4' + +concurrency: + group: bench-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + compare: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout PR + uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + + - name: Resolve base commit + shell: bash + run: | + if [ -n "${{ github.event.pull_request.base.sha }}" ]; then + echo "${{ github.event.pull_request.base.sha }}" > "$RUNNER_TEMP/base.sha" + else + git rev-parse HEAD~1 > "$RUNNER_TEMP/base.sha" + fi + cat "$RUNNER_TEMP/base.sha" + + - name: Benchmark base + shell: bash + run: | + git worktree add "$RUNNER_TEMP/base" "$(cat "$RUNNER_TEMP/base.sha")" + # The base commit predates the bench target in some PRs. Use the PR's + # Makefile so both sides run the exact same benchmark command. + cp "$GITHUB_WORKSPACE/Makefile" "$RUNNER_TEMP/base/Makefile" + cd "$RUNNER_TEMP/base" + make bench BENCH_COUNT=5 > "$RUNNER_TEMP/base.txt" + + - name: Benchmark PR + shell: bash + run: | + make bench BENCH_COUNT=5 > "$RUNNER_TEMP/pr.txt" + + - name: Compare with benchstat + shell: bash + run: | + go run golang.org/x/perf/cmd/benchstat@v0.0.0-20261117185222-4febdb082b2c \ + "$RUNNER_TEMP/base.txt" "$RUNNER_TEMP/pr.txt" | tee "$RUNNER_TEMP/benchstat.txt" + + - name: Upload results + if: always() + uses: actions/upload-artifact@v7 + with: + name: benchstat + path: ${{ runner.temp }}/benchstat.txt + if-no-files-found: warn diff --git a/.github/workflows/bridges.yml b/.github/workflows/bridges.yml deleted file mode 100644 index 7976a79..0000000 --- a/.github/workflows/bridges.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: bridges - -# Consolidated CI for the monorepo bridges. The per-bridge certification.yml -# workflows were removed on import: nested workflows do not run on GitHub, and -# a stale copy invites edits that never take effect. -# -# This workflow is scoped to bridge and core-internal changes. The path filters -# are native GitHub `paths:` triggers — no custom scope binary is needed, which -# keeps the toolchain single-language (Go only). - -on: - push: - paths: - - 'bridges/**' - - 'internal/**' - pull_request: - paths: - - 'bridges/**' - - 'internal/**' - -permissions: - contents: read - -concurrency: - group: bridges-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - bundled-bridges: - name: Verify every bundled bridge loads - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Go - uses: actions/setup-go@v5 - with: - go-version: '1.27' - cache: true - cache-dependency-path: go.sum - - - name: Download dependencies - run: go mod download - - - name: Build core - run: go build ./cmd/domaincraft - - - name: Verify every bundled bridge loads (contract gate) - run: go test ./internal/renderer/ -run TestBundledBridgesLoad -v diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df12d91..63bf7bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,10 @@ name: ci on: + # PR checks cover feature branches. Push runs only after a merge to main, + # so the same commit is not tested twice. push: + branches: [main] paths-ignore: - '**/*.md' - 'docs/**' @@ -9,16 +12,24 @@ on: paths-ignore: - '**/*.md' - 'docs/**' + workflow_dispatch: permissions: contents: read +env: + GO_VERSION: '1.27.4' + concurrency: group: ci-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true +# Independent gates run in parallel. On a local 16-core machine the sequential +# steps cost ~13s lint + ~8s govulncheck + ~23s race tests; one job serialized +# all of them. jobs: test: + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -27,12 +38,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: - go-version: '1.27' + go-version: ${{ env.GO_VERSION }} cache: true cache-dependency-path: go.sum @@ -42,24 +53,82 @@ jobs: - name: Build run: go build ./cmd/domaincraft - - name: Vet - run: go vet ./... + - name: Build WASM validator (js/wasm smoke) + # The validator entry point is build-tagged js&&wasm, so the native + # build above cannot see parser/validator/lexer/specmeta breakage. + # Cross-compile to a temp path: no .wasm artifact is committed here. + # The committed GUI binary is refreshed by hand with make build-wasm-gui. + shell: bash + run: GOOS=js GOARCH=wasm go build -o "$RUNNER_TEMP/validate.wasm" ./cmd/wasm-validator - name: Test - run: go test ./... + # Shuffles order because suites mutate package-global seams. + # CI must never skip the bundled-bridge contract gate via local opt-out. + # -count=1 keeps the result deterministic; on this repo the test cache + # costs more to hash (~25s of embedded bridge files) than to rebuild. + # Step-level env works on both bash and PowerShell runners. + env: + DOMAINCRAFT_LOCAL_DEV: "" + run: go test -race -count=1 -shuffle=on ./... + + - name: Integration tests + run: go test -race -count=1 -shuffle=on -tags=integration ./internal/bridge + + lint: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Setup Go + uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + + - name: Download dependencies + run: go mod download + + - name: Check go.mod/go.sum are tidy + run: make check-tidy + + - name: Lint + # Same command as the local gate; the version lives in the Makefile. + run: make lint + + vuln: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Setup Go + uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + + - name: Vulnerability scan + # Pinned in the Makefile, not @latest, so the gate is reproducible. + run: make vulncheck schema-check: name: Verify generated schema is up to date runs-on: ubuntu-latest + timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: - go-version: '1.27' + go-version: ${{ env.GO_VERSION }} cache: true cache-dependency-path: go.sum diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e641335..5c38f01 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,28 +4,75 @@ on: push: tags: - 'v*' + # Manual dry run: build and test the current ref without publishing. + workflow_dispatch: permissions: contents: write +env: + GO_VERSION: '1.27.4' + concurrency: group: release-${{ github.ref }} cancel-in-progress: false jobs: + verify: + name: Verify tagged commit + # A tag can be pushed without a preceding green main CI run. Run the same + # gates as ci.yml before allowing a release to be published. + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Setup Go + uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + + - name: Check go.mod/go.sum are tidy + run: make check-tidy + + - name: Lint + run: make lint + + - name: Vulnerability scan + run: make vulncheck + + - name: Verify generated schema is up to date + run: | + go run ./cmd/schema-gen -o "$RUNNER_TEMP/domain.schema.json" + diff -u spec/domain.schema.json "$RUNNER_TEMP/domain.schema.json" + + - name: Build WASM validator (js/wasm smoke) + run: GOOS=js GOARCH=wasm go build -o "$RUNNER_TEMP/validate.wasm" ./cmd/wasm-validator + + - name: Test + env: + DOMAINCRAFT_LOCAL_DEV: "" + run: go test -race -count=1 -shuffle=on ./... + build-and-release: name: Build binaries and publish release + needs: verify runs-on: ubuntu-latest + timeout-minutes: 25 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: - go-version: '1.27' + go-version: ${{ env.GO_VERSION }} cache: true + cache-dependency-path: go.sum - name: Build all platforms run: | @@ -43,7 +90,8 @@ jobs: sha256sum * > checksums.txt - name: Publish GitHub Release - uses: softprops/action-gh-release@v2 + if: github.event_name == 'push' + uses: softprops/action-gh-release@v3 with: generate_release_notes: true files: | diff --git a/.github/workflows/tck.yml b/.github/workflows/tck.yml new file mode 100644 index 0000000..0d524ef --- /dev/null +++ b/.github/workflows/tck.yml @@ -0,0 +1,110 @@ +name: tck + +# Targets: compliance-suite/tck-matrix.json. Logic: compliance-suite/tck.sh. +# This file only declares jobs. A bridge change selects that bridge and its +# extenders; a core change selects everything. + +on: + push: + branches: [main] + paths: ['bridges/**', 'internal/**', 'pkg/**', 'spec/**', 'cmd/**', 'compliance-suite/**', 'go.mod', 'go.sum', '.github/workflows/tck.yml'] + pull_request: + paths: ['bridges/**', 'internal/**', 'pkg/**', 'spec/**', 'cmd/**', 'compliance-suite/**', 'go.mod', 'go.sum', '.github/workflows/tck.yml'] + workflow_dispatch: + +permissions: + contents: read + +env: + GO_VERSION: '1.27.4' + +concurrency: + group: tck-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + discover: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + node: ${{ steps.scope.outputs.node }} + k6: ${{ steps.scope.outputs.k6 }} + steps: + - uses: actions/checkout@v7 + with: { fetch-depth: 0 } + - uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + - name: Scope targets changed in this PR + id: scope + run: bash compliance-suite/tck.sh discover + + node: + name: Node TCK — ${{ matrix.target.id }} + needs: discover + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + target: ${{ fromJSON(needs.discover.outputs.node) }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + - uses: actions/setup-node@v7 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: ${{ matrix.target.tck_dir && format('{0}/package-lock.json', matrix.target.tck_dir) || 'bridges/typescript/core/tck/package-lock.json' }} + - name: Generate and certify + run: bash compliance-suite/tck.sh node '${{ toJSON(matrix.target) }}' + + k6: + name: Backend TCK — ${{ matrix.target.id }} + needs: discover + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + target: ${{ fromJSON(needs.discover.outputs.k6) }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + cache-dependency-path: go.sum + - uses: actions/setup-node@v7 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: bridges/typescript/client/tck/package-lock.json + - uses: grafana/setup-k6-action@v1 + - name: Generate and start backend + run: bash compliance-suite/tck.sh backend-up '${{ toJSON(matrix.target) }}' + # Interop runs first: suite.js deliberately ends by exhausting the + # 400-request/60s rate window, which makes a later client see 429 with + # Retry-After: 60 and stall in the generated client's retry loop. + - name: Client interop against the same backend + run: bash compliance-suite/tck.sh interop '${{ toJSON(matrix.target) }}' + - name: Run k6 certification suite + run: k6 run -e API_URL="http://127.0.0.1:${{ matrix.target.port || 9000 }}" ./compliance-suite/suite.js + - name: Dump logs on failure + if: failure() + run: bash compliance-suite/tck.sh logs '${{ toJSON(matrix.target) }}' + - uses: actions/upload-artifact@v7 + if: failure() + with: + name: tck-logs-${{ matrix.target.id }} + path: ${{ runner.temp }}/compose-${{ matrix.target.id }}.log + if-no-files-found: ignore + - name: Stop backend + if: always() + run: bash compliance-suite/tck.sh backend-down '${{ toJSON(matrix.target) }}' diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..4008208 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,29 @@ +version: "2" + +run: + timeout: 5m + tests: true + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +linters: + enable: + - govet + - errcheck + - ineffassign + - staticcheck + - unused + - modernize + - revive + - gosec + - bodyclose + - errorlint + - nolintlint + exclusions: + rules: + # Test fixtures use 0644 files and t.TempDir paths on purpose; gosec's + # file-permission and path-taint rules target production code. + - path: '(.+)_test\.go$' + linters: [gosec] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cc9584e..769403d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,18 +15,22 @@ make install-deps && make build # → bin/domaincraft make test && make lint ``` +`make test` needs only Go. `make test-affected` additionally needs a working `python3` (or `python`) on `PATH` — the script uses it to walk the affected-package graph. Without it, run `make test`. + **Validate and generate:** ```bash make cli-validate DOMAIN=examples/domain.yaml -make cli-generate DOMAIN=examples/domain.yaml BRIDGE=../domaincraft-bridge-csharp-rest OUTPUT=/tmp/out +make cli-generate DOMAIN=examples/domain.yaml BRIDGE=csharp-rest OUTPUT=/tmp/out # direct: go run ./cmd/domaincraft validate --domain domain.yaml go run ./cmd/domaincraft generate --domain domain.yaml --bridge ../my-bridge --output ./out # swap a layer without forking: -go run ./cmd/domaincraft generate --domain domain.yaml --bridge ../domaincraft-bridge-csharp-rest --replace persistence=../my-dapper --output ./out +go run ./cmd/domaincraft generate --domain domain.yaml --bridge csharp-rest --replace persistence=../my-dapper --output ./out ``` +Sibling `domaincraft-bridge-*` directories are legacy mirrors of the old standalone repos — they are not part of a fresh monorepo clone. + `--bridge` accepts a local path, a registry ID (`csharp-rest`, `ts-core`) or `owner/repo`. `--replace` accepts `layer=bridgeRef` or `bridgeId=bridgeRef` (repeatable). Create a starter `domain.yaml` by hand or in [Studio](https://fellmonkey.github.io/domaincraft-studio/) — an example is `examples/domain.yaml`. ## Architecture @@ -36,7 +40,7 @@ domain.yaml → Parser → Lexer → Validator → IR Builder → Renderer → G → Snapshot (.domaincraft/snapshot.json) ``` -The **IR** is the contract. Templates read a fully linked `IRProject` — the core never contains C# or TypeScript. Composition is `extends` + `layer` + `--replace` (see [Axes and layers](https://fellmonkey.github.io/domaincraft-site/docs/concepts/three-axes/) and [Architecture](https://fellmonkey.github.io/domaincraft-site/docs/concepts/architecture/)). +The **IR** is the contract. Templates read a fully linked `Project` — the core never contains C# or TypeScript. Composition is `extends` + `layer` + `--replace` (see [Axes and layers](https://fellmonkey.github.io/domaincraft-site/docs/concepts/three-axes/) and [Architecture](https://fellmonkey.github.io/domaincraft-site/docs/concepts/architecture/)). ## Creating a new bridge diff --git a/Makefile b/Makefile index 087c92d..15f2604 100644 --- a/Makefile +++ b/Makefile @@ -6,17 +6,17 @@ SPEC_OUTPUT ?= spec/domain.schema.json GUI_DIR ?= ../domaincraft-studio SKILLS_DIR ?= ../domaincraft-skills/domaincraft-core GO_CACHE_DIR ?= $(CURDIR)/.gocache -GO_TMP_DIR ?= $(CURDIR)/bin +GOLANGCI_LINT_VERSION ?= v2.15.0 +GOVULNCHECK_VERSION ?= v1.9.0 # Release version stamped into the CLI (and WASM validator) binary. ifeq ($(OS),Windows_NT) -VERSION ?= $(shell git describe --tags --abbrev=0 2>nul || echo dev) +VERSION ?= $(shell git describe --tags --exact-match 2>nul || echo dev) else -VERSION ?= $(shell git describe --tags --abbrev=0 2>/dev/null || echo dev) +VERSION ?= $(shell git describe --tags --exact-match 2>/dev/null || echo dev) endif # Cross-platform file copy used by the spec-distribution targets. -# Cross-platform copy used by the spec-distribution targets. ifeq ($(OS),Windows_NT) COPY_CMD = copy /Y "$(subst /,\,$(SPEC_OUTPUT))" "$(subst /,\,$(SKILLS_DIR))\domain.schema.json" GUI_CMD = cd /d "$(subst /,\,$(GUI_DIR))" && call npm run generate:types @@ -26,9 +26,10 @@ GUI_CMD = cd $(GUI_DIR) && npm run generate:types endif export GOCACHE := $(GO_CACHE_DIR) -export GOTMPDIR := $(GO_TMP_DIR) +# GOTMPDIR is deliberately not set: pointing it inside the repo makes +# t.TempDir() land under a monorepo root and breaks path-sensitive tests. -.PHONY: help build install run test test-verbose test-coverage lint fmt clean install-deps cli-validate cli-generate cli-bridges regenerate-spec generate-gui-types copy-spec-skills build-wasm build-wasm-gui +.PHONY: help build install run test test-affected contract-test contract-golden-update bench bench-full bench-golden-update test-verbose test-coverage lint vulncheck vet fmt clean install-deps check-tidy dev-watch dev-test-watch cli-validate cli-generate cli-bridges regenerate-spec generate-gui-types copy-spec-skills build-wasm build-wasm-gui help: @echo "DomainCraft CLI - Available Commands" @@ -44,18 +45,34 @@ help: @echo " make copy-spec-skills - Copy regenerated schema to domaincraft-skills/domaincraft-core" @echo " make build-wasm - Build WASM validator binary (GOOS=js GOARCH=wasm)" @echo " make build-wasm-gui - Build WASM and copy to domaincraft-studio/public/wasm/" - @echo " make test - Run all tests" + @echo " make test - Run all tests (test cache disabled)" + @echo " make test-affected - Run tests for packages touched by uncommitted changes" + @echo " make contract-test - Run contract tests (golden output + determinism)" + @echo " make contract-golden-update - Regenerate golden manifests after an intentional output change" + @echo " make bench - Run the fast benchmarks (one pass each)" + @echo " make bench-full - Include BenchmarkComputeDiff (~157 s)" + @echo " make bench-golden-update - Rewrite benchmark behavior goldens" @echo " make test-verbose - Run tests with verbose output" @echo " make test-coverage - Run tests and generate coverage report" - @echo " make lint - Run linter (go vet)" + @echo " make lint - Run golangci-lint via go run (same gate as CI)" + @echo " make vulncheck - Run govulncheck via go run" + @echo " make vet - Run go vet ./..." @echo " make fmt - Format code (gofmt)" @echo " make clean - Clean build artifacts" - @echo " make install-deps - Install dependencies" + @echo " make install-deps - Download dependencies (go mod download)" + @echo " make check-tidy - Fail if go mod tidy would change go.mod/go.sum" + @echo " make dev-watch - Rebuild/run on file changes (requires entr)" + @echo " make dev-test-watch - Run tests on file changes (requires entr)" install-deps: - @echo "Installing dependencies..." + @echo "Downloading dependencies..." @go mod download + +# Check only: go mod tidy must not mutate go.mod/go.sum in CI. +check-tidy: + @echo "Checking go.mod/go.sum are tidy..." @go mod tidy + @git diff --exit-code -- go.mod go.sum build: install-deps @echo "Building domaincraft ($(VERSION))..." @@ -63,6 +80,12 @@ build: install-deps install: build @echo "Installing domaincraft..." +ifeq ($(OS),Windows_NT) + @cmd /c "if not exist %LOCALAPPDATA%\DomainCraft mkdir %LOCALAPPDATA%\DomainCraft" + @cmd /c "copy /Y bin\domaincraft %LOCALAPPDATA%\DomainCraft\domaincraft.exe >nul" + @echo "Installed to %LOCALAPPDATA%\DomainCraft\domaincraft.exe" + @echo "Make sure %LOCALAPPDATA%\DomainCraft is in your PATH" +else @if [ -d "/usr/local/bin" ] && [ -w "/usr/local/bin" ]; then \ cp bin/domaincraft /usr/local/bin/domaincraft; \ echo "Installed to /usr/local/bin/domaincraft"; \ @@ -76,6 +99,7 @@ install: build echo "Installed to $$HOME/.local/bin/domaincraft"; \ echo "Make sure ~/.local/bin is in your PATH"; \ fi +endif run: build @echo "Running domaincraft with example domain.yaml..." @@ -114,9 +138,19 @@ else @echo "Copied schema to $(SKILLS_DIR)/domain.schema.json" endif -test: install-deps +# -count=1: hashing the embedded bridges tree (3454 files) for the test cache +# costs ~25s on Windows, more than the tests themselves (~7s). +test: @echo "Running tests..." - @go test ./... + @go test -count=1 ./... + +# Run only packages affected by uncommitted changes and their dependents. +test-affected: +ifeq ($(OS),Windows_NT) + @echo "test-affected requires Git Bash with bash and python3 on PATH. Install Git Bash, then run 'make test-affected' from a Git Bash shell." +else + @bash scripts/test-impact.sh +endif # Contract tests (Phase 2): golden output + determinism for bundled bridges. contract-test: @@ -126,19 +160,48 @@ contract-test: contract-golden-update: @go test ./internal/contract/ -run TestGoldenLeafBridges -update -test-verbose: install-deps +# Benchmarks have two layers: +# - behavior goldens run in `make test` on small fixtures, so CI gates them; +# - timing runs here. No baseline is committed: a number from one CPU says +# nothing about another. bench.yml runs the same command on base and PR in +# one runner and compares with benchstat. +BENCH_PACKAGES ?= ./internal/renderer ./internal/ir ./internal/snapshot +BENCH_PATTERN ?= RenderWarm|SafeOutputPathWarm|SortEntities|BuildHubRelations +# CI overrides the count for a noisier runner; the command itself stays shared. +BENCH_COUNT ?= 1 +BENCH_CMD = go test -run "^$$" -bench "$(BENCH_PATTERN)" -benchmem -benchtime=1x -count=$(BENCH_COUNT) $(BENCH_PACKAGES) + +bench: + @$(BENCH_CMD) + +# Includes BenchmarkComputeDiff: ~157 s for one full pass. +bench-full: + @go test -run "^$$" -bench . -benchmem -benchtime=1x -count=1 $(BENCH_PACKAGES) + +bench-golden-update: + @go test $(BENCH_PACKAGES) -update + +test-verbose: @echo "Running tests (verbose)..." - @go test -v ./... + @go test -v -count=1 ./... -test-coverage: install-deps +test-coverage: @echo "Running tests with coverage..." - @go test -cover ./... @go test -coverprofile=coverage.out ./... + @go tool cover -func=coverage.out @go tool cover -html=coverage.out -o coverage.html @echo "Coverage report generated: coverage.html" lint: - @echo "Running linter..." + @echo "Running golangci-lint $(GOLANGCI_LINT_VERSION)..." + @go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) run ./... + +vulncheck: + @echo "Running govulncheck $(GOVULNCHECK_VERSION)..." + @go run golang.org/x/vuln/cmd/govulncheck@$(GOVULNCHECK_VERSION) ./... + +vet: + @echo "Running go vet..." @go vet ./... fmt: @@ -146,18 +209,33 @@ fmt: @go fmt ./... clean: +ifeq ($(OS),Windows_NT) + @echo "Cleaning build artifacts..." + @cmd /c "if exist bin rmdir /S /Q bin" + @cmd /c "if exist coverage.out del /Q coverage.out" + @cmd /c "if exist coverage.html del /Q coverage.html" +else @echo "Cleaning build artifacts..." @rm -rf bin/ @rm -f coverage.out coverage.html +endif # Development targets dev-watch: +ifeq ($(OS),Windows_NT) + @echo "dev-watch requires Git Bash + entr. Install both, then run 'make dev-watch' from a Git Bash shell." +else @echo "Watching for changes (requires entr)..." @find . -name "*.go" | entr -r make run +endif dev-test-watch: +ifeq ($(OS),Windows_NT) + @echo "dev-test-watch requires Git Bash + entr. Install both, then run 'make dev-test-watch' from a Git Bash shell." +else @echo "Watching for changes and running tests..." @find . -name "*.go" | entr -r make test-verbose +endif # WASM targets WASM_OUTPUT ?= bin/validate.wasm diff --git a/README.md b/README.md index a707cb3..6b6aed1 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,11 @@ The same model compiles to a typed web client: domaincraft generate --bridge react-rest --output ./frontend ``` -Swap a persistence layer without forking templates: +Swap a persistence layer without forking templates. The bundled Dapper bridge is an experimental stub; pass its local path from the repository root: ```bash -domaincraft generate --bridge csharp-rest --replace persistence=csharp-dapper +domaincraft generate --bridge csharp-rest --replace persistence=bridges/csharp/persistence/dapper-stub +# → core → domain → dapper-stub → rest ``` --- @@ -136,7 +137,7 @@ matrix and query grammar — so the agent builds UI instead of guessing. See | **Features** | `audit` (`createdAt`/`updatedAt`), `audit_log` (`createdBy`/`updatedBy`), `soft_delete` (`deletedAt`), `optimistic_lock` (`version` → `409 Conflict`), `event_sourced`, `cacheable` | | **Permissions** | `read`/`create`/`update`/`delete` with `*` (public), roles (RBAC) and `@Owner` (ABAC) | | **Bridges** | C# (domain → EF Core → REST), TypeScript (core → React), Appwrite, admin panel via `--admin` | -| **Migrations** | `old_name` renames become `RenameTable`/`RenameColumn` (data kept); `--prune` applies schema cleanup and runs bridge migrations best-effort | +| **Migrations** | `old_name` renames produce a core plan; C#/EF Core renders data-preserving `RenameTable`/`RenameColumn`. Other targets get the plan, no bridge artifact yet; `--prune` applies file cleanup and runs bridge migrations best-effort | Full language: [domain.yaml reference](https://fellmonkey.github.io/domaincraft-site/docs/reference/language/) @@ -156,19 +157,19 @@ The **IR** is the contract. It is language-agnostic — the core never contains One bridge = one layer in one axis. All bridges live in this repository (`bridges/`) and are embedded into the binary: ``` -backend (C#): domain (core) → persistence (efcore/dapper) → transport (rest/grpc) -web: core (ts-core) → framework (react/vue) -mobile: core (dart-core) → framework (flutter) → offline (drift) +backend (C#): core → domain → persistence (efcore; dapper-stub experimental) → transport (rest; grpc planned) +web: core (ts-core) → client (ts-client) → framework (react; vue planned) +mobile: core (dart-core) → framework (flutter) → offline (drift) — planned ``` -`extends:` composes a chain; `--replace` swaps one edge without forking: +`extends:` composes a chain; `--replace` swaps one edge without forking. The shipped C# chain is `rest → efcore → domain → core`: -``` ---replace persistence=dapper → core+dapper+rest ---replace transport=grpc → core+efcore+grpc +```bash +# from the repository root; dapper-stub is a local path, not a registry ID +domaincraft generate --bridge csharp-rest --replace persistence=bridges/csharp/persistence/dapper-stub ``` -A new persistence or transport layer is one more bridge in `bridges/` — not a fork of the templates, and not a new repository. +`--replace transport=grpc` and a Vue adapter are planned; no such bridges exist yet. A new persistence or transport layer is one more bridge in `bridges/` — not a fork of the templates, and not a new repository. --- @@ -176,8 +177,10 @@ A new persistence or transport layer is one more bridge in `bridges/` — not a | ID | Layer | Targets | |-----|-------|--------| -| `csharp-core` | `domain` | Domain + Application | -| `csharp-efcore` | `persistence` — `extends: csharp-core` | EF Core + PostgreSQL + `migrations:` | +| `csharp-core` | `core` | C# language core | +| `csharp-domain` | `domain` — `extends: csharp-core` | Domain + Application | +| `csharp-efcore` | `persistence` — `extends: csharp-domain` | EF Core + PostgreSQL + `migrations:` | +| `csharp-dapper-stub` | `persistence` — `extends: csharp-domain` | Experimental stub, local path only | | `csharp-rest` | `transport` — `extends: csharp-efcore` | ASP.NET REST + JWT + k8s/tests | | `csharp-restful` | — | *Archived* monolith — use `csharp-rest` | | `ts-core` | `core` | TypeScript data layer (types, Zod, query DSL, permissions) | @@ -198,19 +201,19 @@ domaincraft bridges --check-updates domaincraft update --check ``` -Flags: `--domain`/`-d`, `--bridge`/`-b`, `--output`/`-o`, `--admin`, `--replace left=right` (repeatable), `--prune`/`--migrate`, `--addons dapr`, `--non-interactive`. See [CLI reference](https://fellmonkey.github.io/domaincraft-site/docs/reference/cli/). +Flags: `--domain`/`-d`, `--bridge`/`-b`, `--output`/`-o`, `--admin`, `--replace left=right` (repeatable), `--prune`/`--migrate`, `--allow-bridge-commands`, `--addons dapr`, `--non-interactive`, `--update-bridges` (refresh cached bridges before generating). Community bridges need explicit consent for shell-declared database migrations: `--migrate` fails without `--allow-bridge-commands`. Command lines are printed before execution. See [CLI reference](https://fellmonkey.github.io/domaincraft-site/docs/reference/cli/). --- ## Migration -The IR and manifest are saved to `.domaincraft/snapshot.json`. On the next run, renames (`old_name: Product`) become `RenameTable`/`RenameColumn` (data kept), deletions prompt, type changes print a report. `--prune` applies cleanup and rewrites identifiers in `overwrite: false` files. See [Migrations](https://fellmonkey.github.io/domaincraft-site/docs/guides/migrations/). +The IR and manifest are saved to `.domaincraft/snapshot.json`. On the next run, renames (`old_name: Product`) produce a core plan; C#/EF Core renders `RenameTable`/`RenameColumn` (data kept). Other targets get the plan, no bridge artifact yet. Deletions prompt, type changes print a report. `--prune` applies cleanup and rewrites identifiers in `overwrite: false` files. See [Migrations](https://fellmonkey.github.io/domaincraft-site/docs/guides/migrations/). --- ## Certification -The compliance suite (`compliance-suite/`) is a hand-written oracle: `kitchen-sink.yaml` (a maximal domain) + `suite.js` (k6 over HTTP). TypeScript ships its own TCK in `ts-core/tck/`. See [Certification](https://fellmonkey.github.io/domaincraft-site/docs/guides/certification/). +The compliance suite (`compliance-suite/`) is a hand-written oracle: `kitchen-sink.yaml` (a maximal domain) + `suite.js` (k6 over HTTP). TypeScript ships TCKs in `ts-core/tck/` and `ts-client/tck/`. CI runs their hermetic halves: `tsc --noEmit` and `vitest run` against locally generated artifacts. It also runs the k6/Docker backend suite and client interop on every scoped PR. Only the dotnet TCK stays manual — it needs a local SDK. See [Certification](https://fellmonkey.github.io/domaincraft-site/docs/guides/certification/). --- diff --git a/bridges/admin/bridge.yaml b/bridges/admin/bridge.yaml index 153dddc..94b01ac 100644 --- a/bridges/admin/bridge.yaml +++ b/bridges/admin/bridge.yaml @@ -1,8 +1,9 @@ name: admin-alpine +contract_version: 2 description: Admin panel with Alpine.js + 0build UIkit for DomainCraft version: "1.1.0" output_dir: admin -helpers: templates/_helpers.html.tmpl +helpers: templates/helpers.html.tmpl templates: - for: project diff --git a/bridges/admin/templates/_helpers.html.tmpl b/bridges/admin/templates/helpers.html.tmpl similarity index 100% rename from bridges/admin/templates/_helpers.html.tmpl rename to bridges/admin/templates/helpers.html.tmpl diff --git a/bridges/appwrite/bridge.yaml b/bridges/appwrite/bridge.yaml index c37d5c2..e98f54c 100644 --- a/bridges/appwrite/bridge.yaml +++ b/bridges/appwrite/bridge.yaml @@ -1,4 +1,5 @@ name: appwrite +contract_version: 2 description: Appwrite bridge for DomainCraft — TablesDB schema + role teams + project settings in one appwrite.config.json, deployed with the Appwrite CLI v26 (itself the migration engine). version: "1.0.0" output_dir: generated diff --git a/bridges/csharp/core/bridge.yaml b/bridges/csharp/core/bridge.yaml index 8ada71e..c7d7309 100644 --- a/bridges/csharp/core/bridge.yaml +++ b/bridges/csharp/core/bridge.yaml @@ -1,8 +1,12 @@ name: csharp-core +contract_version: 2 description: C# language core — enum wire values, entity types, query schema, permission matrix. Certified once per language. version: "1.0.0" layer: core -helpers: templates/_helpers.cs.tmpl +# C#-specific target framework. The core never bakes in a TFM: a bridge that +# resolves NuGet versions must declare the framework its templates generate. +target_framework: net10.0 +helpers: templates/helpers.cs.tmpl templates: - for: entity source: templates/entity.cs.tmpl diff --git a/bridges/csharp/core/tck/QueryContractTests.cs b/bridges/csharp/core/tck/QueryContractTests.cs index f852f9b..b049e98 100644 --- a/bridges/csharp/core/tck/QueryContractTests.cs +++ b/bridges/csharp/core/tck/QueryContractTests.cs @@ -37,7 +37,7 @@ public class QueryContractTests [Fact] public void FilterOperator_vocabulary_is_canonical_and_not_drifted() { - // Generated from IRProject.AllFilterOperators — a hand-maintained + // Generated from Project.AllFilterOperators — a hand-maintained // parallel grammar would fail here. var names = Enum.GetNames(); Assert.Equal( diff --git a/bridges/csharp/core/templates/_helpers.cs.tmpl b/bridges/csharp/core/templates/helpers.cs.tmpl similarity index 95% rename from bridges/csharp/core/templates/_helpers.cs.tmpl rename to bridges/csharp/core/templates/helpers.cs.tmpl index e4e4066..0a25a7b 100644 --- a/bridges/csharp/core/templates/_helpers.cs.tmpl +++ b/bridges/csharp/core/templates/helpers.cs.tmpl @@ -1,7 +1,7 @@ {{- /* Shared named templates for the C# bridge. Loaded via bridge.yaml "helpers" field. */ -}} {{- /* seedValueExpression converts a seed data value to a C# expression. - Context: dict with "Field" (IRField-like) and "Value" (the seed value). + Context: dict with "Field" (Field-like) and "Value" (the seed value). Used by both seed-seeder.cs.tmpl and controller.cs.tmpl Seed action. The literal syntax is loaded from type_mappings.yaml; this template only decides the password-hash special case and the array recursion. */ -}} @@ -41,7 +41,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- /* defaultValueExpression generates a C# default value expression for a field. Uses .DefaultValue from YAML when available, falls back to type-based defaults. - Context: IRField-like dict with .DatabaseType, .DefaultValue, .DefaultIsFunc. */ -}} + Context: Field-like dict with .DatabaseType, .DefaultValue, .DefaultIsFunc. */ -}} {{- define "defaultValueExpression" -}} {{- if .DefaultValue -}}{{ template "defaultValueLiteral" . }} {{- else -}}{{ literalDefault .DatabaseType }} @@ -49,7 +49,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end -}} {{- /* authOrAuthorize emits the auth attribute from the CORE-computed permission plan. - Context: dict with "Plan" (IRPermissionPlan or nil), "Entity", "Op". + Context: dict with "Plan" (PermissionPlan or nil), "Entity", "Op". The plan already decomposes the roles into IsPublic / HasOwner / Roles, so this bridge no longer parses "*" wildcards or "@Owner" tokens. */ -}} {{- define "authOrAuthorize" -}} @@ -70,19 +70,19 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- /* ownerCheck emits the boolean expression that guards an @Owner operation: forbid unless the caller is the owner OR holds at least one explicit role from the plan's Roles (the bypass roles are already extracted by the core). - Context: dict with "Plan" (IRPermissionPlan) and "Var" (the entity expression). */ -}} + Context: dict with "Plan" (PermissionPlan) and "Var" (the entity expression). */ -}} {{- define "ownerCheck" -}} {{- $plan := .Plan -}} {{- $var := .Var -}} {{- if gt (len $plan.Roles) 0 }}!_permissionService.HasAnyRole(new[] { {{- range $i, $r := $plan.Roles }}{{ if $i }}, {{ end }}"{{ $r }}"{{- end }} }) && {{ end }}!_permissionService.IsOwner({{ $var }}){{- end -}} {{- /* validationAttributes emits C# validation attributes from the CORE's normalized - validation rules (IRField.ValidationRules()). The core has already classified + validation rules (Field.ValidationRules()). The core has already classified each rule (required / email / url / ipv4 / regex / min_length / max_length / min_value / max_value) AND assigned a stable Code + default Message, so this bridge only maps each rule to a DataAnnotations attribute — it neither re-derives which modifier is a length vs a numeric bound, nor hardcodes the - message text. Context: IRField. */ -}} + message text. Context: Field. */ -}} {{- define "validationAttributes" -}} {{- $field := . -}} {{- $rules := .ValidationRules -}} @@ -140,7 +140,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end -}} {{- /* dtoFieldProperties emits C# properties for a DTO field (used in Dto, CreateRequest, UpdateRequest). - Context: IRField (or dict with .Name, .IsRelation, .IsMany, .DatabaseType, .IsNullable, .IsHidden, .IsPrimary). */ -}} + Context: Field (or dict with .Name, .IsRelation, .IsMany, .DatabaseType, .IsNullable, .IsHidden, .IsPrimary). */ -}} {{- define "dtoFieldProperties" -}} {{- if .IsRelation -}} {{- if .IsMany }} @@ -160,7 +160,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end -}} {{- /* requestFieldProperties emits C# properties for Create/Update request DTOs with validation attributes. - Context: IRField. */ -}} + Context: Field. */ -}} {{- define "requestFieldProperties" -}} {{- if .IsRelation -}} {{- if not .IsMany }} @@ -175,7 +175,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end -}} {{- /* mapFieldToDto emits a DTO mapping line for one field. - Context: IRField. */ -}} + Context: Field. */ -}} {{- define "mapFieldToDto" -}} {{- if .IsRelation -}} {{- if .IsMany }} @@ -189,7 +189,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end -}} {{- /* mapRequestToEntity emits a request-to-entity mapping line for one field. - Context: IRField. */ -}} + Context: Field. */ -}} {{- define "mapRequestToEntity" -}} {{- if .IsRelation -}} {{- if not .IsMany }} @@ -203,7 +203,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{/* ===== Test helpers: shared by the split tests/*.cs.tmpl templates ===== */}} {{- /* testFieldValue emits a single C# object-initializer line for one field. - Context: IRField. Relations map onto the FK-named entity property. Scalar + Context: Field. Relations map onto the FK-named entity property. Scalar literal syntax (Guid.NewGuid, 1L, 1.0m, DateTime.UtcNow, new List<...>) is loaded from type_mappings.yaml; this template keeps only the test-specific value choices (email/url/name strings, relation FK lookups). */ -}} @@ -275,7 +275,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) required scalar fields, skipping identity/relations/feature fields and the email/password/role fields (set explicitly by CreateDbUserAsync). Used so a Db-context-direct user insert satisfies every NOT NULL column the auth entity - declares. Context: the auth IREntity. */ -}} + declares. Context: the auth Entity. */ -}} {{- define "testAuthEntityFields" }} {{- range .Fields }} {{- $n := .Name | lower }} @@ -313,7 +313,7 @@ _passwordHasher.HashPassword({{ literalValue $dbType $value }}) {{- end }} {{- /* testRequestBody builds a CLR entity object-initializer (relations → FK entity - property). Context: IRField. */ -}} + property). Context: Field. */ -}} {{- define "testRequestBody" }} {{- range .Fields }} {{- if and (not .IsPrimary) (not .IsMany) }} diff --git a/bridges/csharp/core/templates/query.cs.tmpl b/bridges/csharp/core/templates/query.cs.tmpl index 6a6cf93..3494d7a 100644 --- a/bridges/csharp/core/templates/query.cs.tmpl +++ b/bridges/csharp/core/templates/query.cs.tmpl @@ -19,7 +19,7 @@ namespace {{ .Project.Name | pascalcase }}.Application.Query; /// /// A comparison operator in the DomainCraft filter grammar (spec/query.md). /// The member list is generated from the core's canonical operator vocabulary -/// (IRProject.AllFilterOperators), so this bridge never hand-maintains a parallel +/// (Project.AllFilterOperators), so this bridge never hand-maintains a parallel /// grammar that can drift out of sync. /// public enum FilterOperator @@ -428,7 +428,7 @@ public static class SortApplier } /// -/// The normalized list-query contract (the runtime mirror of the core's IRQuery): +/// The normalized list-query contract (the runtime mirror of the core's Query contract): /// the raw search/filter/sort strings plus clamped pagination. The repository /// resolves the strings against the entity's filterable/sortable schema. /// @@ -473,7 +473,7 @@ public sealed class ListQuery /// /// Normalizes transport parameters into a ListQuery: `limit` wins over /// `pageSize`, the default fills in, and page/pageSize are clamped (the - /// runtime mirror of IRPaginationConfig.NormalizePage/EffectivePageSize). + /// runtime mirror of PaginationConfig.NormalizePage/EffectivePageSize). /// public static ListQuery FromQuery(int page, int? pageSize, int? limit, string? sort, string? search, string? filter, string? cursor, string? include, int defaultPageSize, int maxPageSize) { diff --git a/bridges/csharp/domain/bridge.yaml b/bridges/csharp/domain/bridge.yaml index 9c829fe..eba1866 100644 --- a/bridges/csharp/domain/bridge.yaml +++ b/bridges/csharp/domain/bridge.yaml @@ -1,4 +1,5 @@ name: csharp-domain +contract_version: 2 description: Domain + Application layer for C# — services, Generation Gap, ports. Extends language core. version: "1.0.0" layer: domain diff --git a/bridges/csharp/domain/templates/irepository.cs.tmpl b/bridges/csharp/domain/templates/irepository.cs.tmpl index 5715c8b..4f00f8a 100644 --- a/bridges/csharp/domain/templates/irepository.cs.tmpl +++ b/bridges/csharp/domain/templates/irepository.cs.tmpl @@ -19,7 +19,7 @@ public interface I{{ .Entity.Name }}Repository : IRepository<{{ .Entity.Name }}> /// /// Get a page of {{ .Entity.NamePlural | lowercase }} per the normalized /// : search/filter/sort strings plus clamped - /// pagination — the runtime mirror of the core's IRQuery (spec/query.md). + /// pagination — the runtime mirror of the core's Query contract (spec/query.md). /// Task> GetPagedAsync(ListQuery query, CancellationToken cancellationToken = default); } diff --git a/bridges/csharp/persistence/dapper-stub/README.md b/bridges/csharp/persistence/dapper-stub/README.md index 4b00489..0a24883 100644 --- a/bridges/csharp/persistence/dapper-stub/README.md +++ b/bridges/csharp/persistence/dapper-stub/README.md @@ -1,19 +1,19 @@ -# DomainCraft C# Persistence (Dapper) — `csharp-dapper` +# DomainCraft C# Persistence (Dapper) — `csharp-dapper-stub` -> **Stub.** This is a placeholder for a Dapper-based persistence layer that will replace `csharp-efcore` via `--replace persistence=csharp-dapper`. It is not production-ready — it exists so the `--replace` contract has a second persistence to compose against. +> **Stub.** A placeholder for a Dapper-based persistence layer. It lets the `--replace` contract compose a second persistence from the repository root. Not production-ready — templates are a skeleton, not a full Dapper repository. ## Status -- `extends: csharp-core` (not `csharp-domain` — Dapper may choose to reuse the domain layer or ship its own ports) +- `extends: csharp-domain` (as declared in `bridge.yaml`; the stub reuses the domain layer) - `layer: persistence` -- Templates: skeleton, not a full Dapper repository implementation +- Not in `internal/bridge/registry.go` — pass its local path, not an ID -## How it will compose +## How it composes ```bash -# when ready: -domaincraft generate --bridge csharp-rest --replace persistence=csharp-dapper -# → core + domain + dapper + rest +# from the repository root +domaincraft generate --bridge csharp-rest --replace persistence=bridges/csharp/persistence/dapper-stub +# → core → domain → dapper-stub → rest ``` See [Axes and layers](https://fellmonkey.github.io/domaincraft-site/docs/concepts/three-axes/) for how `--replace` swaps one edge of the chain. diff --git a/bridges/csharp/persistence/dapper-stub/bridge.yaml b/bridges/csharp/persistence/dapper-stub/bridge.yaml index ada4d4e..f159e26 100644 --- a/bridges/csharp/persistence/dapper-stub/bridge.yaml +++ b/bridges/csharp/persistence/dapper-stub/bridge.yaml @@ -1,4 +1,5 @@ name: csharp-dapper-stub +contract_version: 2 description: Stub Dapper persistence (proof of replace) version: "0.1.0" layer: persistence diff --git a/bridges/csharp/persistence/dapper-stub/templates/_helpers.cs.tmpl b/bridges/csharp/persistence/dapper-stub/templates/helpers.cs.tmpl similarity index 100% rename from bridges/csharp/persistence/dapper-stub/templates/_helpers.cs.tmpl rename to bridges/csharp/persistence/dapper-stub/templates/helpers.cs.tmpl diff --git a/bridges/csharp/persistence/efcore/bridge.yaml b/bridges/csharp/persistence/efcore/bridge.yaml index 3a89fc9..a97d7b8 100644 --- a/bridges/csharp/persistence/efcore/bridge.yaml +++ b/bridges/csharp/persistence/efcore/bridge.yaml @@ -1,4 +1,5 @@ name: csharp-efcore +contract_version: 2 description: EF Core persistence layer for DomainCraft C#. version: "1.0.0" layer: persistence diff --git a/bridges/csharp/persistence/efcore/templates/seed-seeder.cs.tmpl b/bridges/csharp/persistence/efcore/templates/seed-seeder.cs.tmpl index 0b35c48..6b8418f 100644 --- a/bridges/csharp/persistence/efcore/templates/seed-seeder.cs.tmpl +++ b/bridges/csharp/persistence/efcore/templates/seed-seeder.cs.tmpl @@ -25,7 +25,7 @@ namespace {{ .Project.Name | pascalcase }}.Infrastructure.Persistence.Seeders; /// The CORE normalizes the developer's explicit `seed:` rows into typed /// SeedRecord/SeedValue records (types, relations and constraints already /// resolved), so this bridge only serializes them into C# object initializers. -/// seedValueExpression is defined in _helpers.cs.tmpl (loaded via bridge.yaml helpers). +/// seedValueExpression is defined in helpers.cs.tmpl (loaded via bridge.yaml helpers). /// Password-typed seed fields are hashed through IPasswordHasher so a plaintext value in /// domain.yaml never lands in the database; pre-hashed (bcrypt, "$2...") values pass through. /// diff --git a/bridges/csharp/transport/rest/bridge.yaml b/bridges/csharp/transport/rest/bridge.yaml index b296b0a..95a7e17 100644 --- a/bridges/csharp/transport/rest/bridge.yaml +++ b/bridges/csharp/transport/rest/bridge.yaml @@ -1,4 +1,5 @@ name: csharp-rest +contract_version: 2 description: ASP.NET Core REST transport for DomainCraft C#. version: "1.0.0" layer: transport diff --git a/bridges/csharp/transport/rest/templates/api-app-extensions.cs.tmpl b/bridges/csharp/transport/rest/templates/api-app-extensions.cs.tmpl index 57b97e3..499db68 100644 --- a/bridges/csharp/transport/rest/templates/api-app-extensions.cs.tmpl +++ b/bridges/csharp/transport/rest/templates/api-app-extensions.cs.tmpl @@ -72,7 +72,7 @@ public static class ApplicationBuilderExtensions app.UseOutputCache(); - // Unique-constraint names are core-owned (IRIndex.DatabaseName()). Build a + // Unique-constraint names are core-owned (Index.DatabaseName()). Build a // map from the PostgreSQL constraint name to the field that must be unique, // so a unique violation is reported as a stable, field-specific 409 instead // of a bare 500 (see spec/errors.md → UNIQUE_CONFLICT). diff --git a/bridges/csharp/transport/rest/templates/auth-controller.cs.tmpl b/bridges/csharp/transport/rest/templates/auth-controller.cs.tmpl index 92d1924..8370c45 100644 --- a/bridges/csharp/transport/rest/templates/auth-controller.cs.tmpl +++ b/bridges/csharp/transport/rest/templates/auth-controller.cs.tmpl @@ -51,7 +51,7 @@ public class {{ $authType }}Controller : ControllerBase _configuration = configuration; } -{{- /* The auth endpoint contract (IRProject.AuthEndpoints) is the single source of +{{- /* The auth endpoint contract (Project.AuthEndpoints) is the single source of truth for which endpoints exist, their HTTP method and anonymity. Only the C#-specific bodies live here. */ -}} {{- range .Project.AuthEndpoints }} diff --git a/bridges/csharp/transport/rest/templates/controller.cs.tmpl b/bridges/csharp/transport/rest/templates/controller.cs.tmpl index 103589c..c7122f5 100644 --- a/bridges/csharp/transport/rest/templates/controller.cs.tmpl +++ b/bridges/csharp/transport/rest/templates/controller.cs.tmpl @@ -63,7 +63,7 @@ public class {{ pluralize $entity }}Controller : ControllerBase {{- end }} } -{{- /* The endpoint contract (IREntity.Endpoints) is the single source of truth for +{{- /* The endpoint contract (Entity.Endpoints) is the single source of truth for method, operation, authorization plan and concurrency. Only the C#-specific bodies and response-type annotations live here. */ -}} {{- range .Endpoints }} diff --git a/bridges/typescript/client/bridge.yaml b/bridges/typescript/client/bridge.yaml index 94f48f5..45014d9 100644 --- a/bridges/typescript/client/bridge.yaml +++ b/bridges/typescript/client/bridge.yaml @@ -1,4 +1,5 @@ name: ts-client +contract_version: 2 description: TypeScript client — Zod validation, JWT client and CRUD API. Extends language core. version: "1.0.0" layer: client diff --git a/bridges/typescript/client/tck/interop.test.ts b/bridges/typescript/client/tck/interop.test.ts index 9dd9cb5..69ba792 100644 --- a/bridges/typescript/client/tck/interop.test.ts +++ b/bridges/typescript/client/tck/interop.test.ts @@ -48,13 +48,17 @@ describe.skipIf(!ENABLED)("interop: ts-client ↔ certified backend", () => { let adminId = ""; let adminToken = ""; + // 10 attempts * (2s fetch timeout + 1s pause) fit in the hook budget. + // The bound also stops a 429 + long Retry-After from hanging the suite. beforeAll(async () => { // Wait briefly for the backend to become healthy (CI may start it in the // same step; a standalone run points at an already-running compose). let ready = false; - for (let i = 0; i < 30 && !ready; i++) { + for (let i = 0; i < 10 && !ready; i++) { try { - const res = await fetch(`${API_URL}/health/ready`); + const res = await fetch(`${API_URL}/health/ready`, { + signal: AbortSignal.timeout(2000), + }); ready = res.ok; } catch { // backend not listening yet @@ -87,7 +91,7 @@ describe.skipIf(!ENABLED)("interop: ts-client ↔ certified backend", () => { const me = await api("api/user/me"); adminId = me.id; - }); + }, 60_000); afterAll(() => { setToken(null); diff --git a/bridges/typescript/client/templates/api.ts.tmpl b/bridges/typescript/client/templates/api.ts.tmpl index 55ea421..266ede5 100644 --- a/bridges/typescript/client/templates/api.ts.tmpl +++ b/bridges/typescript/client/templates/api.ts.tmpl @@ -6,13 +6,13 @@ import type { ListResult } from "./types"; import type { {{ $e.Name }}Create, {{ $e.Name }}Update, {{ $e.Name }}Patch } from "./schemas"; import type { {{ $e.Name }}Query, {{ $e.Name }}Include } from "./query"; {{ end }} -/** Substitutes `{id}` in an endpoint path template (the core's IREndpoint.Path). */ +/** Substitutes `{id}` in an endpoint path template (the core's Endpoint.Path). */ function fillPath(template: string, id: string | number): string { return template.replace("{id}", encodeURIComponent(String(id))); } {{ range $e := .Project.Entities }} -// Endpoint routes come from the core's endpoint contract (IREntity.Endpoints) — +// Endpoint routes come from the core's endpoint contract (Entity.Endpoints) — // method paths, not hand-written strings. export const {{ camelcase $e.NamePlural }}Routes = { {{- range $ep := $e.Endpoints }} diff --git a/bridges/typescript/core/bridge.yaml b/bridges/typescript/core/bridge.yaml index a8114b6..5613670 100644 --- a/bridges/typescript/core/bridge.yaml +++ b/bridges/typescript/core/bridge.yaml @@ -1,8 +1,9 @@ name: ts-core +contract_version: 2 description: TypeScript language core — enum wire values, entity types, query schema, permission matrix. Certified once per language. version: "1.0.0" layer: core -helpers: templates/_helpers.ts.tmpl +helpers: templates/helpers.ts.tmpl templates: - for: project source: templates/types.ts.tmpl diff --git a/bridges/typescript/core/templates/_helpers.ts.tmpl b/bridges/typescript/core/templates/helpers.ts.tmpl similarity index 94% rename from bridges/typescript/core/templates/_helpers.ts.tmpl rename to bridges/typescript/core/templates/helpers.ts.tmpl index ad0733b..02e71ba 100644 --- a/bridges/typescript/core/templates/_helpers.ts.tmpl +++ b/bridges/typescript/core/templates/helpers.ts.tmpl @@ -10,7 +10,7 @@ {{ end }} {{- /* readFieldLine: one member of the read-DTO interface for a field. - Context: IRField. A to-many relation becomes `Target[]`, a to-one relation + Context: Field. A to-many relation becomes `Target[]`, a to-one relation and a scalar become the FK id / scalar value (nullable -> `| null`). */ -}} {{ define "readFieldLine" -}} {{- $f := . -}} @@ -39,7 +39,7 @@ {{- end -}} {{- /* zodField: the full Zod schema (base + validations) for a field. - Context: dict "Field" (IRField), "Project". Validations come from the SAME + Context: dict "Field" (Field), "Project". Validations come from the SAME source as the server's rules, so client and server can never drift. */ -}} {{ define "zodField" -}} {{- $f := .Field -}} @@ -58,7 +58,7 @@ {{- end -}} {{- /* conditionType: the typed filter condition a field's type maps to. - Context: dict "Field" (IRField). */ -}} + Context: dict "Field" (Field). */ -}} {{ define "conditionType" -}} {{- $f := .Field -}} {{- if $f.IsText }}TextCondition diff --git a/bridges/typescript/core/templates/query.ts.tmpl b/bridges/typescript/core/templates/query.ts.tmpl index a715331..e95cf77 100644 --- a/bridges/typescript/core/templates/query.ts.tmpl +++ b/bridges/typescript/core/templates/query.ts.tmpl @@ -3,7 +3,7 @@ // Typed query DSL compiled from the core's filter grammar (spec/query.md). // The operator vocabulary below is ITERATED from the core -// (`IRProject.AllFilterOperators`) so adding an operator to the grammar +// (`Project.AllFilterOperators`) so adding an operator to the grammar // updates this client on the next generate instead of drifting. // // The `filter` object's keys are restricted to the entity's filterable surface @@ -159,7 +159,7 @@ export type {{ $e.Name }}Include = {{ join " | " $incKeys }}; export type {{ $e.Name }}Include = never; {{- end }} -{{- /* Searchable surface (fix: surfaced from IRProject.SearchableFields) — +{{- /* Searchable surface (fix: surfaced from Project.SearchableFields) — lets a UI show "searches over title, description" without guessing. */ -}} {{- $searchKeys := list -}} {{- range $f := $e.SearchableFields -}}{{- $searchKeys = append $searchKeys (printf "%q" (camelcase $f.Name)) -}}{{- end }} diff --git a/bridges/typescript/core/templates/types.ts.tmpl b/bridges/typescript/core/templates/types.ts.tmpl index 7ba0fec..61c19fc 100644 --- a/bridges/typescript/core/templates/types.ts.tmpl +++ b/bridges/typescript/core/templates/types.ts.tmpl @@ -56,7 +56,7 @@ export type {{ $e.Name }} = {{ $e.Name }}Detail; {{ end }} {{ if .Project.HasAuth }} -// Auth contract (IRProject.AuthEndpoints) — only enabled endpoints get types. +// Auth contract (Project.AuthEndpoints) — only enabled endpoints get types. {{ if .Project.Auth.Endpoints.HasLogin }} export interface LoginRequest { email: string; diff --git a/bridges/typescript/core/type_mappings.yaml b/bridges/typescript/core/type_mappings.yaml index 144376a..a33d686 100644 --- a/bridges/typescript/core/type_mappings.yaml +++ b/bridges/typescript/core/type_mappings.yaml @@ -27,5 +27,9 @@ types: "array(json)": "unknown[]" "array(jsonb)": "unknown[]" +# Array types not in `types` above (enum arrays, future primitives) use this +# bridge-owned format. The core never substitutes a language default. +array_format: "%s[]" + # Nullability is handled in the templates (response -> `| null`, request -> `?`), # so no nullable_format / enum_nullable wrapping is applied. diff --git a/bridges/typescript/react/bridge.yaml b/bridges/typescript/react/bridge.yaml index c4bad2a..837b064 100644 --- a/bridges/typescript/react/bridge.yaml +++ b/bridges/typescript/react/bridge.yaml @@ -1,4 +1,5 @@ name: react-rest +contract_version: 2 description: React + TypeScript client for DomainCraft — a thin adapter over the ts-client data layer, adding TanStack Query hooks, JWT auth hooks and a role-based useCan guard. version: "1.0.0" layer: framework diff --git a/bridges/typescript/react/templates/auth.ts.tmpl b/bridges/typescript/react/templates/auth.ts.tmpl index 2429d81..821bdfa 100644 --- a/bridges/typescript/react/templates/auth.ts.tmpl +++ b/bridges/typescript/react/templates/auth.ts.tmpl @@ -8,7 +8,7 @@ import { can, type EntityName, type PermissionOp } from "./permissions"; import type { {{ if $auth.Endpoints.HasLogin }}AuthResponse, LoginRequest, {{ end }}{{ if or $auth.Endpoints.HasRegister $auth.Endpoints.HasSetup }}RegisterRequest, {{ end }}{{ $auth.Entity }} } from "./types"; // Auth endpoint paths come from the core's endpoint contract -// (IRProject.AuthEndpoints) — only endpoints enabled in domain.yaml exist here. +// (Project.AuthEndpoints) — only endpoints enabled in domain.yaml exist here. const AUTH_ROUTES = { {{- range .Project.AuthEndpoints }} {{ .Operation }}: {{ jsonValue .Path }}, diff --git a/bridges_embed.go b/bridges_embed.go index e6dfad8..4fb53dd 100644 --- a/bridges_embed.go +++ b/bridges_embed.go @@ -7,9 +7,15 @@ import "embed" // Bridges is the embedded copy of the monorepo `bridges/` tree. The loader uses // it as the fallback before cloning from a remote (local path → embedded → -// remote → cache). It is regenerated by the release job and verified against the -// on-disk tree by the bundled-bridges test so the shipped binary can never -// silently diverge from what the repository contains. +// remote → cache). +// +// `go:embed bridges` compiles the tree into the binary at build time. A release +// needs no regeneration step: checkout at the tag plus `go build` embeds exactly +// that commit's templates. +// +// Helper templates are named helpers.*.tmpl (no "_" prefix), so a single +// directory directive embeds them along with every other bridge file. +// TestEmbeddedBridgesMatchTree compares this set with the source tree. // //go:embed bridges var Bridges embed.FS diff --git a/cmd/domaincraft/bridge_chain.go b/cmd/domaincraft/bridge_chain.go new file mode 100644 index 0000000..1ee8bfd --- /dev/null +++ b/cmd/domaincraft/bridge_chain.go @@ -0,0 +1,306 @@ +package main + +import ( + "cmp" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/bridgechain" + "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/interactive" + "github.com/DomainCraft/DomainCraft/pkg/logger" + + "github.com/spf13/cobra" +) + +type commandContext struct { + opts *cliOptions + cmd *cobra.Command + log *logger.Logger + chainHasCommunity bool + cleanupApplied bool + migrationsPlanned bool +} + +// newBridgeResolver builds a resolver with the CLI's bridge cache/update options. +func newBridgeResolver(opts *cliOptions, log *logger.Logger) *bridge.Resolver { + return bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(opts, log)) +} + +// resolveBridgeInteractive resolves the bridge from the --bridge flag, or +// prompts the user interactively. Returns (path, displayName, error). +func resolveBridgeInteractive(opts *cliOptions, log *logger.Logger) (string, string, error) { + resolver := newBridgeResolver(opts, log) + + if opts.bridgePath != "" { + // Monorepo-first, through the same step `extends` uses. + if wd, err := os.Getwd(); err == nil { + if p := bridge.ResolveOfficialLocal(opts.bridgePath, wd); p != "" { + return p, "", nil + } + } + resolved, err := resolver.Resolve(opts.bridgePath) + return resolved, "", usageOnInvalidBridgeRef(err) + } + + if opts.nonInteractive || !isTerminal() { + return "", "", asUsageError(fmt.Errorf("--bridge is required in non-interactive mode")) + } + + entry, err := interactive.SelectBridge(bridge.Default()) + if err != nil { + return "", "", err + } + + resolved, err := resolver.Resolve(entry.ID) + if err != nil { + return "", "", fmt.Errorf("resolve bridge %q: %w", entry.ID, err) + } + + return resolved, entry.Name, nil +} + +// resolveBaseChain resolves an adapter bridge's `extends` chain to local bridge +// paths, ordered outermost base first (so the deepest base renders first). Each +// base is resolved the same way --bridge is: a path, registry ID or owner/repo. +func resolveBaseChain(opts *cliOptions, adapterDir, baseRef string, log *logger.Logger) ([]string, error) { + chain, err := bridgechain.Walk(baseRef, adapterDir, newBridgeResolver(opts, log), log) + if err != nil { + return nil, err + } + // The walker returns the deepest chain top-first; bases must render with + // the outermost base first, so reverse it. + slices.Reverse(chain) + return chain, nil +} + +// replaceEntry is one --replace flag: left (= layer or bridge name) -> right (bridge ref). +type replaceEntry struct { + left string + right string +} + +func parseReplaceFlags(raw []string) ([]replaceEntry, error) { + var out []replaceEntry + for _, s := range raw { + parts := strings.SplitN(s, "=", 2) + if len(parts) != 2 || strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" { + return nil, fmt.Errorf("invalid --replace %q: expected layer|bridgeId=bridgeRef", s) + } + out = append(out, replaceEntry{left: strings.TrimSpace(parts[0]), right: strings.TrimSpace(parts[1])}) + } + return out, nil +} + +// resolveChainWithReplacements resolves the extends chain with --replace overrides. +// It returns the (possibly replaced) entry dir and base paths outermost-first. +func resolveChainWithReplacements(opts *cliOptions, entryDir string, reps []replaceEntry, log *logger.Logger) (string, []string, error) { + // One read per directory. A chain with N --replace flags used to parse + // every manifest N+1 times through renderer.New and a second YAML reader. + metaCache := make(map[string]bridge.Manifest) + metaFor := func(dir string) (bridge.Manifest, error) { + if m, ok := metaCache[dir]; ok { + return m, nil + } + m, err := bridge.LoadManifest(dir) + if err != nil { + return bridge.Manifest{}, err + } + metaCache[dir] = m + return m, nil + } + if len(reps) == 0 { + m, err := metaFor(entryDir) + if err != nil { + return "", nil, err + } + bases, err := resolveBaseChain(opts, entryDir, m.Extends, log) + return entryDir, bases, err + } + resolver := newBridgeResolver(opts, log) + fullChain, err := bridgechain.Walk(entryDir, entryDir, resolver, log) + if err != nil { + return "", nil, err + } + for _, rep := range reps { + // Find target index by layer or name. + targetIdx := -1 + var targetLayer string + for i, dir := range fullChain { + m, err := metaFor(dir) + if err != nil { + return "", nil, err + } + if m.Layer == rep.left || m.Name == rep.left { + targetIdx = i + targetLayer = m.Layer + break + } + } + if targetIdx == -1 { + return "", nil, asUsageError(fmt.Errorf("no bridge with layer or name %q in chain %v", rep.left, fullChain)) + } + // Resolve replacement bridge. + rightPath, err := bridge.ResolveExtendsRef(rep.right, entryDir, resolver) + if err != nil { + return "", nil, asUsageError(fmt.Errorf("resolve --replace %s=%s: %w", rep.left, rep.right, err)) + } + if abs, err := filepath.Abs(rightPath); err == nil { + rightPath = abs + } + rightMeta, err := metaFor(rightPath) + if err != nil { + return "", nil, err + } + // Warn on layer mismatch (both non-empty and different). + if targetLayer != "" && rightMeta.Layer != "" && targetLayer != rightMeta.Layer && log != nil { + log.Warn("layer mismatch: replacing %q (layer=%q) with %q (layer=%q)", rep.left, targetLayer, rightMeta.Name, rightMeta.Layer) + } + // Build replacement's full chain top-first. + rightChain, err := bridgechain.Walk(rightPath, rightPath, resolver, log) + if err != nil { + return "", nil, err + } + // Splice: fullChain[:targetIdx] + rightChain (replaces tail after targetIdx) + newChain := make([]string, 0, len(fullChain[:targetIdx])+len(rightChain)) + newChain = append(newChain, fullChain[:targetIdx]...) + newChain = append(newChain, rightChain...) + // Validate no duplicate layer and no cycle. + seenLayer := make(map[string]string) + seenPaths := make(map[string]bool, len(newChain)) + for _, d := range newChain { + abs, err := filepath.Abs(d) + if err != nil { + return "", nil, fmt.Errorf("resolve absolute bridge path %q: %w", d, err) + } + key := bridge.PathKey(abs) + if seenPaths[key] { + return "", nil, asUsageError(fmt.Errorf("bridge `extends` cycle detected at %q", d)) + } + seenPaths[key] = true + m, err := metaFor(d) + if err != nil { + return "", nil, fmt.Errorf("read layer of %s: %w", d, err) + } + if m.Layer != "" { + if prev, ok := seenLayer[m.Layer]; ok { + return "", nil, asUsageError(fmt.Errorf("duplicate layer %q: %q and %q", m.Layer, prev, d)) + } + seenLayer[m.Layer] = d + } + } + fullChain = newChain + } + newEntry := fullChain[0] + tail := fullChain[1:] + slices.Reverse(tail) + return newEntry, tail, nil +} + +// --- domaincraft.lock.json (Phase 0.4) --- +// +// The lock records the exact bridge chain that rendered a project, next to the +// domain.yaml (not inside the output dir, not in the snapshot). It holds no +// timestamps, so it is diff-friendly and reproducible. It answers "which +// bridges rendered this project" — the snapshot answers "what did the model +// look like". + +// lockBridge is one entry in domaincraft.lock.json. +type lockBridge struct { + ID string `json:"id"` + Path string `json:"path,omitempty"` // monorepo path under bridges/ when resolved locally from the monorepo + Source string `json:"source,omitempty"` // GitHub owner/repo when resolved from the registry/cache + Version string `json:"version,omitempty"` + ContractVersion int `json:"contract_version"` +} + +// domainLock is the on-disk shape of domaincraft.lock.json. +type domainLock struct { + Bridges []lockBridge `json:"bridges"` +} + +// writeDomainLock records the resolved bridge chain (top-first: entry, then its +// bases) next to domainPath. It is best-effort: a failure to write the lock +// must never break generation. +func writeDomainLock(domainPath string, dirs []string) error { + reg := bridge.Default() + var out []lockBridge + seen := make(map[string]bool) + for _, dir := range dirs { + id, version, contractVersion, err := bridgeMetadata(dir) + if err != nil { + return err + } + if id == "" || seen[id] { + continue + } + seen[id] = true + b := lockBridge{ID: id, Version: version, ContractVersion: contractVersion} + if entry := reg.ByID(id); entry != nil { + if p := bridge.MonorepoRelPath(dir, entry.Path); p != "" { + b.Path = p + } else if entry.GitHub != "" { + b.Source = entry.GitHub + } + } + out = append(out, b) + } + slices.SortFunc(out, func(a, b lockBridge) int { return cmp.Compare(a.ID, b.ID) }) + + return fsutil.WriteJSON(filepath.Join(filepath.Dir(domainPath), "domaincraft.lock.json"), domainLock{Bridges: out}) +} + +// bridgeMetadata is the lock-file view of the shared manifest reader. +func bridgeMetadata(dir string) (string, string, int, error) { + m, err := bridge.LoadManifest(dir) + if err != nil { + return "", "", 0, err + } + return m.Name, m.Version, m.ContractVersion, nil +} + +// bridgeEnsureOptions builds the bridge caching/update policy from the CLI +// flags and terminal state: +// - --update-bridges consents to downloading newer versions (CI-safe); +// - otherwise, an interactive terminal is prompted when an update is found; +// - in non-interactive mode the cached copy is kept and a warning is logged. +func bridgeEnsureOptions(cli *cliOptions, log *logger.Logger) *bridge.EnsureOptions { + opts := &bridge.EnsureOptions{ + Force: cli.updateBridges, + Warn: log.Warn, + } + + switch { + case cli.updateBridges: + // The flag itself is the consent — update without prompting. + opts.ConfirmUpdate = func(entry bridge.RegistryEntry, u *bridge.Update) (bool, error) { + log.Info("%s", bridgeUpdateNotice(entry.ID, u)) + return true, nil + } + case !cli.nonInteractive && isTerminal(): + opts.ConfirmUpdate = interactive.PromptBridgeUpdate + default: + // Non-interactive (even on a TTY) without the flag: keep the cached + // copy; the bridge package logs a warning pointing at --update-bridges. + opts.ConfirmUpdate = nil + } + return opts +} + +// bridgeUpdateNotice renders the log line for a bridge update. It deliberately +// omits version numbers: bridge.Update only carries the cached (old) version, +// which must not be presented as the available release. +func bridgeUpdateNotice(entryID string, _ *bridge.Update) string { + return fmt.Sprintf("Updating bridge %s (cached copy is outdated)", entryID) +} + +// runBridgeDatabaseMigrations applies the bridge's declared schema commands. +// They run with --migrate, or automatically under --prune when the diff has +// changes that must reach the database. Community bridges never auto-run them; +// explicit --migrate still needs --allow-bridge-commands consent. A failure is +// hard with --migrate and best-effort under --prune (the container can apply +// pending migrations at startup). diff --git a/cmd/domaincraft/cli_helpers.go b/cmd/domaincraft/cli_helpers.go new file mode 100644 index 0000000..ea1fea1 --- /dev/null +++ b/cmd/domaincraft/cli_helpers.go @@ -0,0 +1,65 @@ +package main + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/specmeta" + "github.com/DomainCraft/DomainCraft/internal/validator" + "github.com/DomainCraft/DomainCraft/pkg/logger" + + "github.com/spf13/cobra" +) + +func applyAddons(opts *cliOptions, project *ir.Project, log *logger.Logger) { + if strings.TrimSpace(opts.addons) == "" { + return + } + if project.Addons == nil { + project.Addons = make(map[string]bool) + } + for addon := range strings.SplitSeq(opts.addons, ",") { + addon = strings.TrimSpace(addon) + if addon == "" { + continue + } + if specmeta.IsAddon(addon) { + project.Addons[addon] = true + continue + } + log.Warn("unknown addon %q ignored; valid addons: %s", addon, strings.Join(specmeta.Addons, ", ")) + } +} + +// loadAndValidate reports warnings on the command's error stream and returns +// hard validation errors as one aggregated error. The caller prints that error +// once; printing each error here as well would duplicate every line. +func loadAndValidate(opts *cliOptions, cmd *cobra.Command) (*parser.ParsedSchema, error) { + data, err := os.ReadFile(opts.domainFile) + if err != nil { + return nil, fmt.Errorf("read domain file: %w", err) + } + schema, err := parser.ParseYAML(data) + if err != nil { + return nil, err + } + + log := commandLogger(cmd) + hardErrors := make([]error, 0) + for _, e := range validator.New(schema).Validate() { + if e.Warning { + log.Warn("%s", e.Error()) + continue + } + hardErrors = append(hardErrors, e) + } + if len(hardErrors) > 0 { + return nil, fmt.Errorf("validation failed with %d error(s): %w", len(hardErrors), errors.Join(hardErrors...)) + } + + return schema, nil +} diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index 5d27d7e..1506d25 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -1,11 +1,12 @@ // Command domaincraft compiles domain.yaml into code through pluggable bridges. // // Commands: -// init — write a starter domain.yaml from a scenario, then generate -// generate — parse and validate the model, build IR, render code via a bridge -// validate — validate domain.yaml without generating -// bridges — list known bridges with cache and update status -// update — update the core to the latest GitHub release +// +// init — write a starter domain.yaml from a scenario, then generate +// generate — parse and validate the model, build IR, render code via a bridge +// validate — validate domain.yaml without generating +// bridges — list known bridges with cache and update status +// update — update the core to the latest GitHub release // // Global flags: --domain/-d, --bridge/-b, --output/-o, --non-interactive, // --addons, --update-bridges, --version. Command flags live with their @@ -13,47 +14,66 @@ package main import ( - "cmp" - "encoding/json" + "errors" "fmt" "io" - "os" "os/exec" - "path/filepath" "regexp" - "runtime" "runtime/debug" - "slices" "strings" + "time" "github.com/DomainCraft/DomainCraft/internal/bridge" - "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/interactive" "github.com/DomainCraft/DomainCraft/internal/ir" - "github.com/DomainCraft/DomainCraft/internal/parser" - "github.com/DomainCraft/DomainCraft/internal/renderer" "github.com/DomainCraft/DomainCraft/internal/seed" "github.com/DomainCraft/DomainCraft/internal/snapshot" - "github.com/DomainCraft/DomainCraft/internal/specmeta" - "github.com/DomainCraft/DomainCraft/internal/validator" "github.com/DomainCraft/DomainCraft/pkg/logger" "github.com/spf13/cobra" - "gopkg.in/yaml.v3" ) +const ( + defaultDomainFile = "domain.yaml" + defaultOutputDir = "generated" + + // databaseMigrationTimeout bounds one batch of bridge-declared database + // migration commands. The signal context from main stays the parent, so an + // interrupt still cancels a child immediately; this only stops a hung + // command from blocking a generation run forever. + databaseMigrationTimeout = 10 * time.Minute +) + +// cliOptions holds the flag values of one command tree. A fresh instance is +// created by every newRootCommand call, so two live trees never clobber each +// other's flags. +type cliOptions struct { + domainFile string + bridgePath string + outputDir string + nonInteractive bool + adminBridge string // --admin [bridge-id]; empty = not requested + prune bool // --prune: apply migration cleanup without prompting + addons string // --addons "dapr,pulsar": comma-separated infrastructure accelerators + migrate bool // --migrate: run the bridge's database-migration commands after generation + updateBridges bool // --update-bridges: download newer bridge versions before generating + checkUpdates bool // bridges --check-updates: contact remotes and report outdated cached bridges + allowBridgeCommands bool // explicit consent to run shell lines declared by community bridges + replaceFlags []string +} + +func newCLIOptions() *cliOptions { + return &cliOptions{domainFile: defaultDomainFile, outputDir: defaultOutputDir} +} + var ( - domainFile string - bridgePath string - outputDir string - nonInteractive bool - adminBridge string // --admin [bridge-id]; empty = not requested - prune bool // --prune: apply migration cleanup without prompting - addonsFlag string // --addons "dapr,pulsar": comma-separated infrastructure accelerators - migrateFlag bool // --migrate: run the bridge's database-migration commands after generation - updateBridges bool // --update-bridges: download newer bridge versions before generating - checkUpdates bool // bridges --check-updates: contact remotes and report outdated cached bridges - replaceFlags []string + // isTerminal is a seam for testing prompt gating without a real TTY. + isTerminal = interactive.IsTerminal + + // execCommandFn constructs child processes for bridge-declared database + // migrations. It is a seam so tests can inspect the working directory and + // context passed to a command without changing production behavior. + execCommandFn = exec.CommandContext // version is stamped at build time via -ldflags "-X main.version=vX.Y.Z" and, // when it isn't, backed by the module version in build info (see init). @@ -90,42 +110,115 @@ func init() { } } -func Execute() { - if err := newRootCommand().Execute(); err != nil { - os.Exit(1) +// errUsage marks CLI misuse: bad flags, bad arguments or a missing required +// flag. main maps it to exit code 2; every other error is a runtime failure +// (exit 1). The message stays that of the underlying error — the marker is +// invisible to the user and to log output. +var errUsage = errors.New("usage error") + +type usageError struct{ err error } + +// Error returns the underlying CLI misuse message. +func (u usageError) Error() string { return u.err.Error() } + +// Unwrap exposes the original error for errors.Is/As inspection. +func (u usageError) Unwrap() error { return u.err } + +// Is marks the error as CLI misuse so main can map it to exit code 2. +func (u usageError) Is(target error) bool { + return target == errUsage +} + +// asUsageError tags an error raised inside RunE so it gets the usage exit code. +func asUsageError(err error) error { + if err == nil { + return nil + } + return usageError{err: err} +} + +// usageOnInvalidBridgeRef maps a rejected bridge reference (a bad flag value) +// to a usage error, while leaving clone/network failures as runtime errors. +func usageOnInvalidBridgeRef(err error) error { + if err == nil || !errors.Is(err, bridge.ErrInvalidRef) { + return err + } + return asUsageError(err) +} + +// newRootCommandFn is a seam so tests can attach their own error writer to +// the command tree instead of replacing the process-global os.Stderr. +var newRootCommandFn = newRootCommand + +// reportCommandError is the only place a command failure reaches stderr. A +// cleanup handler must return its error instead of also logging a warning, or +// the same failure would be printed twice. +func reportCommandError(w io.Writer, err error) { + _, _ = fmt.Fprintln(w, "Error:", err) +} + +// Execute runs the root command. Cobra is silenced so the error is printed +// exactly once here; the error is returned to main, which owns the exit code. +func Execute() error { + return executeRoot(newRootCommandFn()) +} + +// executeRoot runs a prepared command tree. Errors raised before the command's +// PersistentPreRun (unknown flag, unknown command, failed argument validation) +// are usage errors by construction. +func executeRoot(root *cobra.Command) error { + preRun := root.PersistentPreRun + reachedRun := false + root.PersistentPreRun = func(cmd *cobra.Command, args []string) { + reachedRun = true + if preRun != nil { + preRun(cmd, args) + } + } + if err := root.Execute(); err != nil { + reportCommandError(root.ErrOrStderr(), err) + if !reachedRun || errors.Is(err, errUsage) { + return asUsageError(err) + } + return err } + return nil } func newRootCommand() *cobra.Command { + opts := newCLIOptions() rootCmd := &cobra.Command{ - Use: "domaincraft", - Short: "DomainCraft CLI", - Long: "DomainCraft CLI — domain-driven code generator.\nParse domain.yaml, validate it, and generate production-ready code via pluggable bridges.", - Version: version, - RunE: func(cmd *cobra.Command, args []string) error { + Use: "domaincraft", + Short: "DomainCraft CLI", + Long: "DomainCraft CLI — domain-driven code generator.\nParse domain.yaml, validate it, and generate production-ready code via pluggable bridges.", + Version: version, + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { // Make the root runnable so Cobra exposes its --version flag, while // still showing the help text when invoked without a subcommand. return cmd.Help() }, } - rootCmd.PersistentFlags().StringVarP(&domainFile, "domain", "d", "domain.yaml", "path to domain.yaml") - rootCmd.PersistentFlags().StringVarP(&bridgePath, "bridge", "b", "", "bridge ID, path, or owner/repo (interactive if omitted)") - rootCmd.PersistentFlags().StringVarP(&outputDir, "output", "o", "generated", "output directory") - rootCmd.PersistentFlags().BoolVar(&nonInteractive, "non-interactive", false, "disable interactive prompts (requires all flags)") - rootCmd.PersistentFlags().StringVar(&addonsFlag, "addons", "", "comma-separated infrastructure addons to enable (e.g. dapr)") - rootCmd.PersistentFlags().BoolVar(&updateBridges, "update-bridges", false, "check cached bridges for newer versions and download them before generating (no prompts)") + rootCmd.PersistentFlags().StringVarP(&opts.domainFile, "domain", "d", defaultDomainFile, "path to domain.yaml") + rootCmd.PersistentFlags().StringVarP(&opts.bridgePath, "bridge", "b", "", "bridge ID, path, or owner/repo (interactive if omitted)") + rootCmd.PersistentFlags().StringVarP(&opts.outputDir, "output", "o", defaultOutputDir, "output directory") + rootCmd.PersistentFlags().BoolVar(&opts.nonInteractive, "non-interactive", false, "disable interactive prompts (requires all flags)") + rootCmd.PersistentFlags().StringVar(&opts.addons, "addons", "", "comma-separated infrastructure addons to enable (e.g. dapr)") + rootCmd.PersistentFlags().BoolVar(&opts.updateBridges, "update-bridges", false, "check cached bridges for newer versions and download them before generating (no prompts)") // Best-effort "new version available" notice on every invocation. - rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) { + rootCmd.PersistentPreRun = func(cmd *cobra.Command, _ []string) { maybeNotifyUpdate(cmd) } for _, cmd := range []*cobra.Command{ - newValidateCmd(), - newInitCmd(), - newGenerateCmd(), - newBridgesCmd(), + newValidateCmd(opts), + newInitCmd(opts), + newGenerateCmd(opts), + newBridgesCmd(opts), newUpdateCmd(), } { rootCmd.AddCommand(cmd) @@ -133,23 +226,23 @@ func newRootCommand() *cobra.Command { return rootCmd } -// commandLogger returns a logger writing to the command's output stream. +// commandLogger returns a logger writing to the command's error stream. CLI +// progress and diagnostics are not data; stdout stays usable for piping. func commandLogger(cmd *cobra.Command) *logger.Logger { - log := logger.New() - log.SetWriter(cmd.OutOrStdout()) - return log + return logger.NewWithWriter(cmd.ErrOrStderr()) } // --- validate --- -func newValidateCmd() *cobra.Command { +func newValidateCmd(opts *cliOptions) *cobra.Command { return &cobra.Command{ Use: "validate", Short: "Validate domain.yaml", - RunE: func(cmd *cobra.Command, args []string) error { + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { log := commandLogger(cmd) - log.Info("Validating %s", domainFile) - schema, err := loadAndValidate(cmd.OutOrStdout()) + log.Info("Validating %s", opts.domainFile) + schema, err := loadAndValidate(opts, cmd) if err != nil { return err } @@ -161,61 +254,99 @@ func newValidateCmd() *cobra.Command { // --- generate --- -func newGenerateCmd() *cobra.Command { +func newGenerateCmd(opts *cliOptions) *cobra.Command { cmd := &cobra.Command{ Use: "generate", Short: "Generate code from domain.yaml", Long: "Parse domain.yaml, build IR, and render code via the selected bridge.\nIf --bridge is omitted, an interactive selection menu is shown.\nUse --admin to also generate an admin panel (optionally specify a bridge ID).", - RunE: runGenerate, + // One positional argument is the optional value of `--admin `; + // `generate` itself takes none. Validate the pairing here, before + // RunE writes any files. + Args: func(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + return nil + } + if err := cobra.MaximumNArgs(1)(cmd, args); err != nil { + return err + } + if !cmd.Flags().Changed("admin") || opts.adminBridge != "admin-alpine" { + return asUsageError(fmt.Errorf("unexpected positional argument %q: use --admin ", args[0])) + } + opts.adminBridge = args[0] + return nil + }, + RunE: func(cmd *cobra.Command, _ []string) error { + return runGenerate(opts, cmd) + }, } // --admin [bridge-id] — optional value, defaults to "admin-alpine" when flag // is present without a value. NoOptDefVal is used for the default, and the - // RunE handler reclaims a space-separated value from args so both - // `--admin ` and `--admin=` work. - cmd.Flags().StringVar(&adminBridge, "admin", "", "generate admin panel (optionally specify bridge ID, default: admin-alpine)") + // Args validator reclaims a space-separated value so both `--admin ` + // and `--admin=` work. + cmd.Flags().StringVar(&opts.adminBridge, "admin", "", "generate admin panel (optionally specify bridge ID, default: admin-alpine)") cmd.Flags().Lookup("admin").NoOptDefVal = "admin-alpine" // --prune — automatically delete/rename orphaned files without prompting (CI). - cmd.Flags().BoolVar(&prune, "prune", false, "automatically remove/rename orphaned files and rewrite renamed identifiers in custom files, then run the bridge's database migrations (best-effort) when the schema changed (no prompts; CI-safe)") + cmd.Flags().BoolVar(&opts.prune, "prune", false, "automatically remove/rename orphaned files and rewrite renamed identifiers in custom files, then run the bridge's database migrations (best-effort) when the schema changed (no prompts; CI-safe)") // --migrate — after generation, run the bridge's declared database-migration commands. - cmd.Flags().BoolVar(&migrateFlag, "migrate", false, "run the bridge's database-migration commands after generation (e.g. dotnet ef database update)") - cmd.Flags().StringArrayVar(&replaceFlags, "replace", nil, "replace a bridge in the extends chain: layer=bridgeRef or bridgeId=bridgeRef (repeatable)") + cmd.Flags().BoolVar(&opts.migrate, "migrate", false, "run the bridge's database-migration commands after generation (e.g. dotnet ef database update)") + cmd.Flags().BoolVar(&opts.allowBridgeCommands, "allow-bridge-commands", false, "allow shell commands declared by community bridges (required with --migrate or automatic --prune migrations)") + cmd.Flags().StringArrayVar(&opts.replaceFlags, "replace", nil, "replace a bridge in the extends chain: layer=bridgeRef or bridgeId=bridgeRef (repeatable)") return cmd } -// runGenerate is shared by `generate` and `init --bridge` so both paths go -// through the same validation, rendering and migration pipeline. -func runGenerate(cmd *cobra.Command, args []string) error { - log := commandLogger(cmd) - - log.Info("Parsing %s", domainFile) - schema, err := loadAndValidate(cmd.OutOrStdout()) +// loadAndValidateDomain parses and validates domain.yaml, then builds the IR +// and applies addons. Bridge resolution stays between validation and IR +// building so prompts, log lines and errors keep their original order. +func loadAndValidateDomain(opts *cliOptions, cmd *cobra.Command, log *logger.Logger) (*ir.Project, string, error) { + log.Info("Parsing %s", opts.domainFile) + schema, err := loadAndValidate(opts, cmd) if err != nil { - return err + return nil, "", err } log.Success("Schema valid (%d entities)", len(schema.Entities)) - resolvedPath, bridgeName, err := resolveBridgeInteractive(log) + bridgePath, bridgeName, err := resolveBridgeInteractive(opts, log) if err != nil { - return err + return nil, "", err } - bridgePath = resolvedPath + opts.bridgePath = bridgePath log.Info("Building IR") irProject, err := ir.Build(schema) + if err != nil { + return nil, "", err + } + applyAddons(opts, irProject, log) + return irProject, bridgeName, nil +} + +// runGenerate is shared by `generate` and `init --bridge` so both paths go +// through the same validation, rendering and migration pipeline. +func runGenerate(opts *cliOptions, cmd *cobra.Command) error { + log := commandLogger(cmd) + ctx := &commandContext{opts: opts, cmd: cmd, log: log} + + // Flag syntax is checked before reading the domain, prompting the user, + // building the IR or cloning a bridge. + replacements, err := parseReplaceFlags(opts.replaceFlags) + if err != nil { + return asUsageError(err) + } + + irProject, bridgeName, err := loadAndValidateDomain(opts, cmd, log) if err != nil { return err } - applyAddons(irProject) // --- Schema snapshot / migration diff --- - snapPath := snapshot.SnapshotPath(outputDir) + snapPath := snapshot.Path(opts.outputDir) oldSnapshot, err := snapshot.Load(snapPath) if err != nil { return fmt.Errorf("load schema snapshot: %w", err) } - migrationDiff := snapshot.ComputeDiff(oldSnapshot, irProject, outputDir) + migrationDiff := snapshot.ComputeDiff(oldSnapshot, irProject, opts.outputDir, log.Warn) // --- Abstract schema migration plan (smart core / dumb bridge) --- // The core compares the previous model against the current one and @@ -229,125 +360,86 @@ func runGenerate(cmd *cobra.Command, args []string) error { seedData := seed.Normalize(irProject) mockDataset := seed.Generate(irProject, seed.Options{}) - // Parse --replace flags (layer|bridgeId=bridgeRef). - replacements, err := parseReplaceFlags(replaceFlags) - if err != nil { - return err - } // Resolve extends chain with optional node replacements. - newBridgePath, basePaths, err := resolveChainWithReplacements(bridgePath, replacements, log) + newBridgePath, basePaths, err := resolveChainWithReplacements(opts, opts.bridgePath, replacements, log) if err != nil { return err } - bridgePath = newBridgePath + opts.bridgePath = newBridgePath + // One resolved chain drives both the trust decision and the lock file. + chainPaths := append([]string{opts.bridgePath}, basePaths...) // Phase 3.5: a community bridge (not a bundled official bridge) must // never have migrations auto-run — that would execute arbitrary shell // lines from an untrusted bridge.yaml during a code-generation run. chainHasCommunity := false - for _, p := range append([]string{bridgePath}, basePaths...) { + for _, p := range chainPaths { if !bridge.IsOfficialBundled(p) { chainHasCommunity = true break } } - log.Info("Rendering via %s", bridgePath) - rendererInstance, err := renderer.New(bridgePath, log) + ctx.chainHasCommunity = chainHasCommunity + // Build the renderer before writing anything so the consent decision can + // be made up front: a rejected --migrate must not leave generated files + // or pruned files behind. + rendererInstance, err := newBridgeRenderer(renderOptions{ + path: opts.bridgePath, + outDir: opts.outputDir, + bases: basePaths, + plan: migrationPlan, + seedData: seedData, + mockDataset: mockDataset, + log: log, + }) if err != nil { return err } - if err := rendererInstance.AttachBases(basePaths); err != nil { + if err := planBridgeMigrations(ctx, migrationDiff, rendererInstance.MigrationConfig()); err != nil { return err } - rendererInstance.SetMigration(migrationPlan) - rendererInstance.SetSeedData(seedData) - rendererInstance.SetMockData(mockDataset) - writtenFiles, manifest, err := rendererInstance.Render(irProject, outputDir) + log.Info("Rendering via %s", opts.bridgePath) + writtenFiles, manifest, err := rendererInstance.Render(irProject, opts.outputDir) if err != nil { return err } - log.Success("Generated %d file(s) into %s", len(writtenFiles), outputDir) + log.Success("Generated %d file(s) into %s", len(writtenFiles), opts.outputDir) // --- Admin panel generation --- - // pflag's NoOptDefVal makes `--admin ` stop consuming the next - // argument (it lands in args), so reclaim it here. This keeps both - // `--admin ` and `--admin=` working while `--admin` alone - // still means the default admin-alpine bridge. - if cmd.Flags().Changed("admin") && adminBridge == "admin-alpine" && len(args) > 0 { - adminBridge = args[0] - } - if adminBridge == "" && !cmd.Flags().Changed("admin") && nonInteractive { - // In non-interactive mode, skip admin prompt — admin not requested. - } else if adminBridge == "" && !cmd.Flags().Changed("admin") && interactive.IsTerminal() { - generate, _ := interactive.PromptGenerateAdmin() - if generate { - adminBridge = "admin-alpine" - } - } - if adminBridge != "" { - adminManifest, err := generateAdminPanel(irProject, seedData, mockDataset, log) - if err != nil { - return err - } - manifest = append(manifest, adminManifest...) + adminManifest, err := generateAdminPanel(ctx, irProject, seedData, mockDataset) + if err != nil { + return err } + manifest = append(manifest, adminManifest...) // --- Migration actions: clean up orphaned / renamed files --- - // Files written from this run must never be touched by cleanup. - fresh := make(map[string]bool) - for _, f := range manifest { - if f.Written { - fresh[f.Path] = true - } - } - applied, err := applyMigrationActions(migrationDiff, fresh, log, cmd) + applied, err := applySchemaMigrations(ctx, migrationDiff, manifest) if err != nil { return err } // --- Database migrations --- - // Run the bridge's declared migration commands so the developer never - // has to think about SQL schemas. Triggered explicitly via --migrate, or - // automatically in --prune mode when the diff detected renames/deletions - // that must reach the database (skipped when cleanup was deferred). - autoMigrate := prune && migrationDiff.HasSchemaChanges() - if autoMigrate && chainHasCommunity { - log.Warn("community bridge(s) in the resolved chain — not auto-running database migrations; use --migrate explicitly") - autoMigrate = false - } - shouldMigrate := migrateFlag || autoMigrate - if applied && shouldMigrate && rendererInstance.MigrationConfig() != nil && rendererInstance.MigrationConfig().Enabled { - if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), outputDir, cmd, log); err != nil { - if migrateFlag { - // Explicit --migrate: a failed migration is a hard error. - return err - } - // Auto-migration under --prune is best-effort. In a docker/CI - // workflow the API container applies pending migrations at startup - // (Database:SchemaMode=migrate → MigrateAsync), so a host without - // the dotnet SDK or an unreachable database must not abort generation. - log.Warn("Database migration was not applied by --prune: %v", err) - log.Warn("In docker, set Database:SchemaMode=migrate — the container applies pending migrations on startup.") - } - } - - // --- Smart warning for type changes (manual refactoring report) --- - if report := migrationDiff.TypeChangeReport(); report != "" { - log.Warn("ACTION REQUIRED — manual refactoring may be needed") - fmt.Fprint(cmd.OutOrStdout(), report) - } - - // --- Smart warning for field renames (data-preserving column rename) --- - if report := migrationDiff.FieldRenameReport(); report != "" { - log.Warn("ACTION REQUIRED — fields were renamed; apply a safe column rename to avoid data loss") - fmt.Fprint(cmd.OutOrStdout(), report) + ctx.cleanupApplied = applied + if err := runBridgeDatabaseMigrations(ctx, rendererInstance.MigrationConfig()); err != nil { + return err } - // --- Project-rename warning: custom files with a stale root namespace --- - if report := migrationDiff.NamespaceRenameReport(); report != "" { - log.Warn("ACTION REQUIRED — project was renamed; custom files reference the old namespace") - fmt.Fprint(cmd.OutOrStdout(), report) + // --- Smart refactoring reports --- + // Warnings and the multi-line reports are both human-facing diagnostics: + // they go to stderr so stdout stays usable for piping. Order is fixed. + for _, r := range []struct { + report func() string + warning string + }{ + {migrationDiff.TypeChangeReport, "ACTION REQUIRED — manual refactoring may be needed"}, + {migrationDiff.FieldRenameReport, "ACTION REQUIRED — fields were renamed; apply a safe column rename to avoid data loss"}, + {migrationDiff.NamespaceRenameReport, "ACTION REQUIRED — project was renamed; custom files reference the old namespace"}, + } { + if report := r.report(); report != "" { + log.Warn("%s", r.warning) + _, _ = fmt.Fprint(cmd.ErrOrStderr(), report) + } } // --- Persist the new snapshot --- @@ -358,13 +450,13 @@ func runGenerate(cmd *cobra.Command, args []string) error { log.Info("Snapshot kept — cleanup pending (re-run with --prune to finish)") return nil } - bridgeID := bridgePath + bridgeID := opts.bridgePath if bridgeName != "" { bridgeID = bridgeName } // Record the resolved bridge chain next to domain.yaml (Phase 0.4). // Best-effort: a lock-write failure must never abort generation. - if err := writeDomainLock(domainFile, append([]string{bridgePath}, basePaths...)); err != nil { + if err := writeDomainLock(opts.domainFile, chainPaths); err != nil { log.Warn("could not write domaincraft.lock.json: %v", err) } if err := snapshot.Save(snapPath, snapshot.New(bridgeID, irProject, manifest)); err != nil { @@ -376,23 +468,24 @@ func runGenerate(cmd *cobra.Command, args []string) error { // --- bridges --- -func newBridgesCmd() *cobra.Command { +func newBridgesCmd(opts *cliOptions) *cobra.Command { cmd := &cobra.Command{ Use: "bridges", Short: "List available bridges", Long: "Show all known bridges with their cache status.", - RunE: func(cmd *cobra.Command, args []string) error { + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { registry := bridge.Default() out := cmd.OutOrStdout() entries := registry.All() if len(entries) == 0 { - fmt.Fprintln(out, "No bridges registered.") + _, _ = fmt.Fprintln(out, "No bridges registered.") return nil } - fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", "ID", "Language", "Source", "Status", "Description") - fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", + _, _ = fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", "ID", "Language", "Source", "Status", "Description") + _, _ = fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", strings.Repeat("-", 20), strings.Repeat("-", 10), strings.Repeat("-", 18), @@ -401,7 +494,7 @@ func newBridgesCmd() *cobra.Command { ) for _, e := range entries { - st := e.Status(checkUpdates) + st := e.Status(opts.checkUpdates) source := "remote" switch { case st.Embedded && st.Cached: @@ -429,673 +522,24 @@ func newBridgesCmd() *cobra.Command { if e.Deprecated { status += "+deprecated" } - fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", e.ID, e.Language, source, status, e.Description) + _, _ = fmt.Fprintf(out, "%-20s %-10s %-18s %-16s %s\n", e.ID, e.Language, source, status, e.Description) } - fmt.Fprintln(out, "\nLegend: embedded = inside this binary; cache = local copy; remote = fetched on demand.") - fmt.Fprintln(out, "Run `domaincraft generate --update-bridges` to refresh cached bridges to the latest supported version.") + _, _ = fmt.Fprintln(out, "\nLegend: embedded = inside this binary; cache = local copy; remote = fetched on demand.") + _, _ = fmt.Fprintln(out, "Run `domaincraft generate --update-bridges` to refresh cached bridges to the latest supported version.") return nil }, } // --check-updates — contact each cached bridge's remote and report whether a // newer version is available (no modification, just status). - cmd.Flags().BoolVar(&checkUpdates, "check-updates", false, "contact remotes and report whether cached bridges are outdated") + cmd.Flags().BoolVar(&opts.checkUpdates, "check-updates", false, "contact remotes and report whether cached bridges are outdated") return cmd } // --- helpers --- -// newBridgeResolver builds a resolver with the CLI's bridge cache/update options. -func newBridgeResolver(log *logger.Logger) *bridge.Resolver { - return bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(log)) -} - -// walkBridgeChain resolves ref relative to fromDir and follows `extends` to the -// deepest base. It returns absolute paths top-first: the resolved bridge first, -// then its bases. Absolute paths make cycle detection path-based, not textual. -func walkBridgeChain(ref, fromDir string, log *logger.Logger) ([]string, error) { - resolver := newBridgeResolver(log) - var chain []string - visited := make(map[string]bool) - for ref != "" { - path, err := bridge.ResolveExtendsRef(ref, fromDir, resolver) - if err != nil { - return nil, fmt.Errorf("resolve bridge `extends: %s`: %w", ref, err) - } - if abs, err := filepath.Abs(path); err == nil { - path = abs - } - if visited[path] { - return nil, fmt.Errorf("bridge `extends` cycle detected at %q", ref) - } - visited[path] = true - chain = append(chain, path) - - base, err := renderer.New(path, log) - if err != nil { - return nil, fmt.Errorf("load bridge %s: %w", path, err) - } - ref, fromDir = base.Extends(), path - } - return chain, nil -} - -// resolveBridgeInteractive resolves the bridge from the --bridge flag, or -// prompts the user interactively. Returns (path, displayName, error). -func resolveBridgeInteractive(log *logger.Logger) (string, string, error) { - resolver := newBridgeResolver(log) - - if bridgePath != "" { - // Monorepo-first: an official bridge ID resolves to the local - // /bridges/ copy when it exists (same order as `extends`). - if entry := bridge.Default().ByID(bridgePath); entry != nil && entry.Path != "" { - if wd, err := os.Getwd(); err == nil { - if p := bridge.FindMonorepoBridge(wd, entry.Path); p != "" { - return p, "", nil - } - } - } - resolved, err := resolver.Resolve(bridgePath) - return resolved, "", err - } - - if nonInteractive || !interactive.IsTerminal() { - return "", "", fmt.Errorf("--bridge is required in non-interactive mode") - } - - entry, err := interactive.SelectBridge(bridge.Default()) - if err != nil { - return "", "", err - } - - resolved, err := resolver.Resolve(entry.ID) - if err != nil { - return "", "", fmt.Errorf("resolve bridge %q: %w", entry.ID, err) - } - - return resolved, entry.Name, nil -} - -// resolveBaseChain resolves an adapter bridge's `extends` chain to local bridge -// paths, ordered outermost base first (so the deepest base renders first). Each -// base is resolved the same way --bridge is: a path, registry ID or owner/repo. -func resolveBaseChain(adapterDir, baseRef string, log *logger.Logger) ([]string, error) { - chain, err := walkBridgeChain(baseRef, adapterDir, log) - if err != nil { - return nil, err - } - // The walker returns the deepest chain top-first; bases must render with - // the outermost base first, so reverse it. - slices.Reverse(chain) - return chain, nil -} - -// replaceEntry is one --replace flag: left (= layer or bridge name) -> right (bridge ref). -type replaceEntry struct { - left string - right string -} - -func parseReplaceFlags(raw []string) ([]replaceEntry, error) { - var out []replaceEntry - for _, s := range raw { - parts := strings.SplitN(s, "=", 2) - if len(parts) != 2 || strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" { - return nil, fmt.Errorf("invalid --replace %q: expected layer|bridgeId=bridgeRef", s) - } - out = append(out, replaceEntry{left: strings.TrimSpace(parts[0]), right: strings.TrimSpace(parts[1])}) - } - return out, nil -} - -// bridgeLayerAndName loads bridge.yaml for dir and returns layer and name. -func bridgeLayerAndName(dir string, log *logger.Logger) (string, string, error) { - r, err := renderer.New(dir, log) - if err != nil { - return "", "", err - } - cfg := r.Config() - return cfg.Layer, cfg.Name, nil -} - -// buildFullChainTopFirst builds the full chain top-first: [entry, base1, base2, ... deepest]. -func buildFullChainTopFirst(entryDir string, log *logger.Logger) ([]string, error) { - return walkBridgeChain(entryDir, entryDir, log) -} - -// resolveChainWithReplacements resolves the extends chain with --replace overrides. -// It returns the (possibly replaced) entry dir and base paths outermost-first. -func resolveChainWithReplacements(entryDir string, reps []replaceEntry, log *logger.Logger) (string, []string, error) { - if len(reps) == 0 { - r, err := renderer.New(entryDir, log) - if err != nil { - return "", nil, err - } - bases, err := resolveBaseChain(entryDir, r.Extends(), log) - return entryDir, bases, err - } - resolver := newBridgeResolver(log) - fullChain, err := buildFullChainTopFirst(entryDir, log) - if err != nil { - return "", nil, err - } - for _, rep := range reps { - // Find target index by layer or name. - targetIdx := -1 - var targetLayer string - for i, dir := range fullChain { - layer, name, err := bridgeLayerAndName(dir, log) - if err != nil { - return "", nil, err - } - if layer == rep.left || name == rep.left { - targetIdx = i - targetLayer = layer - break - } - } - if targetIdx == -1 { - return "", nil, fmt.Errorf("no bridge with layer or name %q in chain %v", rep.left, fullChain) - } - // Resolve replacement bridge. - rightPath, err := bridge.ResolveExtendsRef(rep.right, entryDir, resolver) - if err != nil { - return "", nil, fmt.Errorf("resolve --replace %s=%s: %w", rep.left, rep.right, err) - } - if abs, err := filepath.Abs(rightPath); err == nil { - rightPath = abs - } - rightLayer, rightName, err := bridgeLayerAndName(rightPath, log) - if err != nil { - return "", nil, err - } - // Warn on layer mismatch (both non-empty and different). - if targetLayer != "" && rightLayer != "" && targetLayer != rightLayer && log != nil { - log.Warn("layer mismatch: replacing %q (layer=%q) with %q (layer=%q)", rep.left, targetLayer, rightName, rightLayer) - } - // Build replacement's full chain top-first. - rightChain, err := buildFullChainTopFirst(rightPath, log) - if err != nil { - return "", nil, err - } - // Splice: fullChain[:targetIdx] + rightChain (replaces tail after targetIdx) - newChain := make([]string, 0, len(fullChain[:targetIdx])+len(rightChain)) - newChain = append(newChain, fullChain[:targetIdx]...) - newChain = append(newChain, rightChain...) - // Validate no duplicate layer and no cycle. - seenLayer := make(map[string]string) - seenPath := make(map[string]bool) - for _, d := range newChain { - abs, _ := filepath.Abs(d) - if seenPath[abs] { - return "", nil, fmt.Errorf("bridge `extends` cycle detected at %q", d) - } - seenPath[abs] = true - layer, _, _ := bridgeLayerAndName(d, log) - if layer != "" { - if prev, ok := seenLayer[layer]; ok { - return "", nil, fmt.Errorf("duplicate layer %q: %q and %q", layer, prev, d) - } - seenLayer[layer] = d - } - } - fullChain = newChain - } - newEntry := fullChain[0] - tail := fullChain[1:] - slices.Reverse(tail) - return newEntry, tail, nil -} - -// --- domaincraft.lock.json (Phase 0.4) --- -// -// The lock records the exact bridge chain that rendered a project, next to the -// domain.yaml (not inside the output dir, not in the snapshot). It holds no -// timestamps, so it is diff-friendly and reproducible. It answers "which -// bridges rendered this project" — the snapshot answers "what did the model -// look like". - -// lockBridge is one entry in domaincraft.lock.json. -type lockBridge struct { - ID string `json:"id"` - Path string `json:"path,omitempty"` // monorepo path under bridges/ when resolved locally from the monorepo - Source string `json:"source,omitempty"` // GitHub owner/repo when resolved from the registry/cache - Version string `json:"version,omitempty"` - ContractVersion int `json:"contract_version"` -} - -// domainLock is the on-disk shape of domaincraft.lock.json. -type domainLock struct { - Bridges []lockBridge `json:"bridges"` -} - -// writeDomainLock records the resolved bridge chain (top-first: entry, then its -// bases) next to domainPath. It is best-effort: a failure to write the lock -// must never break generation. -func writeDomainLock(domainPath string, dirs []string) error { - reg := bridge.Default() - var out []lockBridge - seen := make(map[string]bool) - for _, dir := range dirs { - id, version, contractVersion, err := bridgeMetadata(dir) - if err != nil { - return err - } - if id == "" || seen[id] { - continue - } - seen[id] = true - b := lockBridge{ID: id, Version: version, ContractVersion: contractVersion} - if entry := reg.ByID(id); entry != nil { - if p := bridge.MonorepoRelPath(dir, entry.Path); p != "" { - b.Path = p - } else if entry.GitHub != "" { - b.Source = entry.GitHub - } - } - out = append(out, b) - } - slices.SortFunc(out, func(a, b lockBridge) int { return cmp.Compare(a.ID, b.ID) }) - - data, err := json.MarshalIndent(domainLock{Bridges: out}, "", " ") - if err != nil { - return err - } - dir := filepath.Dir(domainPath) - if dir == "" { - dir = "." - } - return fsutil.AtomicWrite(filepath.Join(dir, "domaincraft.lock.json"), data) -} - -// bridgeMetadata reads the identifying fields out of a bridge directory's -// bridge.yaml for the lock file. -func bridgeMetadata(dir string) (id, version string, contractVersion int, err error) { - data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) - if err != nil { - return "", "", 0, err - } - var cfg struct { - Name string `yaml:"name"` - Version string `yaml:"version"` - ContractVersion int `yaml:"contract_version"` - } - if err := yaml.Unmarshal(data, &cfg); err != nil { - return "", "", 0, err - } - if cfg.ContractVersion == 0 { - cfg.ContractVersion = 1 - } - return cfg.Name, cfg.Version, cfg.ContractVersion, nil -} - -// bridgeEnsureOptions builds the bridge caching/update policy from the CLI -// flags and terminal state: -// - --update-bridges consents to downloading newer versions (CI-safe); -// - otherwise, an interactive terminal is prompted when an update is found; -// - in non-interactive mode the cached copy is kept and a warning is logged. -func bridgeEnsureOptions(log *logger.Logger) *bridge.EnsureOptions { - opts := &bridge.EnsureOptions{ - Force: updateBridges, - Warn: log.Warn, - } - - switch { - case updateBridges: - // The flag itself is the consent — update without prompting. - opts.ConfirmUpdate = func(entry bridge.RegistryEntry, u *bridge.Update) (bool, error) { - log.Info("Updating bridge %s %s", entry.ID, versionDelta(u)) - return true, nil - } - case interactive.IsTerminal(): - opts.ConfirmUpdate = func(entry bridge.RegistryEntry, u *bridge.Update) (bool, error) { - return interactive.PromptBridgeUpdate(entry, u) - } - default: - // Non-interactive without the flag: keep the cached copy; the bridge - // package logs a warning pointing at --update-bridges. - opts.ConfirmUpdate = nil - } - return opts -} - -// versionDelta renders a "vX" hint for a detected update, or "" when the local -// version is unknown. -func versionDelta(u *bridge.Update) string { - if u == nil || u.LocalVersion == "" { - return "" - } - return fmt.Sprintf("(v%s available)", u.LocalVersion) -} - -// generateAdminPanel renders the optional admin panel bridge into the output -// directory and returns the extra file manifest entries. -func generateAdminPanel(irProject *ir.IRProject, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { - resolver := bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(log)) - - adminID := adminBridge - if adminID == "" { - adminID = "admin-alpine" - } - - adminPath, err := resolver.Resolve(adminID) - if err != nil { - return nil, fmt.Errorf("resolve admin bridge %q: %w", adminID, err) - } - - log.Info("Rendering admin panel via %s", adminID) - adminRenderer, err := renderer.New(adminPath, log) - if err != nil { - return nil, err - } - adminRenderer.SetSeedData(seedData) - adminRenderer.SetMockData(mockDataset) - - adminFiles, adminManifest, err := adminRenderer.Render(irProject, outputDir) - if err != nil { - return nil, err - } - - log.Success("Generated %d admin file(s)", len(adminFiles)) - return adminManifest, nil -} - -// runDatabaseMigrations executes the bridge's declared database-migration -// commands in order, from the generated output directory. Commands are shell -// lines invoked through the platform shell so bridges can rely on standard -// tooling (e.g. `dotnet ef ...`). A failing command aborts the run. -func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *cobra.Command, log *logger.Logger) error { - if cfg == nil || !cfg.Enabled || len(cfg.Commands) == 0 { - return nil - } - out := cmd.OutOrStdout() - // The resolved command lines are printed before they run, so the developer - // always sees exactly what will be executed (Phase 3.5 safety). - fmt.Fprintf(out, " Applying %d database migration command(s):\n", len(cfg.Commands)) - for i, command := range cfg.Commands { - fmt.Fprintf(out, " %d) %s\n", i+1, command) - } - for i, command := range cfg.Commands { - log.Info("Migration %d/%d: %s", i+1, len(cfg.Commands), command) - var argv []string - var shell string - if runtime.GOOS == "windows" { - shell = "cmd" - argv = []string{"/C", command} - } else { - shell = "sh" - argv = []string{"-c", command} - } - c := exec.Command(shell, argv...) - c.Dir = outDir - c.Stdout = out - c.Stderr = out - if err := c.Run(); err != nil { - log.Error("Migration failed: %s", err) - return fmt.Errorf("database migration %d failed: %w", i+1, err) - } - } - log.Success("Database migrations applied") - return nil -} - -// applyMigrationActions handles orphaned file cleanup for entities that were -// removed or renamed since the last generation. In interactive mode the user -// is prompted before touching custom (overwrite: false) files. With --prune -// everything is done automatically; otherwise (non-interactive) a warning is -// printed and nothing is modified. Files freshly written this run (fresh) are -// never touched. -// -// It returns whether all actions were applied. When cleanup was deferred -// (non-interactive without --prune) it returns false so the caller keeps the -// previous snapshot — otherwise orphaned files would be forgotten and a later -// --prune run could no longer find them. -func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logger.Logger, cmd *cobra.Command) (bool, error) { - if diff == nil || diff.IsEmpty() { - return true, nil - } - out := cmd.OutOrStdout() - - // In --prune mode the tool owns the whole cleanup, so it also rewrites - // identifier references in developer-owned files: the project's root - // namespace after a project rename, and renamed entity fields. Generated - // files are already regenerated with the new names; custom files are not, - // so this is what keeps them compiling. - if prune { - if diff.NamespaceRename != nil { - for _, rel := range diff.NamespaceRename.Files { - if fresh[rel] { - continue - } - rewrote, err := snapshot.RewriteFile(outputDir, rel, snapshot.NamespaceTransform(diff.NamespaceRename)) - if err != nil { - log.Warn("could not rewrite namespace in %s: %v", rel, err) - continue - } - if rewrote { - fmt.Fprintf(out, " ▸ updated namespace %s -> %s in %s\n", diff.NamespaceRename.OldNamespace, diff.NamespaceRename.NewNamespace, rel) - } - } - } - for _, fr := range diff.FieldRenames { - for _, rel := range fr.CustomFiles { - if fresh[rel] { - continue - } - rewrote, err := snapshot.RewriteFile(outputDir, rel, snapshot.FieldTransform(fr)) - if err != nil { - log.Warn("could not rewrite field references in %s: %v", rel, err) - continue - } - if rewrote { - fmt.Fprintf(out, " ▸ updated field %s -> %s in %s\n", fr.OldField, fr.NewField, rel) - } - } - } - } - - applied := true - for _, del := range diff.Deleted { - if len(del.Files) == 0 { - continue - } - done, err := handleDeletedEntity(del, fresh, log, out) - if err != nil { - return false, err - } - applied = applied && done - } - - for _, ren := range diff.Renamed { - if len(ren.Files) == 0 { - continue - } - done, err := handleRename(ren, diff, fresh, log, out) - if err != nil { - return false, err - } - applied = applied && done - } - return applied, nil -} - -// chooseMigrationFiles returns the files selected for cleanup. --prune takes -// all of them; otherwise the caller's prompt decides. The non-interactive -// fallback stays in the caller because its warning is operation-specific. -func chooseMigrationFiles(files []snapshot.FileRef, prompt func([]interactive.FileChoice) ([]string, error)) (map[string]bool, error) { - selected := make(map[string]bool) - if prune { - for _, f := range files { - selected[f.Path] = true - } - return selected, nil - } - choices := make([]interactive.FileChoice, len(files)) - for i, f := range files { - choices[i] = interactive.FileChoice{Path: f.Path, Label: fileLabel(f)} - } - picked, err := prompt(choices) - if err != nil { - return nil, err - } - for _, p := range picked { - selected[p] = true - } - return selected, nil -} - -// handleDeletedEntity deletes generated files automatically and asks (or warns) -// about custom files of a removed entity. Returns false when cleanup was -// deferred (non-interactive without --prune). -func handleDeletedEntity(del snapshot.DeletedEntity, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { - if !prune && !interactive.IsTerminal() { - log.Warn("Entity %q was removed from domain.yaml — orphaned files kept (re-run with --prune to delete):", del.Name) - for _, f := range del.Files { - fmt.Fprintf(out, " - %s%s\n", f.Path, customMark(f)) - } - return false, nil - } - selected, err := chooseMigrationFiles(del.Files, func(choices []interactive.FileChoice) ([]string, error) { - return interactive.PromptDeleteFiles(del.Name, choices) - }) - if err != nil { - return false, err - } - - for _, f := range del.Files { - if !selected[f.Path] || fresh[f.Path] { - continue - } - if err := snapshot.DeleteFile(outputDir, f.Path); err != nil { - log.Warn("could not delete %s: %v", f.Path, err) - continue - } - fmt.Fprintf(out, " ▸ deleted %s\n", f.Path) - } - return true, nil -} - -// handleRename renames custom files after a prompt and removes stale generated -// files (they have been regenerated under the new entity name). In --prune mode -// the renamed files' contents are rewritten too (entity, namespace and field -// identifiers), so the developer-owned file keeps compiling after the rename. -// Returns false when cleanup was deferred (non-interactive without --prune). -func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { - if !prune && !interactive.IsTerminal() { - log.Warn("Entity %q was renamed to %q — files kept (re-run with --prune to rename):", ren.OldName, ren.NewName) - for _, f := range ren.Files { - fmt.Fprintf(out, " - %s -> %s\n", f.Path, snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName)) - } - return false, nil - } - selected, err := chooseMigrationFiles(ren.Files, func(choices []interactive.FileChoice) ([]string, error) { - return interactive.PromptRenameFiles(ren.OldName, ren.NewName, choices) - }) - if err != nil { - return false, err - } - - for _, f := range ren.Files { - if !selected[f.Path] || fresh[f.Path] { - continue - } - if f.Custom { - newRel := snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName) - if fresh[newRel] { - // The destination was scaffolded this run by the custom - // (overwrite: false) template. Replace it with the developer's - // existing custom file so custom hooks survive the rename. - if err := os.Remove(filepath.Join(outputDir, filepath.FromSlash(newRel))); err != nil { - log.Warn("could not replace scaffolded %s: %v", newRel, err) - continue - } - } - newRel, renamed, err := snapshot.RenameEntityFile(outputDir, f.Path, ren.OldName, ren.NewName) - if err != nil { - log.Warn("could not rename %s: %v", f.Path, err) - continue - } - if renamed { - if rewrote, rerr := snapshot.RewriteFile(outputDir, newRel, snapshot.RenameTransforms(ren.OldName, ren.NewName, d)...); rerr != nil { - log.Warn("could not rewrite content of %s: %v", newRel, rerr) - } else if rewrote { - fmt.Fprintf(out, " ▸ renamed %s -> %s (content updated)\n", f.Path, newRel) - continue - } - fmt.Fprintf(out, " ▸ renamed %s -> %s\n", f.Path, newRel) - } - continue - } - // Generated files have been regenerated under the new name — remove the stale copy. - if err := snapshot.DeleteFile(outputDir, f.Path); err != nil { - log.Warn("could not delete stale generated file %s: %v", f.Path, err) - continue - } - fmt.Fprintf(out, " ▸ removed stale generated file %s\n", f.Path) - } - return true, nil -} - -// fileLabel renders a file choice label, annotating developer-owned files. -func fileLabel(f snapshot.FileRef) string { - return f.Path + customMark(f) -} - -// customMark returns a marker suffix for custom (overwrite: false) files. -func customMark(f snapshot.FileRef) string { - if f.Custom { - return " [custom]" - } - return "" -} - -// applyAddons parses the --addons flag into the IR project's Addons set, -// validating each name against specmeta. Unknown addons are silently ignored so -// bridges that don't know a given addon simply render their non-addon templates. -func applyAddons(project *ir.IRProject) { - if strings.TrimSpace(addonsFlag) == "" { - return - } - if project.Addons == nil { - project.Addons = make(map[string]bool) - } - for _, addon := range strings.Split(addonsFlag, ",") { - addon = strings.TrimSpace(addon) - if addon == "" { - continue - } - if specmeta.IsAddon(addon) { - project.Addons[addon] = true - } - } -} - -func loadAndValidate(out io.Writer) (*parser.ParsedSchema, error) { - data, err := os.ReadFile(domainFile) - if err != nil { - return nil, fmt.Errorf("read domain file: %w", err) - } - schema, err := parser.ParseYAML(data) - if err != nil { - return nil, err - } - - allErrors := validator.New(schema).Validate() - var hardErrors []validator.ValidationError - for _, e := range allErrors { - if e.Warning { - fmt.Fprintf(out, "⚠ %s\n", e.Error()) - } else { - hardErrors = append(hardErrors, e) - fmt.Fprintln(out, e.Error()) - } - } - - if len(hardErrors) > 0 { - return nil, fmt.Errorf("validation failed with %d error(s)", len(hardErrors)) - } - - return schema, nil -} +// commandContext groups the state threaded through the generation pipeline's +// helper steps: parsed flags, the command (for stdio), its logger, and the two +// chain/cleanup facts the migration helpers act on. diff --git a/cmd/domaincraft/commands_admin_test.go b/cmd/domaincraft/commands_admin_test.go new file mode 100644 index 0000000..3a2347a --- /dev/null +++ b/cmd/domaincraft/commands_admin_test.go @@ -0,0 +1,181 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + +func writeAdminTestBridge(t *testing.T, dir, template, target string) string { + t.Helper() + if err := os.MkdirAll(filepath.Join(dir, "templates"), 0o755); err != nil { + t.Fatal(err) + } + manifest := "name: " + filepath.Base(dir) + "\nversion: \"1.0.0\"\noutput_dir: generated\ntemplates:\n - for: project\n source: templates/main.tmpl\n target: \"" + target + "\"\n" + if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(manifest), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "templates", "main.tmpl"), []byte(template+"\n"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +// TestGenerateAdminPanelPath covers the documented --admin flow: a local admin +// bridge resolves, renders and contributes files to the same output tree. +func TestGenerateAdminPanelPath(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + root := t.TempDir() + domainPath := filepath.Join(root, "domain.yaml") + domain := "project:\n name: Fixture\ndatabase: postgresql\nentities:\n Item:\n fields:\n id: uuid [primary]\n" + if err := os.WriteFile(domainPath, []byte(domain), 0o644); err != nil { + t.Fatal(err) + } + mainBridge := writeAdminTestBridge(t, filepath.Join(root, "main-bridge"), "main", "main.txt") + adminBridge := writeAdminTestBridge(t, filepath.Join(root, "admin-bridge"), "admin", "admin.html") + + tests := []struct { + name string + adminFlag []string + wantAdmin bool + }{ + {name: "explicit admin bridge", adminFlag: []string{"--admin", adminBridge}, wantAdmin: true}, + {name: "no admin", adminFlag: nil, wantAdmin: false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + out := filepath.Join(root, strings.ReplaceAll(tc.name, " ", "-")) + cmd := newRootCommand() + var stdout, stderr strings.Builder + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + args := []string{"generate", "--domain", domainPath, "--bridge", mainBridge, "--output", out, "--non-interactive"} + args = append(args, tc.adminFlag...) + cmd.SetArgs(args) + if err := cmd.Execute(); err != nil { + t.Fatalf("generate: %v\nstderr: %s", err, stderr.String()) + } + + _, mainErr := os.Stat(filepath.Join(out, "main.txt")) + if mainErr != nil { + t.Errorf("main output missing: %v", mainErr) + } + _, adminErr := os.Stat(filepath.Join(out, "admin.html")) + if tc.wantAdmin { + if adminErr != nil { + t.Errorf("admin output missing: %v", adminErr) + } + if !strings.Contains(stderr.String(), "admin file(s)") { + t.Errorf("diagnostics do not report admin files: %q", stderr.String()) + } + } else if adminErr == nil { + t.Error("admin output was generated without --admin") + } + }) + } +} + +// seedAdminAlpineCache puts a minimal admin-alpine bridge in the isolated bridge +// cache so bare `--admin` resolves offline to a predictable fixture. The metadata +// marks the cache as freshly checked, which keeps the update probe off the network. +func seedAdminAlpineCache(t *testing.T, template, target string) { + t.Helper() + entry := bridge.Default().ByID("admin-alpine") + if entry == nil { + t.Fatal("admin-alpine is missing from the bridge registry") + } + writeAdminTestBridge(t, bridge.CachePath(*entry), template, target) + now := time.Now() + if err := bridge.WriteMeta(*entry, &bridge.CacheMeta{ + ID: entry.ID, + Source: entry.GitHub, + Version: "1.0.0", + ClonedAt: now, + LastCheckedAt: now, + }); err != nil { + t.Fatal(err) + } +} + +// TestGenerateAdminFlagForms covers the remaining --admin spellings: an equals +// sign, a bare flag (which defaults to admin-alpine) and an omitted flag. The +// positional `--admin ` form is covered by +// TestRootCommandSuppressesCobraErrorNoise in commands_hardening_test.go. +func TestGenerateAdminFlagForms(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + root := t.TempDir() + domainPath := filepath.Join(root, "domain.yaml") + domain := "project:\n name: Fixture\ndatabase: postgresql\nentities:\n Item:\n fields:\n id: uuid [primary]\n" + if err := os.WriteFile(domainPath, []byte(domain), 0o644); err != nil { + t.Fatal(err) + } + mainBridge := writeAdminTestBridge(t, filepath.Join(root, "main-bridge"), "main", "main.txt") + adminBridge := writeAdminTestBridge(t, filepath.Join(root, "admin-bridge"), "admin", "admin.html") + + tests := []struct { + name string + adminArgs []string + seedCache bool + wantAdmin bool + wantLog string + }{ + { + name: "equals form with explicit path", + adminArgs: []string{"--admin=" + adminBridge}, + wantAdmin: true, + wantLog: "admin file(s)", + }, + { + name: "bare flag defaults to admin-alpine", + adminArgs: []string{"--admin"}, + seedCache: true, + wantAdmin: true, + wantLog: "Rendering admin panel via admin-alpine", + }, + { + name: "flag omitted", + wantAdmin: false, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if tc.seedCache { + seedAdminAlpineCache(t, "admin", "admin.html") + } + out := filepath.Join(root, strings.ReplaceAll(tc.name, " ", "-")) + cmd := newRootCommand() + var stdout, stderr strings.Builder + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + args := []string{"generate", "--domain", domainPath, "--bridge", mainBridge, "--output", out, "--non-interactive"} + args = append(args, tc.adminArgs...) + cmd.SetArgs(args) + if err := cmd.Execute(); err != nil { + t.Fatalf("generate: %v\nstderr: %s", err, stderr.String()) + } + + if _, err := os.Stat(filepath.Join(out, "main.txt")); err != nil { + t.Errorf("main output missing: %v", err) + } + _, adminErr := os.Stat(filepath.Join(out, "admin.html")) + if tc.wantAdmin && adminErr != nil { + t.Errorf("admin output missing: %v", adminErr) + } + if !tc.wantAdmin && adminErr == nil { + t.Error("admin output was generated without --admin") + } + if tc.wantLog != "" && !strings.Contains(stderr.String(), tc.wantLog) { + t.Errorf("stderr = %q, want %q", stderr.String(), tc.wantLog) + } + }) + } +} diff --git a/cmd/domaincraft/commands_bridges_test.go b/cmd/domaincraft/commands_bridges_test.go new file mode 100644 index 0000000..1233e12 --- /dev/null +++ b/cmd/domaincraft/commands_bridges_test.go @@ -0,0 +1,41 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + +// TestBridgesCheckUpdatesKeepsRegistryOrder pins the output contract of the +// concurrent probe: every cached bridge is checked in parallel, but rows must +// still follow the registry order. +func TestBridgesCheckUpdatesKeepsRegistryOrder(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + root := newRootCommand() + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(io.Discard) + root.SetArgs([]string{"bridges", "--check-updates"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + + lines := strings.Split(strings.TrimSpace(out.String()), "\n") + entries := bridge.Default().All() + if len(lines) < len(entries)+2 { + t.Fatalf("got %d output lines, want at least %d", len(lines), len(entries)+2) + } + for i, e := range entries { + want := fmt.Sprintf("%-20s", e.ID) + if got := lines[i+2]; !strings.HasPrefix(got, want) { + t.Errorf("row %d = %q, want registry entry %q", i, got, e.ID) + } + } +} diff --git a/cmd/domaincraft/commands_contract_test.go b/cmd/domaincraft/commands_contract_test.go new file mode 100644 index 0000000..32e4995 --- /dev/null +++ b/cmd/domaincraft/commands_contract_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +// TestBridgeMetadataRejectsNegativeContractVersion keeps the lock-file reader +// on the same contract parser as the renderer and update gate. A local int +// field used to accept a negative version that the shared parser rejects. +func TestBridgeMetadataRejectsNegativeContractVersion(t *testing.T) { + dir := t.TempDir() + manifest := "name: bad\nversion: 1.0.0\ncontract_version: -1\n" + if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(manifest), 0o644); err != nil { + t.Fatalf("write bridge.yaml: %v", err) + } + if _, _, _, err := bridgeMetadata(dir); err == nil { + t.Fatal("bridgeMetadata accepted a negative contract_version") + } +} diff --git a/cmd/domaincraft/commands_extends_test.go b/cmd/domaincraft/commands_extends_test.go new file mode 100644 index 0000000..4066449 --- /dev/null +++ b/cmd/domaincraft/commands_extends_test.go @@ -0,0 +1,313 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +// writeBridgeDir scaffolds a minimal bridge directory (just a bridge.yaml, +// optionally declaring `extends:`) and returns its absolute path. +func writeBridgeDir(t *testing.T, dir, extends string) string { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir %s: %v", dir, err) + } + content := "name: " + filepath.Base(dir) + "\n" + if extends != "" { + content += "extends: " + extends + "\n" + } + path := filepath.Join(dir, "bridge.yaml") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } + return dir +} + +// writeLayeredBridge scaffolds a bridge with an explicit layer (and optional +// extends) so --replace can be exercised without cloning anything. +func writeLayeredBridge(t *testing.T, dir, layer, extends string) string { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir %s: %v", dir, err) + } + content := "name: " + filepath.Base(dir) + "\nlayer: " + layer + "\n" + if extends != "" { + content += "extends: " + extends + "\n" + } + path := filepath.Join(dir, "bridge.yaml") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } + return dir +} + +// layeredChain builds core <- domain <- persistence <- transport plus an +// alternative bridge used as a --replace target. +func layeredChain(t *testing.T, altLayer, altExtends string) (core, domain, persistence, transport, alt string) { + t.Helper() + root := t.TempDir() + core = writeLayeredBridge(t, filepath.Join(root, "c-core"), "core", "") + domain = writeLayeredBridge(t, filepath.Join(root, "c-domain"), "domain", core) + persistence = writeLayeredBridge(t, filepath.Join(root, "c-efcore"), "persistence", domain) + transport = writeLayeredBridge(t, filepath.Join(root, "c-rest"), "transport", persistence) + if altLayer == "" { + altLayer = "persistence" + } + if altExtends == "" { + altExtends = domain + } + alt = writeLayeredBridge(t, filepath.Join(root, "c-dapper"), altLayer, altExtends) + return +} + +func TestParseReplaceFlags(t *testing.T) { + t.Run("valid entries are trimmed and split once", func(t *testing.T) { + got, err := parseReplaceFlags([]string{ + "persistence=../dapper", + " csharp-efcore = bridges/csharp/persistence/efcore ", + "persistence=/tmp/a=b", + }) + if err != nil { + t.Fatalf("parseReplaceFlags: %v", err) + } + want := []replaceEntry{ + {left: "persistence", right: "../dapper"}, + {left: "csharp-efcore", right: "bridges/csharp/persistence/efcore"}, + {left: "persistence", right: "/tmp/a=b"}, + } + if len(got) != len(want) { + t.Fatalf("entries = %+v, want %+v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("entry %d = %+v, want %+v", i, got[i], want[i]) + } + } + }) + + t.Run("malformed entries are rejected", func(t *testing.T) { + for _, raw := range []string{"persistence", "=../dapper", "persistence=", ""} { + if _, err := parseReplaceFlags([]string{raw}); err == nil { + t.Errorf("parseReplaceFlags(%q) should fail", raw) + } + } + }) +} + +func TestResolveChainWithReplacements(t *testing.T) { + checkBases := func(t *testing.T, got []string, want []string) { + t.Helper() + if len(got) != len(want) { + t.Fatalf("bases = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("base %d = %q, want %q", i, got[i], want[i]) + } + } + } + + t.Run("replacement by layer splices the chain", func(t *testing.T) { + core, domain, _, transport, alt := layeredChain(t, "", "") + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + entry, bases, err := resolveChainWithReplacements(&cliOptions{}, transport, + []replaceEntry{{left: "persistence", right: alt}}, log) + if err != nil { + t.Fatalf("resolveChainWithReplacements: %v", err) + } + if entry != transport { + t.Errorf("entry = %q, want %q", entry, transport) + } + checkBases(t, bases, []string{core, domain, alt}) + }) + + t.Run("replacement by bridgeId finds the same node", func(t *testing.T) { + core, domain, _, transport, alt := layeredChain(t, "", "") + quiet := logger.New() + quiet.SetWriter(&bytes.Buffer{}) + entry, bases, err := resolveChainWithReplacements(&cliOptions{}, transport, + []replaceEntry{{left: "c-efcore", right: alt}}, quiet) + if err != nil { + t.Fatalf("resolveChainWithReplacements: %v", err) + } + if entry != transport { + t.Errorf("entry = %q, want %q", entry, transport) + } + checkBases(t, bases, []string{core, domain, alt}) + }) + + t.Run("layer mismatch warns but still succeeds", func(t *testing.T) { + _, _, _, transport, alt := layeredChain(t, "storage", "") + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + if _, _, err := resolveChainWithReplacements(&cliOptions{}, transport, + []replaceEntry{{left: "persistence", right: alt}}, log); err != nil { + t.Fatalf("resolveChainWithReplacements: %v", err) + } + if !strings.Contains(logOut.String(), "layer mismatch") || !strings.Contains(logOut.String(), "c-dapper") { + t.Errorf("warning = %q, want the layer mismatch and replacement name", logOut.String()) + } + }) + + t.Run("duplicate layer is rejected", func(t *testing.T) { + _, _, _, transport, alt := layeredChain(t, "domain", "") + quiet := logger.New() + quiet.SetWriter(&bytes.Buffer{}) + _, _, err := resolveChainWithReplacements(&cliOptions{}, transport, + []replaceEntry{{left: "persistence", right: alt}}, quiet) + if err == nil || !strings.Contains(err.Error(), "duplicate layer") { + t.Fatalf("err = %v, want duplicate layer error", err) + } + }) + + t.Run("cycle is rejected", func(t *testing.T) { + _, _, _, transport, _ := layeredChain(t, "", "") + quiet := logger.New() + quiet.SetWriter(&bytes.Buffer{}) + _, _, err := resolveChainWithReplacements(&cliOptions{}, transport, + []replaceEntry{{left: "domain", right: transport}}, quiet) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("err = %v, want cycle error", err) + } + }) +} + +func TestResolveBaseChainOrdersOutermostBaseFirst(t *testing.T) { + root := t.TempDir() + + c := writeBridgeDir(t, filepath.Join(root, "bridge-c"), "") + b := writeBridgeDir(t, filepath.Join(root, "bridge-b"), c) + a := writeBridgeDir(t, filepath.Join(root, "bridge-a"), b) + + chain, err := resolveBaseChain(&cliOptions{}, a, b, logger.New()) + if err != nil { + t.Fatalf("resolveBaseChain: %v", err) + } + + if len(chain) != 2 { + t.Fatalf("chain = %v, want the two bases (the adapter itself is not part of the chain)", chain) + } + if chain[0] != c || chain[1] != b { + t.Errorf("chain = %v, want [%s %s] (deepest base first)", chain, c, b) + } +} + +func TestResolveBaseChainDetectsCycle(t *testing.T) { + root := t.TempDir() + + b := writeBridgeDir(t, filepath.Join(root, "bridge-b"), "") + a := writeBridgeDir(t, filepath.Join(root, "bridge-a"), b) + // Close the cycle: B now extends A while A extends B. + writeBridgeDir(t, filepath.Join(root, "bridge-b"), a) + + _, err := resolveBaseChain(&cliOptions{}, a, b, logger.New()) + if err == nil { + t.Fatal("expected a cycle error") + } + if !strings.Contains(err.Error(), "cycle") { + t.Errorf("err = %v, want it to mention the cycle", err) + } +} + +func TestResolveExtendsRefPrefersLocalCheckout(t *testing.T) { + root := t.TempDir() + resolver := bridge.NewResolver(bridge.Default()) + + // Registry ID whose repo checkout sits next to the extending bridge + // (monorepo sibling layout) — must resolve locally without cloning. + sibling := writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp"), "") + + got, err := bridge.ResolveExtendsRef("csharp-restful", filepath.Join(root, "adapter"), resolver) + if err != nil { + t.Fatalf("resolveExtendsRef: %v", err) + } + if abs, _ := filepath.Abs(got); abs != sibling { + t.Errorf("resolved = %q, want the sibling checkout %q", got, sibling) + } + + // CI layout: the base bridge checked out inside the adapter's directory. + innerRoot := t.TempDir() + innerAdapter := filepath.Join(innerRoot, "adapter") + inner := writeBridgeDir(t, filepath.Join(innerAdapter, "domaincraft-bridge-csharp"), "") + + got, err = bridge.ResolveExtendsRef("csharp-restful", innerAdapter, resolver) + if err != nil { + t.Fatalf("resolveExtendsRef: %v", err) + } + if abs, _ := filepath.Abs(got); abs != inner { + t.Errorf("resolved = %q, want the in-directory checkout %q", got, inner) + } +} + +func TestResolveExtendsRefPrefersMonorepoLayout(t *testing.T) { + root := t.TempDir() + resolver := bridge.NewResolver(bridge.Default()) + + // Monorepo layout: /bridges/csharp/core for the csharp-core bridge. + mp := writeBridgeDir(t, filepath.Join(root, "bridges", "csharp", "core"), "") + + // Distractor sibling checkout with the legacy repo name — must NOT win now. + writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp-core"), "") + + got, err := bridge.ResolveExtendsRef("csharp-core", filepath.Join(root, "adapter"), resolver) + if err != nil { + t.Fatalf("resolveExtendsRef: %v", err) + } + if abs, _ := filepath.Abs(got); abs != mp { + t.Errorf("resolved = %q, want the monorepo bridge %q", got, mp) + } + + // A bridge with a multi-segment path: csharp-efcore → csharp/persistence/efcore. + ef := writeBridgeDir(t, filepath.Join(root, "bridges", "csharp", "persistence", "efcore"), "") + got, err = bridge.ResolveExtendsRef("csharp-efcore", filepath.Join(root, "adapter"), resolver) + if err != nil { + t.Fatalf("bridge.ResolveExtendsRef(efcore): %v", err) + } + if abs, _ := filepath.Abs(got); abs != ef { + t.Errorf("resolved = %q, want %q", got, ef) + } +} + +func TestResolveExtendsRefFallsBackWhenNoMonorepo(t *testing.T) { + root := t.TempDir() + resolver := bridge.NewResolver(bridge.Default()) + sibling := writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp"), "") + got, err := bridge.ResolveExtendsRef("csharp-restful", filepath.Join(root, "adapter"), resolver) + if err != nil { + t.Fatalf("resolveExtendsRef: %v", err) + } + if abs, _ := filepath.Abs(got); abs != sibling { + t.Errorf("resolved = %q, want legacy sibling %q", got, sibling) + } +} + +func TestBridgeUpdateNoticeOmitsCachedVersion(t *testing.T) { + cases := []struct { + name string + u *bridge.Update + }{ + {"nil update", nil}, + {"unknown local version", &bridge.Update{}}, + {"known local version", &bridge.Update{LocalVersion: "1.2.3"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := bridgeUpdateNotice("csharp-core", c.u) + if !strings.Contains(got, "Updating bridge csharp-core") { + t.Errorf("notice = %q, want the bridge ID", got) + } + if strings.Contains(got, "1.2.3") || strings.Contains(got, "available") { + t.Errorf("notice = %q, must not present the cached version as available", got) + } + }) + } +} diff --git a/cmd/domaincraft/commands_hardening_test.go b/cmd/domaincraft/commands_hardening_test.go new file mode 100644 index 0000000..0f8879d --- /dev/null +++ b/cmd/domaincraft/commands_hardening_test.go @@ -0,0 +1,806 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/internal/snapshot" + "github.com/DomainCraft/DomainCraft/pkg/logger" + + "github.com/spf13/cobra" +) + +func digestHex(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +func snapshotDeleted(rel string) snapshot.DeletedEntity { + return snapshot.DeletedEntity{Name: "Old", Files: []snapshot.FileRef{{Path: rel, Custom: true}}} +} + +func snapshotRename(rel string) snapshot.Rename { + return snapshot.Rename{OldName: "Old", NewName: "New", Files: []snapshot.FileRef{{Path: rel, Custom: true}}} +} + +// stubTerminal forces the prompt gate for the duration of a test. +func stubTerminal(t *testing.T, value bool) { + t.Helper() + old := isTerminal + isTerminal = func() bool { return value } + t.Cleanup(func() { isTerminal = old }) +} + +func TestBridgeEnsureOptionsRespectsNonInteractiveOnTTY(t *testing.T) { + stubTerminal(t, true) + + cases := []struct { + name string + nonInteractive bool + updateBridges bool + wantPrompt bool + }{ + {"interactive prompts", false, false, true}, + {"non-interactive does not prompt", true, false, false}, + {"update-bridges consents without prompting", false, true, true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + var out bytes.Buffer + log := logger.New() + log.SetWriter(&out) + opts := &cliOptions{nonInteractive: tt.nonInteractive, updateBridges: tt.updateBridges} + got := bridgeEnsureOptions(opts, log) + if tt.wantPrompt != (got.ConfirmUpdate != nil) { + t.Fatalf("ConfirmUpdate set = %v, want %v", got.ConfirmUpdate != nil, tt.wantPrompt) + } + if !tt.updateBridges || got.ConfirmUpdate == nil { + return + } + _, err := got.ConfirmUpdate(bridge.RegistryEntry{ID: "csharp-core"}, &bridge.Update{LocalVersion: "1.2.3"}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "1.2.3") || strings.Contains(out.String(), "available") { + t.Errorf("log = %q, must not label the cached version as available", out.String()) + } + }) + } +} + +func TestMigrationCleanupDeferredOnTTYWhenNonInteractive(t *testing.T) { + stubTerminal(t, true) + + t.Run("deleted entity files are kept", func(t *testing.T) { + root := t.TempDir() + rel := "src/Old.cs" + if err := os.MkdirAll(filepath.Join(root, "src"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(rel)), []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + opts := &cliOptions{outputDir: root, nonInteractive: true} + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + cmd := &cobra.Command{} + var fileOut bytes.Buffer + cmd.SetOut(&fileOut) + + diff := &snapshot.Diff{Deleted: []snapshot.DeletedEntity{snapshotDeleted(rel)}} + applied, err := applyMigrationActions(opts, diff, map[string]bool{}, log, cmd) + if err != nil || applied { + t.Fatalf("applyMigrationActions = %v, %v; want false, nil", applied, err) + } + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(rel))); err != nil { + t.Errorf("orphaned file was touched: %v", err) + } + if !strings.Contains(logOut.String(), "orphaned files kept") { + t.Errorf("missing non-interactive warning: %q", logOut.String()) + } + }) + + t.Run("renamed entity files are kept", func(t *testing.T) { + root := t.TempDir() + rel := "src/OldService.cs" + if err := os.MkdirAll(filepath.Join(root, "src"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(rel)), []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + opts := &cliOptions{outputDir: root, nonInteractive: true} + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + var fileOut bytes.Buffer + + mc := migrationContext{opts: opts, fresh: map[string]bool{}, log: log, out: &fileOut} + applied, err := handleRename(&mc, snapshotRename(rel), nil) + if err != nil || applied { + t.Fatalf("handleRename = %v, %v; want false, nil", applied, err) + } + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(rel))); err != nil { + t.Errorf("file was touched: %v", err) + } + if !strings.Contains(logOut.String(), "files kept") { + t.Errorf("missing non-interactive warning: %q", logOut.String()) + } + }) +} + +func TestCleanupDeferred(t *testing.T) { + stubTerminal(t, true) + cases := []struct { + name string + opts cliOptions + want bool + }{ + {"prune on a TTY", cliOptions{prune: true}, false}, + {"prune non-interactive", cliOptions{prune: true, nonInteractive: true}, false}, + {"interactive on a TTY", cliOptions{}, false}, + {"non-interactive on a TTY", cliOptions{nonInteractive: true}, true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := cleanupDeferred(&tt.opts); got != tt.want { + t.Fatalf("cleanupDeferred(%+v) = %v, want %v", tt.opts, got, tt.want) + } + }) + } + + stubTerminal(t, false) + if !cleanupDeferred(&cliOptions{}) { + t.Fatal("cleanup must be deferred without a TTY") + } +} + +// TestPruneRejectsScaffoldReplaceEscape guards the last unvalidated removal in +// --prune: a poisoned rename destination must never delete a file outside the +// output directory, neither via ".." nor through a symlink. +func TestPruneRejectsScaffoldReplaceEscape(t *testing.T) { + run := func(t *testing.T, output, oldRel, newRel string) { + t.Helper() + opts := &cliOptions{outputDir: output, prune: true} + ren := snapshot.Rename{ + OldName: "Old", + NewName: "New", + Files: []snapshot.FileRef{{Path: oldRel, Custom: true}}, + } + diff := &snapshot.Diff{Renamed: []snapshot.Rename{ren}} + // The scaffolded destination is marked as freshly written, which + // triggers the replace path in the rename handler. + fresh := map[string]bool{newRel: true} + cmd := &cobra.Command{} + cmd.SetOut(&bytes.Buffer{}) + applied, err := applyMigrationActions(opts, diff, fresh, logger.New(), cmd) + if applied || err == nil { + t.Fatalf("applyMigrationActions = %v, %v; want a hard error under --prune", applied, err) + } + if !strings.Contains(err.Error(), "replace scaffolded") { + t.Errorf("err = %v, want it to name the scaffold replacement", err) + } + } + + t.Run("path traversal", func(t *testing.T) { + root := t.TempDir() + output := filepath.Join(root, "generated") + outside := filepath.Join(root, "outside") + for _, dir := range []string{output, outside} { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + } + victim := filepath.Join(outside, "NewService.txt") + if err := os.WriteFile(victim, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + run(t, output, "../outside/OldService.txt", "../outside/NewService.txt") + if _, err := os.Stat(victim); err != nil { + t.Fatalf("file outside outputDir was removed: %v", err) + } + }) + + t.Run("symlink to outside directory", func(t *testing.T) { + root := t.TempDir() + output := filepath.Join(root, "generated") + outside := filepath.Join(root, "outside") + for _, dir := range []string{output, outside} { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + } + victim := filepath.Join(outside, "NewService.txt") + if err := os.WriteFile(victim, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(output, "link")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + run(t, output, "link/OldService.txt", "link/NewService.txt") + if _, err := os.Stat(victim); err != nil { + t.Fatalf("file behind the symlink was removed: %v", err) + } + }) +} + +// TestPruneCleanupErrorPrintedOnce checks that a failed namespace rewrite under +// --prune is returned (and printed by reportCommandError) but never warned about +// a second time by the cleanup handler itself. +func TestPruneCleanupErrorPrintedOnce(t *testing.T) { + root := t.TempDir() + // A non-empty directory at the custom file path makes RewriteFile fail. + blocked := filepath.Join(root, "src", "ItemService.txt") + if err := os.MkdirAll(filepath.Join(blocked, "child"), 0o755); err != nil { + t.Fatal(err) + } + diff := &snapshot.Diff{NamespaceRename: &snapshot.NamespaceMismatch{ + OldNamespace: "OldNs", + NewNamespace: "NewNs", + Files: []string{"src/ItemService.txt"}, + }} + + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldStderr := os.Stderr + os.Stderr = w + t.Cleanup(func() { + os.Stderr = oldStderr + _ = r.Close() + _ = w.Close() + }) + + log := logger.New() + log.SetWriter(w) + cmd := &cobra.Command{} + cmd.SetErr(w) + applied, err := applyMigrationActions(&cliOptions{outputDir: root, prune: true}, diff, nil, log, cmd) + if applied || err == nil { + t.Fatalf("applyMigrationActions = %v, %v; want a hard error", applied, err) + } + reportCommandError(w, err) + _ = w.Close() + out, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + got := string(out) + if n := strings.Count(got, "rewrite namespace in src/ItemService.txt"); n != 1 { + t.Errorf("cleanup failure printed %d times, want 1: %q", n, got) + } + if strings.Contains(got, "could not rewrite namespace") { + t.Errorf("duplicate warning was emitted: %q", got) + } +} + +// TestUsageErrorsExitTwo separates CLI misuse (exit 2) from runtime failures +// (exit 1) while keeping the error itself printed exactly once. +func TestUsageErrorsExitTwo(t *testing.T) { + oldArgs, oldVersion, oldCtx, oldNewRoot := os.Args, version, bridge.CommandContext(), newRootCommandFn + version = "dev" + // run() cancels the context it installs via its deferred stop(); restore + // the shared command context so later tests keep a live one. + t.Cleanup(func() { + os.Args, version, newRootCommandFn = oldArgs, oldVersion, oldNewRoot + bridge.SetCommandContext(oldCtx) + }) + + domainPath := filepath.Join(t.TempDir(), "domain.yaml") + if err := os.WriteFile(domainPath, []byte(`project: + name: Fixture +database: postgresql +entities: + Item: + fields: + id: uuid [primary] +`), 0o644); err != nil { + t.Fatal(err) + } + + initPath := filepath.Join(t.TempDir(), "domain.yaml") + if err := os.WriteFile(initPath, []byte("project:\n name: Existing\n"), 0o644); err != nil { + t.Fatal(err) + } + bridgeDir := pruneBridge(t, "") + cases := []struct { + name string + args []string + want int + }{ + {"init missing scenario", []string{"domaincraft", "init", "--non-interactive", "--domain", filepath.Join(t.TempDir(), "missing.yaml")}, 2}, + {"init unknown scenario", []string{"domaincraft", "init", "--scenario", "nope", "--domain", filepath.Join(t.TempDir(), "other.yaml")}, 2}, + {"init existing file", []string{"domaincraft", "init", "--scenario", "shop", "--domain", initPath}, 2}, + {"unknown flag", []string{"domaincraft", "validate", "--bogus"}, 2}, + {"too many arguments", []string{"domaincraft", "validate", "a", "b"}, 2}, + {"unknown command", []string{"domaincraft", "nope"}, 2}, + {"missing bridge", []string{"domaincraft", "generate", "--domain", domainPath, "--output", t.TempDir(), "--non-interactive"}, 2}, + {"malformed --replace", []string{"domaincraft", "generate", "--domain", domainPath, "--bridge", bridgeDir, "--output", t.TempDir(), "--non-interactive", "--replace", "malformed"}, 2}, + {"runtime failure", []string{"domaincraft", "validate", "--domain", filepath.Join(t.TempDir(), "missing.yaml")}, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "stderr.log") + f, err := os.Create(logPath) + if err != nil { + t.Fatal(err) + } + os.Args = tc.args + newRootCommandFn = func() *cobra.Command { + root := newRootCommand() + root.SetErr(f) + return root + } + got := run() + _ = f.Close() + if got != tc.want { + data, _ := os.ReadFile(logPath) + t.Errorf("run(%v) = %d, want %d; stderr: %s", tc.args, got, tc.want, data) + } + }) + } +} + +func TestSanitizeCommandLine(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + {"CSI", "echo \x1b[2JSAFE", "echo SAFE"}, + {"OSC with BEL", "\x1b]0;pwn\x07echo SAFE", "echo SAFE"}, + {"OSC with ST", "echo SAFE\x1b]0;pwn\x1b\\", "echo SAFE"}, + {"C0 and DEL", "echo\tSAFE\r\n\x00\x07\x7f", `echo\tSAFE\n`}, + {"C1", "echo\u0085SAFE\u009f", "echoSAFE"}, + {"bare ESC", "echo SAFE\x1b", "echo SAFE"}, + {"UTF-8 preserved", "echo Привет", "echo Привет"}, + {"embedded newline cannot split the command", "echo SAFE\nrm -rf /", `echo SAFE\nrm -rf /`}, + {"embedded tab cannot fake a new argument", "echo\tSAFE", `echo\tSAFE`}, + {"bidi override", "echo \u202eSAFE\u202c", "echo SAFE"}, + {"bidi isolates", "\u2066evil\u2069SAFE", "evilSAFE"}, + {"zero-width characters", "e\u200bx\u200dy\u200cz", "exyz"}, + {"zero-width no-break space", "\ufeffSAFE", "SAFE"}, + {"RTL mark", "\u200fSAFE", "SAFE"}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := sanitizeCommandLine(tt.in); got != tt.want { + t.Fatalf("sanitizeCommandLine(%q) = %q, want %q", tt.in, got, tt.want) + } + }) + } +} + +// TestRunDatabaseMigrationsSanitizesDisplayedCommand uses a shell comment to +// carry the control bytes: the command stays harmless while exercising the +// consent-review output. Only presentation is sanitized; execution is unchanged. +func TestRunDatabaseMigrationsSanitizesDisplayedCommand(t *testing.T) { + evil := "\x1b[31mRED\x1b[0m \x1b]0;window-title\x07 \x07" + command := "echo SAFE # " + evil + if runtime.GOOS == "windows" { + command = "echo SAFE & rem " + evil + } + cfg := &renderer.MigrationConfig{Enabled: true, Commands: []string{command}} + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + if err := runDatabaseMigrations(cfg, t.TempDir(), cmd, log); err != nil { + t.Fatalf("runDatabaseMigrations: %v", err) + } + if n := strings.Count(stderr.String(), "echo SAFE"); n != 1 { + t.Fatalf("command was displayed %d times in stderr: stdout=%q stderr=%q", n, stdout.String(), stderr.String()) + } + if stdout.Len() != 0 { + t.Errorf("migration diagnostics leaked into stdout: %q", stdout.String()) + } + if strings.Contains(stderr.String(), "\x1b") { + t.Errorf("raw escape byte reached stderr: %q", stderr.String()) + } + for _, injected := range []string{"\x1b[31m", "\x1b]0;", "\x07"} { + if strings.Contains(stderr.String(), injected) { + t.Errorf("raw escape byte %q reached stderr: %q", injected, stderr.String()) + } + } +} + +func TestSanitizeStreamChunk(t *testing.T) { + in := "line \x1b[31mRED\x1b[0m\n\u202ehidden\u2066\tend" + got := sanitizeStreamChunk(in) + if strings.Contains(got, "\x1b") { + t.Errorf("ANSI escape reached output: %q", got) + } + if !strings.Contains(got, "\n") || !strings.Contains(got, "\t") { + t.Errorf("line breaks or tabs were lost: %q", got) + } + if !strings.Contains(got, "") { + t.Errorf("bidi control was not made visible: %q", got) + } +} + +// stubMigrationExec swaps the child-process constructor for one test. Tests in +// this package are not parallel, so swapping the seam is race-free. +func stubMigrationExec(t *testing.T, fn func(context.Context, string, ...string) *exec.Cmd) { + t.Helper() + old := execCommandFn + execCommandFn = fn + t.Cleanup(func() { execCommandFn = old }) +} + +// migrationTestCmd builds a shell command for a stub. It mirrors the shell +// selection in runDatabaseMigrations so a stub can choose its own command line +// while still receiving the context from production. +func migrationTestCmd(ctx context.Context, line string) *exec.Cmd { + if runtime.GOOS == "windows" { + return exec.CommandContext(ctx, "cmd", "/C", line) + } + return exec.CommandContext(ctx, "sh", "-c", line) +} + +// TestRunDatabaseMigrationsPropagatesFailure covers the execution branch: a +// non-zero exit code aborts the run and names the failing command. +func TestRunDatabaseMigrationsPropagatesFailure(t *testing.T) { + stubMigrationExec(t, func(ctx context.Context, _ string, _ ...string) *exec.Cmd { + return migrationTestCmd(ctx, "exit 7") + }) + cfg := &renderer.MigrationConfig{Enabled: true, Commands: []string{"echo harmless"}} + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + err := runDatabaseMigrations(cfg, t.TempDir(), cmd, log) + if err == nil { + t.Fatal("runDatabaseMigrations succeeded with a failing command") + } + if !strings.Contains(err.Error(), "database migration 1 failed") { + t.Errorf("err = %q, want it to name migration 1", err) + } + if !strings.Contains(err.Error(), "exit status 7") { + t.Errorf("err = %q, want the child's exit status", err) + } + if strings.Contains(stderr.String(), "Database migrations applied") { + t.Errorf("success reported after a failed command: %q", stderr.String()) + } +} + +// TestRunDatabaseMigrationsUsesOutputDir checks that child processes inherit +// the generated output directory as their working directory. +func TestRunDatabaseMigrationsUsesOutputDir(t *testing.T) { + outDir := filepath.Join(t.TempDir(), "generated") + if err := os.MkdirAll(outDir, 0o755); err != nil { + t.Fatal(err) + } + var captured *exec.Cmd + stubMigrationExec(t, func(ctx context.Context, _ string, _ ...string) *exec.Cmd { + captured = migrationTestCmd(ctx, "exit 0") + return captured + }) + cfg := &renderer.MigrationConfig{Enabled: true, Commands: []string{"echo harmless"}} + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + if err := runDatabaseMigrations(cfg, outDir, cmd, log); err != nil { + t.Fatalf("runDatabaseMigrations: %v", err) + } + if captured == nil { + t.Fatal("no migration command was started") + } + if captured.Dir != outDir { + t.Errorf("command Dir = %q, want %q", captured.Dir, outDir) + } + // Child output is buffered for sanitization and then written to cmd stderr. + if captured.Stdout == nil || captured.Stderr == nil || captured.Stdout != captured.Stderr { + t.Errorf("child streams = (%v, %v), want one shared sanitizing buffer", captured.Stdout, captured.Stderr) + } + if stdout.Len() != 0 { + t.Errorf("migration diagnostics leaked into stdout: %q", stdout.String()) + } + // The stubbed child produces no output, so only the displayed command remains. + if n := strings.Count(stderr.String(), "echo harmless"); n != 1 { + t.Errorf("command text appeared %d times in stderr, want 1: %q", n, stderr.String()) + } +} + +// TestRunDatabaseMigrationsRespectsCommandContext checks that the shared +// command context is handed to the child and that a canceled context prevents +// the process from starting at all. +func TestRunDatabaseMigrationsRespectsCommandContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + oldCtx := bridge.CommandContext() + bridge.SetCommandContext(ctx) + t.Cleanup(func() { bridge.SetCommandContext(oldCtx) }) + + var seenCtx context.Context + var captured *exec.Cmd + stubMigrationExec(t, func(c context.Context, _ string, _ ...string) *exec.Cmd { + seenCtx = c + captured = migrationTestCmd(c, "echo SHOULD_NOT_RUN") + return captured + }) + cfg := &renderer.MigrationConfig{Enabled: true, Commands: []string{"echo harmless"}} + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + err := runDatabaseMigrations(cfg, t.TempDir(), cmd, log) + if err == nil { + t.Fatal("runDatabaseMigrations succeeded with a canceled context") + } + if seenCtx != ctx { + t.Errorf("command received context %v, want the canceled command context", seenCtx) + } + if captured == nil || captured.Process != nil { + t.Fatalf("child process was started with a canceled context: %+v", captured) + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want it to wrap context.Canceled", err) + } + if !strings.Contains(err.Error(), "database migration 1 failed") { + t.Errorf("err = %q, want it to name migration 1", err) + } +} + +// TestRunDatabaseMigrationsRunsCommandsInOrder appends from two real shell +// commands into one file, so the file records execution order rather than the +// order in which commands were merely displayed. +func TestRunDatabaseMigrationsRunsCommandsInOrder(t *testing.T) { + outDir := t.TempDir() + cfg := &renderer.MigrationConfig{ + Enabled: true, + Commands: []string{"echo FIRST >> order.txt", "echo SECOND >> order.txt"}, + } + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + if err := runDatabaseMigrations(cfg, outDir, cmd, log); err != nil { + t.Fatalf("runDatabaseMigrations: %v", err) + } + data, err := os.ReadFile(filepath.Join(outDir, "order.txt")) + if err != nil { + t.Fatalf("read migration output: %v", err) + } + got := strings.Fields(string(data)) + if len(got) != 2 || got[0] != "FIRST" || got[1] != "SECOND" { + t.Errorf("execution order = %q, want [FIRST SECOND]", got) + } + lines := stderr.String() + first, second := strings.Index(lines, "Migration 1/2"), strings.Index(lines, "Migration 2/2") + if first < 0 || second < 0 || first > second { + t.Errorf("progress log order = %q, want 1/2 before 2/2", lines) + } +} + +func TestLoadAndValidateSendsDiagnosticsToStderr(t *testing.T) { + cases := []struct { + name string + domain string + wantErr bool + wantOutput string + }{ + { + name: "warning only", + domain: `project: + name: Warn App +database: postgresql +enums: + Unused: [A, B] +entities: + User: + fields: + id: uuid [primary] +`, + wantOutput: "enum is declared but never used", + }, + { + name: "hard error is returned once", + domain: `project: + name: Bad App +database: postgresql +entities: + User: + fields: + id: uuid + email: string +`, + wantErr: true, + }, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "domain.yaml") + if err := os.WriteFile(path, []byte(tt.domain), 0o644); err != nil { + t.Fatal(err) + } + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + + _, err := loadAndValidate(&cliOptions{domainFile: path}, cmd) + if tt.wantErr != (err != nil) { + t.Fatalf("err = %v, want error = %v", err, tt.wantErr) + } + if stdout.Len() != 0 { + t.Errorf("diagnostics leaked to stdout: %q", stdout.String()) + } + if tt.wantOutput != "" && !strings.Contains(stderr.String(), tt.wantOutput) { + t.Errorf("stderr = %q, want %q", stderr.String(), tt.wantOutput) + } + if tt.wantErr { + // The error is aggregated and must not also be printed here. + if strings.Contains(stderr.String(), "validation failed") { + t.Errorf("hard errors were printed instead of returned: %q", stderr.String()) + } + if strings.Count(err.Error(), "User") == 0 { + t.Errorf("aggregated error lost its details: %q", err.Error()) + } + } + }) + } +} + +func TestCommandLoggerWritesToStderr(t *testing.T) { + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + + commandLogger(cmd).Info("progress") + if stdout.Len() != 0 { + t.Errorf("stdout = %q, want empty", stdout.String()) + } + if !strings.Contains(stderr.String(), "progress") { + t.Errorf("stderr = %q, want progress", stderr.String()) + } +} + +func TestRootCommandSuppressesCobraErrorNoise(t *testing.T) { + root := newRootCommand() + if !root.SilenceUsage || !root.SilenceErrors { + t.Fatalf("SilenceUsage=%v SilenceErrors=%v, want both true", root.SilenceUsage, root.SilenceErrors) + } + + cases := []struct { + name string + command string // empty = root + args []string + admin bool // --admin flag is present, so one positional arg is its value + wantErr bool + }{ + {"root rejects positional argument", "", []string{"extra"}, false, true}, + {"validate rejects positional argument", "validate", []string{"extra"}, false, true}, + {"bridges rejects positional argument", "bridges", []string{"extra"}, false, true}, + {"update rejects positional argument", "update", []string{"extra"}, false, true}, + {"init rejects positional argument", "init", []string{"extra"}, false, true}, + {"generate rejects bare positional argument", "generate", []string{"admin-alpine"}, false, true}, + {"generate allows one admin argument", "generate", []string{"admin-alpine"}, true, false}, + {"generate rejects two arguments", "generate", []string{"a", "b"}, false, true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + cmd := root + if tt.command != "" { + var found *cobra.Command + for _, sub := range root.Commands() { + if sub.Name() == tt.command { + found = sub + break + } + } + if found == nil { + t.Fatalf("subcommand %q not found", tt.command) + } + cmd = found + } + if tt.admin { + if err := cmd.Flags().Set("admin", "admin-alpine"); err != nil { + t.Fatal(err) + } + } + err := cmd.Args(cmd, tt.args) + if tt.wantErr != (err != nil) { + t.Fatalf("Args(%v) = %v, want error = %v", tt.args, err, tt.wantErr) + } + }) + } +} + +func TestCommandTreesHaveIndependentFlags(t *testing.T) { + validDomain := func(name string) string { + return `project: + name: ` + name + ` +database: postgresql +entities: + User: + fields: + id: uuid [primary] +` + } + path := filepath.Join(t.TempDir(), "tree-a.yaml") + if err := os.WriteFile(path, []byte(validDomain("Tree A")), 0o644); err != nil { + t.Fatal(err) + } + + first := newRootCommand() + first.SetOut(io.Discard) + first.SetErr(io.Discard) + first.SetArgs([]string{"validate", "--domain", path}) + if err := first.Execute(); err != nil { + t.Fatalf("first tree: %v", err) + } + + second := newRootCommand() + if got := second.PersistentFlags().Lookup("domain").Value.String(); got != defaultDomainFile { + t.Errorf("second tree domain flag = %q, want %q", got, defaultDomainFile) + } + if got := second.PersistentFlags().Lookup("output").Value.String(); got != defaultOutputDir { + t.Errorf("second tree output flag = %q, want %q", got, defaultOutputDir) + } +} + +func TestExecutePrintsErrorOnce(t *testing.T) { + oldArgs, oldNewRoot := os.Args, newRootCommandFn + os.Args = []string{"domaincraft", "validate", "--domain", filepath.Join(t.TempDir(), "missing.yaml")} + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + newRootCommandFn = func() *cobra.Command { + root := newRootCommand() + root.SetErr(w) + return root + } + t.Cleanup(func() { + os.Args, newRootCommandFn = oldArgs, oldNewRoot + _ = w.Close() + _ = r.Close() + }) + + if err := Execute(); err == nil { + t.Fatal("expected Execute to return the validation error") + } + _ = w.Close() + out, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + got := string(out) + if n := strings.Count(got, "read domain file"); n != 1 { + t.Errorf("error printed %d times, want 1: %q", n, got) + } + if strings.Contains(got, "Usage:") { + t.Errorf("usage was printed despite SilenceUsage: %q", got) + } +} diff --git a/cmd/domaincraft/commands_infra_test.go b/cmd/domaincraft/commands_infra_test.go new file mode 100644 index 0000000..d48a19b --- /dev/null +++ b/cmd/domaincraft/commands_infra_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +func TestBuildStampsOnlyExactTags(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "Makefile")) + if err != nil { + t.Fatal(err) + } + body := string(data) + // Whitespace between the git arguments is formatting, not policy: both + // checks stay token-exact (abbrev is still forbidden, exact-match required). + abbrevTag := regexp.MustCompile(`describe\s+--tags\s+--abbrev(?:=|\s+)`) + if abbrevTag.MatchString(body) { + t.Fatal("Makefile still stamps the nearest tag onto an untagged commit") + } + exactTag := regexp.MustCompile(`describe\s+--tags\s+--exact-match\b`) + if !exactTag.MatchString(body) { + t.Fatal("Makefile does not use an exact tag match") + } +} + +func TestToolVersionsLiveInMakefile(t *testing.T) { + ci, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "ci.yml")) + if err != nil { + t.Fatal(err) + } + body := string(ci) + duplicatedTool := regexp.MustCompile(`golangci-lint-action\s*@|govulncheck\s*@v`) + if duplicatedTool.MatchString(body) { + t.Fatal("CI still duplicates tool versions instead of calling the Makefile targets") + } +} + +func TestReleaseUsesSameTestGate(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "release.yml")) + if err != nil { + t.Fatal(err) + } + // \s+ tolerates reformatting while the flag values stay exact: -count=10 + // or -shuffle=only must not satisfy this gate. + ciTestFlags := regexp.MustCompile(`go\s+test\s+-race\s+-count=1\s+-shuffle=on\s+\./\.\.\.`) + if !ciTestFlags.MatchString(string(data)) { + t.Fatal("release workflow does not use the CI test flags") + } +} + +func TestMainPackageHasSingleDocComment(t *testing.T) { + data, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + packageDoc := regexp.MustCompile(`//\s+Package\s+main\b`) + if packageDoc.MatchString(string(data)) { + t.Fatal("main.go repeats the package doc comment from commands.go") + } +} + +func TestInvalidBridgeRefIsUsageError(t *testing.T) { + err := usageOnInvalidBridgeRef(bridge.ErrInvalidRef) + if !errors.Is(err, errUsage) { + t.Fatalf("invalid bridge ref exit code = runtime error, want usage error: %v", err) + } + runtimeErr := errors.New("clone failed") + if got := usageOnInvalidBridgeRef(runtimeErr); !errors.Is(got, runtimeErr) || errors.Is(got, errUsage) { + t.Fatalf("runtime error was remapped to a usage error: %v", got) + } +} + +func TestApplyAddonsWarnsOnUnknownName(t *testing.T) { + var stderr bytes.Buffer + log := logger.New() + log.SetWriter(&stderr) + project := &ir.Project{} + applyAddons(&cliOptions{addons: "dapr, daprx"}, project, log) + if !project.Addons["dapr"] { + t.Fatal("known addon was not applied") + } + if !strings.Contains(stderr.String(), "unknown addon \"daprx\"") { + t.Fatalf("unknown addon produced no warning: %q", stderr.String()) + } +} diff --git a/cmd/domaincraft/init_test.go b/cmd/domaincraft/commands_init_test.go similarity index 92% rename from cmd/domaincraft/init_test.go rename to cmd/domaincraft/commands_init_test.go index e6ad6a1..54c87bf 100644 --- a/cmd/domaincraft/init_test.go +++ b/cmd/domaincraft/commands_init_test.go @@ -11,6 +11,17 @@ import ( "gopkg.in/yaml.v3" ) +func TestRenderScenarioRejectsControlCharacters(t *testing.T) { + for _, name := range []string{"bad\nname", "bad\rname", "bad\x00name"} { + if _, err := renderScenario("shop", name); err == nil { + t.Errorf("renderScenario(%q) accepted a control character", name) + } + } + if _, err := renderScenario("shop", "O'Brien"); err != nil { + t.Errorf("valid name with an apostrophe was rejected: %v", err) + } +} + func runInit(t *testing.T, args ...string) (string, error) { t.Helper() cmd := newRootCommand() diff --git a/cmd/domaincraft/lock_test.go b/cmd/domaincraft/commands_lock_test.go similarity index 89% rename from cmd/domaincraft/lock_test.go rename to cmd/domaincraft/commands_lock_test.go index 83402ff..c74ec47 100644 --- a/cmd/domaincraft/lock_test.go +++ b/cmd/domaincraft/commands_lock_test.go @@ -9,6 +9,8 @@ import ( func TestWriteDomainLock(t *testing.T) { root := t.TempDir() + // The bridge package recognises a monorepo by its module marker. + mustWriteFile(t, filepath.Join(root, "go.mod"), "module github.com/DomainCraft/DomainCraft\n") // A monorepo-located bridge (csharp-core → bridges/csharp/core). mp := filepath.Join(root, "bridges", "csharp", "core") @@ -66,8 +68,8 @@ func TestWriteDomainLock(t *testing.T) { if second.Path != "" || second.Source != "" { t.Errorf("my-bridge should have neither path nor source: %+v", second) } - if second.ContractVersion != 1 { - t.Errorf("my-bridge contract_version = %d, want default 1", second.ContractVersion) + if second.ContractVersion != 2 { + t.Errorf("my-bridge contract_version = %d, want default 2", second.ContractVersion) } } diff --git a/cmd/domaincraft/commands_notify_test.go b/cmd/domaincraft/commands_notify_test.go new file mode 100644 index 0000000..838c511 --- /dev/null +++ b/cmd/domaincraft/commands_notify_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +func TestCachedLatestCoreVersion(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + ops := defaultUpdateOps() + ops.latestForNotice = func() (*githubRelease, error) { + return decodeRelease([]byte(`{"tag_name":"v9.9.9","assets":[]}`)) + } + + latest, err := cachedLatestCoreVersionWithOps(ops) + if err != nil { + t.Fatalf("cachedLatestCoreVersion: %v", err) + } + if latest != "9.9.9" { + t.Fatalf("latest = %q, want 9.9.9", latest) + } + + // Network is now down — the fresh cache must still serve the same version. + ops.latestForNotice = func() (*githubRelease, error) { + return nil, fmt.Errorf("network down") + } + latest2, err := cachedLatestCoreVersionWithOps(ops) + if err != nil || latest2 != "9.9.9" { + t.Errorf("cached latest = %q, %v; want 9.9.9", latest2, err) + } +} + +// Regression: an offline check used to leave no cache entry, so every later +// command waited for the full HTTP timeout again. +func TestCachedLatestCoreVersionCachesFailedCheck(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + calls := 0 + ops := defaultUpdateOps() + ops.latestForNotice = func() (*githubRelease, error) { + calls++ + return nil, fmt.Errorf("network down") + } + + if _, err := cachedLatestCoreVersionWithOps(ops); err == nil { + t.Fatal("expected the first check to return an error") + } + // The failed attempt is cached as an empty result: no notice and no second + // network wait. + latest, err := cachedLatestCoreVersionWithOps(ops) + if err != nil || latest != "" { + t.Fatalf("second check = %q, %v; want empty result without error", latest, err) + } + if calls != 1 { + t.Fatalf("network calls = %d, want 1 (failed attempt must be cached)", calls) + } +} + +func TestNoticeClientHasShortTimeout(t *testing.T) { + if noticeClient.Timeout > 2*time.Second { + t.Errorf("notice timeout = %v, want at most 2s", noticeClient.Timeout) + } + if noticeClient.Timeout == httpClient.Timeout { + t.Errorf("notice client shares the download timeout %v", httpClient.Timeout) + } +} + +func TestCachedLatestCoreVersionSurfacesCacheWriteFailure(t *testing.T) { + base := t.TempDir() + appdir.SetBaseForTesting(base) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + cacheDir := appdir.CacheDir("core") + if err := os.MkdirAll(filepath.Join(cacheDir, "core-update.json"), 0o755); err != nil { + t.Fatal(err) + } + ops := defaultUpdateOps() + ops.latestForNotice = func() (*githubRelease, error) { + return decodeRelease([]byte(`{"tag_name":"v9.9.9","assets":[]}`)) + } + if _, err := cachedLatestCoreVersionWithOps(ops); err == nil { + t.Fatal("cache write failure was silently discarded") + } +} diff --git a/cmd/domaincraft/commands_prune_test.go b/cmd/domaincraft/commands_prune_test.go new file mode 100644 index 0000000..5aa0312 --- /dev/null +++ b/cmd/domaincraft/commands_prune_test.go @@ -0,0 +1,477 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/DomainCraft/DomainCraft/internal/interactive" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/internal/snapshot" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +// TestApplyMigrationActionsRewritesFieldRenames covers the --prune branch that +// rewrites identifiers in developer-owned files. Progress goes through the +// logger (stderr); stdout stays reserved for command data. +func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { + root := t.TempDir() + opts := &cliOptions{outputDir: root, prune: true} + + custom := filepath.Join(root, "src", "ItemService.cs") + if err := os.MkdirAll(filepath.Dir(custom), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(custom, []byte("class ItemService { public string Title; var title = 1; }"), 0o644); err != nil { + t.Fatal(err) + } + + diff := &snapshot.Diff{FieldRenames: []snapshot.FieldRename{{ + Entity: "Item", + OldField: "title", + NewField: "name", + CustomFiles: []string{"src/ItemService.cs"}, + }}} + + cmd := &cobra.Command{} + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + log := logger.New() + log.SetWriter(&stderr) + + applied, err := applyMigrationActions(opts, diff, map[string]bool{}, log, cmd) + if err != nil || !applied { + t.Fatalf("applyMigrationActions = %v, %v; want true, nil", applied, err) + } + data, err := os.ReadFile(custom) + if err != nil { + t.Fatal(err) + } + if string(data) != "class ItemService { public string Name; var name = 1; }" { + t.Fatalf("custom file not rewritten: %q", data) + } + if !strings.Contains(stderr.String(), "updated field title -> name") { + t.Fatalf("progress missing from stderr: %q", stderr.String()) + } + if stdout.Len() != 0 { + t.Fatalf("progress leaked to stdout: %q", stdout.String()) + } +} + +func TestBridgeCommandsAllowed(t *testing.T) { + tests := []struct { + name string + community bool + allow bool + want bool + }{ + {name: "official bridge", community: false, allow: false, want: true}, + {name: "community bridge without consent", community: true, allow: false, want: false}, + {name: "community bridge with consent", community: true, allow: true, want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := bridgeCommandsAllowed(tt.community, tt.allow); got != tt.want { + t.Fatalf("bridgeCommandsAllowed(%v, %v) = %v, want %v", tt.community, tt.allow, got, tt.want) + } + }) + } +} + +func TestChooseMigrationFiles(t *testing.T) { + files := []snapshot.FileRef{{Path: "src/A.cs"}, {Path: "src/B.cs"}} + + t.Run("prune selects every file without prompting", func(t *testing.T) { + opts := &cliOptions{prune: true} + + selected, err := chooseMigrationFiles(opts, files, func([]interactive.FileChoice) ([]string, error) { + t.Fatal("prompt must not be called in --prune mode") + return nil, nil + }) + if err != nil || len(selected) != 2 || !selected["src/A.cs"] || !selected["src/B.cs"] { + t.Fatalf("selected = %v, %v", selected, err) + } + }) + + t.Run("prompt result is respected", func(t *testing.T) { + opts := &cliOptions{} + + selected, err := chooseMigrationFiles(opts, files, func(choices []interactive.FileChoice) ([]string, error) { + if len(choices) != 2 { + t.Fatalf("choices = %d, want 2", len(choices)) + } + return []string{"src/B.cs"}, nil + }) + if err != nil || len(selected) != 1 || !selected["src/B.cs"] { + t.Fatalf("selected = %v, %v", selected, err) + } + }) +} + +// --- hermetic CLI fixtures for --prune orchestration --- + +// pruneBridge writes a minimal bridge with one regenerated and one scaffolded +// (overwrite: false) template. The optional migrations block is appended as-is. +func pruneBridge(t *testing.T, migrations string) string { + t.Helper() + dir := t.TempDir() + write := func(rel, content string) { + t.Helper() + p := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + write("bridge.yaml", `name: fixture-bridge +version: "1.0.0" +output_dir: generated +templates: + - for: entity + source: templates/generated.tmpl + target: "src/{{ .Entity.Name }}.g.txt" + - for: entity + source: templates/custom.tmpl + target: "src/{{ .Entity.Name }}Service.txt" + overwrite: false +`+migrations) + write("templates/generated.tmpl", "generated {{ .Entity.Name }}\n") + write("templates/custom.tmpl", "class {{ .Entity.Name }}Service { {{ .Entity.Name }} id; }\n") + return dir +} + +func pruneDomainText(entity string) string { + return "project:\n name: Fixture\ndatabase: postgresql\nentities:\n" + entity +} + +func pruneEntity(name string) string { + return " " + name + ":\n fields:\n id: uuid [primary]\n" +} + +func writeDomainFile(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "domain.yaml") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func runPruneCLI(t *testing.T, domainPath, bridgeDir, output string, extra ...string) (string, string, error) { + t.Helper() + oldVersion := version + version = "dev" + t.Cleanup(func() { version = oldVersion }) + + cmd := newRootCommand() + var stdout, stderr strings.Builder + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + args := []string{"generate", "--domain", domainPath, "--bridge", bridgeDir, "--output", output, "--non-interactive"} + args = append(args, extra...) + cmd.SetArgs(args) + err := cmd.Execute() + return stdout.String(), stderr.String(), err +} + +func writePruneSnapshot(t *testing.T, output string, snap *snapshot.Snapshot) { + t.Helper() + data, err := json.Marshal(snap) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(output, snapshot.DirName), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(snapshot.Path(output), data, 0o644); err != nil { + t.Fatal(err) + } +} + +func readPruneSnapshot(t *testing.T, output string) *snapshot.Snapshot { + t.Helper() + snap, err := snapshot.Load(snapshot.Path(output)) + if err != nil { + t.Fatal(err) + } + if snap == nil { + t.Fatal("no snapshot on disk") + } + return snap +} + +func requireFile(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(data) +} + +func requireAbsent(t *testing.T, path string) { + t.Helper() + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("%s should not exist (stat err = %v)", path, err) + } +} + +// TestPruneCLIOrphanCleanup drives the whole generate pipeline with a seeded +// snapshot: deleted orphan, renamed custom file and freshly regenerated file. +func TestPruneCLIOrphanCleanup(t *testing.T) { + tests := []struct { + name string + prepare func(t *testing.T, bridge, output string) string + check func(t *testing.T, output string) + }{ + { + name: "deleted orphan file removed", + prepare: func(t *testing.T, bridge, output string) string { + generateFixture(t, pruneDomainText(pruneEntity("Old")), bridge, output) + return writeDomainFile(t, pruneDomainText(pruneEntity("Keep"))) + }, + check: func(t *testing.T, output string) { + requireAbsent(t, filepath.Join(output, "src", "Old.g.txt")) + requireAbsent(t, filepath.Join(output, "src", "OldService.txt")) + requireFile(t, filepath.Join(output, "src", "Keep.g.txt")) + snap := readPruneSnapshot(t, output) + if _, ok := snap.Entities["Old"]; ok { + t.Error("deleted entity still in snapshot") + } + if _, ok := snap.Entities["Keep"]; !ok { + t.Error("new entity missing from snapshot") + } + }, + }, + { + name: "renamed custom file renamed with content rewritten", + prepare: func(t *testing.T, bridge, output string) string { + generateFixture(t, pruneDomainText(pruneEntity("Old")), bridge, output) + custom := filepath.Join(output, "src", "OldService.txt") + if err := os.WriteFile(custom, []byte("class OldService { Old id; }\n"), 0o644); err != nil { + t.Fatal(err) + } + next := " New:\n old_name: Old\n fields:\n id: uuid [primary]\n" + return writeDomainFile(t, pruneDomainText(next)) + }, + check: func(t *testing.T, output string) { + requireAbsent(t, filepath.Join(output, "src", "OldService.txt")) + requireAbsent(t, filepath.Join(output, "src", "Old.g.txt")) + content := requireFile(t, filepath.Join(output, "src", "NewService.txt")) + if !strings.Contains(content, "class NewService") || !strings.Contains(content, "New id") { + t.Fatalf("renamed custom file kept stale identifiers: %q", content) + } + snap := readPruneSnapshot(t, output) + state, ok := snap.Entities["New"] + if !ok || state.OldName != "Old" { + t.Fatalf("snapshot rename state = %+v, %v", state, ok) + } + }, + }, + { + name: "regenerated file is never deleted", + prepare: func(t *testing.T, bridge, output string) string { + generateFixture(t, pruneDomainText(pruneEntity("Keep")), bridge, output) + // Point a deleted entity's snapshot at a file this run rewrites. + snap := readPruneSnapshot(t, output) + snap.Entities["Old"] = snapshot.EntityState{Fields: map[string]string{"id": "uuid"}} + snap.Files = append(snap.Files, renderer.RenderedFile{Path: "src/Keep.g.txt", Entity: "Old"}) + writePruneSnapshot(t, output, snap) + if err := os.WriteFile(filepath.Join(output, "src", "Keep.g.txt"), []byte("stale"), 0o644); err != nil { + t.Fatal(err) + } + return writeDomainFile(t, pruneDomainText(pruneEntity("Keep"))) + }, + check: func(t *testing.T, output string) { + if got := requireFile(t, filepath.Join(output, "src", "Keep.g.txt")); got != "generated Keep\n" { + t.Fatalf("fresh file was removed or not regenerated: %q", got) + } + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + bridge := pruneBridge(t, "") + output := t.TempDir() + domainPath := tt.prepare(t, bridge, output) + stdout, stderr, err := runPruneCLI(t, domainPath, bridge, output, "--prune") + if err != nil { + t.Fatalf("generate --prune failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr) + } + if strings.Contains(stdout, " ▸") { + t.Errorf("progress leaked to stdout: %q", stdout) + } + tt.check(t, output) + }) + } +} + +// TestPruneCLICleanupFailureKeepsSnapshot asserts the F01 contract at the CLI +// level: a failed rewrite or delete under --prune returns an error and leaves +// the previous snapshot untouched, so a later run can retry the cleanup. +func TestPruneCLICleanupFailureKeepsSnapshot(t *testing.T) { + tests := []struct { + name string + domain string + entity string + fields map[string]string + file renderer.RenderedFile + wantDiag string + }{ + { + name: "failed field rewrite", + domain: " Item:\n fields:\n id: uuid [primary]\n name: string [old_name:title]\n", + entity: "Item", + fields: map[string]string{"title": "string"}, + file: renderer.RenderedFile{Path: "src/LegacyService.txt", Entity: "Item", Custom: true}, + wantDiag: "rewrite field references in src/LegacyService.txt", + }, + { + name: "failed orphan delete", + domain: pruneEntity("Keep"), + entity: "Old", + fields: map[string]string{"id": "uuid"}, + file: renderer.RenderedFile{Path: "src/OldService.txt", Entity: "Old", Custom: true}, + wantDiag: "delete src/OldService.txt", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + bridge := pruneBridge(t, "") + output := t.TempDir() + writePruneSnapshot(t, output, &snapshot.Snapshot{ + FormatVersion: snapshot.FormatVersion, + Bridge: "SENTINEL", + ProjectNamespace: "Fixture", + Entities: map[string]snapshot.EntityState{tt.entity: {Fields: tt.fields}}, + Files: []renderer.RenderedFile{tt.file}, + }) + // A non-empty directory cannot be read as a file or removed with + // os.Remove: both cleanup paths fail without touching the network. + blocked := filepath.Join(output, filepath.FromSlash(tt.file.Path)) + if err := os.MkdirAll(blocked, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(blocked, "child"), []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + + domainPath := writeDomainFile(t, pruneDomainText(tt.domain)) + stdout, stderr, err := runPruneCLI(t, domainPath, bridge, output, "--prune") + if err == nil { + t.Fatalf("generate --prune should fail; stdout: %s", stdout) + } + // Under --prune the failure is returned once (Execute prints it as + // "Error: ..."), not warned about and then returned again. + if !strings.Contains(err.Error(), tt.wantDiag) { + t.Errorf("err = %q, want %q (stderr: %q)", err, tt.wantDiag, stderr) + } + if strings.Contains(stderr, "could not ") { + t.Errorf("cleanup failure was warned about twice: %q", stderr) + } + if got := readPruneSnapshot(t, output).Bridge; got != "SENTINEL" { + t.Errorf("snapshot was advanced past failed cleanup: bridge = %q", got) + } + }) + } +} + +// TestPruneCLICommunityConsentGate checks the gate decision without running +// any bridge-declared shell command. +func TestPruneCLICommunityConsentGate(t *testing.T) { + const migrations = `migrations: + enabled: true + commands: + - "echo blocked > gate.txt" +` + marker := func(output string) string { return filepath.Join(output, "gate.txt") } + + t.Run("prune never auto-runs community migrations", func(t *testing.T) { + bridge := pruneBridge(t, migrations) + output := t.TempDir() + generateFixture(t, pruneDomainText(pruneEntity("Old")), bridge, output) + domainPath := writeDomainFile(t, pruneDomainText(pruneEntity("Keep"))) + stdout, stderr, err := runPruneCLI(t, domainPath, bridge, output, "--prune") + if err != nil { + t.Fatalf("generate --prune: %v\n%s", err, stderr) + } + if !strings.Contains(stderr, "community bridge(s)") { + t.Errorf("missing gate warning: %q", stderr) + } + if strings.Contains(stdout, "Applying 1 database migration command(s)") { + t.Errorf("community migration was reviewed for execution: %q", stdout) + } + requireAbsent(t, marker(output)) + }) + + t.Run("migrate without consent is rejected", func(t *testing.T) { + bridge := pruneBridge(t, migrations) + output := t.TempDir() + domainPath := writeDomainFile(t, pruneDomainText(pruneEntity("Keep"))) + stdout, _, err := runPruneCLI(t, domainPath, bridge, output, "--migrate") + if err == nil || !strings.Contains(err.Error(), "--allow-bridge-commands") { + t.Fatalf("err = %v, want consent error", err) + } + if strings.Contains(stdout, "Applying 1 database migration command(s)") { + t.Errorf("migration command was reviewed without consent: %q", stdout) + } + entries, err := os.ReadDir(output) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Errorf("consent rejected after writing files: %v", entries) + } + requireAbsent(t, marker(output)) + }) +} + +// TestPruneCLIReportStreams asserts that all human-facing output — warnings, +// progress and the multi-line refactoring reports — goes to stderr, leaving +// stdout clean for piping. +func TestPruneCLIReportStreams(t *testing.T) { + bridge := pruneBridge(t, "") + output := t.TempDir() + custom := filepath.Join(output, "src", "ItemService.txt") + if err := os.MkdirAll(filepath.Dir(custom), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(custom, []byte("class ItemService { string title; string note; }\n"), 0o644); err != nil { + t.Fatal(err) + } + writePruneSnapshot(t, output, &snapshot.Snapshot{ + FormatVersion: snapshot.FormatVersion, + Bridge: "fixture-bridge", + ProjectNamespace: "Fixture", + Entities: map[string]snapshot.EntityState{ + "Item": {Fields: map[string]string{"title": "string", "note": "string"}}, + }, + Files: []renderer.RenderedFile{{Path: "src/ItemService.txt", Entity: "Item", Custom: true}}, + }) + domain := " Item:\n fields:\n id: uuid [primary]\n name: string [old_name:title]\n note: int\n" + domainPath := writeDomainFile(t, pruneDomainText(domain)) + + stdout, stderr, err := runPruneCLI(t, domainPath, bridge, output, "--prune") + if err != nil { + t.Fatalf("generate --prune: %v\n%s", err, stderr) + } + for _, want := range []string{"You changed data types in domain.yaml", "You renamed fields in domain.yaml", "ACTION REQUIRED", "updated field title -> name"} { + if !strings.Contains(stderr, want) { + t.Errorf("diagnostic missing from stderr: %q; stderr = %q", want, stderr) + } + } + if stdout != "" { + t.Errorf("human-facing output leaked to stdout: %q", stdout) + } +} diff --git a/cmd/domaincraft/regression_csharp_role_test.go b/cmd/domaincraft/commands_regression_csharp_role_test.go similarity index 98% rename from cmd/domaincraft/regression_csharp_role_test.go rename to cmd/domaincraft/commands_regression_csharp_role_test.go index b2fe03b..8db1fe4 100644 --- a/cmd/domaincraft/regression_csharp_role_test.go +++ b/cmd/domaincraft/commands_regression_csharp_role_test.go @@ -12,7 +12,7 @@ import ( // Regression: a role declared as `string` used to render as `string.Admin` // in generated C# tests, which does not compile. func TestGeneratedCSharpTestsHandleStringRole(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"versions":["10.0.0"]}`)) })) defer srv.Close() diff --git a/cmd/domaincraft/regression_ts_package_test.go b/cmd/domaincraft/commands_regression_ts_package_test.go similarity index 100% rename from cmd/domaincraft/regression_ts_package_test.go rename to cmd/domaincraft/commands_regression_ts_package_test.go diff --git a/cmd/domaincraft/commands_test.go b/cmd/domaincraft/commands_test.go index 4364faa..db53b28 100644 --- a/cmd/domaincraft/commands_test.go +++ b/cmd/domaincraft/commands_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "errors" "os" "path/filepath" "strings" @@ -10,17 +11,18 @@ import ( func TestVersionFlag(t *testing.T) { cmd := newRootCommand() - output := &bytes.Buffer{} - cmd.SetOut(output) - cmd.SetErr(output) + stdout := &bytes.Buffer{} + stderr := &bytes.Buffer{} + cmd.SetOut(stdout) + cmd.SetErr(stderr) cmd.SetArgs([]string{"--version"}) if err := cmd.Execute(); err != nil { t.Fatalf("--version failed: %v", err) } - if !strings.Contains(output.String(), "version") { - t.Fatalf("expected version in output, got %q", output.String()) + if !strings.Contains(stdout.String(), "version") { + t.Fatalf("expected version on stdout, got %q", stdout.String()) } } @@ -41,16 +43,21 @@ entities: } cmd := newRootCommand() - output := &bytes.Buffer{} - cmd.SetOut(output) - cmd.SetErr(output) + stdout := &bytes.Buffer{} + stderr := &bytes.Buffer{} + cmd.SetOut(stdout) + cmd.SetErr(stderr) cmd.SetArgs([]string{"validate", "--domain", domainPath}) if err := cmd.Execute(); err != nil { - t.Fatalf("validate command failed: %v\noutput: %s", err, output.String()) + t.Fatalf("validate command failed: %v\nstderr: %s", err, stderr.String()) } - if !strings.Contains(output.String(), "Schema valid") { - t.Fatalf("expected 'Schema valid' in output, got: %s", output.String()) + // The CLI logger writes progress and diagnostics to stderr; stdout stays data-only. + if !strings.Contains(stderr.String(), "Schema valid") { + t.Fatalf("expected 'Schema valid' on stderr, got: %s", stderr.String()) + } + if strings.Contains(stdout.String(), "Schema valid") { + t.Fatalf("diagnostics must not leak to stdout, got: %s", stdout.String()) } } @@ -75,14 +82,32 @@ entities: } cmd := newRootCommand() - output := &bytes.Buffer{} - cmd.SetOut(output) - cmd.SetErr(output) + stdout := &bytes.Buffer{} + stderr := &bytes.Buffer{} + cmd.SetOut(stdout) + cmd.SetErr(stderr) cmd.SetArgs([]string{"generate", "--domain", domainPath, "--bridge", bridgeDir, "--output", outputDirPath}) - // Should fail because bridge doesn't exist - if err := cmd.Execute(); err == nil { - t.Fatalf("generate command should fail with nonexistent bridge") + // executeRoot (not cmd.Execute) is the path that prints the single error + // to stderr and tags CLI misuse with errUsage (exit code 2 in main). + err := executeRoot(cmd) + if err == nil { + t.Fatal("generate command should fail with nonexistent bridge") + } + if !errors.Is(err, errUsage) { + t.Errorf("error = %v, want usage error (exit code 2)", err) + } + if !strings.Contains(stderr.String(), "bridge") { + t.Errorf("stderr does not name the bridge: %q", stderr.String()) + } + // Bridge resolution fails before the renderer runs, so no files may land + // in the requested output directory. + if entries, readErr := os.ReadDir(outputDirPath); readErr == nil { + if len(entries) != 0 { + t.Errorf("output dir has %d entries after a usage error: %v", len(entries), entries) + } + } else if !errors.Is(readErr, os.ErrNotExist) { + t.Fatalf("read output dir: %v", readErr) } } @@ -92,3 +117,7 @@ func mustExist(t *testing.T, path string) { t.Fatalf("expected %s to exist: %v", path, err) } } + +func TestMustExist(t *testing.T) { + mustExist(t, os.Args[0]) +} diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go new file mode 100644 index 0000000..4fe15fa --- /dev/null +++ b/cmd/domaincraft/commands_update_security_test.go @@ -0,0 +1,688 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/netutil" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +const ( + assetURLBase = "https://github.com/" + coreRepo + "/releases/download/v1.2.0/" +) + +func updateAssetURL(name string) string { return assetURLBase + name } + +func fakeUpdateServer(tag string, assets map[string]string, bodies map[string][]byte) func(string) ([]byte, error) { + release := fakeReleases(tag, assets) + return func(rawURL string) ([]byte, error) { + if rawURL == releasesLatestURL { + return release(rawURL) + } + if body, ok := bodies[rawURL]; ok { + return body, nil + } + return nil, fmt.Errorf("unexpected url %s", rawURL) + } +} + +// stubUpdateRun installs offline dependencies for the self-update path. +func stubUpdateRun(t *testing.T, current string, serve func(string) ([]byte, error)) (*bytes.Buffer, *int, *[]byte, updateOps) { + t.Helper() + oldVersion := version + version = current + t.Cleanup(func() { version = oldVersion }) + + calls := 0 + var installed []byte + ops := defaultUpdateOps() + ops.getBody = serve + ops.executable = func() (string, error) { return filepath.Join(t.TempDir(), "domaincraft"), nil } + ops.replaceExecutable = func(tmp, _ string) error { + calls++ + data, err := os.ReadFile(tmp) + if err != nil { + return err + } + installed = data + return nil + } + out := &bytes.Buffer{} + log := logger.New() + log.SetWriter(out) + return out, &calls, &installed, ops +} + +func TestValidateReleaseURL(t *testing.T) { + cases := []struct { + name string + raw string + wantErr bool + }{ + {"github asset", updateAssetURL("dc"), false}, + {"api endpoint", releasesLatestURL, false}, + {"plain http", "http://github.com/DomainCraft/DomainCraft/releases/latest", true}, + {"unknown host", "https://evil.example/dc", true}, + {"lookalike host", "https://github.com.evil.example/dc", true}, + {"userinfo", "https://user:secret@github.com/dc", true}, + {"query", updateAssetURL("dc") + "?token=secret", true}, + {"fragment", updateAssetURL("dc") + "#frag", true}, + {"non-standard port", "https://github.com:8443/dc", true}, + {"malformed", "https://[::1", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + got, err := validateReleaseURL(tt.raw) + if tt.wantErr != (err != nil) { + t.Fatalf("validateReleaseURL(%q) = %q, %v; want error = %v", tt.raw, got, err, tt.wantErr) + } + if !tt.wantErr && got != tt.raw { + t.Errorf("URL = %q, want %q", got, tt.raw) + } + }) + } +} + +func TestRedactURL(t *testing.T) { + // D3: all callers now use the strictest format — scheme and host only. + cases := []struct { + name string + raw string + want string + }{ + {"credentials and query", "https://user:secret@github.com/dc?token=abc#f", "https://github.com"}, + {"plain", updateAssetURL("dc"), "https://github.com"}, + {"port is dropped", "https://github.com:8443/dc", "https://github.com"}, + {"malformed", "https://[::1", ""}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := netutil.RedactedURL(tt.raw); got != tt.want { + t.Errorf("netutil.RedactedURL = %q, want %q", got, tt.want) + } + }) + } +} + +func TestValidateReleaseRedirectRejectsCredentials(t *testing.T) { + u, err := url.Parse("https://user:secret@objects.githubusercontent.com/asset") + if err != nil { + t.Fatal(err) + } + if err := validateReleaseRedirect(u); err == nil { + t.Fatal("redirect with userinfo was accepted") + } + clean, err := url.Parse("https://objects.githubusercontent.com/asset?sig=abc") + if err != nil { + t.Fatal(err) + } + if err := validateReleaseRedirect(clean); err != nil { + t.Fatalf("signed asset redirect rejected: %v", err) + } +} + +func TestReadResponseBodyRejectsOversizedPayload(t *testing.T) { + limit := int64(4) + + u, err := url.Parse(updateAssetURL("dc")) + if err != nil { + t.Fatal(err) + } + cases := []struct { + name string + body string + want string + wantErr bool + }{ + {"exact limit", "1234", "1234", false}, + {"one byte over", "12345", "", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(tt.body)), + Request: &http.Request{URL: u}, + } + got, err := netutil.ReadBoundedBody(resp, u.String(), limit, validateReleaseRedirect) + if tt.wantErr { + if err == nil || !strings.Contains(err.Error(), "exceeds") { + t.Fatalf("err = %v, want oversized error", err) + } + return + } + if err != nil || string(got) != tt.want { + t.Fatalf("body = %q, %v; want %q", got, err, tt.want) + } + }) + } +} + +func TestReadResponseBodyChecksRedirectHost(t *testing.T) { + cases := []struct { + name string + finalURL string + wantErrPart string + }{ + {"signed github asset redirect", "https://objects.githubusercontent.com/asset?X-Amz-Signature=abc", ""}, + {"foreign redirect", "https://evil.example/asset", "redirect from"}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + u, err := url.Parse(tt.finalURL) + if err != nil { + t.Fatal(err) + } + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader("ok")), + Request: &http.Request{URL: u}, + } + _, err = netutil.ReadBoundedBody(resp, updateAssetURL("dc"), defaultUpdateOps().maxBodyBytes, validateReleaseRedirect) + if tt.wantErrPart == "" { + if err != nil { + t.Fatalf("netutil.ReadBoundedBody: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.wantErrPart) { + t.Fatalf("err = %v, want %q", err, tt.wantErrPart) + } + }) + } +} + +type contextCheckingTransport struct { + ctxErr error + called bool +} + +func (tr *contextCheckingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + tr.called = true + tr.ctxErr = req.Context().Err() + return nil, errors.New("transport stopped") +} + +func TestHTTPGetBodyUsesCommandContext(t *testing.T) { + oldClient, oldCtx := httpClient, bridge.CommandContext() + t.Cleanup(func() { + httpClient = oldClient + bridge.SetCommandContext(oldCtx) + }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + bridge.SetCommandContext(ctx) + transport := &contextCheckingTransport{} + httpClient = &http.Client{Transport: transport} + + if _, err := httpGetBody(releasesLatestURL); err == nil { + t.Fatal("expected request error") + } + if !transport.called { + t.Fatal("transport was not called") + } + if !errors.Is(transport.ctxErr, context.Canceled) { + t.Errorf("request context error = %v, want context.Canceled", transport.ctxErr) + } +} + +type fixedStatusTransport struct{ status int } + +func (tr fixedStatusTransport) RoundTrip(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: tr.status, + Body: io.NopCloser(strings.NewReader("")), + Request: req, + }, nil +} + +func TestHTTPGetBodyRedactsURLInErrors(t *testing.T) { + oldClient := httpClient + t.Cleanup(func() { httpClient = oldClient }) + httpClient = &http.Client{Transport: fixedStatusTransport{status: http.StatusForbidden}} + + _, err := httpGetBody("https://user:secret@github.com/dc?token=abc") + if err == nil { + t.Fatal("expected http error") + } + got := err.Error() + if strings.Contains(got, "secret") || strings.Contains(got, "token=abc") { + t.Errorf("error leaked credentials or query: %q", got) + } +} + +func TestReleaseChecksum(t *testing.T) { + asset := assetName() + sum := digestHex("binary") + assets := map[string]string{ + asset: updateAssetURL(asset), + checksumsAssetName: updateAssetURL(checksumsAssetName), + } + cases := []struct { + name string + body string + want string + wantErr bool + }{ + {"plain shasum line", fmt.Sprintf("%s %s\n", sum, asset), sum, false}, + {"binary marker", fmt.Sprintf("%s *%s\n", sum, asset), sum, false}, + {"missing asset", "other " + sum + "\n", "", true}, + {"malformed digest", "nothex " + asset + "\n", "", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + ops := defaultUpdateOps() + ops.getBody = fakeUpdateServer("v1.2.0", assets, map[string][]byte{ + updateAssetURL(checksumsAssetName): []byte(tt.body), + }) + + rel := &githubRelease{ + TagName: "v1.2.0", + Assets: []struct { + Name string `json:"name"` + BrowserDownloadURL string `json:"browser_download_url"` + }{ + {Name: asset, BrowserDownloadURL: updateAssetURL(asset)}, + {Name: checksumsAssetName, BrowserDownloadURL: updateAssetURL(checksumsAssetName)}, + }, + } + got, err := releaseChecksumWithOps(ops, rel, asset) + if tt.wantErr != (err != nil) { + t.Fatalf("releaseChecksum = %q, %v; want error = %v", got, err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Errorf("checksum = %q, want %q", got, tt.want) + } + }) + } +} + +func TestVerifyFileSHA256(t *testing.T) { + path := filepath.Join(t.TempDir(), "binary") + if err := os.WriteFile(path, []byte("binary"), 0o644); err != nil { + t.Fatal(err) + } + cases := []struct { + name string + want string + wantErr bool + }{ + {"matching digest", digestHex("binary"), false}, + {"wrong digest", digestHex("other"), true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + err := verifyFileSHA256(path, tt.want) + if tt.wantErr != (err != nil) { + t.Fatalf("verifyFileSHA256 = %v, want error = %v", err, tt.wantErr) + } + }) + } +} + +func TestRunCoreUpdateFailsClosed(t *testing.T) { + asset := assetName() + goodSum := digestHex("new-binary-content") + validAssets := map[string]string{ + asset: updateAssetURL(asset), + checksumsAssetName: updateAssetURL(checksumsAssetName), + } + checksums := []byte(fmt.Sprintf("%s %s\n", goodSum, asset)) + + cases := []struct { + name string + assets map[string]string + sums []byte + binary []byte + wantErrPart string + wantReplace bool + }{ + { + name: "valid checksum installs binary", + assets: validAssets, + sums: checksums, + binary: []byte("new-binary-content"), + wantReplace: true, + }, + { + name: "checksum mismatch blocks replacement", + assets: validAssets, + sums: []byte(fmt.Sprintf("%s %s\n", digestHex("attacker"), asset)), + binary: []byte("new-binary-content"), + wantErrPart: "checksum mismatch", + }, + { + name: "untrusted asset host blocks replacement", + assets: map[string]string{asset: "https://evil.example/dc", checksumsAssetName: updateAssetURL(checksumsAssetName)}, + sums: checksums, + binary: []byte("new-binary-content"), + wantErrPart: "refusing download", + }, + { + name: "missing checksums asset blocks replacement", + assets: map[string]string{asset: updateAssetURL(asset)}, + binary: []byte("new-binary-content"), + wantErrPart: "checksums.txt", + }, + { + name: "malformed checksum blocks replacement", + assets: validAssets, + sums: []byte("not-a-sha " + asset + "\n"), + binary: []byte("new-binary-content"), + wantErrPart: "invalid sha-256 checksum", + }, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + bodies := map[string][]byte{} + for _, u := range tt.assets { + if strings.HasSuffix(u, checksumsAssetName) && tt.sums != nil { + bodies[u] = tt.sums + } + if strings.HasSuffix(u, "/"+asset) { + bodies[u] = tt.binary + } + } + _, calls, installed, ops := stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", tt.assets, bodies)) + err := runCoreUpdateWithOps(ops, logger.New(), false) + if tt.wantErrPart != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErrPart) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErrPart) + } + } else if err != nil { + t.Fatalf("runCoreUpdate: %v", err) + } + wantCalls := 0 + if tt.wantReplace { + wantCalls = 1 + if !bytes.Equal(*installed, tt.binary) { + t.Errorf("installed = %q, want %q", *installed, tt.binary) + } + } + if *calls != wantCalls { + t.Errorf("replace calls = %d, want %d", *calls, wantCalls) + } + }) + } +} + +// --- F03: failed installs must be reported, never presented as success --- + +func stubFileOps(t *testing.T) updateOps { + t.Helper() + return defaultUpdateOps() +} + +func updatePayload(binary []byte) (map[string]string, map[string][]byte) { + asset := assetName() + assets := map[string]string{ + asset: updateAssetURL(asset), + checksumsAssetName: updateAssetURL(checksumsAssetName), + } + bodies := map[string][]byte{ + updateAssetURL(asset): binary, + updateAssetURL(checksumsAssetName): []byte(digestHex(string(binary)) + " " + asset + "\n"), + } + return assets, bodies +} + +func TestDownloadBinaryChmodFailure(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("executable bit is not set on Windows") + } + ops := stubFileOps(t) + ops.getBody = func(string) ([]byte, error) { return []byte("binary"), nil } + + chmodErr := errors.New("chmod denied") + ops.chmod = func(string, os.FileMode) error { return chmodErr } + path, err := downloadBinaryWithOps(ops, "https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64", t.TempDir()) + if !errors.Is(err, chmodErr) || !strings.Contains(err.Error(), "make downloaded update executable") { + t.Fatalf("err = %v, want chmod failure", err) + } + if path != "" { + t.Errorf("path = %q, want no installed binary", path) + } +} + +// TestReplaceExecutableUsesSameVolumeTemp guards the EXDEV fix: the download +// temp must be created next to the running executable, not in the OS temp dir. +func TestReplaceExecutableUsesSameVolumeTemp(t *testing.T) { + oldVersion := version + t.Cleanup(func() { version = oldVersion }) + ops := defaultUpdateOps() + + root := t.TempDir() + exe := filepath.Join(root, "domaincraft") + assets, bodies := updatePayload([]byte("new binary")) + version = "1.0.0" + ops.getBody = fakeUpdateServer("v1.2.0", assets, bodies) + ops.executable = func() (string, error) { return exe, nil } + + var tempDir, installedFrom string + ops.createTemp = func(dir, pattern string) (*os.File, error) { + tempDir = dir + return os.CreateTemp(dir, pattern) + } + ops.replaceExecutable = func(tmp, gotExe string) error { + installedFrom = tmp + if gotExe != exe { + t.Errorf("replace target = %q, want %q", gotExe, exe) + } + return nil + } + + log := logger.New() + log.SetWriter(io.Discard) + if err := runCoreUpdateWithOps(ops, log, false); err != nil { + t.Fatalf("runCoreUpdate: %v", err) + } + if tempDir != root { + t.Fatalf("CreateTemp dir = %q, want the executable directory %q", tempDir, root) + } + if filepath.Dir(installedFrom) != root { + t.Errorf("temp binary %q is not next to the executable %q", installedFrom, exe) + } +} + +func TestReplaceExecutableJoinsRenameFailures(t *testing.T) { + ops := stubFileOps(t) + root := t.TempDir() + tmp, exe := filepath.Join(root, "new"), filepath.Join(root, "domaincraft") + if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + + directErr := errors.New("direct rename failed") + installErr := errors.New("install rename failed") + restoreErr := errors.New("restore failed") + calls := 0 + ops.rename = func(src, dst string) error { + calls++ + switch calls { + case 1: + return directErr + case 2: + return os.Rename(src, dst) // move the locked binary aside + case 3: + return installErr + case 4: + return restoreErr + default: + t.Fatalf("unexpected rename call %d", calls) + return nil + } + } + + err := replaceExecutableWithOps(ops, tmp, exe) + if err == nil { + t.Fatal("expected a hard error") + } + for _, want := range []string{directErr.Error(), installErr.Error(), restoreErr.Error(), exe + ".old"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q is missing %q", err.Error(), want) + } + } +} + +func TestReplaceExecutableRestoresOriginalOnInstallFailure(t *testing.T) { + ops := stubFileOps(t) + root := t.TempDir() + tmp, exe := filepath.Join(root, "new"), filepath.Join(root, "domaincraft") + if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + + calls := 0 + ops.rename = func(src, dst string) error { + calls++ + if calls == 1 || calls == 3 { + return errors.New("rename failed") + } + return os.Rename(src, dst) + } + err := replaceExecutableWithOps(ops, tmp, exe) + if err == nil || !strings.Contains(err.Error(), exe+".old") { + t.Fatalf("err = %v, want failure naming the backup path", err) + } + if got := string(mustReadFile(t, exe)); got != "old" { + t.Errorf("original binary was not restored: %q", got) + } +} + +func TestReplaceExecutableRemoveOldFailure(t *testing.T) { + ops := stubFileOps(t) + root := t.TempDir() + tmp, exe := filepath.Join(root, "new"), filepath.Join(root, "domaincraft") + if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + + ops.remove = func(path string) error { + if path == exe+".old" { + return errors.New("backup is locked") + } + return os.Remove(path) + } + ops.rename = func(src, _ string) error { + if src == tmp { + return errors.New("locked") + } + t.Error("no rename should happen when the backup cannot be removed") + return nil + } + err := replaceExecutableWithOps(ops, tmp, exe) + if err == nil || !strings.Contains(err.Error(), exe+".old") || !strings.Contains(err.Error(), "backup is locked") { + t.Fatalf("err = %v, want backup removal failure naming %s", err, exe+".old") + } +} + +func TestReplaceExecutableFinalCleanupFailure(t *testing.T) { + ops := stubFileOps(t) + root := t.TempDir() + tmp, exe := filepath.Join(root, "new"), filepath.Join(root, "domaincraft") + if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + + renames := 0 + ops.rename = func(src, dst string) error { + renames++ + if renames == 1 { + return errors.New("locked") + } + return os.Rename(src, dst) + } + removals := 0 + ops.remove = func(path string) error { + removals++ + if removals == 2 { + return errors.New("backup cleanup failed") + } + return os.Remove(path) + } + err := replaceExecutableWithOps(ops, tmp, exe) + if err == nil || !strings.Contains(err.Error(), exe+".old") { + t.Fatalf("err = %v, want cleanup failure naming %s", err, exe+".old") + } + if got := string(mustReadFile(t, exe)); got != "new" { + t.Errorf("new binary was not installed: %q", got) + } +} + +func mustReadFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return data +} + +func TestCoreUpdateLogsSuccessOnlyAfterReplace(t *testing.T) { + assets, bodies := updatePayload([]byte("new-binary-content")) + + t.Run("failed replace", func(t *testing.T) { + _, _, _, ops := stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", assets, bodies)) + replaceErr := errors.New("disk full") + calls := 0 + ops.replaceExecutable = func(string, string) error { + calls++ + return replaceErr + } + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + err := runCoreUpdateWithOps(ops, log, false) + if !errors.Is(err, replaceErr) { + t.Fatalf("err = %v, want %v", err, replaceErr) + } + if strings.Contains(logOut.String(), "Updated to") { + t.Errorf("success logged before the binary was installed: %q", logOut.String()) + } + if calls != 1 { + t.Errorf("replace calls = %d, want 1", calls) + } + }) + + t.Run("successful replace", func(t *testing.T) { + _, calls, installed, ops := stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", assets, bodies)) + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + err := runCoreUpdateWithOps(ops, log, false) + if err != nil { + t.Fatalf("runCoreUpdate: %v", err) + } + if *calls != 1 || string(*installed) != "new-binary-content" { + t.Fatalf("replace calls = %d, installed = %q", *calls, *installed) + } + if !strings.Contains(logOut.String(), "Updated to v1.2.0") { + t.Errorf("missing success message: %q", logOut.String()) + } + }) +} diff --git a/cmd/domaincraft/update_test.go b/cmd/domaincraft/commands_update_test.go similarity index 74% rename from cmd/domaincraft/update_test.go rename to cmd/domaincraft/commands_update_test.go index ffcd9dd..74d0602 100644 --- a/cmd/domaincraft/update_test.go +++ b/cmd/domaincraft/commands_update_test.go @@ -10,7 +10,7 @@ import ( "github.com/DomainCraft/DomainCraft/pkg/logger" ) -// fakeReleases returns an httpGetBodyFn that serves a fixed release payload. +// fakeReleases returns a getBody function that serves a fixed release payload. func fakeReleases(tag string, assets map[string]string) func(string) ([]byte, error) { var sb strings.Builder sb.WriteString(`{"tag_name":"` + tag + `","assets":[`) @@ -23,12 +23,12 @@ func fakeReleases(tag string, assets map[string]string) func(string) ([]byte, er sb.WriteString(`{"name":"` + name + `","browser_download_url":"` + url + `"}`) } sb.WriteString("]}") - return func(url string) ([]byte, error) { + return func(_ string) ([]byte, error) { return []byte(sb.String()), nil } } -func runUpdateCheck(t *testing.T, setVersion string) (string, error) { +func runUpdateCheck(t *testing.T, ops updateOps, setVersion string) (string, error) { t.Helper() old := version version = setVersion @@ -37,19 +37,18 @@ func runUpdateCheck(t *testing.T, setVersion string) (string, error) { buf := &bytes.Buffer{} log := logger.New() log.SetWriter(buf) - err := runCoreUpdate(log, true) + err := runCoreUpdateWithOps(ops, log, true) return buf.String(), err } func TestUpdateDevBuildDoesNotCheck(t *testing.T) { - oldHTTP := httpGetBodyFn - httpGetBodyFn = func(url string) ([]byte, error) { + ops := defaultUpdateOps() + ops.getBody = func(url string) ([]byte, error) { t.Fatalf("network must not be contacted for a dev build (url=%s)", url) return nil, nil } - defer func() { httpGetBodyFn = oldHTTP }() - out, err := runUpdateCheck(t, "dev") + out, err := runUpdateCheck(t, ops, "dev") if err != nil { t.Fatalf("runCoreUpdate: %v", err) } @@ -59,13 +58,12 @@ func TestUpdateDevBuildDoesNotCheck(t *testing.T) { } func TestUpdateCheckUpToDate(t *testing.T) { - oldHTTP := httpGetBodyFn - httpGetBodyFn = fakeReleases("v1.0.0", map[string]string{ + ops := defaultUpdateOps() + ops.getBody = fakeReleases("v1.0.0", map[string]string{ "domaincraft-linux-amd64": "https://example/dc-linux-amd64", }) - defer func() { httpGetBodyFn = oldHTTP }() - out, err := runUpdateCheck(t, "v1.0.0") + out, err := runUpdateCheck(t, ops, "v1.0.0") if err != nil { t.Fatalf("runCoreUpdate: %v", err) } @@ -75,13 +73,12 @@ func TestUpdateCheckUpToDate(t *testing.T) { } func TestUpdateCheckReportsNewer(t *testing.T) { - oldHTTP := httpGetBodyFn - httpGetBodyFn = fakeReleases("v1.2.0", map[string]string{ + ops := defaultUpdateOps() + ops.getBody = fakeReleases("v1.2.0", map[string]string{ "domaincraft-linux-amd64": "https://example/dc-linux-amd64", }) - defer func() { httpGetBodyFn = oldHTTP }() - out, err := runUpdateCheck(t, "v1.0.0") + out, err := runUpdateCheck(t, ops, "v1.0.0") if err != nil { t.Fatalf("runCoreUpdate: %v", err) } @@ -94,11 +91,10 @@ func TestUpdateCheckReportsNewer(t *testing.T) { } func TestUpdateCheckSamePatch(t *testing.T) { - oldHTTP := httpGetBodyFn - httpGetBodyFn = fakeReleases("v1.0.0", map[string]string{}) - defer func() { httpGetBodyFn = oldHTTP }() + ops := defaultUpdateOps() + ops.getBody = fakeReleases("v1.0.0", map[string]string{}) - out, err := runUpdateCheck(t, "v1.0.0") + out, err := runUpdateCheck(t, ops, "v1.0.0") if err != nil { t.Fatalf("runCoreUpdate: %v", err) } @@ -134,24 +130,23 @@ func TestReleaseAssetFor(t *testing.T) { } func TestDownloadAndReplace(t *testing.T) { - oldHTTP := httpGetBodyFn - httpGetBodyFn = func(url string) ([]byte, error) { + ops := defaultUpdateOps() + ops.getBody = func(_ string) ([]byte, error) { return []byte("new-binary-content"), nil } - defer func() { httpGetBodyFn = oldHTTP }() - tmp, err := downloadBinary("https://example/dc") + tmp, err := downloadBinaryWithOps(ops, "https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64", t.TempDir()) if err != nil { t.Fatalf("downloadBinary: %v", err) } - defer os.Remove(tmp) + defer func() { _ = os.Remove(tmp) }() // Replace a non-running target so the rename path is exercised directly. target := filepath.Join(t.TempDir(), "domaincraft.exe") if err := os.WriteFile(target, []byte("old-binary"), 0o644); err != nil { t.Fatal(err) } - if err := replaceExecutable(tmp, target); err != nil { + if err := replaceExecutableWithOps(ops, tmp, target); err != nil { t.Fatalf("replaceExecutable: %v", err) } got, err := os.ReadFile(target) diff --git a/cmd/domaincraft/commands_version_test.go b/cmd/domaincraft/commands_version_test.go new file mode 100644 index 0000000..4735efc --- /dev/null +++ b/cmd/domaincraft/commands_version_test.go @@ -0,0 +1,25 @@ +package main + +import "testing" + +func TestResolveVersion(t *testing.T) { + cases := []struct { + name, stamped, buildInfo, want string + }{ + {"stamped wins", "v0.5.0", "v0.5.0", "v0.5.0"}, + {"go install clean tag", "dev", "v0.5.0", "v0.5.0"}, + {"local build", "dev", "(devel)", "dev"}, + {"pseudo-version", "dev", "v0.5.1-0.20260821125410-876219469a43", "dev"}, + {"pseudo-version with metadata", "dev", "v0.5.1-0.20260821125410-876219469a43+dirty", "dev"}, + {"no build info", "dev", "", "dev"}, + {"empty stamp clean tag", "", "v0.5.0", "v0.5.0"}, + {"empty stamp devel", "", "(devel)", "dev"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := resolveVersion(c.stamped, c.buildInfo); got != c.want { + t.Errorf("resolveVersion(%q, %q) = %q, want %q", c.stamped, c.buildInfo, got, c.want) + } + }) + } +} diff --git a/cmd/domaincraft/extends_test.go b/cmd/domaincraft/extends_test.go deleted file mode 100644 index 9915880..0000000 --- a/cmd/domaincraft/extends_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package main - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/DomainCraft/DomainCraft/internal/bridge" - "github.com/DomainCraft/DomainCraft/pkg/logger" -) - -// writeBridgeDir scaffolds a minimal bridge directory (just a bridge.yaml, -// optionally declaring `extends:`) and returns its absolute path. -func writeBridgeDir(t *testing.T, dir, extends string) string { - t.Helper() - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatalf("mkdir %s: %v", dir, err) - } - content := "name: " + filepath.Base(dir) + "\n" - if extends != "" { - content += "extends: " + extends + "\n" - } - path := filepath.Join(dir, "bridge.yaml") - if err := os.WriteFile(path, []byte(content), 0o644); err != nil { - t.Fatalf("write %s: %v", path, err) - } - return dir -} - -func TestResolveBaseChainOrdersOutermostBaseFirst(t *testing.T) { - root := t.TempDir() - - c := writeBridgeDir(t, filepath.Join(root, "bridge-c"), "") - b := writeBridgeDir(t, filepath.Join(root, "bridge-b"), c) - a := writeBridgeDir(t, filepath.Join(root, "bridge-a"), b) - - chain, err := resolveBaseChain(a, b, logger.New()) - if err != nil { - t.Fatalf("resolveBaseChain: %v", err) - } - - if len(chain) != 2 { - t.Fatalf("chain = %v, want the two bases (the adapter itself is not part of the chain)", chain) - } - if chain[0] != c || chain[1] != b { - t.Errorf("chain = %v, want [%s %s] (deepest base first)", chain, c, b) - } -} - -func TestResolveBaseChainDetectsCycle(t *testing.T) { - root := t.TempDir() - - b := writeBridgeDir(t, filepath.Join(root, "bridge-b"), "") - a := writeBridgeDir(t, filepath.Join(root, "bridge-a"), b) - // Close the cycle: B now extends A while A extends B. - writeBridgeDir(t, filepath.Join(root, "bridge-b"), a) - - _, err := resolveBaseChain(a, b, logger.New()) - if err == nil { - t.Fatal("expected a cycle error") - } - if !strings.Contains(err.Error(), "cycle") { - t.Errorf("err = %v, want it to mention the cycle", err) - } -} - -func TestResolveExtendsRefPrefersLocalCheckout(t *testing.T) { - root := t.TempDir() - resolver := bridge.NewResolver(bridge.Default()) - - // Registry ID whose repo checkout sits next to the extending bridge - // (monorepo sibling layout) — must resolve locally without cloning. - sibling := writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp"), "") - - got, err := bridge.ResolveExtendsRef("csharp-restful", filepath.Join(root, "adapter"), resolver) - if err != nil { - t.Fatalf("resolveExtendsRef: %v", err) - } - if abs, _ := filepath.Abs(got); abs != sibling { - t.Errorf("resolved = %q, want the sibling checkout %q", got, sibling) - } - - // CI layout: the base bridge checked out inside the adapter's directory. - innerRoot := t.TempDir() - innerAdapter := filepath.Join(innerRoot, "adapter") - inner := writeBridgeDir(t, filepath.Join(innerAdapter, "domaincraft-bridge-csharp"), "") - - got, err = bridge.ResolveExtendsRef("csharp-restful", innerAdapter, resolver) - if err != nil { - t.Fatalf("resolveExtendsRef: %v", err) - } - if abs, _ := filepath.Abs(got); abs != inner { - t.Errorf("resolved = %q, want the in-directory checkout %q", got, inner) - } -} - -func TestResolveExtendsRefPrefersMonorepoLayout(t *testing.T) { - root := t.TempDir() - resolver := bridge.NewResolver(bridge.Default()) - - // Monorepo layout: /bridges/csharp/core for the csharp-core bridge. - mp := writeBridgeDir(t, filepath.Join(root, "bridges", "csharp", "core"), "") - - // Distractor sibling checkout with the legacy repo name — must NOT win now. - writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp-core"), "") - - got, err := bridge.ResolveExtendsRef("csharp-core", filepath.Join(root, "adapter"), resolver) - if err != nil { - t.Fatalf("resolveExtendsRef: %v", err) - } - if abs, _ := filepath.Abs(got); abs != mp { - t.Errorf("resolved = %q, want the monorepo bridge %q", got, mp) - } - - // A bridge with a multi-segment path: csharp-efcore → csharp/persistence/efcore. - ef := writeBridgeDir(t, filepath.Join(root, "bridges", "csharp", "persistence", "efcore"), "") - got, err = bridge.ResolveExtendsRef("csharp-efcore", filepath.Join(root, "adapter"), resolver) - if err != nil { - t.Fatalf("bridge.ResolveExtendsRef(efcore): %v", err) - } - if abs, _ := filepath.Abs(got); abs != ef { - t.Errorf("resolved = %q, want %q", got, ef) - } -} - -func TestResolveExtendsRefFallsBackWhenNoMonorepo(t *testing.T) { - root := t.TempDir() - resolver := bridge.NewResolver(bridge.Default()) - sibling := writeBridgeDir(t, filepath.Join(root, "domaincraft-bridge-csharp"), "") - got, err := bridge.ResolveExtendsRef("csharp-restful", filepath.Join(root, "adapter"), resolver) - if err != nil { - t.Fatalf("resolveExtendsRef: %v", err) - } - if abs, _ := filepath.Abs(got); abs != sibling { - t.Errorf("resolved = %q, want legacy sibling %q", got, sibling) - } -} - -func TestVersionDelta(t *testing.T) { - cases := []struct { - name string - u *bridge.Update - want string - }{ - {"nil update", nil, ""}, - {"unknown local version", &bridge.Update{}, ""}, - {"known local version", &bridge.Update{LocalVersion: "1.2.3"}, "(v1.2.3 available)"}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - if got := versionDelta(c.u); got != c.want { - t.Errorf("versionDelta = %q, want %q", got, c.want) - } - }) - } -} diff --git a/cmd/domaincraft/init.go b/cmd/domaincraft/init.go index 74c5848..e960923 100644 --- a/cmd/domaincraft/init.go +++ b/cmd/domaincraft/init.go @@ -62,7 +62,10 @@ func scenarioTemplate(id string) (string, bool) { func renderScenario(id, name string) (string, error) { tmpl, ok := scenarioTemplate(id) if !ok { - return "", fmt.Errorf("unknown scenario %q: use shop, saas, crm or blog", id) + return "", asUsageError(fmt.Errorf("unknown scenario %q: use shop, saas, crm or blog", id)) + } + if strings.ContainsFunc(name, func(r rune) bool { return r < 0x20 || r == 0x7f }) { + return "", asUsageError(fmt.Errorf("invalid project name: control characters are not allowed")) } escaped := strings.ReplaceAll(name, "'", "''") return strings.ReplaceAll(tmpl, "{{PROJECT_NAME}}", escaped), nil @@ -78,7 +81,7 @@ func defaultProjectName() string { return filepath.Base(wd) } -func newInitCmd() *cobra.Command { +func newInitCmd(opts *cliOptions) *cobra.Command { var scenarioFlag string var nameFlag string var force bool @@ -88,19 +91,20 @@ func newInitCmd() *cobra.Command { Short: "Bootstrap a starter domain.yaml and generate code", Long: "Choose a scenario (shop, saas, crm, blog), write a starter domain.yaml and generate code.\n" + "Non-interactive runs require --scenario. Add --bridge to generate immediately; without it the model is written and the generate command is printed.", - RunE: func(cmd *cobra.Command, args []string) error { + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { log := commandLogger(cmd) selected := scenarioFlag if selected == "" { - if nonInteractive || !interactive.IsTerminal() { - return fmt.Errorf("--scenario is required in non-interactive mode (shop|saas|crm|blog)") + if opts.nonInteractive || !isTerminal() { + return asUsageError(fmt.Errorf("--scenario is required in non-interactive mode (shop|saas|crm|blog)")) } options := make([]interactive.Option, 0, len(scenarios)) for _, s := range scenarios { options = append(options, interactive.Option{Label: s.label, Description: s.description}) } - idx, err := interactive.SelectOption("Select a starter scenario", "Writes "+domainFile+" and offers to generate", options) + idx, err := interactive.SelectOption("Select a starter scenario", "Writes "+opts.domainFile+" and offers to generate", options) if err != nil { return err } @@ -116,36 +120,53 @@ func newInitCmd() *cobra.Command { return err } - if _, err := os.Stat(domainFile); err == nil && !force { - return fmt.Errorf("%s already exists; use --force to overwrite", domainFile) - } else if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("check %s: %w", domainFile, err) + // O_EXCL is the authoritative guard against another process + // creating domain.yaml between the friendly Stat check and the + // atomic write. The guard file is replaced by AtomicWrite below. + if err := os.MkdirAll(filepath.Dir(opts.domainFile), 0o755); err != nil { //nolint:gosec // user-selected output directory + return fmt.Errorf("create parent of %s: %w", opts.domainFile, err) + } + flags := os.O_WRONLY | os.O_CREATE + if force { + flags |= os.O_TRUNC + } else { + flags |= os.O_EXCL + } + guard, err := os.OpenFile(opts.domainFile, flags, 0o644) //nolint:gosec // starter domain.yaml must stay readable like other project files + if err != nil { + if os.IsExist(err) { + return asUsageError(fmt.Errorf("%s already exists; use --force to overwrite", opts.domainFile)) + } + return fmt.Errorf("create %s: %w", opts.domainFile, err) + } + if err := guard.Close(); err != nil { + return fmt.Errorf("close %s: %w", opts.domainFile, err) } - if err := fsutil.AtomicWrite(domainFile, []byte(content)); err != nil { - return fmt.Errorf("write %s: %w", domainFile, err) + if err := fsutil.AtomicWrite(opts.domainFile, []byte(content)); err != nil { + return fmt.Errorf("write %s: %w", opts.domainFile, err) } - log.Success("Created %s from the %s scenario", domainFile, selected) + log.Success("Created %s from the %s scenario", opts.domainFile, selected) // Generate when explicitly requested, or after an interactive // confirmation. Non-interactive runs without --bridge stop here — // they cannot pick a bridge on the user's behalf. - generate := bridgePath != "" - if !generate && interactive.IsTerminal() && !nonInteractive { + generate := opts.bridgePath != "" + if !generate && !opts.nonInteractive && isTerminal() { generate, err = interactive.PromptYesNo("Generate code now?", "Runs domaincraft generate with the selected bridge") if err != nil { return err } } if !generate { - fmt.Fprintf(cmd.OutOrStdout(), "Next: domaincraft validate --domain %s\nthen: domaincraft generate --domain %s --bridge \n", domainFile, domainFile) + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Next: domaincraft validate --domain %s\nthen: domaincraft generate --domain %s --bridge \n", opts.domainFile, opts.domainFile) return nil } - genCmd := newGenerateCmd() + genCmd := newGenerateCmd(opts) genCmd.SetOut(cmd.OutOrStdout()) genCmd.SetErr(cmd.ErrOrStderr()) genCmd.SetIn(cmd.InOrStdin()) - return runGenerate(genCmd, nil) + return runGenerate(opts, genCmd) }, } diff --git a/cmd/domaincraft/main.go b/cmd/domaincraft/main.go index 736ef31..580eff3 100644 --- a/cmd/domaincraft/main.go +++ b/cmd/domaincraft/main.go @@ -1,5 +1,31 @@ package main +import ( + "context" + "errors" + "os" + "os/signal" + "syscall" + + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + func main() { - Execute() + // run returns an exit code instead of calling os.Exit, so signal.Notify's + // stop() defer runs before the process exits. + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + // One holder for every cancellable child: git, probes and migrations. + bridge.SetCommandContext(ctx) + if err := Execute(); err != nil { + if errors.Is(err, errUsage) { + return 2 + } + return 1 + } + return 0 } diff --git a/cmd/domaincraft/migration_actions.go b/cmd/domaincraft/migration_actions.go new file mode 100644 index 0000000..af34322 --- /dev/null +++ b/cmd/domaincraft/migration_actions.go @@ -0,0 +1,601 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "regexp" + "runtime" + "strings" + "unicode/utf8" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/interactive" + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/internal/snapshot" + "github.com/DomainCraft/DomainCraft/pkg/logger" + + "github.com/spf13/cobra" +) + +// planBridgeMigrations decides before any file is written whether bridge +// commands may run. Consent is an intent check: rejecting it after rendering +// would leave a partially updated project behind. +func planBridgeMigrations(ctx *commandContext, diff *snapshot.Diff, cfg *renderer.MigrationConfig) error { + autoMigrate := ctx.opts.prune && diff.HasSchemaChanges() + if autoMigrate && ctx.chainHasCommunity { + ctx.log.Warn("community bridge(s) in the resolved chain — not auto-running database migrations; use --migrate explicitly") + autoMigrate = false + } + ctx.migrationsPlanned = (ctx.opts.migrate || autoMigrate) && cfg != nil && cfg.Enabled + if ctx.migrationsPlanned && !bridgeCommandsAllowed(ctx.chainHasCommunity, ctx.opts.allowBridgeCommands) { + return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") + } + return nil +} + +func runBridgeDatabaseMigrations(ctx *commandContext, cfg *renderer.MigrationConfig) error { + if !ctx.cleanupApplied || !ctx.migrationsPlanned { + return nil + } + // The preflight above already decided this; keep the check as a guard + // against a caller that bypasses it. + if !bridgeCommandsAllowed(ctx.chainHasCommunity, ctx.opts.allowBridgeCommands) { + return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") + } + if err := runDatabaseMigrations(cfg, ctx.opts.outputDir, ctx.cmd, ctx.log); err != nil { + if ctx.opts.migrate { + // Explicit --migrate: a failed migration is a hard error. + return err + } + // Auto-migration under --prune is best-effort. In a docker/CI + // workflow the API container applies pending migrations at startup + // (Database:SchemaMode=migrate → MigrateAsync), so a host without + // the dotnet SDK or an unreachable database must not abort generation. + ctx.log.Warn("Database migration was not applied by --prune: %v", err) + ctx.log.Warn("In docker, set Database:SchemaMode=migrate — the container applies pending migrations on startup.") + } + return nil +} + +// applySchemaMigrations cleans up files orphaned by removed or renamed +// entities. Files written by this run are never touched. It reports whether +// all actions were applied: deferred cleanup keeps the previous snapshot. +func applySchemaMigrations(ctx *commandContext, diff *snapshot.Diff, manifest []renderer.RenderedFile) (bool, error) { + // Files written from this run must never be touched by cleanup. + fresh := make(map[string]bool) + for _, f := range manifest { + if f.Written { + fresh[f.Path] = true + } + } + return applyMigrationActions(ctx.opts, diff, fresh, ctx.log, ctx.cmd) +} + +// generateAdminPanel handles the optional --admin flag and renders the panel +// into the output directory. It returns the extra file manifest entries; an +// empty manifest means no panel was requested. +func generateAdminPanel(ctx *commandContext, irProject *ir.Project, seedData, mockDataset *ir.SeedDataset) ([]renderer.RenderedFile, error) { + // The optional `--admin ` value is reclaimed by the command's Args + // validator, before RunE starts writing files. + if ctx.opts.adminBridge == "" && !ctx.cmd.Flags().Changed("admin") && !ctx.opts.nonInteractive && isTerminal() { + generate, err := interactive.PromptGenerateAdmin() + if err != nil { + return nil, fmt.Errorf("prompt for admin panel: %w", err) + } + if generate { + ctx.opts.adminBridge = "admin-alpine" + } + } + if ctx.opts.adminBridge == "" { + return nil, nil + } + + resolver := newBridgeResolver(ctx.opts, ctx.log) + adminID := ctx.opts.adminBridge + + adminPath, err := resolver.Resolve(adminID) + if err != nil { + return nil, usageOnInvalidBridgeRef(fmt.Errorf("resolve admin bridge %q: %w", adminID, err)) + } + + ctx.log.Info("Rendering admin panel via %s", adminID) + // The admin bridge has no extends chain of its own and no schema-migration + // plan, so both stay explicitly empty. Success wording stays admin-specific. + adminFiles, adminManifest, _, err := renderBridge(irProject, renderOptions{ + path: adminPath, + outDir: ctx.opts.outputDir, + bases: nil, + plan: nil, + seedData: seedData, + mockDataset: mockDataset, + log: ctx.log, + }) + if err != nil { + return nil, err + } + + ctx.log.Success("Generated %d admin file(s)", len(adminFiles)) + return adminManifest, nil +} + +// renderOptions groups the renderer inputs that differ between the generate and +// admin paths. Empty Bases/Plan is explicit for the admin bridge, which has no +// extends chain and no schema-migration plan. +type renderOptions struct { + path string + outDir string + bases []string + plan *ir.MigrationPlan + seedData *ir.SeedDataset + mockDataset *ir.SeedDataset + log *logger.Logger +} + +// renderBridge performs the renderer setup shared by `generate` and the admin +// panel: New → AttachBases → SetMigration → SetSeedData → SetMockData → Render. +// The renderer is returned so the caller can read its declared migration config. +// Success logging stays with the callers because the two paths use different wording. +func newBridgeRenderer(o renderOptions) (*renderer.Renderer, error) { + r, err := renderer.New(o.path, o.log) + if err != nil { + return nil, err + } + if err := r.AttachBases(o.bases); err != nil { + return nil, err + } + r.SetMigration(o.plan) + r.SetSeedData(o.seedData) + r.SetMockData(o.mockDataset) + return r, nil +} + +func renderBridge(irProject *ir.Project, o renderOptions) ([]string, []renderer.RenderedFile, *renderer.Renderer, error) { + r, err := newBridgeRenderer(o) + if err != nil { + return nil, nil, nil, err + } + files, manifest, err := r.Render(irProject, o.outDir) + if err != nil { + return nil, nil, nil, err + } + return files, manifest, r, nil +} + +// bridgeCommandsAllowed reports whether shell lines from a community bridge +// may run. Official bundled bridges are trusted; community bridges need the +// explicit --allow-bridge-commands consent. +func bridgeCommandsAllowed(chainHasCommunity, allow bool) bool { + return !chainHasCommunity || allow +} + +// runDatabaseMigrations executes the bridge's declared database-migration +// commands in order, from the generated output directory. Commands are shell +// lines invoked through the platform shell so bridges can rely on standard +// tooling (e.g. `dotnet ef ...`). A failing command aborts the run. +func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *cobra.Command, log *logger.Logger) error { + if cfg == nil || !cfg.Enabled || len(cfg.Commands) == 0 { + return nil + } + // Migration progress and child-process output are diagnostics, not + // machine-readable data: stdout stays clean for piping. + out := cmd.ErrOrStderr() + // The resolved command lines are printed before they run, so the developer + // always sees exactly what will be executed (Phase 3.5 safety). Bridge YAML + // is untrusted input: strip terminal controls before showing or logging a + // command. Execution still uses the original line, unchanged. + _, _ = fmt.Fprintf(out, " Applying %d database migration command(s):\n", len(cfg.Commands)) + for i, command := range cfg.Commands { + _, _ = fmt.Fprintf(out, " %d) %s\n", i+1, sanitizeCommandLine(command)) + } + + // The signal context from main stays the parent: an interrupt still + // cancels the child at once. Add a deadline so a hung bridge command + // cannot block a generation run forever. An already-finished parent is + // passed through unchanged — no child starts anyway, and callers can + // observe the exact cancellation they installed. + parent := bridge.CommandContext() + migrationCtx := parent + if parent.Err() == nil { + var cancel context.CancelFunc + migrationCtx, cancel = context.WithTimeout(parent, databaseMigrationTimeout) + defer cancel() + } + + for i, command := range cfg.Commands { + log.Info("Migration %d/%d", i+1, len(cfg.Commands)) + var argv []string + var shell string + if runtime.GOOS == "windows" { + shell = "cmd" + argv = []string{"/C", command} + } else { + shell = "sh" + argv = []string{"-c", command} + } + c := execCommandFn(migrationCtx, shell, argv...) + c.Dir = outDir + // Output comes from a bridge-declared command and is untrusted. Keep + // newlines for readability, but strip control sequences and make + // invisible bidi/zero-width characters visible before displaying it. + var childOut bytes.Buffer + c.Stdout = &childOut + c.Stderr = &childOut + runErr := c.Run() + _, _ = io.WriteString(out, sanitizeStreamChunk(childOut.String())) + if runErr != nil { + if errors.Is(migrationCtx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("database migration %d (%s) timed out after %s: %w", i+1, sanitizeCommandLine(command), databaseMigrationTimeout, runErr) + } + return fmt.Errorf("database migration %d failed: %w", i+1, runErr) + } + } + log.Success("Database migrations applied") + return nil +} + +// ansiSequenceRe matches complete ESC-led terminal sequences: CSI, OSC and +// two-byte Fe controls. A bare ESC (no valid sequence) is dropped separately. +var ansiSequenceRe = regexp.MustCompile(`\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[@-_])`) + +// isInvisibleFormat reports Unicode format characters that can reorder, hide +// or join displayed text. Left as-is, one bridge-declared line can be rendered +// as several harmless-looking commands while the shell still executes the +// original string. Kept separate so the display policy has one source of truth. +func isInvisibleFormat(r rune) bool { + switch { + case r >= 0x200b && r <= 0x200f, // zero-width space, ZWNJ, ZWJ, LRM, RLM + r >= 0x202a && r <= 0x202e, // LRE, RLE, PDF, LRO, RLO + r >= 0x2060 && r <= 0x206f, // word joiner, invisible operators, LRI/RLI/FSI/PDI + r == 0x061c, // Arabic letter mark + r == 0xfeff: // zero-width no-break space / BOM + return true + } + return false +} + +// sanitizeStreamChunk applies the same display policy as sanitizeCommandLine to +// a child process' output, but keeps tabs and line breaks so progress stays +// readable. It is applied after the command finishes: splitting escape sequences +// across write chunks would make a streaming filter unreliable. +func sanitizeStreamChunk(s string) string { + s = ansiSequenceRe.ReplaceAllString(s, "") + var b strings.Builder + b.Grow(len(s)) + for _, r := range s { + switch { + case r == '\t' || r == '\n' || r == '\r': + b.WriteRune(r) + case r == 0x1b || r < 0x20 || (r >= 0x7f && r < 0xa0): + continue + case isInvisibleFormat(r): + fmt.Fprintf(&b, "", r) + default: + b.WriteRune(r) + } + } + return b.String() +} + +// sanitizeCommandLine removes terminal control characters from a bridge-declared +// command before it is displayed or logged. C0 (except tab and newline), C1, +// CSI/OSC sequences, bare ESC and invalid UTF-8 bytes are dropped. Tab and +// newline become visible "\t"/"\n" escapes; bidi and zero-width controls become +// visible "" tokens, so one line can never masquerade as several +// harmless commands. The command itself is never modified — only its +// presentation. +func sanitizeCommandLine(s string) string { + s = ansiSequenceRe.ReplaceAllString(s, "") + var b strings.Builder + b.Grow(len(s)) + for i := 0; i < len(s); { + c := s[i] + if c == 0x1b { // ESC without a complete sequence + i++ + continue + } + if c < utf8.RuneSelf { + switch c { + case '\t': + b.WriteString(`\t`) + case '\n': + b.WriteString(`\n`) + default: + if (c < 0x20) || c == 0x7f { + i++ + continue + } + b.WriteByte(c) + } + i++ + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 { // invalid byte + i++ + continue + } + if r >= 0x80 && r <= 0x9f { // C1 controls + i += size + continue + } + if isInvisibleFormat(r) { + fmt.Fprintf(&b, "", r) + i += size + continue + } + b.WriteString(s[i : i+size]) + i += size + } + return b.String() +} + +// migrationContext bundles the state shared by every cleanup handler. +type migrationContext struct { + opts *cliOptions + fresh map[string]bool + log *logger.Logger + out io.Writer // stdout: orphan lists are command data, progress goes to log + failures []error // hard failures under --prune, joined once at the end +} + +// fail applies the cleanup failure policy at one site. Under --prune the +// failure is recorded so the final errors.Join keeps the snapshot from +// advancing; other modes only warn and continue. Prompt errors never go through +// here — they are hard errors returned directly to the CLI boundary. +func (mc *migrationContext) fail(err error, what string) bool { + if mc.opts.prune { + mc.failures = append(mc.failures, fmt.Errorf("%s: %w", what, err)) + return true + } + mc.log.Warn("could not %s: %v", what, err) + return false +} + +// cleanupDeferred reports whether a run must keep cleanup pending: non-interactive +// (or no TTY) without --prune. The previous snapshot stays on disk so a later +// --prune run can still find the orphaned files. +func cleanupDeferred(opts *cliOptions) bool { + return !opts.prune && (opts.nonInteractive || !isTerminal()) +} + +// applyMigrationActions handles orphaned file cleanup for entities that were +// removed or renamed since the last generation. In interactive mode the user +// is prompted before touching custom (overwrite: false) files. With --prune +// everything is done automatically; otherwise (non-interactive) a warning is +// printed and nothing is modified. Files freshly written this run (fresh) are +// never touched. +// +// It returns whether all actions were applied. When cleanup was deferred +// (non-interactive without --prune) it returns false so the caller keeps the +// previous snapshot — otherwise orphaned files would be forgotten and a later +// --prune run could no longer find them. +// +// Under --prune a failed rewrite, delete or rename is a hard error: the caller +// must not advance the snapshot, or the failed cleanup becomes unrecoverable. +// Without --prune the advisory warn-and-continue behavior is preserved. +func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[string]bool, log *logger.Logger, cmd *cobra.Command) (bool, error) { + if diff == nil || diff.IsEmpty() { + return true, nil + } + mc := &migrationContext{opts: opts, fresh: fresh, log: log, out: cmd.OutOrStdout()} + + // In --prune mode the tool owns the whole cleanup, so it also rewrites + // identifier references in developer-owned files: the project's root + // namespace after a project rename, and renamed entity fields. Generated + // files are already regenerated with the new names; custom files are not, + // so this is what keeps them compiling. + if opts.prune { + if diff.NamespaceRename != nil { + for _, rel := range diff.NamespaceRename.Files { + if mc.fresh[rel] { + continue + } + rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.NamespaceTransform(diff.NamespaceRename)) + if err != nil { + mc.fail(err, fmt.Sprintf("rewrite namespace in %s", rel)) + continue + } + if rewrote { + mc.log.Info("updated namespace %s -> %s in %s", diff.NamespaceRename.OldNamespace, diff.NamespaceRename.NewNamespace, rel) + } + } + } + for _, fr := range diff.FieldRenames { + for _, rel := range fr.CustomFiles { + if mc.fresh[rel] { + continue + } + rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.FieldTransform(fr)) + if err != nil { + mc.fail(err, fmt.Sprintf("rewrite field references in %s", rel)) + continue + } + if rewrote { + mc.log.Info("updated field %s -> %s in %s", fr.OldField, fr.NewField, rel) + } + } + } + } + + // File-level failures are recorded in mc.failures and joined once at the + // end. A handler only returns an error for a prompt failure, which is hard. + applied := true + for _, del := range diff.Deleted { + if len(del.Files) == 0 { + continue + } + done, err := runCleanup( + mc, + del.Files, + func(choices []interactive.FileChoice) ([]string, error) { + return interactive.PromptDeleteFiles(del.Name, choices) + }, + fmt.Sprintf("Entity %q was removed from domain.yaml — orphaned files kept (re-run with --prune to delete):", del.Name), + fileLabel, + func(f snapshot.FileRef) { + if err := snapshot.DeleteFile(mc.opts.outputDir, f.Path); err != nil { + mc.fail(err, fmt.Sprintf("delete %s", f.Path)) + return + } + mc.log.Info("deleted %s", f.Path) + }, + ) + if err != nil { + return false, err + } + applied = applied && done + } + + for _, ren := range diff.Renamed { + if len(ren.Files) == 0 { + continue + } + done, err := handleRename(mc, ren, diff) + if err != nil { + return false, err + } + applied = applied && done + } + if err := errors.Join(mc.failures...); err != nil { + return false, err + } + return applied, nil +} + +// chooseMigrationFiles returns the files selected for cleanup. --prune takes +// all of them; otherwise the caller's prompt decides. The non-interactive +// fallback stays in the caller because its warning is operation-specific. +func chooseMigrationFiles(opts *cliOptions, files []snapshot.FileRef, prompt func([]interactive.FileChoice) ([]string, error)) (map[string]bool, error) { + selected := make(map[string]bool) + if opts.prune { + for _, f := range files { + selected[f.Path] = true + } + return selected, nil + } + choices := make([]interactive.FileChoice, len(files)) + for i, f := range files { + choices[i] = interactive.FileChoice{Path: f.Path, Label: fileLabel(f)} + } + picked, err := prompt(choices) + if err != nil { + return nil, err + } + for _, p := range picked { + selected[p] = true + } + return selected, nil +} + +// runCleanup owns the frame shared by the delete and rename handlers: defer +// cleanup with a warning when there is no prompt to ask, otherwise select the +// files, skip freshly generated ones and run opFn per file. Failures are +// recorded in mc.failures and joined once by the caller, so a handler returns +// an error only when the prompt itself failed. +func runCleanup( + mc *migrationContext, + files []snapshot.FileRef, + selectFiles func([]interactive.FileChoice) ([]string, error), + deferredWarning string, + deferredLine func(snapshot.FileRef) string, + opFn func(snapshot.FileRef), +) (bool, error) { + if cleanupDeferred(mc.opts) { + mc.log.Warn("%s", deferredWarning) + for _, f := range files { + _, _ = fmt.Fprintf(mc.out, " - %s\n", deferredLine(f)) + } + return false, nil + } + selected, err := chooseMigrationFiles(mc.opts, files, selectFiles) + if err != nil { + return false, err + } + + before := len(mc.failures) + for _, f := range files { + if !selected[f.Path] || mc.fresh[f.Path] { + continue + } + opFn(f) + } + return len(mc.failures) == before, nil +} + +// handleRename renames custom files after a prompt and removes stale generated +// files (they have been regenerated under the new entity name). In --prune mode +// the renamed files' contents are rewritten too (entity, namespace and field +// identifiers), so the developer-owned file keeps compiling after the rename. +// Returns false when cleanup was deferred (non-interactive without --prune). +func handleRename(mc *migrationContext, ren snapshot.Rename, d *snapshot.Diff) (bool, error) { + return runCleanup( + mc, + ren.Files, + func(choices []interactive.FileChoice) ([]string, error) { + return interactive.PromptRenameFiles(ren.OldName, ren.NewName, choices) + }, + fmt.Sprintf("Entity %q was renamed to %q — files kept (re-run with --prune to rename):", ren.OldName, ren.NewName), + func(f snapshot.FileRef) string { + return f.Path + " -> " + snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName) + }, + func(f snapshot.FileRef) { + if f.Custom { + newRel := snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName) + if mc.fresh[newRel] { + // The destination was scaffolded this run by the custom + // (overwrite: false) template. Replace it with the developer's + // existing custom file so custom hooks survive the rename. + // The helper commits the new file before removing the old one: + // a failed write or removal cannot leave the developer without + // either copy, and poisoned snapshot paths stay inside outputDir. + transforms := snapshot.RenameTransforms(ren.OldName, ren.NewName, d) + if err := snapshot.ReplaceScaffoldedFile(mc.opts.outputDir, f.Path, newRel, transforms...); err != nil { + mc.fail(err, fmt.Sprintf("replace scaffolded %s", newRel)) + return + } + mc.log.Info("renamed %s -> %s (content updated)", f.Path, newRel) + return + } + newRel, renamed, err := snapshot.RenameEntityFile(mc.opts.outputDir, f.Path, ren.OldName, ren.NewName) + if err != nil { + mc.fail(err, fmt.Sprintf("rename %s", f.Path)) + return + } + if renamed { + if rewrote, rerr := snapshot.RewriteFile(mc.opts.outputDir, newRel, snapshot.RenameTransforms(ren.OldName, ren.NewName, d)...); rerr != nil { + // No early return: the rename itself succeeded, so the + // final Info line still reports it. + mc.fail(rerr, fmt.Sprintf("rewrite content of %s", newRel)) + } else if rewrote { + mc.log.Info("renamed %s -> %s (content updated)", f.Path, newRel) + return + } + mc.log.Info("renamed %s -> %s", f.Path, newRel) + } + return + } + // Generated files have been regenerated under the new name — remove the stale copy. + if err := snapshot.DeleteFile(mc.opts.outputDir, f.Path); err != nil { + mc.fail(err, fmt.Sprintf("delete stale generated file %s", f.Path)) + return + } + mc.log.Info("removed stale generated file %s", f.Path) + }, + ) +} + +// fileLabel renders a file choice label, annotating developer-owned files. +func fileLabel(f snapshot.FileRef) string { + if f.Custom { + return f.Path + " [custom]" + } + return f.Path +} + +// applyAddons parses the --addons flag into the IR project's Addons set, +// validating each name against specmeta. Unknown addons are ignored with a +// warning so a typo is visible instead of looking like a successful opt-in. diff --git a/cmd/domaincraft/notify_test.go b/cmd/domaincraft/notify_test.go deleted file mode 100644 index f3131c9..0000000 --- a/cmd/domaincraft/notify_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "testing" - - "github.com/DomainCraft/DomainCraft/internal/appdir" -) - -func TestCachedLatestCoreVersion(t *testing.T) { - orig := httpGetBodyFn - defer func() { httpGetBodyFn = orig }() - - appdir.SetBaseForTesting(t.TempDir()) - - httpGetBodyFn = func(url string) ([]byte, error) { - if url != releasesLatestURL { - return nil, fmt.Errorf("unexpected url %s", url) - } - return []byte(`{"tag_name":"v9.9.9","assets":[]}`), nil - } - - latest, err := cachedLatestCoreVersion() - if err != nil { - t.Fatalf("cachedLatestCoreVersion: %v", err) - } - if latest != "9.9.9" { - t.Fatalf("latest = %q, want 9.9.9", latest) - } - - // Network is now down — the fresh cache must still serve the same version. - httpGetBodyFn = func(url string) ([]byte, error) { - return nil, fmt.Errorf("network down") - } - latest2, err := cachedLatestCoreVersion() - if err != nil || latest2 != "9.9.9" { - t.Errorf("cached latest = %q, %v; want 9.9.9", latest2, err) - } -} diff --git a/cmd/domaincraft/update.go b/cmd/domaincraft/update.go index 08a3d1f..7181627 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -1,10 +1,14 @@ package main import ( + "crypto/sha256" + "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" + "net/url" "os" "path/filepath" "runtime" @@ -12,7 +16,9 @@ import ( "time" "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/bridge" "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/netutil" "github.com/DomainCraft/DomainCraft/internal/packages" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -22,14 +28,31 @@ import ( // coreRepo is the GitHub owner/repo that publishes domaincraft releases. const coreRepo = "DomainCraft/DomainCraft" -const releasesLatestURL = "https://api.github.com/repos/DomainCraft/DomainCraft/releases/latest" +const releasesLatestURL = "https://api.github.com/repos/" + coreRepo + "/releases/latest" -// httpClient is the HTTP client used by update checks and binary downloads. +// checksumsAssetName is the release asset holding one SHA-256 digest per binary. +const checksumsAssetName = "checksums.txt" + +// releaseHosts is the strict allowlist for release URLs. A release payload is +// remote data: only these hosts may supply a binary that replaces this process. +var releaseHosts = map[string]bool{ + "api.github.com": true, + "github.com": true, + "objects.githubusercontent.com": true, + "release-assets.githubusercontent.com": true, +} + +// httpClient is the HTTP client used by release checks and binary downloads. var httpClient = &http.Client{Timeout: 120 * time.Second} -// httpGetBodyFn is the HTTP GET used by the core update flow. It is a variable -// so tests can substitute a fake and exercise the GitHub code paths offline. -var httpGetBodyFn = httpGetBody +// noticeClient bounds the automatic "new version available" probe. It shares +// the release transport and redirect policy but must never make an unrelated +// command wait for a download-sized timeout. +var noticeClient = &http.Client{ + Timeout: 2 * time.Second, + Transport: httpClient.Transport, + CheckRedirect: httpClient.CheckRedirect, +} // githubRelease is the subset of the GitHub releases/latest payload we need. type githubRelease struct { @@ -50,51 +73,73 @@ type updateCheckCache struct { Latest string `json:"latest"` } -// maybeNotifyUpdate prints a one-line notice to stderr when a newer core release -// exists. It is best-effort, throttled by a local cache, and skipped for -// development builds and for the `update` command itself. -func maybeNotifyUpdate(cmd *cobra.Command) { - current := strings.TrimPrefix(version, "v") +// releaseVersion strips the optional v prefix from the stamped CLI version. +func releaseVersion() string { return strings.TrimPrefix(version, "v") } + +// updateAvailableMessage is the single wording for "a newer core exists", +// shared by the passive notice and `update --check`. +func updateAvailableMessage(latest, current string) string { + return fmt.Sprintf("A new domaincraft version is available: v%s (current v%s). Run `domaincraft update` to install it.", latest, current) +} + +// maybeNotifyUpdate prints a one-line notice to the command's error stream when +// a newer core release exists. It is best-effort, throttled by a local cache, +// and skipped for development builds and for the `update` command itself. +func maybeNotifyUpdate(cmd *cobra.Command) { maybeNotifyUpdateWithOps(defaultUpdateOps(), cmd) } + +func maybeNotifyUpdateWithOps(ops updateOps, cmd *cobra.Command) { + current := releaseVersion() if current == "" || current == "dev" || cmd.Name() == "update" { return } - latest, err := cachedLatestCoreVersion() + latest, err := cachedLatestCoreVersionWithOps(ops) if err != nil || latest == "" { return } if packages.VersionGreater(latest, current) { - fmt.Fprintf(os.Stderr, "ℹ A new domaincraft version is available: v%s (current v%s). Run `domaincraft update` to install it.\n", latest, current) + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "ℹ %s\n", updateAvailableMessage(latest, current)) } } -// cachedLatestCoreVersion returns the latest released core version, using the -// throttled cache when it is fresh and otherwise querying GitHub. -func cachedLatestCoreVersion() (string, error) { - cacheDir, err := appdir.CacheDir("core") - if err != nil { - cacheDir = os.TempDir() - } +// cachedLatestCoreVersionWithOps returns the latest released core version, +// using the throttled cache when it is fresh and otherwise querying GitHub. +func cachedLatestCoreVersionWithOps(ops updateOps) (string, error) { + cacheDir := appdir.CacheDir("core") cachePath := filepath.Join(cacheDir, "core-update.json") - if data, rerr := os.ReadFile(cachePath); rerr == nil { + if data, rerr := os.ReadFile(cachePath); rerr == nil { //nolint:gosec // cachePath is built by appdir helpers var c updateCheckCache - if json.Unmarshal(data, &c) == nil && !c.CheckedAt.IsZero() && time.Since(c.CheckedAt) < updateNoticeTTL && c.Latest != "" { + if json.Unmarshal(data, &c) == nil && !c.CheckedAt.IsZero() && time.Since(c.CheckedAt) < updateNoticeTTL { return c.Latest, nil } } - rel, err := latestRelease() + rel, err := ops.latestForNotice() if err != nil { + // Record the attempt as well: an offline or blackholed network must not + // make every later invocation wait for another HTTP timeout again. + if werr := writeUpdateCheckCache(cacheDir, cachePath, updateCheckCache{CheckedAt: time.Now()}); werr != nil { + return "", errors.Join(err, fmt.Errorf("cache update check: %w", werr)) + } return "", err } latest := strings.TrimPrefix(rel.TagName, "v") - if werr := os.MkdirAll(cacheDir, 0o755); werr == nil { - if body, jerr := json.Marshal(updateCheckCache{CheckedAt: time.Now(), Latest: latest}); jerr == nil { - _ = fsutil.AtomicWrite(cachePath, body) - } + if err := writeUpdateCheckCache(cacheDir, cachePath, updateCheckCache{CheckedAt: time.Now(), Latest: latest}); err != nil { + return "", fmt.Errorf("cache update check: %w", err) } return latest, nil } +func writeUpdateCheckCache(cacheDir, cachePath string, c updateCheckCache) error { + if err := os.MkdirAll(cacheDir, 0o755); err != nil { //nolint:gosec // cache dirs must stay readable across CLI runs + return err + } + body, err := json.Marshal(c) + if err != nil { + return err + } + return fsutil.AtomicWrite(cachePath, body) +} + // newUpdateCmd checks for and installs a newer version of the domaincraft core. func newUpdateCmd() *cobra.Command { var checkOnly bool @@ -102,7 +147,8 @@ func newUpdateCmd() *cobra.Command { Use: "update", Short: "Update the domaincraft core to the latest release", Long: "Check the GitHub releases for a newer domaincraft version and, if available, download and replace the current executable.\nUse --check to only report whether a newer version exists, without downloading.", - RunE: func(cmd *cobra.Command, args []string) error { + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return runCoreUpdate(commandLogger(cmd), checkOnly) }, } @@ -112,7 +158,11 @@ func newUpdateCmd() *cobra.Command { // runCoreUpdate implements `domaincraft update` (and `domaincraft update --check`). func runCoreUpdate(log *logger.Logger, checkOnly bool) error { - current := strings.TrimPrefix(version, "v") + return runCoreUpdateWithOps(defaultUpdateOps(), log, checkOnly) +} + +func runCoreUpdateWithOps(ops updateOps, log *logger.Logger, checkOnly bool) error { + current := releaseVersion() if current == "" || current == "dev" { log.Info("Running a development build (v%s).", version) if !checkOnly { @@ -122,7 +172,7 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { } log.Info("Checking for updates (current: v%s)...", current) - release, err := latestRelease() + release, err := latestReleaseWithOps(ops) if err != nil { return fmt.Errorf("check for updates: %w", err) } @@ -134,39 +184,54 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { } if checkOnly { - log.Info("A newer version is available: v%s (current: v%s). Run `domaincraft update` to install it.", latest, current) + log.Info("%s", updateAvailableMessage(latest, current)) return nil } - assetURL, err := releaseAssetFor(release, assetName()) + // Fail closed: validate the remote URL and the checksum before any bytes + // are written, and again against the downloaded bytes before replacing the + // running executable. + asset := assetName() + assetURL, err := validatedReleaseAssetURL(release, asset) if err != nil { return err } - - tmp, err := downloadBinary(assetURL) + wantSum, err := releaseChecksumWithOps(ops, release, asset) if err != nil { return err } - defer os.Remove(tmp) - - exe, err := os.Executable() + // Resolve the executable before downloading: the temp file must live on the + // same volume as the binary, otherwise rename fails with EXDEV on install. + exe, err := ops.executable() if err != nil { return fmt.Errorf("locate current executable: %w", err) } - if err := replaceExecutable(tmp, exe); err != nil { + tmp, err := downloadBinaryWithOps(ops, assetURL, filepath.Dir(exe)) + if err != nil { return err } + defer func() { + if cerr := ops.remove(tmp); cerr != nil && !errors.Is(cerr, os.ErrNotExist) { + log.Warn("could not remove temporary update %s: %v", tmp, cerr) + } + }() + + if err := verifyFileSHA256(tmp, wantSum); err != nil { + return fmt.Errorf("refusing to install update: %w", err) + } + if err := ops.replaceExecutable(tmp, exe); err != nil { + return err + } + // The new binary is in place only now: a failed rename above never reports + // success, even when the old executable had to be moved aside first. log.Success("Updated to v%s (was v%s). Re-run the command to use the new version.", latest, current) return nil } -// latestRelease fetches the newest published release metadata. -func latestRelease() (*githubRelease, error) { - body, err := httpGetBodyFn(releasesLatestURL) - if err != nil { - return nil, err - } +// decodeRelease validates the release payload shared by the explicit update +// command and the automatic notice probe. +func decodeRelease(body []byte) (*githubRelease, error) { var rel githubRelease if err := json.Unmarshal(body, &rel); err != nil { return nil, err @@ -177,6 +242,15 @@ func latestRelease() (*githubRelease, error) { return &rel, nil } +// latestReleaseWithOps fetches the newest published release metadata. +func latestReleaseWithOps(ops updateOps) (*githubRelease, error) { + body, err := ops.getBody(releasesLatestURL) + if err != nil { + return nil, err + } + return decodeRelease(body) +} + // assetName returns the upload name of the binary for the current platform, // matching the naming used by the release pipeline: domaincraft--, // with a .exe suffix on Windows. @@ -198,59 +272,188 @@ func releaseAssetFor(rel *githubRelease, name string) (string, error) { return "", fmt.Errorf("no prebuilt binary %s for this release (platform %s/%s); use `go install` instead", name, runtime.GOOS, runtime.GOARCH) } -// httpGetBody performs a GET and returns the response body, limiting its size -// to 64 MiB to avoid unbounded reads from a misbehaving endpoint. -func httpGetBody(url string) ([]byte, error) { - resp, err := httpClient.Get(url) +// validatedReleaseAssetURL finds a release asset and validates its URL before +// the bytes are used. Only https and known GitHub hosts are accepted. +func validatedReleaseAssetURL(rel *githubRelease, name string) (string, error) { + raw, err := releaseAssetFor(rel, name) if err != nil { - return nil, err + return "", err + } + u, err := validateReleaseURL(raw) + if err != nil { + return "", fmt.Errorf("refusing download for %s: %w", name, err) + } + return u, nil +} + +// validateReleaseURL accepts only https URLs on the release host allowlist, +// without credentials, query or fragment. +func validateReleaseURL(raw string) (string, error) { + u, err := parseAllowedURL(raw) + if err != nil { + return "", err + } + if u.User != nil { + return "", fmt.Errorf("refusing release URL with credentials") + } + if u.RawQuery != "" || u.Fragment != "" { + return "", fmt.Errorf("refusing release URL with query or fragment") + } + return u.String(), nil +} + +// parseAllowedURL checks scheme and host only. Redirects from GitHub carry +// signed query strings, so those are allowed here but never in a URL taken +// from release JSON. +func parseAllowedURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("invalid release URL: %w", err) + } + if u.Scheme != "https" { + return nil, fmt.Errorf("refusing non-https release URL") + } + if !releaseHosts[strings.ToLower(u.Hostname())] { + return nil, fmt.Errorf("refusing release URL on host %q", u.Hostname()) + } + if p := u.Port(); p != "" && p != "443" { + return nil, fmt.Errorf("refusing release URL on port %q", p) + } + return u, nil +} + +// releaseChecksumWithOps reads the SHA-256 digest for name from the release's +// checksums.txt asset. A missing, malformed or foreign digest is an error. +func releaseChecksumWithOps(ops updateOps, rel *githubRelease, name string) (string, error) { + assetURL, err := validatedReleaseAssetURL(rel, checksumsAssetName) + if err != nil { + return "", fmt.Errorf("verify update: %w", err) + } + data, err := ops.getBody(assetURL) + if err != nil { + return "", fmt.Errorf("fetch release checksums: %w", err) + } + for line := range strings.SplitSeq(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + if strings.TrimPrefix(fields[1], "*") != name { + continue + } + sum := strings.ToLower(fields[0]) + if _, err := hex.DecodeString(sum); err != nil || len(sum) != sha256.Size*2 { + return "", fmt.Errorf("invalid sha-256 checksum for %s", name) + } + return sum, nil + } + return "", fmt.Errorf("no sha-256 checksum for %s in %s", name, checksumsAssetName) +} + +// verifyFileSHA256 compares a downloaded file's digest against want. +func verifyFileSHA256(path, want string) error { + f, err := os.Open(path) //nolint:gosec // path is the verified temporary release asset + if err != nil { + return fmt.Errorf("open downloaded update: %w", err) + } + defer func() { _ = f.Close() }() + + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return fmt.Errorf("hash downloaded update: %w", err) + } + if got := hex.EncodeToString(h.Sum(nil)); got != want { + return fmt.Errorf("checksum mismatch for downloaded update (got %s, want %s)", got, want) + } + return nil +} + +// validateReleaseRedirect keeps a redirect from moving the download off the +// release-host allowlist. Signed query strings on GitHub's asset redirects are +// allowed here; validateReleaseURL still rejects them on URLs from release JSON. +func validateReleaseRedirect(u *url.URL) error { + if _, err := parseAllowedURL(u.String()); err != nil { + return err } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, url) + // parseAllowedURL checks scheme/host/port only; credentials have the same + // meaning on a redirect as on a URL from release JSON. + if u.User != nil { + return fmt.Errorf("refusing release redirect with credentials") } - return io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + return nil +} + +// httpGetBody performs a GET bound to bridge.CommandContext() and returns the response body, +// capping it at the configured maxBodyBytes. The shared helper owns the status check, +// cap and redaction; this package supplies the client, context and redirect +// policy. +func httpGetBody(rawURL string) ([]byte, error) { + return netutil.BoundedGet(bridge.CommandContext(), httpClient, rawURL, defaultUpdateOps().maxBodyBytes, validateReleaseRedirect) } -// downloadBinary fetches a release asset into a temp file and returns its path. -func downloadBinary(url string) (string, error) { - data, err := httpGetBodyFn(url) +// downloadBinaryWithOps fetches a release asset into a temp file in dir and +// returns its path. Callers pass filepath.Dir(exe) so the final rename never +// crosses a volume boundary (EXDEV on Unix, a needless copy on Windows). +func downloadBinaryWithOps(ops updateOps, rawURL, dir string) (string, error) { + validURL, err := validateReleaseURL(rawURL) + if err != nil { + return "", fmt.Errorf("download update: %w", err) + } + data, err := ops.getBody(validURL) if err != nil { return "", fmt.Errorf("download update: %w", err) } - tmp, err := os.CreateTemp("", "domaincraft-update-*") + tmp, err := ops.createTemp(dir, "domaincraft-update-*") if err != nil { return "", err } - defer tmp.Close() + defer func() { _ = tmp.Close() }() if _, err := tmp.Write(data); err != nil { - os.Remove(tmp.Name()) - return "", err + return "", errors.Join(err, ops.remove(tmp.Name())) } if runtime.GOOS != "windows" { - _ = os.Chmod(tmp.Name(), 0o755) + // A non-executable download must never reach the install step. + if err := ops.chmod(tmp.Name(), 0o755); err != nil { + return "", errors.Join(fmt.Errorf("make downloaded update executable: %w", err), ops.remove(tmp.Name())) + } } return tmp.Name(), nil } -// replaceExecutable puts the new binary in place of the running executable. It -// first tries a direct rename; on platforms where the running binary is locked -// (Windows), it moves the current one aside first. -func replaceExecutable(tmp, exe string) error { - if err := os.Rename(tmp, exe); err == nil { +// replaceExecutableWithOps puts the new binary in place of the running +// executable. It first tries a direct rename; on platforms where the running +// binary is locked (Windows), it moves the current one aside first. +func replaceExecutableWithOps(ops updateOps, tmp, exe string) error { + // Direct rename is the normal path. Its error is kept: on a locked binary + // it explains why the fallback was needed, and on a real failure it is the + // only cause reported to the user. + firstErr := ops.rename(tmp, exe) + if firstErr == nil { return nil } + + // Windows keeps the running executable locked, so move it aside first. + // Every failure mentions `old` — a human must be able to recover by hand. old := exe + ".old" - _ = os.Remove(old) - if err := os.Rename(exe, old); err != nil { - return fmt.Errorf("update in place failed (%v); replace %s manually or run `go install`", err, exe) + if err := ops.remove(old); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove previous backup %s: %w", old, err) + } + if err := ops.rename(exe, old); err != nil { + return fmt.Errorf("update in place failed; replace %s manually or run go install (backup path %s): %w", + exe, old, errors.Join(firstErr, fmt.Errorf("move %s to %s: %w", exe, old, err))) + } + if err := ops.rename(tmp, exe); err != nil { + restoreErr := ops.rename(old, exe) + return fmt.Errorf("could not install update to %s (backup at %s): %w", exe, old, errors.Join( + fmt.Errorf("initial rename: %w", firstErr), + fmt.Errorf("rename update into place: %w", err), + fmt.Errorf("restore %s from %s: %w", exe, old, restoreErr), + )) } - if err := os.Rename(tmp, exe); err != nil { - _ = os.Rename(old, exe) // restore the original - return fmt.Errorf("could not install update: %w", err) + if err := ops.remove(old); err != nil { + return fmt.Errorf("update installed to %s but could not remove backup %s: %w", exe, old, err) } - _ = os.Remove(old) return nil } diff --git a/cmd/domaincraft/update_ops.go b/cmd/domaincraft/update_ops.go new file mode 100644 index 0000000..58a82e7 --- /dev/null +++ b/cmd/domaincraft/update_ops.go @@ -0,0 +1,44 @@ +package main + +import ( + "os" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/netutil" +) + +// updateOps is the full set of external effects used by the core self-update +// flow. Production builds use defaultUpdateOps(); tests construct a value with +// hermetic fakes and pass it explicitly — no package-level variable is swapped. +type updateOps struct { + getBody func(string) ([]byte, error) + executable func() (string, error) + replaceExecutable func(tmp, exe string) error + chmod func(string, os.FileMode) error + rename func(src, dst string) error + remove func(string) error + createTemp func(dir, pattern string) (*os.File, error) + maxBodyBytes int64 + latestForNotice func() (*githubRelease, error) +} + +func defaultUpdateOps() updateOps { + o := updateOps{ + getBody: httpGetBody, + executable: os.Executable, + chmod: os.Chmod, + rename: os.Rename, + remove: os.Remove, + createTemp: os.CreateTemp, + maxBodyBytes: 64 << 20, + latestForNotice: func() (*githubRelease, error) { + body, err := netutil.BoundedGet(bridge.CommandContext(), noticeClient, releasesLatestURL, 64<<20, validateReleaseRedirect) + if err != nil { + return nil, err + } + return decodeRelease(body) + }, + } + o.replaceExecutable = func(tmp, exe string) error { return replaceExecutableWithOps(o, tmp, exe) } + return o +} diff --git a/cmd/domaincraft/version_test.go b/cmd/domaincraft/version_test.go deleted file mode 100644 index 3bf17da..0000000 --- a/cmd/domaincraft/version_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "testing" - -func TestResolveVersion(t *testing.T) { - cases := []struct { - stamped, buildInfo, want string - }{ - {"v0.5.0", "v0.5.0", "v0.5.0"}, // stamped wins - {"dev", "v0.5.0", "v0.5.0"}, // go install pkg@vX.Y.Z: clean tag - {"dev", "(devel)", "dev"}, // local build, no stamp - {"dev", "v0.5.1-0.20260821125410-876219469a43", "dev"}, // pseudo-version = dev - {"dev", "v0.5.1-0.20260821125410-876219469a43+dirty", "dev"}, // pseudo-version with build metadata - {"dev", "", "dev"}, // no build info at all - {"", "v0.5.0", "v0.5.0"}, // empty stamp, clean tag - {"", "(devel)", "dev"}, - } - for _, c := range cases { - if got := resolveVersion(c.stamped, c.buildInfo); got != c.want { - t.Errorf("resolveVersion(%q, %q) = %q, want %q", c.stamped, c.buildInfo, got, c.want) - } - } -} diff --git a/cmd/schema-gen/main.go b/cmd/schema-gen/main.go index e60aa90..ad1b5cc 100644 --- a/cmd/schema-gen/main.go +++ b/cmd/schema-gen/main.go @@ -1,12 +1,14 @@ +// Package main implements schema-gen, which generates spec/domain.schema.json +// from specmeta. package main import ( - "encoding/json" "flag" "fmt" "os" "path/filepath" + "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/specmeta" ) @@ -14,17 +16,28 @@ func main() { outputPath := flag.String("o", filepath.Join("spec", "domain.schema.json"), "output path for the generated schema") flag.Parse() - schema := buildSchema() - data, err := json.MarshalIndent(schema, "", " ") - if err != nil { - fmt.Fprintln(os.Stderr, "marshal schema:", err) + if err := fsutil.WriteJSONWithNewline(*outputPath, buildSchema(), true); err != nil { + fmt.Fprintln(os.Stderr, "write schema:", err) os.Exit(1) } +} - if err := os.WriteFile(*outputPath, append(data, '\n'), 0o644); err != nil { - fmt.Fprintln(os.Stderr, "write schema:", err) - os.Exit(1) +// objectDef is the shape shared by every $defs entry: a closed object with +// named properties, an optional description and an optional required list. +func objectDef(title string, props map[string]any, required []string, description string) map[string]any { + def := map[string]any{ + "title": title, + "type": "object", + "additionalProperties": false, + "properties": props, + } + if description != "" { + def["description"] = description } + if len(required) > 0 { + def["required"] = required + } + return def } func buildSchema() map[string]any { @@ -52,206 +65,132 @@ func buildSchema() map[string]any { }, }, "required": []string{"project", "entities"}, - "$defs": map[string]any{ - "Project": map[string]any{ - "title": "Project", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "name": map[string]any{"type": "string"}, - "description": map[string]any{"type": "string"}, - "version": map[string]any{"type": "string"}, - "platform": map[string]any{"type": "string", "description": "Target platform version (e.g. net10.0). Defaults to net10.0 for the csharp bridge."}, - "multi_tenancy": map[string]any{ - "$ref": "#/$defs/MultiTenancy", - }, - "cache": map[string]any{ - "$ref": "#/$defs/CacheConfig", - }, - "cors": map[string]any{ - "$ref": "#/$defs/CORSConfig", - }, - "deploy": map[string]any{ - "$ref": "#/$defs/DeployConfig", - }, - "versioning": map[string]any{ - "$ref": "#/$defs/VersioningConfig", - }, - "rate_limit": map[string]any{ - "$ref": "#/$defs/RateLimitConfig", - }, - "pagination": map[string]any{ - "$ref": "#/$defs/PaginationConfig", - }, - "infrastructure": map[string]any{ - "$ref": "#/$defs/InfrastructureConfig", - }, - }, - "required": []string{"name"}, - }, - "CacheConfig": map[string]any{ - "title": "CacheConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "enabled": map[string]any{"type": "boolean"}, - "provider": map[string]any{"type": "string", "enum": specmeta.CacheProviders, "description": "Cache provider"}, - "connection_string": map[string]any{"type": "string"}, - "ttl_seconds": map[string]any{"type": "integer", "minimum": 0}, - }, - "required": []string{"enabled"}, - }, - "CORSConfig": map[string]any{ - "title": "CORSConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "enabled": map[string]any{"type": "boolean"}, - "origins": map[string]any{ - "type": "array", - "items": map[string]any{"type": "string"}, - }, - }, - "required": []string{"enabled"}, - }, - "MultiTenancy": map[string]any{ - "title": "MultiTenancy", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "enabled": map[string]any{"type": "boolean"}, - "mode": map[string]any{"type": "string", "enum": specmeta.MultiTenancyModes}, - }, - "required": []string{"enabled"}, - }, - "DeployConfig": map[string]any{ - "title": "DeployConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "domain": map[string]any{"type": "string", "description": "API domain (e.g. localhost, api.example.com)"}, - "port": map[string]any{"type": "integer", "minimum": 1, "maximum": 65535, "description": "Exposed application port (default: 8080)"}, - }, - }, - "VersioningConfig": map[string]any{ - "title": "VersioningConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "enabled": map[string]any{"type": "boolean", "description": "Enable API versioning (default: true)"}, - "default_version": map[string]any{"type": "string", "description": "Default API version (default: 1.0)"}, - }, - }, - "RateLimitConfig": map[string]any{ - "title": "RateLimitConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "enabled": map[string]any{"type": "boolean", "description": "Enable request rate limiting (default: true)"}, - "policy": map[string]any{"type": "string", "enum": specmeta.RateLimitPolicies, "description": "Limiter algorithm (default: fixed)"}, - "permit_limit": map[string]any{"type": "integer", "minimum": 1, "description": "Max requests (default: 100)"}, - "window_seconds": map[string]any{"type": "integer", "minimum": 1, "description": "Window duration in seconds (default: 60)"}, - }, - }, - "PaginationConfig": map[string]any{ - "title": "PaginationConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "default_page_size": map[string]any{"type": "integer", "minimum": 1, "description": "Default page size (default: 20)"}, - "max_page_size": map[string]any{"type": "integer", "minimum": 1, "description": "Hard cap on page size (default: 200)"}, - }, - }, - "InfrastructureConfig": map[string]any{ - "title": "InfrastructureConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "queue": map[string]any{"type": "string", "enum": specmeta.InfraQueues, "description": "Message broker"}, - "cache": map[string]any{"type": "string", "enum": specmeta.InfraCacheStores, "description": "Distributed cache store"}, - "secrets": map[string]any{"type": "string", "enum": specmeta.InfraSecretStores, "description": "Secrets store"}, - "storage": map[string]any{"type": "string", "enum": specmeta.InfraStores, "description": "Object/file storage"}, - }, - }, - "EntityDefinition": map[string]any{ - "title": "EntityDefinition", - "type": "object", - "description": "An entity. Valid keys: old_name, features, fields, indexes, permissions, seed. There is no `relations:` key — relations are declared as fields of type `relation(Target)` (see the fields description).", - "additionalProperties": false, - "properties": map[string]any{ - "old_name": map[string]any{"type": "string", "description": "Previous entity name — a hint for the migration engine to detect renames"}, - "features": map[string]any{ - "type": "array", - "items": map[string]any{"type": "string", "enum": specmeta.Features}, - }, - "fields": map[string]any{ - "type": "object", - "description": "Field definitions. Each value is a definition string: `type [modifiers]` (e.g. `string [required, max:255]`). Relations are fields, not a separate key: `relation(Target) [many]` for many-to-many, `relation(Target) [required, on_delete:cascade]`, `relation(Target) [optional, on_delete:set_null]`. `on_delete` accepts cascade|restrict|set_null|no_action. Flag modifiers: `required`, `optional`, `unique`, `hidden`, `readonly`, `primary`, `many`, `email`, `url`, `ipv4`. Key:value modifiers: `min:N`, `max:N`, `gte:N`, `lte:N`, `gt:N`, `lt:N`, `regex:\"...\"`, `default:...`, `old_name:`. `old_name` is a rename hint for the migration engine: the field was previously named ``, so bridges can generate a safe `RenameColumn` instead of a destructive drop + add. `hidden` excludes a field from API responses; `readonly` keeps it in responses but excludes it from create/update/patch requests (server-owned). Do not put a space after `:` inside the definition string (`default:5`, not `default: 5`); quoted string defaults are allowed (`default:\"pending\"`).", - "additionalProperties": map[string]any{"type": "string"}, - }, - "indexes": map[string]any{ - "type": "array", - "items": map[string]any{"$ref": "#/$defs/IndexDefinition"}, - }, - "permissions": map[string]any{ - "$ref": "#/$defs/EntityPermissions", - }, - "seed": map[string]any{ - "type": "array", - "items": map[string]any{"type": "object", "additionalProperties": true}, - }, - }, - "required": []string{"fields"}, - }, - "IndexDefinition": map[string]any{ - "title": "IndexDefinition", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "fields": map[string]any{ - "type": "array", - "items": map[string]any{"type": "string"}, - }, - "type": map[string]any{"type": "string", "enum": specmeta.IndexTypes}, - "sort": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "unique": map[string]any{"type": "boolean"}, - }, - "required": []string{"fields"}, - }, - "EntityPermissions": map[string]any{ - "title": "EntityPermissions", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "read": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "create": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "update": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "delete": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - }, - }, - "AuthConfig": map[string]any{ - "title": "AuthConfig", - "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "type": map[string]any{"type": "string", "enum": specmeta.AuthTypes}, - "entity": map[string]any{"type": "string", "description": "Entity with email+password fields (auto-detected if omitted)"}, - "roles": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "endpoints": map[string]any{"$ref": "#/$defs/AuthEndpoints"}, - }, - "required": []string{"type"}, - }, - "AuthEndpoints": map[string]any{ - "title": "AuthEndpoints", + "$defs": schemaDefs(), + } +} + +func schemaDefs() map[string]any { + return map[string]any{ + "Project": objectDef("Project", map[string]any{ + "name": map[string]any{"type": "string"}, + "description": map[string]any{"type": "string"}, + "version": map[string]any{"type": "string"}, + "platform": map[string]any{"type": "string", "description": "Target platform version (e.g. net10.0). Defaults to net10.0 for the csharp bridge."}, + "multi_tenancy": map[string]any{ + "$ref": "#/$defs/MultiTenancy", + }, + "cache": map[string]any{ + "$ref": "#/$defs/CacheConfig", + }, + "cors": map[string]any{ + "$ref": "#/$defs/CORSConfig", + }, + "deploy": map[string]any{ + "$ref": "#/$defs/DeployConfig", + }, + "versioning": map[string]any{ + "$ref": "#/$defs/VersioningConfig", + }, + "rate_limit": map[string]any{ + "$ref": "#/$defs/RateLimitConfig", + }, + "pagination": map[string]any{ + "$ref": "#/$defs/PaginationConfig", + }, + "infrastructure": map[string]any{ + "$ref": "#/$defs/InfrastructureConfig", + }, + }, []string{"name"}, ""), + "CacheConfig": objectDef("CacheConfig", map[string]any{ + "enabled": map[string]any{"type": "boolean"}, + "provider": map[string]any{"type": "string", "enum": specmeta.CacheProviders, "description": "Cache provider"}, + "connection_string": map[string]any{"type": "string"}, + "ttl_seconds": map[string]any{"type": "integer", "minimum": 0}, + }, []string{"enabled"}, ""), + "CORSConfig": objectDef("CORSConfig", map[string]any{ + "enabled": map[string]any{"type": "boolean"}, + "origins": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + }, + }, []string{"enabled"}, ""), + "MultiTenancy": objectDef("MultiTenancy", map[string]any{ + "enabled": map[string]any{"type": "boolean"}, + "mode": map[string]any{"type": "string", "enum": specmeta.MultiTenancyModes}, + }, []string{"enabled"}, ""), + "DeployConfig": objectDef("DeployConfig", map[string]any{ + "domain": map[string]any{"type": "string", "description": "API domain (e.g. localhost, api.example.com)"}, + "port": map[string]any{"type": "integer", "minimum": 0, "maximum": 65535, "description": "Exposed application port (default: 8080)"}, + }, nil, ""), + "VersioningConfig": objectDef("VersioningConfig", map[string]any{ + "enabled": map[string]any{"type": "boolean", "description": "Enable API versioning (default: true)"}, + "default_version": map[string]any{"type": "string", "description": "Default API version (default: 1.0)"}, + }, nil, ""), + "RateLimitConfig": objectDef("RateLimitConfig", map[string]any{ + "enabled": map[string]any{"type": "boolean", "description": "Enable request rate limiting (default: true)"}, + "policy": map[string]any{"type": "string", "enum": specmeta.RateLimitPolicies, "description": "Limiter algorithm (default: fixed)"}, + "permit_limit": map[string]any{"type": "integer", "minimum": 0, "description": "Max requests (default: 100)"}, + "window_seconds": map[string]any{"type": "integer", "minimum": 0, "description": "Window duration in seconds (default: 60)"}, + }, nil, ""), + "PaginationConfig": objectDef("PaginationConfig", map[string]any{ + "default_page_size": map[string]any{"type": "integer", "minimum": 0, "description": "Default page size (default: 20)"}, + "max_page_size": map[string]any{"type": "integer", "minimum": 0, "description": "Hard cap on page size (default: 200)"}, + }, nil, ""), + "InfrastructureConfig": objectDef("InfrastructureConfig", map[string]any{ + "queue": map[string]any{"type": "string", "enum": specmeta.InfraQueues, "description": "Message broker"}, + "cache": map[string]any{"type": "string", "enum": specmeta.InfraCacheStores, "description": "Distributed cache store"}, + "secrets": map[string]any{"type": "string", "enum": specmeta.InfraSecretStores, "description": "Secrets store"}, + "storage": map[string]any{"type": "string", "enum": specmeta.InfraStores, "description": "Object/file storage"}, + }, nil, ""), + "EntityDefinition": objectDef("EntityDefinition", map[string]any{ + "old_name": map[string]any{"type": "string", "description": "Previous entity name — a hint for the migration engine to detect renames"}, + "features": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string", "enum": specmeta.Features}, + }, + "fields": map[string]any{ "type": "object", - "additionalProperties": false, - "properties": map[string]any{ - "login": map[string]any{"type": "boolean", "description": "Generate login endpoint (default: true)"}, - "register": map[string]any{"type": "boolean", "description": "Generate register endpoint (default: true)"}, - "me": map[string]any{"type": "boolean", "description": "Generate /me endpoint (default: true)"}, - "setup": map[string]any{"type": "boolean", "description": "Generate /setup endpoint that bootstraps the first Admin (default: true)"}, - }, - }, - }, + "description": "Field definitions. Each value is a definition string: `type [modifiers]` (e.g. `string [required, max:255]`). Relations are fields, not a separate key: `relation(Target) [many]` for many-to-many, `relation(Target) [required, on_delete:cascade]`, `relation(Target) [optional, on_delete:set_null]`. `on_delete` accepts cascade|restrict|set_null|no_action. Flag modifiers: `required`, `optional`, `unique`, `hidden`, `readonly`, `primary`, `many`, `email`, `url`, `ipv4`. Key:value modifiers: `min:N`, `max:N`, `gte:N`, `lte:N`, `gt:N`, `lt:N`, `regex:\"...\"`, `default:...`, `old_name:`. `old_name` is a rename hint for the migration engine: the field was previously named ``, so bridges can generate a safe `RenameColumn` instead of a destructive drop + add. `hidden` excludes a field from API responses; `readonly` keeps it in responses but excludes it from create/update/patch requests (server-owned). Do not put a space after `:` inside the definition string (`default:5`, not `default: 5`); quoted string defaults are allowed (`default:\"pending\"`).", + "additionalProperties": map[string]any{"type": "string"}, + }, + "indexes": map[string]any{ + "type": "array", + "items": map[string]any{"$ref": "#/$defs/IndexDefinition"}, + }, + "permissions": map[string]any{ + "$ref": "#/$defs/EntityPermissions", + }, + "seed": map[string]any{ + "type": "array", + "items": map[string]any{"type": "object", "additionalProperties": true}, + }, + }, []string{"fields"}, "An entity. Valid keys: old_name, features, fields, indexes, permissions, seed. There is no `relations:` key — relations are declared as fields of type `relation(Target)` (see the fields description)."), + "IndexDefinition": objectDef("IndexDefinition", map[string]any{ + "fields": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + }, + "type": map[string]any{"type": "string", "enum": specmeta.IndexTypes}, + "sort": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "unique": map[string]any{"type": "boolean"}, + }, []string{"fields"}, ""), + "EntityPermissions": objectDef("EntityPermissions", map[string]any{ + "read": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "create": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "update": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "delete": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + }, nil, ""), + "AuthConfig": objectDef("AuthConfig", map[string]any{ + "type": map[string]any{"type": "string", "enum": specmeta.AuthTypes}, + "entity": map[string]any{"type": "string", "description": "Entity with email+password fields (auto-detected if omitted)"}, + "roles": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "endpoints": map[string]any{"$ref": "#/$defs/AuthEndpoints"}, + }, []string{"type"}, ""), + "AuthEndpoints": objectDef("AuthEndpoints", map[string]any{ + "login": map[string]any{"type": "boolean", "description": "Generate login endpoint (default: true)"}, + "register": map[string]any{"type": "boolean", "description": "Generate register endpoint (default: true)"}, + "me": map[string]any{"type": "boolean", "description": "Generate /me endpoint (default: true)"}, + "setup": map[string]any{"type": "boolean", "description": "Generate /setup endpoint that bootstraps the first Admin (default: true)"}, + }, nil, ""), } } diff --git a/cmd/schema-gen/main_test.go b/cmd/schema-gen/main_test.go new file mode 100644 index 0000000..d6bf581 --- /dev/null +++ b/cmd/schema-gen/main_test.go @@ -0,0 +1,70 @@ +package main + +import ( + "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) + +func TestSchemaTopLevelContract(t *testing.T) { + t.Parallel() + schema := buildSchema() + for _, key := range []string{"$schema", "$id", "title", "type", "properties", "required", "$defs"} { + if _, ok := schema[key]; !ok { + t.Errorf("buildSchema() is missing %q", key) + } + } + props, ok := schema["properties"].(map[string]any) + if !ok { + t.Fatal("schema has no properties") + } + databases, ok := props["database"].(map[string]any) + if !ok { + t.Fatal("schema has no database property") + } + values, ok := databases["enum"].([]string) + if !ok || len(values) == 0 || values[0] != specmeta.Databases[0] { + t.Fatalf("database enum = %v, want specmeta.Databases", values) + } +} + +// TestSchemaAllowsExplicitZeros pins the schema side of the zero contract: the +// parser and validator treat an explicit 0 in these fields as meaningful, so the +// generated JSON schema must not mark the same document invalid. +func TestSchemaAllowsExplicitZeros(t *testing.T) { + schema := buildSchema() + defs, ok := schema["$defs"].(map[string]any) + if !ok { + t.Fatal("schema has no $defs") + } + + cases := []struct { + def string + field string + }{ + {"DeployConfig", "port"}, + {"RateLimitConfig", "permit_limit"}, + {"RateLimitConfig", "window_seconds"}, + {"PaginationConfig", "default_page_size"}, + {"PaginationConfig", "max_page_size"}, + } + for _, tc := range cases { + t.Run(tc.def+"."+tc.field, func(t *testing.T) { + def, ok := defs[tc.def].(map[string]any) + if !ok { + t.Fatalf("missing def %s", tc.def) + } + props, ok := def["properties"].(map[string]any) + if !ok { + t.Fatalf("%s has no properties", tc.def) + } + prop, ok := props[tc.field].(map[string]any) + if !ok { + t.Fatalf("%s has no property %s", tc.def, tc.field) + } + if got := prop["minimum"]; got != 0 { + t.Errorf("%s.%s minimum = %v, want 0", tc.def, tc.field, got) + } + }) + } +} diff --git a/cmd/wasm-validator/main.go b/cmd/wasm-validator/main.go index 315b551..c9409c5 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -1,9 +1,11 @@ //go:build js && wasm +// Package main exposes the Go parser and validator to the browser GUI. package main import ( "encoding/json" + "fmt" "syscall/js" "github.com/DomainCraft/DomainCraft/internal/lexer" @@ -36,21 +38,35 @@ func main() { <-c } -func versionFunc(_ js.Value, _ []js.Value) interface{} { +func versionFunc(_ js.Value, _ []js.Value) any { return version } -func specmetaFunc(_ js.Value, _ []js.Value) interface{} { - return marshal(specmeta.SpecmetaJSON()) +func specmetaFunc(_ js.Value, _ []js.Value) any { + return marshal(specmeta.JSON()) } -func validate(_ js.Value, args []js.Value) interface{} { - if len(args) < 1 { +// stringArg validates the JS API contract. Without a type check an object +// becomes "[object Object]" and surfaces as a confusing parse error in the GUI. +func stringArg(args []js.Value, i int, label string) (string, error) { + if len(args) <= i { + return "", fmt.Errorf("no %s provided", label) + } + if args[i].Type() != js.TypeString { + return "", fmt.Errorf("%s must be a string", label) + } + return args[i].String(), nil +} + +func validate(_ js.Value, args []js.Value) any { + raw, err := stringArg(args, 0, "YAML input") + if err != nil { return marshal(validationResult{ - Errors: []validationError{{Message: "no YAML input provided"}}, + Errors: []validationError{{Message: err.Error()}}, + Parse: true, }) } - schema, err := parser.ParseYAML([]byte(args[0].String())) + schema, err := parser.ParseYAML([]byte(raw)) if err != nil { return marshal(validationResult{ Errors: []validationError{{Message: err.Error()}}, @@ -70,14 +86,17 @@ func validate(_ js.Value, args []js.Value) interface{} { return marshal(validationResult{Errors: result}) } -func parseField(_ js.Value, args []js.Value) interface{} { - if len(args) < 1 { - return marshal(map[string]string{"error": "no field definition provided"}) +func parseField(_ js.Value, args []js.Value) any { + def, err := stringArg(args, 0, "field definition") + if err != nil { + return marshal(map[string]string{"error": err.Error()}) } - def := args[0].String() name := "" if len(args) > 1 { - name = args[1].String() + name, err = stringArg(args, 1, "field name") + if err != nil { + return marshal(map[string]string{"error": err.Error()}) + } } fd, err := lexer.ParseFieldString(def) if err != nil { @@ -87,21 +106,22 @@ func parseField(_ js.Value, args []js.Value) interface{} { return marshal(fd) } -func parseDomain(_ js.Value, args []js.Value) interface{} { - if len(args) < 1 { - return marshal(map[string]string{"error": "no YAML input provided"}) +func parseDomain(_ js.Value, args []js.Value) any { + input, err := stringArg(args, 0, "YAML input") + if err != nil { + return marshal(map[string]string{"error": err.Error()}) } - raw, err := parser.ParseRawSchema([]byte(args[0].String())) + raw, err := parser.ParseRawSchema([]byte(input)) if err != nil { return marshal(map[string]string{"error": err.Error()}) } return marshal(raw) } -func marshal(v interface{}) string { +func marshal(v any) string { data, err := json.Marshal(v) if err != nil { - data, _ = json.Marshal(map[string]string{"error": "marshal failed"}) + data, _ = json.Marshal(map[string]string{"error": "marshal failed: " + err.Error()}) } return string(data) } diff --git a/compliance-suite/certification.yml b/compliance-suite/certification.yml deleted file mode 100644 index 3597fb5..0000000 --- a/compliance-suite/certification.yml +++ /dev/null @@ -1,96 +0,0 @@ -# DomainCraft Bridge Certification (TCK) CI Template -# -# Copy this file into your bridge repository at .github/workflows/certification.yml -# and adjust the `bridge_path:` input below if your templates are not at the repo root. -# -# This workflow downloads the DomainCraft core + compliance-suite, generates code -# from kitchen-sink.yaml using your bridge templates, starts the app + database -# via Docker Compose, and runs the k6 certification suite against it. -# -# The compliance-suite is maintained in the DomainCraft/core repository so that -# every new check is automatically inherited by all certified bridges. -# --- -name: Bridge Certification (TCK) - -on: - push: - branches: ["main"] - pull_request: - branches: ["main"] - -env: - # Core repo ref to checkout (branch or tag). Use a release tag like v1.2.3 to - # lock the TCK version, or leave as `main` to always run against the latest. - CORE_VERSION: main - # Port the generated app listens on. Must match `project.deploy.port` in - # kitchen-sink.yaml (the compliance suite is generated from that file). - API_PORT: 9000 - -jobs: - certify: - runs-on: ubuntu-latest - steps: - # 1. Checkout the bridge (templates) under test. - - name: Checkout Bridge - uses: actions/checkout@v4 - - # 2. Checkout the DomainCraft core (compliance-suite + k6 script) and - # install the CLI from the matching release in one go. - - name: Checkout Core - uses: actions/checkout@v4 - with: - repository: DomainCraft/DomainCraft - path: core - ref: ${{ env.CORE_VERSION }} - - # 3. Set up Go. ubuntu-latest (24.04) does NOT ship a preinstalled Go, - # and the core requires Go 1.25+ (see go.mod). - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: "1.25" - - # 4. Build & install the CLI. `main` maps to the latest release; a pinned - # CORE_VERSION (e.g. v1.2.3) installs that exact release. - - name: Install DomainCraft CLI - run: | - go install github.com/DomainCraft/DomainCraft/cmd/domaincraft@${{ env.CORE_VERSION == 'main' && 'latest' || env.CORE_VERSION }} - - # 5. Generate code from the kitchen-sink domain using the current bridge. - - name: Generate Code - run: | - # Adjust bridge_path if your templates live in a subdirectory. - bridge_path="." - domaincraft generate \ - --domain ./core/compliance-suite/kitchen-sink.yaml \ - --bridge "$bridge_path" \ - --output ./test-app \ - --non-interactive - - # 6. Build & start the generated application (API + DB). - - name: Start Application - working-directory: ./test-app - run: | - docker compose up -d --build - # Wait for the API to become healthy. The generated app listens on - # $API_PORT (9000 by default — see project.deploy.port). - timeout 120 bash -c 'until [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://localhost:${API_PORT}/health/ready)" == "200" ]]; do sleep 2; done' || { - echo "::error::API did not become healthy in time" - docker compose logs --tail=100 api || true - exit 1 - } - - # 7. Install k6 (official Grafana action). - - name: Install k6 - uses: grafana/setup-k6-action@v1 - - # 8. Run the k6 certification suite. - - name: Run Certification Suite - run: | - k6 run -e API_URL=http://localhost:${API_PORT} ./core/compliance-suite/suite.js - - # 9. Cleanup. - - name: Stop Application - if: always() - working-directory: ./test-app - run: docker compose down --volumes --remove-orphans diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 93de370..9bf5bdd 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -7,7 +7,91 @@ # unit test), put the check name in the first column, the issue or PR number # in the second, and one line on what broke in the third. internal/validator/validator_test.go::TestValidateReconciledWarningKeepsFKName #3 FK field ending in Id got a second Id in the reconciliation warning -internal/validator/validator_test.go::TestExampleDomainHasNoWarnings #3 shipped example emitted a reconciliation warning -internal/packages/registry_test.go::TestResolveVersionForFrameworkRespectsTargetFramework #3 NuGet resolver picked a version above the generated net10.0 target -cmd/domaincraft/regression_csharp_role_test.go::TestGeneratedCSharpTestsHandleStringRole #3 string role rendered as string.Admin in generated tests -cmd/domaincraft/regression_ts_package_test.go::TestGeneratedTSPackageNameIsKebabCase #3 raw project name with spaces landed in package.json +internal/packages/registry_test.go::TestResolveVersionForFrameworkRespectsTargetFramework #5 NuGet resolver picked a version above the generated net10.0 target +cmd/domaincraft/commands_regression_csharp_role_test.go::TestGeneratedCSharpTestsHandleStringRole #3 string role rendered as string.Admin in generated tests +cmd/domaincraft/commands_regression_ts_package_test.go::TestGeneratedTSPackageNameIsKebabCase #3 raw project name with spaces landed in package.json +internal/bridge/clone_id_test.go::TestValidateCacheIDRejectsEscapes #5 owner/repo id escaped the bridge cache and could delete an arbitrary path +internal/snapshot/paths_test.go::TestSafeRelPathKeepsPathsInsideOutputDir #5 snapshot file path could escape outputDir under --prune +cmd/domaincraft/commands_notify_test.go::TestCachedLatestCoreVersionCachesFailedCheck #5 offline update check repeated the full HTTP timeout on every command +internal/snapshot/rewrite_test.go::TestRenameTransformsIncludesFieldRenames #5 field rename was dropped from the compound transform for custom files +internal/bridge/clone_policy_test.go::TestMaybeUpdatePolicies #5 bridge update policy decisions had no regression coverage +internal/ir/build_entities_test.go::TestBuildDetectsRelationPrimaryKeyCycle #5 relation-typed primary keys overflowed the stack during IR build +internal/seed/seed_test.go::TestGenerateClampsNonPositiveMaxLength #5 negative max sliced a string with a negative bound and panicked +internal/bridge/update_safety_test.go::TestMonorepoRelPathRejectsLookalikes #5 lookalike bridge paths bypassed the community migration consent gate +internal/bridge/hardening_test.go::TestValidatePinRef #5 user @ref could be passed to git as an option +internal/bridge/update_contract_test.go::TestParseBridgeContractVersion #5 malformed remote contract version defaulted to v1 +internal/packages/ssrf_test.go::TestRestrictedRegistryDialerRejectsInternalDNS #5 registry hostname resolving to a private address bypassed SSRF checks +internal/renderer/hardening_test.go::TestRenderCommitPreservesCustomFileCreatedBeforeCommit #5 PR #5 review sweep: contradictory bounds, empty array defaults, int64 clamp wrap, mutating status probe, unbounded clone, custom-file overwrite +internal/snapshot/hardening_test.go::TestSaveReplacesSnapshotWithoutTempLeftovers #5 snapshot.json was written non-atomically +cmd/domaincraft/commands_hardening_test.go::TestBridgeEnsureOptionsRespectsNonInteractiveOnTTY #5 --non-interactive was ignored by the bridge update prompt +cmd/domaincraft/commands_update_security_test.go::TestValidateReleaseURL #5 self-update accepted an unvalidated download URL +cmd/domaincraft/commands_extends_test.go::TestBridgeUpdateNoticeOmitsCachedVersion #5 cached old version was shown as the available version +compliance-suite/regressions_test.go::TestRegressionsTable #5 regression table validated format but not that named checks still exist +internal/parser/parser_test.go::TestParseDuplicateFeature #5 duplicate features in domain.yaml were silently collapsed +internal/renderer/contract_test.go::TestLoadSourceRejectsUnknownWhenCondition #5 unknown when condition rendered templates unconditionally +internal/renderer/version_test.go::TestContractVersionAliasesSpecmeta #5 contract version had four independent definitions and could drift +internal/packages/cache_test.go::TestPersistFailureKeepsResolvedVersion #5 cache write failure discarded a successfully resolved package version +internal/fsutil/fsutil_test.go::TestAtomicWritePreservesExistingFileMode #5 atomic rewrite dropped developer-owned files to mode 0600 +internal/snapshot/migration_test.go::TestMigrationPlanTableNameMatchesIRForAcronymEntity #5 migration plan and IR derived table names through two different rules +cmd/domaincraft/commands_prune_test.go::TestPruneCLICleanupFailureKeepsSnapshot #5 prune reported success and advanced the snapshot after a failed cleanup +internal/ir/build_relations_bench_test.go::TestBuildHubRelationsPreservesFirstMatch #5 relation indexing changed first-match semantics on hub entities +internal/renderer/load_test.go::TestLoadSourceFailsClosedOnMissingBridgeYaml #5 renderer guessed a config path for a directory without bridge.yaml +internal/bridge/embed_test.go::TestEmbeddedBridgesMatchTree #5 embedded bridge tree omitted underscore-prefixed helper templates +internal/bridge/resolver_test.go::TestResolver_MissingPathLikeIsErrorNotClone #5 missing path-like bridge input fell through to cloning github.com/../domaincraftcsharp +internal/lexer/lexer_test.go::TestLexerRejectsUnclosedTypeDeclaration #5 unclosed relation( and enum( declarations were silently normalized into valid types +internal/ir/build_relations_test.go::TestReconciliationRuleAgreesAcrossValidatorAndIR #5 validator and IR applied different one-to-many reconciliation rules +internal/ir/seed_kind_test.go::TestKindOfFollowsSpecmetaClassification #5 KindOf duplicated type classification and could drift from specmeta +internal/ir/contract_test.go::TestValidationRulesSemanticOrder #5 validation rules came out in alphabetical order instead of required, format, length, numeric +internal/ir/toposort_test.go::TestTopoSortInsertReadyKeepsNameOrder #5 ready queue could lose name order when entities became ready during topological sort +internal/snapshot/snapshot_test.go::TestLoadRejectsIncompatibleFormatVersion #5 Load accepted snapshots with any format_version, so stale snapshots could trigger destructive prune +internal/renderer/bridgefuncs_test.go::TestBuildBridgeFuncsRequiresLiteralSpecs #5 core substituted C# and UI syntax when a bridge omitted literal specs +internal/renderer/render_test.go::TestResolvePackagesHasNoLanguageSpecificFrameworkDefault #5 core hardcoded net10.0 as the package-resolution framework default; removing it left C# bridges resolving net11.0 packages for net10.0 projects +internal/renderer/enum_array_test.go::TestTSCoreRendersEnumArrayType #5 generated TypeScript enum arrays were empty because the core dropped its array syntax fallback and the bridge declared no array_format +internal/bridgechain/chain_test.go::TestWalkFailsWhenAbsFails #5 a failed Abs left a relative key in the extends cycle detector +pkg/logger/logger_test.go::TestNewWritesDiagnosticsToStderr #5 default logger wrote diagnostics into the data stream +internal/ir/models_test.go::TestFieldOldColumnNameFallsBackToOldName #5 field rename report and migration plan derived old column names through different rules +internal/specmeta/specmeta_test.go::TestJSONReturnsDefensiveCopies #5 WASM specmeta JSON exposed references to the canonical slices and maps +cmd/schema-gen/main_test.go::TestSchemaAllowsExplicitZeros #review JSON schema rejected explicit zeros the parser and validator accepted +pkg/textutil/textutil_test.go::TestCasingKeepsUnicodeValid #review byte-sliced first letter corrupted multi-byte project names +cmd/domaincraft/commands_admin_test.go::TestGenerateAdminPanelPath #review admin bridge resolution and rendering had no CLI coverage +internal/ir/endpoints_test.go::TestEndpointsDoNotShareErrorStatuses #review endpoint pairs shared one ErrorStatuses backing array; mutating one changed its sibling +internal/ir/dto_test.go::TestDTOFieldsDoNotShareValidations #review DTO projections copied Field but not Field.Validations; mutating a DTO changed the IR field +internal/renderer/models_test.go::TestSeedReturnsDefensiveCopy #review RenderContext.Seed() returned Records directly; mutating the result changed SeedData +internal/bridge/context_test.go::TestCommandContextConcurrentAccess #review global commandCtx was read and written without synchronization and raced under -race +internal/validator/validator_hardening_test.go::TestAuthJWTRequiresEntityAndRoles #5 jwt auth without an auth entity or roles validated cleanly then crashed template rendering +internal/lexer/lexer_hardening_test.go::TestUnterminatedModifierList #review field definition with an unclosed modifier list was accepted as valid +internal/parser/parser_hardening_test.go::TestStrictParsingRejectsStructuralShortcuts #5 fields sequence and unknown keys smuggled through YAML merges bypassed strict decoding +internal/snapshot/snapshot_hardening_test.go::TestRewritePreservesInvalidUTF8Bytes #review prune rewrite replaced invalid UTF-8 bytes with U+FFFD in developer-owned files +internal/templatefuncs/templatefuncs_hardening_test.go::TestSetInitializesNilMap #review Set template function panicked on a nil registry-packages map +internal/appdir/appdir_test.go::TestBaseOverrideConcurrentAccess #review baseOverride was written without synchronization and raced under -race +internal/bridge/bridge_hardening_test.go::TestParseGitHubRefAllowsSlashInPin #5 a pinned ref containing a slash was rejected before splitPinRef ran +internal/packages/packages_hardening_test.go::TestVersionStoreReportsStorageErrors #5 every ReadJSON error was masked as a cache miss and the file was overwritten +cmd/domaincraft/commands_infra_test.go::TestBuildStampsOnlyExactTags #review local builds stamped the nearest tag onto an untagged commit +internal/fsutil/fsutil_hardening_test.go::TestLocalPathWithinRejectsEscape #review path-containment helper had no direct escape test +internal/validator/validator_test.go::TestValidationDiagnosticsAreDeterministic #review validation diagnostics changed line order between runs +cmd/domaincraft/commands_contract_test.go::TestBridgeMetadataRejectsNegativeContractVersion #review lock-file reader accepted a negative contract_version the renderer rejects +internal/bridge/bridge_hardening_test.go::TestCacheSourceMatchesRepairsCorruptMeta #review unreadable cache metadata discarded a usable bridge checkout +internal/bridge/bridge_hardening_test.go::TestGitHeadResultDistinguishesFailure #review a failed git probe was indistinguishable from an empty HEAD +internal/bridge/bridge_hardening_test.go::TestCheckForUpdateRejectsStaleCommitWhenGitFails #review missing git produced a false update notice +internal/bridge/update_pin_test.go::TestFinishUpdateFetchesMissingPinnedRef #review shallow clone left a pinned bridge on the default branch +internal/bridge/update_pin_test.go::TestFinishUpdateDropsPinWhenRefCannotBeFetched #review metadata kept a pin the checkout no longer held +internal/snapshot/migration_test.go::TestDropColumnUsesCanonicalRelationColumn #review DropColumn emitted the logical field name for a relation and left the FK column behind +internal/snapshot/migration_test.go::TestDropColumnFallsBackForLegacySnapshot #review old snapshots without column names must still produce a DropColumn +internal/snapshot/migration_test.go::TestShadowedRenameStillDropsOldColumn #review shadowed rename skipped DropColumn and left a stale column in the DB +internal/snapshot/migration_test.go::TestChainedRenameUsesSnapshotColumn #review chained rename generated RenameColumn from a name that no longer existed in the DB +internal/snapshot/migration_test.go::TestFieldRenameReportUsesCanonicalColumns #review rename report showed logical field names instead of the FK columns the DB actually has +cmd/domaincraft/commands_prune_test.go::TestPruneCLICommunityConsentGate #review missing consent was rejected after rendering and pruning had already modified the project +cmd/domaincraft/commands_hardening_test.go::TestRootCommandSuppressesCobraErrorNoise #review a bare positional argument to generate was accepted and rejected only after files were written +internal/bridge/update_metadata_test.go::TestApplyUpdateRejectsCorruptMetadata #review corrupt cache metadata silently dropped a pin and moved the checkout to the default branch +internal/packages/packages_hardening_test.go::TestCachedResolveReportsUnreadableCache #review unreadable package-version cache degraded to a cacheless resolve without any diagnostic +cmd/domaincraft/commands_update_security_test.go::TestValidateReleaseRedirectRejectsCredentials #review release redirects with userinfo passed validation while direct release URLs rejected them +internal/snapshot/hardening_test.go::TestDeleteFileIsIdempotent #review an already-removed orphan made --prune fail instead of reaching the requested state +internal/snapshot/hardening_test.go::TestRenameEntityFileLeavesExistingDestination #review rename could overwrite a developer file created between the check and the rename +internal/snapshot/hardening_test.go::TestComputeDiffReportsSkippedManifestPaths #review unsafe or missing manifest paths were dropped from the diff with no diagnostic +internal/seed/seed_test.go::TestStepExclusiveInt64DoesNotWrapAtBounds #review generic type switch sent named int64 types down the float path and could overflow at the bounds +internal/seed/seed_test.go::TestNormalizeOutOfRangeIntegralSeedDoesNotWrap #review an out-of-range float seed wrapped to a negative int64 instead of a safe zero +cmd/domaincraft/commands_hardening_test.go::TestSanitizeStreamChunk #review unsanitized child-process output could inject terminal sequences and fake success messages +cmd/domaincraft/commands_init_test.go::TestRenderScenarioRejectsControlCharacters #review a newline or NUL in --name changed the structure of the generated domain.yaml +pkg/logger/logger_test.go::TestNewWithWriterNeverColorsBuffers #review logger colors were decided from process stderr after output had been redirected to a buffer +internal/interactive/theme_test.go::TestFitVisible #review wide CJK and emoji counted as one column, so a "fitting" prompt wrapped and broke in-place redraw +internal/specmeta/specmeta_test.go::TestSplitArrayDefaultRespectsQuotes #review a comma inside a quoted array default was treated as a separator by the validator and seed generator but not by the lexer diff --git a/compliance-suite/regressions_test.go b/compliance-suite/regressions_test.go index 88ff2df..0bc64c9 100644 --- a/compliance-suite/regressions_test.go +++ b/compliance-suite/regressions_test.go @@ -1,7 +1,10 @@ +// Package compliance verifies that the regression table names real checks. package compliance import ( + "fmt" "os" + "path/filepath" "strings" "testing" ) @@ -9,8 +12,11 @@ import ( // TestRegressionsTable guards the regression table format: // every non-comment line must have exactly three tab-separated fields // (check name, issue/PR reference, a line on what broke), the check name -// must be non-empty and unique. This is the enforcement for the rule -// "every bug fix adds its check here; a removed name is an error". +// must be non-empty and unique. A `file::TestX` name must still point at +// an existing test file that defines TestX with at least one assertion, so a +// removed, renamed or emptied check cannot silently pass. This is the +// enforcement for the rule "one row per test file; a removed check name is an +// error". func TestRegressionsTable(t *testing.T) { data, err := os.ReadFile("regressions.tsv") if err != nil { @@ -18,6 +24,8 @@ func TestRegressionsTable(t *testing.T) { } seen := make(map[string]bool) + // Read each referenced test file once. + sources := make(map[string]string) for i, line := range strings.Split(string(data), "\n") { line = strings.TrimSuffix(line, "\r") trimmed := strings.TrimSpace(line) @@ -49,5 +57,160 @@ func TestRegressionsTable(t *testing.T) { t.Errorf("duplicate check name %q (line %d)", name, i+1) } seen[name] = true + + ref, testName, ok := strings.Cut(name, "::") + if !ok || ref == "" || testName == "" { + continue // Not a file::TestX reference. + } + path := resolveRegressionTestFile(t, ref, i+1) + if path == "" { + continue + } + src, cached := sources[path] + if !cached { + body, rerr := os.ReadFile(path) + if rerr != nil { + t.Errorf("line %d: read %s: %v", i+1, path, rerr) + sources[path] = "" + continue + } + src = string(body) + sources[path] = src + } + if src == "" { + continue // Read already reported as an error. + } + defined, hasAssert := regressionFuncHasAssert(src, testName) + if !defined { + t.Errorf("line %d: %s does not define func %s(", i+1, path, testName) + continue + } + if !hasAssert { + t.Errorf("line %d: %s defines func %s( without an assertion: a check with no assert proves nothing", i+1, path, testName) + } + } +} + +// regressionFuncHasAssert reports whether src defines func testName(...) and, +// if so, whether that function's body contains at least one assertion. A body +// with no assertion would let an empty stub satisfy the table. The body ends +// at the first line starting with "}" in column zero, which in gofmt'd Go is +// the function's closing brace. +func regressionFuncHasAssert(src, testName string) (defined, hasAssert bool) { + sig := "func " + testName + "(" + idx := strings.Index(src, sig) + if idx < 0 { + return false, false + } + open := strings.IndexByte(src[idx:], '{') + if open < 0 { + return false, false + } + body := src[idx+open+1:] + if end := strings.Index(body, "\n}"); end >= 0 { + body = body[:end] + } + for _, assert := range []string{"t.Fatal", "t.Error", "assert.", "require."} { + if strings.Contains(body, assert) { + return true, true + } + } + return true, false +} + +// TestRegressionsTableRejectsEmptyBody guards the guard: a listed function +// whose body is empty, or only computes values without asserting them, must +// be rejected by regressionFuncHasAssert. The source is written to a real +// temp file so the check sees exactly the bytes it sees for table entries. +func TestRegressionsTableRejectsEmptyBody(t *testing.T) { + src := `package sample + +import "testing" + +func TestEmptyBody(t *testing.T) { +} + +func TestNoAssert(t *testing.T) { + got := 1 + 1 + _ = got +} + +func TestWithAssert(t *testing.T) { + if 1+1 != 2 { + t.Fatal("bad math") + } +} +` + path := filepath.Join(t.TempDir(), "sample_test.go") + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { + t.Fatalf("write temp file: %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read temp file: %v", err) + } + for _, tc := range []struct { + name string + defined bool + hasAssert bool + }{ + {name: "TestEmptyBody", defined: true, hasAssert: false}, + {name: "TestNoAssert", defined: true, hasAssert: false}, + {name: "TestWithAssert", defined: true, hasAssert: true}, + {name: "TestMissing", defined: false, hasAssert: false}, + } { + t.Run(tc.name, func(t *testing.T) { + defined, hasAssert := regressionFuncHasAssert(string(data), tc.name) + if defined != tc.defined || hasAssert != tc.hasAssert { + t.Errorf("regressionFuncHasAssert(%q) = (%v, %v), want (%v, %v)", tc.name, defined, hasAssert, tc.defined, tc.hasAssert) + } + }) + } +} + +// resolveRegressionTestFile turns a check's file reference into a repo-root +// relative path. Paths with a separator are used as-is; bare names are +// resolved against *_test.go files under the repo root (the test runs from +// compliance-suite/, one level below it). +func resolveRegressionTestFile(t *testing.T, ref string, line int) string { + t.Helper() + + if strings.ContainsAny(ref, `/\`) { + // Table paths are repo-root relative; tests run one level below it. + return filepath.Join("..", filepath.FromSlash(ref)) + } + if !strings.HasSuffix(ref, "_test.go") { + ref += "_test.go" + } + + root := ".." + found := "" + err := filepath.WalkDir(root, func(path string, d os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if d.IsDir() { + switch d.Name() { + case ".git", "node_modules", "bin": + return filepath.SkipDir + } + return nil + } + if d.Name() != ref { + return nil + } + if found != "" { + return fmt.Errorf("ambiguous file %q: %s and %s", ref, found, path) + } + found = filepath.ToSlash(path) + return nil + }) + if err != nil { + t.Errorf("line %d: resolve %q: %v", line, ref, err) + return "" + } + if found == "" { + t.Errorf("line %d: no %s under %s", line, ref, root) } + return found } diff --git a/compliance-suite/suite.js b/compliance-suite/suite.js index 953af6c..522f7db 100644 --- a/compliance-suite/suite.js +++ b/compliance-suite/suite.js @@ -337,7 +337,9 @@ function testAuthAndJwtSecurity() { function testCrudAndValidation() { // Unique sku per run: a soft-deleted row from a previous run keeps its unique // column occupied, so a fixed sku would 409 instead of exercising CRUD. - const crudSku = 'PRD-' + Math.floor(Date.now() / 1000).toString(36).toUpperCase(); + // Seconds alone collide when two runs land in the same second; add randomness. + const crudSku = 'PRD-' + Math.floor(Date.now() / 1000).toString(36).toUpperCase() + + '-' + Math.random().toString(36).slice(2, 10).toUpperCase(); // CREATE const createRes = http.post( diff --git a/compliance-suite/tck-matrix.json b/compliance-suite/tck-matrix.json new file mode 100644 index 0000000..36856b0 --- /dev/null +++ b/compliance-suite/tck-matrix.json @@ -0,0 +1,46 @@ +{ + "comment": "Single source of truth for certification targets. Adding a bridge = one row here; compliance-suite/tck.sh discovers it with Python. kind: hermetic = npm suite only; glue = generated project typecheck; k6 = generated backend over Docker Compose + suite.js + interop clients.", + "targets": [ + { + "id": "ts-core", + "kind": "hermetic", + "enabled": true, + "bridge": "bridges/typescript/core", + "tck_dir": "bridges/typescript/core/tck", + "script": "certify" + }, + { + "id": "ts-client", + "kind": "hermetic", + "enabled": true, + "bridge": "bridges/typescript/client", + "tck_dir": "bridges/typescript/client/tck", + "script": "certify" + }, + { + "id": "react-rest", + "kind": "glue", + "enabled": true, + "bridge": "bridges/typescript/react", + "output": "bridges/typescript/react/tck/generated", + "script": "typecheck" + }, + { + "id": "csharp-rest", + "kind": "k6", + "enabled": true, + "bridge": "bridges/csharp/transport/rest", + "output": "test-app", + "port": 9000, + "health_path": "/health/ready", + "interop": [ + { + "id": "ts-client", + "bridge": "bridges/typescript/client", + "tck_dir": "bridges/typescript/client/tck", + "script": "interop" + } + ] + } + ] +} diff --git a/compliance-suite/tck.sh b/compliance-suite/tck.sh new file mode 100755 index 0000000..7a8072b --- /dev/null +++ b/compliance-suite/tck.sh @@ -0,0 +1,206 @@ +#!/usr/bin/env bash +# Single TCK entrypoint. The workflow only declares jobs; all logic is here. +# Usage: tck.sh [target-json] +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DOMAIN=compliance-suite/kitchen-sink.yaml +PY="$(command -v python3 || command -v python || true)" +cd "$ROOT" + +fail() { echo "error: $*" >&2; exit 1; } +need() { command -v "$1" >/dev/null 2>&1 || fail "tool not found: $1"; } +[[ -n "$PY" ]] || fail "python3 not found" + +field() { + "$PY" - "$1" "$2" "${3-}" <<'PY' +import json, sys +v = json.loads(sys.argv[1]).get(sys.argv[2]) +print(sys.argv[3] if v is None else json.dumps(v, separators=(",", ":")) if isinstance(v, (dict, list)) else v) +PY +} + +output_dir() { + local out; out="$(field "$1" output)" + if [[ -n "$out" ]]; then echo "$out"; else out="$(field "$1" tck_dir)"; [[ -n "$out" ]] || return 1; echo "$out/generated"; fi +} + +generate() { + local target="$1" + need go + local bridge out + bridge="$(field "$target" bridge)" + out="$(output_dir "$target")" + echo "generate: $bridge -> $out" >&2 + go run ./cmd/domaincraft generate --domain "$DOMAIN" --bridge "$bridge" --output "$out" --non-interactive +} + +# Scope in one pass: core change or force -> all; bridge change -> that bridge +# plus every target whose extends chain contains it. No jq, no Go command. +discover() { + local changed="" force=0 + if [[ "${TCK_SCOPE_FORCE:-0}" == 1 ]]; then force=1 + elif [[ -n "${GITHUB_BASE_REF:-}" ]]; then + git fetch origin "$GITHUB_BASE_REF" || fail "cannot fetch $GITHUB_BASE_REF" + changed="$(git diff --name-only "origin/$GITHUB_BASE_REF...HEAD")" + elif [[ ! -t 0 ]]; then changed="$(cat)"; fi + echo "scope: $force force, $(printf '%s\n' "$changed" | awk 'NF{n++}END{print n+0}') changed paths" >&2 + + local result + result="$("$PY" - "$changed" "$force" <<'PY' +import json, os, pathlib, sys +matrix = json.load(open("compliance-suite/tck-matrix.json", encoding="utf-8")) +raw = matrix.get("targets", []) +ids = [t.get("id", "") for t in raw] +if not ids or len(ids) != len(set(ids)): + sys.exit("tck-matrix.json: targets must be non-empty with unique ids") +kinds = {"hermetic", "glue", "k6"} +for t in raw: + k, tid = t.get("kind"), t["id"] + if k not in kinds: sys.exit("%s: unknown kind %r" % (tid, k)) + if not t.get("bridge"): sys.exit("%s: missing bridge" % tid) + if k == "hermetic" and not (t.get("tck_dir") and t.get("script")): sys.exit("%s: hermetic needs tck_dir and script" % tid) + if k == "glue" and not (t.get("output") and t.get("script")): sys.exit("%s: glue needs output and script" % tid) + if k == "k6" and not (t.get("output") and t.get("port") and t.get("health_path")): sys.exit("%s: k6 needs output, port, health_path" % tid) + for it in t.get("interop", []): + if not (it.get("id") and it.get("bridge") and it.get("tck_dir") and it.get("script")): + sys.exit("%s: interop needs id, bridge, tck_dir, script" % tid) +targets = [t for t in raw if t.get("enabled", True)] +changed = [p.strip().replace("\\", "/") for p in sys.argv[1].splitlines() if p.strip()] +force = sys.argv[2] == "1" +core = ("internal/", "pkg/", "spec/", "cmd/", "compliance-suite/", ".github/workflows/", "go.mod", "go.sum") + +def norm(p): return os.path.normpath(p).replace("\\", "/") + +if force or not changed or any(p.startswith(core) for p in changed): + selected = targets +else: + manifests = list(pathlib.Path("bridges").rglob("bridge.yaml")) + graph, registry = {}, {} + for m in manifests: + d = norm(str(m.parent)); ext = name = "" + for line in m.read_text(encoding="utf-8").splitlines(): + key, _, value = line.partition(":") + if key.strip() == "extends": ext = value.strip().strip("\"'") + if key.strip() == "name": name = value.strip().strip("\"'") + graph[d] = ext + if name: registry[name] = d + + def resolve(ref, base): + if not ref: return "" + if ref in registry: return registry[ref] + if ref.startswith("."): return norm(os.path.join(os.path.dirname(base), ref)) + for cand in (ref, norm(os.path.join(os.path.dirname(base), ref))): + if os.path.isfile(os.path.join(cand, "bridge.yaml")): return norm(cand) + sys.exit("unresolved extends ref %r in %s: use a registry id or local path" % (ref, base)) + + def chain(start): + out, seen = [], set() + while start and start not in seen: + seen.add(start); out.append(start) + start = resolve(graph.get(start, ""), start) + return out + + roots = set() + for p in changed: + cur = norm(p) + while cur and cur != ".": + if os.path.isfile(os.path.join(cur, "bridge.yaml")): + roots.add(cur); break + cur = os.path.dirname(cur) + selected = [t for t in targets if any(r in chain(norm(t["bridge"])) for r in roots)] + if roots and not selected: + sys.exit("bridge change selected no TCK target: add the bridge to tck-matrix.json") + +# An interop oracle lives in a client TCK but runs inside the k6 job. A change +# to it must select the backend target that executes it, not just the client. +ids = {t["id"] for t in selected} +for t in targets: + for item in t.get("interop", []): + d = item.get("tck_dir", "").rstrip("/") + if d and any(p == d or p.startswith(d + "/") for p in changed): + ids.add(t["id"]) +selected = [t for t in targets if t["id"] in ids] + +def bucket(kinds): + return json.dumps([t for t in selected if t["kind"] in kinds], separators=(",", ":")) +print("node=" + bucket(("hermetic", "glue"))) +print("k6=" + bucket(("k6",))) +PY +)" + if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + echo "$result" >> "$GITHUB_OUTPUT" + echo "scope: written to GITHUB_OUTPUT" >&2 + else + echo "$result" + fi +} + +node_suite() { + local target="$1" kind dir script out + kind="$(field "$target" kind)" + generate "$target" + if [[ "$kind" == glue ]]; then + out="$(output_dir "$target")"; script="$(field "$target" script)" + echo "typecheck: $script in $out" >&2 + (cd "$out" && npm install --no-audit --no-fund && npm run "$script") + else + dir="$(field "$target" tck_dir)"; script="$(field "$target" script)" + echo "certify: $script in $dir" >&2 + (cd "$dir" && npm ci --no-audit --no-fund && npm run "$script") + fi +} + +backend_up() { + local target="$1" out url + generate "$target" + out="$(output_dir "$target")" + url="http://127.0.0.1:$(field "$target" port 9000)$(field "$target" health_path /health/ready)" + echo "backend-up: $out, waiting for $url" >&2 + ( + cd "$out" + docker compose up -d --build + timeout 180 bash -c 'until [[ "$(curl -s -o /dev/null -w "%{http_code}" "$1")" == "200" ]]; do sleep 2; done' _ "$url" || { + echo "::error::API did not become healthy" >&2; docker compose logs --tail=100 || true; exit 1; } + ) +} + +backend_down() { + local target="$1" out + out="$(output_dir "$target")" + [[ -d "$out" ]] || { echo "backend-down: nothing to stop" >&2; return 0; } + (cd "$out" && docker compose down --volumes --remove-orphans) +} + +interop() { + local target="$1" port; port="$(field "$target" port 9000)" + need go; need npm + "$PY" - "$target" <<'PY' | while read -r item; do +import json, sys +for x in json.loads(sys.argv[1]).get("interop", []): + print(json.dumps(x, separators=(",", ":"))) +PY + local dir script bridge + dir="$(field "$item" tck_dir)"; script="$(field "$item" script)"; bridge="$(field "$item" bridge)" + echo "interop: $script in $dir" >&2 + go run ./cmd/domaincraft generate --domain "$DOMAIN" --bridge "$bridge" --output "$dir/generated" --non-interactive + # IPv4 literal matches the Docker-published port; no resolver ambiguity. + (cd "$dir" && npm ci --no-audit --no-fund && API_URL="http://127.0.0.1:${port}" npm run "$script") + echo "::notice::interop $(field "$item" id) passed" + done +} + +logs() { + local target="$1" out id; out="$(output_dir "$target")"; id="$(field "$target" id)" + [[ -d "$out" ]] || return 0 + (cd "$out" && docker compose logs --tail=300 > "${RUNNER_TEMP:-$TMPDIR}/compose-${id}.log" || true) +} + +case "${1:-}" in + discover) discover ;; + node) node_suite "$2" ;; + backend-up) need docker; need curl; need timeout; backend_up "$2" ;; + backend-down) need docker; backend_down "$2" ;; + interop) interop "$2" ;; + logs) need docker; logs "$2" ;; + *) echo "usage: $0 [target-json]" >&2; exit 2 ;; +esac diff --git a/internal/appdir/appdir.go b/internal/appdir/appdir.go index b00c306..c3a447b 100644 --- a/internal/appdir/appdir.go +++ b/internal/appdir/appdir.go @@ -8,48 +8,51 @@ package appdir import ( "os" "path/filepath" + "sync/atomic" ) // baseOverride, when set, redirects the app base directory. Used by tests so -// they never write into the user's real home directory. -var baseOverride string +// they never write into the user's real home directory. The atomic pointer +// keeps parallel tests from racing on the override. +var baseOverride atomic.Pointer[string] // SetBaseForTesting redirects the app base directory for a test. Restore with // SetBaseForTesting("") in a defer. func SetBaseForTesting(dir string) { - baseOverride = dir + if dir == "" { + baseOverride.Store(nil) + return + } + baseOverride.Store(&dir) } // Base returns the per-user DomainCraft directory, typically ~/.domaincraft. // Returns .domaincraft relative to the current directory when the home // directory is unavailable. The directory is NOT created; callers that write // under it are responsible for creating the subdirectories they need. -func Base() (string, error) { - if baseOverride != "" { - return baseOverride, nil +// Path resolution cannot fail, so callers get a plain string. +func Base() string { + if override := baseOverride.Load(); override != nil && *override != "" { + return *override } home, err := os.UserHomeDir() if err != nil || home == "" { - return filepath.Join(".domaincraft"), nil + return ".domaincraft" } - return filepath.Join(home, ".domaincraft"), nil + return filepath.Join(home, ".domaincraft") } // UnionDir returns the path of a subdirectory under the app base directory, // e.g. appdir.UnionDir("bridges") -> ~/.domaincraft/bridges. -func UnionDir(elem ...string) (string, error) { - base, err := Base() - if err != nil { - return "", err - } - parts := append([]string{base}, elem...) - return filepath.Join(parts...), nil +func UnionDir(elem ...string) string { + parts := append([]string{Base()}, elem...) + return filepath.Join(parts...) } // CacheDir resolves a per-consumer cache directory under ~/.domaincraft/cache. // Each consumer passes its own name so caches never mix, e.g. // appdir.CacheDir("csharp-restful") -> ~/.domaincraft/cache/csharp-restful. -func CacheDir(names ...string) (string, error) { +func CacheDir(names ...string) string { parts := append([]string{"cache"}, names...) return UnionDir(parts...) } diff --git a/internal/appdir/appdir_test.go b/internal/appdir/appdir_test.go new file mode 100644 index 0000000..45ee155 --- /dev/null +++ b/internal/appdir/appdir_test.go @@ -0,0 +1,93 @@ +package appdir + +import ( + "path/filepath" + "strconv" + "sync" + "testing" +) + +func setBaseForTest(t *testing.T, dir string) { + t.Helper() + old := baseOverride.Load() + SetBaseForTesting(dir) + t.Cleanup(func() { baseOverride.Store(old) }) +} + +// TestBaseFallback pins the home-directory fallback. Every cache path derives +// from Base, so a regression here redirects caches silently. +func TestBaseFallback(t *testing.T) { + setBaseForTest(t, "") + + t.Run("from home env", func(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + got := Base() + if want := filepath.Join(home, ".domaincraft"); got != want { + t.Errorf("Base() = %q, want %q", got, want) + } + }) + + t.Run("no home", func(t *testing.T) { + t.Setenv("HOME", "") + t.Setenv("USERPROFILE", "") + t.Setenv("HOMEDRIVE", "") + t.Setenv("HOMEPATH", "") + got := Base() + if got != ".domaincraft" { + t.Errorf("Base() = %q, want .domaincraft", got) + } + }) +} + +// TestBaseOverrideConcurrentAccess would report a data race under -race if +// SetBaseForTesting and Base touched an unsynchronized global. +func TestBaseOverrideConcurrentAccess(t *testing.T) { + setBaseForTest(t, t.TempDir()) + var wg sync.WaitGroup + for i := range 16 { + wg.Add(2) + go func() { + defer wg.Done() + _ = Base() + }() + go func(i int) { + defer wg.Done() + SetBaseForTesting(filepath.Join("parallel", strconv.Itoa(i))) + }(i) + } + wg.Wait() + SetBaseForTesting("final") + if got := Base(); got != "final" { + t.Fatalf("Base() after concurrent access = %q; want final", got) + } +} + +// TestDerivedPaths checks the test seam and both path constructors: the suite +// redirects the base, so no test may write into the real ~/.domaincraft. +func TestDerivedPaths(t *testing.T) { + dir := filepath.Join(t.TempDir(), "app") + setBaseForTest(t, dir) + + t.Run("override", func(t *testing.T) { + got := Base() + if got != dir { + t.Errorf("Base() = %q, want %q", got, dir) + } + }) + + t.Run("union dir appends components", func(t *testing.T) { + got := UnionDir("bridges", "cache") + if want := filepath.Join(dir, "bridges", "cache"); got != want { + t.Errorf("UnionDir() = %q, want %q", got, want) + } + }) + + t.Run("cache dir is namespaced", func(t *testing.T) { + got := CacheDir("csharp-rest", "v2") + if want := filepath.Join(dir, "cache", "csharp-rest", "v2"); got != want { + t.Errorf("CacheDir() = %q, want %q", got, want) + } + }) +} diff --git a/internal/bridge/bridge_hardening_test.go b/internal/bridge/bridge_hardening_test.go new file mode 100644 index 0000000..42c04cd --- /dev/null +++ b/internal/bridge/bridge_hardening_test.go @@ -0,0 +1,336 @@ +package bridge + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +func TestParseGitHubRefAllowsSlashInPin(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + input string + repo string + ref string + wantErr bool + }{ + {name: "branch with slash", input: "owner/repo@feature/branch", repo: "owner/repo", ref: "feature/branch"}, + {name: "plain shorthand", input: "owner/repo", repo: "owner/repo"}, + {name: "repo with extra segment", input: "owner/repo/extra", wantErr: true}, + {name: "option-like pin", input: "owner/repo@--upload-pack=sh", wantErr: true}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + repo, ref, err := parseGitHubRef(c.input) + if c.wantErr { + if err == nil { + t.Fatalf("parseGitHubRef(%q) unexpectedly succeeded", c.input) + } + return + } + if err != nil || repo != c.repo || ref != c.ref { + t.Fatalf("parseGitHubRef(%q) = (%q, %q, %v)", c.input, repo, ref, err) + } + }) + } +} + +func TestGithubOriginMatchesExactRepository(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + origin string + want bool + }{ + {name: "https origin", origin: "https://github.com/owner/repo.git", want: true}, + {name: "ssh origin", origin: "git@github.com:owner/repo.git", want: true}, + {name: "lookalike repository", origin: "https://github.com/owner/repo-evil.git", want: false}, + {name: "empty origin", origin: "", want: false}, + } { + t.Run(c.name, func(t *testing.T) { + if got := githubOriginMatches(c.origin, "owner/repo"); got != c.want { + t.Errorf("githubOriginMatches(%q) = %t, want %t", c.origin, got, c.want) + } + }) + } +} + +func TestCacheSourceMatchesFailsClosedWithoutProof(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + entry := cacheEntry("foreign-cache", "owner/repo") + if err := os.MkdirAll(CachePath(entry), 0o755); err != nil { + t.Fatal(err) + } + if cacheSourceMatches(entry) { + t.Fatal("a cache without metadata or a matching remote was accepted as owned") + } +} + +// TestCacheSourceMatchesRepairsCorruptMeta pins F21: a truncated metadata file +// must not cost a working checkout. If git's origin proves ownership, the cache +// is kept and the metadata rebuilt. A foreign origin still fails closed. +func TestCacheSourceMatchesRepairsCorruptMeta(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("corrupt-meta", "owner/corrupt-meta") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, dir, "main") + origin := "https://github.com/owner/corrupt-meta.git" + if out := testGit(t, dir, "remote", "add", "origin", origin); out != "" { + t.Fatalf("unexpected git output: %q", out) + } + // Simulate a truncated/partially written metadata file. + if err := os.WriteFile(filepath.Join(dir, MetaFileName), []byte("{\"id\":\"corrupt"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := ReadMeta(entry); err == nil { + t.Fatal("test fixture: corrupt metadata should not decode") + } + if !cacheSourceMatches(entry) { + t.Fatal("a matching git origin should prove ownership of a corrupt-meta cache") + } + meta, err := ReadMeta(entry) + if err != nil || meta == nil { + t.Fatalf("metadata was not rebuilt: %+v, %v", meta, err) + } + if meta.Source != entry.GitHub { + t.Fatalf("rebuilt source = %q, want %q", meta.Source, entry.GitHub) + } + if meta.Version != "1.0.0" || meta.Commit == "" || meta.Branch != "main" { + t.Fatalf("metadata not rebuilt from checkout: %+v", meta) + } + + // A foreign origin must stay fail-closed and must not be repaired. + testGit(t, dir, "remote", "set-url", "origin", "https://github.com/other/foreign.git") + if err := os.WriteFile(filepath.Join(dir, MetaFileName), []byte(`{"id":"corrupt`), 0o644); err != nil { + t.Fatal(err) + } + if cacheSourceMatches(entry) { + t.Fatal("a foreign origin was accepted as proof of ownership") + } + if _, err := ReadMeta(entry); err == nil { + t.Fatal("foreign metadata was rewritten despite a mismatched origin") + } +} + +// TestGitHeadResultDistinguishesFailure pins F22's seam: a missing or damaged +// checkout is an error, never an empty but successfully read HEAD. +func TestGitHeadResultDistinguishesFailure(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("head-result", "owner/head-result") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if head, err := gitHeadResult(entry); err == nil { + t.Fatalf("gitHeadResult on a non-repo = (%q, nil), want an error", head) + } + makeBridgeRepo(t, dir, "main") + head, err := gitHeadResult(entry) + if err != nil || head == "" { + t.Fatalf("gitHeadResult on a valid checkout = (%q, %v)", head, err) + } + if want := testGit(t, dir, "rev-parse", "HEAD"); head != want { + t.Fatalf("gitHeadResult = %q, want %q", head, want) + } +} + +// TestCheckForUpdateRejectsStaleCommitWhenGitFails pins F22: with no readable +// HEAD, a stale metadata commit must not be compared against the remote tip. +func TestCheckForUpdateRejectsStaleCommitWhenGitFails(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("stale-commit", "owner/stale-commit") + if err := os.MkdirAll(CachePath(entry), 0o755); err != nil { + t.Fatal(err) + } + writeBridgeYAML(t, CachePath(entry), "1.0.0") + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", Commit: "stale-commit", + Branch: "main", LastCheckedAt: time.Now().Add(-48 * time.Hour), + }); err != nil { + t.Fatal(err) + } + stubGitHubAPI(t, "new-remote-commit", "") + + upd, err := CheckForUpdate(entry, 0) + if err != nil || upd != nil { + t.Fatalf("CheckForUpdate = (%+v, %v), want no update when HEAD is unreadable", upd, err) + } + meta, err := ReadMeta(entry) + if err != nil { + t.Fatal(err) + } + if meta.Commit != "stale-commit" { + t.Fatalf("stale commit was overwritten: %q", meta.Commit) + } + if meta.LastCheckedAt.Before(time.Now().Add(-time.Hour)) { + t.Fatal("probe attempt was not recorded") + } +} + +// TestCheckForUpdateSyncsHeadBeforeComparing pins the other half of F22: a +// valid checkout is authoritative even when metadata carries an older commit. +func TestCheckForUpdateSyncsHeadBeforeComparing(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("head-sync", "owner/head-sync") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, dir, "main") + head := testGit(t, dir, "rev-parse", "HEAD") + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", Commit: "stale-commit", + Branch: "main", LastCheckedAt: time.Now().Add(-48 * time.Hour), + }); err != nil { + t.Fatal(err) + } + stubGitHubAPI(t, head, "") + + upd, err := CheckForUpdate(entry, 0) + if err != nil || upd != nil { + t.Fatalf("CheckForUpdate = (%+v, %v), want no update after syncing HEAD", upd, err) + } + meta, err := ReadMeta(entry) + if err != nil { + t.Fatal(err) + } + if meta.Commit != head { + t.Fatalf("metadata commit = %q, want %q", meta.Commit, head) + } +} + +func TestFinishUpdateChecksPinnedContract(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + entry := cacheEntry("pin-contract", "owner/pin-contract") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, dir, "main") + body := "name: test-bridge\nversion: \"1.0.0\"\ncontract_version: 99\n" + if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + testGit(t, dir, "add", ".") + testGit(t, dir, "commit", "-q", "-m", "bump contract") + pin := testGit(t, dir, "rev-parse", "HEAD") + + if _, err := finishUpdate(entry, "main", pin); err == nil || !strings.Contains(err.Error(), "contract") { + t.Fatalf("finishUpdate accepted an unsupported pinned contract: %v", err) + } + // Fail closed: an unsupported pinned tree must not stay in the cache with a + // pin that would make the next run skip its checks. + if _, err := os.Stat(filepath.Join(dir, "bridge.yaml")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("unsupported pinned cache was left behind: %v", err) + } + if meta, err := ReadMeta(entry); err != nil || (meta != nil && meta.Pin != "") { + t.Fatalf("unsupported pin was kept in metadata: %+v, %v", meta, err) + } +} + +func TestRunGitHonoursCommandContext(t *testing.T) { + previous := CommandContext() + defer SetCommandContext(previous) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + SetCommandContext(ctx) + if _, err := runGit(t.TempDir(), "status"); err == nil { + t.Fatal("runGit ignored a cancelled command context") + } +} + +// TestCloneGitContextHasDeadline pins the context source shared by the initial +// clone and every update command. CloneBridge used to pass the raw package +// context to exec.CommandContext, so a stalled remote hung forever. +func TestCloneGitContextHasDeadline(t *testing.T) { + ctx, cancel := gitCommandContext() + defer cancel() + deadline, ok := ctx.Deadline() + if !ok { + t.Fatal("git command context has no deadline") + } + remaining := time.Until(deadline) + if remaining <= 0 || remaining > gitCommandTimeout { + t.Fatalf("git command deadline in %v, want (0, %v]", remaining, gitCommandTimeout) + } + + // The bound composes with CLI cancellation rather than replacing it. + parent, parentCancel := context.WithCancel(context.Background()) + previous := CommandContext() + SetCommandContext(parent) + t.Cleanup(func() { SetCommandContext(previous); parentCancel() }) + child, childCancel := gitCommandContext() + defer childCancel() + parentCancel() + if !errors.Is(child.Err(), context.Canceled) { + t.Fatalf("git context error after parent cancellation = %v, want context.Canceled", child.Err()) + } +} + +// TestCloneBridgeRefusesSymlinkedCachePath checks the cache path before any +// clone is attempted. A planted symlink used to let git write outside the +// cache, while embedded materialization and metadata writes already refused it. +func TestCloneBridgeRefusesSymlinkedCachePath(t *testing.T) { + // appdir's base override is a package global — no t.Parallel here. + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("symlink-cache", "owner/symlink-cache") + cacheDir := CachePath(entry) + if err := os.MkdirAll(appdir.UnionDir("bridges"), 0o755); err != nil { + t.Fatalf("mkdir cache root: %v", err) + } + outside := filepath.Join(t.TempDir(), "outside") + if err := os.MkdirAll(outside, 0o755); err != nil { + t.Fatalf("mkdir outside: %v", err) + } + if err := os.Symlink(outside, cacheDir); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + + err := prepareCloneCacheDir(cacheDir) + if err == nil { + t.Fatal("preparation accepted a symlinked cache path") + } + if !strings.Contains(err.Error(), "symlink") && !strings.Contains(err.Error(), "escape") { + t.Errorf("error = %q, want it to name the symlink refusal", err) + } +} diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index db20c3e..39fd49d 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -1,28 +1,109 @@ package bridge import ( + "errors" "fmt" "os" "os/exec" "path/filepath" + "strings" "time" "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/fsutil" ) -// BridgeCacheDir returns ~/.domaincraft/bridges/. -// Falls back to .domaincraft/bridges in the current directory if the home directory is unavailable. -func BridgeCacheDir() string { - dir, err := appdir.UnionDir("bridges") +// CachePath returns the local cache directory for a bridge entry. +func CachePath(entry RegistryEntry) string { + return filepath.Join(appdir.UnionDir("bridges"), entry.ID) +} + +// cacheIDForGitHub derives a cache-safe ID for a GitHub shorthand. Using the +// bare repository name would make alice/utils and bob/utils share one cache +// directory (and one checkout, including its migrations:). The owner is part +// of the key, with "__" as an unambiguous separator that keeps validateCacheID +// happy: no separators, no dot segments, a single local path component. +func cacheIDForGitHub(repo string) string { + owner, name, ok := strings.Cut(repo, "/") + if !ok || owner == "" || name == "" { + return repo + } + return owner + "__" + name +} + +// cacheSourceMatches reports whether an existing checkout belongs to the +// expected GitHub repository. A foreign cache is replaced, never reused: it +// can carry another owner's templates, migrations and metadata. +func cacheSourceMatches(entry RegistryEntry) bool { + meta, err := ReadMeta(entry) + if err != nil && !errors.Is(err, os.ErrNotExist) { + // A corrupt or unreadable metadata file is not proof of ownership — + // but neither is proof of foreign ownership. The checkout's origin can + // still prove it; on success rebuild the metadata instead of letting + // the caller discard a working checkout and re-clone it. + if !cacheOriginMatches(entry) { + return false + } + // Metadata is advisory: proven ownership must not be thrown away + // because the rewrite failed. A later run retries the rewrite. + _ = WriteMeta(entry, newMetaFromCache(entry)) + return true + } + if meta == nil { + // Legacy cache without metadata: fall back to git's origin. Fail closed + // when there is no remote or it names a different repository. + return cacheOriginMatches(entry) + } + if meta.Source == "" { + return false // metadata without a source cannot prove ownership + } + return meta.Source == entry.GitHub +} + +// cacheOriginMatches checks the checkout's git origin against the expected +// repository. It is the ownership proof for legacy caches and for metadata +// that could not be read. Fail closed on a missing or foreign origin. +func cacheOriginMatches(entry RegistryEntry) bool { + out, err := runGit(CachePath(entry), "remote", "get-url", "origin") if err != nil { - return filepath.Join(".domaincraft", "bridges") + return false } - return dir + return githubOriginMatches(out, entry.GitHub) } -// CachePath returns the local cache directory for a bridge entry. -func CachePath(entry RegistryEntry) string { - return filepath.Join(BridgeCacheDir(), entry.ID) +// githubHost is the canonical host for bridge sources. Origin checks, redirect +// policy and clone URL construction all derive from it so a host change cannot +// leave one of them pointing elsewhere. +const githubHost = "github.com" + +// githubOriginMatches compares a git origin with the expected GitHub slug. +// A substring check would accept an unrelated repository whose name merely +// contains the expected one. +func githubOriginMatches(origin, repo string) bool { + origin = strings.TrimSuffix(strings.TrimSpace(origin), ".git") + for _, prefix := range []string{ + "https://" + githubHost + "/", + "http://" + githubHost + "/", + "ssh://git@" + githubHost + "/", + "git@" + githubHost + ":", + "git://" + githubHost + "/", + } { + if origin == prefix+repo { + return true + } + } + return false +} + +// validateCacheID rejects bridge IDs that could resolve outside the cache +// directory. IDs come from registry entries and from `owner/repo` refs, so a +// separator or a dot segment would otherwise let CloneBridge and ApplyUpdate +// write to or delete an arbitrary path under the user's account. +func validateCacheID(id string) error { + if id == "" || id == "." || id == ".." || !filepath.IsLocal(id) || filepath.Base(id) != id || strings.ContainsAny(id, "/\\") { + return fmt.Errorf("unsafe bridge id %q", id) + } + return nil } // IsCached checks whether a bridge is already cloned and contains bridge.yaml. @@ -62,26 +143,42 @@ type EnsureOptions struct { // the cached copy fresh by checking the upstream repo for newer versions. // Returns the local path to the bridge directory. func EnsureBridge(entry RegistryEntry, opts *EnsureOptions) (string, error) { + if err := validateCacheID(entry.ID); err != nil { + return "", err + } if entry.GitHub == "" { return "", fmt.Errorf("bridge %q has no GitHub repository configured", entry.ID) } cacheDir := CachePath(entry) + if IsCached(entry) && !cacheSourceMatches(entry) { + // A cache entry from a different repository must not be served as this + // bridge: another owner's code and migration commands would be used. + if err := os.RemoveAll(cacheDir); err != nil { + return "", fmt.Errorf("remove foreign bridge cache %q: %w", cacheDir, err) + } + } if !IsCached(entry) { // Offline fallback: materialize the embedded copy before cloning. - if ok, err := TryMaterializeEmbedded(entry, opts); err != nil { + ok, err := TryMaterializeEmbedded(entry, opts) + if err != nil { return "", err - } else if ok { + } + if ok { return cacheDir, nil } if err := CloneBridge(entry); err != nil { return "", err } - // Verify the cloned repo contains bridge.yaml. + // Verify the cloned repo contains bridge.yaml. Fail closed: the missing + // manifest stays the primary error even if cleanup also fails. if !IsCached(entry) { - os.RemoveAll(cacheDir) - return "", fmt.Errorf("cloned bridge %q does not contain bridge.yaml", entry.ID) + missing := fmt.Errorf("cloned bridge %q does not contain bridge.yaml", entry.ID) + if err := os.RemoveAll(cacheDir); err != nil { + return "", errors.Join(missing, fmt.Errorf("remove incomplete cache %q: %w", cacheDir, err)) + } + return "", missing } if err := WriteMeta(entry, newMetaFromCache(entry)); err != nil { @@ -115,6 +212,12 @@ func maybeUpdate(entry RegistryEntry, opts *EnsureOptions) error { interval = 0 // check now, regardless of when we last looked } + // A pinned bridge is deliberately fixed at one ref; refreshing it would + // silently replace the version the user selected. + if meta, err := ReadMeta(entry); err == nil && meta != nil && meta.Pin != "" { + return nil + } + update, err := CheckForUpdate(entry, interval) if err != nil { return err @@ -125,12 +228,11 @@ func maybeUpdate(entry RegistryEntry, opts *EnsureOptions) error { // Contract gate: never offer (and thus never download) an upstream bridge // this core cannot support. The hard check is re-done in ApplyUpdate; this - // only avoids prompting for an update that would be rejected anyway. - if c, rerr := remoteContractVersion(entry, update.RemoteBranch); rerr == nil { - if cerr := shouldApplyContract(c); cerr != nil { - warnOpts(opts, "skipping update of %q: %v", entry.ID, cerr) - return nil - } + // only avoids prompting for an update that would be rejected anyway. A + // failed probe is "cannot offer update", never "assume supported". + if cerr := gateRemoteContract(entry, update.RemoteBranch); cerr != nil { + warnOpts(opts, "skipping update of %q: %v", entry.ID, cerr) + return nil } // No policy set: keep the cached version and surface the availability. @@ -168,23 +270,50 @@ func warnOpts(opts *EnsureOptions, format string, args ...any) { } } +// prepareCloneCacheDir checks the whole cache path for planted symlinks before +// creating the parent directory. A clone must not follow a link out of the +// cache any more than embedded materialization or metadata writes may. +func prepareCloneCacheDir(cacheDir string) error { + cacheRoot := appdir.UnionDir("bridges") + _, err := fsutil.AbsPathWithin(cacheRoot, cacheDir) + if err == nil { + err = fsutil.RefuseSymlinks(cacheRoot, cacheDir) + } + if err != nil { + return fmt.Errorf("prepare bridge cache dir %q: %w", cacheDir, err) + } + parent := filepath.Dir(cacheDir) + if err := os.MkdirAll(parent, 0o755); err != nil { //nolint:gosec // bridge cache dirs must stay readable across CLI runs + return fmt.Errorf("create cache directory: %w", err) + } + return nil +} + // CloneBridge performs a shallow git clone of the bridge repository. func CloneBridge(entry RegistryEntry) error { + if err := validateCacheID(entry.ID); err != nil { + return err + } if _, err := exec.LookPath("git"); err != nil { return fmt.Errorf("git is required to download bridges but was not found in PATH") } cacheDir := CachePath(entry) - parent := filepath.Dir(cacheDir) - if err := os.MkdirAll(parent, 0o755); err != nil { - return fmt.Errorf("create cache directory: %w", err) + if err := prepareCloneCacheDir(cacheDir); err != nil { + return err } - url := fmt.Sprintf("https://github.com/%s.git", entry.GitHub) - cmd := exec.Command("git", "clone", "--depth", "1", url, cacheDir) + url := fmt.Sprintf("https://%s/%s.git", githubHost, entry.GitHub) + ctx, cancel := gitCommandContext() + defer cancel() + cmd := exec.CommandContext(ctx, "git", "clone", "--depth", "1", url, cacheDir) //nolint:gosec // args passed separately; no shell interpretation + cmd.Env = gitScrubbedEnv() if out, err := cmd.CombinedOutput(); err != nil { - os.RemoveAll(cacheDir) - return fmt.Errorf("clone %s: %w: %s", url, err, out) + cloneErr := fmt.Errorf("clone %s: %w: %s", url, err, out) + if rerr := os.RemoveAll(cacheDir); rerr != nil { + return errors.Join(cloneErr, fmt.Errorf("remove incomplete cache %q: %w", cacheDir, rerr)) + } + return cloneErr } return nil } diff --git a/internal/bridge/clone_id_test.go b/internal/bridge/clone_id_test.go new file mode 100644 index 0000000..026cc88 --- /dev/null +++ b/internal/bridge/clone_id_test.go @@ -0,0 +1,30 @@ +package bridge + +import "testing" + +func TestValidateCacheIDRejectsEscapes(t *testing.T) { + tests := []struct { + name string + id string + wantErr bool + }{ + {name: "simple id", id: "csharp-restful"}, + {name: "underscore and digits", id: "my_bridge2"}, + {name: "empty", id: "", wantErr: true}, + {name: "dot", id: ".", wantErr: true}, + {name: "parent", id: "..", wantErr: true}, + {name: "slash", id: "bar/../../Documents", wantErr: true}, + {name: "backslash", id: `bar\..\..\Documents`, wantErr: true}, + {name: "absolute", id: `/etc/passwd`, wantErr: true}, + {name: "drive", id: `C:\Users\secret`, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateCacheID(tt.id) + if (err != nil) != tt.wantErr { + t.Fatalf("validateCacheID(%q) error = %v, wantErr %v", tt.id, err, tt.wantErr) + } + }) + } +} diff --git a/internal/bridge/clone_policy_test.go b/internal/bridge/clone_policy_test.go new file mode 100644 index 0000000..cf562f1 --- /dev/null +++ b/internal/bridge/clone_policy_test.go @@ -0,0 +1,307 @@ +package bridge + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +// TestMaybeUpdatePolicies covers the decision gate that was previously +// untested: disabled checks, no policy, decline, prompt error and the +// pre-prompt contract gate. +func TestMaybeUpdatePolicies(t *testing.T) { + tests := []struct { + name string + interval time.Duration + remoteYAML string + pin string + confirm func(RegistryEntry, *Update) (bool, error) + wantWarn string + wantConfirm bool + wantErr bool + wantNoHTTP bool + }{ + { + name: "disabled interval skips the remote", + interval: -1, + remoteYAML: "name: test\ncontract_version: 1\n", + wantNoHTTP: true, + }, + { + name: "fresh cache skips the remote", + interval: 24 * time.Hour, + remoteYAML: "name: test\ncontract_version: 1\n", + wantNoHTTP: true, + }, + { + name: "no policy warns without applying", + remoteYAML: "name: test\ncontract_version: 1\n", + wantWarn: "has an update available", + }, + { + name: "declined update keeps the cache", + remoteYAML: "name: test\ncontract_version: 1\n", + confirm: func(RegistryEntry, *Update) (bool, error) { return false, nil }, + wantConfirm: true, + }, + { + name: "prompt error is propagated", + remoteYAML: "name: test\ncontract_version: 1\n", + confirm: func(RegistryEntry, *Update) (bool, error) { return false, errors.New("prompt failed") }, + wantConfirm: true, + wantErr: true, + }, + { + name: "unsupported contract skips the prompt", + remoteYAML: "name: test\ncontract_version: 3\n", + wantWarn: "skipping update", + }, + { + name: "unreadable remote contract skips the prompt", + remoteYAML: "contract_version: [1, 2\n", + wantWarn: "skipping update", + }, + { + name: "pinned checkout skips the remote", + remoteYAML: "name: test\ncontract_version: 1\n", + pin: "v1.2.3", + wantNoHTTP: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("policy-bridge", "owner/policy-bridge") + cacheDir := CachePath(entry) + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + t.Fatal(err) + } + // Update detection must read a real HEAD: a stale metadata commit + // is deliberately ignored when git cannot be consulted. + makeBridgeRepo(t, cacheDir, "main") + head := testGit(t, cacheDir, "rev-parse", "HEAD") + lastChecked := time.Now().Add(-48 * time.Hour) + if tt.name == "fresh cache skips the remote" { + lastChecked = time.Now() + } + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, + Source: entry.GitHub, + Version: "1.0.0", + Commit: head, + Branch: "main", + Pin: tt.pin, + LastCheckedAt: lastChecked, + }); err != nil { + t.Fatal(err) + } + + stub := stubGitHubAPI(t, "remote-head", tt.remoteYAML) + + confirmed := false + confirm := tt.confirm + if confirm != nil { + confirm = func(e RegistryEntry, u *Update) (bool, error) { + confirmed = true + return tt.confirm(e, u) + } + } + + var warnings []string + opts := &EnsureOptions{ + Interval: tt.interval, + ConfirmUpdate: confirm, + Warn: func(format string, _ ...any) { warnings = append(warnings, format) }, + } + + err := maybeUpdate(entry, opts) + if (err != nil) != tt.wantErr { + t.Fatalf("maybeUpdate error = %v, wantErr %v", err, tt.wantErr) + } + if confirmed != tt.wantConfirm { + t.Fatalf("confirm called = %v, want %v", confirmed, tt.wantConfirm) + } + if tt.wantWarn == "" && len(warnings) != 0 { + t.Fatalf("unexpected warnings: %v", warnings) + } + if tt.wantWarn != "" && !strings.Contains(strings.Join(warnings, " "), tt.wantWarn) { + t.Fatalf("warnings %v do not contain %q", warnings, tt.wantWarn) + } + if tt.wantNoHTTP && stub.Calls() != 0 { + t.Fatalf("remote was contacted %d times, want 0", stub.Calls()) + } + }) + } +} + +// TestCacheIsolationBetweenOwners covers the cache key collision: two GitHub +// repos with the same name but different owners must never share a checkout. +// A cache entry carrying another owner's metadata is replaced, not reused. +func TestCacheIsolationBetweenOwners(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + alice := RegistryEntry{ID: cacheIDForGitHub("alice/utils"), GitHub: "alice/utils"} + bob := RegistryEntry{ID: cacheIDForGitHub("bob/utils"), GitHub: "bob/utils"} + if CachePath(alice) == CachePath(bob) { + t.Fatalf("both owners resolved to the same cache dir %q", CachePath(alice)) + } + for _, e := range []RegistryEntry{alice, bob} { + if err := validateCacheID(e.ID); err != nil { + t.Fatalf("derived cache ID %q is unsafe: %v", e.ID, err) + } + dir := CachePath(e) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + // Simulate the old collision: both dirs hold alice's checkout. + writeBridgeYAML(t, dir, "alice-1.0.0") + } + if err := WriteMeta(alice, &CacheMeta{ID: alice.ID, Source: alice.GitHub, Version: "alice-1.0.0"}); err != nil { + t.Fatal(err) + } + if err := WriteMeta(bob, &CacheMeta{ID: bob.ID, Source: alice.GitHub, Version: "alice-1.0.0"}); err != nil { + t.Fatal(err) + } + if !IsCached(bob) { + t.Fatal("bob's foreign checkout should look cached before the fix") + } + + // Local bare remote stands in for github.com/bob/utils.git. + remote, _ := newRemoteWithBridge(t, root, "main", "bob-2.0.0") + + home := t.TempDir() + cfg := "[url \"file:///" + filepath.ToSlash(remote) + "\"]\n\tinsteadOf = https://github.com/bob/utils.git\n" + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte(cfg), 0o644); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + + path, err := EnsureBridge(bob, nil) + if err != nil { + t.Fatalf("EnsureBridge(bob): %v", err) + } + if path != CachePath(bob) { + t.Fatalf("EnsureBridge(bob) = %q, want %q", path, CachePath(bob)) + } + data, err := os.ReadFile(filepath.Join(path, "bridge.yaml")) + if err != nil || !strings.Contains(string(data), "bob-2.0.0") { + t.Fatalf("bob served a foreign checkout: %q, %v", data, err) + } + meta, err := ReadMeta(bob) + if err != nil || meta == nil || meta.Source != bob.GitHub { + t.Fatalf("bob metadata = %+v, %v; want source %q", meta, err, bob.GitHub) + } + data, err = os.ReadFile(filepath.Join(CachePath(alice), "bridge.yaml")) + if err != nil || !strings.Contains(string(data), "alice-1.0.0") { + t.Fatalf("alice's cache was modified: %q, %v", data, err) + } +} + +// TestApplyUpdateRejectsUnsupportedContract checks the hard invariant at the +// apply site, not only the isolated CheckContractVersion predicate: a bridge +// declaring a newer contract must never be fetched into the cache. +func TestApplyUpdateRejectsUnsupportedContract(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + remote, src := newRemoteWithBridge(t, root, "main", "") + + entry := cacheEntry("contract-bridge", "owner/contract-bridge") + cacheDir := CachePath(entry) + testGit(t, root, "clone", "-q", remote, cacheDir) + if err := WriteMeta(entry, newMetaFromCache(entry)); err != nil { + t.Fatalf("WriteMeta: %v", err) + } + + // Publish a bridge.yaml the core cannot support. + if err := os.WriteFile(filepath.Join(src, "bridge.yaml"), []byte("name: test\nversion: \"2.0.0\"\ncontract_version: 3\n"), 0o644); err != nil { + t.Fatal(err) + } + testGit(t, src, "add", ".") + testGit(t, src, "commit", "-q", "-m", "bump contract") + testGit(t, src, "push", "-q", "origin", "main") + + stubGitHubAPI(t, testGit(t, remote, "rev-parse", "HEAD"), "") + update, err := CheckForUpdate(entry, 0) + if err != nil || update == nil { + t.Fatalf("CheckForUpdate = %+v, %v; want an update", update, err) + } + if _, err := ApplyUpdate(entry, update); err == nil { + t.Fatal("ApplyUpdate accepted an unsupported contract version") + } + + data, err := os.ReadFile(filepath.Join(cacheDir, "bridge.yaml")) + if err != nil || !strings.Contains(string(data), `version: "1.0.0"`) { + t.Fatalf("cached bridge.yaml changed: %q, %v", data, err) + } +} + +// TestApplyUpdateFallbackRejectsUnsupportedContract pins the gate on the clean +// re-clone path. A failed in-place fetch used to bypass the contract check +// entirely, so a bridge with a newer contract landed in the cache. +func TestApplyUpdateFallbackRejectsUnsupportedContract(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + remote, src := newRemoteWithBridge(t, root, "main", "") + + entry := cacheEntry("fallback-contract", "owner/fallback-contract") + cacheDir := CachePath(entry) + testGit(t, root, "clone", "-q", remote, cacheDir) + if err := WriteMeta(entry, newMetaFromCache(entry)); err != nil { + t.Fatal(err) + } + + // Publish a contract this core cannot support on the default branch. + if err := os.WriteFile(filepath.Join(src, "bridge.yaml"), []byte("name: test\nversion: \"2.0.0\"\ncontract_version: 99\n"), 0o644); err != nil { + t.Fatal(err) + } + testGit(t, src, "add", ".") + testGit(t, src, "commit", "-q", "-m", "bump contract") + testGit(t, src, "push", "-q", "origin", "main") + + // Rewrite the clone URL to the local remote so the fallback clone is offline. + home := t.TempDir() + cfg := "[url \"file:///" + filepath.ToSlash(remote) + "\"]\n\tinsteadOf = https://github.com/owner/fallback-contract.git\n" + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte(cfg), 0o644); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + + // A syntactically valid but nonexistent branch forces the fallback path. + u := &Update{RemoteBranch: "missing-branch"} + if _, err := ApplyUpdate(entry, u); err == nil || !strings.Contains(err.Error(), "contract") { + t.Fatalf("ApplyUpdate fallback error = %v, want a contract rejection", err) + } + if _, err := os.Stat(filepath.Join(cacheDir, "bridge.yaml")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("unsupported fallback clone was left in the cache: %v", err) + } +} diff --git a/internal/bridge/context.go b/internal/bridge/context.go new file mode 100644 index 0000000..b82b6ab --- /dev/null +++ b/internal/bridge/context.go @@ -0,0 +1,37 @@ +package bridge + +import ( + "context" + "sync" +) + +// commandCtx is cancelled on interrupt so git children and HTTP probes started +// by bridge resolution and updates are never orphaned. main wires the signal +// context. +var commandCtx = context.Background() + +// commandCtxMu guards commandCtx so the accessor pair is race-free when the +// bridge package is embedded in a long-running host. +var commandCtxMu sync.RWMutex + +// SetCommandContext wires the CLI's cancellable context into bridge operations. +// A nil context is ignored so a caller cannot clear the cancellation signal. +// Concurrent writes are now safe, but callers should prefer passing ctx +// explicitly through the call chain. +func SetCommandContext(ctx context.Context) { + if ctx != nil { + commandCtxMu.Lock() + commandCtx = ctx + commandCtxMu.Unlock() + } +} + +// CommandContext returns the current command context for read-only use (e.g. +// binding an HTTP request lifetime to the CLI's cancellation). It never mutates +// the package-level context. Concurrent reads are now safe, but callers should +// prefer passing ctx explicitly through the call chain. +func CommandContext() context.Context { + commandCtxMu.RLock() + defer commandCtxMu.RUnlock() + return commandCtx +} diff --git a/internal/bridge/context_test.go b/internal/bridge/context_test.go new file mode 100644 index 0000000..d8e1b03 --- /dev/null +++ b/internal/bridge/context_test.go @@ -0,0 +1,39 @@ +package bridge + +import ( + "context" + "sync" + "sync/atomic" + "testing" +) + +// TestCommandContextConcurrentAccess pins the RWMutex around the package-level +// command context: concurrent Set/Get pairs must finish without racing (run +// with -race). Not parallel: the context is package-global and shared with +// other tests. +func TestCommandContextConcurrentAccess(t *testing.T) { + original := CommandContext() + t.Cleanup(func() { SetCommandContext(original) }) + + const goroutines = 8 + const iterations = 100 + var wg sync.WaitGroup + var reads atomic.Int64 + for range goroutines { + wg.Go(func() { + for range iterations { + ctx, cancel := context.WithCancel(context.Background()) + SetCommandContext(ctx) + if CommandContext() == nil { + t.Error("CommandContext returned nil after SetCommandContext") + } + reads.Add(1) + cancel() + } + }) + } + wg.Wait() + if got := reads.Load(); got != goroutines*iterations { + t.Errorf("completed %d reads, want %d", got, goroutines*iterations) + } +} diff --git a/internal/bridge/embed.go b/internal/bridge/embed.go index cc0dd77..c8c4715 100644 --- a/internal/bridge/embed.go +++ b/internal/bridge/embed.go @@ -8,8 +8,16 @@ import ( "strings" domaincraft "github.com/DomainCraft/DomainCraft" + "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/fsutil" ) +// embeddedBridgeRel builds the path of a bundled bridge inside the embedded +// filesystem. All embedded-tree lookups use this one spelling. +func embeddedBridgeRel(entryPath string) string { + return "bridges/" + filepath.ToSlash(entryPath) +} + // TryMaterializeEmbedded copies the embedded copy of an official bridge into its // cache directory. It returns (true, nil) when the bridge is embedded and was // materialized, (false, nil) when it is not embedded (caller should clone), and @@ -22,13 +30,23 @@ func TryMaterializeEmbedded(entry RegistryEntry, opts *EnsureOptions) (bool, err if entry.Path == "" { return false, nil } - rel := "bridges/" + filepath.ToSlash(entry.Path) + rel := embeddedBridgeRel(entry.Path) if _, err := domaincraft.Bridges.ReadDir(rel); err != nil { return false, nil // not embedded in this binary } dst := CachePath(entry) - if err := os.MkdirAll(dst, 0o755); err != nil { + // The cache may be attacker-controlled (a planted symlink would redirect + // writes outside it), so check the whole path before creating anything. + cacheRoot := appdir.UnionDir("bridges") + _, err := fsutil.AbsPathWithin(cacheRoot, dst) + if err == nil { + err = fsutil.RefuseSymlinks(cacheRoot, dst) + } + if err != nil { + return false, fmt.Errorf("materialize embedded bridge %q: %w", entry.ID, err) + } + if err := os.MkdirAll(dst, 0o755); err != nil { //nolint:gosec // bridge cache dirs must stay readable across CLI runs return false, fmt.Errorf("create cache dir for embedded bridge %q: %w", entry.ID, err) } if err := writeFSDir(domaincraft.Bridges, rel, dst); err != nil { @@ -43,8 +61,17 @@ func TryMaterializeEmbedded(entry RegistryEntry, opts *EnsureOptions) (bool, err } // writeFSDir copies every file in the embedded filesystem subtree rooted at -// root into the destination directory, preserving relative paths. +// root into the destination directory, preserving relative paths. Every target +// component is checked for symlinks before it is written. func writeFSDir(fsys fs.FS, root, dst string) error { + // os.Root confines every write to dst. RefuseSymlinks still rejects links + // that stay inside the cache; Root additionally closes the window between + // the check and the commit if a component is replaced concurrently. + dir, err := os.OpenRoot(dst) + if err != nil { + return err + } + defer func() { _ = dir.Close() }() return fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error { if err != nil { return err @@ -52,16 +79,24 @@ func writeFSDir(fsys fs.FS, root, dst string) error { rel := strings.TrimPrefix(path, root) rel = strings.TrimPrefix(rel, "/") target := filepath.Join(dst, filepath.FromSlash(rel)) - if d.IsDir() { - return os.MkdirAll(target, 0o755) + _, err = fsutil.AbsPathWithin(dst, target) + if err == nil { + err = fsutil.RefuseSymlinks(dst, target) } - data, err := fs.ReadFile(fsys, path) if err != nil { return err } - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + name := filepath.FromSlash(rel) + if name == "" { + return nil + } + if d.IsDir() { + return dir.MkdirAll(name, 0o755) + } + data, err := fs.ReadFile(fsys, path) + if err != nil { return err } - return os.WriteFile(target, data, 0o644) + return fsutil.AtomicWriteRoot(dir, name, data) }) } diff --git a/internal/bridge/embed_test.go b/internal/bridge/embed_test.go index 3a2d205..fabc8b8 100644 --- a/internal/bridge/embed_test.go +++ b/internal/bridge/embed_test.go @@ -1,22 +1,22 @@ package bridge import ( + "io/fs" + "maps" "os" "path/filepath" + "slices" "testing" domaincraft "github.com/DomainCraft/DomainCraft" "github.com/DomainCraft/DomainCraft/internal/appdir" ) -// TestEmbeddedContainsRegistryBridges guards against drift between the embedded -// bridge tree (what ships in the binary) and the registry mapping. Every -// registered, non-deprecated bridge must exist embedded; the deprecated -// csharp-restful monolith is intentionally not bundled. // TestTryMaterializeEmbedded verifies that an embedded bridge can be // materialized into the cache directory (the offline fallback path). func TestTryMaterializeEmbedded(t *testing.T) { appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) entry := Default().ByID("csharp-core") if entry == nil { t.Fatal("csharp-core not in registry") @@ -36,6 +36,20 @@ func TestTryMaterializeEmbedded(t *testing.T) { } } +// F27: the embedded tree path has one spelling for all lookups. +func TestEmbeddedBridgeRel(t *testing.T) { + if got := embeddedBridgeRel("csharp/core"); got != "bridges/csharp/core" { + t.Errorf("embeddedBridgeRel = %q, want bridges/csharp/core", got) + } + if got := embeddedBridgeRel(filepath.FromSlash("csharp/core")); got != "bridges/csharp/core" { + t.Errorf("embeddedBridgeRel with OS separators = %q, want bridges/csharp/core", got) + } +} + +// TestEmbeddedContainsRegistryBridges guards against drift between the embedded +// bridge tree (what ships in the binary) and the registry mapping. Every +// registered, non-deprecated bridge must exist embedded; the deprecated +// csharp-restful monolith is intentionally not bundled. func TestEmbeddedContainsRegistryBridges(t *testing.T) { reg := Default() for _, e := range reg.All() { @@ -48,3 +62,81 @@ func TestEmbeddedContainsRegistryBridges(t *testing.T) { } } } + +// TestEmbeddedBridgesMatchTree compares the embedded tree with the source tree. +// Helper templates are named helpers.*.tmpl, so //go:embed bridges picks them up +// along with every other file. The two sets must stay identical, or an installed +// binary cannot render. +func TestEmbeddedBridgesMatchTree(t *testing.T) { + root := filepath.Join("..", "..", "bridges") + if _, err := os.Stat(root); err != nil { + if os.Getenv("DOMAINCRAFT_LOCAL_DEV") != "" { + t.Skipf("no bundled bridges tree at %s (DOMAINCRAFT_LOCAL_DEV set): %v", root, err) + } + t.Fatalf("bundled bridges tree missing at %s: %v", root, err) + } + + embedded := make(map[string]bool) + if err := fs.WalkDir(domaincraft.Bridges, "bridges", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + // Generated TCK output and snapshots are runtime artifacts: they + // may exist on disk but not in the compiled embed (or vice versa). + switch d.Name() { + case "bin", "obj", "node_modules", ".git", ".domaincraft": + return fs.SkipDir + case "generated": + if filepath.Base(filepath.Dir(path)) == "tck" { + return fs.SkipDir + } + } + return nil + } + embedded[path] = true + return nil + }); err != nil { + t.Fatalf("walk embedded bridges: %v", err) + } + + onDisk := make(map[string]bool) + if err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + // Local build artifacts are not part of the source tree and go:embed + // does not include them either. TCK output and .domaincraft snapshots + // are runtime artifacts for the same reason. + switch d.Name() { + case "bin", "obj", "node_modules", ".git", ".domaincraft": + return filepath.SkipDir + case "generated": + if filepath.Base(filepath.Dir(path)) == "tck" { + return filepath.SkipDir + } + } + return nil + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + onDisk["bridges/"+filepath.ToSlash(rel)] = true + return nil + }); err != nil { + t.Fatalf("walk source bridges: %v", err) + } + + for _, path := range slices.Sorted(maps.Keys(onDisk)) { + if !embedded[path] { + t.Errorf("embedded tree missing %s: check go:embed name exclusions", path) + } + } + for _, path := range slices.Sorted(maps.Keys(embedded)) { + if !onDisk[path] { + t.Errorf("embedded tree has %s but the source tree does not", path) + } + } +} diff --git a/internal/bridge/hardening_test.go b/internal/bridge/hardening_test.go new file mode 100644 index 0000000..449452d --- /dev/null +++ b/internal/bridge/hardening_test.go @@ -0,0 +1,562 @@ +package bridge + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" + "github.com/DomainCraft/DomainCraft/internal/fsutil" +) + +// S7: a user-supplied pin must be a git ref, not a git option or a revision +// expression. Validation happens before rev-parse/checkout run. +func TestValidatePinRef(t *testing.T) { + tests := []struct { + name string + ref string + wantErr bool + }{ + {name: "commit sha", ref: "9f8e7d6c5b4a"}, + {name: "tag", ref: "v1.2.3"}, + {name: "branch with slash", ref: "feature/branch"}, + {name: "plus suffix", ref: "release+build"}, + {name: "empty", ref: "", wantErr: true}, + {name: "leading dash", ref: "--upload-pack=sh", wantErr: true}, + {name: "dash branch", ref: "-dangerous", wantErr: true}, + {name: "dotdot traversal", ref: "release/../../main", wantErr: true}, + {name: "double slash", ref: "feature//branch", wantErr: true}, + {name: "revision expression", ref: "HEAD~1", wantErr: true}, + {name: "caret expression", ref: "HEAD^", wantErr: true}, + {name: "at brace expression", ref: "main@{1}", wantErr: true}, + {name: "newline", ref: "main\n--exec", wantErr: true}, + {name: "question mark", ref: "v1?", wantErr: true}, + {name: "backslash", ref: `a\b`, wantErr: true}, + {name: "leading slash", ref: "/main", wantErr: true}, + {name: "trailing slash", ref: "main/", wantErr: true}, + {name: "lock suffix", ref: "branch.lock", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validatePinRef(tt.ref) + if (err != nil) != tt.wantErr { + t.Fatalf("validatePinRef(%q) error = %v, wantErr %v", tt.ref, err, tt.wantErr) + } + if tt.wantErr && !strings.Contains(err.Error(), "invalid pinned ref") { + t.Errorf("error = %q, want it to name the invalid ref", err) + } + }) + } + + dir := t.TempDir() + if err := checkoutPinnedRef(dir, "--upload-pack=sh"); err == nil { + t.Error("checkoutPinnedRef accepted an option-like ref without running validation") + } +} + +// S8: the pin is persisted in cache metadata and legacy metadata (no pin +// field) keeps decoding with an empty pin. +func TestRecordPinIsPersisted(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("pinned", "owner/pinned") + legacy := &CacheMeta{ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", Branch: "main"} + if err := WriteMeta(entry, legacy); err != nil { + t.Fatal(err) + } + meta, err := ReadMeta(entry) + if err != nil || meta.Pin != "" { + t.Fatalf("legacy metadata pin = %q, %v; want empty", meta.Pin, err) + } + + if err := recordPin(entry, "v1.2.3"); err != nil { + t.Fatalf("recordPin: %v", err) + } + meta, err = ReadMeta(entry) + if err != nil { + t.Fatal(err) + } + if meta.Pin != "v1.2.3" || meta.Version != "1.0.0" || meta.Branch != "main" { + t.Fatalf("metadata after pin = %+v; want pin v1.2.3 and preserved version/branch", meta) + } +} + +// S11: git children get a minimal environment. A GIT_CONFIG_* injection, an +// SSH command override or a proxy override must never reach them. +func TestGitScrubbedEnvAllowlist(t *testing.T) { + dangerous := []string{ + "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", + "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", + "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_SSH_COMMAND", + "GIT_PROXY_COMMAND", "GIT_ASKPASS", "GIT_TRACE", "GIT_EXEC_PATH", + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + } + for _, name := range dangerous { + t.Setenv(name, "attacker-controlled") + } + + got := make(map[string]string) + for _, kv := range gitScrubbedEnv() { + name, value, _ := strings.Cut(kv, "=") + got[strings.ToUpper(name)] = value + } + for _, name := range dangerous { + if value, ok := got[name]; ok { + t.Errorf("git environment leaked %s=%q", name, value) + } + } + if _, ok := got["PATH"]; !ok { + t.Error("git environment dropped PATH") + } + _, hasHome := got["HOME"] + _, hasProfile := got["USERPROFILE"] + if !hasHome && !hasProfile { + t.Error("git environment dropped HOME/USERPROFILE") + } +} + +// S12: cache paths are attacker-controlled. A planted symlink must stop the +// embedded materialization before any file is written through it. +func TestTryMaterializeEmbeddedRefusesSymlinks(t *testing.T) { + entry := Default().ByID("csharp-core") + if entry == nil { + t.Fatal("csharp-core not in registry") + } + tests := []struct { + name string + plant func(t *testing.T, dst, outside string) + }{ + { + name: "symlink at bridge cache dir", + plant: func(t *testing.T, dst, outside string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, dst); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + }, + }, + { + name: "symlink at child directory", + plant: func(t *testing.T, dst, outside string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(dst), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(dst, "templates")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + outside := t.TempDir() + dst := CachePath(*entry) + tt.plant(t, dst, outside) + + if ok, err := TryMaterializeEmbedded(*entry, nil); err == nil || ok { + t.Fatalf("TryMaterializeEmbedded = %v, %v; want error", ok, err) + } else if !strings.Contains(err.Error(), "symlink") { + t.Errorf("error = %q, want it to mention the symlink", err) + } + entries, err := os.ReadDir(outside) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Errorf("materialization wrote %d entries through the symlink into %s", len(entries), outside) + } + }) + } + + // A target outside the cache directory is rejected too. + base := t.TempDir() + target := filepath.Join(t.TempDir(), "elsewhere") + _, err := fsutil.AbsPathWithin(base, target) + if err == nil { + err = fsutil.RefuseSymlinks(base, target) + } + if err == nil { + t.Error("path check accepted a target outside the base directory") + } +} + +// S2/S5/S14: an unreadable fetched manifest is a hard error, an oversized +// probe body is never truncated into a valid-looking one, and URL errors do +// not leak credentials or query strings. +func TestApplyUpdateFailsWhenFetchedManifestIsUnreadable(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + remote, src := newRemoteWithBridge(t, root, "main", "") + + entry := cacheEntry("no-manifest", "owner/no-manifest") + cacheDir := CachePath(entry) + testGit(t, root, "clone", "-q", remote, cacheDir) + if err := WriteMeta(entry, newMetaFromCache(entry)); err != nil { + t.Fatal(err) + } + + // The new upstream commit removes bridge.yaml, so `git show` on the + // fetched tree fails. The old gate skipped the check in that case. + if err := os.Remove(filepath.Join(src, "bridge.yaml")); err != nil { + t.Fatal(err) + } + testGit(t, src, "add", "-A") + testGit(t, src, "commit", "-q", "-m", "remove manifest") + testGit(t, src, "push", "-q", "origin", "main") + + stubGitHubAPI(t, testGit(t, remote, "rev-parse", "HEAD"), "") + update, err := CheckForUpdate(entry, 0) + if err != nil || update == nil { + t.Fatalf("CheckForUpdate = %+v, %v; want an update", update, err) + } + if _, err := ApplyUpdate(entry, update); err == nil { + t.Fatal("ApplyUpdate accepted a fetched tree without bridge.yaml") + } + if _, err := os.Stat(filepath.Join(cacheDir, "bridge.yaml")); err != nil { + t.Fatalf("cached bridge.yaml was lost: %v", err) + } +} + +func TestHTTPProbeLimitsAndRedaction(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/large": + _, _ = w.Write(make([]byte, maxProbeBodyBytes+1)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + + tests := []struct { + name string + url string + wantErr string + hidden string + }{ + {name: "oversized body fails", url: server.URL + "/large", wantErr: "exceeds"}, + {name: "url errors are redacted", url: strings.Replace(server.URL, "http://", "http://user:pass@", 1) + "/missing?token=secret", wantErr: "http 404 for http://", hidden: "secret"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := httpGetBody(tt.url) + if err == nil { + t.Fatalf("httpGetBody(%q) succeeded, want error", tt.url) + } + if !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("error = %q, want it to contain %q", err, tt.wantErr) + } + if tt.hidden != "" && strings.Contains(err.Error(), tt.hidden) { + t.Errorf("error = %q, leaked %q", err, tt.hidden) + } + if strings.Contains(err.Error(), "user:pass") { + t.Errorf("error = %q, leaked userinfo", err) + } + }) + } +} + +// F35: a redirect must be rejected before the follow-up request reaches the +// new host. Checking resp.Request.URL after client.Do is too late — the target +// has already been fetched. +func TestHTTPProbeRejectsRedirectBeforeFetch(t *testing.T) { + var targetHits atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + targetHits.Add(1) + _, _ = w.Write([]byte("secret-body")) + })) + defer target.Close() + + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/payload?token=super-secret", http.StatusFound) + })) + defer origin.Close() + + _, err := httpGetBody(origin.URL + "/start") + if err == nil { + t.Fatal("httpGetBody followed a redirect to a forbidden host") + } + if !strings.Contains(err.Error(), "redirect") { + t.Errorf("error = %q, want a redirect rejection", err) + } + if strings.Contains(err.Error(), "super-secret") { + t.Errorf("error = %q, leaked the redirect target's query", err) + } + if n := targetHits.Load(); n != 0 { + t.Errorf("redirect target received %d requests, want none", n) + } +} + +// S9: probe requests are bound to the command context and the accessor does +// not mutate the package-level context. +func TestHTTPProbeUsesCommandContext(t *testing.T) { + previous := CommandContext() + defer SetCommandContext(previous) + + ctx, cancel := context.WithCancel(context.Background()) + SetCommandContext(ctx) + if got := CommandContext(); got != ctx { + t.Fatalf("CommandContext() = %v, want the wired context", got) + } + cancel() + + server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer server.Close() + if _, err := httpGetBody(server.URL); err == nil { + t.Fatal("httpGetBody ignored the cancelled command context") + } +} + +// F31: the branch handed to `git fetch` may come from cache metadata, so it +// must pass the same strict git-ref grammar used for pinned refs. +func TestValidateFetchBranch(t *testing.T) { + tests := []struct { + name string + branch string + wantErr bool + }{ + {name: "main", branch: "main"}, + {name: "feature branch", branch: "feature/branch"}, + {name: "release with plus", branch: "release+build"}, + {name: "tag-like name", branch: "v1.2.3"}, + {name: "empty", branch: "", wantErr: true}, + {name: "leading dash", branch: "--upload-pack=sh", wantErr: true}, + {name: "dash branch", branch: "-dangerous", wantErr: true}, + {name: "dotdot traversal", branch: "release/../../main", wantErr: true}, + {name: "double slash", branch: "feature//branch", wantErr: true}, + {name: "at brace expression", branch: "main@{1}", wantErr: true}, + {name: "leading slash", branch: "/main", wantErr: true}, + {name: "trailing slash", branch: "main/", wantErr: true}, + {name: "newline", branch: "main\n--exec", wantErr: true}, + {name: "lock suffix", branch: "branch.lock", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // ApplyUpdate feeds the branch through validatePinRef; test the + // grammar directly instead of re-wrapping the error in the test. + err := validatePinRef(tt.branch) + if (err != nil) != tt.wantErr { + t.Fatalf("validatePinRef(%q) = %v, wantErr %v", tt.branch, err, tt.wantErr) + } + if tt.wantErr && !strings.Contains(err.Error(), "invalid pinned ref") { + t.Errorf("error = %q, want it to name the invalid ref", err) + } + }) + } +} + +// F31 wiring: a hostile branch from either source (Update or cache metadata) +// is rejected before git runs. Without the guard ApplyUpdate falls through to +// a clone, so the validation error is the observable contract here. +func TestApplyUpdateRejectsUnsafeFetchBranch(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("unsafe-branch", "owner/unsafe-branch") + bad := "--upload-pack=sh" + + // Keep the no-guard baseline offline too: rewrite the clone URL to a + // missing local path so an unguarded fall-through fails without network. + home := t.TempDir() + missing := filepath.ToSlash(filepath.Join(home, "missing.git")) + cfg := "[url \"file:///" + missing + "\"]\n\tinsteadOf = https://github.com/owner/unsafe-branch.git\n" + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte(cfg), 0o644); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + + // Source 1: the Update passed by the caller. + if _, err := ApplyUpdate(entry, &Update{RemoteBranch: bad}); err == nil || + !strings.Contains(err.Error(), "invalid fetch branch") { + t.Errorf("ApplyUpdate with hostile Update branch = %v, want validation error", err) + } + + // Source 2: the branch recorded in cache metadata. + if err := WriteMeta(entry, &CacheMeta{ID: entry.ID, Source: entry.GitHub, Branch: bad}); err != nil { + t.Fatal(err) + } + if _, err := ApplyUpdate(entry, nil); err == nil || + !strings.Contains(err.Error(), "invalid fetch branch") { + t.Errorf("ApplyUpdate with hostile metadata branch = %v, want validation error", err) + } +} + +// F32: when the in-place update fails and the fallback re-clone also fails, +// both causes and the cache path are reported, with the original failure first. +func TestApplyUpdateJoinsFastPathFailureWithCloneFailure(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + remote, _ := newRemoteWithBridge(t, root, "main", "") + + entry := cacheEntry("joined-errors", "owner/joined-errors") + cacheDir := CachePath(entry) + testGit(t, root, "clone", "-q", remote, cacheDir) + + // A syntactically valid but nonexistent branch makes the fetch fail, so the + // update takes the re-clone fallback. + if err := WriteMeta(entry, &CacheMeta{ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", Branch: "missing-branch"}); err != nil { + t.Fatal(err) + } + + // Rewrite the clone URL to a missing local path: the fallback fails fast, + // offline, and the original fetch cause must survive in the joined error. + home := t.TempDir() + missing := filepath.ToSlash(filepath.Join(home, "missing.git")) + cfg := "[url \"file:///" + missing + "\"]\n\tinsteadOf = https://github.com/owner/joined-errors.git\n" + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte(cfg), 0o644); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + + _, err := ApplyUpdate(entry, nil) + if err == nil { + t.Fatal("ApplyUpdate succeeded despite a failed fetch and re-clone") + } + msg := err.Error() + fetch := strings.Index(msg, `fetch branch "missing-branch"`) + clone := strings.Index(msg, "re-clone bridge") + if fetch < 0 { + t.Errorf("error = %q, want the original fetch failure", msg) + } + if clone < 0 || !strings.Contains(msg, cacheDir) { + t.Errorf("error = %q, want the re-clone failure with cache path %q", msg, cacheDir) + } + if fetch >= 0 && clone >= 0 && fetch > clone { + t.Errorf("error = %q, want the original fetch failure before the cleanup failure", msg) + } +} + +// R3: when the remote probe and the freshness write both fail, both causes must +// reach the caller. Dropping the write error left the timestamp unpersisted, so +// every later run paid the probe timeout again with no diagnostic. +func TestCheckForUpdateJoinsCacheWriteFailure(t *testing.T) { + // No t.Parallel: the cache base and httpGetBodyFn are package globals. + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("joined-write-failure", "owner/joined-write-failure") + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", Branch: "main", + }); err != nil { + t.Fatal(err) + } + + probeErr := errors.New("probe offline") + originalGet := httpGetBodyFn + t.Cleanup(func() { httpGetBodyFn = originalGet }) + httpGetBodyFn = func(string) ([]byte, error) { + // Metadata has already been read; break the cache dir before WriteMeta + // so the freshness write fails without a symlink or permission trick. + dir := CachePath(entry) + if err := os.RemoveAll(dir); err != nil { + t.Fatalf("remove cache dir: %v", err) + } + if err := os.WriteFile(dir, []byte("not a directory"), 0o644); err != nil { + t.Fatalf("replace cache dir with a file: %v", err) + } + return nil, probeErr + } + + _, err := CheckForUpdate(entry, 0) + if err == nil { + t.Fatal("CheckForUpdate hid both the probe and metadata-write failures") + } + if !errors.Is(err, probeErr) { + t.Errorf("error = %q, want the probe failure to stay inspectable", err) + } + msg := err.Error() + if !strings.Contains(msg, "record bridge update check") { + t.Errorf("error = %q, want the cache-write context", msg) + } + if !strings.Contains(msg, probeErr.Error()) { + t.Errorf("error = %q, want the network failure context", msg) + } +} + +// --check-updates is a status query: probing the remote must not rewrite +// .domaincraft-meta.json. Generation-time probes still record the attempt. +func TestStatusCheckDoesNotMutateCacheMeta(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } + // No t.Parallel: the cache base and httpGetBodyFn are package globals. + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("status-readonly", "owner/status-readonly") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, dir, "main") + head := testGit(t, dir, "rev-parse", "HEAD") + checkedAt := time.Now().Add(-time.Hour).UTC().Truncate(time.Millisecond) + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, Source: entry.GitHub, Version: "1.0.0", + Commit: head, Branch: "main", LastCheckedAt: checkedAt, + }); err != nil { + t.Fatal(err) + } + + stubGitHubAPI(t, "abcdef1234567890", "name: b\ncontract_version: 1\n") + + st := entry.Status(true) + if !st.RemoteReachable || !st.Outdated { + t.Fatalf("status = %+v, want a reachable, supported update", st) + } + + after, err := ReadMeta(entry) + if err != nil { + t.Fatal(err) + } + if after == nil { + t.Fatal("cache metadata disappeared after a status check") + } + if !after.LastCheckedAt.Equal(checkedAt) || after.Commit != head { + t.Fatalf("status check mutated cache metadata: got %+v, want LastCheckedAt %v and Commit %s", after, checkedAt, head) + } + + // The ordinary (generation-time) probe must keep its previous behavior. + if _, err := CheckForUpdate(entry, 0); err != nil { + t.Fatal(err) + } + written, err := ReadMeta(entry) + if err != nil { + t.Fatal(err) + } + if written.LastCheckedAt.Equal(checkedAt) { + t.Fatal("CheckForUpdate stopped recording LastCheckedAt") + } +} diff --git a/internal/bridge/local_paths_test.go b/internal/bridge/local_paths_test.go new file mode 100644 index 0000000..ceb2cc9 --- /dev/null +++ b/internal/bridge/local_paths_test.go @@ -0,0 +1,119 @@ +package bridge + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// localBridgePathsFixtures lays out the four inputs shared by the normalization +// tests: a valid bridge directory, a directory without a config, the config file +// itself and a path that does not exist. +func localBridgePathsFixtures(t *testing.T) (withConfig, withoutConfig, configFile, missing string) { + t.Helper() + root := t.TempDir() + withConfig = filepath.Join(root, "with-config") + if err := os.MkdirAll(withConfig, 0o755); err != nil { + t.Fatal(err) + } + configFile = filepath.Join(withConfig, "bridge.yaml") + if err := os.WriteFile(configFile, []byte("name: test\n"), 0o644); err != nil { + t.Fatal(err) + } + withoutConfig = filepath.Join(root, "without-config") + if err := os.MkdirAll(withoutConfig, 0o755); err != nil { + t.Fatal(err) + } + missing = filepath.Join(root, "missing") + return withConfig, withoutConfig, configFile, missing +} + +func TestLocalBridgePaths(t *testing.T) { + t.Parallel() + withConfig, withoutConfig, configFile, missing := localBridgePathsFixtures(t) + + cases := []struct { + name string + input string + wantDir string + wantConfig string + wantErrPart string + }{ + {name: "existing directory with bridge.yaml", input: withConfig, wantDir: withConfig, wantConfig: configFile}, + {name: "existing directory without bridge.yaml", input: withoutConfig, wantErrPart: "does not contain bridge.yaml"}, + {name: "file path", input: configFile, wantDir: withConfig, wantConfig: configFile}, + {name: "missing path", input: missing, wantErrPart: "bridge path"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + dir, config, err := LocalBridgePaths(tc.input) + if tc.wantErrPart != "" { + if err == nil { + t.Fatalf("LocalBridgePaths(%q) = (%q, %q), want error containing %q", tc.input, dir, config, tc.wantErrPart) + } + if !strings.Contains(err.Error(), tc.wantErrPart) { + t.Fatalf("error = %q, want it to contain %q", err, tc.wantErrPart) + } + return + } + if err != nil { + t.Fatalf("LocalBridgePaths(%q): %v", tc.input, err) + } + if dir != tc.wantDir || config != tc.wantConfig { + t.Errorf("LocalBridgePaths(%q) = (%q, %q), want (%q, %q)", tc.input, dir, config, tc.wantDir, tc.wantConfig) + } + // The config path returned for a valid input must exist, not be a + // re-derived lookalike. + if _, err := os.Stat(config); err != nil { + t.Errorf("returned config %q is not readable: %v", config, err) + } + }) + } +} + +// Resolver.Resolve must keep its original diagnostics: a directory without a +// config is a hard error, a missing path-like input never becomes a clone, and +// a missing bare name still falls through to registry/owner-repo resolution. +func TestResolver_LocalPathNormalization(t *testing.T) { + t.Parallel() + withConfig, withoutConfig, configFile, missing := localBridgePathsFixtures(t) + r := NewResolver(&Registry{}) + + cases := []struct { + name string + input string + wantDir string + wantErrPart string + }{ + {name: "existing directory with bridge.yaml", input: withConfig, wantDir: withConfig}, + {name: "existing directory without bridge.yaml", input: withoutConfig, wantErrPart: "does not contain bridge.yaml"}, + {name: "file path", input: configFile, wantDir: withConfig}, + {name: "missing path-like input", input: missing, wantErrPart: "no such local path"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + dir, err := r.Resolve(tc.input) + if tc.wantErrPart != "" { + if err == nil { + t.Fatalf("Resolve(%q) = %q, want error containing %q", tc.input, dir, tc.wantErrPart) + } + if !strings.Contains(err.Error(), tc.wantErrPart) { + t.Fatalf("error = %q, want it to contain %q", err, tc.wantErrPart) + } + if strings.Contains(err.Error(), "github.com") { + t.Fatalf("Resolve(%q) fell through to a GitHub clone: %v", tc.input, err) + } + return + } + if err != nil { + t.Fatalf("Resolve(%q): %v", tc.input, err) + } + if dir != tc.wantDir { + t.Errorf("Resolve(%q) = %q, want %q", tc.input, dir, tc.wantDir) + } + }) + } +} diff --git a/internal/bridge/manifest.go b/internal/bridge/manifest.go new file mode 100644 index 0000000..d05d19c --- /dev/null +++ b/internal/bridge/manifest.go @@ -0,0 +1,45 @@ +package bridge + +import ( + "fmt" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +// Manifest is the identity and registry metadata of bridge.yaml shared by the +// CLI (chain resolution, --replace, lock file) and the contract golden tests. +// The renderer parses the full config — templates, helpers, migrations — in +// its own package; this struct covers only the fields those two consumers read. +type Manifest struct { + Name string `yaml:"name"` + Layer string `yaml:"layer"` + Version string `yaml:"version"` + Extends string `yaml:"extends"` + ContractVersion int `yaml:"contract_version"` + RegistryURL string `yaml:"registry_url"` + RegistryPackages map[string]string `yaml:"registry_packages"` + TargetFramework string `yaml:"target_framework"` +} + +// LoadManifest reads bridge.yaml once from a local bridge directory. The +// contract version goes through ParseContractVersion so an absent/zero field +// resolves to the core's version and a malformed one fails closed — the same +// rule the contract gate applies. +func LoadManifest(dir string) (Manifest, error) { + data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) //nolint:gosec // dir comes from validated bridge resolution + if err != nil { + return Manifest{}, err + } + var m Manifest + if err := yaml.Unmarshal(data, &m); err != nil { + return Manifest{}, fmt.Errorf("parse bridge manifest in %q: %w", dir, err) + } + version, _, err := ParseContractVersion(data) + if err != nil { + return Manifest{}, err + } + m.ContractVersion = version + return m, nil +} diff --git a/internal/bridge/meta.go b/internal/bridge/meta.go index fe52259..97cbbc5 100644 --- a/internal/bridge/meta.go +++ b/internal/bridge/meta.go @@ -1,6 +1,7 @@ package bridge import ( + "encoding/json" "errors" "fmt" "os" @@ -8,8 +9,6 @@ import ( "time" "github.com/DomainCraft/DomainCraft/internal/fsutil" - - "gopkg.in/yaml.v3" ) // MetaFileName is the cache-metadata filename stored inside each cached bridge. @@ -25,6 +24,10 @@ type CacheMeta struct { Version string `json:"version"` // bridge.yaml version at download/update time Commit string `json:"commit"` // git HEAD of the local checkout Branch string `json:"branch"` // upstream default branch + // Pin is the exact ref requested by `owner/repo@ref`. It is empty for + // registry IDs and unpinned shorthands. Old metadata has no field, which + // decodes to "" and keeps those caches backwards compatible. + Pin string `json:"pin,omitempty"` // ClonedAt marks when the bridge was first downloaded. ClonedAt time.Time `json:"cloned_at"` // LastCheckedAt is updated every time the remote is actually contacted, so @@ -57,7 +60,21 @@ func WriteMeta(entry RegistryEntry, meta *CacheMeta) error { if meta == nil { return fmt.Errorf("cannot write nil cache metadata") } - return fsutil.WriteJSON(MetaPath(entry), meta) + path := MetaPath(entry) + parent := filepath.Dir(path) + if err := os.MkdirAll(parent, 0o755); err != nil { //nolint:gosec // bridge cache dirs must stay readable across CLI runs + return err + } + root, rel, err := fsutil.OpenRootFor(parent, path) + if err != nil { + return fmt.Errorf("open cache root for %q: %w", entry.ID, err) + } + defer func() { _ = root.Close() }() + data, err := json.MarshalIndent(meta, "", " ") + if err != nil { + return fmt.Errorf("marshal cache metadata for %q: %w", entry.ID, err) + } + return fsutil.AtomicWriteRoot(root, rel, data) } // ensureMeta returns the cache metadata for a cached bridge, synthesizing it @@ -77,11 +94,26 @@ func ensureMeta(entry RegistryEntry) (*CacheMeta, error) { return newMetaFromCache(entry), nil } +// modifyMeta performs one read-modify-write of a bridge's cache metadata. +// A bridge cached before metadata existed is synthesized first, so callers +// never have to repeat the ensure/mutate/write sequence. +func modifyMeta(entry RegistryEntry, mutate func(*CacheMeta)) error { + meta, err := ensureMeta(entry) + if err != nil { + return err + } + if meta == nil { + meta = newMetaFromCache(entry) + } + mutate(meta) + return WriteMeta(entry, meta) +} + // newMetaFromCache builds metadata from the current on-disk checkout. It is // best-effort: missing git or an unreadable bridge.yaml degrade gracefully. func newMetaFromCache(entry RegistryEntry) *CacheMeta { now := time.Now() - meta := &CacheMeta{ + return &CacheMeta{ ID: entry.ID, Source: entry.GitHub, Version: readBridgeVersion(entry), @@ -90,32 +122,35 @@ func newMetaFromCache(entry RegistryEntry) *CacheMeta { ClonedAt: now, LastCheckedAt: now, } - return meta } // readBridgeVersion parses the `version:` field out of a cached bridge.yaml. // Returns "" when the field is absent or the file cannot be read. func readBridgeVersion(entry RegistryEntry) string { - data, err := os.ReadFile(filepath.Join(CachePath(entry), "bridge.yaml")) + manifest, err := LoadManifest(CachePath(entry)) if err != nil { return "" } - var cfg struct { - Version string `yaml:"version"` - } - if err := yaml.Unmarshal(data, &cfg); err != nil { - return "" - } - return cfg.Version + return manifest.Version } -// gitHead returns the current git HEAD commit of the cached checkout, or "". +// gitHead returns the current git HEAD commit of the cached checkout, or "" +// when it cannot be read. Callers that must tell "no commit" from "git failed" +// use gitHeadResult; a failed probe must not be mistaken for an empty HEAD. func gitHead(entry RegistryEntry) string { + head, _ := gitHeadResult(entry) + return head +} + +// gitHeadResult returns the cached checkout's HEAD commit and reports git +// failures separately. An error means the local commit is unknown — callers +// must not fall back to a stale metadata commit and compare it with the remote. +func gitHeadResult(entry RegistryEntry) (string, error) { out, err := runGit(CachePath(entry), "rev-parse", "HEAD") if err != nil { - return "" + return "", fmt.Errorf("read local bridge HEAD in %q: %w", CachePath(entry), err) } - return out + return out, nil } // gitBranch returns the current branch of the cached checkout, or "". diff --git a/internal/bridge/meta_test.go b/internal/bridge/meta_test.go new file mode 100644 index 0000000..1bfbf80 --- /dev/null +++ b/internal/bridge/meta_test.go @@ -0,0 +1,46 @@ +package bridge + +import ( + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +func TestMetaRoundTrip(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + + entry := cacheEntry("test-bridge", "owner/bridge") + + // Nothing cached yet -> no meta, not cached. + if _, err := ReadMeta(entry); err != nil { + t.Fatalf("ReadMeta on missing meta: %v", err) + } + + now := time.Now() + meta := &CacheMeta{ + ID: entry.ID, + Source: entry.GitHub, + Version: "1.0.0", + Commit: "abc123", + Branch: "main", + ClonedAt: now, + LastCheckedAt: now, + } + if err := WriteMeta(entry, meta); err != nil { + t.Fatalf("WriteMeta: %v", err) + } + + got, err := ReadMeta(entry) + if err != nil { + t.Fatalf("ReadMeta: %v", err) + } + if got.Version != "1.0.0" || got.Commit != "abc123" || got.Source != "owner/bridge" { + t.Fatalf("round-trip mismatch: %+v", got) + } + if !got.ClonedAt.Equal(now) { + t.Fatalf("ClonedAt not preserved: got %v want %v", got, now) + } +} diff --git a/internal/bridge/registry.go b/internal/bridge/registry.go index 595dcdd..76d56a4 100644 --- a/internal/bridge/registry.go +++ b/internal/bridge/registry.go @@ -1,5 +1,8 @@ +// Package bridge resolves, caches and updates bridge directories. package bridge +import "slices" + // RegistryEntry describes a known bridge in the registry. type RegistryEntry struct { ID string // unique identifier, e.g. "csharp-restful" @@ -13,10 +16,6 @@ type RegistryEntry struct { // or local bridges). The ID→Path mapping lives here, in the registry — it // is never derived from directory names at resolution time. Path string - // Layer is the bridge's open layer identifier (core/domain/persistence/ - // transport, core/client/framework/offline, ...). It matches the `layer:` - // field each bridge declares, so --replace matches what it documents. - Layer string // Deprecated marks legacy bridges kept resolvable for existing `extends:` // chains but hidden from interactive selection and flagged in `bridges`. Deprecated bool @@ -32,7 +31,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "C#", GitHub: "DomainCraft/domaincraft-bridge-csharp-core", Path: "csharp/core", - Layer: "core", }, { ID: "csharp-domain", @@ -41,7 +39,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "C#", GitHub: "DomainCraft/domaincraft-bridge-csharp-domain", Path: "csharp/domain", - Layer: "domain", }, { ID: "csharp-efcore", @@ -50,7 +47,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "C#", GitHub: "DomainCraft/domaincraft-bridge-csharp-efcore", Path: "csharp/persistence/efcore", - Layer: "persistence", }, { ID: "csharp-rest", @@ -59,7 +55,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "C#", GitHub: "DomainCraft/domaincraft-bridge-csharp-rest", Path: "csharp/transport/rest", - Layer: "transport", }, { ID: "csharp-restful", @@ -93,7 +88,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "TypeScript", GitHub: "DomainCraft/domaincraft-bridge-ts-core", Path: "typescript/core", - Layer: "core", }, { ID: "ts-client", @@ -102,7 +96,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "TypeScript", GitHub: "DomainCraft/domaincraft-bridge-ts-client", Path: "typescript/client", - Layer: "client", }, { ID: "react-rest", @@ -111,7 +104,6 @@ var DefaultRegistry = []RegistryEntry{ Language: "TypeScript", GitHub: "DomainCraft/domaincraft-bridge-react", Path: "typescript/react", - Layer: "framework", }, } @@ -122,7 +114,7 @@ type Registry struct { // NewRegistry creates a registry from the given entries. func NewRegistry(entries []RegistryEntry) *Registry { - return &Registry{entries: entries} + return &Registry{entries: slices.Clone(entries)} } // Default returns a registry backed by the built-in bridge list. @@ -132,34 +124,16 @@ func Default() *Registry { // All returns every registered bridge. func (r *Registry) All() []RegistryEntry { - return r.entries + return slices.Clone(r.entries) } // ByID finds a bridge by its unique ID. Returns nil if not found. func (r *Registry) ByID(id string) *RegistryEntry { for i := range r.entries { if r.entries[i].ID == id { - return &r.entries[i] + cp := r.entries[i] + return &cp } } return nil } - -// OfficialPath returns the monorepo-relative location (`bridges/`) of an -// official bridge, or "" when the ID is unknown or has no fixed position. -// This is the single source of truth for the ID→path mapping — callers must -// never derive it from directory names. -func (r *Registry) OfficialPath(id string) string { - if e := r.ByID(id); e != nil { - return e.Path - } - return "" -} - -// ByIDDeprecated reports whether the named bridge is deprecated. -func (r *Registry) ByIDDeprecated(id string) bool { - if e := r.ByID(id); e != nil { - return e.Deprecated - } - return false -} diff --git a/internal/bridge/status_test.go b/internal/bridge/registry_status_test.go similarity index 66% rename from internal/bridge/status_test.go rename to internal/bridge/registry_status_test.go index 365f628..1e9cd40 100644 --- a/internal/bridge/status_test.go +++ b/internal/bridge/registry_status_test.go @@ -1,7 +1,6 @@ package bridge import ( - "os" "testing" "github.com/DomainCraft/DomainCraft/internal/appdir" @@ -10,6 +9,7 @@ import ( // TestStatusLocalFacts covers embedded/cached without any network access. func TestStatusLocalFacts(t *testing.T) { appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) entry := *Default().ByID("csharp-core") st := entry.Status(false) @@ -36,32 +36,22 @@ func TestStatusLocalFacts(t *testing.T) { // TestStatusRemoteOnlyWhenRequested ensures CheckRemote=true contacts the remote // and reports outdated only for a supported (not newer-contract) bridge. func TestStatusRemoteOnlyWhenRequested(t *testing.T) { + if !gitAvailable() { + t.Skip("git not installed") + } appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) - orig := httpGetBodyFn - defer func() { httpGetBodyFn = orig }() - - httpGetBodyFn = func(url string) ([]byte, error) { - if !containsAny(url, "/repos/", "/commits/", "/bridge.yaml") { - return nil, os.ErrNotExist - } - // Simulate an upstream with a newer commit but the same contract v1. - if containsAny(url, "/commits/") { - return []byte(`{"sha":"abcdef1234567890"}`), nil - } - if containsAny(url, "/bridge.yaml") { - return []byte("name: b\ncontract_version: 1\n"), nil - } - if containsAny(url, "/repos/") { - return []byte(`{"default_branch":"main"}`), nil - } - return nil, os.ErrNotExist - } + // Simulate an upstream with a newer commit but the same contract v1. + stubGitHubAPI(t, "abcdef1234567890", "name: b\ncontract_version: 1\n") entry := *Default().ByID("csharp-core") if ok, err := TryMaterializeEmbedded(entry, nil); err != nil || !ok { t.Fatalf("materialize embedded: %v, %v", ok, err) } + // An embedded copy has no git history; without a HEAD the remote probe + // cannot tell a stale commit from the real one, so give the fixture one. + makeBridgeRepo(t, CachePath(entry), "main") st := entry.Status(true) if !st.Embedded || !st.Cached { @@ -74,14 +64,3 @@ func TestStatusRemoteOnlyWhenRequested(t *testing.T) { t.Errorf("a supported newer version should be flagged as outdated") } } - -func containsAny(s string, subs ...string) bool { - for _, sub := range subs { - for i := 0; i+len(sub) <= len(s); i++ { - if s[i:i+len(sub)] == sub { - return true - } - } - } - return false -} diff --git a/internal/bridge/resolve_ext.go b/internal/bridge/resolve_ext.go index 66facc6..9a5828c 100644 --- a/internal/bridge/resolve_ext.go +++ b/internal/bridge/resolve_ext.go @@ -8,6 +8,18 @@ import ( domaincraft "github.com/DomainCraft/DomainCraft" ) +// ResolveOfficialLocal returns the local monorepo checkout for a registered +// bridge ID, or "" when the ref is not an official ID or no local tree exists. +// Both --bridge and extends use this step, so a registered ID resolves to the +// same directory regardless of the entry point. +func ResolveOfficialLocal(ref, fromDir string) string { + entry := Default().ByID(ref) + if entry == nil { + return "" + } + return FindMonorepoBridge(fromDir, entry.Path) +} + // ResolveExtendsRef resolves one `extends` reference. It shares the loader // order with the top-level `--bridge` entry, from most to least preferred: // @@ -21,10 +33,10 @@ import ( // // Finally, the normal path/ID/owner-repo resolution (cache + clone). func ResolveExtendsRef(ref, fromDir string, resolver *Resolver) (string, error) { + if p := ResolveOfficialLocal(ref, fromDir); p != "" { + return p, nil + } if entry := Default().ByID(ref); entry != nil { - if p := FindMonorepoBridge(fromDir, entry.Path); p != "" { - return p, nil - } repo := filepath.Base(entry.GitHub) for _, candidate := range []string{ filepath.Join(filepath.Dir(fromDir), repo), // sibling of the adapter (monorepo) @@ -35,9 +47,37 @@ func ResolveExtendsRef(ref, fromDir string, resolver *Resolver) (string, error) } } } + // A relative path-like `extends` belongs to the adapter that declared it, + // not to the CLI's current working directory. The generic resolver treats + // such refs as CWD-relative (and rejects a missing one as a hard error), so + // join it with the adapter directory before handing it over. + if strings.HasPrefix(ref, ".") && looksLikePath(ref) && fromDir != "" { + local := ref + if !filepath.IsAbs(local) { + local = filepath.Join(fromDir, filepath.FromSlash(local)) + } + return resolver.Resolve(local) + } return resolver.Resolve(ref) } +// walkUpFromDir visits dir and each ancestor up to the filesystem root, +// stopping as soon as visit reports a match. Both monorepo lookups share this +// walk so their search order and stopping rule cannot drift. +func walkUpFromDir(dir string, visit func(cur string) bool) { + cur := dir + for { + if visit(cur) { + return + } + parent := filepath.Dir(cur) + if parent == cur { + return + } + cur = parent + } +} + // FindMonorepoBridge walks up from dir looking for /bridges/ // containing a bridge.yaml. It returns the bridge directory, or "" when relPath // is empty or no such bridge exists anywhere up the tree. The walk stops at the @@ -47,32 +87,80 @@ func FindMonorepoBridge(dir, relPath string) string { if relPath == "" { return "" } - cur := dir - for { + found := "" + walkUpFromDir(dir, func(cur string) bool { candidate := filepath.Join(cur, "bridges", filepath.FromSlash(relPath)) if info, err := os.Stat(filepath.Join(candidate, "bridge.yaml")); err == nil && !info.IsDir() { - return candidate + found = candidate + return true } - parent := filepath.Dir(cur) - if parent == cur { - return "" + return false + }) + return found +} + +// monorepoRoot walks up from dir looking for the root of the DomainCraft +// monorepo: a directory with a bridges/ tree and a go.mod declaring this module. +// It returns "" when dir is not inside such a tree. +func monorepoRoot(dir string) string { + abs, err := filepath.Abs(dir) + if err != nil { + return "" + } + found := "" + walkUpFromDir(abs, func(cur string) bool { + if info, err := os.Stat(filepath.Join(cur, "bridges")); err == nil && info.IsDir() { + if data, err := os.ReadFile(filepath.Join(cur, "go.mod")); err == nil && //nolint:gosec // path walked upward from the validated bridge dir + strings.Contains(string(data), "module github.com/DomainCraft/DomainCraft") { + found = cur + return true + } } - cur = parent + return false + }) + return found +} + +// samePath compares two absolute paths using the filesystem's case rules. +func samePath(a, b string) bool { return PathKey(a) == PathKey(b) } + +// PathKey normalizes an absolute path for set-based cycle detection using the +// filesystem's case rules. Both the chain walker and the CLI's `--replace` +// validation use it, so a cycle cannot be missed by one of them. +func PathKey(path string) string { + path = filepath.Clean(path) + if os.PathSeparator == '\\' { + return strings.ToLower(path) } + return path } -// MonorepoRelPath reports whether dir is the monorepo location for an official -// bridge (i.e. it ends with `bridges/`) and returns that relative -// path, or "" when the bridge was resolved from elsewhere. +// MonorepoRelPath reports whether dir is the monorepo location of a bundled +// official bridge and returns its `bridges/` relative path, or "". +// +// Three independent checks are required: the path component before the bridge +// must be exactly `bridges` (not `mybridges`), the bridge must exist in the +// embedded tree shipped by this binary, and dir must be inside the actual +// monorepo root. A suffix match alone is not enough — a lookalike local path +// must stay a community bridge so the migration consent gate still applies. func MonorepoRelPath(dir, entryPath string) string { - if entryPath == "" { + if entryPath == "" || !filepath.IsLocal(filepath.FromSlash(entryPath)) { + return "" + } + embedded := embeddedBridgeRel(entryPath) + if _, err := domaincraft.Bridges.ReadDir(embedded); err != nil { + return "" // not a bundled bridge in this binary + } + rel := filepath.Join("bridges", filepath.FromSlash(entryPath)) + abs, err := filepath.Abs(dir) + if err != nil { return "" } - suffix := filepath.Join("bridges", filepath.FromSlash(entryPath)) - if strings.HasSuffix(filepath.Clean(dir), suffix) { - return filepath.ToSlash(suffix) + root := monorepoRoot(abs) + if root == "" || !samePath(abs, filepath.Join(root, rel)) { + return "" } - return "" + return filepath.ToSlash(rel) } // IsOfficialBundled reports whether dir is a bundled monorepo bridge, i.e. it @@ -88,9 +176,9 @@ func IsOfficialBundled(dir string) bool { return false } -// BridgeStatus describes where a bridge is available from and whether it is +// Status describes where a bridge is available from and whether it is // current. It is computed without network access unless CheckRemote is true. -type BridgeStatus struct { +type Status struct { // Embedded is true when the bridge ships inside this binary (go:embed). Embedded bool // Cached is true when the bridge is materialized in the local cache. @@ -109,10 +197,10 @@ type BridgeStatus struct { // and cached — are reported, with no network traffic. // - CheckRemote=true (used by `--check-updates`): additionally probes the // remote and reports whether a newer supported version exists. -func (e RegistryEntry) Status(checkRemote bool) BridgeStatus { - s := BridgeStatus{} +func (e RegistryEntry) Status(checkRemote bool) Status { + s := Status{} if e.Path != "" { - if _, err := domaincraft.Bridges.ReadDir("bridges/" + filepath.ToSlash(e.Path)); err == nil { + if _, err := domaincraft.Bridges.ReadDir(embeddedBridgeRel(e.Path)); err == nil { s.Embedded = true } } @@ -122,15 +210,17 @@ func (e RegistryEntry) Status(checkRemote bool) BridgeStatus { if !checkRemote { return s } - u, err := CheckForUpdate(e, 0) + // A pinned bridge is fixed at one ref; there is no update to offer. + if meta, err := ReadMeta(e); err == nil && meta != nil && meta.Pin != "" { + return s + } + u, err := CheckForUpdateReadOnly(e, 0) if err == nil && u != nil { - // Only flag an update if the remote contract is supported, so an - // unsupported (neverer-contract) bridge is never offered. - if c, rerr := remoteContractVersion(e, u.RemoteBranch); rerr == nil { - if cerr := shouldApplyContract(c); cerr == nil { - s.Outdated = true - s.RemoteReachable = true - } + s.RemoteReachable = true + // Only flag an update when the remote contract can be read and is + // supported. A failed probe is "cannot offer update". + if gateRemoteContract(e, u.RemoteBranch) == nil { + s.Outdated = true } } return s diff --git a/internal/bridge/resolver.go b/internal/bridge/resolver.go index 624649e..7d3c3a2 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -1,12 +1,27 @@ package bridge import ( + "errors" "fmt" "os" "path/filepath" "strings" + "time" ) +// ErrInvalidRef marks a bridge reference rejected by validation, so CLI +// commands can map it to a usage exit code instead of a runtime failure. +var ErrInvalidRef = errors.New("invalid bridge reference") + +// asInvalidRef tags an error so the CLI can classify it as usage (exit 2). +// Multiple %w verbs keep both the marker and the original cause in the chain. +func asInvalidRef(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: %w", ErrInvalidRef, err) +} + // Resolver maps a bridge identifier to a local filesystem path. // The identifier can be: // - a local path (directory or file) — used directly @@ -32,73 +47,198 @@ func (r *Resolver) WithEnsureOptions(opts *EnsureOptions) *Resolver { // Resolve maps a bridge identifier to a local path containing bridge.yaml. // Returns ("", nil) when input is empty — caller must handle interactive selection. +// Resolution order is local path → registry ID → GitHub shorthand; a handled +// step returns done=true, otherwise the next step is tried. func (r *Resolver) Resolve(input string) (string, error) { if input == "" { return "", nil } + if path, done, err := r.resolveLocal(input); done { + return path, err + } + if path, done, err := r.resolveRegistry(input); done { + return path, err + } + if path, done, err := r.resolveGitHub(input); done { + return path, err + } + return "", asInvalidRef(fmt.Errorf("bridge %q not found: not a local path, registry ID, or owner/repo", input)) +} - // 1. Local path — use directly. Bare names that exist in the CWD count too. - if info, err := os.Stat(input); err == nil { - if info.IsDir() { - bridgeFile := filepath.Join(input, "bridge.yaml") - if _, err := os.Stat(bridgeFile); err == nil { - return input, nil - } - return "", fmt.Errorf("directory %q does not contain bridge.yaml", input) - } - return filepath.Dir(input), nil +// resolveLocal handles a local path, including bare names that exist in the +// CWD. An existing directory without bridge.yaml and a missing path-like input +// are hard errors; other missing paths fall through to remote resolution. +func (r *Resolver) resolveLocal(input string) (string, bool, error) { + dir, _, err := LocalBridgePaths(input) + if err == nil { + return dir, true, nil + } + if _, ok := errors.AsType[*missingBridgeConfigError](err); ok { + // The path exists but is not a bridge. That is a hard error, never a + // registry ID or GitHub shorthand. + return "", true, asInvalidRef(err) } // Path-like inputs ("../x", "./x", "/x", "~/x", "C:\\x") that do not // exist are an error, never a GitHub shorthand: a missing "../bridge" // must not turn into a clone of github.com/../bridge.git. if looksLikePath(input) { - abs, _ := filepath.Abs(input) - return "", fmt.Errorf("bridge %q not found: no such local path (tried %q); for GitHub use owner/repo", input, abs) + // Abs is only used for the diagnostic; the original input remains the + // authoritative value if it cannot be resolved. + abs, absErr := filepath.Abs(input) + if absErr != nil { + abs = input + } + return "", true, asInvalidRef(fmt.Errorf("bridge %q not found: no such local path (tried %q); for GitHub use owner/repo", input, abs)) } + return "", false, nil +} - // 2. Registry ID — check cache, clone if needed. - if entry := r.registry.ByID(input); entry != nil { - return EnsureBridge(*entry, r.ensure) +// resolveRegistry handles registry IDs by checking the cache and cloning if +// needed. +func (r *Resolver) resolveRegistry(input string) (string, bool, error) { + entry := r.registry.ByID(input) + if entry == nil { + return "", false, nil } + path, err := EnsureBridge(*entry, r.ensure) + return path, true, err +} - // 3. GitHub shorthand "owner/repo" — clone directly. An owner of "." or - // ".." would be a path fragment, not a GitHub user (looksLikePath already - // rejects dot-led inputs; this keeps step 3 correct on its own too). - if parts := strings.SplitN(input, "/", 2); len(parts) == 2 && parts[0] != "" && parts[1] != "" && parts[0] != "." && parts[0] != ".." { - repo, ref := splitPinRef(input) - entry := RegistryEntry{ - ID: parts[1], - GitHub: repo, +// resolveGitHub handles the "owner/repo" shorthand. An owner of "." or ".." +// would be a path fragment, not a GitHub user (resolveLocal already rejects +// dot-led inputs; the check in parseGitHubRef keeps this step correct on its +// own too). +func (r *Resolver) resolveGitHub(input string) (string, bool, error) { + repo, ref, err := parseGitHubRef(input) + if err != nil { + return "", true, asInvalidRef(err) + } + if repo == "" { + return "", false, nil + } + entry := RegistryEntry{ + // Owner-scoped: the bare repository name would collide in the + // cache with another owner's repo of the same name. + ID: cacheIDForGitHub(repo), + GitHub: repo, + } + path, err := EnsureBridge(entry, r.ensure) + if err != nil { + return "", true, err + } + if ref != "" { + if err := checkoutPinnedRef(path, ref); err != nil { + return "", true, err } - path, err := EnsureBridge(entry, r.ensure) - if err != nil { - return "", err + // Persist the pin: a later cache refresh must not silently move a + // pinned bridge onto the default branch. + if err := recordPin(entry, ref); err != nil { + return "", true, err } - if ref != "" { - if err := checkoutPinnedRef(path, ref); err != nil { - return "", err - } + } + return path, true, nil +} + +// parseGitHubRef splits an `owner/repo@ref` shorthand and validates both parts. +// The pin is split first: a ref may legally contain "/", while a repository +// name may not. +func parseGitHubRef(input string) (repo, ref string, err error) { + repo, ref = splitPinRef(input) + parts := strings.SplitN(repo, "/", 2) + if len(parts) != 2 || parts[0] == "" || parts[1] == "" || parts[0] == "." || parts[0] == ".." { + // An empty repo is the single "not an owner/repo" signal for callers. + return "", "", nil + } + if strings.ContainsAny(parts[1], "/\\") || parts[1] == "." || parts[1] == ".." { + return "", "", fmt.Errorf("bridge %q not found: invalid repository name", input) + } + if ref != "" { + if err := validatePinRef(ref); err != nil { + return "", "", err } - return path, nil } + return repo, ref, nil +} + +// missingBridgeConfigError marks an existing directory that has no bridge.yaml. +// Resolve surfaces it verbatim instead of falling through to registry/GitHub +// resolution; the renderer fails closed on the same error. +type missingBridgeConfigError struct{ dir string } + +// Error reports the directory lacking bridge.yaml. +func (e *missingBridgeConfigError) Error() string { + return fmt.Sprintf("directory %q does not contain bridge.yaml", e.dir) +} - return "", fmt.Errorf("bridge %q not found: not a local path, registry ID, or owner/repo", input) +// LocalBridgePaths validates a local bridge reference and returns its directory +// and bridge.yaml path. A directory must contain bridge.yaml; a file is treated +// as the config itself and yields its parent directory. Missing or unreadable +// paths are errors. This is the single normalization used by both the resolver +// and the renderer, so a path accepted by one is accepted by the other. +func LocalBridgePaths(input string) (dir, configFile string, err error) { + info, err := os.Stat(input) + if err != nil { + return "", "", fmt.Errorf("bridge path %q: %w", input, err) + } + if !info.IsDir() { + return filepath.Dir(input), input, nil + } + config := filepath.Join(input, "bridge.yaml") + if _, err := os.Stat(config); err != nil { + return "", "", &missingBridgeConfigError{dir: input} + } + return input, config, nil } // splitPinRef splits a `owner/repo@ref` shorthand into the repository and the // pinned ref (commit SHA, tag or branch). A bare `owner/repo` has no ref. func splitPinRef(s string) (repo, ref string) { - if i := strings.LastIndexByte(s, '@'); i > 0 { - return s[:i], s[i+1:] + before, after, found := strings.CutLast(s, "@") + if found && before != "" { + return before, after } return s, "" } +// validatePinRef enforces a strict git-ref grammar before a user-supplied ref +// is handed to rev-parse/checkout. A leading '-' would become a git option and +// revision expressions ("..", "~", "^", "@{") would escape the "one ref" +// contract, so they are rejected before any command runs. +func validatePinRef(ref string) error { + if ref == "" { + return fmt.Errorf("invalid pinned ref: empty") + } + if strings.HasPrefix(ref, "-") { + return fmt.Errorf("invalid pinned ref %q: leading '-' would be parsed as a git option", ref) + } + if strings.HasPrefix(ref, "/") || strings.HasSuffix(ref, "/") { + return fmt.Errorf("invalid pinned ref %q: leading or trailing '/'", ref) + } + if strings.Contains(ref, "..") || strings.Contains(ref, "//") || strings.Contains(ref, "@{") { + return fmt.Errorf("invalid pinned ref %q: traversal or revision expression", ref) + } + if strings.HasSuffix(ref, ".lock") { + return fmt.Errorf("invalid pinned ref %q: '.lock' suffix", ref) + } + for _, r := range ref { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + case r == '-' || r == '_' || r == '.' || r == '/' || r == '+': + default: + return fmt.Errorf("invalid pinned ref %q: character %q is not allowed", ref, r) + } + } + return nil +} + // checkoutPinnedRef checks that the pinned ref exists in the checkout and // switches the cached bridge to it, so community-bridge resolution is pinned to // a specific commit/tag rather than "whatever main is today". func checkoutPinnedRef(dir, ref string) error { + if err := validatePinRef(ref); err != nil { + return err + } if _, err := runGit(dir, "rev-parse", "--verify", ref+"^{commit}"); err != nil { return fmt.Errorf("pinned ref %q not found in %s: %w", ref, dir, err) } @@ -106,6 +246,17 @@ func checkoutPinnedRef(dir, ref string) error { return err } +// recordPin stores the pin in cache metadata so a later update cannot move the +// checkout off the requested ref. Legacy metadata without the field decodes to +// an empty pin and is left untouched. +func recordPin(entry RegistryEntry, ref string) error { + return modifyMeta(entry, func(meta *CacheMeta) { + meta.Pin = ref + meta.Commit = gitHead(entry) + meta.LastCheckedAt = time.Now() + }) +} + // looksLikePath reports whether input is path-like — relative ("../x", "./x"), // absolute ("/x", "\\x"), home-relative ("~/x") or a Windows drive // ("C:\\x") — and therefore must be resolved only against the local diff --git a/internal/bridge/resolver_test.go b/internal/bridge/resolver_test.go index 7999e71..9cafcd3 100644 --- a/internal/bridge/resolver_test.go +++ b/internal/bridge/resolver_test.go @@ -34,14 +34,7 @@ func TestResolver_LocalPath(t *testing.T) { } // Bare directory name resolvable from the CWD (backwards compatible). - orig, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - if err := os.Chdir(root); err != nil { - t.Fatal(err) - } - defer os.Chdir(orig) //nolint:errcheck // test-only cleanup + t.Chdir(root) got, err := r.Resolve("my-bridge") if err != nil { t.Fatalf("Resolve(my-bridge): %v", err) @@ -55,12 +48,12 @@ func TestResolver_MissingPathLikeIsErrorNotClone(t *testing.T) { r := NewResolver(&Registry{}) for _, input := range []string{ - "../domaincraftcsharp", // the regression: must NOT clone github.com/../domaincraftcsharp - "./no-such-bridge", // explicit relative path - "/no/such/bridge", // absolute path - "~/no-such-bridge", // home-relative - "no\\such\\bridge", // Windows-style relative - "C:/no/such/bridge", // Windows drive + "../domaincraftcsharp", // the regression: must NOT clone github.com/../domaincraftcsharp + "./no-such-bridge", // explicit relative path + "/no/such/bridge", // absolute path + "~/no-such-bridge", // home-relative + "no\\such\\bridge", // Windows-style relative + "C:/no/such/bridge", // Windows drive } { _, err := r.Resolve(input) if err == nil { @@ -94,3 +87,89 @@ func TestLooksLikePath(t *testing.T) { } } } + +// TestResolveExtendsRelativeToAdapterDir pins the base of a relative +// `extends`: it belongs to the declaring adapter, not to the CLI's current +// working directory. +func TestResolveExtendsRelativeToAdapterDir(t *testing.T) { + root := t.TempDir() + adapter := filepath.Join(root, "adapter") + base := filepath.Join(adapter, "base") + sibling := filepath.Join(root, "shared") + for _, spec := range []struct{ dir, name string }{ + {adapter, "adapter"}, {base, "base"}, {sibling, "shared"}, + } { + if err := os.MkdirAll(spec.dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(spec.dir, "bridge.yaml"), []byte("name: "+spec.name+"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + + r := NewResolver(&Registry{}) + for _, ref := range []string{"./base", "../shared"} { + want := base + if ref == "../shared" { + want = sibling + } + got, err := ResolveExtendsRef(ref, adapter, r) + if err != nil { + t.Fatalf("ResolveExtendsRef(%q, %q): %v", ref, adapter, err) + } + if got != want { + t.Errorf("ResolveExtendsRef(%q, %q) = %q, want %q", ref, adapter, got, want) + } + } + + // A missing relative ref stays a hard local-path error, never a clone. + if _, err := ResolveExtendsRef("./missing", adapter, r); err == nil || + !strings.Contains(err.Error(), "no such local path") { + t.Errorf("missing relative extends: err = %v, want a local-path error", err) + } +} + +// F27: FindMonorepoBridge walks up to the filesystem root and takes the first +// (nearest) match — the shared walk must preserve that order. +func TestFindMonorepoBridgeWalksUp(t *testing.T) { + root := t.TempDir() + bridgeDir := makeMonorepoBridge(t, root, "csharp/core") + deep := filepath.Join(root, "a", "b", "c") + if err := os.MkdirAll(deep, 0o755); err != nil { + t.Fatal(err) + } + if got := FindMonorepoBridge(deep, "csharp/core"); got != bridgeDir { + t.Errorf("FindMonorepoBridge(%q) = %q, want %q", deep, got, bridgeDir) + } + if got := FindMonorepoBridge(deep, ""); got != "" { + t.Errorf("FindMonorepoBridge with empty relPath = %q, want empty", got) + } + + // A nearer candidate wins over the one at the monorepo root. + inner := filepath.Join(root, "a", "bridges", "csharp", "core") + if err := os.MkdirAll(inner, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inner, "bridge.yaml"), []byte("name: inner\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := FindMonorepoBridge(deep, "csharp/core"); got != inner { + t.Errorf("FindMonorepoBridge(%q) = %q, want nearest match %q", deep, got, inner) + } +} + +// F27: monorepoRoot uses the same upward walk with a different visitor. +func TestMonorepoRootWalksUp(t *testing.T) { + root := t.TempDir() + makeMonorepoBridge(t, root, "csharp/core") + deep := filepath.Join(root, "a", "b", "c") + if err := os.MkdirAll(deep, 0o755); err != nil { + t.Fatal(err) + } + if got := monorepoRoot(deep); got != root { + t.Errorf("monorepoRoot(%q) = %q, want %q", deep, got, root) + } + if got := monorepoRoot(t.TempDir()); got != "" { + t.Errorf("monorepoRoot outside a monorepo = %q, want empty", got) + } +} diff --git a/internal/bridge/safety_test.go b/internal/bridge/safety_test.go deleted file mode 100644 index 85ac5e1..0000000 --- a/internal/bridge/safety_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package bridge - -import ( - "os" - "path/filepath" - "testing" -) - -// TestIsOfficialBundled distinguishes bundled official bridges (which may -// auto-run declared migrations) from community/local bridges (which must not). -func TestIsOfficialBundled(t *testing.T) { - root := t.TempDir() - - // A bundled official monorepo location: /bridges/csharp/core. - official := filepath.Join(root, "bridges", "csharp", "core") - if err := os.MkdirAll(official, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(official, "bridge.yaml"), []byte("name: csharp-core\n"), 0o644); err != nil { - t.Fatal(err) - } - if !IsOfficialBundled(official) { - t.Errorf("IsOfficialBundled(%s) = false, want true", official) - } - - // A custom/local path must not count as bundled official. - custom := filepath.Join(root, "my-bridge") - if err := os.MkdirAll(custom, 0o755); err != nil { - t.Fatal(err) - } - if IsOfficialBundled(custom) { - t.Errorf("IsOfficialBundled(%s) = true, want false", custom) - } - - // A registry cache path (~/.domaincraft/bridges/) must not count either. - cache := filepath.Join(root, "csharp-core") - if err := os.MkdirAll(cache, 0o755); err != nil { - t.Fatal(err) - } - if IsOfficialBundled(cache) { - t.Errorf("IsOfficialBundled(%s) = true, want false", cache) - } -} - -// TestSplitPinRef covers the community-bridge pin syntax `owner/repo@ref`. -func TestSplitPinRef(t *testing.T) { - cases := []struct { - in string - repo string - ref string - }{ - {"owner/repo", "owner/repo", ""}, - {"owner/repo@v1.2.3", "owner/repo", "v1.2.3"}, - {"owner/repo@9f8e7d6c5b4a3210", "owner/repo", "9f8e7d6c5b4a3210"}, - {"owner/repo@feature/branch", "owner/repo", "feature/branch"}, - {"owner/repo@tag@x", "owner/repo@tag", "x"}, // last @ wins - } - for _, c := range cases { - repo, ref := splitPinRef(c.in) - if repo != c.repo || ref != c.ref { - t.Errorf("splitPinRef(%q) = (%q, %q), want (%q, %q)", c.in, repo, ref, c.repo, c.ref) - } - } -} - -// TestPinRefNotAppliedToRegistryIDs ensures the pin syntax never collides with -// path handling: a bare registry ID is not treated as owner/repo. -func TestPinRefNotAppliedToRegistryIDs(t *testing.T) { - if _, ref := splitPinRef("csharp-rest"); ref != "" { - t.Errorf("registry ID got a ref: %q", ref) - } -} diff --git a/internal/bridge/testhelpers_test.go b/internal/bridge/testhelpers_test.go new file mode 100644 index 0000000..f6049e4 --- /dev/null +++ b/internal/bridge/testhelpers_test.go @@ -0,0 +1,115 @@ +package bridge + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +// gitAvailable reports whether git is installed (bridge update handling needs it). +func gitAvailable() bool { + _, err := exec.LookPath("git") + return err == nil +} + +// testGit runs git in dir and returns combined output, failing the test on error. +func testGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(gitScrubbedEnv(), "GIT_AUTHOR_NAME=domaincraft-test", "GIT_AUTHOR_EMAIL=test@example.com") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %s in %s: %v\n%s", strings.Join(args, " "), dir, err, out) + } + return strings.TrimSpace(string(out)) +} + +// makeBridgeRepo creates a non-bare git repo at dir with a bridge.yaml committed +// on the given branch. Returns the repo path. +func makeBridgeRepo(t *testing.T, dir, branch string) { + t.Helper() + testGit(t, dir, "init", "-q", "-b", branch) + testGit(t, dir, "config", "user.email", "test@domaincraft.dev") + testGit(t, dir, "config", "user.name", "DomainCraft Test") + writeBridgeYAML(t, dir, "1.0.0") + testGit(t, dir, "add", ".") + testGit(t, dir, "commit", "-q", "-m", "init") +} + +// newRemoteWithBridge builds a bare git remote with one bridge commit and +// returns the remote path plus the source checkout. Tests drive the unusual +// steps (tags, version bumps, second pushes) through the returned src path. +func newRemoteWithBridge(t *testing.T, root, branch, version string) (remote, src string) { + t.Helper() + remote = filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", branch, "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/"+branch) + + src = filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, branch) + if version != "" && version != "1.0.0" { + writeBridgeYAML(t, src, version) + testGit(t, src, "add", ".") + testGit(t, src, "commit", "-q", "-m", "version "+version) + } + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", branch) + return remote, src +} + +// writeBridgeYAML writes a minimal bridge.yaml with the given version. +func writeBridgeYAML(t *testing.T, dir, version string) { + t.Helper() + body := "name: test-bridge\nversion: \"" + version + "\"\n" + if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(body), 0o644); err != nil { + t.Fatalf("write bridge.yaml: %v", err) + } +} + +// githubAPIStub is the offline stand-in for the GitHub probes. Calls counts +// every request, so tests can assert the remote was never contacted. +type githubAPIStub struct { + calls atomic.Int32 + sha string + yaml string +} + +// stubGitHubAPI swaps httpGetBodyFn for a deterministic GitHub API response: +// sha for commit probes, yaml for raw bridge.yaml probes (an empty yaml means +// the manifest is unavailable). The original function is restored on cleanup. +func stubGitHubAPI(t *testing.T, sha, yaml string) *githubAPIStub { + t.Helper() + stub := &githubAPIStub{sha: sha, yaml: yaml} + original := httpGetBodyFn + t.Cleanup(func() { httpGetBodyFn = original }) + httpGetBodyFn = func(url string) ([]byte, error) { + stub.calls.Add(1) + switch { + case strings.Contains(url, "/commits/"): + return []byte(`{"sha":"` + stub.sha + `"}`), nil + case strings.Contains(url, "/repos/"): + return []byte(`{"default_branch":"main"}`), nil + case strings.Contains(url, "bridge.yaml"): + if stub.yaml == "" { + return nil, os.ErrNotExist + } + return []byte(stub.yaml), nil + } + return nil, os.ErrNotExist + } + return stub +} + +func (s *githubAPIStub) Calls() int { return int(s.calls.Load()) } + +// cacheEntry returns a RegistryEntry whose cache path is under the test cache root. +func cacheEntry(id, source string) RegistryEntry { + return RegistryEntry{ID: id, GitHub: source} +} diff --git a/internal/bridge/update.go b/internal/bridge/update.go index 34c949d..1c8e13f 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -1,20 +1,34 @@ package bridge import ( + "context" "encoding/json" + "errors" "fmt" - "io" - "net/http" + "net/url" "os" "os/exec" + "path/filepath" "strings" "time" + "github.com/DomainCraft/DomainCraft/internal/netutil" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "gopkg.in/yaml.v3" ) // httpClient is shared by remote version probes. -var httpClient = &http.Client{Timeout: 10 * time.Second} +var httpClient = netutil.NewBoundedClient(10*time.Second, nil) + +// gitCommandTimeout bounds every git child so a library host without a +// cancellable command context cannot hang on a stalled remote. +const gitCommandTimeout = 2 * time.Minute + +// gitCommandContext is the single context source for git children. The initial +// clone and every update command share this deadline; callers must cancel it. +func gitCommandContext() (context.Context, context.CancelFunc) { + return context.WithTimeout(CommandContext(), gitCommandTimeout) +} // httpGetBodyFn is the HTTP GET used by update probes. It is a variable so // tests can substitute a fake and exercise the GitHub code paths offline. @@ -27,55 +41,106 @@ var httpGetBodyFn = httpGetBody const DefaultUpdateInterval = 24 * time.Hour // CoreContractVersion is the bridge-contract version the current core -// implements. It must match renderer.ContractVersion. An upstream bridge -// declaring a higher contract is unsupported and must never be applied. -const CoreContractVersion = 1 +// implements. It aliases specmeta.ContractVersion so a bump needs one edit. +// An upstream bridge declaring a higher contract is unsupported and must never +// be applied. +const CoreContractVersion = specmeta.ContractVersion -// parseBridgeContractVersion reads `contract_version` from bridge.yaml bytes. -// An absent field means contract v1. -func parseBridgeContractVersion(data []byte) int { +// ParseContractVersion reads `contract_version` from bridge.yaml bytes. It is +// the single parser used by both the update gate and the renderer loader, so +// a manifest can never be accepted on one side and rejected on the other. +// Returns the effective version, whether the field was explicitly declared, +// and an error. An absent (or zero) field means the core's contract version; +// every other unreadable value — including a negative one — is a hard error: +// a malformed manifest must never be silently downgraded to "supported". +func ParseContractVersion(data []byte) (int, bool, error) { + // Parse once into a node, then decode from it. A truncated body may still + // be valid YAML (e.g. a scalar or a list), so require a mapping document + // before reading the version. + var doc yaml.Node + if err := yaml.Unmarshal(data, &doc); err != nil { + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) + } + if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { + return 0, false, fmt.Errorf("parse bridge contract version: manifest must be a YAML mapping") + } + // A pointer distinguishes an absent field from an explicit 0, while the + // declared flag follows the legacy "0 means absent" behaviour. var cfg struct { - ContractVersion int `yaml:"contract_version"` + ContractVersion *int `yaml:"contract_version"` } - if err := yaml.Unmarshal(data, &cfg); err != nil { - return 1 + if err := doc.Decode(&cfg); err != nil { + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) } - if cfg.ContractVersion == 0 { - return 1 + if cfg.ContractVersion == nil { + return CoreContractVersion, false, nil } - return cfg.ContractVersion + if *cfg.ContractVersion < 0 { + return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) + } + if *cfg.ContractVersion == 0 { + return CoreContractVersion, false, nil + } + return *cfg.ContractVersion, true, nil } -// shouldApplyContract verifies that a bridge declaring contractVersion is +// CheckContractVersion verifies that a bridge declaring contractVersion is // supported by the current core. A newer contract is a hard error — an -// unsupported bridge must never be downloaded/applied. -func shouldApplyContract(contractVersion int) error { +// unsupported bridge must never be downloaded/applied. Shared with the +// renderer so both gates move together on a contract bump. +func CheckContractVersion(contractVersion int) error { if contractVersion > CoreContractVersion { return fmt.Errorf("bridge requires contract v%d, but this core implements contract v%d", contractVersion, CoreContractVersion) } return nil } +// gateRemoteContract fetches a bridge manifest at ref and applies the contract +// gate. Every read path (update offer, status probe) uses this one decision. +func gateRemoteContract(entry RegistryEntry, ref string) error { + c, err := remoteContractVersion(entry, ref) + if err != nil { + return err + } + return CheckContractVersion(c) +} + +// gateContractBytes applies the same gate to bridge.yaml bytes already in hand +// (a fetched FETCH_HEAD or the local cache). An unreadable manifest fails closed. +func gateContractBytes(data []byte) error { + version, _, err := ParseContractVersion(data) + if err != nil { + return err + } + return CheckContractVersion(version) +} + // remoteContractVersion fetches a bridge's declared contract version at a ref -// without cloning, via the GitHub raw-content endpoint. Best-effort: a missing -// or unreadable bridge.yaml is treated as contract v1 (the lowest). +// without cloning, via the GitHub raw-content endpoint. An unreadable manifest +// is an error: callers treat it as "cannot offer update" rather than guessing +// a supported version. func remoteContractVersion(entry RegistryEntry, ref string) (int, error) { if ref == "" { ref = "main" } + // The ref reaches a URL path before git ever validates it. Reject hostile + // path/revision characters here so the contract gate cannot be pointed at a + // different manifest than the ref ApplyUpdate later checks out. + if err := validatePinRef(ref); err != nil { + return 0, fmt.Errorf("invalid contract ref %q: %w", ref, err) + } body, err := httpGetBodyFn(fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/bridge.yaml", entry.GitHub, ref)) if err != nil { return 0, err } - return parseBridgeContractVersion(body), nil + version, _, err := ParseContractVersion(body) + return version, err } // Update describes a detected newer version of a cached bridge. Callers hand it // to the user (e.g. an interactive prompt) and then to ApplyUpdate. type Update struct { - Entry RegistryEntry LocalVersion string // version of the cached checkout - RemoteCommit string RemoteBranch string } @@ -87,6 +152,18 @@ type Update struct { // offline generation keeps working with the cached copy. A nil result means the // bridge is current (or the check was skipped). func CheckForUpdate(entry RegistryEntry, interval time.Duration) (*Update, error) { + return checkForUpdate(entry, interval, true) +} + +// CheckForUpdateReadOnly detects updates without recording the attempt in cache +// metadata. It is the `bridges --check-updates` path: a status query must not +// mutate .domaincraft-meta.json, while generation-time probes keep refreshing +// LastCheckedAt through CheckForUpdate. +func CheckForUpdateReadOnly(entry RegistryEntry, interval time.Duration) (*Update, error) { + return checkForUpdate(entry, interval, false) +} + +func checkForUpdate(entry RegistryEntry, interval time.Duration, recordCheck bool) (*Update, error) { meta, err := ensureMeta(entry) if err != nil { return nil, err @@ -101,31 +178,41 @@ func CheckForUpdate(entry RegistryEntry, interval time.Duration) (*Update, error } // Keep the local commit in sync with the actual checkout so a manual pull - // of the cache does not incorrectly report an update. - if head := gitHead(entry); head != "" { + // of the cache does not incorrectly report an update. A git failure (no + // binary, broken checkout) leaves the local commit unknown: a stale + // metadata commit compared with the remote tip would be a false update. + head, headErr := gitHeadResult(entry) + if headErr == nil && head != "" { meta.Commit = head } remoteBranch, remoteCommit, err := githubAPIHead(entry) // Record the attempt regardless of outcome so the freshness gate applies - // even while offline (otherwise every run would wait on a timeout). + // even while offline (otherwise every run would wait on a timeout) — but + // only for write-enabled probes; status checks leave the cache untouched. meta.LastCheckedAt = now - if werr := WriteMeta(entry, meta); werr != nil && err == nil { - return nil, werr + if recordCheck { + werr := WriteMeta(entry, meta) + if err != nil && werr != nil { + return nil, errors.Join(err, fmt.Errorf("record bridge update check: %w", werr)) + } + if werr != nil { + return nil, werr + } } - if err != nil || remoteCommit == "" { - return nil, nil // can't reach the remote — assume up to date + if headErr != nil || err != nil || remoteCommit == "" { + // No trustworthy local commit or no reachable remote: assume up to + // date. The attempt has already been recorded above. + return nil, nil } if remoteCommit == meta.Commit { return nil, nil // local checkout already at the remote tip } return &Update{ - Entry: entry, LocalVersion: meta.Version, - RemoteCommit: remoteCommit, RemoteBranch: remoteBranch, }, nil } @@ -134,47 +221,151 @@ func CheckForUpdate(entry RegistryEntry, interval time.Duration) (*Update, error // preserving the checkout via a shallow fetch + hard reset (a full re-clone is // used as a fallback if the in-place update fails). It returns the new version. func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { + if err := validateCacheID(entry.ID); err != nil { + return "", err + } cacheDir := CachePath(entry) + // A pinned checkout has an explicit ref. Remember it so a direct ApplyUpdate + // never leaves the cache on the default branch. + // A corrupt metadata file must not silently drop a pin and move the cache + // to the default branch. Fail closed before touching the checkout. + meta, err := ReadMeta(entry) + if err != nil { + return "", fmt.Errorf("read metadata for bridge %q: %w", entry.ID, err) + } + pin := "" + if meta != nil { + pin = meta.Pin + } + branch := "main" if u != nil && u.RemoteBranch != "" { branch = u.RemoteBranch - } else if meta, err := ReadMeta(entry); err == nil && meta != nil && meta.Branch != "" { + } else if meta != nil && meta.Branch != "" { branch = meta.Branch } + // The branch can come from cache metadata, so an attacker-controlled value + // must never become a git option or a revision expression. + if err := validatePinRef(branch); err != nil { + return "", fmt.Errorf("invalid fetch branch %q: %w", branch, err) + } - // Fast path: update the existing checkout in place. - if _, err := runGit(cacheDir, "fetch", "--depth", "1", "origin", branch); err == nil { + // Fast path: update the existing checkout in place. Keep why it failed so a + // fallback failure reports the original cause as well as the cleanup. + var fastPathErrs []error + if _, err := runGit(cacheDir, "fetch", "--depth", "1", "origin", branch); err != nil { + fastPathErrs = append(fastPathErrs, + fmt.Errorf("fetch branch %q of bridge %q in %q: %w", branch, entry.ID, cacheDir, err)) + } else { // Contract gate: never apply an upstream bridge this core cannot support. - // Check the fetched tree's bridge.yaml before touching the checkout. - if out, serr := runGit(cacheDir, "show", "FETCH_HEAD:bridge.yaml"); serr == nil { - if cerr := shouldApplyContract(parseBridgeContractVersion([]byte(out))); cerr != nil { - return "", cerr - } + // The manifest must be readable — fail closed when it is not. + out, serr := runGit(cacheDir, "show", "FETCH_HEAD:bridge.yaml") + if serr != nil { + return "", fmt.Errorf("read fetched bridge manifest: %w", serr) } - if _, err := runGit(cacheDir, "reset", "--hard", "FETCH_HEAD"); err == nil { - return syncMetaAfterUpdate(entry, branch) + if cerr := gateContractBytes([]byte(out)); cerr != nil { + return "", cerr + } + if _, err := runGit(cacheDir, "reset", "--hard", "FETCH_HEAD"); err != nil { + fastPathErrs = append(fastPathErrs, + fmt.Errorf("reset bridge %q in %q to FETCH_HEAD: %w", entry.ID, cacheDir, err)) + } else { + return finishUpdate(entry, branch, pin) } // reset failed — fall through to a clean re-clone } - // Fallback: the existing checkout is unusable; replace it entirely. + // Fallback: the existing checkout is unusable; replace it entirely. Report + // the in-place failure (primary) alongside any cleanup/re-clone failure. if err := os.RemoveAll(cacheDir); err != nil { - return "", err + return "", errors.Join(append(fastPathErrs, + fmt.Errorf("remove cache dir %q: %w", cacheDir, err))...) } if err := CloneBridge(entry); err != nil { - return "", err + return "", errors.Join(append(fastPathErrs, + fmt.Errorf("re-clone bridge %q into %q: %w", entry.ID, cacheDir, err))...) } - return syncMetaAfterUpdate(entry, branch) + // The fallback clone is a fresh checkout of the default branch, so it must + // pass the same contract gate as the fast path. Fail closed: an unsupported + // bridge is never recorded as the new cache, and the in-place failure stays + // as the primary cause alongside the contract and cleanup errors. + if cerr := checkCachedContract(entry); cerr != nil { + errs := append(append([]error{}, fastPathErrs...), cerr) + if rerr := os.RemoveAll(cacheDir); rerr != nil { + errs = append(errs, fmt.Errorf("remove unsupported bridge cache %q: %w", cacheDir, rerr)) + } + return "", errors.Join(errs...) + } + return finishUpdate(entry, branch, pin) +} + +// checkCachedContract reads the freshly cloned bridge.yaml and rejects a +// contract this core cannot support. An unreadable manifest is an error, never +// a pass — the same rule the fast path applies to FETCH_HEAD. +func checkCachedContract(entry RegistryEntry) error { + data, err := os.ReadFile(filepath.Join(CachePath(entry), "bridge.yaml")) + if err != nil { + return fmt.Errorf("read bridge manifest in %q: %w", CachePath(entry), err) + } + return gateContractBytes(data) +} + +// finishUpdate re-applies a pin (if any) before recording metadata, so an +// updated cache never drifts from the ref the user asked for. +func finishUpdate(entry RegistryEntry, branch, pin string) (string, error) { + if pin != "" { + dir := CachePath(entry) + pinErr := checkoutPinnedRef(dir, pin) + if pinErr != nil { + // A shallow clone/fetch often lacks an arbitrary tag or commit. + // Try to bring that exact ref in before declaring the pin lost. + if verr := validatePinRef(pin); verr == nil { + // Fetch into a local ref named exactly like the pin: a plain + // `fetch origin ` only fills FETCH_HEAD, which checkout by + // name cannot resolve. A '+' allows refreshing an existing ref. + refspec := "+" + pin + ":refs/heads/" + pin + if _, ferr := runGit(dir, "fetch", "--depth", "1", "origin", refspec); ferr == nil { + pinErr = checkoutPinnedRef(dir, pin) + } else { + pinErr = errors.Join(pinErr, fmt.Errorf("fetch pinned ref %q: %w", pin, ferr)) + } + } + } + if pinErr != nil { + // The branch checkout already passed the contract gate. Keep it, + // but drop the pin: metadata claiming a pin the checkout does not + // hold would make the next run skip every freshness check. + if _, werr := syncMetaAfterUpdate(entry, branch, ""); werr != nil { + pinErr = errors.Join(pinErr, fmt.Errorf("clear stale pin after update: %w", werr)) + } + return "", fmt.Errorf("restore pinned ref %q after update: %w", pin, pinErr) + } + // The gate above checked FETCH_HEAD, not the ref we actually keep. + // Re-check the pinned manifest before recording the cache. + if err := checkCachedContract(entry); err != nil { + // The checkout now holds an unsupported pinned tree. Remove it so + // a later run cannot treat it as an already-certified pin. + cerr := fmt.Errorf("check pinned bridge %q contract: %w", pin, err) + if rerr := os.RemoveAll(dir); rerr != nil { + cerr = errors.Join(cerr, fmt.Errorf("remove unsupported pinned cache %q: %w", dir, rerr)) + } + return "", cerr + } + } + // One write records version, branch and pin together. The old flow wrote + // metadata twice and briefly persisted a cache with no pin at all. + return syncMetaAfterUpdate(entry, branch, pin) } // syncMetaAfterUpdate refreshes the cached checkout's metadata after a // successful download/update and returns the new bridge version. -func syncMetaAfterUpdate(entry RegistryEntry, branch string) (string, error) { +func syncMetaAfterUpdate(entry RegistryEntry, branch, pin string) (string, error) { meta := newMetaFromCache(entry) if branch != "" { meta.Branch = branch } + meta.Pin = pin if err := WriteMeta(entry, meta); err != nil { return meta.Version, err } @@ -189,44 +380,82 @@ func githubAPIHead(entry RegistryEntry) (branch, commit string, err error) { if err != nil { return "", "", err } - var repo struct { - DefaultBranch string `json:"default_branch"` - } - if err := json.Unmarshal(repoBody, &repo); err != nil { + branch, err = decodeJSONString(repoBody, "default_branch") + if err != nil { return "", "", err } - if repo.DefaultBranch == "" { + if branch == "" { return "", "", fmt.Errorf("github API: no default branch for %s", entry.GitHub) } + // The API response is remote data: validate it before it becomes a URL path + // or, later, the branch passed to git fetch. + if err := validatePinRef(branch); err != nil { + return "", "", fmt.Errorf("github API: %w", err) + } - commitBody, err := httpGetBodyFn(fmt.Sprintf("https://api.github.com/repos/%s/commits/%s", entry.GitHub, repo.DefaultBranch)) + commitBody, err := httpGetBodyFn(fmt.Sprintf("https://api.github.com/repos/%s/commits/%s", entry.GitHub, branch)) if err != nil { return "", "", err } - var c struct { - SHA string `json:"sha"` - } - if err := json.Unmarshal(commitBody, &c); err != nil { + commit, err = decodeJSONString(commitBody, "sha") + if err != nil { return "", "", err } - if c.SHA == "" { - return "", "", fmt.Errorf("github API: no head commit for %s/%s", entry.GitHub, repo.DefaultBranch) + if commit == "" { + return "", "", fmt.Errorf("github API: no head commit for %s/%s", entry.GitHub, branch) } - return repo.DefaultBranch, c.SHA, nil + return branch, commit, nil } -// httpGetBody performs a GET and returns the response body, limiting its size -// to 1 MiB to avoid unbounded reads from a misbehaving endpoint. -func httpGetBody(url string) ([]byte, error) { - resp, err := httpClient.Get(url) - if err != nil { - return nil, err +// decodeJSONString reads one string field from a remote JSON object. Both +// GitHub API responses use the same shape; keeping the decode in one place +// makes their error handling consistent. +func decodeJSONString(body []byte, key string) (string, error) { + var raw map[string]json.RawMessage + if err := json.Unmarshal(body, &raw); err != nil { + return "", err + } + value, ok := raw[key] + if !ok { + return "", nil + } + var s string + if err := json.Unmarshal(value, &s); err != nil { + return "", fmt.Errorf("github API: field %q: %w", key, err) + } + return s, nil +} + +// maxProbeBodyBytes caps remote probe responses (bridge.yaml, GitHub JSON). +const maxProbeBodyBytes = netutil.DefaultMaxBodyBytes + +// validateProbeRedirect is the redirect rule for bridge/update HTTP probes. +// netutil installs it as CheckRedirect, so it runs before each follow-up +// request is sent — checking resp.Request.URL after client.Do is too late. +// Only the HTTPS hosts GitHub uses for these probes are allowed. +func validateProbeRedirect(u *url.URL) error { + if u == nil { + return fmt.Errorf("redirect without a target URL") + } + if u.Scheme != "https" { + return fmt.Errorf("redirect scheme %q is not allowed", u.Scheme) } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, url) + host := strings.ToLower(u.Hostname()) + switch host { + case githubHost, "api." + githubHost, "raw.githubusercontent.com": + return nil + default: + return fmt.Errorf("host %q is not allowed", host) } - return io.ReadAll(io.LimitReader(resp.Body, 1<<20)) +} + +// httpGetBody performs a GET bound to the CLI's command context and returns the +// response body. The bounded GET, status check and redaction live in netutil; +// this wrapper keeps the package's test seam and the 10s probe client, and +// passes a redirect rule so every hop is validated before the request to the +// new host is made. +func httpGetBody(rawURL string) ([]byte, error) { + return netutil.BoundedGet(CommandContext(), httpClient, rawURL, int64(maxProbeBodyBytes), validateProbeRedirect) } // runGit runs a git command in dir and returns its trimmed stdout. @@ -236,7 +465,11 @@ func httpGetBody(url string) ([]byte, error) { // can never redirect a bridge-cache operation onto the wrong repository — the // command always acts on the repo in dir. func runGit(dir string, args ...string) (string, error) { - cmd := exec.Command("git", args...) + // A library host may wire context.Background(), so git needs its own + // deadline: a hung fetch or clone must not block generation forever. + ctx, cancel := gitCommandContext() + defer cancel() + cmd := exec.CommandContext(ctx, "git", args...) //nolint:gosec // args passed separately; no shell interpretation cmd.Dir = dir cmd.Env = gitScrubbedEnv() out, err := cmd.Output() @@ -246,16 +479,28 @@ func runGit(dir string, args ...string) (string, error) { return strings.TrimSpace(string(out)), nil } -// gitScrubbedEnv returns the process environment without git-location variables. +// gitEnvironmentNames is an allowlist for git children. Git reads a large +// family of GIT_CONFIG_*/GIT_SSH_COMMAND/proxy variables that can redirect a +// cache operation onto another repository or another transport; none of them +// are needed to fetch a bridge. Only process basics survive. +var gitEnvironmentNames = map[string]struct{}{ + "HOME": {}, "USERPROFILE": {}, "HOMEDRIVE": {}, "HOMEPATH": {}, + "PATH": {}, "PATHEXT": {}, "SYSTEMROOT": {}, "COMSPEC": {}, + "TEMP": {}, "TMP": {}, "TMPDIR": {}, "APPDATA": {}, + "LOCALAPPDATA": {}, "PROGRAMDATA": {}, "LANG": {}, "LC_ALL": {}, + "LANGUAGE": {}, "TZ": {}, "SSL_CERT_FILE": {}, "SSL_CERT_DIR": {}, +} + +// gitScrubbedEnv returns a minimal environment for git children. It keeps the +// variables git needs to find its binary, HOME and the temp dir on Windows/CI, +// and drops everything else (notably all GIT_* overrides and proxies). func gitScrubbedEnv() []string { var env []string for _, kv := range os.Environ() { name, _, _ := strings.Cut(kv, "=") - switch name { - case "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY": - continue + if _, ok := gitEnvironmentNames[strings.ToUpper(name)]; ok { + env = append(env, kv) } - env = append(env, kv) } return env } diff --git a/internal/bridge/update_contract_test.go b/internal/bridge/update_contract_test.go index 09b5761..93916fe 100644 --- a/internal/bridge/update_contract_test.go +++ b/internal/bridge/update_contract_test.go @@ -4,34 +4,60 @@ import ( "fmt" "strings" "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" ) +// TestCoreContractVersionMatchesSpecmeta pins the single source of truth: the +// bridge gate must move with specmeta.ContractVersion after a contract bump. +func TestCoreContractVersionMatchesSpecmeta(t *testing.T) { + if CoreContractVersion != specmeta.ContractVersion { + t.Errorf("CoreContractVersion = %d, specmeta.ContractVersion = %d", CoreContractVersion, specmeta.ContractVersion) + } + if err := CheckContractVersion(specmeta.ContractVersion); err != nil { + t.Errorf("contract equal to specmeta version must be accepted: %v", err) + } + if err := CheckContractVersion(specmeta.ContractVersion + 1); err == nil { + t.Error("contract newer than specmeta version must be rejected") + } +} + func TestParseBridgeContractVersion(t *testing.T) { cases := []struct { - name string - in string - want int + name string + in string + want int + wantErr bool }{ - {"absent defaults to 1", "name: b\n", 1}, - {"explicit 1", "name: b\ncontract_version: 1\n", 1}, - {"explicit 2", "name: b\ncontract_version: 2\n", 2}, - {"garbage defaults to 1", "::: not yaml", 1}, + {name: "absent defaults to core", in: "name: b\n", want: CoreContractVersion}, + {name: "explicit 1", in: "name: b\ncontract_version: 1\n", want: 1}, + {name: "explicit 2", in: "name: b\ncontract_version: 2\n", want: 2}, + {name: "malformed yaml is an error", in: "contract_version: [1, 2\n", wantErr: true}, + {name: "scalar manifest is an error", in: "just a string\n", wantErr: true}, + {name: "non integer is an error", in: "contract_version: two\n", wantErr: true}, + {name: "negative is an error", in: "contract_version: -1\n", wantErr: true}, } for _, c := range cases { - if got := parseBridgeContractVersion([]byte(c.in)); got != c.want { - t.Errorf("%s: parseBridgeContractVersion = %d, want %d", c.name, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + got, _, err := ParseContractVersion([]byte(c.in)) + if (err != nil) != c.wantErr { + t.Fatalf("ParseContractVersion error = %v, wantErr %v", err, c.wantErr) + } + if err == nil && got != c.want { + t.Errorf("ParseContractVersion = %d, want %d", got, c.want) + } + }) } } func TestShouldApplyContract(t *testing.T) { - if err := shouldApplyContract(1); err != nil { + if err := CheckContractVersion(1); err != nil { t.Errorf("contract 1 should be accepted, got %v", err) } - if err := shouldApplyContract(CoreContractVersion); err != nil { + if err := CheckContractVersion(CoreContractVersion); err != nil { t.Errorf("contract equal to core should be accepted, got %v", err) } - if err := shouldApplyContract(CoreContractVersion + 1); err == nil { + if err := CheckContractVersion(CoreContractVersion + 1); err == nil { t.Error("newer contract must be rejected") } else if !strings.Contains(err.Error(), "contract") { t.Errorf("error should mention the contract, got: %v", err) @@ -46,19 +72,81 @@ func TestRemoteContractVersion(t *testing.T) { if !strings.Contains(url, "/bridge.yaml") { return nil, fmt.Errorf("unexpected url %s", url) } - if strings.Contains(url, "unsupported") { - return []byte("name: b\ncontract_version: 2\n"), nil + switch { + case strings.Contains(url, "unsupported"): + return []byte("name: b\ncontract_version: 3\n"), nil + case strings.Contains(url, "malformed"): + return []byte("contract_version: [1, 2\n"), nil + default: + return []byte("name: b\n"), nil } - return []byte("name: b\n"), nil } ok := RegistryEntry{GitHub: "DomainCraft/domaincraft-bridge-csharp-core"} - if v, err := remoteContractVersion(ok, "main"); err != nil || v != 1 { - t.Errorf("supported contract = %d, %v; want 1", v, err) + if v, err := remoteContractVersion(ok, "main"); err != nil || v != CoreContractVersion { + t.Errorf("supported contract = %d, %v; want %d", v, err, CoreContractVersion) } bad := RegistryEntry{GitHub: "DomainCraft/unsupported"} - if v, err := remoteContractVersion(bad, "main"); err != nil || v != 2 { - t.Errorf("unsupported contract = %d, %v; want 2", v, err) + if v, err := remoteContractVersion(bad, "main"); err != nil || v != 3 { + t.Errorf("unsupported contract = %d, %v; want 3", v, err) + } + + malformed := RegistryEntry{GitHub: "DomainCraft/malformed"} + if _, err := remoteContractVersion(malformed, "main"); err == nil { + t.Error("malformed remote manifest must be an error, not contract v1") + } + + probeFailure := RegistryEntry{GitHub: "DomainCraft/offline"} + origGet := httpGetBodyFn + httpGetBodyFn = func(string) ([]byte, error) { return nil, fmt.Errorf("offline") } + if _, err := remoteContractVersion(probeFailure, "main"); err == nil { + t.Error("failed probe must be an error") + } + httpGetBodyFn = origGet +} + +// TestRemoteContractVersionRejectsUnsafeRef pins the URL boundary: the ref is +// interpolated into a raw-content URL before git sees it, so validation must +// happen first and no HTTP probe may be made for a hostile value. +func TestRemoteContractVersionRejectsUnsafeRef(t *testing.T) { + orig := httpGetBodyFn + defer func() { httpGetBodyFn = orig }() + + calls := 0 + httpGetBodyFn = func(string) ([]byte, error) { + calls++ + return nil, fmt.Errorf("must not probe an unsafe ref") + } + entry := RegistryEntry{GitHub: "owner/repo"} + for _, ref := range []string{"../main", "--upload-pack=sh", "main@{0}", "release%2fmain"} { + if _, err := remoteContractVersion(entry, ref); err == nil { + t.Errorf("ref %q must be rejected before a URL is built", ref) + } + } + if calls != 0 { + t.Errorf("unsafe refs caused %d HTTP probes, want 0", calls) + } +} + +// TestGithubAPIHeadRejectsUnsafeDefaultBranch checks that a remote-controlled +// default_branch cannot redirect the commit probe to another API path. +func TestGithubAPIHeadRejectsUnsafeDefaultBranch(t *testing.T) { + orig := httpGetBodyFn + defer func() { httpGetBodyFn = orig }() + + calls := 0 + httpGetBodyFn = func(url string) ([]byte, error) { + calls++ + if strings.Contains(url, "/commits/") { + return nil, fmt.Errorf("commit probe must not run for an unsafe branch: %s", url) + } + return []byte(`{"default_branch":"../evil"}`), nil + } + if _, _, err := githubAPIHead(RegistryEntry{GitHub: "owner/repo"}); err == nil { + t.Error("unsafe default branch must be rejected") + } + if calls != 1 { + t.Errorf("HTTP calls = %d, want 1 (repo probe only)", calls) } } diff --git a/internal/bridge/update_metadata_test.go b/internal/bridge/update_metadata_test.go new file mode 100644 index 0000000..4034b9b --- /dev/null +++ b/internal/bridge/update_metadata_test.go @@ -0,0 +1,31 @@ +package bridge + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +// A corrupt metadata file used to be ignored: the pin was lost and the update +// silently moved a pinned checkout to the default branch. +func TestApplyUpdateRejectsCorruptMetadata(t *testing.T) { + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + entry := cacheEntry("corrupt-meta", "DomainCraft/test") + dir := CachePath(entry) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, MetaFileName), []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + + _, err := ApplyUpdate(entry, &Update{}) + if err == nil || !strings.Contains(err.Error(), "metadata") { + t.Fatalf("ApplyUpdate = %v, want a metadata error", err) + } +} diff --git a/internal/bridge/update_pin_test.go b/internal/bridge/update_pin_test.go new file mode 100644 index 0000000..81a7fff --- /dev/null +++ b/internal/bridge/update_pin_test.go @@ -0,0 +1,113 @@ +package bridge + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +// shallowPinnedCache builds the state ApplyUpdate leaves after its fallback +// re-clone: a --depth 1 checkout of the default branch (v2.0.0), with a pin +// recorded in metadata that the shallow checkout does not necessarily contain. +func shallowPinnedCache(t *testing.T, pin string) (RegistryEntry, string) { + t.Helper() + if !gitAvailable() { + t.Skip("git not installed") + } + root := t.TempDir() + appdir.SetBaseForTesting(root) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + remote, src := newRemoteWithBridge(t, root, "main", "") + testGit(t, src, "tag", "v1.0.0") + // file:// makes the later shallow fetch use the real transport instead of + // a local-path clone, which ignores --depth. + remoteURL := "file:///" + filepath.ToSlash(remote) + testGit(t, src, "remote", "set-url", "origin", remoteURL) + testGit(t, src, "push", "-q", "-u", "origin", "main") + testGit(t, src, "push", "-q", "origin", "v1.0.0") + + writeBridgeYAML(t, src, "2.0.0") + testGit(t, src, "add", ".") + testGit(t, src, "commit", "-q", "-m", "bump version") + testGit(t, src, "push", "-q", "origin", "main") + + entry := cacheEntry("pin-recovery", "owner/pin-recovery") + dir := CachePath(entry) + if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { + t.Fatal(err) + } + testGit(t, root, "clone", "-q", "--depth", "1", remoteURL, dir) + if err := WriteMeta(entry, &CacheMeta{ + ID: entry.ID, Source: entry.GitHub, Version: "2.0.0", + Commit: testGit(t, dir, "rev-parse", "HEAD"), Branch: "main", Pin: pin, + ClonedAt: time.Now(), LastCheckedAt: time.Now(), + }); err != nil { + t.Fatal(err) + } + return entry, dir +} + +// F23: a shallow fallback clone does not carry an arbitrary pinned ref. The +// update may fail, but it must not leave metadata claiming a pin the checkout +// does not hold — that would disable every later freshness check. +func TestFinishUpdateDropsPinWhenRefCannotBeFetched(t *testing.T) { + entry, dir := shallowPinnedCache(t, "missing-pin") + + version, err := finishUpdate(entry, "main", "missing-pin") + if err == nil || !strings.Contains(err.Error(), "restore pinned ref") { + t.Fatalf("finishUpdate error = %v, want a failed pin restore", err) + } + if version != "" { + t.Fatalf("finishUpdate version = %q, want empty on failure", version) + } + meta, err := ReadMeta(entry) + if err != nil || meta == nil { + t.Fatalf("ReadMeta: %+v, %v", meta, err) + } + if meta.Pin != "" { + t.Fatalf("stale pin %q kept after a failed restore", meta.Pin) + } + if meta.Commit != testGit(t, dir, "rev-parse", "HEAD") { + t.Fatalf("metadata commit %q does not match the checkout", meta.Commit) + } + data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) + if err != nil || !strings.Contains(string(data), `version: "2.0.0"`) { + t.Fatalf("branch checkout lost after failed pin restore: %q, %v", data, err) + } +} + +// F23: when the ref exists upstream, fetch it explicitly and land on the pin +// instead of silently serving the default branch. +func TestFinishUpdateFetchesMissingPinnedRef(t *testing.T) { + entry, dir := shallowPinnedCache(t, "v1.0.0") + if tags := testGit(t, dir, "tag", "-l"); strings.Contains(tags, "v1.0.0") { + t.Skip("this git version included the tag in a shallow clone; nothing to recover") + } + + version, err := finishUpdate(entry, "main", "v1.0.0") + if err != nil { + t.Fatalf("finishUpdate: %v", err) + } + if version != "1.0.0" { + t.Fatalf("version = %q, want the pinned 1.0.0", version) + } + meta, err := ReadMeta(entry) + if err != nil || meta == nil { + t.Fatalf("ReadMeta: %+v, %v", meta, err) + } + if meta.Pin != "v1.0.0" { + t.Fatalf("pin = %q, want v1.0.0", meta.Pin) + } + if meta.Commit != testGit(t, dir, "rev-parse", "HEAD") { + t.Fatalf("metadata commit %q does not match the pinned checkout", meta.Commit) + } + data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) + if err != nil || !strings.Contains(string(data), `version: "1.0.0"`) { + t.Fatalf("checkout is not on the pinned version: %q, %v", data, err) + } +} diff --git a/internal/bridge/update_safety_test.go b/internal/bridge/update_safety_test.go new file mode 100644 index 0000000..5ddecfe --- /dev/null +++ b/internal/bridge/update_safety_test.go @@ -0,0 +1,135 @@ +package bridge + +import ( + "os" + "path/filepath" + "testing" +) + +// makeMonorepoBridge creates /bridges//bridge.yaml and marks root as +// the DomainCraft monorepo with a go.mod, matching the real checkout layout. +func makeMonorepoBridge(t *testing.T, root, rel string) string { + t.Helper() + dir := filepath.Join(root, "bridges", filepath.FromSlash(rel)) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte("name: csharp-core\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "go.mod"), []byte("module github.com/DomainCraft/DomainCraft\n\ngo 1.27\n"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +// TestIsOfficialBundled distinguishes bundled official bridges (which may +// auto-run declared migrations) from community/local bridges (which must not). +func TestIsOfficialBundled(t *testing.T) { + root := t.TempDir() + official := makeMonorepoBridge(t, root, "csharp/core") + if !IsOfficialBundled(official) { + t.Errorf("IsOfficialBundled(%s) = false, want true", official) + } + + // A custom/local path must not count as bundled official. + custom := filepath.Join(root, "my-bridge") + if err := os.MkdirAll(custom, 0o755); err != nil { + t.Fatal(err) + } + if IsOfficialBundled(custom) { + t.Errorf("IsOfficialBundled(%s) = true, want false", custom) + } + + // A registry cache path (~/.domaincraft/bridges/) must not count either. + cache := filepath.Join(root, "csharp-core") + if err := os.MkdirAll(cache, 0o755); err != nil { + t.Fatal(err) + } + if IsOfficialBundled(cache) { + t.Errorf("IsOfficialBundled(%s) = true, want false", cache) + } + + // Regression: `mybridges` ends with `bridges` but is not a path component + // boundary. The old HasSuffix check treated it as bundled-official and + // bypassed the community-bridge migration consent gate. + lookalike := filepath.Join(root, "mybridges", "csharp", "core") + if err := os.MkdirAll(lookalike, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(lookalike, "bridge.yaml"), []byte("name: evil\n"), 0o644); err != nil { + t.Fatal(err) + } + if IsOfficialBundled(lookalike) { + t.Errorf("IsOfficialBundled(%s) = true for a lookalike path, want false", lookalike) + } +} + +// TestMonorepoRelPathRejectsLookalikes pins the three checks behind the +// official-bundled decision: component boundary, embedded membership and the +// real monorepo root. +func TestMonorepoRelPathRejectsLookalikes(t *testing.T) { + root := t.TempDir() + realBridge := makeMonorepoBridge(t, root, "csharp/core") + + other := t.TempDir() + noMarker := filepath.Join(other, "bridges", "csharp", "core") + if err := os.MkdirAll(noMarker, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(noMarker, "bridge.yaml"), []byte("name: csharp-core\n"), 0o644); err != nil { + t.Fatal(err) + } + lookalike := filepath.Join(other, "mybridges", "csharp", "core") + if err := os.MkdirAll(lookalike, 0o755); err != nil { + t.Fatal(err) + } + unbundled := makeMonorepoBridge(t, t.TempDir(), "custom/bridge") + + tests := []struct { + name string + dir string + path string + want string + }{ + {name: "real monorepo bridge", dir: realBridge, path: "csharp/core", want: "bridges/csharp/core"}, + {name: "lookalike component", dir: lookalike, path: "csharp/core"}, + {name: "no monorepo root", dir: noMarker, path: "csharp/core"}, + {name: "not embedded in binary", dir: unbundled, path: "custom/bridge"}, + {name: "traversal in entry path", dir: realBridge, path: "../../csharp/core"}, + {name: "empty entry path", dir: realBridge, path: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := MonorepoRelPath(tt.dir, tt.path) + if got != tt.want { + t.Errorf("MonorepoRelPath(%q, %q) = %q, want %q", tt.dir, tt.path, got, tt.want) + } + }) + } +} + +// TestSplitPinRef covers the community-bridge pin syntax `owner/repo@ref`. +func TestSplitPinRef(t *testing.T) { + cases := []struct { + name string + in string + repo string + ref string + }{ + {"plain", "owner/repo", "owner/repo", ""}, + {"registry id stays unpinned", "csharp-rest", "csharp-rest", ""}, + {"version_pin", "owner/repo@v1.2.3", "owner/repo", "v1.2.3"}, + {"commit_pin", "owner/repo@9f8e7d6c5b4a3210", "owner/repo", "9f8e7d6c5b4a3210"}, + {"branch_pin", "owner/repo@feature/branch", "owner/repo", "feature/branch"}, + {"last_at_wins", "owner/repo@tag@x", "owner/repo@tag", "x"}, // last @ wins + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + repo, ref := splitPinRef(c.in) + if repo != c.repo || ref != c.ref { + t.Errorf("splitPinRef(%q) = (%q, %q), want (%q, %q)", c.in, repo, ref, c.repo, c.ref) + } + }) + } +} diff --git a/internal/bridge/update_test.go b/internal/bridge/update_test.go index e423705..9106ca9 100644 --- a/internal/bridge/update_test.go +++ b/internal/bridge/update_test.go @@ -2,98 +2,12 @@ package bridge import ( "os" - "os/exec" - "path/filepath" - "strings" "testing" "time" "github.com/DomainCraft/DomainCraft/internal/appdir" ) -// gitAvailable reports whether git is installed (bridge update handling needs it). -func gitAvailable() bool { - _, err := exec.LookPath("git") - return err == nil -} - -// testGit runs git in dir and returns combined output, failing the test on error. -func testGit(t *testing.T, dir string, args ...string) string { - t.Helper() - cmd := exec.Command("git", args...) - cmd.Dir = dir - cmd.Env = append(gitScrubbedEnv(), "GIT_AUTHOR_NAME=domaincraft-test", "GIT_AUTHOR_EMAIL=test@example.com") - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("git %s in %s: %v\n%s", strings.Join(args, " "), dir, err, out) - } - return strings.TrimSpace(string(out)) -} - -// makeBridgeRepo creates a non-bare git repo at dir with a bridge.yaml committed -// on the given branch. Returns the repo path. -func makeBridgeRepo(t *testing.T, dir, branch string) { - t.Helper() - testGit(t, dir, "init", "-q", "-b", branch) - testGit(t, dir, "config", "user.email", "test@domaincraft.dev") - testGit(t, dir, "config", "user.name", "DomainCraft Test") - writeBridgeYAML(t, dir, "1.0.0") - testGit(t, dir, "add", ".") - testGit(t, dir, "commit", "-q", "-m", "init") -} - -// writeBridgeYAML writes a minimal bridge.yaml with the given version. -func writeBridgeYAML(t *testing.T, dir, version string) { - t.Helper() - body := "name: test-bridge\nversion: \"" + version + "\"\n" - if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(body), 0o644); err != nil { - t.Fatalf("write bridge.yaml: %v", err) - } -} - -// cacheEntry returns a RegistryEntry whose cache path is under the test cache root. -func cacheEntry(id, source string) RegistryEntry { - return RegistryEntry{ID: id, GitHub: source} -} - -func TestMetaRoundTrip(t *testing.T) { - root := t.TempDir() - appdir.SetBaseForTesting(root) - defer appdir.SetBaseForTesting("") - - entry := cacheEntry("test-bridge", "owner/bridge") - - // Nothing cached yet -> no meta, not cached. - if _, err := ReadMeta(entry); err != nil { - t.Fatalf("ReadMeta on missing meta: %v", err) - } - - now := time.Now() - meta := &CacheMeta{ - ID: entry.ID, - Source: entry.GitHub, - Version: "1.0.0", - Commit: "abc123", - Branch: "main", - ClonedAt: now, - LastCheckedAt: now, - } - if err := WriteMeta(entry, meta); err != nil { - t.Fatalf("WriteMeta: %v", err) - } - - got, err := ReadMeta(entry) - if err != nil { - t.Fatalf("ReadMeta: %v", err) - } - if got.Version != "1.0.0" || got.Commit != "abc123" || got.Source != "owner/bridge" { - t.Fatalf("round-trip mismatch: %+v", got) - } - if !got.ClonedAt.Equal(now) { - t.Fatalf("ClonedAt not preserved: got %v want %v", got.ClonedAt, now) - } -} - // TestCheckAndApplyUpdate exercises the full freshness flow: GitHub API // detection (faked offline) plus a real git fetch+reset apply against a local // bare remote, so it doesn't depend on the network. @@ -105,17 +19,8 @@ func TestCheckAndApplyUpdate(t *testing.T) { appdir.SetBaseForTesting(root) defer appdir.SetBaseForTesting("") - // Bare remote acting as the bridge's origin. - remote := filepath.Join(root, "remote.git") - testGit(t, root, "init", "--bare", "-b", "main", "remote.git") - testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") - - // Working repo that we push to the remote. - src := filepath.Join(root, "src") - os.MkdirAll(src, 0o755) - makeBridgeRepo(t, src, "main") - testGit(t, src, "remote", "add", "origin", remote) - testGit(t, src, "push", "-q", "-u", "origin", "main") + // Bare remote acting as the bridge's origin, with a working source repo. + remote, src := newRemoteWithBridge(t, root, "main", "") // "Download" the bridge into our cache just like EnsureBridge would. entry := RegistryEntry{ID: "test-bridge", GitHub: "owner/test-bridge"} @@ -126,18 +31,7 @@ func TestCheckAndApplyUpdate(t *testing.T) { } // Fake the GitHub API: report the current head of the local bare remote. - headCommit := func() string { return testGit(t, remote, "rev-parse", "HEAD") } - oldHTTP := httpGetBodyFn - httpGetBodyFn = func(url string) ([]byte, error) { - switch { - case strings.Contains(url, "/commits/main"): - return []byte(`{"sha":"` + headCommit() + `"}`), nil - case strings.Contains(url, "/repos/owner/test-bridge"): - return []byte(`{"default_branch":"main"}`), nil - } - return nil, os.ErrNotExist - } - defer func() { httpGetBodyFn = oldHTTP }() + stub := stubGitHubAPI(t, testGit(t, remote, "rev-parse", "HEAD"), "") // No update yet: local checkout already at the remote tip. upd, err := CheckForUpdate(entry, 0) @@ -168,6 +62,7 @@ func TestCheckAndApplyUpdate(t *testing.T) { testGit(t, src, "add", ".") testGit(t, src, "commit", "-q", "-m", "bump version") testGit(t, src, "push", "-q", "origin", "main") + stub.sha = testGit(t, remote, "rev-parse", "HEAD") // Now an update is detected. upd, err = CheckForUpdate(entry, 0) @@ -206,7 +101,9 @@ func TestEnsureMetaSynthesizesForLegacyCache(t *testing.T) { entry := RegistryEntry{ID: "legacy-bridge", GitHub: "owner/legacy-bridge"} cacheDir := CachePath(entry) - os.MkdirAll(cacheDir, 0o755) + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + t.Fatal(err) + } makeBridgeRepo(t, cacheDir, "main") // No metadata file exists (legacy cache), but the checkout is usable. @@ -225,17 +122,20 @@ func TestEnsureMetaSynthesizesForLegacyCache(t *testing.T) { } } -// TestCheckForUpdateViaGitHubAPI verifies update detection through the GitHub -// REST API for a cached bridge that has no usable git checkout (e.g. a bridge -// directory copied without its .git). -func TestCheckForUpdateViaGitHubAPI(t *testing.T) { +// TestCheckForUpdateSkippedWithoutGitCheckout pins the F22 rule: a cache whose +// HEAD cannot be read has no trustworthy local commit. Even when the GitHub API +// reports a different SHA, that stale metadata commit must not produce a false +// "update available" (the same outcome as an offline probe). +func TestCheckForUpdateSkippedWithoutGitCheckout(t *testing.T) { root := t.TempDir() appdir.SetBaseForTesting(root) defer appdir.SetBaseForTesting("") entry := RegistryEntry{ID: "github-bridge", GitHub: "owner/github-bridge"} cacheDir := CachePath(entry) - os.MkdirAll(cacheDir, 0o755) + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + t.Fatal(err) + } writeBridgeYAML(t, cacheDir, "1.0.0") // No .git in the checkout, but metadata records the local commit. @@ -253,29 +153,23 @@ func TestCheckForUpdateViaGitHubAPI(t *testing.T) { } // Fake the GitHub API responses. - oldHTTP := httpGetBodyFn - httpGetBodyFn = func(url string) ([]byte, error) { - switch { - case strings.Contains(url, "/commits/main"): - return []byte(`{"sha":"new-remote-commit"}`), nil - case strings.Contains(url, "/repos/owner/github-bridge"): - return []byte(`{"default_branch":"main"}`), nil - } - return nil, os.ErrNotExist - } - defer func() { httpGetBodyFn = oldHTTP }() + stubGitHubAPI(t, "new-remote-commit", "") upd, err := CheckForUpdate(entry, 0) if err != nil { t.Fatalf("CheckForUpdate: %v", err) } - if upd == nil { - t.Fatal("expected an update to be detected via the GitHub API") + if upd != nil { + t.Fatalf("a cache without a readable HEAD must not offer an update: %+v", upd) + } + after, err := ReadMeta(entry) + if err != nil { + t.Fatalf("ReadMeta: %v", err) } - if upd.RemoteCommit != "new-remote-commit" || upd.RemoteBranch != "main" { - t.Fatalf("unexpected update info: %+v", upd) + if after.Commit != "old-local-commit" { + t.Fatalf("stale commit was overwritten despite git failing: %q", after.Commit) } - if upd.LocalVersion != "1.0.0" { - t.Fatalf("wrong local version: %q", upd.LocalVersion) + if after.LastCheckedAt.Equal(meta.LastCheckedAt) { + t.Fatal("CheckForUpdate stopped recording the probe attempt") } } diff --git a/internal/bridgechain/chain.go b/internal/bridgechain/chain.go new file mode 100644 index 0000000..b15b12f --- /dev/null +++ b/internal/bridgechain/chain.go @@ -0,0 +1,49 @@ +// Package bridgechain resolves a bridge's `extends` chain into local bridge +// directories. It lives outside cmd/domaincraft so both the CLI and the +// cross-process contract tests walk the exact same chain. +package bridgechain + +import ( + "fmt" + "path/filepath" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +// absPathFn is a seam for testing the failure path: a failed Abs must not +// silently leave a relative key in the cycle-detection set. +var absPathFn = filepath.Abs + +// Walk resolves ref relative to fromDir and follows `extends` to the deepest +// base. It returns absolute paths top-first: the resolved bridge first, then +// its bases. Absolute paths make cycle detection path-based, not textual. +func Walk(ref, fromDir string, resolver *bridge.Resolver, log *logger.Logger) ([]string, error) { + var chain []string + visited := make(map[string]bool) + for ref != "" { + path, err := bridge.ResolveExtendsRef(ref, fromDir, resolver) + if err != nil { + return nil, fmt.Errorf("resolve bridge `extends: %s`: %w", ref, err) + } + abs, err := absPathFn(path) + if err != nil { + return nil, fmt.Errorf("resolve absolute bridge path %q: %w", path, err) + } + path = abs + key := bridge.PathKey(path) + if visited[key] { + return nil, fmt.Errorf("bridge `extends` cycle detected at %q", ref) + } + visited[key] = true + chain = append(chain, path) + + base, err := renderer.New(path, log) + if err != nil { + return nil, fmt.Errorf("load bridge %s: %w", path, err) + } + ref, fromDir = base.Extends(), path + } + return chain, nil +} diff --git a/internal/bridgechain/chain_test.go b/internal/bridgechain/chain_test.go new file mode 100644 index 0000000..656d9fa --- /dev/null +++ b/internal/bridgechain/chain_test.go @@ -0,0 +1,115 @@ +package bridgechain + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + +func writeBridge(t *testing.T, dir, extends string) string { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir %s: %v", dir, err) + } + content := "name: " + filepath.Base(dir) + "\n" + if extends != "" { + content += "extends: " + filepath.ToSlash(extends) + "\n" + } + path := filepath.Join(dir, "bridge.yaml") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } + return dir +} + +func TestWalkResolvesExtendsChainTopFirst(t *testing.T) { + t.Parallel() + root := t.TempDir() + base := writeBridge(t, filepath.Join(root, "base"), "") + mid := writeBridge(t, filepath.Join(root, "mid"), base) + top := writeBridge(t, filepath.Join(root, "top"), mid) + + chain, err := Walk(top, top, bridge.NewResolver(bridge.Default()), nil) + if err != nil { + t.Fatalf("Walk: %v", err) + } + want := []string{top, mid, base} + if len(chain) != len(want) { + t.Fatalf("chain = %v, want %v", chain, want) + } + for i := range want { + if chain[i] != want[i] { + t.Errorf("chain[%d] = %q, want %q", i, chain[i], want[i]) + } + if !filepath.IsAbs(chain[i]) { + t.Errorf("chain[%d] = %q, want an absolute path", i, chain[i]) + } + } +} + +func TestWalkDetectsCycle(t *testing.T) { + t.Parallel() + root := t.TempDir() + a := writeBridge(t, filepath.Join(root, "a"), "") + b := writeBridge(t, filepath.Join(root, "b"), a) + writeBridge(t, a, b) // a → b → a + + _, err := Walk(a, a, bridge.NewResolver(bridge.Default()), nil) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("err = %v, want a cycle error", err) + } +} + +func TestWalkDetectsCycleAcrossCaseVariants(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("case-insensitive filesystem check") + } + root := t.TempDir() + a := writeBridge(t, filepath.Join(root, "CycleA"), "") + b := writeBridge(t, filepath.Join(root, "cyclea"), a) + + if _, err := Walk(a, a, bridge.NewResolver(bridge.Default()), nil); err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("err = %v, want a cycle error across case variants (%q vs %q)", err, a, b) + } +} + +func TestWalkFailsWhenAbsFails(t *testing.T) { + root := t.TempDir() + base := writeBridge(t, filepath.Join(root, "base"), "") + + original := absPathFn + t.Cleanup(func() { absPathFn = original }) + absPathFn = func(string) (string, error) { return "", os.ErrPermission } + + _, err := Walk(base, root, bridge.NewResolver(bridge.Default()), nil) + if err == nil { + t.Fatal("Walk accepted a bridge path it could not make absolute") + } + if !strings.Contains(err.Error(), "resolve absolute bridge path") { + t.Errorf("err = %v, want the absolute-path failure context", err) + } +} + +func TestWalkMissingLocalPathIsHardError(t *testing.T) { + t.Parallel() + root := t.TempDir() + missing := filepath.Join(root, "missing-bridge") + + _, err := Walk(missing, root, bridge.NewResolver(bridge.Default()), nil) + if err == nil { + t.Fatal("expected an error for a missing local bridge") + } + if !strings.Contains(err.Error(), "no such local path") { + t.Errorf("err = %v, want the local-path failure text", err) + } + if strings.Contains(err.Error(), "clone") { + t.Errorf("err = %v, must not attempt a clone for a path-like ref", err) + } + if !strings.HasPrefix(err.Error(), "resolve bridge `extends:") { + t.Errorf("err = %v, want the chain resolution context", err) + } +} diff --git a/internal/contract/golden_test.go b/internal/contract/golden_test.go index 983c9dc..686d5e6 100644 --- a/internal/contract/golden_test.go +++ b/internal/contract/golden_test.go @@ -6,16 +6,22 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "encoding/json" "flag" "fmt" + "maps" "os" "path/filepath" - "sort" + "slices" "strings" "testing" + "time" + "github.com/DomainCraft/DomainCraft/internal/appdir" "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/bridgechain" "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/packages" "github.com/DomainCraft/DomainCraft/internal/parser" "github.com/DomainCraft/DomainCraft/internal/renderer" "github.com/DomainCraft/DomainCraft/internal/seed" @@ -24,22 +30,181 @@ import ( var updateGolden = flag.Bool("update", false, "regenerate golden files") -// leafBridges are the self-contained (no `extends`) official bridges that -// render without network package resolution — the hermetic subject of the -// golden test. Composed bridges (e.g. csharp-rest → … → csharp-core) need the -// extends-chain resolver, which lives in cmd/domaincraft; covering them here is -// a follow-up once that resolution moves into an importable package. -var leafBridges = []string{"csharp-core", "ts-core", "admin-alpine", "appwrite"} +// goldenBridges are the official bridges with committed golden manifests: the +// self-contained leaves plus the composed chains (csharp-rest → … → +// csharp-core, react-rest → … → ts-core). Composed chains are resolved by the +// same importable bridgechain.Walk the CLI uses and rendered base-first, so +// their manifests pin the real composition order. +var goldenBridges = []string{ + "csharp-core", + "ts-core", + "admin-alpine", + "appwrite", + "csharp-rest", + "react-rest", +} -func loadGoldenProject(t *testing.T) *ir.IRProject { - t.Helper() +// hermeticPackageVersion is the fixed version seeded into the per-bridge +// package cache in TestMain. Composed C# bridges declare NuGet packages; the +// seeded cache keeps rendering offline and makes the golden manifests stable +// even when upstream versions change. +const hermeticPackageVersion = "1.0.0" + +type goldenPackageCache struct { + Entries map[string]goldenPackageEntry `json:"entries"` +} + +type goldenPackageEntry struct { + Value string `json:"value"` + StoredAt time.Time `json:"stored_at"` +} + +// TestMain points per-user state at a temporary directory and seeds the +// package-version caches of every bundled bridge. No registry is contacted by +// any test in this package. +func TestMain(m *testing.M) { + root, err := os.MkdirTemp("", "domaincraft-golden-") + if err != nil { + fmt.Fprintln(os.Stderr, "golden temp dir:", err) + os.Exit(1) + } + appdir.SetBaseForTesting(root) + code := 0 + framework, err := goldenPlatform() + if err == nil { + err = seedPackageVersions(framework) + } + if err != nil { + fmt.Fprintln(os.Stderr, "seed package versions:", err) + code = 1 + } else { + code = m.Run() + } + appdir.SetBaseForTesting("") + _ = os.RemoveAll(root) + os.Exit(code) +} + +// goldenPlatform returns the target platform of the golden domain model. It is +// part of the package-version cache key and must match the framework the +// renderer sees. +// loadGoldenDomain is the single parse step for TestMain's platform probe and +// the per-test project loader, so they cannot drift apart. +func loadGoldenDomain() (*parser.ParsedSchema, error) { data, err := os.ReadFile(filepath.Join("testdata", "domain.yaml")) if err != nil { - t.Fatalf("read testdata/domain.yaml: %v", err) + return nil, err + } + return parser.ParseYAML(data) +} + +func goldenPlatform() (string, error) { + schema, err := loadGoldenDomain() + if err != nil { + return "", err } - schema, err := parser.ParseYAML(data) + proj, err := ir.Build(schema) if err != nil { - t.Fatalf("parse domain.yaml: %v", err) + return "", err + } + return proj.Platform, nil +} + +// cacheNamespace mirrors renderer.cacheNamespace: package versions are cached +// under the adapter bridge's name, not under its filesystem path. +func cacheNamespace(name string) string { + var b strings.Builder + for _, ch := range strings.ToLower(strings.TrimSpace(name)) { + if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' { + b.WriteRune(ch) + } + } + if b.Len() == 0 { + return "default" + } + return b.String() +} + +// seedPackageVersions writes one packages.json per bundled adapter so the +// renderer never needs a network lookup. The key layout is the one documented +// by internal/packages: registryURL + NUL + packageID + NUL + framework. +func seedPackageVersions(framework string) error { + resolver := bridge.NewResolver(bridge.Default()) + for _, entry := range bridge.Default().All() { + if entry.Path == "" || entry.Deprecated { + continue + } + dir, err := filepath.Abs(filepath.Join("..", "..", "bridges", filepath.FromSlash(entry.Path))) + if err != nil { + return err + } + chain, err := bridgechain.Walk(dir, dir, resolver, nil) + if err != nil { + return fmt.Errorf("resolve %s: %w", entry.ID, err) + } + // The renderer merges registry_packages from the whole chain under a + // single URL: the adapter's, otherwise the first one declared by a base. + packageIDs := make(map[string]struct{}) + registryURL := "" + manifests := make([]bridge.Manifest, 0, len(chain)) + for _, base := range chain { + m, err := bridge.LoadManifest(base) + if err != nil { + return err + } + manifests = append(manifests, m) + for _, packageID := range m.RegistryPackages { + packageIDs[packageID] = struct{}{} + } + if registryURL == "" && m.RegistryURL != "" { + registryURL = m.RegistryURL + } + } + adapter := manifests[0] + if len(packageIDs) == 0 { + continue + } + if registryURL == "" { + return fmt.Errorf("bridge %s declares packages but no registry_url", entry.ID) + } + // The renderer uses the project platform when set, otherwise the + // bridge-declared target_framework. Seed both keys so a golden run is + // hermetic even when the golden domain declares no platform. + frameworks := map[string]bool{framework: true} + for _, m := range manifests { + if m.TargetFramework != "" { + frameworks[m.TargetFramework] = true + } + } + packagesByKey := make(map[string]goldenPackageEntry, len(packageIDs)*len(frameworks)) + storedAt := time.Now() + for packageID := range packageIDs { + for fw := range frameworks { + key := registryURL + "\x00" + packageID + "\x00" + fw + packagesByKey[key] = goldenPackageEntry{Value: hermeticPackageVersion, StoredAt: storedAt} + } + } + cacheDir := appdir.CacheDir(cacheNamespace(adapter.Name)) + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + return err + } + data, err := json.Marshal(goldenPackageCache{Entries: packagesByKey}) + if err != nil { + return err + } + path := filepath.Join(cacheDir, packages.CacheFileName) + if err := os.WriteFile(path, data, 0o644); err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + } + return nil +} + +func loadGoldenProject(t *testing.T) *ir.Project { + t.Helper() + schema, err := loadGoldenDomain() + if err != nil { + t.Fatalf("load golden domain: %v", err) } for _, ve := range validator.New(schema).Validate() { if !ve.Warning { @@ -63,33 +228,16 @@ func bridgeDir(t *testing.T, id string) string { } // resolveChain resolves a bridge's full `extends` chain top-first (adapter -// first, deepest base last) using the importable resolver. It mirrors what the -// CLI does, so the contract tests exercise the same resolution path. +// first, deepest base last) through the same importable walker the CLI uses. func resolveChain(t *testing.T, entryDir string) []string { t.Helper() - resolver := bridge.NewResolver(bridge.Default()) - chain := []string{entryDir} - seen := map[string]bool{entryDir: true} - cur := entryDir - for { - r, err := renderer.New(cur, nil) - if err != nil { - t.Fatalf("renderer.New(%s): %v", cur, err) - } - ext := r.Extends() - if ext == "" { - break - } - next, err := bridge.ResolveExtendsRef(ext, cur, resolver) - if err != nil { - t.Fatalf("resolve extends %q from %s: %v", ext, cur, err) - } - if seen[next] { - t.Fatalf("extends cycle detected at %q", next) - } - seen[next] = true - chain = append(chain, next) - cur = next + abs, err := filepath.Abs(entryDir) + if err != nil { + t.Fatalf("abs(%s): %v", entryDir, err) + } + chain, err := bridgechain.Walk(abs, abs, bridge.NewResolver(bridge.Default()), nil) + if err != nil { + t.Fatalf("bridgechain.Walk(%s): %v", abs, err) } return chain } @@ -97,7 +245,7 @@ func resolveChain(t *testing.T, entryDir string) []string { // renderChain renders proj through a resolved bridge chain (top-first) and // returns a path→sha256 map of the produced files (relative to the output dir, // forward slashes). -func renderChain(t *testing.T, chain []string, proj *ir.IRProject) map[string]string { +func renderChain(t *testing.T, chain []string, proj *ir.Project) map[string]string { t.Helper() out := t.TempDir() r, err := renderer.New(chain[0], nil) @@ -105,8 +253,12 @@ func renderChain(t *testing.T, chain []string, proj *ir.IRProject) map[string]st t.Fatalf("renderer.New(%s): %v", chain[0], err) } if len(chain) > 1 { - if err := r.AttachBases(chain[1:]); err != nil { - t.Fatalf("AttachBases(%v): %v", chain[1:], err) + // Walk returns top-first; AttachBases wants the outermost base first, + // exactly as the CLI's resolveBaseChain does. + bases := slices.Clone(chain[1:]) + slices.Reverse(bases) + if err := r.AttachBases(bases); err != nil { + t.Fatalf("AttachBases(%v): %v", bases, err) } } r.SetSeedData(seed.Normalize(proj)) @@ -141,11 +293,7 @@ func renderChain(t *testing.T, chain []string, proj *ir.IRProject) map[string]st } func manifestLines(m map[string]string) []string { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) + keys := slices.Sorted(maps.Keys(m)) lines := make([]string, 0, len(keys)) for _, k := range keys { lines = append(lines, fmt.Sprintf("%s\t%s", k, m[k])) @@ -153,14 +301,16 @@ func manifestLines(m map[string]string) []string { return lines } -// TestGoldenLeafBridges asserts that each hermetic leaf bridge produces -// byte-identical output to a committed golden manifest. Regenerate changed -// output with `go test ./internal/contract -update`. +// TestGoldenLeafBridges asserts that every hermetic bridge — leaves and +// composed chains alike — produces byte-identical output to a committed golden +// manifest. Regenerate changed output with `go test ./internal/contract -update`. func TestGoldenLeafBridges(t *testing.T) { + t.Parallel() proj := loadGoldenProject(t) - for _, id := range leafBridges { + for _, id := range goldenBridges { t.Run(id, func(t *testing.T) { - got := strings.Join(manifestLines(renderChain(t, []string{bridgeDir(t, id)}, proj)), "\n") + t.Parallel() + got := strings.Join(manifestLines(renderChain(t, resolveChain(t, bridgeDir(t, id)), proj)), "\n") goldenPath := filepath.Join("testdata", id+".golden.txt") if *updateGolden { if err := os.WriteFile(goldenPath, []byte(got+"\n"), 0o644); err != nil { @@ -188,6 +338,7 @@ func TestGoldenLeafBridges(t *testing.T) { // bridges. The chain is resolved through the same importable resolver the CLI // uses. func TestRenderDeterministic(t *testing.T) { + t.Parallel() proj := loadGoldenProject(t) for _, entry := range bridge.Default().All() { if entry.Path == "" || entry.Deprecated { @@ -195,6 +346,7 @@ func TestRenderDeterministic(t *testing.T) { } id := entry.ID t.Run(id, func(t *testing.T) { + t.Parallel() chain := resolveChain(t, bridgeDir(t, id)) a := strings.Join(manifestLines(renderChain(t, chain, proj)), "\n") b := strings.Join(manifestLines(renderChain(t, chain, proj)), "\n") diff --git a/internal/contract/testdata/csharp-core.golden.txt b/internal/contract/testdata/csharp-core.golden.txt index ae9077c..bf82c67 100644 --- a/internal/contract/testdata/csharp-core.golden.txt +++ b/internal/contract/testdata/csharp-core.golden.txt @@ -1,4 +1,4 @@ -src/Application/Query/Query.g.cs e51cb7d485e32fec33fb6ce0ebed367336a98d20a2e5d0e024153645b51744ae +src/Application/Query/Query.g.cs 6a48a7da9b8ae77d0c4cf9225c3566b18ae2344440fab97aa30904bfd108be0a src/Domain/Entities/User.g.cs 1dcf056f46ec7f4a145a02b91f540bd361e667b52f6f28c852290b9a47900bb7 src/Domain/Shared/Enums.g.cs 99922a4cdf2c14d73a9dca3370634466b52a8399639b147476731ef2da972d5f src/Domain/Shared/PagedResult.g.cs 4839c8d6363a31dc2b5f6f6342b1c8eaf0162af7d29e9bda5661e53d06ade356 diff --git a/internal/contract/testdata/csharp-rest.golden.txt b/internal/contract/testdata/csharp-rest.golden.txt new file mode 100644 index 0000000..bd9ca3e --- /dev/null +++ b/internal/contract/testdata/csharp-rest.golden.txt @@ -0,0 +1,54 @@ +Dockerfile 1f930ffb25846048ff4fe732d13551bd77d9dfe2b13c6451ef3775f7bc925d74 +Golden.sln 8821b8ad33a8886cf3ae26e6b4a0a2f71f9ea7127482e96d92b1a8e707170735 +deploy/k8s/deployment.yaml 3bce43f60ad018cfd680c8e71d4bbc9e503e274995d5a2aff7eff81ca83d0a11 +deploy/k8s/ingress.yaml af90d21ab808ad22f4bb21a8ca1906ce161bbce709df8601b5afecfe2d36bfdb +deploy/k8s/service.yaml 797c3dfc5144d693c1d6aebb5df68202a41505c62e2338d56403b441d9ad9d0b +docker-compose.yml 7d96712a46018c10d0dd0c23e8246991e7777002ca1549a10b3c19eea7559fa8 +docs/Entities/User.md ec41d1bef42ff41c63ede338295970f9e9b9cb344835c271ba28a2bb2f4d8d82 +docs/ProjectSummary.md a5c81af3384b6ed5144df349dfc2db5d7312732b9cdbdc60d67ca42af061cd95 +src/Application/Application.csproj 8283308b145fdfce3d0f52b1b92bd4e097eafe913b7fd187cd9a9cb64b460f09 +src/Application/Caching/ICacheService.g.cs cd3d8c64f4125d4d310cd90a97468452d9d018e047823223491e88a5b222812f +src/Application/DependencyInjection.g.cs 3a771fa655927044b400b2b5b0a4fb876cb54f8f2012a54bcbb456dbc5403336 +src/Application/Email/IEmailService.g.cs 2424c0e2ec205f1ab4f035b17c3670b9e8dcd288238deeb65e79f082b31dbe8a +src/Application/Events/IEventPublisher.g.cs ed033b92dfe97a2e8cbc407c68e36a50b480597958c23b5fb49618e3d495c24f +src/Application/Generated/UserService.g.cs 7d239b5a78597541013371ea1d3ec50992fd6da189791564310bdf4d86853157 +src/Application/Query/Query.g.cs 6a48a7da9b8ae77d0c4cf9225c3566b18ae2344440fab97aa30904bfd108be0a +src/Application/Repositories/IRepository.g.cs 7c5b0695a00764cc63bf2568750ed9f083087d6ffa217325ca354dae0b2269d8 +src/Application/Repositories/IUserRepository.g.cs 7e16c15aa65b395e06bd412d5b16150576c8d93129f2c0f71064e9b1fd2caf0d +src/Application/Security/IOwnerResolver.g.cs 1fdab3616d197ca37f33df22b2a5816b96fa89fc9cf30704a08df381fc450dcd +src/Application/Security/IPermissionService.g.cs 68b13461bc000f7bb8a26d7dda3eb6573b914ede91cd3bed2b7147352ca38a60 +src/Application/Security/OwnerResolver.g.cs 98ed9a200eaa16e3040e2b338c13c38d62089f4a59a6ed8378d51846d97b135a +src/Application/Security/PermissionService.g.cs 7cb958dfa06d91e14d3feaf163cb6367437adfe4bb4087f435c71d1064dc07d0 +src/Application/Services/IUserService.g.cs e7ecfc178de1473d7b0c4f20d61546acc94d031efe5f5ca94b6bef356964edd5 +src/Application/Services/ServiceHooks.g.cs 341b198a5601954890723289aa38fc3456b54374336d5883ee19f5eac672537e +src/Application/Services/UserService.cs 2635b2772b6dfe3b723d0cb6c3516914e89d7a8147ca6e0e7aca04ec9e0b4de4 +src/Application/Storage/IStorageService.g.cs c8716c1056f3beaa4c3ebfba0c584da34f8c991b02f4576115910fbb502abda5 +src/Domain/Domain.csproj 40fb93b5509640ebac25a86e04c043b426e8c2563b4676d797c604357593ea4c +src/Domain/Entities/User.g.cs 1dcf056f46ec7f4a145a02b91f540bd361e667b52f6f28c852290b9a47900bb7 +src/Domain/MockData.g.cs be8b0b76fc5f294816a38b7ca891c2d12e4e46f814f791fc02d649f32e3ffab8 +src/Domain/Shared/Enums.g.cs 99922a4cdf2c14d73a9dca3370634466b52a8399639b147476731ef2da972d5f +src/Domain/Shared/PagedResult.g.cs 4839c8d6363a31dc2b5f6f6342b1c8eaf0162af7d29e9bda5661e53d06ade356 +src/Infrastructure/Caching/InMemoryCacheService.g.cs e585c7bb682d7b5e435f36237e3988230f8415a49c1c0bf064f3a56f16e440df +src/Infrastructure/DependencyInjection.g.cs 89942fe471b569ebf089c0d6fbb1aa55b9f5a4218dfc5ca32ced0e6039c12eff +src/Infrastructure/Email/InMemoryEmailService.g.cs 8933f478ab20831b81adeabe394eac68df37279882cd5107a5cab273fe2a674c +src/Infrastructure/Events/InMemoryEventPublisher.g.cs 72dff5948761e130ab7b19f0141992317f1026c565967539c96f13e3c6e2c1bf +src/Infrastructure/Infrastructure.csproj 41e1e4856f8706505f9589fb9a76bfddca0e07eb393a3588a34ab6a95bb6a7c8 +src/Infrastructure/Persistence/Configurations/UserConfiguration.g.cs 6ed93045e44b52e1005935203c2b53982ab2cf553c0a4af582ddcae642f8699b +src/Infrastructure/Persistence/DomainDbContext.g.cs c92816229ff5293513fa4ec79aad95b9f245f7cabf71736176d72c6c2611c220 +src/Infrastructure/Repositories/UserRepository.g.cs ab8b62c8417cefe1a4bb1929044bbc6e9e113f5aea562fc2723b229afe9b0206 +src/Infrastructure/Storage/LocalFileStorageService.g.cs 87da9498a92a30da0055a3606230f2e68ac8e12a683c4ae834c0c76960f344ee +src/WebApi/Controllers/UsersController.g.cs d1f82a93aadbd30404de1f533936e71e6782de377c840c688c9889a79e1e124a +src/WebApi/Extensions/ApplicationBuilderExtensions.g.cs ad57e25a4f02959facce32e4f7780dac4446d18d0d51fd32cf44140bb4a28304 +src/WebApi/Extensions/ServiceCollectionExtensions.g.cs db832245ef76a1c838e6e0fe7ff5be461ccf106a713f1091af5d0f33762f087e +src/WebApi/HealthChecks/HealthCheckResponseWriter.g.cs 957bc2933f56320080e824c33efacc5095f1ff656136f90822ce758a34d1bf1b +src/WebApi/Program.cs db357be34121c5a5c1536bd081c007e92e349db78abe5c0adf0608d8cb784ed4 +src/WebApi/WebApi.csproj 7b1118d44528a407b3be5027a1b0ca5f75b44bc536f1cd1c5fd82af81be27294 +src/WebApi/appsettings.Development.json 2f8b287f87c8d02cbc09443004e31b1ddc038c3dc4da49d6f63dcfbd92866990 +src/WebApi/appsettings.Production.json 35fe8bbf01443af04b3f077957504ff819749a5c1f0b52675c490a8d74198a86 +src/WebApi/appsettings.Staging.json c6917505823d49d98fb025581f33cbabf861f6c088cca9eb195b972ad7fb4960 +src/WebApi/appsettings.json 49a90b1f3507c07231ecc37cc57c75d3830e05abf4ea56e38a3f195528f88793 +tests/ApiTests.g.cs 3ad5a1a4a2587095d1e63e85140cac7989bd507cc7cdff384b2dbbe4761c0e00 +tests/AuthTests.g.cs d031a535cbd005bd12616803dd3668b715d143f75a59d16fee2c352496ef5bd2 +tests/EntityStateTests.g.cs cd849e93c84446f3a65a62730e4cb5be334c4710cc855831516e4b37e289f68d +tests/EntityTests.g.cs 7fc37e2c4243122cbce0337bb19f0854f7d396b4c364dae7f5c1bd3e1d8cd8b4 +tests/Golden.Tests.csproj ee1965fd25e49ab19b317d332928bb51cad8e05d059a485653db8e0fbf0cb325 diff --git a/internal/contract/testdata/react-rest.golden.txt b/internal/contract/testdata/react-rest.golden.txt new file mode 100644 index 0000000..0ce4731 --- /dev/null +++ b/internal/contract/testdata/react-rest.golden.txt @@ -0,0 +1,11 @@ +README.md 88f154f27fd725d87ea5ab77d9443d7005f346499bdc5bb88f5ac6279af1a83a +package.json dea6f4929a9d64e7b072f634f5cdb1b4022983fb8df4019721ca573e2ece8f41 +src/generated/api.ts 7bb843d0a739345a17ef8bc1318df7f997cfca94c06e78093346ee6f211eaa2b +src/generated/client.ts 763c42189f8c533ec4debddbe0e9138bf00013b42c58263c0a7a414ab99efb08 +src/generated/hooks.ts 5fc5b0dad069452cce174dae4f05a0ffaf63763edaa4c1aeefea3e30f9bb8770 +src/generated/permissions.ts b3f0c1a24281c5b168c86954e1a86c0e40c30b007de42decd30f6100652a13ed +src/generated/query.ts 8050e9b9e14e726cf45719c720e5cb905a2376a262cdd8cc3e61301d6f79adb8 +src/generated/schemas.ts b9b77ddeb850bd703b2185a21c4e4fdc8523c948f873b304a5249631a24f9e71 +src/generated/types.ts 1bc0a0c29c6588437c6bfd3ddd1f17e9754124e4a267b0ff0a9138e05f808266 +src/index.ts a655e0a07d4068ed9d986deba4f5fff29f60c647e105f412957ae429b1737b57 +tsconfig.json 35cf270240eb062c3d1e6b5050f7386877cf4dd0918e5375e6f01cd8e414f49a diff --git a/internal/contract/testdata/ts-core.golden.txt b/internal/contract/testdata/ts-core.golden.txt index bd54102..a6f250d 100644 --- a/internal/contract/testdata/ts-core.golden.txt +++ b/internal/contract/testdata/ts-core.golden.txt @@ -1,3 +1,3 @@ src/generated/permissions.ts b3f0c1a24281c5b168c86954e1a86c0e40c30b007de42decd30f6100652a13ed -src/generated/query.ts 7d89338d16ac4ae60e9679ad3dc94a3a2371fa81655887fa908e0d47d1dc05f8 +src/generated/query.ts 8050e9b9e14e726cf45719c720e5cb905a2376a262cdd8cc3e61301d6f79adb8 src/generated/types.ts 1bc0a0c29c6588437c6bfd3ddd1f17e9754124e4a267b0ff0a9138e05f808266 diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index 7b5e7a3..68cd4c9 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -4,42 +4,269 @@ package fsutil import ( + "crypto/rand" "encoding/json" + "errors" + "fmt" "os" "path/filepath" + "strings" ) -// AtomicWrite writes data to path via a temp file in the same directory -// followed by a rename, so a crash mid-write never leaves a truncated or -// corrupt file behind. The parent directory is created if missing. -func AtomicWrite(path string, data []byte) error { - dir := filepath.Dir(path) - if err := os.MkdirAll(dir, 0o755); err != nil { - return err +// AbsPathWithin checks that an absolute target stays under base and returns its +// relative form. It is the containment half shared by lexical path resolution +// and by callers that already hold an absolute path (bridge cache materialization). +func AbsPathWithin(base, target string) (string, error) { + absBase, err := filepath.Abs(base) + if err != nil { + return "", fmt.Errorf("resolve base %q: %w", base, err) + } + absTarget, err := filepath.Abs(target) + if err != nil { + return "", fmt.Errorf("resolve target %q: %w", target, err) + } + return relWithin(absBase, absTarget, target) +} + +// relWithin is the containment check for callers that already hold absolute +// paths. Keeping it separate avoids a second filepath.Abs on the same base. +func relWithin(absBase, absTarget, displayTarget string) (string, error) { + rel, err := filepath.Rel(absBase, absTarget) + if err != nil { + return "", fmt.Errorf("resolve path %q: %w", displayTarget, err) + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", fmt.Errorf("path %q escapes %q", displayTarget, absBase) + } + return rel, nil +} + +// LocalPathWithin resolves rel against base and rejects anything outside base. +// It returns the absolute target and its path relative to base. Callers add +// their own symlink policy: RefuseSymlinks for writes, EvalSymlinks for reads +// that must follow a symlinked root. +func LocalPathWithin(base, rel string) (string, string, error) { + local := filepath.FromSlash(rel) + if !filepath.IsLocal(local) { + return "", "", fmt.Errorf("path %q is not local", rel) + } + absBase, err := filepath.Abs(base) + if err != nil { + return "", "", fmt.Errorf("resolve base %q: %w", base, err) + } + absTarget := filepath.Join(absBase, local) + relative, err := relWithin(absBase, absTarget, absTarget) + if err != nil { + return "", "", err + } + return absTarget, relative, nil +} + +// OpenRootFor is the shared root transaction: containment, symlink refusal and +// one os.OpenRoot on the verified base. Every read or write goes through the +// returned root, so a component swapped for a symlink after the check cannot +// redirect it. The caller closes the root. Opening one root per operation keeps +// the cost at ~1.13x versus ~2.9x for routing every staging call through Root. +func OpenRootFor(base, absTarget string) (*os.Root, string, error) { + rel, err := AbsPathWithin(base, absTarget) + if err != nil { + return nil, "", err + } + if err := RefuseSymlinks(base, absTarget); err != nil { + return nil, "", err + } + root, err := os.OpenRoot(base) + if err != nil { + return nil, "", fmt.Errorf("open root %q: %w", base, err) + } + return root, rel, nil +} + +// RefuseSymlinks rejects an existing symlink at base or any component of target +// below it. Missing components are ignored; the caller creates them later and +// must re-check before committing a file. +func RefuseSymlinks(base, target string) error { + return RefuseSymlinksCached(base, target, nil) +} + +// RefuseSymlinksCached is RefuseSymlinks with an optional cache of directories +// already verified non-symlink. A cached directory skips only its Lstat; the +// final target component is always inspected, and so is every missing +// component (it may have appeared since the previous call). Callers must only +// share a cache between checks whose gap they re-check separately — passing +// nil gives the fully fresh walk used by RefuseSymlinks. +func RefuseSymlinksCached(base, target string, verified map[string]bool) error { + rel, err := filepath.Rel(base, target) + if err != nil { + return fmt.Errorf("resolve path %q: %w", target, err) + } + paths := []string{base} + cur := base + for comp := range strings.SplitSeq(rel, string(filepath.Separator)) { + if comp == "" || comp == "." { + continue + } + cur = filepath.Join(cur, comp) + paths = append(paths, cur) + } + cached := verified != nil + for i, path := range paths { + // The leaf is the file about to be written (or, when target == base, + // the base itself): a link planted there must never be cached away. + isLeaf := cached && i == len(paths)-1 + if cached && !isLeaf && verified[filepath.Clean(path)] { + continue + } + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return fmt.Errorf("inspect %q: %w", path, err) + } + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("refuse to write through symlink %q", path) + } + // Only existing, non-symlink directories enter the cache; missing + // components stay unchecked until they appear on a later call. + if cached && !isLeaf && info.IsDir() { + verified[filepath.Clean(path)] = true + } + } + return nil +} + +// atomicOps is the filesystem surface shared by AtomicWrite and +// AtomicWriteRoot. osAtomicOps routes through os.*, rootAtomicOps through one +// *os.Root, so the staging algorithm below exists only once. +type atomicOps interface { + mkdir(dir string) error + lstat(name string) (os.FileInfo, error) + createTemp(dir, name string) (*os.File, string, error) + rename(from, to string) error + remove(name string) error + // abort closes a file after a staging failure and shapes the returned + // error. os.* joins the close error, *os.Root drops it; keeping the policy + // in the backend preserves both callers' error contracts. + abort(f *os.File, err error) error +} + +type osAtomicOps struct{} + +func (osAtomicOps) mkdir(dir string) error { + return os.MkdirAll(dir, 0o755) //nolint:gosec // generated project and cache dirs must stay world-readable +} + +func (osAtomicOps) lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } + +func (osAtomicOps) createTemp(dir, name string) (*os.File, string, error) { + f, err := os.CreateTemp(dir, filepath.Base(name)+".tmp-*") + if err != nil { + return nil, "", err } + return f, f.Name(), nil +} + +func (osAtomicOps) rename(from, to string) error { return os.Rename(from, to) } + +func (osAtomicOps) remove(name string) error { return os.Remove(name) } + +func (osAtomicOps) abort(f *os.File, err error) error { return errors.Join(err, f.Close()) } - tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") +type rootAtomicOps struct{ root *os.Root } + +func (o rootAtomicOps) mkdir(dir string) error { return o.root.MkdirAll(dir, 0o755) } + +func (o rootAtomicOps) lstat(name string) (os.FileInfo, error) { return o.root.Lstat(name) } + +func (o rootAtomicOps) createTemp(_, name string) (*os.File, string, error) { + tmp := name + ".tmp-" + rand.Text() + f, err := o.root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { + return nil, "", err + } + return f, tmp, nil +} + +func (o rootAtomicOps) rename(from, to string) error { return o.root.Rename(from, to) } + +func (o rootAtomicOps) remove(name string) error { return o.root.Remove(name) } + +func (rootAtomicOps) abort(f *os.File, err error) error { + _ = f.Close() + return err +} + +// atomicWrite stages data in a temp file in the target's directory, copies the +// target's mode onto it, then renames it into place. Every filesystem call goes +// through ops, so the same algorithm can be confined to an *os.Root. A crash +// before the rename leaves an orphaned temp file, never a truncated target. +func atomicWrite(ops atomicOps, name string, data []byte) error { + dir := filepath.Dir(name) + if err := ops.mkdir(dir); err != nil { return err } - tmpName := tmp.Name() - defer os.Remove(tmpName) // no-op once the rename succeeds - if _, err := tmp.Write(data); err != nil { - tmp.Close() + mode := os.FileMode(0o600) // CreateTemp/OpenFile's default for new files + if info, err := ops.lstat(name); err == nil { + if info.Mode()&os.ModeSymlink == 0 { + mode = info.Mode().Perm() + } + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + + f, tmpName, err := ops.createTemp(dir, name) + if err != nil { return err } - if err := tmp.Close(); err != nil { + defer func() { _ = ops.remove(tmpName) }() // no-op once the rename succeeds + + // The temp file starts at 0600; apply the target's mode before committing + // the rename, the same way the renderer stages generated files. + if err := f.Chmod(mode); err != nil { + return ops.abort(f, err) + } + if _, err := f.Write(data); err != nil { + return ops.abort(f, err) + } + if err := f.Close(); err != nil { return err } - return os.Rename(tmpName, path) + return ops.rename(tmpName, name) +} + +// AtomicWrite writes data to path via a temp file in the same directory +// followed by a rename, so a crash mid-write never leaves a truncated or +// corrupt file behind. The parent directory is created if missing. An existing +// target keeps its permissions; a genuinely new file gets CreateTemp's 0600. +func AtomicWrite(path string, data []byte) error { + return atomicWrite(osAtomicOps{}, path, data) +} + +// AtomicWriteRoot writes data to name relative to root via a temp file and a +// rename, so a crash mid-write cannot leave a truncated file behind. Unlike +// AtomicWrite, every operation is confined to root: a symlink planted between +// validation and commit can redirect neither the temp file nor the rename. +func AtomicWriteRoot(root *os.Root, name string, data []byte) error { + return atomicWrite(rootAtomicOps{root: root}, name, data) } // WriteJSON marshals v as indented JSON and writes it to path atomically. func WriteJSON(path string, v any) error { + return WriteJSONWithNewline(path, v, false) +} + +// WriteJSONWithNewline marshals v as indented JSON and writes it atomically. +// The newline flag preserves the exact byte format expected by committed +// fixtures and schema files. +func WriteJSONWithNewline(path string, v any, newline bool) error { data, err := json.MarshalIndent(v, "", " ") if err != nil { - return err + return fmt.Errorf("marshal JSON for %q: %w", path, err) + } + if newline { + data = append(data, '\n') } return AtomicWrite(path, data) } @@ -47,7 +274,7 @@ func WriteJSON(path string, v any) error { // ReadJSON reads path and unmarshals it into v. It returns os.ErrNotExist when // the file does not exist. func ReadJSON(path string, v any) error { - data, err := os.ReadFile(path) + data, err := os.ReadFile(path) //nolint:gosec // path comes from internal appdir/cache helpers if err != nil { return err } diff --git a/internal/fsutil/fsutil_hardening_test.go b/internal/fsutil/fsutil_hardening_test.go new file mode 100644 index 0000000..509d989 --- /dev/null +++ b/internal/fsutil/fsutil_hardening_test.go @@ -0,0 +1,24 @@ +package fsutil + +import ( + "os" + "testing" +) + +func TestLocalPathWithinRejectsEscape(t *testing.T) { + t.Parallel() + if _, _, err := LocalPathWithin(t.TempDir(), "../outside"); err == nil { + t.Fatal("LocalPathWithin accepted a path outside the base") + } +} + +func TestAtomicWriteRootConfinesWrites(t *testing.T) { + root, err := os.OpenRoot(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = root.Close() }() + if err := AtomicWriteRoot(root, "../outside.txt", []byte("x")); err == nil { + t.Fatal("AtomicWriteRoot accepted a path outside the root") + } +} diff --git a/internal/fsutil/fsutil_json_compat_test.go b/internal/fsutil/fsutil_json_compat_test.go new file mode 100644 index 0000000..9af0fd3 --- /dev/null +++ b/internal/fsutil/fsutil_json_compat_test.go @@ -0,0 +1,41 @@ +package fsutil + +import ( + "os" + "path/filepath" + "testing" +) + +// TestJSONV1Compatibility pins the decoding behavior of durable files +// (snapshot, cache, bridge metadata). encoding/json/v2 rejects duplicate keys +// and invalid UTF-8, so switching to it requires an explicit compatibility +// decision with fixtures — this test documents the v1 contract in the meantime. +func TestJSONV1Compatibility(t *testing.T) { + tests := []struct { + name string + data string + want string + }{ + {name: "duplicate keys keep last value", data: `{"v":"old","v":"new"}`, want: "new"}, + {name: "invalid utf8 is replaced", data: "{\"v\":\"\xff\"}", want: "\uFFFD"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "state.json") + if err := os.WriteFile(path, []byte(tt.data), 0o600); err != nil { + t.Fatal(err) + } + var got struct { + V string `json:"v"` + } + if err := ReadJSON(path, &got); err != nil { + t.Fatal(err) + } + if got.V != tt.want { + t.Fatalf("decoded %q, want %q", got.V, tt.want) + } + }) + } +} diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go index b570933..b47c029 100644 --- a/internal/fsutil/fsutil_test.go +++ b/internal/fsutil/fsutil_test.go @@ -3,6 +3,7 @@ package fsutil import ( "encoding/json" "errors" + "fmt" "os" "path/filepath" "testing" @@ -23,6 +24,40 @@ func TestAtomicWriteCreatesDirsAndWrites(t *testing.T) { } } +// A rewrite must not silently turn a developer-owned 0644 file into a 0600 +// file: AtomicWrite stages in a 0600 temp file, so it has to copy the target's +// mode onto the temp file before the rename. Windows normalises permission bits +// (0644 reads back as 0666), so the assertion compares the observed mode. +func TestAtomicWritePreservesExistingFileMode(t *testing.T) { + path := filepath.Join(t.TempDir(), "developer-owned.cs") + if err := os.WriteFile(path, []byte("old"), 0o644); err != nil { + t.Fatalf("seed file: %v", err) + } + before, err := os.Lstat(path) + if err != nil { + t.Fatalf("lstat before: %v", err) + } + modeBefore := before.Mode().Perm() + + if err := AtomicWrite(path, []byte("new")); err != nil { + t.Fatalf("AtomicWrite: %v", err) + } + after, err := os.Lstat(path) + if err != nil { + t.Fatalf("lstat after: %v", err) + } + if got := after.Mode().Perm(); got != modeBefore { + t.Errorf("mode = %04o, want %04o (unchanged from the 0644 seed)", got, modeBefore) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read back: %v", err) + } + if string(data) != "new" { + t.Errorf("content = %q, want %q", data, "new") + } +} + func TestAtomicWriteOverwritesAndLeavesNoTempFiles(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "cache.json") @@ -103,3 +138,145 @@ func TestReadJSONCorruptFileErrors(t *testing.T) { t.Errorf("err = %v, want a JSON syntax error", err) } } + +// A verified parent must not make the file leaf trustworthy: the leaf is +// re-inspected on every call, including when it was never in the cache. +func TestRefuseSymlinksCachedRejectsSymlinkAtFinalComponent(t *testing.T) { + base := t.TempDir() + sub := filepath.Join(base, "sub") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatalf("mkdir sub: %v", err) + } + outside := filepath.Join(base, "outside.txt") + if err := os.WriteFile(outside, []byte("keep"), 0o644); err != nil { + t.Fatalf("write outside file: %v", err) + } + + verified := make(map[string]bool) + cleanTarget := filepath.Join(sub, "clean.txt") + if err := RefuseSymlinksCached(base, cleanTarget, verified); err != nil { + t.Fatalf("warm cache: %v", err) + } + if !verified[filepath.Clean(base)] || !verified[filepath.Clean(sub)] { + t.Fatalf("base and sub should be cached as verified directories, got %v", verified) + } + if verified[filepath.Clean(cleanTarget)] { + t.Fatal("final target component must never be cached") + } + + link := filepath.Join(sub, "link.txt") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + want := fmt.Sprintf("refuse to write through symlink %q", link) + if got := RefuseSymlinksCached(base, link, verified); got == nil || got.Error() != want { + t.Errorf("cached check = %v, want %q", got, want) + } + if got := RefuseSymlinks(base, link); got == nil || got.Error() != want { + t.Errorf("fresh check = %v, want %q", got, want) + } + if verified[filepath.Clean(link)] { + t.Error("symlinked leaf was cached") + } +} + +// Cached and uncached checks must be indistinguishable for clean trees and +// for a symlink at an intermediate component. +func TestRefuseSymlinksCachedMatchesRefuseSymlinks(t *testing.T) { + tests := []struct { + name string + target func(t *testing.T, base string) string + }{ + { + name: "clean tree", + target: func(t *testing.T, base string) string { + t.Helper() + dir := filepath.Join(base, "src") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir src: %v", err) + } + leaf := filepath.Join(dir, "file.txt") + if err := os.WriteFile(leaf, []byte("x"), 0o644); err != nil { + t.Fatalf("write leaf: %v", err) + } + return leaf + }, + }, + { + name: "symlinked intermediate component", + target: func(t *testing.T, base string) string { + t.Helper() + realDir := filepath.Join(base, "real") + if err := os.MkdirAll(realDir, 0o755); err != nil { + t.Fatalf("mkdir real: %v", err) + } + link := filepath.Join(base, "linked") + if err := os.Symlink(realDir, link); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + return filepath.Join(link, "file.txt") + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + base := t.TempDir() + target := tt.target(t, base) + fresh := fmt.Sprintf("%v", RefuseSymlinks(base, target)) + + verified := make(map[string]bool) + for range 2 { // the second call must use the cache + got := fmt.Sprintf("%v", RefuseSymlinksCached(base, target, verified)) + if got != fresh { + t.Errorf("cached check = %q, fresh check = %q", got, fresh) + } + } + }) + } +} + +// A component that was missing on the first call is never cached: when it +// later appears as a symlink, the next call must still reject it. +func TestRefuseSymlinksCachedRechecksNewlyCreatedComponent(t *testing.T) { + base := t.TempDir() + outside := filepath.Join(base, "outside.txt") + if err := os.WriteFile(outside, []byte("keep"), 0o644); err != nil { + t.Fatalf("write outside file: %v", err) + } + missing := filepath.Join(base, "later") + target := filepath.Join(missing, "file.txt") + + verified := make(map[string]bool) + if err := RefuseSymlinksCached(base, target, verified); err != nil { + t.Fatalf("check with missing component: %v", err) + } + if verified[filepath.Clean(missing)] { + t.Fatal("missing component must not be cached") + } + if err := os.Symlink(outside, missing); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + want := fmt.Sprintf("refuse to write through symlink %q", missing) + if got := RefuseSymlinksCached(base, target, verified); got == nil || got.Error() != want { + t.Errorf("cached check = %v, want %q", got, want) + } +} + +func TestAtomicWriteRootRefusesSymlinkEscape(t *testing.T) { + root := t.TempDir() + outside := t.TempDir() + if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + dir, err := os.OpenRoot(root) + if err != nil { + t.Fatalf("OpenRoot: %v", err) + } + defer func() { _ = dir.Close() }() + if err := AtomicWriteRoot(dir, filepath.Join("escape", "victim.txt"), []byte("bad")); err == nil { + t.Fatal("AtomicWriteRoot followed a symlink outside the root") + } + if _, err := os.Stat(filepath.Join(outside, "victim.txt")); !os.IsNotExist(err) { + t.Errorf("file appeared outside the root: err = %v", err) + } +} diff --git a/internal/interactive/prompts.go b/internal/interactive/prompts.go index ea41f05..a6c5528 100644 --- a/internal/interactive/prompts.go +++ b/internal/interactive/prompts.go @@ -1,11 +1,96 @@ package interactive import ( + "bufio" "fmt" "github.com/DomainCraft/DomainCraft/internal/bridge" ) +// runPrompt owns the input loop shared by every interactive prompt. It draws +// the initial state, reads keys in raw mode, lets onKey mutate state and decide +// whether the prompt is done, and redraws after every key that does not end the +// prompt. Enter and Esc are reported as done, so neither triggers a redraw. +func runPrompt(draw func() []string, onKey func(key) (done bool, err error)) error { + f := &field{} + f.draw(draw()) + + reader := bufio.NewReader(promptInput) + return rawMode(func() error { + for { + k, err := readKey(reader) + if err != nil { + return err + } + done, err := onKey(k) + if done || err != nil { + return err + } + f.draw(draw()) + } + }) +} + +// runListNav is the single input loop for the numbered menus. Single-select +// prompts pass a nil onToggle: digits 1-9 move the cursor and Enter confirms. +// Multi-select passes onToggle: digits and Space toggle an item, Enter confirms. +func runListNav(count int, draw func(cursor int) []string, onToggle func(int)) (int, error) { + cursor := 0 + render := func() []string { return draw(cursor) } + onKey := func(k key) (bool, error) { + switch k.kind { + case keyUp: + if cursor > 0 { + cursor-- + } + case keyDown: + if cursor < count-1 { + cursor++ + } + case keySpace: + if onToggle != nil { + onToggle(cursor) + } + case keyEnter: + return true, nil + case keyEsc: + return true, errAborted + case keyRune: + if k.r >= '1' && k.r <= '9' { + if n := int(k.r - '1'); n < count { + if onToggle != nil { + onToggle(n) + } else { + cursor = n + } + } + } + } + return false, nil + } + err := runPrompt(render, onKey) + return cursor, err +} + +// numberedMenu renders the shared shape of a numbered selection prompt: a +// bold title, an optional description, one row per choice with the focused row +// highlighted, and the navigation hint. +func numberedMenu(title, description string, rows []string, cursor int) []string { + lines := []string{lineField(ansiBold + title)} + if description != "" { + lines = append(lines, lineField(" "+description)) + } + for i, row := range rows { + if i == cursor { + lines = append(lines, lineFocus(row)) + } else { + lines = append(lines, lineField(row)) + } + } + lines = append(lines, lineField(ansiDim+" ↑/↓ or 1-9 to move, Enter to confirm")) + return lines +} + // SelectBridge shows a bridge selection menu. ↑/↓ or 1-9 moves, Enter picks, // Esc aborts. func SelectBridge(registry *bridge.Registry) (*bridge.RegistryEntry, error) { @@ -21,60 +106,17 @@ func SelectBridge(registry *bridge.Registry) (*bridge.RegistryEntry, error) { return nil, fmt.Errorf("no bridges available") } - cursor := 0 - build := func() []string { - lines := []string{lineField(ansiBold + "Select a bridge (target language/framework for code generation)")} - for i, e := range entries { - s := fmt.Sprintf(" %2d) %s (%s) — %s", i+1, e.Name, e.Language, e.Description) - if i == cursor { - lines = append(lines, lineFocus(s)) - } else { - lines = append(lines, lineField(s)) - } - } - lines = append(lines, lineField(ansiDim+" ↑/↓ or 1-9 to move, Enter to confirm")) - return lines + rows := make([]string, 0, len(entries)) + for i, e := range entries { + rows = append(rows, fmt.Sprintf(" %2d) %s (%s) — %s", i+1, e.Name, e.Language, e.Description)) } - - f := &field{} - f.draw(build()) - var selected *bridge.RegistryEntry - err := rawMode(func() error { - for { - k, err := readKey() - if err != nil { - return err - } - switch k.kind { - case keyUp: - if cursor > 0 { - cursor-- - f.draw(build()) - } - case keyDown: - if cursor < len(entries)-1 { - cursor++ - f.draw(build()) - } - case keyEnter: - selected = &entries[cursor] - return nil - case keyEsc: - return errAborted - case keyRune: - if k.r >= '1' && k.r <= '9' { - if n := int(k.r - '1'); n < len(entries) && n != cursor { - cursor = n - f.draw(build()) - } - } - } - } - }) + cursor, err := runListNav(len(entries), func(cursor int) []string { + return numberedMenu("Select a bridge (target language/framework for code generation)", "", rows, cursor) + }, nil) if err != nil { return nil, err } - return selected, nil + return &entries[cursor], nil } // Option is one choice in SelectOption. @@ -92,60 +134,17 @@ func SelectOption(title, description string, options []Option) (int, error) { return 0, fmt.Errorf("no options available") } - cursor := 0 - build := func() []string { - lines := []string{lineField(ansiBold + title)} - if description != "" { - lines = append(lines, lineField(" "+description)) + rows := make([]string, 0, len(options)) + for i, o := range options { + row := fmt.Sprintf(" %2d) %s", i+1, o.Label) + if o.Description != "" { + row += " — " + o.Description } - for i, o := range options { - s := fmt.Sprintf(" %2d) %s", i+1, o.Label) - if o.Description != "" { - s += " — " + o.Description - } - if i == cursor { - lines = append(lines, lineFocus(s)) - } else { - lines = append(lines, lineField(s)) - } - } - lines = append(lines, lineField(ansiDim+" ↑/↓ or 1-9 to move, Enter to confirm")) - return lines + rows = append(rows, row) } - - f := &field{} - f.draw(build()) - err := rawMode(func() error { - for { - k, err := readKey() - if err != nil { - return err - } - switch k.kind { - case keyUp: - if cursor > 0 { - cursor-- - f.draw(build()) - } - case keyDown: - if cursor < len(options)-1 { - cursor++ - f.draw(build()) - } - case keyEnter: - return nil - case keyEsc: - return errAborted - case keyRune: - if k.r >= '1' && k.r <= '9' { - if n := int(k.r - '1'); n < len(options) && n != cursor { - cursor = n - f.draw(build()) - } - } - } - } - }) + cursor, err := runListNav(len(options), func(cursor int) []string { + return numberedMenu(title, description, rows, cursor) + }, nil) if err != nil { return 0, err } @@ -162,13 +161,13 @@ func PromptGenerateAdmin() (bool, error) { // PromptBridgeUpdate asks whether to update a cached bridge to the newer // upstream version. Returns true to download the update, false to keep the -// cached copy. -func PromptBridgeUpdate(entry bridge.RegistryEntry, update *bridge.Update) (bool, error) { - description := "A newer version is available for the cached bridge." - if update.LocalVersion != "" { - description = fmt.Sprintf("A newer version is available for the cached bridge (v%s). Update the cached copy?", update.LocalVersion) - } - return confirm(fmt.Sprintf("Update bridge %q?", entry.ID), description) +// cached copy. The version is intentionally omitted: bridge.Update carries +// the cached (old) version, not the available upstream one. +func PromptBridgeUpdate(entry bridge.RegistryEntry, _ *bridge.Update) (bool, error) { + return confirm( + fmt.Sprintf("Update bridge %q?", entry.ID), + "A newer version is available for the cached bridge. Update the cached copy?", + ) } // PromptYesNo asks a yes/no question with the default focus on "No". @@ -181,7 +180,7 @@ func PromptYesNo(title, description string) (bool, error) { // absent — they break on non-Latin keyboard layouts. func confirm(title, description string) (bool, error) { cursor := 1 // default: No - build := func() []string { + render := func() []string { lines := []string{lineField(ansiBold + title)} if description != "" { lines = append(lines, lineField(" "+description)) @@ -190,35 +189,26 @@ func confirm(title, description string) (bool, error) { lines = append(lines, lineField(" "+buttons+" "+ansiDim+"←/→ to switch, Enter to confirm")) return lines } - - f := &field{} - f.draw(build()) var result bool - err := rawMode(func() error { - for { - k, err := readKey() - if err != nil { - return err + onKey := func(k key) (bool, error) { + switch k.kind { + case keyEnter: + result = cursor == 0 + return true, nil + case keyEsc: + return true, errAborted + case keyLeft: + if cursor != 0 { + cursor = 0 } - switch { - case k.kind == keyEnter: - result = cursor == 0 - return nil - case k.kind == keyEsc: - return errAborted - case k.kind == keyLeft: - if cursor != 0 { - cursor = 0 - f.draw(build()) - } - case k.kind == keyRight: - if cursor != 1 { - cursor = 1 - f.draw(build()) - } + case keyRight: + if cursor != 1 { + cursor = 1 } } - }) + return false, nil + } + err := runPrompt(render, onKey) return result, err } @@ -231,10 +221,7 @@ type FileChoice struct { // PromptDeleteFiles asks which orphaned files of a deleted entity should be // removed. Returns the selected relative paths (empty = keep everything). func PromptDeleteFiles(entityName string, files []FileChoice) ([]string, error) { - if len(files) == 0 { - return nil, nil - } - return multiSelect( + return promptFiles( fmt.Sprintf("Entity %q was removed from domain.yaml", entityName), "The following files are no longer generated. Select files to delete:", files, @@ -244,16 +231,22 @@ func PromptDeleteFiles(entityName string, files []FileChoice) ([]string, error) // PromptRenameFiles asks which files of a renamed entity should be renamed. // Returns the selected relative paths (empty = keep everything). func PromptRenameFiles(oldName, newName string, files []FileChoice) ([]string, error) { - if len(files) == 0 { - return nil, nil - } - return multiSelect( + return promptFiles( fmt.Sprintf("Entity %q was renamed to %q", oldName, newName), "Select files to rename (old name -> new name in the path):", files, ) } +// promptFiles skips the prompt entirely when there are no files to choose +// from, so callers don't have to repeat the empty check. +func promptFiles(title, description string, files []FileChoice) ([]string, error) { + if len(files) == 0 { + return nil, nil + } + return multiSelect(title, description, files) +} + // multiSelect shows a numbered list with every item preselected. ↑/↓ moves // the green focus, Space toggles the focused item, 1-9 toggle directly, // Enter confirms, Esc aborts. Returns selected paths in original order. @@ -262,9 +255,7 @@ func multiSelect(title, description string, files []FileChoice) ([]string, error for i := range files { selected[i] = true } - cursor := 0 - - build := func() []string { + build := func(cursor int) []string { lines := []string{lineField(ansiBold + title)} if description != "" { lines = append(lines, lineField(" "+description)) @@ -289,43 +280,8 @@ func multiSelect(title, description string, files []FileChoice) ([]string, error return lines } - f := &field{} - f.draw(build()) - err := rawMode(func() error { - for { - k, err := readKey() - if err != nil { - return err - } - switch k.kind { - case keyUp: - if cursor > 0 { - cursor-- - f.draw(build()) - } - case keyDown: - if cursor < len(files)-1 { - cursor++ - f.draw(build()) - } - case keySpace: - selected[cursor] = !selected[cursor] - f.draw(build()) - case keyEnter: - return nil - case keyEsc: - return errAborted - case keyRune: - if k.r >= '1' && k.r <= '9' { - if n := int(k.r - '1'); n < len(files) { - selected[n] = !selected[n] - f.draw(build()) - } - } - } - } - }) - if err != nil { + toggle := func(i int) { selected[i] = !selected[i] } + if _, err := runListNav(len(files), build, toggle); err != nil { return nil, err } result := make([]string, 0, len(files)) diff --git a/internal/interactive/prompts_test.go b/internal/interactive/prompts_test.go index 2a311b5..481fef3 100644 --- a/internal/interactive/prompts_test.go +++ b/internal/interactive/prompts_test.go @@ -3,6 +3,7 @@ package interactive import ( "errors" "io" + "slices" "strings" "testing" @@ -14,33 +15,35 @@ import ( func setInput(s string) { promptInput = strings.NewReader(s) promptOutput = io.Discard - promptReader = nil } func TestConfirm(t *testing.T) { cases := []struct { + name string input string want bool err error }{ - {"\n", false, nil}, // Enter on default (No) - {"\x1b[D\n", true, nil}, // ← moves to Yes - {"\x1b[C\n", false, nil}, // → stays on No - {"\x1b[D\x1b[C\n", false, nil}, // Yes then back to No - {"\x1b", false, errAborted}, // Esc cancels + {"default_no", "\n", false, nil}, // Enter on default (No) + {"left_to_yes", "\x1b[D\n", true, nil}, // ← moves to Yes + {"right_stays_no", "\x1b[C\n", false, nil}, // → stays on No + {"yes_then_no", "\x1b[D\x1b[C\n", false, nil}, // Yes then back to No + {"esc_aborts", "\x1b", false, errAborted}, // Esc cancels } for _, c := range cases { - setInput(c.input) - got, err := confirm("?", "") - if !errors.Is(err, c.err) { - t.Fatalf("confirm(%q) error = %v, want %v", c.input, err, c.err) - } - if err != nil { - continue - } - if got != c.want { - t.Errorf("confirm(%q) = %v, want %v", c.input, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + setInput(c.input) + got, err := confirm("?", "") + if !errors.Is(err, c.err) { + t.Fatalf("confirm(%q) error = %v, want %v", c.input, err, c.err) + } + if err != nil { + return + } + if got != c.want { + t.Errorf("confirm(%q) = %v, want %v", c.input, got, c.want) + } + }) } } @@ -202,3 +205,70 @@ func TestPromptDeleteFilesEmpty(t *testing.T) { t.Errorf("PromptDeleteFiles(nil) = %v, want nil", got) } } + +func TestRunPrompt(t *testing.T) { + var keys []keyKind + draws := 0 + draw := func() []string { draws++; return []string{"line"} } + onKey := func(k key) (bool, error) { + keys = append(keys, k.kind) + if k.kind == keyEsc { + return true, errAborted + } + return k.kind == keyEnter, nil + } + + // Initial draw, one redraw after Down, none after Enter. + setInput("\x1b[B\n") + if err := runPrompt(draw, onKey); err != nil { + t.Fatal(err) + } + if draws != 2 { + t.Errorf("draws = %d, want 2 (initial + after Down)", draws) + } + if want := []keyKind{keyDown, keyEnter}; !slices.Equal(keys, want) { + t.Errorf("keys = %v, want %v", keys, want) + } + + // Esc aborts before a redraw. + keys = nil + draws = 0 + setInput("\x1b") + if err := runPrompt(draw, onKey); !errors.Is(err, errAborted) { + t.Fatalf("runPrompt(esc) error = %v, want errAborted", err) + } + if draws != 1 || !slices.Equal(keys, []keyKind{keyEsc}) { + t.Errorf("esc: draws = %d, keys = %v; want 1, [keyEsc]", draws, keys) + } +} + +func TestNumberedMenu(t *testing.T) { + got := numberedMenu("Title", "desc", []string{" 1) one", " 2) two"}, 1) + want := []string{ + lineField(ansiBold + "Title"), + lineField(" desc"), + lineField(" 1) one"), + lineFocus(" 2) two"), + lineField(ansiDim + " ↑/↓ or 1-9 to move, Enter to confirm"), + } + if !slices.Equal(got, want) { + t.Errorf("numberedMenu() = %q, want %q", got, want) + } +} + +func TestPromptFilesEmpty(t *testing.T) { + for _, call := range []struct { + name string + fn func() ([]string, error) + }{ + {"promptFiles", func() ([]string, error) { return promptFiles("t", "d", nil) }}, + {"PromptRenameFiles", func() ([]string, error) { return PromptRenameFiles("Old", "New", nil) }}, + } { + t.Run(call.name, func(t *testing.T) { + got, err := call.fn() + if err != nil || got != nil { + t.Errorf("empty files = %v, %v; want nil, nil", got, err) + } + }) + } +} diff --git a/internal/interactive/terminal.go b/internal/interactive/terminal.go index 79415d9..9887c6e 100644 --- a/internal/interactive/terminal.go +++ b/internal/interactive/terminal.go @@ -1,3 +1,4 @@ +// Package interactive provides the dependency-free ANSI terminal prompts. package interactive import ( @@ -70,7 +71,6 @@ func IsTerminal() bool { var ( promptInput io.Reader = os.Stdin promptOutput io.Writer = os.Stdout - promptReader *bufio.Reader ) // realTTY reports whether prompts run against a real terminal (raw mode, @@ -89,7 +89,11 @@ func rawMode(fn func() error) error { if err != nil { return err } - defer term.Restore(int(os.Stdin.Fd()), state) + defer func() { + // Best effort: a failed restore leaves the terminal in raw mode, but the + // prompt's own result must not be replaced by a cleanup error. + _ = term.Restore(int(os.Stdin.Fd()), state) + }() return fn() } @@ -105,23 +109,46 @@ func termWidth() int { return w } -// fitVisible truncates s so its visible width fits in width columns (one -// column per rune). ANSI escape sequences are zero-width and are preserved; -// a trailing ellipsis replaces the last column of truncated text. When the -// truncation cut through a styled line, a reset sequence is re-appended so -// the color cannot leak past the line. +// runeWidth is the number of terminal columns a rune occupies. East Asian +// wide/fullwidth characters and emoji take two columns; counting one column +// per rune let a line "fit" by the metric and then wrap in the terminal, which +// breaks in-place redraw — the reason fitVisible exists. +func runeWidth(r rune) int { + switch { + case r < 0x20 || (r >= 0x7f && r < 0xa0): + return 0 + case r >= 0x1100 && (r <= 0x115f || r == 0x2329 || r == 0x232a || + (r >= 0x2e80 && r <= 0xa4cf && r != 0x303f) || + (r >= 0xac00 && r <= 0xd7a3) || + (r >= 0xf900 && r <= 0xfaff) || + (r >= 0xfe10 && r <= 0xfe19) || + (r >= 0xfe30 && r <= 0xfe6f) || + (r >= 0xff00 && r <= 0xff60) || + (r >= 0xffe0 && r <= 0xffe6) || + (r >= 0x1f300 && r <= 0x1faff) || + (r >= 0x20000 && r <= 0x3fffd)): + return 2 + default: + return 1 + } +} + +// fitVisible truncates s so its visible width fits in width columns. ANSI +// escape sequences are zero-width and are preserved; a trailing ellipsis +// replaces the last column of truncated text. When the truncation cut through +// a styled line, a reset sequence is re-appended so the color cannot leak. func fitVisible(s string, width int) string { toks := tokenize(s) visible := 0 for _, t := range toks { if t.esc == "" { - visible++ + visible += runeWidth(t.r) } } if visible <= width { return s } - // Keep width-1 runes and let the ellipsis take the last column. + // Keep width-1 columns and let the ellipsis take the last one. keep := width - 1 var out strings.Builder hasANSI := false @@ -132,9 +159,10 @@ func fitVisible(s string, width int) string { out.WriteString(t.esc) continue } - if written < keep { + w := runeWidth(t.r) + if written+w <= keep { out.WriteRune(t.r) - written++ + written += w } else { out.WriteString("\u2026") break @@ -201,19 +229,12 @@ type key struct { r rune } -func readByte() (byte, error) { - if promptReader == nil { - promptReader = bufio.NewReader(promptInput) - } - return promptReader.ReadByte() -} - -// readKey reads one keypress. Arrow keys arrive as ESC [ X or ESC O X (some -// terminals use application cursor mode); a bare Esc (no '['/'O' after it) -// aborts the prompt and the extra byte, if any, is pushed back so it isn't -// lost. -func readKey() (key, error) { - b, err := readByte() +// readKey reads one keypress from the reader created for this prompt. Arrow +// keys arrive as ESC [ X or ESC O X (some terminals use application cursor +// mode); a bare Esc (no '['/'O' after it) aborts the prompt and the extra byte, +// if any, is pushed back so it isn't lost. +func readKey(r *bufio.Reader) (key, error) { + b, err := r.ReadByte() if err != nil { return key{}, err } @@ -223,15 +244,15 @@ func readKey() (key, error) { case ' ': return key{kind: keySpace}, nil case 27: - next, err := readByte() + next, err := r.ReadByte() if err != nil { return key{kind: keyEsc}, nil } if next != '[' && next != 'O' { - _ = promptReader.UnreadByte() + _ = r.UnreadByte() return key{kind: keyEsc}, nil } - seq, err := readByte() + seq, err := r.ReadByte() if err != nil { return key{kind: keyEsc}, nil } @@ -247,7 +268,21 @@ func readKey() (key, error) { } return key{kind: keyOther}, nil default: - return key{kind: keyRune, r: rune(b)}, nil + if b < utf8.RuneSelf { + return key{kind: keyRune, r: rune(b)}, nil + } + // Buffer the continuation bytes of a multi-byte UTF-8 rune instead of + // emitting one keyRune per byte. + buf := []byte{b} + for !utf8.FullRune(buf) && len(buf) < utf8.UTFMax { + next, err := r.ReadByte() + if err != nil { + break + } + buf = append(buf, next) + } + decoded, _ := utf8.DecodeRune(buf) + return key{kind: keyRune, r: decoded}, nil } } @@ -268,24 +303,24 @@ func (f *field) draw(lines []string) { // are printed over the old ones in place. Skipping the final "move // back up" would shift the block down by n-1 lines on every redraw // and make the terminal scroll ("run away"). - fmt.Fprintf(promptOutput, "\x1b[%dA", n) + _, _ = fmt.Fprintf(promptOutput, "\x1b[%dA", n) for i := range n { if i > 0 { - fmt.Fprint(promptOutput, "\n") + _, _ = fmt.Fprint(promptOutput, "\n") } - fmt.Fprint(promptOutput, "\x1b[2K") + _, _ = fmt.Fprint(promptOutput, "\x1b[2K") } - fmt.Fprintf(promptOutput, "\r\x1b[%dA", n-1) + _, _ = fmt.Fprintf(promptOutput, "\r\x1b[%dA", n-1) } for _, l := range fitted { - fmt.Fprintln(promptOutput, l) + _, _ = fmt.Fprintln(promptOutput, l) } // Clear the leftover lines below when the new block is shorter. if old := len(f.lines); old > len(fitted) { for range old - len(fitted) { - fmt.Fprint(promptOutput, "\x1b[1B\x1b[2K") + _, _ = fmt.Fprint(promptOutput, "\x1b[1B\x1b[2K") } - fmt.Fprintf(promptOutput, "\x1b[%dA", old-len(fitted)) + _, _ = fmt.Fprintf(promptOutput, "\x1b[%dA", old-len(fitted)) } f.lines = fitted -} \ No newline at end of file +} diff --git a/internal/interactive/theme_test.go b/internal/interactive/theme_test.go index f615769..2886f0a 100644 --- a/internal/interactive/theme_test.go +++ b/internal/interactive/theme_test.go @@ -22,19 +22,24 @@ func TestLineFieldColors(t *testing.T) { func TestFitVisible(t *testing.T) { cases := []struct { + name string s string width int want string }{ - {"short", 80, "short"}, // fits - {"12345", 5, "12345"}, // exact fit - {"123456", 5, "1234…"}, // truncated with ellipsis - {"Привет мир", 5, "Прив…"}, // rune-aware, not byte-aware - {"\x1b[42mhello\x1b[0m", 4, "\x1b[42mhel…\x1b[0m"}, // ANSI preserved, text truncated + {"fits", "short", 80, "short"}, // fits + {"exact_fit", "12345", 5, "12345"}, // exact fit + {"truncated", "123456", 5, "1234…"}, // truncated with ellipsis + {"rune_aware", "Привет мир", 5, "Прив…"}, // rune-aware, not byte-aware + {"ansi_preserved", "\x1b[42mhello\x1b[0m", 4, "\x1b[42mhel…\x1b[0m"}, // ANSI preserved, text truncated + {"wide_runes", "漢字abc", 5, "漢字…"}, // CJK takes two columns each; "漢字a" would wrap + {"emoji", "🚀abc", 3, "🚀…"}, // emoji takes two columns } for _, c := range cases { - if got := fitVisible(c.s, c.width); got != c.want { - t.Errorf("fitVisible(%q, %d) = %q, want %q", c.s, c.width, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + if got := fitVisible(c.s, c.width); got != c.want { + t.Errorf("fitVisible(%q, %d) = %q, want %q", c.s, c.width, got, c.want) + } + }) } } diff --git a/internal/ir/build_entities.go b/internal/ir/build_entities.go index 428df91..5436d5f 100644 --- a/internal/ir/build_entities.go +++ b/internal/ir/build_entities.go @@ -11,6 +11,19 @@ import ( "github.com/DomainCraft/DomainCraft/pkg/textutil" ) +// copySeed detaches the IR from ParsedSchema: a caller mutating seed rows after +// Build must not silently change the contract templates render from. +func copySeed(rows []map[string]any) []map[string]any { + if rows == nil { + return nil + } + out := make([]map[string]any, 0, len(rows)) + for _, row := range rows { + out = append(out, maps.Clone(row)) + } + return out +} + // oldDatabaseColumnName returns the snake_case DB column name of a field's // old_name hint (previous field name), or "" when the field has no rename hint. func oldDatabaseColumnName(field *parser.ParsedField) string { @@ -20,13 +33,100 @@ func oldDatabaseColumnName(field *parser.ParsedField) string { return textutil.ToDatabaseColumnName(field.OldName) } -// Build converts ParsedSchema into IRProject. -func Build(schema *parser.ParsedSchema) (*IRProject, error) { +// applyProjectConfig copies the optional project blocks into their IR shape. +// A nil parser block means "absent"; a non-nil block is copied even when all of +// its values are zero — presence flags stay in the parser and are resolved +// before Build, so the IR needs only the values. +func applyProjectConfig(target *Project, p parser.ProjectConfig) { + target.Cache = convertCacheConfig(p.Cache) + target.CORS = convertCORSConfig(p.CORS) + target.Deploy = convertDeployConfig(p.Deploy) + target.Versioning = convertVersioningConfig(p.Versioning) + target.RateLimit = convertRateLimitConfig(p.RateLimit) + target.Pagination = convertPaginationConfig(p.Pagination) + target.Infrastructure = convertInfrastructure(p.Infrastructure) +} + +func convertCacheConfig(src *parser.CacheConfig) *CacheConfig { + if src == nil { + return nil + } + return &CacheConfig{ + Enabled: src.Enabled, + Provider: src.Provider, + ConnectionString: src.ConnectionString, + TTLSeconds: src.TTLSeconds, + } +} + +func convertCORSConfig(src *parser.CORSConfig) *CORSConfig { + if src == nil { + return nil + } + return &CORSConfig{ + Enabled: src.Enabled, + Origins: append([]string(nil), src.Origins...), + } +} + +func convertDeployConfig(src *parser.DeployConfig) *DeployConfig { + if src == nil { + return nil + } + return &DeployConfig{Domain: src.Domain, Port: src.Port} +} + +func convertVersioningConfig(src *parser.VersioningConfig) *VersioningConfig { + if src == nil { + return nil + } + return &VersioningConfig{ + Enabled: src.Enabled, + DefaultVersion: src.DefaultVersion, + } +} + +func convertRateLimitConfig(src *parser.RateLimitConfig) *RateLimitConfig { + if src == nil { + return nil + } + return &RateLimitConfig{ + Enabled: src.Enabled, + Policy: src.Policy, + PermitLimit: src.PermitLimit, + WindowSeconds: src.WindowSeconds, + } +} + +func convertPaginationConfig(src *parser.PaginationConfig) *PaginationConfig { + if src == nil { + return nil + } + return &PaginationConfig{ + DefaultPageSize: src.DefaultPageSize, + MaxPageSize: src.MaxPageSize, + } +} + +func convertInfrastructure(src *parser.InfrastructureConfig) *Infrastructure { + if src == nil { + return nil + } + return &Infrastructure{ + Queue: src.Queue, + Cache: src.Cache, + Secrets: src.Secrets, + Storage: src.Storage, + } +} + +// Build converts ParsedSchema into Project. +func Build(schema *parser.ParsedSchema) (*Project, error) { if schema == nil { return nil, fmt.Errorf("parsed schema is nil") } - irProject := &IRProject{ + irProject := &Project{ Name: schema.Project.Name, Description: schema.Project.Description, Database: schema.Database, @@ -35,76 +135,29 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { Platform: schema.Project.Platform, Enums: copyEnumsSorted(schema.Enums), EnumOrder: sortedEnumKeys(schema.Enums), - Entities: make([]IREntity, 0, len(schema.Entities)), + Entities: make([]Entity, 0, len(schema.Entities)), } - if schema.Project.Cache != nil { - irProject.Cache = &IRCacheConfig{ - Enabled: schema.Project.Cache.Enabled, - Provider: schema.Project.Cache.Provider, - ConnectionString: schema.Project.Cache.ConnectionString, - TTLSeconds: schema.Project.Cache.TTLSeconds, - } - } - if schema.Project.CORS != nil { - irProject.CORS = &IRCORSConfig{ - Enabled: schema.Project.CORS.Enabled, - Origins: append([]string(nil), schema.Project.CORS.Origins...), - } - } - if schema.Project.Deploy != nil { - irProject.Deploy = &IRDeployConfig{ - Domain: schema.Project.Deploy.Domain, - Port: schema.Project.Deploy.Port, - } - } - if schema.Project.Versioning != nil { - irProject.Versioning = &IRVersioningConfig{ - Enabled: schema.Project.Versioning.Enabled, - DefaultVersion: schema.Project.Versioning.DefaultVersion, - } - } - if schema.Project.RateLimit != nil { - irProject.RateLimit = &IRRateLimitConfig{ - Enabled: schema.Project.RateLimit.Enabled, - Policy: schema.Project.RateLimit.Policy, - PermitLimit: schema.Project.RateLimit.PermitLimit, - WindowSeconds: schema.Project.RateLimit.WindowSeconds, - } - } - if schema.Project.Pagination != nil { - irProject.Pagination = &IRPaginationConfig{ - DefaultPageSize: schema.Project.Pagination.DefaultPageSize, - MaxPageSize: schema.Project.Pagination.MaxPageSize, - } - } - if schema.Project.Infrastructure != nil { - irProject.Infrastructure = &IRInfrastructure{ - Queue: schema.Project.Infrastructure.Queue, - Cache: schema.Project.Infrastructure.Cache, - Secrets: schema.Project.Infrastructure.Secrets, - Storage: schema.Project.Infrastructure.Storage, - } - } + applyProjectConfig(irProject, schema.Project) // Pass 1: build entities - entityIndex := make(map[string]*IREntity, len(schema.Entities)) + entityIndex := make(map[string]*Entity, len(schema.Entities)) for _, entityName := range schema.EntityOrder { sourceEntity := schema.Entities[entityName] if sourceEntity == nil { continue } - irEntity := IREntity{ + irEntity := Entity{ Name: sourceEntity.Name, OldName: sourceEntity.OldName, NamePlural: sourceEntity.NamePlural, Features: copyFeatureMap(sourceEntity.Features), - Fields: make([]IRField, 0, len(sourceEntity.FieldOrder)), - RelationsOut: make([]IRRelation, 0), - RelationsIn: make([]IRRelation, 0), - Indexes: make([]IRIndex, 0, len(sourceEntity.Indexes)), - Seed: sourceEntity.Seed, + Fields: make([]Field, 0, len(sourceEntity.FieldOrder)), + RelationsOut: make([]Relation, 0, len(sourceEntity.Fields)), + RelationsIn: make([]Relation, 0, len(sourceEntity.Fields)), + Indexes: make([]Index, 0, len(sourceEntity.Indexes)), + Seed: copySeed(sourceEntity.Seed), Permissions: convertPermissions(sourceEntity.Permissions), } @@ -114,12 +167,12 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { continue } - databaseType, err := resolveDatabaseType(field, schema) + databaseType, err := resolveDatabaseType(field, schema, make(map[string]bool)) if err != nil { return nil, fmt.Errorf("field '%s.%s': %w", sourceEntity.Name, field.Name, err) } - irEntity.Fields = append(irEntity.Fields, IRField{ + irEntity.Fields = append(irEntity.Fields, Field{ Name: field.Name, OldName: field.OldName, DatabaseType: databaseType, @@ -141,7 +194,7 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { } for _, idx := range sourceEntity.Indexes { - irEntity.Indexes = append(irEntity.Indexes, IRIndex{ + irEntity.Indexes = append(irEntity.Indexes, Index{ Name: idx.Name, Fields: append([]string(nil), idx.Fields...), Type: idx.Type, @@ -159,14 +212,17 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { return nil, err } + // One index serves all three relation passes. + relationIndex := indexRelationsOut(irProject.Entities) + // Pass 2b: reconcile one-to-many - reconcileOneToMany(irProject.Entities) + reconcileOneToMany(irProject.Entities, relationIndex) // Pass 2c: resolve inverse navigation names - resolveInverseNavs(irProject.Entities) + resolveInverseNavs(irProject.Entities, relationIndex) // Pass 3d: incoming relations - buildIncomingRelations(irProject.Entities) + buildIncomingRelations(irProject.Entities, relationIndex) // Topologically sort entities by FK dependencies (parents before children). irProject.Entities = sortEntities(irProject.Entities) @@ -174,22 +230,22 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { return irProject, nil } -func convertValidations(source map[string]string) []IRValidation { +func convertValidations(source map[string]string) []Validation { if len(source) == 0 { return nil } - result := make([]IRValidation, 0, len(source)) + result := make([]Validation, 0, len(source)) for _, key := range slices.Sorted(maps.Keys(source)) { - result = append(result, IRValidation{Name: key, Value: source[key]}) + result = append(result, Validation{Name: key, Value: source[key]}) } return result } -func convertPermissions(source *parser.ParsedPermissions) *IRPermissions { +func convertPermissions(source *parser.ParsedPermissions) *Permissions { if source == nil { return nil } - return &IRPermissions{ + return &Permissions{ Read: append([]string(nil), source.Read...), Create: append([]string(nil), source.Create...), Update: append([]string(nil), source.Update...), @@ -197,12 +253,22 @@ func convertPermissions(source *parser.ParsedPermissions) *IRPermissions { } } -func resolveDatabaseType(field *parser.ParsedField, schema *parser.ParsedSchema) (string, error) { +// resolveDatabaseType resolves a field's database type. Relation fields inherit +// the type of the target entity's primary key, which is itself a relation in a +// malformed model; visiting guards that chain against infinite recursion. +func resolveDatabaseType(field *parser.ParsedField, schema *parser.ParsedSchema, visiting map[string]bool) (string, error) { if field == nil || field.FieldDefinition == nil { return "", fmt.Errorf("field definition is missing") } if field.IsRelation() { + key := field.TargetEntity + "." + field.Name + if visiting[key] { + return "", fmt.Errorf("cyclic relation primary key at '%s'", key) + } + visiting[key] = true + defer delete(visiting, key) + target, ok := schema.Entities[field.TargetEntity] if !ok { return "", fmt.Errorf("relation target '%s' does not exist", field.TargetEntity) @@ -210,27 +276,27 @@ func resolveDatabaseType(field *parser.ParsedField, schema *parser.ParsedSchema) for _, targetFieldName := range target.FieldOrder { targetField := target.Fields[targetFieldName] if targetField != nil && targetField.IsPrimary { - return resolveDatabaseType(targetField, schema) + return resolveDatabaseType(targetField, schema, visiting) } } return "", fmt.Errorf("relation target '%s' has no primary key", field.TargetEntity) } - if field.Type == "array" { + if field.Type == specmeta.FieldTypeArray { return resolveArrayType(field.TargetType), nil } - if field.Type == "enum" { - if field.TargetType != "" { - return field.TargetType, nil + if field.Type == specmeta.FieldTypeEnum { + if field.TargetType == "" { + return "", fmt.Errorf("enum field has no target type") } - return specmeta.DefaultFieldType, nil + return field.TargetType, nil } if specmeta.IsPrimitive(field.Type) { return field.Type, nil } - return specmeta.DefaultFieldType, nil + return "", fmt.Errorf("unknown field type %q", field.Type) } func resolveArrayType(targetType string) string { @@ -244,8 +310,8 @@ func resolveArrayType(targetType string) string { return "array(string)" } -func convertAuth(source *parser.AuthConfig, schema *parser.ParsedSchema) *IRAuthConfig { - if source == nil || source.Type == "" || source.Type == "none" { +func convertAuth(source *parser.AuthConfig, schema *parser.ParsedSchema) *AuthConfig { + if source == nil || !specmeta.IsAuthEnabled(source.Type) { return nil } @@ -264,11 +330,11 @@ func convertAuth(source *parser.AuthConfig, schema *parser.ParsedSchema) *IRAuth me := source.Endpoints.HasMe() setup := source.Endpoints.HasSetup() - return &IRAuthConfig{ + return &AuthConfig{ Type: source.Type, Entity: entity, Roles: append([]string(nil), source.Roles...), - Endpoints: IRAuthEndpoints{ + Endpoints: AuthEndpoints{ HasLogin: login, HasRegister: register, HasMe: me, @@ -287,7 +353,8 @@ func copyEnumsSorted(source map[string][]string) map[string][]string { return nil } result := make(map[string][]string, len(source)) - for k, v := range source { + for _, k := range slices.Sorted(maps.Keys(source)) { + v := source[k] cp := make([]string, len(v)) copy(cp, v) result[k] = cp @@ -298,4 +365,4 @@ func copyEnumsSorted(source map[string][]string) map[string][]string { // sortedEnumKeys returns a sorted slice of enum names for deterministic iteration. func sortedEnumKeys(source map[string][]string) []string { return slices.Sorted(maps.Keys(source)) -} \ No newline at end of file +} diff --git a/internal/ir/builder_test.go b/internal/ir/build_entities_test.go similarity index 67% rename from internal/ir/builder_test.go rename to internal/ir/build_entities_test.go index 8512ec1..aea91b7 100644 --- a/internal/ir/builder_test.go +++ b/internal/ir/build_entities_test.go @@ -1,6 +1,7 @@ package ir import ( + "strings" "testing" "github.com/DomainCraft/DomainCraft/internal/lexer" @@ -9,6 +10,7 @@ import ( ) func TestBuildCreatesRelations(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -19,8 +21,8 @@ func TestBuildCreatesRelations(t *testing.T) { NamePlural: "Products", FieldOrder: []string{"id", "categoryId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "categoryId": testutil.MustParsedField(t, "categoryId", "relation(Category)"), }, }, "Category": { @@ -28,7 +30,7 @@ func TestBuildCreatesRelations(t *testing.T) { NamePlural: "Categories", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -65,6 +67,7 @@ func TestBuildCreatesRelations(t *testing.T) { } func TestBuildResolvesEnumTypes(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -76,9 +79,9 @@ func TestBuildResolvesEnumTypes(t *testing.T) { NamePlural: "Products", FieldOrder: []string{"id", "status", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(ProductStatus)"), - "tags": mustParsedField(t, "tags", "array(Tag)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(ProductStatus)"), + "tags": testutil.MustParsedField(t, "tags", "array(Tag)"), }, }, }, @@ -109,6 +112,7 @@ func TestBuildResolvesEnumTypes(t *testing.T) { } func TestBuildResolvesPrimitiveTypes(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -119,15 +123,15 @@ func TestBuildResolvesPrimitiveTypes(t *testing.T) { NamePlural: "Users", FieldOrder: []string{"id", "name", "count", "price", "active", "born", "created", "data", "items"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string"), - "count": mustParsedField(t, "count", "bigint"), - "price": mustParsedField(t, "price", "decimal"), - "active": mustParsedField(t, "active", "boolean"), - "born": mustParsedField(t, "born", "date"), - "created": mustParsedField(t, "created", "datetime"), - "data": mustParsedField(t, "data", "jsonb"), - "items": mustParsedField(t, "items", "array(int)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string"), + "count": testutil.MustParsedField(t, "count", "bigint"), + "price": testutil.MustParsedField(t, "price", "decimal"), + "active": testutil.MustParsedField(t, "active", "boolean"), + "born": testutil.MustParsedField(t, "born", "date"), + "created": testutil.MustParsedField(t, "created", "datetime"), + "data": testutil.MustParsedField(t, "data", "jsonb"), + "items": testutil.MustParsedField(t, "items", "array(int)"), }, }, }, @@ -164,11 +168,122 @@ func TestBuildResolvesPrimitiveTypes(t *testing.T) { } } -func mustParsedField(t *testing.T, name, input string) *parser.ParsedField { - return testutil.MustParsedField(t, name, input) +// relationPKCycleSchema builds a model where each entity's primary key is a +// relation to the other entity. Before the cycle guard this made Build recurse +// through resolveDatabaseType until the process died with a stack overflow. +func relationPKCycleSchema(t *testing.T) *parser.ParsedSchema { + t.Helper() + return &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + Database: "postgresql", + EntityOrder: []string{"Alpha", "Beta"}, + Entities: map[string]*parser.ParsedEntity{ + "Alpha": { + Name: "Alpha", + NamePlural: "Alphas", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "relation(Beta) [primary]"), + }, + }, + "Beta": { + Name: "Beta", + NamePlural: "Betas", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "relation(Alpha) [primary]"), + }, + }, + }, + } +} + +func TestBuildDetectsRelationPrimaryKeyCycle(t *testing.T) { + t.Parallel() + + project, err := Build(relationPKCycleSchema(t)) + if err == nil { + t.Fatalf("Build() = %+v, want a cycle error", project) + } + if !strings.Contains(err.Error(), "cyclic relation primary key") { + t.Fatalf("Build() error = %q, want a cycle error", err) + } +} + +func TestResolveDatabaseTypeDetectsCycles(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + schema *parser.ParsedSchema + field func(*testing.T, *parser.ParsedSchema) *parser.ParsedField + wantErr string + want string + }{ + { + name: "self relation primary key", + schema: relationPKCycleSchema(t), + field: func(_ *testing.T, s *parser.ParsedSchema) *parser.ParsedField { + f := testutil.MustParsedField(t, "id", "relation(Alpha) [primary]") + s.Entities["Alpha"].Fields["id"] = f + return f + }, + wantErr: "cyclic relation primary key", + }, + { + name: "two entity relation primary key cycle", + schema: relationPKCycleSchema(t), + field: func(_ *testing.T, s *parser.ParsedSchema) *parser.ParsedField { + return s.Entities["Alpha"].Fields["id"] + }, + wantErr: "cyclic relation primary key", + }, + { + name: "relation chain ending in a scalar primary key", + schema: &parser.ParsedSchema{ + Entities: map[string]*parser.ParsedEntity{ + "Order": { + FieldOrder: []string{"userId"}, + Fields: map[string]*parser.ParsedField{ + "userId": testutil.MustParsedField(t, "userId", "relation(User)"), + }, + }, + "User": { + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }, + }, + }, + }, + field: func(_ *testing.T, s *parser.ParsedSchema) *parser.ParsedField { + return s.Entities["Order"].Fields["userId"] + }, + want: "uuid", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := resolveDatabaseType(tt.field(t, tt.schema), tt.schema, make(map[string]bool)) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("resolveDatabaseType() error = %v, want %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("resolveDatabaseType() error = %v", err) + } + if got != tt.want { + t.Errorf("resolveDatabaseType() = %q, want %q", got, tt.want) + } + }) + } } func TestNavigationNameStripsIdSuffix(t *testing.T) { + t.Parallel() tests := []struct { name string field *parser.ParsedField @@ -184,6 +299,11 @@ func TestNavigationNameStripsIdSuffix(t *testing.T) { field: &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{Name: "categoryID", Type: "relation", TargetEntity: "Category"}}, wantNav: "Category", }, + { + name: "categoryid does not strip id", + field: &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{Name: "categoryid", Type: "relation", TargetEntity: "Category"}}, + wantNav: "Categoryid", + }, { name: "fluid does not strip id", field: &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{Name: "fluid", Type: "string"}}, @@ -207,6 +327,7 @@ func TestNavigationNameStripsIdSuffix(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() got := tt.field.NavigationName() if got != tt.wantNav { t.Errorf("NavigationName() = %q, want %q", got, tt.wantNav) @@ -216,6 +337,7 @@ func TestNavigationNameStripsIdSuffix(t *testing.T) { } func TestBuildCopiesDescription(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test", Description: "A test project"}, Database: "postgresql", @@ -226,7 +348,7 @@ func TestBuildCopiesDescription(t *testing.T) { NamePlural: "Users", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -243,6 +365,7 @@ func TestBuildCopiesDescription(t *testing.T) { } func TestBuildCopiesFeaturesMap(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -254,7 +377,7 @@ func TestBuildCopiesFeaturesMap(t *testing.T) { Features: map[string]bool{"audit": true, "soft_delete": true}, FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -290,6 +413,7 @@ func TestBuildCopiesFeaturesMap(t *testing.T) { } func TestBuildCircularDependency(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -300,8 +424,8 @@ func TestBuildCircularDependency(t *testing.T) { NamePlural: "As", FieldOrder: []string{"id", "bRef"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "bRef": mustParsedField(t, "bRef", "relation(B)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "bRef": testutil.MustParsedField(t, "bRef", "relation(B)"), }, }, "B": { @@ -309,8 +433,8 @@ func TestBuildCircularDependency(t *testing.T) { NamePlural: "Bs", FieldOrder: []string{"id", "aRef"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "aRef": mustParsedField(t, "aRef", "relation(A)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "aRef": testutil.MustParsedField(t, "aRef", "relation(A)"), }, }, }, @@ -328,6 +452,7 @@ func TestBuildCircularDependency(t *testing.T) { } func TestBuildCopiesDatabaseColumnName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -338,8 +463,8 @@ func TestBuildCopiesDatabaseColumnName(t *testing.T) { NamePlural: "Users", FieldOrder: []string{"id", "firstName"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "firstName": mustParsedField(t, "firstName", "string"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "firstName": testutil.MustParsedField(t, "firstName", "string"), }, }, }, @@ -368,6 +493,7 @@ func TestBuildCopiesDatabaseColumnName(t *testing.T) { // carried into the IR, including the derived old snake_case DB column name that // bridges use to emit a safe RenameColumn. func TestBuildCopiesFieldOldName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -378,8 +504,8 @@ func TestBuildCopiesFieldOldName(t *testing.T) { NamePlural: "Products", FieldOrder: []string{"id", "displayName"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "displayName": mustParsedField(t, "displayName", "string [required, old_name:productTitle]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "displayName": testutil.MustParsedField(t, "displayName", "string [required, old_name:productTitle]"), }, }, }, @@ -409,6 +535,7 @@ func TestBuildCopiesFieldOldName(t *testing.T) { // pointer must still point at the correct entity (the in-place reorder used to // overwrite the backing array the pointers referenced, corrupting the targets). func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -418,32 +545,32 @@ func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { Name: "User", NamePlural: "Users", FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{"id": mustParsedField(t, "id", "uuid [primary]")}, + Fields: map[string]*parser.ParsedField{"id": testutil.MustParsedField(t, "id", "uuid [primary]")}, }, "Product": { Name: "Product", NamePlural: "Products", FieldOrder: []string{"id", "categoryId", "supplierId", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category)"), - "supplierId": mustParsedField(t, "supplierId", "relation(User)"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "categoryId": testutil.MustParsedField(t, "categoryId", "relation(Category)"), + "supplierId": testutil.MustParsedField(t, "supplierId", "relation(User)"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Category": { Name: "Category", NamePlural: "Categories", FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{"id": mustParsedField(t, "id", "uuid [primary]")}, + Fields: map[string]*parser.ParsedField{"id": testutil.MustParsedField(t, "id", "uuid [primary]")}, }, "Order": { Name: "Order", NamePlural: "Orders", FieldOrder: []string{"id", "userId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "userId": mustParsedField(t, "userId", "relation(User)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "userId": testutil.MustParsedField(t, "userId", "relation(User)"), }, }, "OrderItem": { @@ -451,25 +578,25 @@ func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { NamePlural: "OrderItems", FieldOrder: []string{"id", "orderId", "productId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "orderId": mustParsedField(t, "orderId", "relation(Order)"), - "productId": mustParsedField(t, "productId", "relation(Product)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "orderId": testutil.MustParsedField(t, "orderId", "relation(Order)"), + "productId": testutil.MustParsedField(t, "productId", "relation(Product)"), }, }, "Tag": { Name: "Tag", NamePlural: "Tags", FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{"id": mustParsedField(t, "id", "uuid [primary]")}, + Fields: map[string]*parser.ParsedField{"id": testutil.MustParsedField(t, "id", "uuid [primary]")}, }, "Review": { Name: "Review", NamePlural: "Reviews", FieldOrder: []string{"id", "productId", "userId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "productId": mustParsedField(t, "productId", "relation(Product)"), - "userId": mustParsedField(t, "userId", "relation(User)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "productId": testutil.MustParsedField(t, "productId", "relation(Product)"), + "userId": testutil.MustParsedField(t, "userId", "relation(User)"), }, }, "Document": { @@ -477,8 +604,8 @@ func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { NamePlural: "Documents", FieldOrder: []string{"id", "authorId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "authorId": mustParsedField(t, "authorId", "relation(User)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "authorId": testutil.MustParsedField(t, "authorId", "relation(User)"), }, }, }, @@ -489,7 +616,7 @@ func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { t.Fatalf("Build() error = %v", err) } - byName := make(map[string]*IREntity, len(projectIR.Entities)) + byName := make(map[string]*Entity, len(projectIR.Entities)) for i := range projectIR.Entities { byName[projectIR.Entities[i].Name] = &projectIR.Entities[i] } @@ -539,14 +666,14 @@ func TestBuildResolvesTargetEntityAfterTopoSort(t *testing.T) { } } -func targetName(e *IREntity) string { +func targetName(e *Entity) string { if e == nil { return "" } return e.Name } -func findEntity(project *IRProject, name string) *IREntity { +func findEntity(project *Project, name string) *Entity { if project == nil { return nil } @@ -563,6 +690,7 @@ func findEntity(project *IRProject, name string) *IREntity { // has both a Buyer and a Seller referencing User), the pluralized inverse name // "EscrowContracts" would collide and produce duplicate C# navigation properties. func TestBuildDisambiguatesInverseNavigationNames(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -572,16 +700,16 @@ func TestBuildDisambiguatesInverseNavigationNames(t *testing.T) { Name: "User", NamePlural: "Users", FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{"id": mustParsedField(t, "id", "uuid [primary]")}, + Fields: map[string]*parser.ParsedField{"id": testutil.MustParsedField(t, "id", "uuid [primary]")}, }, "EscrowContract": { Name: "EscrowContract", NamePlural: "EscrowContracts", FieldOrder: []string{"id", "buyer", "seller"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "buyer": mustParsedField(t, "buyer", "relation(User) [required, on_delete:restrict]"), - "seller": mustParsedField(t, "seller", "relation(User) [required, on_delete:restrict]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "buyer": testutil.MustParsedField(t, "buyer", "relation(User) [required, on_delete:restrict]"), + "seller": testutil.MustParsedField(t, "seller", "relation(User) [required, on_delete:restrict]"), }, }, }, @@ -643,6 +771,7 @@ func TestBuildDisambiguatesInverseNavigationNames(t *testing.T) { // one-to-many relationship, not a many-to-many. Without reconciliation the C# // bridge would emit a spurious EF join table AND a bogus inverse collection. func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -653,8 +782,8 @@ func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { NamePlural: "Wallets", FieldOrder: []string{"id", "transactions"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "transactions": mustParsedField(t, "transactions", "relation(WalletTransaction) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "transactions": testutil.MustParsedField(t, "transactions", "relation(WalletTransaction) [many]"), }, }, "WalletTransaction": { @@ -662,8 +791,8 @@ func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { NamePlural: "WalletTransactions", FieldOrder: []string{"id", "wallet"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "wallet": mustParsedField(t, "wallet", "relation(Wallet) [required, on_delete:cascade]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "wallet": testutil.MustParsedField(t, "wallet", "relation(Wallet) [required, on_delete:cascade]"), }, }, }, @@ -683,7 +812,7 @@ func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { // The [many] relation must be classified as the collection side of a // one-to-many (paired with the FK declared on WalletTransaction). - var transactions *IRRelation + var transactions *Relation for i := range wallet.RelationsOut { if wallet.RelationsOut[i].FieldName == "transactions" { transactions = &wallet.RelationsOut[i] @@ -710,7 +839,7 @@ func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { if wt == nil { t.Fatal("WalletTransaction entity not found") } - var walletRel *IRRelation + var walletRel *Relation for i := range wt.RelationsOut { if wt.RelationsOut[i].FieldName == "wallet" { walletRel = &wt.RelationsOut[i] @@ -740,6 +869,7 @@ func TestBuildReconcilesOneToManyDeclaredOnBothSides(t *testing.T) { // OrderConfiguration.cs failed to compile with // "Cannot implicitly convert type 'System.Guid' to 'Order'". func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -750,8 +880,8 @@ func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { NamePlural: "Orders", FieldOrder: []string{"id", "items"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "items": mustParsedField(t, "items", "relation(OrderItem) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "items": testutil.MustParsedField(t, "items", "relation(OrderItem) [many]"), }, }, "OrderItem": { @@ -759,8 +889,8 @@ func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { NamePlural: "OrderItems", FieldOrder: []string{"id", "orderId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "orderId": mustParsedField(t, "orderId", "relation(Order) [required, on_delete:cascade]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "orderId": testutil.MustParsedField(t, "orderId", "relation(Order) [required, on_delete:cascade]"), }, }, }, @@ -778,7 +908,7 @@ func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { t.Fatal("Order entity not found") } - var items *IRRelation + var items *Relation for i := range order.RelationsOut { if order.RelationsOut[i].FieldName == "items" { items = &order.RelationsOut[i] @@ -797,6 +927,7 @@ func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { } func TestBuildConvertsAuthAndValidations(t *testing.T) { + t.Parallel() disabled := false schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Shop"}, @@ -808,9 +939,9 @@ func TestBuildConvertsAuthAndValidations(t *testing.T) { NamePlural: "Users", FieldOrder: []string{"id", "email", "password"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string [required, email]"), - "password": mustParsedField(t, "password", "string [required]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string [required, email]"), + "password": testutil.MustParsedField(t, "password", "string [required]"), }, }, "Order": { @@ -818,9 +949,9 @@ func TestBuildConvertsAuthAndValidations(t *testing.T) { NamePlural: "Orders", FieldOrder: []string{"id", "total", "sku"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "total": mustParsedField(t, "total", "decimal [min:0, max:999999]"), - "sku": mustParsedField(t, "sku", "string [max:32]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "total": testutil.MustParsedField(t, "total", "decimal [min:0, max:999999]"), + "sku": testutil.MustParsedField(t, "sku", "string [max:32]"), }, }, }, @@ -855,7 +986,7 @@ func TestBuildConvertsAuthAndValidations(t *testing.T) { t.Error("register explicitly disabled but got true") } - var order *IREntity + var order *Entity for i := range projectIR.Entities { if projectIR.Entities[i].Name == "Order" { order = &projectIR.Entities[i] @@ -878,6 +1009,7 @@ func TestBuildConvertsAuthAndValidations(t *testing.T) { } func TestBuildWithoutAuthYieldsNilAuth(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Plain"}, Database: "postgresql", @@ -887,7 +1019,7 @@ func TestBuildWithoutAuthYieldsNilAuth(t *testing.T) { Name: "Item", NamePlural: "Items", FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{"id": mustParsedField(t, "id", "uuid [primary]")}, + Fields: map[string]*parser.ParsedField{"id": testutil.MustParsedField(t, "id", "uuid [primary]")}, }, }, } @@ -900,3 +1032,97 @@ func TestBuildWithoutAuthYieldsNilAuth(t *testing.T) { t.Errorf("auth = %+v, want nil when no auth block is declared", projectIR.Auth) } } + +func TestBuildRejectsUnresolvableFieldTypes(t *testing.T) { + t.Parallel() + cases := []struct { + name string + definition lexer.FieldDefinition + wantErr string + }{ + {"unknown type", lexer.FieldDefinition{Name: "weird", Type: "mystery"}, "unknown field type"}, + {"enum without target", lexer.FieldDefinition{Name: "status", Type: "enum"}, "enum field has no target type"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + definition := tc.definition + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + Database: "postgresql", + EntityOrder: []string{"Item"}, + Entities: map[string]*parser.ParsedEntity{ + "Item": { + Name: "Item", + NamePlural: "Items", + FieldOrder: []string{definition.Name}, + Fields: map[string]*parser.ParsedField{ + definition.Name: {FieldDefinition: &definition}, + }, + }, + }, + } + if _, err := Build(schema); err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Build() error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestBuildPreservesZeroValuedProjectBlocks(t *testing.T) { + t.Parallel() + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{ + Name: "Test", + Cache: &parser.CacheConfig{}, + CORS: &parser.CORSConfig{}, + Deploy: &parser.DeployConfig{}, + Versioning: &parser.VersioningConfig{}, + RateLimit: &parser.RateLimitConfig{}, + Pagination: &parser.PaginationConfig{}, + Infrastructure: &parser.InfrastructureConfig{}, + }, + Database: "postgresql", + } + project, err := Build(schema) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + // A present-but-zero block stays present: presence flags are resolved by + // the parser and must not be re-inferred from the value here. + if project.Cache == nil || project.CORS == nil || project.Deploy == nil || + project.Versioning == nil || project.RateLimit == nil || project.Pagination == nil || + project.Infrastructure == nil { + t.Fatalf("Build() dropped a present zero-valued config block: %+v", project) + } +} + +func TestBuildDetachesSeedFromParsedSchema(t *testing.T) { + t.Parallel() + seedRow := map[string]any{"id": "11111111-1111-4111-8111-111111111111"} + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + Database: "postgresql", + EntityOrder: []string{"Item"}, + Entities: map[string]*parser.ParsedEntity{ + "Item": { + Name: "Item", + NamePlural: "Items", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }, + Seed: []map[string]any{seedRow}, + }, + }, + } + + projectIR, err := Build(schema) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + seedRow["id"] = "mutated" + if got := projectIR.Entities[0].Seed[0]["id"]; got != "11111111-1111-4111-8111-111111111111" { + t.Errorf("IR seed followed a mutation of ParsedSchema: %v", got) + } +} diff --git a/internal/ir/build_relations.go b/internal/ir/build_relations.go index 688ab79..2213aef 100644 --- a/internal/ir/build_relations.go +++ b/internal/ir/build_relations.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) @@ -11,7 +12,7 @@ import ( // entity. It must run as a separate pass from the inverse pass below so the // inverse logic always sees the complete set of RelationsOut regardless of // entity declaration order. -func buildForwardRelations(entities []IREntity, schema *parser.ParsedSchema, entityIndex map[string]*IREntity) error { +func buildForwardRelations(entities []Entity, schema *parser.ParsedSchema, entityIndex map[string]*Entity) error { for i := range entities { irEntity := &entities[i] sourceEntity := schema.Entities[irEntity.Name] @@ -30,7 +31,7 @@ func buildForwardRelations(entities []IREntity, schema *parser.ParsedSchema, ent return fmt.Errorf("relation target '%s' referenced by '%s.%s' does not exist", field.TargetEntity, irEntity.Name, field.Name) } - irEntity.RelationsOut = append(irEntity.RelationsOut, IRRelation{ + irEntity.RelationsOut = append(irEntity.RelationsOut, Relation{ FieldName: field.Name, TargetEntity: targetEntity, NavigationName: field.NavigationName(), @@ -45,13 +46,52 @@ func buildForwardRelations(entities []IREntity, schema *parser.ParsedSchema, ent return nil } +// relationIndex groups an entity's forward relations by the name of the entity +// they point at. Each bucket keeps the FIRST relation in RelationsOut order, +// matching the early return / break of the linear scans it replaces. +type relationIndex struct { + singleBack map[string]*Relation + manyBack map[string]*Relation +} + +// indexRelationsOut builds that view once before the reconciliation passes. A +// hub with N inbound relations used to be rescanned N times per pass. +func indexRelationsOut(entities []Entity) map[string]*relationIndex { + index := make(map[string]*relationIndex, len(entities)) + for i := range entities { + owner := &entities[i] + byTarget := index[owner.Name] + if byTarget == nil { + byTarget = &relationIndex{ + singleBack: make(map[string]*Relation), + manyBack: make(map[string]*Relation), + } + index[owner.Name] = byTarget + } + for j := range owner.RelationsOut { + rel := &owner.RelationsOut[j] + if rel.TargetEntity == nil { + continue + } + bucket := byTarget.singleBack + if rel.IsMany { + bucket = byTarget.manyBack + } + if _, seen := bucket[rel.TargetEntity.Name]; !seen { + bucket[rel.TargetEntity.Name] = rel + } + } + } + return index +} + // reconcileOneToMany (Pass 2b) detects one-to-many relations declared on BOTH // sides. When entity A has a `[many]` relation to B AND B declares a single FK // relation back to A, the two declarations describe the SAME one-to-many // relationship — not a many-to-many. The FK lives on B; A's [many] is its // collection navigation. Without this reconciliation a bridge would generate a // spurious join table in addition to the FK. -func reconcileOneToMany(entities []IREntity) { +func reconcileOneToMany(entities []Entity, index map[string]*relationIndex) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -59,11 +99,18 @@ func reconcileOneToMany(entities []IREntity) { if !rel.IsMany || rel.TargetEntity == nil { continue } - pair := findSingleBack(rel.TargetEntity, entity.Name) + var pair *Relation + if bySource := index[rel.TargetEntity.Name]; bySource != nil { + pair = bySource.singleBack[entity.Name] + } + // singleBack holds only !IsMany relations with a non-nil target, + // bucketed by that target's name — so the lookup above already + // satisfies the validator's single-back rule. The validator keeps + // the explicit check because its inputs are user-declared. if pair == nil { continue } - rel.RelationType = "one-to-many" + rel.RelationType = specmeta.RelationTypeOneToMany rel.PairFieldName = pair.FieldName rel.PairNavigationName = pair.NavigationName rel.OnDeleteBehavior = pair.OnDeleteBehavior @@ -75,7 +122,7 @@ func reconcileOneToMany(entities []IREntity) { // resolveInverseNavs (Pass 2c) resolves each forward relation's inverse-navigation // name to the actual collection on the target entity. For OrderItem→Order the // inverse should be "Items" (Order's forward nav), not the computed "OrderItems". -func resolveInverseNavs(entities []IREntity) { +func resolveInverseNavs(entities []Entity, index map[string]*relationIndex) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -83,10 +130,9 @@ func resolveInverseNavs(entities []IREntity) { if rel.TargetEntity == nil || rel.IsMany { continue } - for _, targetRel := range rel.TargetEntity.RelationsOut { - if targetRel.IsMany && targetRel.TargetEntity != nil && targetRel.TargetEntity.Name == entity.Name { - rel.InverseNavName = textutil.PascalCase(targetRel.FieldName) - break + if bySource := index[rel.TargetEntity.Name]; bySource != nil { + if back := bySource.manyBack[entity.Name]; back != nil { + rel.InverseNavName = textutil.PascalCase(back.FieldName) } } } @@ -96,7 +142,7 @@ func resolveInverseNavs(entities []IREntity) { // buildIncomingRelations (Pass 3d) builds inverse (incoming) relations. Each // incoming relation is a collection navigation on the target that points back // to the owning entity. -func buildIncomingRelations(entities []IREntity) { +func buildIncomingRelations(entities []Entity, index map[string]*relationIndex) { usedInverse := make(map[string]map[string]bool) // target entity -> defined inverse nav names for i := range entities { entity := &entities[i] @@ -108,12 +154,12 @@ func buildIncomingRelations(entities []IREntity) { } // A double-declared one-to-many: the collection already exists as the // forward [many] field — no separate inverse collection on target. - if rel.IsMany && rel.RelationType == "one-to-many" { + if rel.IsMany && rel.RelationType == specmeta.RelationTypeOneToMany { continue } // If the target already declares its own forward IsMany relation back // to this entity, the inverse collection lives there instead. - if hasForwardManyTo(target, entity.Name) { + if bySource := index[target.Name]; bySource != nil && bySource.manyBack[entity.Name] != nil { continue } invName := rel.InverseNavName @@ -130,7 +176,7 @@ func buildIncomingRelations(entities []IREntity) { } usedInverse[target.Name][invName] = true rel.InverseNavName = invName - target.RelationsIn = append(target.RelationsIn, IRRelation{ + target.RelationsIn = append(target.RelationsIn, Relation{ FieldName: rel.FieldName, TargetEntity: entity, InverseNavName: invName, @@ -142,34 +188,3 @@ func buildIncomingRelations(entities []IREntity) { } } } - -// findSingleBack returns the target entity's forward single (non-many) FK -// relation that points back to sourceName, or nil if none exists. -func findSingleBack(target *IREntity, sourceName string) *IRRelation { - if target == nil { - return nil - } - for i := range target.RelationsOut { - r := &target.RelationsOut[i] - if !r.IsMany && r.TargetEntity != nil && r.TargetEntity.Name == sourceName { - return r - } - } - return nil -} - -// hasForwardManyTo reports whether target declares a forward IsMany relation -// that points back to entityName. When true, the inverse collection for that -// relationship already lives on target as its own field. -func hasForwardManyTo(target *IREntity, entityName string) bool { - if target == nil { - return false - } - for i := range target.RelationsOut { - r := &target.RelationsOut[i] - if r.IsMany && r.TargetEntity != nil && r.TargetEntity.Name == entityName { - return true - } - } - return false -} \ No newline at end of file diff --git a/internal/ir/build_relations_bench_test.go b/internal/ir/build_relations_bench_test.go new file mode 100644 index 0000000..b2d6e6a --- /dev/null +++ b/internal/ir/build_relations_bench_test.go @@ -0,0 +1,290 @@ +package ir + +import ( + "flag" + "fmt" + "maps" + "slices" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/lexer" + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/testutil" +) + +var updateGolden = flag.Bool("update", false, "regenerate benchmark golden files") + +// benchmarkSortFixture builds the dependency shapes shared by +// BenchmarkSortEntities and TestBenchmarkSortEntitiesGolden: +// - chain: entity i depends on i-1 (every pop scans all entities today); +// - fanout: one root unlocks every other entity in ascending name order; +// - fanout-reverse: the same root unlocks them in descending name order, +// the case where out-of-order insertions shifted the whole ready slice. +func benchmarkSortFixture(kind string, size int) []Entity { + entities := make([]Entity, size) + for i := range entities { + name := i + if kind == "fanout-reverse" { + name = size - 1 - i + } + entities[i] = Entity{Name: fmt.Sprintf("E%04d", name)} + } + fieldName := "root" + if kind == "chain" { + fieldName = "parent" + } + for i := 1; i < size; i++ { + target := &entities[0] + if kind == "chain" { + target = &entities[i-1] + } + entities[i].RelationsOut = []Relation{{ + FieldName: fieldName, + TargetEntity: target, + IsMany: false, + }} + } + return entities +} + +func BenchmarkSortEntities(b *testing.B) { + for _, size := range []int{100, 500, 2000} { + b.Run(fmt.Sprintf("chain/%d", size), func(b *testing.B) { + entities := benchmarkSortFixture("chain", size) + for b.Loop() { + _ = sortEntities(entities) + } + }) + // Fan-out: one pop makes every other entity ready at once, so the + // ready queue grows by O(n) insertions at a single step. + b.Run(fmt.Sprintf("fanout/%d", size), func(b *testing.B) { + entities := benchmarkSortFixture("fanout", size) + for b.Loop() { + _ = sortEntities(entities) + } + }) + // Reverse fan-out: the root unlocks every other entity in descending + // name order, so each binary insert shifts the whole ready slice — the + // quadratic case the min-heap removes. + b.Run(fmt.Sprintf("fanout-reverse/%d", size), func(b *testing.B) { + entities := benchmarkSortFixture("fanout-reverse", size) + for b.Loop() { + _ = sortEntities(entities) + } + }) + } +} + +// TestBenchmarkSortEntitiesGolden pins the order produced by sortEntities and +// the pointer rebinding that goes with it: every relation must point into the +// returned slice, not into the original backing array. +func TestBenchmarkSortEntitiesGolden(t *testing.T) { + lines := make([]string, 0, 9) + for _, size := range []int{100, 500, 2000} { + for _, kind := range []string{"chain", "fanout", "fanout-reverse"} { + sorted := sortEntities(benchmarkSortFixture(kind, size)) + if len(sorted) != size { + t.Fatalf("%s/%d: got %d entities, want %d", kind, size, len(sorted), size) + } + position := make(map[string]int, len(sorted)) + for i := range sorted { + position[sorted[i].Name] = i + } + var entries []string + for i := range sorted { + e := &sorted[i] + if position[e.Name] != i { + t.Errorf("%s/%d: %s at index %d, index map says %d", kind, size, e.Name, i, position[e.Name]) + } + rels := make([]string, 0, len(e.RelationsOut)) + for _, rel := range e.RelationsOut { + target := "" + if rel.TargetEntity != nil { + idx, ok := position[rel.TargetEntity.Name] + if !ok || &sorted[idx] != rel.TargetEntity { + t.Errorf("%s/%d: %s relation points outside the sorted slice", kind, size, e.Name) + } + target = rel.TargetEntity.Name + } + rels = append(rels, fmt.Sprintf("%s->%s", rel.FieldName, target)) + } + slices.Sort(rels) + entries = append(entries, fmt.Sprintf("%s|%s", e.Name, strings.Join(rels, ","))) + } + lines = append(lines, fmt.Sprintf("%s/%d\tentities=%d\tsha256=%s", kind, size, len(sorted), testutil.HashLines(entries))) + } + } + testutil.CheckGolden(t, "sort-entities.golden.txt", strings.Join(lines, "\n"), *updateGolden) +} + +// benchmarkHubSchema builds one hub with N [many] relations to N leaves and a +// single FK from every leaf back to the hub. This exercises the three relation +// reconciliation passes against a single hot target entity. +func benchmarkHubSchema(n int) *parser.ParsedSchema { + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Hub"}, + Entities: make(map[string]*parser.ParsedEntity, n+1), + EntityOrder: make([]string, 0, n+1), + } + hub := &parser.ParsedEntity{ + Name: "Hub", + NamePlural: "Hubs", + Fields: make(map[string]*parser.ParsedField, n+1), + FieldOrder: make([]string, 0, n+1), + } + hub.Fields["id"] = &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{Name: "id", Type: "uuid", IsPrimary: true}} + hub.FieldOrder = append(hub.FieldOrder, "id") + for i := range n { + leaf := fmt.Sprintf("Leaf%04d", i) + hub.Fields[leaf] = &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{ + Name: leaf, Type: "relation", TargetEntity: leaf, IsMany: true, + }} + hub.FieldOrder = append(hub.FieldOrder, leaf) + schema.Entities[leaf] = &parser.ParsedEntity{ + Name: leaf, + NamePlural: leaf + "s", + Fields: map[string]*parser.ParsedField{ + "id": {FieldDefinition: &lexer.FieldDefinition{Name: "id", Type: "uuid", IsPrimary: true}}, + "hub": {FieldDefinition: &lexer.FieldDefinition{ + Name: "hub", Type: "relation", TargetEntity: "Hub", + }}, + }, + FieldOrder: []string{"id", "hub"}, + } + schema.EntityOrder = append(schema.EntityOrder, leaf) + } + schema.Entities["Hub"] = hub + schema.EntityOrder = append([]string{"Hub"}, schema.EntityOrder...) + return schema +} + +func BenchmarkBuildHubRelations(b *testing.B) { + for _, size := range []int{100, 500, 2000} { + b.Run(fmt.Sprintf("entities=%d", size), func(b *testing.B) { + schema := benchmarkHubSchema(size) + for b.Loop() { + if _, err := Build(schema); err != nil { + b.Fatal(err) + } + } + }) + } +} + +// hubIRDigest serializes the built IR into canonical sorted lines. Fields, +// relation types, pair hints and target names are all covered by the digest; +// map iteration is limited to slices.Sorted(maps.Keys(...)). +func hubIRDigest(t *testing.T, project *Project) string { + t.Helper() + byName := make(map[string]*Entity, len(project.Entities)) + for i := range project.Entities { + byName[project.Entities[i].Name] = &project.Entities[i] + } + var lines []string + for _, name := range slices.Sorted(maps.Keys(byName)) { + e := byName[name] + fields := make([]string, 0, len(e.Fields)) + for _, f := range e.Fields { + fields = append(fields, fmt.Sprintf("%s:%s:pk=%t:relation=%t", f.Name, f.DatabaseType, f.IsPrimary, f.IsRelation)) + } + slices.Sort(fields) + lines = append(lines, fmt.Sprintf("entity\t%s\tfields=[%s]", name, strings.Join(fields, ","))) + for _, side := range []struct { + label string + rels []Relation + }{ + {label: "out", rels: e.RelationsOut}, + {label: "in", rels: e.RelationsIn}, + } { + rels := make([]string, 0, len(side.rels)) + for _, rel := range side.rels { + target := "" + if rel.TargetEntity != nil { + if _, ok := byName[rel.TargetEntity.Name]; !ok { + t.Errorf("%s %s relation target %q is not in the project", name, side.label, rel.TargetEntity.Name) + } + target = rel.TargetEntity.Name + } + rels = append(rels, fmt.Sprintf("%s->%s:type=%s:pair=%s:inverse=%s:many=%t:nav=%s", + rel.FieldName, target, rel.RelationType, rel.PairFieldName, rel.InverseNavName, rel.IsMany, rel.NavigationName)) + } + slices.Sort(rels) + lines = append(lines, fmt.Sprintf("%s\t%s\trels=[%s]", side.label, name, strings.Join(rels, ","))) + } + } + slices.Sort(lines) + return testutil.HashLines(lines) +} + +// TestBenchmarkBuildHubRelationsGolden pins the relation reconciliation on the +// same hub fixture the benchmark builds: one [many] field per leaf paired with +// the leaf's FK, without an extra inverse collection. +func TestBenchmarkBuildHubRelationsGolden(t *testing.T) { + lines := make([]string, 0, 3) + for _, size := range []int{100, 500, 2000} { + project, err := Build(benchmarkHubSchema(size)) + if err != nil { + t.Fatalf("Build(size=%d): %v", size, err) + } + lines = append(lines, fmt.Sprintf("entities=%d\tir=%d\tsha256=%s", size, len(project.Entities), hubIRDigest(t, project))) + } + testutil.CheckGolden(t, "build-hub-relations.golden.txt", strings.Join(lines, "\n"), *updateGolden) +} + +// TestBuildHubRelationsPreservesFirstMatch guards the hub case while the +// per-target linear scans are replaced with indexed lookups. Each leaf's FK is +// paired with the hub's [many] field; no duplicate inverse collection is built. +func TestBuildHubRelationsPreservesFirstMatch(t *testing.T) { + const leaves = 8 + project, err := Build(benchmarkHubSchema(leaves)) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + + var hub *Entity + for i := range project.Entities { + if project.Entities[i].Name == "Hub" { + hub = &project.Entities[i] + break + } + } + if hub == nil { + t.Fatal("Hub entity missing from IR") + } + if len(hub.RelationsOut) != leaves { // id is scalar; all other fields are [many] + t.Fatalf("Hub has %d outgoing relations, want %d", len(hub.RelationsOut), leaves) + } + if len(hub.RelationsIn) != 0 { + t.Errorf("Hub has %d incoming relations, want 0 (paired FKs must not add collections)", len(hub.RelationsIn)) + } + for i, rel := range hub.RelationsOut { + if rel.RelationType != "one-to-many" { + t.Errorf("hub relation %d type = %q, want one-to-many", i, rel.RelationType) + } + if rel.TargetEntity == nil { + t.Errorf("hub relation %d has no target", i) + continue + } + if rel.PairFieldName != "hub" { + t.Errorf("hub relation %d pair field = %q, want hub", i, rel.PairFieldName) + } + } + + for i := range project.Entities { + e := &project.Entities[i] + if e.Name == "Hub" { + continue + } + if len(e.RelationsOut) != 1 { + t.Fatalf("%s has %d outgoing relations, want 1", e.Name, len(e.RelationsOut)) + } + rel := e.RelationsOut[0] + if rel.InverseNavName != e.Name { + t.Errorf("%s inverse nav = %q, want %q", e.Name, rel.InverseNavName, e.Name) + } + if rel.IsMany { + t.Errorf("%s FK relation is many", e.Name) + } + } +} diff --git a/internal/ir/build_relations_test.go b/internal/ir/build_relations_test.go new file mode 100644 index 0000000..6d4d311 --- /dev/null +++ b/internal/ir/build_relations_test.go @@ -0,0 +1,95 @@ +package ir + +import ( + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/validator" +) + +func TestReconciliationRuleAgreesAcrossValidatorAndIR(t *testing.T) { + t.Parallel() + cases := []struct { + name string + backFields string + wantPair string + wantWarnKey string + }{ + { + name: "single FK back reconciles", + backFields: "\n order: relation(Order)", + wantPair: "order", + wantWarnKey: "is reconciled with FK 'order'", + }, + { + name: "many back stays many-to-many", + backFields: "\n orders: relation(Order) [many]", + }, + { + name: "single FK to another entity stays separate", + backFields: "\n company: relation(Company)", + }, + { + name: "no back relation", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test +entities: + Company: + fields: + id: uuid [primary] + Order: + fields: + id: uuid [primary] + items: relation(User) [many] + User: + fields: + id: uuid [primary]` + c.backFields + "\n") + schema, err := parser.ParseYAML(yamlData) + if err != nil { + t.Fatalf("ParseYAML() error = %v", err) + } + + warned := false + for _, e := range validator.New(schema).Validate() { + if e.Field == "items" && strings.Contains(e.Message, c.wantWarnKey) && c.wantWarnKey != "" { + warned = true + } + } + + project, err := Build(schema) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + var rel *Relation + for i := range project.Entities { + if project.Entities[i].Name != "Order" { + continue + } + for j := range project.Entities[i].RelationsOut { + candidate := &project.Entities[i].RelationsOut[j] + if candidate.FieldName == "items" { + rel = candidate + } + } + } + if rel == nil { + t.Fatal("Order.items relation not built") + } + paired := rel.RelationType == "one-to-many" + + if warned != paired { + t.Fatalf("validator reconciled = %t, IR reconciled = %t — rule drift", warned, paired) + } + if paired && rel.PairFieldName != c.wantPair { + t.Errorf("PairFieldName = %q, want %q", rel.PairFieldName, c.wantPair) + } + }) + } +} diff --git a/internal/ir/contract_test.go b/internal/ir/contract_test.go index 88a1ef4..9a8fa7e 100644 --- a/internal/ir/contract_test.go +++ b/internal/ir/contract_test.go @@ -1,12 +1,16 @@ package ir -import "testing" +import ( + "slices" + "testing" +) func TestValidationRules(t *testing.T) { - f := IRField{ + t.Parallel() + f := Field{ Name: "email", DatabaseType: "string", - Validations: []IRValidation{ + Validations: []Validation{ {Name: "email", Value: "true"}, {Name: "min", Value: "3"}, {Name: "max", Value: "50"}, @@ -32,11 +36,63 @@ func TestValidationRules(t *testing.T) { } } +// TestValidationRulesSemanticOrder pins the declared rule order: +// format → length bounds → numeric bounds, regardless of modifier order. +func TestValidationRulesSemanticOrder(t *testing.T) { + t.Parallel() + validations := []Validation{ + {Name: "gte", Value: "1"}, + {Name: "regex", Value: "^[a-z]+$"}, + {Name: "max_length", Value: "50"}, + {Name: "min_length", Value: "3"}, + {Name: "email"}, + } + reversed := []Validation{ + {Name: "email"}, + {Name: "min_length", Value: "3"}, + {Name: "max_length", Value: "50"}, + {Name: "regex", Value: "^[a-z]+$"}, + {Name: "gte", Value: "1"}, + } + want := []string{"email", "regex", "min_length", "max_length", "min_value"} + + for _, tc := range []struct { + name string + in []Validation + }{ + {"declared", validations}, + {"reversed", reversed}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + f := Field{Name: "contact", DatabaseType: "string", IsNullable: true, Validations: tc.in} + rules := f.ValidationRules() + if len(rules) != len(want) { + t.Fatalf("ValidationRules() = %d rules (%+v), want %d", len(rules), rules, len(want)) + } + for i, kind := range want { + if rules[i].Kind != kind { + t.Errorf("rule %d kind = %q, want %q (all kinds: %+v)", i, rules[i].Kind, kind, ruleKinds(rules)) + } + } + }) + } +} + +func ruleKinds(rules []ValidationRule) []string { + kinds := make([]string, 0, len(rules)) + for _, r := range rules { + kinds = append(kinds, r.Kind) + } + return kinds +} + func TestValidationRulesNumericBounds(t *testing.T) { - f := IRField{ + t.Parallel() + f := Field{ Name: "qty", DatabaseType: "int", - Validations: []IRValidation{ + Validations: []Validation{ {Name: "gte", Value: "10"}, {Name: "lte", Value: "20"}, }, @@ -51,38 +107,43 @@ func TestValidationRulesNumericBounds(t *testing.T) { } func TestValidationRulesCodesAndMessages(t *testing.T) { + t.Parallel() cases := []struct { name string - field IRField + field Field wantCode string wantMsg string }{ - {"required", IRField{Name: "title", DatabaseType: "string"}, "REQUIRED", "is required"}, - {"email", IRField{Name: "email", DatabaseType: "string", IsNullable: true, Validations: []IRValidation{{Name: "email"}}}, "EMAIL", "must be a valid email address"}, - {"min_length", IRField{Name: "name", DatabaseType: "string", Validations: []IRValidation{{Name: "min", Value: "3"}}}, "MIN_LENGTH", "must be at least 3 characters"}, - {"min_value", IRField{Name: "qty", DatabaseType: "int", Validations: []IRValidation{{Name: "gte", Value: "10"}}}, "MIN_VALUE", "must be greater than or equal to 10"}, - {"exclusive min_value", IRField{Name: "qty", DatabaseType: "int", Validations: []IRValidation{{Name: "gt", Value: "0"}}}, "MIN_VALUE", "must be greater than 0"}, - {"exclusive max_value", IRField{Name: "rating", DatabaseType: "int", Validations: []IRValidation{{Name: "lt", Value: "6"}}}, "MAX_VALUE", "must be less than 6"}, + {"required", Field{Name: "title", DatabaseType: "string"}, "REQUIRED", "is required"}, + {"email", Field{Name: "email", DatabaseType: "string", IsNullable: true, Validations: []Validation{{Name: "email"}}}, "EMAIL", "must be a valid email address"}, + {"min_length", Field{Name: "name", DatabaseType: "string", Validations: []Validation{{Name: "min", Value: "3"}}}, "MIN_LENGTH", "must be at least 3 characters"}, + {"min_value", Field{Name: "qty", DatabaseType: "int", Validations: []Validation{{Name: "gte", Value: "10"}}}, "MIN_VALUE", "must be greater than or equal to 10"}, + {"exclusive min_value", Field{Name: "qty", DatabaseType: "int", Validations: []Validation{{Name: "gt", Value: "0"}}}, "MIN_VALUE", "must be greater than 0"}, + {"exclusive max_value", Field{Name: "rating", DatabaseType: "int", Validations: []Validation{{Name: "lt", Value: "6"}}}, "MAX_VALUE", "must be less than 6"}, } for _, c := range cases { - rules := c.field.ValidationRules() - found := false - for _, r := range rules { - if r.Code == c.wantCode { - found = true - if r.Message != c.wantMsg { - t.Errorf("%s: message = %q, want %q", c.name, r.Message, c.wantMsg) + t.Run(c.name, func(t *testing.T) { + t.Parallel() + rules := c.field.ValidationRules() + found := false + for _, r := range rules { + if r.Code == c.wantCode { + found = true + if r.Message != c.wantMsg { + t.Errorf("%s: message = %q, want %q", c.name, r.Message, c.wantMsg) + } } } - } - if !found { - t.Errorf("%s: rule with code %q not found in %+v", c.name, c.wantCode, rules) - } + if !found { + t.Errorf("%s: rule with code %q not found in %+v", c.name, c.wantCode, rules) + } + }) } } func TestValidationRulesNullableNotRequired(t *testing.T) { - f := IRField{Name: "nick", DatabaseType: "string", IsNullable: true} + t.Parallel() + f := Field{Name: "nick", DatabaseType: "string", IsNullable: true} for _, r := range f.ValidationRules() { if r.Kind == "required" { t.Error("nullable field should not be required") @@ -91,15 +152,16 @@ func TestValidationRulesNullableNotRequired(t *testing.T) { } func TestAllIndexesMergesUniqueFields(t *testing.T) { - e := IREntity{ + t.Parallel() + e := Entity{ Name: "Order", NamePlural: "Orders", - Fields: []IRField{ + Fields: []Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "sku", DatabaseType: "string", IsUnique: true}, {Name: "ref", DatabaseType: "string"}, }, - Indexes: []IRIndex{ + Indexes: []Index{ {Name: "idx_orders_ref", Fields: []string{"ref"}, Sort: []string{"asc"}, Unique: false}, }, } @@ -125,11 +187,12 @@ func TestAllIndexesMergesUniqueFields(t *testing.T) { } func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { - e := IREntity{ + t.Parallel() + e := Entity{ Name: "Order", NamePlural: "Orders", - Fields: []IRField{{Name: "sku", DatabaseType: "string", IsUnique: true}}, - Indexes: []IRIndex{{Name: "ix_custom", Fields: []string{"sku"}, Unique: true}}, + Fields: []Field{{Name: "sku", DatabaseType: "string", IsUnique: true}}, + Indexes: []Index{{Name: "ix_custom", Fields: []string{"sku"}, Unique: true}}, } got := e.AllIndexes() if len(got) != 1 { @@ -141,7 +204,8 @@ func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { } func TestPermissionPlan(t *testing.T) { - p := &IRPermissions{ + t.Parallel() + p := &Permissions{ Read: []string{"*"}, Create: []string{"Admin", "@Owner"}, Update: []string{}, @@ -169,20 +233,22 @@ func TestPermissionPlan(t *testing.T) { } func TestPermissionPlanNil(t *testing.T) { - var p *IRPermissions + t.Parallel() + var p *Permissions if p.Plan("read") != nil { t.Error("nil permissions should yield nil plan") } } func TestEndpointsContract(t *testing.T) { - e := IREntity{Name: "Order", NamePlural: "Orders", Features: map[string]bool{"optimistic_lock": true}} + t.Parallel() + e := Entity{Name: "Order", NamePlural: "Orders", Features: map[string]bool{"optimistic_lock": true}} eps := e.Endpoints() if len(eps) != 6 { t.Fatalf("got %d endpoints, want 6", len(eps)) } - byOp := map[string]IREndpoint{} + byOp := map[string]Endpoint{} for _, ep := range eps { byOp[ep.Operation] = ep } @@ -198,7 +264,7 @@ func TestEndpointsContract(t *testing.T) { } update := byOp["update"] - if !update.Concurrency || !update.HasStatus(409) { + if !update.Concurrency || !slices.Contains(update.ErrorStatuses, 409) { t.Errorf("update should allow 409 with optimistic lock: %+v", update) } @@ -209,18 +275,20 @@ func TestEndpointsContract(t *testing.T) { } func TestIREntity_PrimaryKey(t *testing.T) { - e := IREntity{Fields: []IRField{{Name: "name"}, {Name: "id", IsPrimary: true}}} + t.Parallel() + e := Entity{Fields: []Field{{Name: "name"}, {Name: "id", IsPrimary: true}}} pk := e.PrimaryKey() if pk == nil || pk.Name != "id" { t.Errorf("PrimaryKey() = %v, want id", pk) } - if (IREntity{Fields: []IRField{{Name: "name"}}}).PrimaryKey() != nil { + if (Entity{Fields: []Field{{Name: "name"}}}).PrimaryKey() != nil { t.Error("no primary key should yield nil") } } func TestIREntity_FieldByName(t *testing.T) { - e := IREntity{Fields: []IRField{{Name: "firstName"}, {Name: "ID"}}} + t.Parallel() + e := Entity{Fields: []Field{{Name: "firstName"}, {Name: "ID"}}} if f := e.FieldByName("FirstName"); f == nil || f.Name != "firstName" { t.Errorf("FieldByName(FirstName) = %v, want firstName (case-insensitive)", f) } @@ -232,15 +300,16 @@ func TestIREntity_FieldByName(t *testing.T) { } } -func TestIRProject_AuthEntity(t *testing.T) { - p := &IRProject{ - Auth: &IRAuthConfig{Type: "jwt", Entity: "User"}, - Entities: []IREntity{{Name: "Order"}, {Name: "User"}}, +func TestProject_AuthEntity(t *testing.T) { + t.Parallel() + p := &Project{ + Auth: &AuthConfig{Type: "jwt", Entity: "User"}, + Entities: []Entity{{Name: "Order"}, {Name: "User"}}, } if e := p.AuthEntity(); e == nil || e.Name != "User" { t.Errorf("AuthEntity() = %v, want User", e) } - if (&IRProject{}).AuthEntity() != nil { + if (&Project{}).AuthEntity() != nil { t.Error("no-auth project should yield nil AuthEntity") } // AuthEntity resolves by the configured auth entity NAME. @@ -251,23 +320,25 @@ func TestIRProject_AuthEntity(t *testing.T) { } func TestIRPermissions_HasOwnerToken(t *testing.T) { - if (&IRPermissions{Read: []string{"Admin"}, Create: []string{"*"}}).HasOwnerToken() { + t.Parallel() + if (&Permissions{Read: []string{"Admin"}, Create: []string{"*"}}).HasOwnerToken() { t.Error("no @Owner token should yield false") } - if !(&IRPermissions{Update: []string{"@Owner"}}).HasOwnerToken() { + if !(&Permissions{Update: []string{"@Owner"}}).HasOwnerToken() { t.Error("any op with @Owner should yield true") } - var nilP *IRPermissions + var nilP *Permissions if nilP.HasOwnerToken() { t.Error("nil permissions should yield false") } } func TestAuthEndpoints(t *testing.T) { - p := &IRProject{Auth: &IRAuthConfig{ + t.Parallel() + p := &Project{Auth: &AuthConfig{ Type: "jwt", Entity: "User", - Endpoints: IRAuthEndpoints{ + Endpoints: AuthEndpoints{ HasLogin: true, HasRegister: true, HasMe: true, HasSetup: true, }, }} @@ -283,7 +354,7 @@ func TestAuthEndpoints(t *testing.T) { t.Error("/login must be anonymous") } } - if got := (&IRProject{}).AuthEndpoints(); got != nil { + if got := (&Project{}).AuthEndpoints(); got != nil { t.Error("no-auth project should yield nil auth endpoints") } } diff --git a/internal/ir/dto.go b/internal/ir/dto.go index 9381945..738c972 100644 --- a/internal/ir/dto.go +++ b/internal/ir/dto.go @@ -1,16 +1,24 @@ package ir import ( + "slices" "strings" "github.com/DomainCraft/DomainCraft/internal/specmeta" ) +// cloneField detaches a field's validation slice so mutating a DTO field cannot +// silently change the entity field it was projected from. +func cloneField(f Field) Field { + f.Validations = slices.Clone(f.Validations) + return f +} + // IsSensitive reports whether the field holds credentials that must never be // serialized into a response DTO (currently: a field literally named "password"). // Sensitive fields are also excluded from the generic create/update projections // — the auth flow handles them explicitly (hashing on write, never returning). -func (f IRField) IsSensitive() bool { +func (f Field) IsSensitive() bool { return strings.EqualFold(f.Name, "password") } @@ -18,7 +26,7 @@ func (f IRField) IsSensitive() bool { // (audit, audit_log, soft_delete, optimistic_lock, ...). Feature fields are // server-managed: they are returned in read projections but never accepted from // a client in a create request. -func (f IRField) IsFeatureField() bool { +func (f Field) IsFeatureField() bool { _, ok := specmeta.FeatureFieldDefs[f.Name] return ok } @@ -27,60 +35,60 @@ func (f IRField) IsFeatureField() bool { // token. It is readable and accepted on update (so the client can send the // version it last read) but is never copied from the request body into the // entity — the server owns the increment. -func (f IRField) IsConcurrencyToken() bool { +func (f Field) IsConcurrencyToken() bool { return f.IsFeatureField() && f.Name == "version" } -// ReadFields returns the fields exposed in a read (response) DTO: every field -// except hidden and sensitive ones. Primary, readonly and feature fields are all -// readable. Feature (server-managed) fields are ordered last, after the -// developer-declared fields, so a response DTO reads naturally (identity and -// data first, timestamps and the version token at the end). -func (e IREntity) ReadFields() []IRField { - out := make([]IRField, 0, len(e.Fields)) - var feature []IRField +// projectFields applies one field predicate to all four DTO projections. When +// featureLast is set, server-managed fields move behind developer fields so a +// response reads identity/data first and timestamps/version last. cloneField +// keeps each projection detached from the entity's validation slice. +func (e Entity) projectFields(pred func(Field) bool, featureLast bool) []Field { + out := make([]Field, 0, len(e.Fields)) + var feature []Field for _, f := range e.Fields { - if f.IsHidden || f.IsSensitive() { + if !pred(f) { continue } - if f.IsFeatureField() { - feature = append(feature, f) + if featureLast && f.IsFeatureField() { + feature = append(feature, cloneField(f)) continue } - out = append(out, f) + out = append(out, cloneField(f)) } return append(out, feature...) } +// ReadFields returns the fields exposed in a read (response) DTO: every field +// except hidden and sensitive ones. Primary, readonly and feature fields are all +// readable. Feature (server-managed) fields are ordered last, after the +// developer-declared fields, so a response DTO reads naturally (identity and +// data first, timestamps and the version token at the end). +func (e Entity) ReadFields() []Field { + return e.projectFields(func(f Field) bool { + return !f.IsHidden && !f.IsSensitive() + }, true) +} + // CreateFields returns the fields accepted in a create (request) DTO: primary, // readonly, feature and sensitive fields are excluded. Hidden fields are kept — // they are client-settable, just never returned in responses. -func (e IREntity) CreateFields() []IRField { - out := make([]IRField, 0, len(e.Fields)) - for _, f := range e.Fields { - if f.IsPrimary || f.IsReadonly || f.IsFeatureField() || f.IsSensitive() { - continue - } - out = append(out, f) - } - return out +func (e Entity) CreateFields() []Field { + return e.projectFields(func(f Field) bool { + return !f.IsPrimary && !f.IsReadonly && !f.IsFeatureField() && !f.IsSensitive() + }, false) } // UpdateFields returns the fields accepted in a full update (request) DTO. It // matches CreateFields but additionally exposes the optimistic-lock concurrency // token (version), which the client echoes on update for safe concurrency. -func (e IREntity) UpdateFields() []IRField { - out := make([]IRField, 0, len(e.Fields)) - for _, f := range e.Fields { +func (e Entity) UpdateFields() []Field { + return e.projectFields(func(f Field) bool { if f.IsPrimary || f.IsReadonly || f.IsSensitive() { - continue + return false } - if f.IsFeatureField() && !f.IsConcurrencyToken() { - continue - } - out = append(out, f) - } - return out + return !f.IsFeatureField() || f.IsConcurrencyToken() + }, false) } // PatchFields returns the fields accepted in a merge-patch (PATCH) request body: @@ -89,12 +97,8 @@ func (e IREntity) UpdateFields() []IRField { // which the client echoes on patch for safe concurrency. Arrays, enums, JSON // blobs and collections are intentionally absent, mirroring the server's // ApplyPatch eligibility. -func (e IREntity) PatchFields() []IRField { - out := make([]IRField, 0, len(e.Fields)) - for _, f := range e.Fields { - if f.IsPatchable() || f.IsConcurrencyToken() { - out = append(out, f) - } - } - return out +func (e Entity) PatchFields() []Field { + return e.projectFields(func(f Field) bool { + return f.IsPatchable() || f.IsConcurrencyToken() + }, false) } diff --git a/internal/ir/dto_test.go b/internal/ir/dto_test.go index 07555b4..95468b6 100644 --- a/internal/ir/dto_test.go +++ b/internal/ir/dto_test.go @@ -2,11 +2,12 @@ package ir import "testing" -func entityWithFields(fields ...IRField) IREntity { - return IREntity{Name: "Order", Fields: fields} +func entityWithFields(fields ...Field) Entity { + return Entity{Name: "Order", Fields: fields} } func TestIRField_IsSensitive(t *testing.T) { + t.Parallel() cases := []struct { name string want bool @@ -18,42 +19,48 @@ func TestIRField_IsSensitive(t *testing.T) { {"email", false}, } for _, tc := range cases { - f := IRField{Name: tc.name} - if got := f.IsSensitive(); got != tc.want { - t.Errorf("IsSensitive(%q) = %v, want %v", tc.name, got, tc.want) - } + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + f := Field{Name: tc.name} + if got := f.IsSensitive(); got != tc.want { + t.Errorf("IsSensitive(%q) = %v, want %v", tc.name, got, tc.want) + } + }) } } func TestIRField_IsFeatureField(t *testing.T) { - if !(IRField{Name: "createdAt"}).IsFeatureField() { + t.Parallel() + if !(Field{Name: "createdAt"}).IsFeatureField() { t.Error("createdAt should be a feature field") } - if !(IRField{Name: "version"}).IsFeatureField() { + if !(Field{Name: "version"}).IsFeatureField() { t.Error("version should be a feature field") } - if (IRField{Name: "title"}).IsFeatureField() { + if (Field{Name: "title"}).IsFeatureField() { t.Error("title should not be a feature field") } } func TestIRField_IsConcurrencyToken(t *testing.T) { - if !(IRField{Name: "version"}).IsConcurrencyToken() { + t.Parallel() + if !(Field{Name: "version"}).IsConcurrencyToken() { t.Error("version should be a concurrency token") } - if (IRField{Name: "createdAt"}).IsConcurrencyToken() { + if (Field{Name: "createdAt"}).IsConcurrencyToken() { t.Error("createdAt should not be a concurrency token") } } func TestIREntity_ReadFields(t *testing.T) { + t.Parallel() e := entityWithFields( - IRField{Name: "id", IsPrimary: true, DatabaseType: "uuid"}, - IRField{Name: "title", DatabaseType: "string"}, - IRField{Name: "password", DatabaseType: "string"}, // sensitive -> excluded - IRField{Name: "internalNotes", IsHidden: true}, // hidden -> excluded - IRField{Name: "balance", IsReadonly: true}, // readonly -> readable - IRField{Name: "createdAt", DatabaseType: "datetime"}, // feature -> readable + Field{Name: "id", IsPrimary: true, DatabaseType: "uuid"}, + Field{Name: "title", DatabaseType: "string"}, + Field{Name: "password", DatabaseType: "string"}, // sensitive -> excluded + Field{Name: "internalNotes", IsHidden: true}, // hidden -> excluded + Field{Name: "balance", IsReadonly: true}, // readonly -> readable + Field{Name: "createdAt", DatabaseType: "datetime"}, // feature -> readable ) got := e.ReadFields() if len(got) != 4 { @@ -67,13 +74,14 @@ func TestIREntity_ReadFields(t *testing.T) { } func TestIREntity_CreateFields(t *testing.T) { + t.Parallel() e := entityWithFields( - IRField{Name: "id", IsPrimary: true}, - IRField{Name: "title", DatabaseType: "string"}, - IRField{Name: "password", DatabaseType: "string"}, - IRField{Name: "balance", IsReadonly: true}, - IRField{Name: "createdAt", DatabaseType: "datetime"}, - IRField{Name: "internalNotes", IsHidden: true}, // hidden but client-settable -> kept + Field{Name: "id", IsPrimary: true}, + Field{Name: "title", DatabaseType: "string"}, + Field{Name: "password", DatabaseType: "string"}, + Field{Name: "balance", IsReadonly: true}, + Field{Name: "createdAt", DatabaseType: "datetime"}, + Field{Name: "internalNotes", IsHidden: true}, // hidden but client-settable -> kept ) got := e.CreateFields() if len(got) != 2 { @@ -87,11 +95,12 @@ func TestIREntity_CreateFields(t *testing.T) { } func TestIREntity_UpdateFieldsIncludesVersion(t *testing.T) { + t.Parallel() e := entityWithFields( - IRField{Name: "id", IsPrimary: true}, - IRField{Name: "title", DatabaseType: "string"}, - IRField{Name: "createdAt", DatabaseType: "datetime"}, // feature -> excluded - IRField{Name: "version", DatabaseType: "int"}, // concurrency token -> kept + Field{Name: "id", IsPrimary: true}, + Field{Name: "title", DatabaseType: "string"}, + Field{Name: "createdAt", DatabaseType: "datetime"}, // feature -> excluded + Field{Name: "version", DatabaseType: "int"}, // concurrency token -> kept ) got := e.UpdateFields() if len(got) != 2 { @@ -112,17 +121,18 @@ func TestIREntity_UpdateFieldsIncludesVersion(t *testing.T) { } func TestIREntity_PatchFields(t *testing.T) { + t.Parallel() e := entityWithFields( - IRField{Name: "id", IsPrimary: true}, - IRField{Name: "title", DatabaseType: "string"}, // scalar -> patchable - IRField{Name: "categoryId", DatabaseType: "uuid", IsRelation: true}, // single FK -> patchable - IRField{Name: "tags", DatabaseType: "array(string)"}, // array -> excluded - IRField{Name: "status", DatabaseType: "OrderStatus"}, // enum -> excluded - IRField{Name: "meta", DatabaseType: "jsonb"}, // json -> excluded - IRField{Name: "password", DatabaseType: "string"}, // sensitive -> excluded - IRField{Name: "balance", IsReadonly: true}, // readonly -> excluded - IRField{Name: "createdAt", DatabaseType: "datetime"}, // feature -> excluded - IRField{Name: "version", DatabaseType: "int"}, // concurrency token -> kept + Field{Name: "id", IsPrimary: true}, + Field{Name: "title", DatabaseType: "string"}, // scalar -> patchable + Field{Name: "categoryId", DatabaseType: "uuid", IsRelation: true}, // single FK -> patchable + Field{Name: "tags", DatabaseType: "array(string)"}, // array -> excluded + Field{Name: "status", DatabaseType: "OrderStatus"}, // enum -> excluded + Field{Name: "meta", DatabaseType: "jsonb"}, // json -> excluded + Field{Name: "password", DatabaseType: "string"}, // sensitive -> excluded + Field{Name: "balance", IsReadonly: true}, // readonly -> excluded + Field{Name: "createdAt", DatabaseType: "datetime"}, // feature -> excluded + Field{Name: "version", DatabaseType: "int"}, // concurrency token -> kept ) got := e.PatchFields() want := []string{"title", "categoryId", "version"} @@ -137,10 +147,11 @@ func TestIREntity_PatchFields(t *testing.T) { } func TestIREntity_PatchFieldsNoVersionWithoutLock(t *testing.T) { + t.Parallel() e := entityWithFields( - IRField{Name: "id", IsPrimary: true}, - IRField{Name: "title", DatabaseType: "string"}, - IRField{Name: "createdAt", DatabaseType: "datetime"}, // no version field declared + Field{Name: "id", IsPrimary: true}, + Field{Name: "title", DatabaseType: "string"}, + Field{Name: "createdAt", DatabaseType: "datetime"}, // no version field declared ) got := e.PatchFields() if len(got) != 1 || got[0].Name != "title" { @@ -148,7 +159,46 @@ func TestIREntity_PatchFieldsNoVersionWithoutLock(t *testing.T) { } } -func names(fields []IRField) []string { +func TestDTOFieldsDoNotShareValidations(t *testing.T) { + t.Parallel() + e := entityWithFields( + Field{Name: "title", DatabaseType: "string", Validations: []Validation{{Name: "max", Value: "255"}}}, + Field{Name: "version", DatabaseType: "int", Validations: []Validation{{Name: "min", Value: "1"}}}, + ) + + projections := []struct { + name string + fields []Field + }{ + {"read", e.ReadFields()}, + {"create", e.CreateFields()}, + {"update", e.UpdateFields()}, + {"patch", e.PatchFields()}, + } + for _, tc := range projections { + t.Run(tc.name, func(t *testing.T) { + for i := range tc.fields { + if len(tc.fields[i].Validations) > 0 { + tc.fields[i].Validations[0].Value = "mutated" + } + } + for _, f := range e.Fields { + if len(f.Validations) == 0 { + continue + } + want := "255" + if f.Name == "version" { + want = "1" + } + if f.Validations[0].Value != want { + t.Errorf("source field %q validation mutated to %q, want %q", f.Name, f.Validations[0].Value, want) + } + } + }) + } +} + +func names(fields []Field) []string { out := make([]string, len(fields)) for i, f := range fields { out[i] = f.Name diff --git a/internal/ir/endpoints.go b/internal/ir/endpoints.go index 4cb8d0e..6996db4 100644 --- a/internal/ir/endpoints.go +++ b/internal/ir/endpoints.go @@ -5,12 +5,12 @@ import ( "strings" ) -// IREndpoint describes one HTTP endpoint in the standard REST contract that the +// Endpoint describes one HTTP endpoint in the standard REST contract that the // core derives from the entity. The bridge renders the body of each endpoint // from this map — the HTTP method, route, success status, possible error // statuses and the authorization plan all come pre-computed, so a bridge only // translates them into its own framework syntax. -type IREndpoint struct { +type Endpoint struct { Method string // GET | POST | PUT | PATCH | DELETE Path string // route template relative to the API root (e.g. "api/orders/{id}") Operation string // list | get | create | update | patch | delete @@ -22,17 +22,20 @@ type IREndpoint struct { ErrorStatuses []int // Auth is the authorization plan, or nil when the entity declares no // permissions (the bridge then applies its "no permissions" default). - Auth *IRPermissionPlan + Auth *PermissionPlan // Paginated is true for the collection (list) endpoint. Paginated bool // Concurrency is true when a 409 conflict is possible (optimistic locking). Concurrency bool + // Anonymous is true for project-level endpoints that need no credentials + // (auth login/register/setup). Entity endpoints always carry an Auth plan. + Anonymous bool } // AuthPolicy returns the authorization policy name for the endpoint's operation // (Read/Create/Update/Delete), matching the policy names a bridge registers for // `[Authorize(Policy = ...)]`-style checks. -func (e IREndpoint) AuthPolicy() string { +func (e Endpoint) AuthPolicy() string { switch e.Operation { case "list", "get": return "Read" @@ -46,22 +49,9 @@ func (e IREndpoint) AuthPolicy() string { return "" } -// HasStatus reports whether status is among the endpoint's possible statuses. -func (e IREndpoint) HasStatus(status int) bool { - if e.SuccessStatus == status { - return true - } - for _, s := range e.ErrorStatuses { - if s == status { - return true - } - } - return false -} - // Endpoints returns the standard REST endpoint contract for the entity, in a // stable order (list, get, create, update, patch, delete). -func (e IREntity) Endpoints() []IREndpoint { +func (e Entity) Endpoints() []Endpoint { plural := e.NamePlural if plural == "" { plural = e.Name @@ -76,93 +66,83 @@ func (e IREntity) Endpoints() []IREndpoint { slices.Sort(updateErrors) } - eps := []IREndpoint{ - { - Method: "GET", Path: base, Operation: "list", - HasBody: false, SuccessStatus: 200, - ErrorStatuses: common, Auth: e.PermissionPlan("read"), - Paginated: true, Concurrency: false, - }, - { - Method: "GET", Path: base + "/{id}", Operation: "get", - HasBody: false, SuccessStatus: 200, - ErrorStatuses: getErrors, Auth: e.PermissionPlan("read"), - }, - { - Method: "POST", Path: base, Operation: "create", - HasBody: true, SuccessStatus: 201, - ErrorStatuses: common, Auth: e.PermissionPlan("create"), - }, - { - Method: "PUT", Path: base + "/{id}", Operation: "update", - HasBody: true, SuccessStatus: 200, - ErrorStatuses: updateErrors, Auth: e.PermissionPlan("update"), - Concurrency: e.HasOptimisticLock(), - }, - { - Method: "PATCH", Path: base + "/{id}", Operation: "patch", - HasBody: true, SuccessStatus: 200, - ErrorStatuses: updateErrors, Auth: e.PermissionPlan("update"), - Concurrency: e.HasOptimisticLock(), - }, - { - Method: "DELETE", Path: base + "/{id}", Operation: "delete", - HasBody: false, SuccessStatus: 204, - ErrorStatuses: getErrors, Auth: e.PermissionPlan("delete"), - }, + // The order of decls is the endpoint contract order; each row is one + // standard REST operation. ErrorStatuses are cloned per endpoint so a + // bridge mutating one route cannot corrupt its sibling. + decls := []struct { + method, operation, suffix, authOperation string + hasBody, paginated, concurrent bool + success int + errors []int + }{ + {method: "GET", operation: "list", authOperation: "read", paginated: true, success: 200, errors: common}, + {method: "GET", operation: "get", suffix: "/{id}", authOperation: "read", success: 200, errors: getErrors}, + {method: "POST", operation: "create", authOperation: "create", hasBody: true, success: 201, errors: common}, + {method: "PUT", operation: "update", suffix: "/{id}", authOperation: "update", hasBody: true, concurrent: true, success: 200, errors: updateErrors}, + {method: "PATCH", operation: "patch", suffix: "/{id}", authOperation: "update", hasBody: true, concurrent: true, success: 200, errors: updateErrors}, + {method: "DELETE", operation: "delete", suffix: "/{id}", authOperation: "delete", success: 204, errors: getErrors}, } - return eps -} -// IREndpointDecl is a project-level endpoint in the contract (e.g. auth -// endpoints). It shares the endpoint shape but lives at the project level. -type IREndpointDecl struct { - Method string - Path string - Operation string - HasBody bool - SuccessStatus int - ErrorStatuses []int - Anonymous bool + eps := make([]Endpoint, 0, len(decls)) + for _, d := range decls { + eps = append(eps, Endpoint{ + Method: d.method, + Path: base + d.suffix, + Operation: d.operation, + HasBody: d.hasBody, + SuccessStatus: d.success, + ErrorStatuses: slices.Clone(d.errors), + Auth: e.PermissionPlan(d.authOperation), + Paginated: d.paginated, + Concurrency: d.concurrent && e.HasOptimisticLock(), + }) + } + return eps } // AuthEndpoints returns the project-level auth endpoint contract (login / -// register / me / setup) when authentication is enabled. -func (p *IRProject) AuthEndpoints() []IREndpointDecl { - if !p.HasAuth() || p.Auth == nil { +// register / me / setup) when authentication is enabled. It shares the same +// Endpoint shape as entity routes; auth endpoints carry no permission plan and +// mark their anonymous routes with Anonymous. +func (p *Project) AuthEndpoints() []Endpoint { + if !p.HasAuth() { return nil } entity := p.Auth.Entity + if entity == "" { + return nil + } base := "api/" + entity - var decls []IREndpointDecl - if p.Auth.Endpoints.HasLogin { - decls = append(decls, IREndpointDecl{ - Method: "POST", Path: base + "/login", Operation: "login", - HasBody: true, SuccessStatus: 200, - ErrorStatuses: []int{400, 401, 429}, Anonymous: true, - }) - } - if p.Auth.Endpoints.HasRegister { - decls = append(decls, IREndpointDecl{ - Method: "POST", Path: base + "/register", Operation: "register", - HasBody: true, SuccessStatus: 201, - ErrorStatuses: []int{400, 409, 429}, Anonymous: true, - }) - } - if p.Auth.Endpoints.HasMe { - decls = append(decls, IREndpointDecl{ - Method: "GET", Path: base + "/me", Operation: "me", - HasBody: false, SuccessStatus: 200, - ErrorStatuses: []int{401, 404, 429}, - }) + // Same shape as entity routes, but no permission plan: anonymous routes are + // marked with Anonymous and /me stays authenticated. + decls := []struct { + enabled bool + method, operation, route string + hasBody, anonymous bool + success int + errors []int + }{ + {p.Auth.Endpoints.HasLogin, "POST", "login", "/login", true, true, 200, []int{400, 401, 429}}, + {p.Auth.Endpoints.HasRegister, "POST", "register", "/register", true, true, 201, []int{400, 409, 429}}, + {p.Auth.Endpoints.HasMe, "GET", "me", "/me", false, false, 200, []int{401, 404, 429}}, + {p.Auth.Endpoints.HasSetup, "POST", "setup", "/setup", true, true, 201, []int{400, 409, 429}}, } - if p.Auth.Endpoints.HasSetup { - decls = append(decls, IREndpointDecl{ - Method: "POST", Path: base + "/setup", Operation: "setup", - HasBody: true, SuccessStatus: 201, - ErrorStatuses: []int{400, 409, 429}, Anonymous: true, + + var endpoints []Endpoint + for _, d := range decls { + if !d.enabled { + continue + } + endpoints = append(endpoints, Endpoint{ + Method: d.method, + Path: base + d.route, + Operation: d.operation, + HasBody: d.hasBody, + SuccessStatus: d.success, + ErrorStatuses: slices.Clone(d.errors), + Anonymous: d.anonymous, }) } - return decls + return endpoints } diff --git a/internal/ir/endpoints_test.go b/internal/ir/endpoints_test.go new file mode 100644 index 0000000..8ab2b21 --- /dev/null +++ b/internal/ir/endpoints_test.go @@ -0,0 +1,43 @@ +package ir + +import ( + "slices" + "testing" +) + +func TestEndpointsDoNotShareErrorStatuses(t *testing.T) { + t.Parallel() + e := Entity{ + Name: "Order", + NamePlural: "Orders", + Features: map[string]bool{"optimistic_lock": true}, + } + eps := e.Endpoints() + if len(eps) != 6 { + t.Fatalf("got %d endpoints, want 6", len(eps)) + } + + // list/create share `common`, get/delete share `getErrors`, + // update/patch share `updateErrors` (which includes 409 with the lock on). + idx := make(map[string]int, len(eps)) + for i, ep := range eps { + idx[ep.Operation] = i + } + if len(idx) != len(eps) { + t.Fatalf("duplicate endpoint operation in %+v", eps) + } + snapshot := make([][]int, len(eps)) + for i := range eps { + snapshot[i] = slices.Clone(eps[i].ErrorStatuses) + } + for _, pair := range [][2]string{{"list", "create"}, {"get", "delete"}, {"update", "patch"}} { + mutated, sibling := idx[pair[0]], idx[pair[1]] + eps[mutated].ErrorStatuses[0] = -1 + eps[mutated].ErrorStatuses = append(eps[mutated].ErrorStatuses, -2) + + if !slices.Equal(eps[sibling].ErrorStatuses, snapshot[sibling]) { + t.Errorf("endpoint %q shares ErrorStatuses with %q: got %v, want %v", + pair[0], pair[1], eps[sibling].ErrorStatuses, snapshot[sibling]) + } + } +} diff --git a/internal/ir/enums.go b/internal/ir/enums.go index d31bc40..3d60f98 100644 --- a/internal/ir/enums.go +++ b/internal/ir/enums.go @@ -2,13 +2,13 @@ package ir import "github.com/DomainCraft/DomainCraft/pkg/textutil" -// IREnumValue is one enum value plus its stable, language-agnostic wire form. +// EnumValue is one enum value plus its stable, language-agnostic wire form. // The wire value (snake_case) is the contract representation of the value: it is // what the API serializes, what filters match, and what a bridge stores. Bridges // print .WireValue instead of re-deriving snake_case themselves — the template // `snakecase` diverges from textutil.ToDatabaseColumnName on acronyms (e.g. // `IPv4`), so the wire form must be computed once, in the core. -type IREnumValue struct { +type EnumValue struct { // Name is the raw value as declared in domain.yaml (e.g. "IN_PROGRESS"). Name string // WireValue is the canonical snake_case contract value (e.g. "in_progress"). @@ -20,7 +20,7 @@ type IREnumValue struct { // EnumValues returns the enum's values in declaration order, each carrying its // canonical wire value. Bridges iterate this instead of reading Project.Enums[name] // and re-deriving snake_case for the wire representation. -func (p *IRProject) EnumValues(name string) []IREnumValue { +func (p *Project) EnumValues(name string) []EnumValue { if p == nil || p.Enums == nil { return nil } @@ -28,9 +28,9 @@ func (p *IRProject) EnumValues(name string) []IREnumValue { if values == nil { return nil } - out := make([]IREnumValue, 0, len(values)) + out := make([]EnumValue, 0, len(values)) for i, v := range values { - out = append(out, IREnumValue{ + out = append(out, EnumValue{ Name: v, WireValue: textutil.ToDatabaseColumnName(v), Ordinal: i, diff --git a/internal/ir/enums_test.go b/internal/ir/enums_test.go index d18501c..c179baf 100644 --- a/internal/ir/enums_test.go +++ b/internal/ir/enums_test.go @@ -3,7 +3,8 @@ package ir import "testing" func TestEnumValuesWireValue(t *testing.T) { - p := &IRProject{ + t.Parallel() + p := &Project{ Enums: map[string][]string{ "OrderStatus": {"PENDING", "IN_PROGRESS", "Shipped"}, "Single": {"Draft"}, @@ -15,24 +16,28 @@ func TestEnumValuesWireValue(t *testing.T) { t.Fatalf("got %d values, want 3", len(got)) } cases := []struct { - idx int - name string - wire string + caseName string + idx int + name string + wire string }{ - {0, "PENDING", "pending"}, - {1, "IN_PROGRESS", "in_progress"}, - {2, "Shipped", "shipped"}, + {"pending", 0, "PENDING", "pending"}, + {"in_progress", 1, "IN_PROGRESS", "in_progress"}, + {"shipped", 2, "Shipped", "shipped"}, } for _, c := range cases { - if got[c.idx].Name != c.name { - t.Errorf("value[%d].Name = %q, want %q", c.idx, got[c.idx].Name, c.name) - } - if got[c.idx].WireValue != c.wire { - t.Errorf("value[%d].WireValue = %q, want %q", c.idx, got[c.idx].WireValue, c.wire) - } - if got[c.idx].Ordinal != c.idx { - t.Errorf("value[%d].Ordinal = %d, want %d", c.idx, got[c.idx].Ordinal, c.idx) - } + t.Run(c.caseName, func(t *testing.T) { + t.Parallel() + if got[c.idx].Name != c.name { + t.Errorf("value[%d].Name = %q, want %q", c.idx, got[c.idx].Name, c.name) + } + if got[c.idx].WireValue != c.wire { + t.Errorf("value[%d].WireValue = %q, want %q", c.idx, got[c.idx].WireValue, c.wire) + } + if got[c.idx].Ordinal != c.idx { + t.Errorf("value[%d].Ordinal = %d, want %d", c.idx, got[c.idx].Ordinal, c.idx) + } + }) } if got := p.EnumValues("Missing"); got != nil { @@ -44,13 +49,15 @@ func TestEnumValuesWireValue(t *testing.T) { } func TestEnumValuesNilProject(t *testing.T) { - var p *IRProject + t.Parallel() + var p *Project if got := p.EnumValues("X"); got != nil { t.Errorf("nil project EnumValues = %v, want nil", got) } } func TestIRIndexDatabaseName(t *testing.T) { + t.Parallel() cases := []struct { name string want string @@ -59,8 +66,11 @@ func TestIRIndexDatabaseName(t *testing.T) { {"idx_order_item_sku_0", "IX_idx_order_item_sku_0"}, } for _, c := range cases { - if got := (IRIndex{Name: c.name}).DatabaseName(); got != c.want { - t.Errorf("DatabaseName(%q) = %q, want %q", c.name, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := (Index{Name: c.name}).DatabaseName(); got != c.want { + t.Errorf("DatabaseName(%q) = %q, want %q", c.name, got, c.want) + } + }) } } diff --git a/internal/ir/field_methods.go b/internal/ir/field_methods.go index 2519504..fe1a23b 100644 --- a/internal/ir/field_methods.go +++ b/internal/ir/field_methods.go @@ -2,22 +2,24 @@ package ir import "strings" -// HasValidation reports whether the field has the named validation. -func (f IRField) HasValidation(name string) bool { +// validation is the single case-insensitive lookup behind both public helpers. +func (f Field) validation(name string) (string, bool) { for _, validation := range f.Validations { if strings.EqualFold(validation.Name, name) { - return true + return validation.Value, true } } - return false + return "", false +} + +// HasValidation reports whether the field has the named validation. +func (f Field) HasValidation(name string) bool { + _, ok := f.validation(name) + return ok } // ValidationValue returns the first validation value for the given name. -func (f IRField) ValidationValue(name string) string { - for _, validation := range f.Validations { - if strings.EqualFold(validation.Name, name) { - return validation.Value - } - } - return "" +func (f Field) ValidationValue(name string) string { + value, _ := f.validation(name) + return value } diff --git a/internal/ir/indexes.go b/internal/ir/indexes.go index 13ec144..e3d8288 100644 --- a/internal/ir/indexes.go +++ b/internal/ir/indexes.go @@ -14,8 +14,8 @@ import ( // This is the single source of truth for a bridge's index rendering — a bridge // no longer needs to remember that per-field uniqueness also produces an index. // The result is sorted by name for deterministic output. -func (e IREntity) AllIndexes() []IRIndex { - result := make([]IRIndex, 0, len(e.Indexes)+1) +func (e Entity) AllIndexes() []Index { + result := make([]Index, 0, len(e.Indexes)+1) // Copy declared indexes (normalizing empty Sort to asc-per-field). for _, idx := range e.Indexes { @@ -41,7 +41,7 @@ func (e IREntity) AllIndexes() []IRIndex { if covered[f.Name] { continue } - result = append(result, IRIndex{ + result = append(result, Index{ Name: "idx_" + textutil.ToDatabaseColumnName(e.NamePlural) + "_" + textutil.ToDatabaseColumnName(f.Name), Fields: []string{f.Name}, Sort: []string{"asc"}, @@ -49,7 +49,7 @@ func (e IREntity) AllIndexes() []IRIndex { }) } - slices.SortFunc(result, func(a, b IRIndex) int { return cmp.Compare(a.Name, b.Name) }) + slices.SortFunc(result, func(a, b Index) int { return cmp.Compare(a.Name, b.Name) }) return result } @@ -58,7 +58,7 @@ func (e IREntity) AllIndexes() []IRIndex { // `IX_{{ .Name | snakecase }}`, which double-prefixes and re-snake_cases a name // the core already computed (the template `snakecase` diverges from the core's // column naming on acronyms). -func (i IRIndex) DatabaseName() string { +func (i Index) DatabaseName() string { return "IX_" + i.Name } diff --git a/internal/ir/models.go b/internal/ir/models.go index 00575b4..a992400 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -1,34 +1,36 @@ +// Package ir builds the resolved intermediate representation consumed by bridges. package ir import ( + "slices" "strings" "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) -// IRProject represents the intermediate project model. -type IRProject struct { +// Project represents the intermediate project model. +type Project struct { Name string Description string Database string - Auth *IRAuthConfig + Auth *AuthConfig APIStyle string Platform string // target platform version (e.g. "net9.0"), passed through to templates // Enums maps enum name → ordered values. EnumOrder holds the sorted keys so // templates can iterate deterministically (Go map iteration order is random). Enums map[string][]string EnumOrder []string - Entities []IREntity - Cache *IRCacheConfig - CORS *IRCORSConfig - Deploy *IRDeployConfig + Entities []Entity + Cache *CacheConfig + CORS *CORSConfig + Deploy *DeployConfig // Versioning carries API versioning settings (enabled flag + default version). - Versioning *IRVersioningConfig + Versioning *VersioningConfig // RateLimit carries the HTTP request rate limiting policy. - RateLimit *IRRateLimitConfig + RateLimit *RateLimitConfig // Pagination carries list sizing defaults (page size + cap). - Pagination *IRPaginationConfig + Pagination *PaginationConfig // Addons contains the infrastructure accelerators requested via the CLI // (e.g. {"dapr": true}). It is not derived from domain.yaml — declared // infrastructure lives in Infrastructure, addon templates go on/off here. @@ -36,11 +38,11 @@ type IRProject struct { // Infrastructure holds the provider-agnostic backing services declared in // project.infrastructure (queue / cache / secrets). It is the input that // addon bridges like Dapr consume to emit concrete component manifests. - Infrastructure *IRInfrastructure + Infrastructure *Infrastructure } -// IRInfrastructure represents the project's backing services in IR. -type IRInfrastructure struct { +// Infrastructure represents the project's backing services in IR. +type Infrastructure struct { Queue string // message broker: pubsub, rabbitmq, kafka, redis, nats, in-memory Cache string // distributed cache store: redis, memcached, in-memory Secrets string // secrets store: local, kubernetes, azure-keyvault, aws-secrets @@ -48,23 +50,23 @@ type IRInfrastructure struct { } // HasAddon returns true if the named infrastructure addon is enabled. -func (p *IRProject) HasAddon(name string) bool { +func (p *Project) HasAddon(name string) bool { if p.Addons == nil { return false } return p.Addons[name] } -// IRAuthConfig represents authentication configuration in IR. -type IRAuthConfig struct { +// AuthConfig represents authentication configuration in IR. +type AuthConfig struct { Type string Entity string // resolved entity name Roles []string - Endpoints IRAuthEndpoints + Endpoints AuthEndpoints } -// IRAuthEndpoints controls which auth endpoints are generated. -type IRAuthEndpoints struct { +// AuthEndpoints controls which auth endpoints are generated. +type AuthEndpoints struct { HasLogin bool HasRegister bool HasMe bool @@ -72,16 +74,16 @@ type IRAuthEndpoints struct { } // HasAuth returns true if authentication is enabled. -func (p *IRProject) HasAuth() bool { - return p.Auth != nil && p.Auth.Type != "" && p.Auth.Type != "none" +func (p *Project) HasAuth() bool { + return p.Auth != nil && specmeta.IsAuthEnabled(p.Auth.Type) } // AuthEntity returns the resolved authentication entity (the entity that owns // email/password and drives the login/register/me/setup flow), or nil when auth // is disabled or the entity could not be found. Bridges use this instead of // scanning Project.Entities for the auth entity. -func (p *IRProject) AuthEntity() *IREntity { - if p == nil || !p.HasAuth() || p.Auth == nil { +func (p *Project) AuthEntity() *Entity { + if p == nil || !p.HasAuth() { return nil } for i := range p.Entities { @@ -92,72 +94,72 @@ func (p *IRProject) AuthEntity() *IREntity { return nil } -// IRCacheConfig represents cache configuration in IR. -type IRCacheConfig struct { +// CacheConfig represents cache configuration in IR. +type CacheConfig struct { Enabled bool Provider string ConnectionString string TTLSeconds int } -// IRCORSConfig represents CORS configuration in IR. -type IRCORSConfig struct { +// CORSConfig represents CORS configuration in IR. +type CORSConfig struct { Enabled bool Origins []string } -// IRDeployConfig represents deployment configuration in IR. -type IRDeployConfig struct { +// DeployConfig represents deployment configuration in IR. +type DeployConfig struct { Domain string // API domain (e.g. "localhost", "api.example.com") Port int // exposed port (default: 8080) } -// Versioning enables/disables API versioning and the default version string. -type IRVersioningConfig struct { +// VersioningConfig controls API versioning and the default version string. +type VersioningConfig struct { Enabled bool DefaultVersion string } // RateLimitConfig represents the HTTP request rate limiting policy in IR. -type IRRateLimitConfig struct { +type RateLimitConfig struct { Enabled bool Policy string // fixed | sliding PermitLimit int WindowSeconds int } -// IRPaginationConfig represents list pagination sizing in IR. -type IRPaginationConfig struct { +// PaginationConfig represents list pagination sizing in IR. +type PaginationConfig struct { DefaultPageSize int MaxPageSize int } // HasVersioning returns true when API versioning is enabled. -func (p *IRProject) HasVersioning() bool { +func (p *Project) HasVersioning() bool { return p.Versioning != nil && p.Versioning.Enabled } // HasRateLimit returns true when request rate limiting is enabled. -func (p *IRProject) HasRateLimit() bool { +func (p *Project) HasRateLimit() bool { return p.RateLimit != nil && p.RateLimit.Enabled } -// IREntity represents an entity in IR. -type IREntity struct { +// Entity represents an entity in IR. +type Entity struct { Name string OldName string // previous entity name (rename hint for the migration engine) NamePlural string Features map[string]bool - Fields []IRField - RelationsOut []IRRelation - RelationsIn []IRRelation - Indexes []IRIndex - Seed []map[string]interface{} - Permissions *IRPermissions + Fields []Field + RelationsOut []Relation + RelationsIn []Relation + Indexes []Index + Seed []map[string]any + Permissions *Permissions } -// IRField represents a field in IR. -type IRField struct { +// Field represents a field in IR. +type Field struct { Name string OldName string // previous field name (rename hint from `old_name:` modifier) DatabaseType string @@ -176,55 +178,62 @@ type IRField struct { RelationTarget string DefaultValue string DefaultIsFunc bool - Validations []IRValidation + Validations []Validation } -// NonRelationFields returns only scalar/non-relation fields (excludes relation FK fields). -func (e IREntity) NonRelationFields() []IRField { - var result []IRField +// fieldsWhere is the single ordered field filter behind the relation views. +func (e Entity) fieldsWhere(pred func(Field) bool) []Field { + var result []Field for _, f := range e.Fields { - if !f.IsRelation { + if pred(f) { result = append(result, f) } } return result } +// NonRelationFields returns only scalar/non-relation fields (excludes relation FK fields). +func (e Entity) NonRelationFields() []Field { + return e.fieldsWhere(func(f Field) bool { return !f.IsRelation }) +} + // RelationFields returns only relation fields. -func (e IREntity) RelationFields() []IRField { - var result []IRField - for _, f := range e.Fields { - if f.IsRelation { - result = append(result, f) - } - } - return result +func (e Entity) RelationFields() []Field { + return e.fieldsWhere(func(f Field) bool { return f.IsRelation }) } // EagerLoadRelations returns the relations a bridge should eager-load when // fetching a full entity graph (list / by-id): every outgoing relation. Bridges // iterate this instead of re-deriving the Include set, and call // EagerLoadNavigation() on each relation for the property to Include. -func (e IREntity) EagerLoadRelations() []IRRelation { - return e.RelationsOut +func (e Entity) EagerLoadRelations() []Relation { + return slices.Clone(e.RelationsOut) } // EagerLoadNavigation returns the navigation property name used to Include a // relation: the collection property for a [many] relation, the navigation // property for a single foreign key. Bridges apply their own casing // (pascalcase, camelcase, ...) to the returned name. -func (r IRRelation) EagerLoadNavigation() string { +func (r Relation) EagerLoadNavigation() string { if r.IsMany { return r.FieldName } return r.NavigationName } -// TableName returns the entity's snake_case database table name. It is the -// single source of truth for the table name — bridges must print this instead of -// re-deriving it with their own snake_case (the template `snakecase` diverges -// from textutil.ToDatabaseColumnName on acronyms, e.g. `IPv4Address`). -func (e IREntity) TableName() string { +// TableNameFor returns the snake_case database table name for an entity name. +// It is the single source of truth for table names — bridges and the migration +// engine must use it instead of re-deriving the name with their own snake_case +// (the template `snakecase` diverges from textutil.ToDatabaseColumnName on +// acronyms, e.g. `IPv4Address` -> `i_pv4address`). +func TableNameFor(name string) string { + return textutil.ToDatabaseColumnName(textutil.Pluralize(name)) +} + +// TableName returns the entity's snake_case database table name. It stays based +// on the parser-provided NamePlural (which may be an irregular plural); callers +// that only have a singular name use TableNameFor. +func (e Entity) TableName() string { return textutil.ToDatabaseColumnName(e.NamePlural) } @@ -232,7 +241,7 @@ func (e IREntity) TableName() string { // foreign key (fieldName + "Id", snake_cased). Bridges must print this instead // of `fkName .FieldName | snakecase`, which diverges from the core's column-name // algorithm on acronyms. -func (r IRRelation) ForeignKeyColumnName() string { +func (r Relation) ForeignKeyColumnName() string { return textutil.ToDatabaseColumnName(textutil.FKName(r.FieldName)) } @@ -241,7 +250,7 @@ func (r IRRelation) ForeignKeyColumnName() string { // scalar field (falling back to ToDatabaseColumnName(Name) when empty). This is // the single source of truth a bridge or the migration engine uses so it never // re-derives a column name with its own snake_case function. -func (f IRField) ColumnName() string { +func (f Field) ColumnName() string { if f.IsRelation { return textutil.ToDatabaseColumnName(textutil.FKName(f.Name)) } @@ -251,8 +260,19 @@ func (f IRField) ColumnName() string { return textutil.ToDatabaseColumnName(f.Name) } +// OldColumnName returns the previous column name of a renamed field. It is the +// single source of truth for the migration report and the migration plan: a +// missing OldDatabaseColumnName falls back to the canonical snake_case of the +// declared old_name, the same way ColumnName treats the current field name. +func (f Field) OldColumnName() string { + if f.OldDatabaseColumnName != "" { + return f.OldDatabaseColumnName + } + return textutil.ToDatabaseColumnName(f.OldName) +} + // HasFeature returns true if the entity has the named feature enabled. -func (e IREntity) HasFeature(name string) bool { +func (e Entity) HasFeature(name string) bool { if e.Features != nil { return e.Features[name] } @@ -260,7 +280,7 @@ func (e IREntity) HasFeature(name string) bool { } // PrimaryKey returns the entity's primary key field, or nil when none is marked. -func (e IREntity) PrimaryKey() *IRField { +func (e Entity) PrimaryKey() *Field { for i := range e.Fields { if e.Fields[i].IsPrimary { return &e.Fields[i] @@ -270,9 +290,9 @@ func (e IREntity) PrimaryKey() *IRField { } // FieldByName returns the field with the given name (case-insensitive), or nil. -// Bridges use this to resolve a seed/column name back to its IRField without +// Bridges use this to resolve a seed/column name back to its Field without // re-implementing the lookup. -func (e IREntity) FieldByName(name string) *IRField { +func (e Entity) FieldByName(name string) *Field { for i := range e.Fields { if strings.EqualFold(e.Fields[i].Name, name) { return &e.Fields[i] @@ -282,53 +302,56 @@ func (e IREntity) FieldByName(name string) *IRField { } // HasAudit returns true if the entity has the audit feature enabled. -func (e IREntity) HasAudit() bool { return e.HasFeature("audit") } +func (e Entity) HasAudit() bool { return e.HasFeature("audit") } // HasAuditLog returns true if the entity has the audit_log feature enabled. -func (e IREntity) HasAuditLog() bool { return e.HasFeature("audit_log") } +func (e Entity) HasAuditLog() bool { return e.HasFeature("audit_log") } // HasSoftDelete returns true if the entity has the soft_delete feature enabled. -func (e IREntity) HasSoftDelete() bool { return e.HasFeature("soft_delete") } +func (e Entity) HasSoftDelete() bool { return e.HasFeature("soft_delete") } // HasOptimisticLock returns true if the entity has the optimistic_lock feature enabled. -func (e IREntity) HasOptimisticLock() bool { return e.HasFeature("optimistic_lock") } +func (e Entity) HasOptimisticLock() bool { return e.HasFeature("optimistic_lock") } // HasEventSourced returns true if the entity emits domain events (event_sourced feature). -func (e IREntity) HasEventSourced() bool { return e.HasFeature("event_sourced") } +func (e Entity) HasEventSourced() bool { return e.HasFeature("event_sourced") } // HasCacheable returns true if the entity should use the distributed cache (cacheable feature). -func (e IREntity) HasCacheable() bool { return e.HasFeature("cacheable") } +func (e Entity) HasCacheable() bool { return e.HasFeature("cacheable") } // IsArray returns true if the field's DatabaseType is an array type (e.g. "array(int)"). -func (f IRField) IsArray() bool { +func (f Field) IsArray() bool { return specmeta.IsArrayType(f.DatabaseType) } // ArrayElementType returns the inner type of an array field (e.g. "int" from "array(int)"). // Returns empty string if the field is not an array. -func (f IRField) ArrayElementType() string { +func (f Field) ArrayElementType() string { if !f.IsArray() { return "" } return specmeta.ParseArrayInner(f.DatabaseType) } -// IRValidation represents one validation rule. -type IRValidation struct { +// Validation represents one validation rule. +type Validation struct { Name string Value string } -// IRRelation represents a relation between entities. -type IRRelation struct { +// Relation represents a relation between entities. +type Relation struct { FieldName string - TargetEntity *IREntity + TargetEntity *Entity NavigationName string InverseNavName string OnDeleteBehavior string IsNullable bool - IsMany bool - RelationType string + // IsMany describes the relation itself, not its inverse collection. For a + // many-to-many inverse in RelationsIn it is false; bridges detect that case + // through RelationType, not by reading IsMany. + IsMany bool + RelationType string // PairFieldName is set when a `[many]` relation is reconciled with a single // (FK) relation declared on the target entity: the two declarations describe @@ -344,8 +367,8 @@ type IRRelation struct { PairNavigationName string } -// IRIndex represents an index. -type IRIndex struct { +// Index represents an index. +type Index struct { Name string Fields []string Type string @@ -353,8 +376,8 @@ type IRIndex struct { Unique bool } -// IRPermissions represents entity permissions in IR. -type IRPermissions struct { +// Permissions represents entity permissions in IR. +type Permissions struct { Read []string Create []string Update []string diff --git a/internal/ir/models_test.go b/internal/ir/models_test.go index 5136e55..6a077f6 100644 --- a/internal/ir/models_test.go +++ b/internal/ir/models_test.go @@ -3,6 +3,7 @@ package ir import "testing" func TestIRField_IsArray(t *testing.T) { + t.Parallel() tests := []struct { name string databaseType string @@ -16,7 +17,8 @@ func TestIRField_IsArray(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - f := IRField{DatabaseType: tt.databaseType} + t.Parallel() + f := Field{DatabaseType: tt.databaseType} if got := f.IsArray(); got != tt.want { t.Errorf("IsArray() = %v, want %v", got, tt.want) } @@ -25,6 +27,7 @@ func TestIRField_IsArray(t *testing.T) { } func TestIRField_ArrayElementType(t *testing.T) { + t.Parallel() tests := []struct { name string databaseType string @@ -37,7 +40,8 @@ func TestIRField_ArrayElementType(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - f := IRField{DatabaseType: tt.databaseType} + t.Parallel() + f := Field{DatabaseType: tt.databaseType} if got := f.ArrayElementType(); got != tt.want { t.Errorf("ArrayElementType() = %q, want %q", got, tt.want) } @@ -46,6 +50,7 @@ func TestIRField_ArrayElementType(t *testing.T) { } func TestIREntity_HasFeature(t *testing.T) { + t.Parallel() tests := []struct { name string features map[string]bool @@ -60,7 +65,8 @@ func TestIREntity_HasFeature(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - e := IREntity{Features: tt.features} + t.Parallel() + e := Entity{Features: tt.features} if got := e.HasFeature(tt.feature); got != tt.want { t.Errorf("HasFeature(%q) = %v, want %v", tt.feature, got, tt.want) } @@ -69,6 +75,7 @@ func TestIREntity_HasFeature(t *testing.T) { } func TestIREntity_HasAudit(t *testing.T) { + t.Parallel() tests := []struct { name string features map[string]bool @@ -80,7 +87,8 @@ func TestIREntity_HasAudit(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - e := IREntity{Features: tt.features} + t.Parallel() + e := Entity{Features: tt.features} if got := e.HasAudit(); got != tt.want { t.Errorf("HasAudit() = %v, want %v", got, tt.want) } @@ -89,33 +97,37 @@ func TestIREntity_HasAudit(t *testing.T) { } func TestIREntity_HasAuditLog(t *testing.T) { - e := IREntity{Features: map[string]bool{"audit_log": true}} + t.Parallel() + e := Entity{Features: map[string]bool{"audit_log": true}} if !e.HasAuditLog() { t.Error("HasAuditLog() = false, want true") } - e2 := IREntity{Features: map[string]bool{}} + e2 := Entity{Features: map[string]bool{}} if e2.HasAuditLog() { t.Error("HasAuditLog() = true, want false") } } func TestIREntity_HasSoftDelete(t *testing.T) { - e := IREntity{Features: map[string]bool{"soft_delete": true}} + t.Parallel() + e := Entity{Features: map[string]bool{"soft_delete": true}} if !e.HasSoftDelete() { t.Error("HasSoftDelete() = false, want true") } } func TestIREntity_HasOptimisticLock(t *testing.T) { - e := IREntity{Features: map[string]bool{"optimistic_lock": true}} + t.Parallel() + e := Entity{Features: map[string]bool{"optimistic_lock": true}} if !e.HasOptimisticLock() { t.Error("HasOptimisticLock() = false, want true") } } func TestIREntity_NonRelationFields(t *testing.T) { - e := IREntity{ - Fields: []IRField{ + t.Parallel() + e := Entity{ + Fields: []Field{ {Name: "id", IsRelation: false}, {Name: "categoryId", IsRelation: true}, {Name: "name", IsRelation: false}, @@ -131,8 +143,9 @@ func TestIREntity_NonRelationFields(t *testing.T) { } func TestIREntity_RelationFields(t *testing.T) { - e := IREntity{ - Fields: []IRField{ + t.Parallel() + e := Entity{ + Fields: []Field{ {Name: "id", IsRelation: false}, {Name: "categoryId", IsRelation: true}, {Name: "name", IsRelation: false}, @@ -151,39 +164,56 @@ func TestIREntity_RelationFields(t *testing.T) { // (TableName, ColumnName, ForeignKeyColumnName) instead of re-deriving them // with the template `snakecase`, which diverges on acronyms. func TestCanonicalNameContract(t *testing.T) { - e := IREntity{Name: "OrderItem", NamePlural: "OrderItems"} + t.Parallel() + e := Entity{Name: "OrderItem", NamePlural: "OrderItems"} if got := e.TableName(); got != "order_items" { t.Errorf("TableName() = %q, want order_items", got) } - relation := IRRelation{FieldName: "category"} + relation := Relation{FieldName: "category"} if got := relation.ForeignKeyColumnName(); got != "category_id" { t.Errorf("ForeignKeyColumnName() = %q, want category_id", got) } cases := []struct { name string - f IRField + f Field want string }{ - {"relation field uses the FK name", IRField{Name: "categoryId", IsRelation: true}, "category_id"}, - {"parser-computed column wins", IRField{Name: "skuCode", DatabaseColumnName: "sku_code"}, "sku_code"}, - {"fallback re-derives from the name", IRField{Name: "createdAt"}, "created_at"}, + {"relation field uses the FK name", Field{Name: "categoryId", IsRelation: true}, "category_id"}, + {"parser-computed column wins", Field{Name: "skuCode", DatabaseColumnName: "sku_code"}, "sku_code"}, + {"fallback re-derives from the name", Field{Name: "createdAt"}, "created_at"}, } for _, c := range cases { - if got := c.f.ColumnName(); got != c.want { - t.Errorf("%s: ColumnName() = %q, want %q", c.name, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := c.f.ColumnName(); got != c.want { + t.Errorf("%s: ColumnName() = %q, want %q", c.name, got, c.want) + } + }) } } func TestEagerLoadNavigation(t *testing.T) { - r := IRRelation{FieldName: "orders", NavigationName: "Order", IsMany: true} + t.Parallel() + r := Relation{FieldName: "orders", NavigationName: "Order", IsMany: true} if got := r.EagerLoadNavigation(); got != "orders" { t.Errorf("[many] navigation = %q, want the collection property orders", got) } - r = IRRelation{FieldName: "customerId", NavigationName: "Customer"} + r = Relation{FieldName: "customerId", NavigationName: "Customer"} if got := r.EagerLoadNavigation(); got != "Customer" { t.Errorf("single FK navigation = %q, want Customer", got) } } + +func TestFieldOldColumnNameFallsBackToOldName(t *testing.T) { + t.Parallel() + f := Field{Name: "price", OldName: "oldPrice", DatabaseType: "decimal"} + if got := f.OldColumnName(); got != "old_price" { + t.Errorf("OldColumnName() = %q, want the snake_case of old_name", got) + } + f.OldDatabaseColumnName = "legacy_price" + if got := f.OldColumnName(); got != "legacy_price" { + t.Errorf("OldColumnName() = %q, want the declared old column", got) + } +} diff --git a/internal/ir/permissions.go b/internal/ir/permissions.go index 8d88bc7..1854c20 100644 --- a/internal/ir/permissions.go +++ b/internal/ir/permissions.go @@ -1,8 +1,12 @@ package ir -import "github.com/DomainCraft/DomainCraft/internal/specmeta" +import ( + "slices" -// IRPermissionPlan is the core-computed authorization plan for one operation + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) + +// PermissionPlan is the core-computed authorization plan for one operation // (read/create/update/delete). The bridge no longer parses `*` wildcards or // `@Owner` tokens in its templates — it receives the already-decomposed plan: // - IsPublic — `*` is present: the endpoint is anonymous (no [Authorize]). @@ -12,7 +16,7 @@ import "github.com/DomainCraft/DomainCraft/internal/specmeta" // // A role is either the public wildcard, an ownership token, or a declared role // (validated against auth.roles elsewhere). -type IRPermissionPlan struct { +type PermissionPlan struct { Operation string // read | create | update | delete IsPublic bool // wildcard "*" → anonymous access HasOwner bool // ownership token ("@...") → owner-scoped check @@ -23,15 +27,13 @@ type IRPermissionPlan struct { // ("@..."). Bridges use this to decide whether an entity needs owner-scoped // row permissions (e.g. Appwrite row-level security) without parsing the // role lists themselves. -func (p *IRPermissions) HasOwnerToken() bool { +func (p *Permissions) HasOwnerToken() bool { if p == nil { return false } for _, roles := range [][]string{p.Read, p.Create, p.Update, p.Delete} { - for _, r := range roles { - if specmeta.IsOwnershipToken(r) { - return true - } + if slices.ContainsFunc(roles, specmeta.IsOwnershipToken) { + return true } } return false @@ -40,7 +42,7 @@ func (p *IRPermissions) HasOwnerToken() bool { // IsPublic reports whether the named operation is declared public (its role // list contains the "*" wildcard). It returns false when no permissions block // exists or the operation has no wildcard. -func (p *IRPermissions) IsPublic(operation string) bool { +func (p *Permissions) IsPublic(operation string) bool { plan := p.Plan(operation) return plan != nil && plan.IsPublic } @@ -48,7 +50,7 @@ func (p *IRPermissions) IsPublic(operation string) bool { // Plan computes the authorization plan for the named operation. It returns nil // when the entity declares no permissions for that operation (meaning the // bridge falls back to its "no permissions defined" default). -func (p *IRPermissions) Plan(operation string) *IRPermissionPlan { +func (p *Permissions) Plan(operation string) *PermissionPlan { if p == nil { return nil } @@ -66,12 +68,12 @@ func (p *IRPermissions) Plan(operation string) *IRPermissionPlan { return nil } - plan := &IRPermissionPlan{Operation: operation} + plan := &PermissionPlan{Operation: operation} for _, r := range roles { switch { - case r == "*": + case specmeta.IsPublicPermission(r): plan.IsPublic = true - case len(r) > 0 && r[0] == '@': + case specmeta.IsOwnershipToken(r): plan.HasOwner = true default: plan.Roles = append(plan.Roles, r) @@ -82,7 +84,7 @@ func (p *IRPermissions) Plan(operation string) *IRPermissionPlan { // PermissionPlan returns the authorization plan for the named operation on the // current entity. It returns nil when the entity has no permissions block. -func (e IREntity) PermissionPlan(operation string) *IRPermissionPlan { +func (e Entity) PermissionPlan(operation string) *PermissionPlan { if e.Permissions == nil { return nil } diff --git a/internal/ir/permissions_test.go b/internal/ir/permissions_test.go new file mode 100644 index 0000000..2654811 --- /dev/null +++ b/internal/ir/permissions_test.go @@ -0,0 +1,48 @@ +package ir + +import ( + "reflect" + "testing" +) + +func TestPermissionsPlanDecomposesTokensViaSpecmeta(t *testing.T) { + t.Parallel() + perms := &Permissions{ + Read: []string{"*", "@Owner", "Admin", ""}, + Create: []string{"@Owner"}, + Update: []string{"Editor"}, + Delete: []string{"*"}, + } + cases := []struct { + name string + op string + want *PermissionPlan + }{ + { + name: "wildcard owner token and explicit role", + op: "read", + want: &PermissionPlan{Operation: "read", IsPublic: true, HasOwner: true, Roles: []string{"Admin", ""}}, + }, + {name: "owner token only", op: "create", want: &PermissionPlan{Operation: "create", HasOwner: true}}, + {name: "explicit roles only", op: "update", want: &PermissionPlan{Operation: "update", Roles: []string{"Editor"}}}, + {name: "wildcard only", op: "delete", want: &PermissionPlan{Operation: "delete", IsPublic: true}}, + {name: "unknown operation", op: "patch", want: nil}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + got := perms.Plan(c.op) + if !reflect.DeepEqual(got, c.want) { + t.Errorf("Plan(%q) = %#v, want %#v", c.op, got, c.want) + } + }) + } +} + +func TestPermissionsPlanNilReceiver(t *testing.T) { + t.Parallel() + var perms *Permissions + if got := perms.Plan("read"); got != nil { + t.Errorf("nil Plan(read) = %#v, want nil", got) + } +} diff --git a/internal/ir/query.go b/internal/ir/query.go index d2eb047..98781de 100644 --- a/internal/ir/query.go +++ b/internal/ir/query.go @@ -4,6 +4,7 @@ import ( "cmp" "slices" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) @@ -16,6 +17,7 @@ import ( // the core so every bridge serializes the same vocabulary. type FilterOp string +// Filter operators in canonical grammar order. const ( OpEq FilterOp = "eq" OpNe FilterOp = "ne" @@ -29,19 +31,35 @@ const ( OpEndsWith FilterOp = "endsWith" ) +// filterOpsByKind is the single source for which operators apply to which +// field kind. FilterOperators and the canonical vocabulary both derive from it. +var filterOpsByKind = map[string][]FilterOp{ + "text": {OpEq, OpNe, OpContains, OpStartsWith, OpEndsWith, OpIn}, + "boolean": {OpEq, OpNe}, + "ordered": {OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn}, + "scalar": {OpEq, OpNe, OpIn}, +} + +// allFilterOps is the canonical operator vocabulary. Every caller gets a clone +// so a bridge cannot mutate the core's contract at runtime. +var allFilterOps = []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} + +// jsonTextFilterOps is the text-semantics subset allowed on any JSON leaf: +// equality/set/string predicates compare the extracted value as text. +var jsonTextFilterOps = []FilterOp{OpEq, OpNe, OpIn, OpContains, OpStartsWith, OpEndsWith} + // AllFilterOperators returns the complete, canonical filter-operator vocabulary // in a deterministic order. The set is fixed by the core (spec/query.md) so // every bridge serializes the same operator names. A bridge iterates this to // emit its runtime operator enum (member names via `pascalcase`) instead of // hand-writing a parallel vocabulary that can drift out of sync with the core. -func (IRProject) AllFilterOperators() []FilterOp { - return []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} +func (Project) AllFilterOperators() []FilterOp { + return slices.Clone(allFilterOps) } -// jsonTextOperators is the text-semantics operator set allowed on any JSON -// leaf: equality/set/string predicates compare the extracted value as text. +// jsonTextOperators is the text-semantics operator set allowed on any JSON leaf. func jsonTextOperators() []FilterOp { - return []FilterOp{OpEq, OpNe, OpIn, OpContains, OpStartsWith, OpEndsWith} + return slices.Clone(jsonTextFilterOps) } // jsonFilterOperators is the operator set for a JSON path leaf. The value type @@ -50,8 +68,8 @@ func jsonTextOperators() []FilterOp { // extracted value) and are only valid on a `jsonb` column — `json` stores an // opaque, untyped document, so only text-semantics operators are allowed there. func jsonFilterOperators(dbType string) []FilterOp { - if dbType == "jsonb" { - return []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} + if dbType == specmeta.FieldTypeJSONB { + return slices.Clone(allFilterOps) } return jsonTextOperators() } @@ -72,26 +90,30 @@ const ( // FilterOperators returns the comparison operators a field's type supports, in // a canonical order. Bridges use this to emit a field's allowed-filter map // without re-deriving which operator is valid for which type. -func (f IRField) FilterOperators() []FilterOp { +func (f Field) FilterOperators() []FilterOp { + var kind string switch { case f.IsText(): - return []FilterOp{OpEq, OpNe, OpContains, OpStartsWith, OpEndsWith, OpIn} + kind = "text" case f.IsBoolean(): - return []FilterOp{OpEq, OpNe} + kind = "boolean" case f.IsInteger() || f.IsFloat() || f.IsDate() || f.IsDateTime(): - return []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn} + kind = "ordered" case f.IsUuid(), f.IsEnum(): - return []FilterOp{OpEq, OpNe, OpIn} - default: + kind = "scalar" + } + ops, ok := filterOpsByKind[kind] + if !ok { return nil } + return slices.Clone(ops) } // SearchableFields returns the scalar text fields eligible for a free-text // `search` (case-insensitive contains across each). Relations, enums, JSON // blobs, arrays, hidden and feature fields are excluded. -func (e IREntity) SearchableFields() []IRField { - return e.queryFields(func(f IRField) bool { +func (e Entity) SearchableFields() []Field { + return e.queryFields(func(f Field) bool { return f.IsText() && !f.IsFeatureField() && !f.IsPrimary && !f.IsHidden }) } @@ -99,22 +121,21 @@ func (e IREntity) SearchableFields() []IRField { // SortableFields returns the scalar fields a list endpoint may order by. // Relations, enums, JSON blobs, arrays, hidden and feature fields and the // primary key are excluded (the PK is the default order, not an explicit key). -func (e IREntity) SortableFields() []IRField { - return e.queryFields(func(f IRField) bool { - return !f.IsFeatureField() && !f.IsPrimary && !f.IsRelation && - !f.IsEnum() && !f.IsArray() && !f.IsJson() && !f.IsHidden +func (e Entity) SortableFields() []Field { + return e.queryFields(func(f Field) bool { + return f.isFilterableScalar() && !f.IsEnum() }) } // FilterableFields returns the scalar fields that may be filtered by value: // every scalar type (including enums) except feature fields, the primary key, // relations, arrays, JSON blobs and hidden fields. -func (e IREntity) FilterableFields() []IRField { - return e.queryFields(func(f IRField) bool { return f.isFilterableScalar() }) +func (e Entity) FilterableFields() []Field { + return e.queryFields(func(f Field) bool { return f.isFilterableScalar() }) } -func (e IREntity) queryFields(pred func(IRField) bool) []IRField { - out := make([]IRField, 0, len(e.Fields)) +func (e Entity) queryFields(pred func(Field) bool) []Field { + out := make([]Field, 0, len(e.Fields)) for _, f := range e.Fields { if pred(f) { out = append(out, f) @@ -126,7 +147,7 @@ func (e IREntity) queryFields(pred func(IRField) bool) []IRField { // isFilterableScalar reports whether the field is a scalar eligible for value // filtering (not a feature field, primary key, relation, array, JSON blob or // hidden field). It is the shared predicate behind FilterableFields. -func (f IRField) isFilterableScalar() bool { +func (f Field) isFilterableScalar() bool { return !f.IsFeatureField() && !f.IsPrimary && !f.IsRelation && !f.IsArray() && !f.IsJson() && !f.IsHidden } @@ -148,10 +169,11 @@ type FilterPathSpec struct { // one-hop to-one relation paths (e.g. "category.name") and JSON roots (e.g. // "meta", whose key path is open-ended). Output is sorted by path for // deterministic rendering. -func (e IREntity) FilterablePaths() []FilterPathSpec { - var out []FilterPathSpec +func (e Entity) FilterablePaths() []FilterPathSpec { + filterable := e.FilterableFields() + out := make([]FilterPathSpec, 0, len(filterable)+len(e.RelationsOut)+len(e.Fields)) - for _, f := range e.FilterableFields() { + for _, f := range filterable { out = append(out, FilterPathSpec{Path: f.Name, Kind: SegmentScalar, Operators: f.FilterOperators()}) } @@ -190,8 +212,8 @@ func (e IREntity) FilterablePaths() []FilterPathSpec { // and filter are peers of the same list-query contract (spec/query.md), not a // filter-first API. type QuerySchema struct { - Searchable []IRField - Sortable []IRField + Searchable []Field + Sortable []Field Filterable []FilterPathSpec } @@ -200,7 +222,7 @@ type QuerySchema struct { // compare with `>` and order by. It returns nil for uuid/text/date keys, where // keyset comparison is not reliably translatable across providers — those // entities fall back to offset pagination. -func (e IREntity) CursorField() *IRField { +func (e Entity) CursorField() *Field { pk := e.PrimaryKey() if pk == nil { return nil @@ -214,7 +236,7 @@ func (e IREntity) CursorField() *IRField { // QuerySchema returns the entity's full query surface in one object. Bridges // iterate this instead of calling SearchableFields/SortableFields/FilterablePaths // separately. -func (e IREntity) QuerySchema() QuerySchema { +func (e Entity) QuerySchema() QuerySchema { return QuerySchema{ Searchable: e.SearchableFields(), Sortable: e.SortableFields(), diff --git a/internal/ir/query_test.go b/internal/ir/query_test.go index 8b8b5f7..d905c38 100644 --- a/internal/ir/query_test.go +++ b/internal/ir/query_test.go @@ -5,19 +5,19 @@ import ( "testing" ) -func testEntity() IREntity { - category := IREntity{ +func testEntity() Entity { + category := Entity{ Name: "Category", - Fields: []IRField{ + Fields: []Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, {Name: "slug", DatabaseType: "string"}, {Name: "sortOrder", DatabaseType: "int"}, }, } - return IREntity{ + return Entity{ Name: "Product", - Fields: []IRField{ + Fields: []Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, {Name: "description", DatabaseType: "text"}, @@ -33,16 +33,17 @@ func testEntity() IREntity { {Name: "categoryId", DatabaseType: "uuid", IsRelation: true, RelationTarget: "Category"}, {Name: "createdAt", DatabaseType: "datetime"}, // feature field }, - RelationsOut: []IRRelation{ + RelationsOut: []Relation{ {FieldName: "categoryId", TargetEntity: &category, NavigationName: "Category", IsMany: false}, }, } } func TestSearchableSortableFilterableFields(t *testing.T) { + t.Parallel() e := testEntity() - names := func(fields []IRField) []string { + names := func(fields []Field) []string { var out []string for _, f := range fields { out = append(out, f.Name) @@ -63,32 +64,38 @@ func TestSearchableSortableFilterableFields(t *testing.T) { } func TestFilterOperators(t *testing.T) { + t.Parallel() cases := []struct { + name string dbType string want []FilterOp }{ - {"string", []FilterOp{OpEq, OpNe, OpContains, OpStartsWith, OpEndsWith, OpIn}}, - {"boolean", []FilterOp{OpEq, OpNe}}, - {"decimal", []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn}}, - {"uuid", []FilterOp{OpEq, OpNe, OpIn}}, - {"Status", []FilterOp{OpEq, OpNe, OpIn}}, - {"array(string)", nil}, - {"jsonb", nil}, + {"string", "string", []FilterOp{OpEq, OpNe, OpContains, OpStartsWith, OpEndsWith, OpIn}}, + {"boolean", "boolean", []FilterOp{OpEq, OpNe}}, + {"decimal", "decimal", []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn}}, + {"uuid", "uuid", []FilterOp{OpEq, OpNe, OpIn}}, + {"enum_status", "Status", []FilterOp{OpEq, OpNe, OpIn}}, + {"array_string", "array(string)", nil}, + {"jsonb", "jsonb", nil}, } for _, c := range cases { - f := IRField{DatabaseType: c.dbType} - got := f.FilterOperators() - if len(got) == 0 && len(c.want) == 0 { - continue - } - if !reflect.DeepEqual(got, c.want) { - t.Errorf("FilterOperators(%q) = %v, want %v", c.dbType, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + f := Field{DatabaseType: c.dbType} + got := f.FilterOperators() + if len(got) == 0 && len(c.want) == 0 { + return + } + if !reflect.DeepEqual(got, c.want) { + t.Errorf("FilterOperators(%q) = %v, want %v", c.dbType, got, c.want) + } + }) } } func TestAllFilterOperators(t *testing.T) { - got := (IRProject{}).AllFilterOperators() + t.Parallel() + got := (Project{}).AllFilterOperators() want := []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} if !reflect.DeepEqual(got, want) { t.Errorf("AllFilterOperators() = %v, want %v", got, want) @@ -96,6 +103,7 @@ func TestAllFilterOperators(t *testing.T) { } func TestFilterablePaths(t *testing.T) { + t.Parallel() e := testEntity() paths := e.FilterablePaths() @@ -126,6 +134,7 @@ func TestFilterablePaths(t *testing.T) { } func TestQuerySchema(t *testing.T) { + t.Parallel() e := testEntity() q := e.QuerySchema() @@ -146,26 +155,31 @@ func TestQuerySchema(t *testing.T) { } func TestCursorField(t *testing.T) { + t.Parallel() cases := []struct { + name string pkType string want bool }{ - {"int", true}, - {"bigint", true}, - {"uuid", false}, - {"string", false}, - {"date", false}, + {"int", "int", true}, + {"bigint", "bigint", true}, + {"uuid", "uuid", false}, + {"string", "string", false}, + {"date", "date", false}, } for _, c := range cases { - e := IREntity{Fields: []IRField{{Name: "id", DatabaseType: c.pkType, IsPrimary: true}}} - got := e.CursorField() - if (got != nil) != c.want { - t.Errorf("CursorField(pk=%s) = %v, want non-nil=%v", c.pkType, got != nil, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + e := Entity{Fields: []Field{{Name: "id", DatabaseType: c.pkType, IsPrimary: true}}} + got := e.CursorField() + if (got != nil) != c.want { + t.Errorf("CursorField(pk=%s) = %v, want non-nil=%v", c.pkType, got != nil, c.want) + } + }) } // No PK -> nil. - if got := (IREntity{Fields: []IRField{{Name: "name"}}}).CursorField(); got != nil { + if got := (Entity{Fields: []Field{{Name: "name"}}}).CursorField(); got != nil { t.Errorf("CursorField() with no PK = %v, want nil", got) } } diff --git a/internal/ir/seed.go b/internal/ir/seed.go index 206a946..83a388d 100644 --- a/internal/ir/seed.go +++ b/internal/ir/seed.go @@ -8,11 +8,11 @@ import "github.com/DomainCraft/DomainCraft/internal/specmeta" // the project (dumb bridge, smart core). Explicit `seed:` rows and // auto-generated mock seed both use this exact shape. type SeedValue struct { - Field string // logical field name - DBType string // IR database type (e.g. "uuid", "decimal", "Status", "array(int)") - IsRelation bool // true when the field is a relation (FK or collection) - IsMany bool // true when the relation is a collection ([many]) - Value interface{} // native Go value (string, int64, float64, bool, []interface{}, map, nil) + Field string // logical field name + DBType string // IR database type (e.g. "uuid", "decimal", "Status", "array(int)") + IsRelation bool // true when the field is a relation (FK or collection) + IsMany bool // true when the relation is a collection ([many]) + Value any // native Go value (string, int64, float64, bool, []any, map, nil) } // Kind returns the language-agnostic value kind for serialization, derived from @@ -26,37 +26,13 @@ func (v SeedValue) Kind() string { return KindOf(v.DBType) } // elements without string-slicing their own array syntax. func (v SeedValue) ElementType() string { return specmeta.ParseArrayInner(v.DBType) } -// KindOf maps an IR database type to its language-agnostic value kind. +// KindOf maps an IR database type to its language-agnostic value kind. The +// classification lives in specmeta so seeds and bridges agree on it. func KindOf(dbType string) string { - inner := specmeta.ParseArrayInner(dbType) - switch { - case specmeta.IsArrayType(dbType): + if specmeta.IsArrayType(dbType) { return "array" - case inner == "uuid": - return "uuid" - case inner == "string" || inner == "text": - return "text" - case inner == "int": - return "int" - case inner == "bigint": - return "bigint" - case inner == "float": - return "float" - case inner == "decimal": - return "decimal" - case inner == "boolean": - return "bool" - case inner == "date": - return "date" - case inner == "datetime": - return "datetime" - case inner == "json" || inner == "jsonb": - return "json" - case !specmeta.IsPrimitive(inner): - return "enum" - default: - return "text" } + return specmeta.FieldKind(specmeta.ParseArrayInner(dbType)) } // SeedRecord is one seed row for an entity: its fields in declaration order. diff --git a/internal/ir/seed_kind_test.go b/internal/ir/seed_kind_test.go new file mode 100644 index 0000000..ce32e53 --- /dev/null +++ b/internal/ir/seed_kind_test.go @@ -0,0 +1,41 @@ +package ir + +import ( + "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) + +func TestKindOfFollowsSpecmetaClassification(t *testing.T) { + t.Parallel() + want := map[string]string{ + specmeta.FieldTypeUUID: "uuid", + specmeta.FieldTypeString: "text", + specmeta.FieldTypeText: "text", + specmeta.FieldTypeInt: "int", + specmeta.FieldTypeBigint: "bigint", + specmeta.FieldTypeFloat: "float", + specmeta.FieldTypeDecimal: "decimal", + specmeta.FieldTypeBoolean: "bool", + specmeta.FieldTypeDate: "date", + specmeta.FieldTypeDatetime: "datetime", + specmeta.FieldTypeJSON: "json", + specmeta.FieldTypeJSONB: "json", + } + for _, typ := range specmeta.PrimitiveFieldTypes { + expected, ok := want[typ] + if !ok { + t.Fatalf("no expected seed kind for primitive type %q", typ) + } + if got := KindOf(typ); got != expected { + t.Errorf("KindOf(%q) = %q, want %q", typ, got, expected) + } + arrayType := specmeta.FieldTypeArray + "(" + typ + ")" + if got := KindOf(arrayType); got != "array" { + t.Errorf("KindOf(%q) = %q, want array", arrayType, got) + } + } + if got := KindOf("Status"); got != "enum" { + t.Errorf("KindOf(Status) = %q, want enum", got) + } +} diff --git a/internal/ir/testdata/build-hub-relations.golden.txt b/internal/ir/testdata/build-hub-relations.golden.txt new file mode 100644 index 0000000..59fd9a5 --- /dev/null +++ b/internal/ir/testdata/build-hub-relations.golden.txt @@ -0,0 +1,3 @@ +entities=100 ir=101 sha256=f71e876e9ec81b45fb1a4c644fc36c69e5264a5d0b578461bef91efa85b5d31a +entities=500 ir=501 sha256=c9e9d2ad18a67a801e5f6aece1d9a2d0a0be00c7e551723b795319e494f538cf +entities=2000 ir=2001 sha256=f72bf5012caa6d49211f7f328f94c0ef9096c342766b07a66702ee4dbf77d623 diff --git a/internal/ir/testdata/sort-entities.golden.txt b/internal/ir/testdata/sort-entities.golden.txt new file mode 100644 index 0000000..13a6a26 --- /dev/null +++ b/internal/ir/testdata/sort-entities.golden.txt @@ -0,0 +1,9 @@ +chain/100 entities=100 sha256=4c1e9f857e67b5e06a49fea15eddee5b7850431ce1014ef285fcf5e045c4f783 +fanout/100 entities=100 sha256=ce022232d177184b376d2b9a619e3eccc44befe2fb8552f9f87cb8d95625bc6c +fanout-reverse/100 entities=100 sha256=e6d819947dcdad94c8248f3ed22b63df6845f23841ccb5ba313c2f8ea1421e03 +chain/500 entities=500 sha256=2315d74b560861744c94efcca938c14d7c808705b653d4fcd9e85b4c03d973cd +fanout/500 entities=500 sha256=41185febc977a58c958beb8e05119470568584a12def0b765d120132f098437a +fanout-reverse/500 entities=500 sha256=949bf411ee6215086a3ec96883567fe96bcf115c6898b964c866924e3e2de210 +chain/2000 entities=2000 sha256=b5b1330c7d068af9eb1e1a2229895f0c7fdb940d7165ac6480eaddec240f44e0 +fanout/2000 entities=2000 sha256=17fcecee27b5e4244449d0fc7525562edabb5058ee794b8dd601234ce17ff8ff +fanout-reverse/2000 entities=2000 sha256=8f4c04e1f5db9c9b476ba908ceb6d342fe7ea0152cfa920b716483fcd1381e4d diff --git a/internal/ir/toposort.go b/internal/ir/toposort.go index 1e102b4..d9783f5 100644 --- a/internal/ir/toposort.go +++ b/internal/ir/toposort.go @@ -4,54 +4,75 @@ import "slices" // sortEntities reorders the slice by FK dependencies using Kahn's algorithm. // The order is deterministic: ties are broken by entity name. -// It returns a new slice because relations hold *IREntity pointers into the +// It returns a new slice because relations hold *Entity pointers into the // original backing array; the original must stay intact until every pointer has // been rebound to its new location. -func sortEntities(entities []IREntity) []IREntity { +func sortEntities(entities []Entity) []Entity { byName := make(map[string]int, len(entities)) for i, e := range entities { byName[e.Name] = i } // deps[i] = set of entity names that entities[i] depends on (must come first). - deps := make([]map[string]bool, len(entities)) + // dependents[name] is the inverse edge: indices that must wait for name. + // Building it once avoids rescanning every entity for every popped name. inDegree := make([]int, len(entities)) + dependents := make(map[string][]int, len(entities)) for i, entity := range entities { depSet := make(map[string]bool) for _, rel := range entity.RelationsOut { if !rel.IsMany && rel.TargetEntity != nil && rel.TargetEntity.Name != entity.Name { - depSet[rel.TargetEntity.Name] = true + target := rel.TargetEntity.Name + if !depSet[target] { + depSet[target] = true + dependents[target] = append(dependents[target], i) + } } } - deps[i] = depSet inDegree[i] = len(depSet) } // Initialize the queue with all entities that have no dependencies. - ready := make([]string, 0) + ready := make([]string, 0, len(entities)) for i, e := range entities { if inDegree[i] == 0 { ready = append(ready, e.Name) } } - // Deterministic ordering: process ready entities in name order. slices.Sort(ready) + // Appending is O(1); only an out-of-order append makes the queue unsorted. + // Deferring the sort until the next pop turns fan-out (N-1 insertions at + // one step) into one sort instead of N-1 full-slice copies. Ascending + // insertions never set dirty and keep the old O(1) append path. + // + // This is load-bearing, not micro-optimization: an unconditional sort at + // every pop was measured at +2884% on BenchmarkSortEntities/fanout/2000 + // (303µs -> 9067µs, benchstat p=0.008) with identical allocations. Do not + // "simplify" it away. + dirty := false + insertReady := func(name string) { + if len(ready) > 0 && name < ready[len(ready)-1] { + dirty = true + } + ready = append(ready, name) + } + order := make([]string, 0, len(entities)) for len(ready) > 0 { + if dirty { + slices.Sort(ready) + dirty = false + } name := ready[0] ready = ready[1:] order = append(order, name) - // For every entity depending on this one, decrement in-degree. - for i := range entities { - if deps[i][name] { - inDegree[i]-- - if inDegree[i] == 0 { - // Insert in sorted order to keep processing deterministic. - ready = append(ready, entities[i].Name) - slices.Sort(ready) - } + // Decrement only the entities that actually depend on this name. + for _, i := range dependents[name] { + inDegree[i]-- + if inDegree[i] == 0 { + insertReady(entities[i].Name) } } } @@ -75,12 +96,12 @@ func sortEntities(entities []IREntity) []IREntity { // Build the reordered slice. The source `entities` backing array is left // untouched, so every TargetEntity pointer still points to valid memory we // can read the name from while rebinding it to the new slice. - sorted := make([]IREntity, 0, len(entities)) + sorted := make([]Entity, 0, len(entities)) for _, name := range order { sorted = append(sorted, entities[byName[name]]) } - relocated := make(map[string]*IREntity, len(sorted)) + relocated := make(map[string]*Entity, len(sorted)) for i := range sorted { relocated[sorted[i].Name] = &sorted[i] } @@ -98,4 +119,4 @@ func sortEntities(entities []IREntity) []IREntity { } return sorted -} \ No newline at end of file +} diff --git a/internal/ir/toposort_test.go b/internal/ir/toposort_test.go new file mode 100644 index 0000000..2592be9 --- /dev/null +++ b/internal/ir/toposort_test.go @@ -0,0 +1,93 @@ +package ir + +import ( + "fmt" + "slices" + "testing" +) + +// TestTopoSortInsertReadyKeepsNameOrder pins the ready-queue ordering: +// entities that become ready out of name order must still be processed in name +// order (ties broken deterministically by name, not by edge order). +func TestTopoSortInsertReadyKeepsNameOrder(t *testing.T) { + t.Parallel() + names := []string{"C", "B", "A", "M", "Z"} + entities := make([]Entity, len(names)) + index := make(map[string]int, len(names)) + for i, name := range names { + entities[i] = Entity{Name: name} + index[name] = i + } + addDep := func(from, to string) { + e := &entities[index[from]] + e.RelationsOut = append(e.RelationsOut, Relation{ + FieldName: to, + TargetEntity: &entities[index[to]], + IsMany: false, + }) + } + // Z unlocks B then A (edge order is B, A); B unlocks C. M is free. + addDep("B", "Z") + addDep("A", "Z") + addDep("C", "B") + + got := sortEntities(entities) + want := []string{"M", "Z", "A", "B", "C"} + if len(got) != len(want) { + t.Fatalf("sortEntities() returned %d entities (%+v), want %d", len(got), got, len(want)) + } + for i, name := range want { + if got[i].Name != name { + t.Fatalf("entity %d = %q, want %q (full order: %+v)", i, got[i].Name, name, entityNames(got)) + } + } + // Rebound relation pointers must still point into the reordered slice. + for i := range got { + for _, rel := range got[i].RelationsOut { + if rel.TargetEntity == nil || rel.TargetEntity.Name != rel.FieldName { + t.Errorf("%s relation %q points to %v, want an entity in the reordered slice", got[i].Name, rel.FieldName, rel.TargetEntity) + } + } + } +} + +// TestTopoSortFanOutEmitsNameOrder pins the fan-out shape: one root unlocks +// every other entity at once, so the ready queue grows via O(n) insertions. +// Leaves are inserted in descending name order; emission must still be +// ascending, i.e. the heap must pop the smallest name on every step. +func TestTopoSortFanOutEmitsNameOrder(t *testing.T) { + t.Parallel() + const leaves = 32 + names := []string{"Root"} + for i := leaves - 1; i >= 0; i-- { + names = append(names, fmt.Sprintf("E%04d", i)) + } + entities := make([]Entity, len(names)) + for i, name := range names { + entities[i] = Entity{Name: name} + } + for i := 1; i < len(entities); i++ { + entities[i].RelationsOut = []Relation{{ + FieldName: "root", + TargetEntity: &entities[0], + IsMany: false, + }} + } + + want := []string{"Root"} + for i := range leaves { + want = append(want, fmt.Sprintf("E%04d", i)) + } + got := entityNames(sortEntities(entities)) + if !slices.Equal(got, want) { + t.Fatalf("sortEntities() order = %v, want %v", got, want) + } +} + +func entityNames(entities []Entity) []string { + names := make([]string, 0, len(entities)) + for _, e := range entities { + names = append(names, e.Name) + } + return names +} diff --git a/internal/ir/typekind.go b/internal/ir/typekind.go index 42b1903..2ff9d16 100644 --- a/internal/ir/typekind.go +++ b/internal/ir/typekind.go @@ -6,14 +6,14 @@ import "github.com/DomainCraft/DomainCraft/internal/specmeta" // array field, the type itself otherwise — is a user-declared enum rather than // a built-in primitive. Bridges use this instead of re-deriving the enum check // from a raw DatabaseType string. -func (f IRField) IsEnum() bool { +func (f Field) IsEnum() bool { return !specmeta.IsPrimitive(specmeta.ParseArrayInner(f.DatabaseType)) } // EnumTypeName returns the effective type name of the field: the enum type name // for an enum field, the element type for an array field, or the field's own // DatabaseType otherwise. It mirrors the old `enumTypeName` template function. -func (f IRField) EnumTypeName() string { +func (f Field) EnumTypeName() string { return specmeta.ParseArrayInner(f.DatabaseType) } @@ -22,67 +22,62 @@ func (f IRField) EnumTypeName() string { // are false for array fields (whose element type is inspected separately via // EnumTypeName/ArrayElementType). -// IsUuid reports whether the field holds a UUID. -func (f IRField) IsUuid() bool { return f.DatabaseType == "uuid" } +// IsUuid reports whether the field holds a UUID. This is the canonical name: +// every shipped bridge and the IR itself use this casing. +func (f Field) IsUuid() bool { return f.DatabaseType == specmeta.FieldTypeUUID } //nolint:revive // bridge template contract casing // IsText reports whether the field holds a string/text value. -func (f IRField) IsText() bool { - return f.DatabaseType == "string" || f.DatabaseType == "text" -} +func (f Field) IsText() bool { return specmeta.IsStringType(f.DatabaseType) } // IsInteger reports whether the field holds an integral number (int or bigint). -func (f IRField) IsInteger() bool { - return f.DatabaseType == "int" || f.DatabaseType == "bigint" -} +func (f Field) IsInteger() bool { return specmeta.IsIntegralType(f.DatabaseType) } // IsFloat reports whether the field holds a floating-point number (float or decimal). -func (f IRField) IsFloat() bool { - return f.DatabaseType == "float" || f.DatabaseType == "decimal" -} +func (f Field) IsFloat() bool { return specmeta.IsFloatType(f.DatabaseType) } // IsNumeric reports whether the field holds any numeric type. -func (f IRField) IsNumeric() bool { return specmeta.IsNumeric(f.DatabaseType) } +func (f Field) IsNumeric() bool { return specmeta.IsNumeric(f.DatabaseType) } // IsBoolean reports whether the field holds a boolean. -func (f IRField) IsBoolean() bool { return f.DatabaseType == "boolean" } +func (f Field) IsBoolean() bool { return f.DatabaseType == specmeta.FieldTypeBoolean } // IsDate reports whether the field holds a date (no time component). -func (f IRField) IsDate() bool { return f.DatabaseType == "date" } +func (f Field) IsDate() bool { return f.DatabaseType == specmeta.FieldTypeDate } // IsDateTime reports whether the field holds a datetime. -func (f IRField) IsDateTime() bool { return f.DatabaseType == "datetime" } +func (f Field) IsDateTime() bool { return f.DatabaseType == specmeta.FieldTypeDatetime } // IsJson reports whether the field holds a JSON document (json or jsonb). -func (f IRField) IsJson() bool { - return f.DatabaseType == "json" || f.DatabaseType == "jsonb" +func (f Field) IsJson() bool { //nolint:revive // bridge template contract casing + return f.DatabaseType == specmeta.FieldTypeJSON || f.DatabaseType == specmeta.FieldTypeJSONB } // IsJsonB reports whether the field holds a jsonb document specifically // (as opposed to a plain json column). Bridges use this to choose between // ordered (numeric) and text-only JSON path operators. -func (f IRField) IsJsonB() bool { return f.DatabaseType == "jsonb" } +func (f Field) IsJsonB() bool { return f.DatabaseType == specmeta.FieldTypeJSONB } //nolint:revive // bridge template contract casing // IsString reports whether the field holds a bounded string column // (as opposed to an unbounded text column, which also satisfies IsText). -func (f IRField) IsString() bool { return f.DatabaseType == "string" } +func (f Field) IsString() bool { return f.DatabaseType == specmeta.FieldTypeString } // IsTextOnly reports whether the field holds an unbounded text column // (as opposed to a bounded string column, which also satisfies IsText). -func (f IRField) IsTextOnly() bool { return f.DatabaseType == "text" } +func (f Field) IsTextOnly() bool { return f.DatabaseType == specmeta.FieldTypeText } // IsBigInt reports whether the field holds a 64-bit integer (bigint), // distinct from the 32-bit int. -func (f IRField) IsBigInt() bool { return f.DatabaseType == "bigint" } +func (f Field) IsBigInt() bool { return f.DatabaseType == specmeta.FieldTypeBigint } // IsDecimal reports whether the field holds an arbitrary-precision decimal, // distinct from the binary float. -func (f IRField) IsDecimal() bool { return f.DatabaseType == "decimal" } +func (f Field) IsDecimal() bool { return f.DatabaseType == specmeta.FieldTypeDecimal } // IsPatchable reports whether the field participates in a merge-patch (PATCH) // request body: scalar fields that are not server-managed, plus single // (non-collection) foreign keys. Collections, enums, JSON blobs, arrays, // identity and server-managed fields are excluded. -func (f IRField) IsPatchable() bool { +func (f Field) IsPatchable() bool { if f.IsFeatureField() || f.IsSensitive() || f.IsReadonly || f.IsPrimary { return false } diff --git a/internal/ir/typekind_test.go b/internal/ir/typekind_test.go index 8983c16..a6807ac 100644 --- a/internal/ir/typekind_test.go +++ b/internal/ir/typekind_test.go @@ -3,149 +3,166 @@ package ir import "testing" func TestIRFieldTypePredicates(t *testing.T) { + t.Parallel() cases := []struct { + name string dbType string - isUuid, isText, isInt, isFloat bool - isBool, isDate, isDt, isJson bool + isUUID, isText, isInt, isFloat bool + isBool, isDate, isDt, isJSON bool isNumeric, isEnum bool enumName string }{ - {dbType: "uuid", isUuid: true, enumName: "uuid"}, - {dbType: "string", isText: true, enumName: "string"}, - {dbType: "text", isText: true, enumName: "text"}, - {dbType: "int", isInt: true, isNumeric: true, enumName: "int"}, - {dbType: "bigint", isInt: true, isNumeric: true, enumName: "bigint"}, - {dbType: "float", isFloat: true, isNumeric: true, enumName: "float"}, - {dbType: "decimal", isFloat: true, isNumeric: true, enumName: "decimal"}, - {dbType: "boolean", isBool: true, enumName: "boolean"}, - {dbType: "date", isDate: true, enumName: "date"}, - {dbType: "datetime", isDt: true, enumName: "datetime"}, - {dbType: "json", isJson: true, enumName: "json"}, - {dbType: "jsonb", isJson: true, enumName: "jsonb"}, - {dbType: "Status", isEnum: true, enumName: "Status"}, - {dbType: "array(int)", enumName: "int"}, - {dbType: "array(Status)", isEnum: true, enumName: "Status"}, + {name: "uuid", dbType: "uuid", isUUID: true, enumName: "uuid"}, + {name: "string", dbType: "string", isText: true, enumName: "string"}, + {name: "text", dbType: "text", isText: true, enumName: "text"}, + {name: "int", dbType: "int", isInt: true, isNumeric: true, enumName: "int"}, + {name: "bigint", dbType: "bigint", isInt: true, isNumeric: true, enumName: "bigint"}, + {name: "float", dbType: "float", isFloat: true, isNumeric: true, enumName: "float"}, + {name: "decimal", dbType: "decimal", isFloat: true, isNumeric: true, enumName: "decimal"}, + {name: "boolean", dbType: "boolean", isBool: true, enumName: "boolean"}, + {name: "date", dbType: "date", isDate: true, enumName: "date"}, + {name: "datetime", dbType: "datetime", isDt: true, enumName: "datetime"}, + {name: "json", dbType: "json", isJSON: true, enumName: "json"}, + {name: "jsonb", dbType: "jsonb", isJSON: true, enumName: "jsonb"}, + {name: "enum_status", dbType: "Status", isEnum: true, enumName: "Status"}, + {name: "array_int", dbType: "array(int)", enumName: "int"}, + {name: "array_enum_status", dbType: "array(Status)", isEnum: true, enumName: "Status"}, } for _, c := range cases { - f := IRField{DatabaseType: c.dbType} - if got := f.IsUuid(); got != c.isUuid { - t.Errorf("%q IsUuid() = %v, want %v", c.dbType, got, c.isUuid) - } - if got := f.IsText(); got != c.isText { - t.Errorf("%q IsText() = %v, want %v", c.dbType, got, c.isText) - } - if got := f.IsInteger(); got != c.isInt { - t.Errorf("%q IsInteger() = %v, want %v", c.dbType, got, c.isInt) - } - if got := f.IsFloat(); got != c.isFloat { - t.Errorf("%q IsFloat() = %v, want %v", c.dbType, got, c.isFloat) - } - if got := f.IsNumeric(); got != c.isNumeric { - t.Errorf("%q IsNumeric() = %v, want %v", c.dbType, got, c.isNumeric) - } - if got := f.IsBoolean(); got != c.isBool { - t.Errorf("%q IsBoolean() = %v, want %v", c.dbType, got, c.isBool) - } - if got := f.IsDate(); got != c.isDate { - t.Errorf("%q IsDate() = %v, want %v", c.dbType, got, c.isDate) - } - if got := f.IsDateTime(); got != c.isDt { - t.Errorf("%q IsDateTime() = %v, want %v", c.dbType, got, c.isDt) - } - if got := f.IsJson(); got != c.isJson { - t.Errorf("%q IsJson() = %v, want %v", c.dbType, got, c.isJson) - } - if got := f.IsEnum(); got != c.isEnum { - t.Errorf("%q IsEnum() = %v, want %v", c.dbType, got, c.isEnum) - } - if got := f.EnumTypeName(); got != c.enumName { - t.Errorf("%q EnumTypeName() = %q, want %q", c.dbType, got, c.enumName) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + f := Field{DatabaseType: c.dbType} + if got := f.IsUuid(); got != c.isUUID { + t.Errorf("%q IsUuid() = %v, want %v", c.dbType, got, c.isUUID) + } + if got := f.IsText(); got != c.isText { + t.Errorf("%q IsText() = %v, want %v", c.dbType, got, c.isText) + } + if got := f.IsInteger(); got != c.isInt { + t.Errorf("%q IsInteger() = %v, want %v", c.dbType, got, c.isInt) + } + if got := f.IsFloat(); got != c.isFloat { + t.Errorf("%q IsFloat() = %v, want %v", c.dbType, got, c.isFloat) + } + if got := f.IsNumeric(); got != c.isNumeric { + t.Errorf("%q IsNumeric() = %v, want %v", c.dbType, got, c.isNumeric) + } + if got := f.IsBoolean(); got != c.isBool { + t.Errorf("%q IsBoolean() = %v, want %v", c.dbType, got, c.isBool) + } + if got := f.IsDate(); got != c.isDate { + t.Errorf("%q IsDate() = %v, want %v", c.dbType, got, c.isDate) + } + if got := f.IsDateTime(); got != c.isDt { + t.Errorf("%q IsDateTime() = %v, want %v", c.dbType, got, c.isDt) + } + if got := f.IsJson(); got != c.isJSON { + t.Errorf("%q IsJson() = %v, want %v", c.dbType, got, c.isJSON) + } + if got := f.IsEnum(); got != c.isEnum { + t.Errorf("%q IsEnum() = %v, want %v", c.dbType, got, c.isEnum) + } + if got := f.EnumTypeName(); got != c.enumName { + t.Errorf("%q EnumTypeName() = %q, want %q", c.dbType, got, c.enumName) + } + }) } } func TestIRFieldSpecificTypePredicates(t *testing.T) { + t.Parallel() cases := []struct { + name string dbType string isString, isBigInt, isDecimal bool - isJsonB bool + isJSONB bool }{ - {dbType: "string", isString: true}, - {dbType: "text", isString: false}, - {dbType: "int"}, - {dbType: "bigint", isBigInt: true}, - {dbType: "float"}, - {dbType: "decimal", isDecimal: true}, - {dbType: "json"}, - {dbType: "jsonb", isJsonB: true}, + {name: "string", dbType: "string", isString: true}, + {name: "text", dbType: "text", isString: false}, + {name: "int", dbType: "int"}, + {name: "bigint", dbType: "bigint", isBigInt: true}, + {name: "float", dbType: "float"}, + {name: "decimal", dbType: "decimal", isDecimal: true}, + {name: "json", dbType: "json"}, + {name: "jsonb", dbType: "jsonb", isJSONB: true}, } for _, c := range cases { - f := IRField{DatabaseType: c.dbType} - if got := f.IsString(); got != c.isString { - t.Errorf("%q IsString() = %v, want %v", c.dbType, got, c.isString) - } - if got := f.IsBigInt(); got != c.isBigInt { - t.Errorf("%q IsBigInt() = %v, want %v", c.dbType, got, c.isBigInt) - } - if got := f.IsDecimal(); got != c.isDecimal { - t.Errorf("%q IsDecimal() = %v, want %v", c.dbType, got, c.isDecimal) - } - if got := f.IsJsonB(); got != c.isJsonB { - t.Errorf("%q IsJsonB() = %v, want %v", c.dbType, got, c.isJsonB) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + f := Field{DatabaseType: c.dbType} + if got := f.IsString(); got != c.isString { + t.Errorf("%q IsString() = %v, want %v", c.dbType, got, c.isString) + } + if got := f.IsBigInt(); got != c.isBigInt { + t.Errorf("%q IsBigInt() = %v, want %v", c.dbType, got, c.isBigInt) + } + if got := f.IsDecimal(); got != c.isDecimal { + t.Errorf("%q IsDecimal() = %v, want %v", c.dbType, got, c.isDecimal) + } + if got := f.IsJsonB(); got != c.isJSONB { + t.Errorf("%q IsJsonB() = %v, want %v", c.dbType, got, c.isJSONB) + } + }) } } func TestIRFieldIsPatchable(t *testing.T) { + t.Parallel() cases := []struct { name string - f IRField + f Field want bool }{ - {"scalar", IRField{Name: "title", DatabaseType: "string"}, true}, - {"single-fk", IRField{Name: "order", DatabaseType: "uuid", IsRelation: true}, true}, - {"collection-fk", IRField{Name: "items", DatabaseType: "uuid", IsRelation: true, IsMany: true}, false}, - {"array", IRField{Name: "tags", DatabaseType: "array(string)"}, false}, - {"enum", IRField{Name: "status", DatabaseType: "Status"}, false}, - {"json", IRField{Name: "meta", DatabaseType: "json"}, false}, - {"primary", IRField{Name: "id", DatabaseType: "uuid", IsPrimary: true}, false}, - {"readonly", IRField{Name: "slug", DatabaseType: "string", IsReadonly: true}, false}, - {"sensitive", IRField{Name: "password", DatabaseType: "string"}, false}, - {"feature", IRField{Name: "version", DatabaseType: "int"}, false}, + {"scalar", Field{Name: "title", DatabaseType: "string"}, true}, + {"single-fk", Field{Name: "order", DatabaseType: "uuid", IsRelation: true}, true}, + {"collection-fk", Field{Name: "items", DatabaseType: "uuid", IsRelation: true, IsMany: true}, false}, + {"array", Field{Name: "tags", DatabaseType: "array(string)"}, false}, + {"enum", Field{Name: "status", DatabaseType: "Status"}, false}, + {"json", Field{Name: "meta", DatabaseType: "json"}, false}, + {"primary", Field{Name: "id", DatabaseType: "uuid", IsPrimary: true}, false}, + {"readonly", Field{Name: "slug", DatabaseType: "string", IsReadonly: true}, false}, + {"sensitive", Field{Name: "password", DatabaseType: "string"}, false}, + {"feature", Field{Name: "version", DatabaseType: "int"}, false}, } for _, c := range cases { - if got := c.f.IsPatchable(); got != c.want { - t.Errorf("%s IsPatchable() = %v, want %v", c.name, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := c.f.IsPatchable(); got != c.want { + t.Errorf("%s IsPatchable() = %v, want %v", c.name, got, c.want) + } + }) } } func TestIRFieldIsTextOnly(t *testing.T) { - if !(IRField{DatabaseType: "text"}).IsTextOnly() { + t.Parallel() + if !(Field{DatabaseType: "text"}).IsTextOnly() { t.Error("text should be IsTextOnly") } - if (IRField{DatabaseType: "string"}).IsTextOnly() { + if (Field{DatabaseType: "string"}).IsTextOnly() { t.Error("string should not be IsTextOnly") } } func TestIREntityTableNameAndForeignKeyColumnName(t *testing.T) { - e := IREntity{Name: "IPv4Rule", NamePlural: "IPv4Rules"} + t.Parallel() + e := Entity{Name: "IPv4Rule", NamePlural: "IPv4Rules"} if got := e.TableName(); got != "i_pv4rules" { t.Errorf("TableName() = %q, want %q (acronyms must match ToDatabaseColumnName)", got, "i_pv4rules") } - r := IRRelation{FieldName: "ipv4Address"} + r := Relation{FieldName: "ipv4Address"} if got := r.ForeignKeyColumnName(); got != "ipv4address_id" { t.Errorf("ForeignKeyColumnName() = %q, want %q (must match ToDatabaseColumnName, not template snakecase)", got, "ipv4address_id") } // A field already suffixed with Id must not get a double Id. - if got := (IRRelation{FieldName: "orderId"}).ForeignKeyColumnName(); got != "order_id" { + if got := (Relation{FieldName: "orderId"}).ForeignKeyColumnName(); got != "order_id" { t.Errorf("ForeignKeyColumnName(orderId) = %q, want order_id", got) } } func TestKindOf(t *testing.T) { + t.Parallel() cases := map[string]string{ "uuid": "uuid", "string": "text", @@ -177,7 +194,8 @@ func TestKindOf(t *testing.T) { } func TestIRPermissionsIsPublic(t *testing.T) { - p := &IRPermissions{Read: []string{"*"}, Create: []string{"Admin"}, Update: nil, Delete: []string{}} + t.Parallel() + p := &Permissions{Read: []string{"*"}, Create: []string{"Admin"}, Update: nil, Delete: []string{}} if !p.IsPublic("read") { t.Error("IsPublic(read) = false, want true") } @@ -190,13 +208,14 @@ func TestIRPermissionsIsPublic(t *testing.T) { if p.IsPublic("delete") { t.Error("IsPublic(delete) = true, want false") } - var nilPerms *IRPermissions + var nilPerms *Permissions if nilPerms.IsPublic("read") { t.Error("nil IsPublic(read) = true, want false") } } func TestIREndpointAuthPolicy(t *testing.T) { + t.Parallel() cases := map[string]string{ "list": "Read", "get": "Read", @@ -206,7 +225,7 @@ func TestIREndpointAuthPolicy(t *testing.T) { "delete": "Delete", } for op, want := range cases { - if got := (IREndpoint{Operation: op}).AuthPolicy(); got != want { + if got := (Endpoint{Operation: op}).AuthPolicy(); got != want { t.Errorf("AuthPolicy(%q) = %q, want %q", op, got, want) } } diff --git a/internal/ir/validations.go b/internal/ir/validations.go index 38a5477..0d7d56e 100644 --- a/internal/ir/validations.go +++ b/internal/ir/validations.go @@ -1,14 +1,18 @@ package ir -import "strings" +import ( + "cmp" + "slices" + "strings" +) -// IRValidationRule is a normalized, language-agnostic validation rule. The core +// ValidationRule is a normalized, language-agnostic validation rule. The core // derives these from the field's type, nullability and the declared validation // modifiers, so a bridge never re-parses modifier names or re-derives which // modifier is a length bound vs a numeric bound. It just maps each Kind (and its // stable Code) to its own syntax (DataAnnotations, FluentValidation, // class-validator, etc.). -type IRValidationRule struct { +type ValidationRule struct { // Kind is the semantic rule kind: required, email, url, ipv4, regex, // min_length, max_length, min_value, max_value. Kind string @@ -35,47 +39,74 @@ type IRValidationRule struct { Message string } +// ruleMeta is the single description of a normalized rule: wire code, +// ordering rank and default message. Adding a rule touches one table instead +// of three switches that can silently drift apart. +type ruleMeta struct { + code string + rank int + message func(value string, exclusive bool) string +} + +var validationRules = map[string]ruleMeta{ + "required": {"REQUIRED", 0, func(_ string, _ bool) string { return "is required" }}, + "email": {"EMAIL", 1, func(_ string, _ bool) string { return "must be a valid email address" }}, + "url": {"URL", 2, func(_ string, _ bool) string { return "must be a valid URL" }}, + "ipv4": {"IPV4", 3, func(_ string, _ bool) string { return "must be a valid IPv4 address" }}, + "regex": {"REGEX", 4, func(_ string, _ bool) string { return "must match the required format" }}, + "min_length": {"MIN_LENGTH", 5, func(v string, _ bool) string { return "must be at least " + v + " characters" }}, + "max_length": {"MAX_LENGTH", 6, func(v string, _ bool) string { return "must be at most " + v + " characters" }}, + "min_value": {"MIN_VALUE", 7, minValueMessage}, + "max_value": {"MAX_VALUE", 8, maxValueMessage}, +} + +func minValueMessage(value string, exclusive bool) string { + if exclusive { + return "must be greater than " + value + } + return "must be greater than or equal to " + value +} + +func maxValueMessage(value string, exclusive bool) string { + if exclusive { + return "must be less than " + value + } + return "must be less than or equal to " + value +} + // validationRuleMeta returns the stable wire code and default message for a // normalized rule kind. The value is interpolated into length/numeric messages. func validationRuleMeta(kind, value string, exclusive bool) (code, message string) { - switch kind { - case "required": - return "REQUIRED", "is required" - case "email": - return "EMAIL", "must be a valid email address" - case "url": - return "URL", "must be a valid URL" - case "ipv4": - return "IPV4", "must be a valid IPv4 address" - case "regex": - return "REGEX", "must match the required format" - case "min_length": - return "MIN_LENGTH", "must be at least " + value + " characters" - case "max_length": - return "MAX_LENGTH", "must be at most " + value + " characters" - case "min_value": - if exclusive { - return "MIN_VALUE", "must be greater than " + value - } - return "MIN_VALUE", "must be greater than or equal to " + value - case "max_value": - if exclusive { - return "MAX_VALUE", "must be less than " + value - } - return "MAX_VALUE", "must be less than or equal to " + value + meta, ok := validationRules[kind] + if !ok { + return strings.ToUpper(kind), "" } - return strings.ToUpper(kind), "" + return meta.code, meta.message(value, exclusive) } // newRule builds a normalized rule with its stable code and default message. -func newRule(kind, value string, exclusive bool) IRValidationRule { +func newRule(kind, value string, exclusive bool) ValidationRule { code, message := validationRuleMeta(kind, value, exclusive) - return IRValidationRule{Kind: kind, Code: code, Value: value, Exclusive: exclusive, Message: message} + return ValidationRule{Kind: kind, Code: code, Value: value, Exclusive: exclusive, Message: message} +} + +// validationRuleOrder is the semantic rank used to order normalized rules. +// The order is required → format (email/url/ipv4/regex) → length bounds +// (min→max) → numeric bounds (min→max), independent of the order in which the +// modifiers were declared (convertValidations sorts keys alphabetically, so +// declaration order cannot be relied on here). +func validationRuleOrder(kind string) int { + if meta, ok := validationRules[kind]; ok { + return meta.rank + } + return 9 } // ValidationRules returns the field's validations as a normalized, ordered list -// of rules. The order is stable and semantic: required first, then format -// validators, then length bounds, then numeric bounds. +// of rules. The order is stable and semantic: required, then format validators +// (email/url/ipv4/regex), then length bounds (min_length → max_length), then +// numeric bounds (min_value → max_value, inclusive or exclusive). Rules of the +// same kind keep their relative input order. // // Mapping from the raw modifiers: // @@ -85,8 +116,10 @@ func newRule(kind, value string, exclusive bool) IRValidationRule { // min_value / max_value on numeric types // gte / lte -> inclusive min_value / max_value // gt / lt -> min_value / max_value with Exclusive=true -func (f IRField) ValidationRules() []IRValidationRule { - rules := make([]IRValidationRule, 0, len(f.Validations)+1) +// min_length / max_length / -> the canonical rule kind, as-is +// min_value / max_value +func (f Field) ValidationRules() []ValidationRule { + rules := make([]ValidationRule, 0, len(f.Validations)+1) if !f.IsNullable && !f.IsPrimary { // Non-nullable fields are required by construction. (A nullable field @@ -107,6 +140,10 @@ func (f IRField) ValidationRules() []IRValidationRule { rules = append(rules, newRule(name, "", false)) case "regex": rules = append(rules, newRule("regex", v.Value, false)) + case "min_length", "max_length", "min_value", "max_value": + // Canonical rule names are accepted as-is so IR fields built + // directly (tests, bridge-side helpers) use the same vocabulary. + rules = append(rules, newRule(name, v.Value, false)) case "min", "max": if f.IsNumeric() { rules = append(rules, newRule(name+"_value", v.Value, false)) @@ -124,5 +161,11 @@ func (f IRField) ValidationRules() []IRValidationRule { } } + // Stable sort keeps same-rank rules in declaration order while enforcing + // the semantic contract above. + slices.SortStableFunc(rules, func(a, b ValidationRule) int { + return cmp.Compare(validationRuleOrder(a.Kind), validationRuleOrder(b.Kind)) + }) + return rules } diff --git a/internal/lexer/lexer.go b/internal/lexer/lexer.go index c5f43db..c81ffca 100644 --- a/internal/lexer/lexer.go +++ b/internal/lexer/lexer.go @@ -1,3 +1,4 @@ +// Package lexer parses field definition strings into structured definitions. package lexer import ( @@ -39,18 +40,13 @@ type FieldDefinition struct { DefaultIsFunc bool // true if default:now() } -// Lexer parses field definition strings into FieldDefinition -type Lexer struct { - input string -} - -// NewLexer creates a new Lexer -func NewLexer(input string) *Lexer { - return &Lexer{input: strings.TrimSpace(input)} +// Parse parses a full field definition: "string [required, max:255]" +func Parse(input string) (*FieldDefinition, error) { + return parse(input, nil) } -// Parse parses a full field definition: "string [required, max:255]" -func (l *Lexer) Parse() (*FieldDefinition, error) { +func parse(input string, extraStringMods []string) (*FieldDefinition, error) { + input = strings.TrimSpace(input) fd := &FieldDefinition{ Validations: make(map[string]string), } @@ -58,22 +54,26 @@ func (l *Lexer) Parse() (*FieldDefinition, error) { // Split into type and modifiers: "string [required, max:255]". Split at the // first "[" only; the rest (modifiers, which may themselves contain brackets, // e.g. default values like "[a, b, c]") is handled by parseModifiers. - parts := strings.SplitN(l.input, "[", 2) + parts := strings.SplitN(input, "[", 2) typePart := strings.TrimSpace(parts[0]) if typePart == "" { - return nil, fmt.Errorf("empty field type: %s", l.input) + return nil, fmt.Errorf("empty field type: %s", input) } // Parse the type - if err := l.parseType(typePart, fd); err != nil { + if err := parseType(typePart, fd); err != nil { return nil, err } // Parse modifiers if present if len(parts) > 1 { - modifierStr := strings.TrimSuffix(strings.TrimSpace(parts[1]), "]") - if err := l.parseModifiers(modifierStr, fd); err != nil { + modifierStr := strings.TrimSpace(parts[1]) + if !strings.HasSuffix(modifierStr, "]") { + return nil, fmt.Errorf("unterminated modifier list in %q: expected ']'", input) + } + modifierStr = strings.TrimSuffix(modifierStr, "]") + if err := parseModifiers(modifierStr, fd, extraStringMods); err != nil { return nil, err } } @@ -86,49 +86,62 @@ func (l *Lexer) Parse() (*FieldDefinition, error) { return fd, nil } +// callType describes one `kind(Target)` field declaration. The three +// variants differ only in kind, destination field and diagnostics. +type callType struct { + kind string + prefix string + missingParen string + missingTarget string + isRelation bool +} + +var callTypes = []callType{ + {specmeta.FieldTypeRelation, specmeta.FieldTypeRelation + "(", "relation type requires a closing parenthesis", "relation type requires a target entity name", true}, + {specmeta.FieldTypeArray, specmeta.FieldTypeArray + "(", "array type requires a closing parenthesis", "array type requires an element type", false}, + {specmeta.FieldTypeEnum, specmeta.FieldTypeEnum + "(", "enum type requires a closing parenthesis", "enum type requires a name", false}, +} + +// fieldFlags are the bare modifiers that set a boolean on the field. Keeping +// them in one table lets validation reuse the same vocabulary. +var fieldFlags = map[string]func(*FieldDefinition){ + "primary": func(f *FieldDefinition) { f.IsPrimary = true }, + "optional": func(f *FieldDefinition) { f.IsOptional = true }, + "required": func(f *FieldDefinition) { f.IsRequired = true }, + "unique": func(f *FieldDefinition) { f.IsUnique = true }, + "hidden": func(f *FieldDefinition) { f.IsHidden = true }, + "readonly": func(f *FieldDefinition) { f.IsReadonly = true }, + "many": func(f *FieldDefinition) { f.IsMany = true }, +} + // parseType parses the type portion (e.g. "string", "relation(User)", "array(int)", "enum(Status)") -func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { +func parseType(typeStr string, fd *FieldDefinition) error { typeStr = strings.TrimSpace(typeStr) - // Check for relation(EntityName) - if strings.HasPrefix(typeStr, "relation(") { - fd.Type = "relation" - targetEntity := strings.TrimPrefix(typeStr, "relation(") - targetEntity = strings.TrimSuffix(targetEntity, ")") - fd.TargetEntity = strings.TrimSpace(targetEntity) - if fd.TargetEntity == "" { - return fmt.Errorf("relation type requires a target entity name") + for _, spec := range callTypes { + if !strings.HasPrefix(typeStr, spec.prefix) { + continue } - return nil - } - - // Check for array(Type) - if strings.HasPrefix(typeStr, "array(") { - fd.Type = "array" - innerType := strings.TrimPrefix(typeStr, "array(") - innerType = strings.TrimSuffix(innerType, ")") - fd.TargetType = strings.TrimSpace(innerType) - if fd.TargetType == "" { - return fmt.Errorf("array type requires an element type") + // A missing closing paren is an error, not a prefix to trim away. + if !strings.HasSuffix(typeStr, ")") { + return fmt.Errorf("%s", spec.missingParen) } - return nil - } - - // Check for enum(Name) - if strings.HasPrefix(typeStr, "enum(") { - fd.Type = "enum" - enumName := strings.TrimPrefix(typeStr, "enum(") - enumName = strings.TrimSuffix(enumName, ")") - fd.TargetType = strings.TrimSpace(enumName) - if fd.TargetType == "" { - return fmt.Errorf("enum type requires a name") + target := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(typeStr, spec.prefix), ")")) + if target == "" { + return fmt.Errorf("%s", spec.missingTarget) + } + fd.Type = spec.kind + if spec.isRelation { + fd.TargetEntity = target + } else { + fd.TargetType = target } return nil } // Built-in types if !specmeta.IsFieldType(typeStr) { - return fmt.Errorf("unknown type: %s. valid types: string, int, uuid, relation, array, enum, json, text, etc.", typeStr) + return fmt.Errorf("unknown type %q; valid types: %s", typeStr, strings.Join(specmeta.FieldTypes, ", ")) } fd.Type = typeStr @@ -136,7 +149,7 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { } // parseModifiers parses modifiers inside square brackets -func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { +func parseModifiers(modStr string, fd *FieldDefinition, extraStringMods []string) error { modifiers := splitModifiers(modStr) for _, mod := range modifiers { @@ -154,61 +167,48 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { // Strip quotes if present value = strings.Trim(value, `"'`) - switch key { - case "min", "max", "gte", "gt", "lte", "lt", "regex": - fd.Validations[key] = value - case "default": - // Check for function-style defaults like now(), uuid() - if strings.HasSuffix(value, "()") { - fd.DefaultIsFunc = true - fd.DefaultValue = value[:len(value)-2] // strip () - } else { - fd.DefaultValue = value - } - case "on_delete": - if !specmeta.IsOnDeleteValue(value) { - return fmt.Errorf("unknown on_delete value: %s. valid: cascade, set_null, restrict, no_action", value) + switch { + case specmeta.IsValidationModifier(key, extraStringMods): + fd.Validations[key] = value + case key == "default": + // Check for function-style defaults like now(), uuid() + if strings.HasSuffix(value, "()") { + fd.DefaultIsFunc = true + fd.DefaultValue = value[:len(value)-2] // strip () + } else { + fd.DefaultValue = value + } + case key == "on_delete": + if !specmeta.IsOnDeleteValue(value) { + return fmt.Errorf("unknown on_delete value: %s. valid: %s", value, strings.Join(specmeta.OnDeleteValues, ", ")) + } + fd.OnDelete = value + case key == "old_name": + // Rename hint: `name: string [required, old_name: title]`. The value is + // the field's previous name; the migration engine + bridges turn it into + // a safe column rename instead of a destructive drop + add. + if value == "" { + return fmt.Errorf("old_name requires a previous field name") + } + fd.OldName = value + default: + return fmt.Errorf("unknown modifier: %s", key) } - fd.OnDelete = value - case "old_name": - // Rename hint: `name: string [required, old_name: title]`. The value is - // the field's previous name; the migration engine + bridges turn it into - // a safe column rename instead of a destructive drop + add. - if value == "" { - return fmt.Errorf("old_name requires a previous field name") - } - fd.OldName = value - default: - return fmt.Errorf("unknown modifier: %s", key) + continue } + + // Bare string flags live in specmeta alongside their key:value forms. + if specmeta.IsStringFlagValidationModifier(mod) { + fd.Validations[mod] = "true" continue } // Flag modifiers (no value) - switch mod { - case "primary": - fd.IsPrimary = true - case "optional": - fd.IsOptional = true - case "required": - fd.IsRequired = true - case "unique": - fd.IsUnique = true - case "hidden": - fd.IsHidden = true - case "readonly": - fd.IsReadonly = true - case "many": - fd.IsMany = true - case "email": - fd.Validations["email"] = "true" - case "url": - fd.Validations["url"] = "true" - case "ipv4": - fd.Validations["ipv4"] = "true" - default: - return fmt.Errorf("unknown modifier flag: %s", mod) + if set, ok := fieldFlags[mod]; ok { + set(fd) + continue } + return fmt.Errorf("unknown modifier flag: %s", mod) } return nil @@ -219,44 +219,7 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { // Without this, "default:[a, b, c]" would be chopped at every comma and the // default value would never round-trip through parse → serialize → parse. func splitModifiers(s string) []string { - var out []string - var cur strings.Builder - depth := 0 - var quote byte - for i := 0; i < len(s); i++ { - c := s[i] - if quote != 0 { - cur.WriteByte(c) - if c == quote { - quote = 0 - } - continue - } - switch c { - case '\'', '"': - quote = c - cur.WriteByte(c) - case '[': - depth++ - cur.WriteByte(c) - case ']': - if depth > 0 { - depth-- - } - cur.WriteByte(c) - case ',': - if depth == 0 { - out = append(out, cur.String()) - cur.Reset() - continue - } - cur.WriteByte(c) - default: - cur.WriteByte(c) - } - } - out = append(out, cur.String()) - return out + return specmeta.SplitRespectingQuotes(s) } // Validate checks the logical consistency of a FieldDefinition @@ -272,56 +235,36 @@ func (fd *FieldDefinition) Validate() error { } // on_delete is only valid on relation fields - if fd.OnDelete != "" && fd.Type != "relation" { + if fd.OnDelete != "" && fd.Type != specmeta.FieldTypeRelation { return fmt.Errorf("on_delete is only valid on relation fields") } // many modifier is only valid on relation fields - if fd.IsMany && fd.Type != "relation" { + if fd.IsMany && fd.Type != specmeta.FieldTypeRelation { return fmt.Errorf("many modifier is only valid on relation fields") } // on_delete:set_null is only valid for optional relation fields - if fd.Type == "relation" && fd.OnDelete == "set_null" && !fd.IsOptional { + if fd.Type == specmeta.FieldTypeRelation && fd.OnDelete == "set_null" && !fd.IsOptional { return fmt.Errorf("on_delete:set_null is only allowed for optional relation fields") } // Validate regex if present if regex, ok := fd.Validations["regex"]; ok { if _, err := regexp.Compile(regex); err != nil { - return fmt.Errorf("invalid regex '%s': %v", regex, err) + return fmt.Errorf("invalid regex %q: %w", regex, err) } } // old_name must be a valid identifier (like the field name itself). - if fd.OldName != "" && !isValidIdentifier(fd.OldName) { + if fd.OldName != "" && !specmeta.IsValidIdentifier(fd.OldName) { return fmt.Errorf("old_name %q is not a valid field name", fd.OldName) } return nil } -// isValidIdentifier reports whether s is a valid domain.yaml field name. -func isValidIdentifier(s string) bool { - if s == "" { - return false - } - for i, r := range s { - if i == 0 { - if r != '_' && !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') { - return false - } - continue - } - if r != '_' && !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') && !(r >= '0' && r <= '9') { - return false - } - } - return true -} - -// ParseFieldString is a convenience function for parsing a field string +// ParseFieldString is a backwards-compatible alias for Parse. func ParseFieldString(fieldString string) (*FieldDefinition, error) { - lexer := NewLexer(fieldString) - return lexer.Parse() + return Parse(fieldString) } diff --git a/internal/lexer/lexer_dry_test.go b/internal/lexer/lexer_dry_test.go new file mode 100644 index 0000000..521c65a --- /dev/null +++ b/internal/lexer/lexer_dry_test.go @@ -0,0 +1,92 @@ +package lexer + +import ( + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) + +func TestParseArrayTypeUsesSpecmetaInner(t *testing.T) { + t.Parallel() + cases := []struct { + name string + in string + want string + }{ + {name: "primitive element", in: "array(int)", want: "int"}, + {name: "enum element", in: "array(Status)", want: "Status"}, + {name: "whitespace is trimmed", in: "array( uuid )", want: "uuid"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + fd, err := ParseFieldString(c.in) + if err != nil { + t.Fatalf("ParseFieldString(%q) error = %v", c.in, err) + } + if fd.Type != "array" { + t.Errorf("Type = %q, want array", fd.Type) + } + if fd.TargetType != c.want { + t.Errorf("TargetType = %q, want %q", fd.TargetType, c.want) + } + canonicalInner := strings.TrimSpace(specmeta.ParseArrayInner(strings.TrimSpace(c.in))) + if fd.TargetType != canonicalInner { + t.Errorf("TargetType = %q, want canonical specmeta inner %q", fd.TargetType, canonicalInner) + } + }) + } +} + +func TestLexerErrorMessagesUseSpecmetaLists(t *testing.T) { + t.Parallel() + t.Run("unknown type lists every declared field type", func(t *testing.T) { + t.Parallel() + _, err := ParseFieldString("nope") + if err == nil { + t.Fatal("expected error for unknown type") + } + want := strings.Join(specmeta.FieldTypes, ", ") + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not contain %q", err, want) + } + }) + t.Run("unknown on_delete lists every declared behavior", func(t *testing.T) { + t.Parallel() + _, err := ParseFieldString("relation(User) [on_delete:nope]") + if err == nil { + t.Fatal("expected error for unknown on_delete value") + } + want := strings.Join(specmeta.OnDeleteValues, ", ") + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not contain %q", err, want) + } + }) +} + +func TestLexerOldNameUsesSharedIdentifierRule(t *testing.T) { + t.Parallel() + cases := []struct { + name string + oldName string + wantErr bool + }{ + {name: "valid old name", oldName: "previousTitle"}, + {name: "leading digit rejected", oldName: "1Title", wantErr: true}, + {name: "hyphen rejected", oldName: "old-title", wantErr: true}, + {name: "non-ASCII rejected", oldName: "староеИмя", wantErr: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + _, err := ParseFieldString("string [old_name:" + c.oldName + "]") + if (err != nil) != c.wantErr { + t.Fatalf("ParseFieldString(old_name:%q) error = %v, wantErr %v", c.oldName, err, c.wantErr) + } + if specmeta.IsValidIdentifier(c.oldName) == c.wantErr { + t.Errorf("shared identifier rule disagrees for %q", c.oldName) + } + }) + } +} diff --git a/internal/lexer/lexer_hardening_test.go b/internal/lexer/lexer_hardening_test.go new file mode 100644 index 0000000..cb440b7 --- /dev/null +++ b/internal/lexer/lexer_hardening_test.go @@ -0,0 +1,51 @@ +package lexer + +import ( + "strings" + "testing" +) + +func FuzzParseFieldString(f *testing.F) { + for _, seed := range []string{ + "string [required, max:255]", + "uuid [primary", + "relation(User) [many, on_delete:cascade]", + "array(int) [default:[1, 2]]", + "", + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, input string) { + field, err := Parse(input) + if err == nil && field == nil { + t.Fatalf("Parse(%q) returned neither a field nor an error", input) + } + }) +} + +func TestUnterminatedModifierList(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + input string + wantErr bool + }{ + {name: "missing closing bracket", input: "uuid [primary", wantErr: true}, + {name: "closed bracket", input: "uuid [primary]"}, + {name: "array default keeps its brackets", input: `string [default:[a, b]]`}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + _, err := Parse(c.input) + if c.wantErr { + if err == nil || !strings.Contains(err.Error(), "unterminated modifier list") { + t.Fatalf("%q error = %v, want unterminated modifier list", c.input, err) + } + return + } + if err != nil { + t.Fatalf("%q unexpected error: %v", c.input, err) + } + }) + } +} diff --git a/internal/lexer/lexer_test.go b/internal/lexer/lexer_test.go index 62057d8..4b67d0a 100644 --- a/internal/lexer/lexer_test.go +++ b/internal/lexer/lexer_test.go @@ -3,27 +3,35 @@ package lexer import ( "strings" "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" ) func TestParsePrimitiveTypes(t *testing.T) { - tests := []struct { + t.Parallel() + // Generate the positive cases from specmeta so a new primitive cannot be + // added to the spec without this test covering it. + tests := make([]struct { input string wantType string wantErr bool - }{ - {"string", "string", false}, - {"int", "int", false}, - {"uuid", "uuid", false}, - {"boolean", "boolean", false}, - {"datetime", "datetime", false}, - {"decimal", "decimal", false}, - {"text", "text", false}, - {"json", "json", false}, - {"unknown_type", "", true}, - } + }, 0, len(specmeta.PrimitiveFieldTypes)+1) + for _, name := range specmeta.PrimitiveFieldTypes { + tests = append(tests, struct { + input string + wantType string + wantErr bool + }{input: name, wantType: name}) + } + tests = append(tests, struct { + input string + wantType string + wantErr bool + }{input: "unknown_type", wantErr: true}) for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if (err != nil) != tt.wantErr { t.Errorf("ParseFieldString() error = %v, wantErr %v", err, tt.wantErr) @@ -37,6 +45,7 @@ func TestParsePrimitiveTypes(t *testing.T) { } func TestParseRelationType(t *testing.T) { + t.Parallel() tests := []struct { input string wantType string @@ -50,6 +59,7 @@ func TestParseRelationType(t *testing.T) { for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if err != nil { t.Errorf("ParseFieldString() error = %v", err) @@ -69,13 +79,14 @@ func TestParseRelationType(t *testing.T) { } func TestParseModifiers(t *testing.T) { + t.Parallel() tests := []struct { - input string - wantPrimary bool - wantOptional bool - wantUnique bool - wantHidden bool - wantReadonly bool + input string + wantPrimary bool + wantOptional bool + wantUnique bool + wantHidden bool + wantReadonly bool }{ {"string [primary]", true, false, false, false, false}, {"string [optional]", false, true, false, false, false}, @@ -87,6 +98,7 @@ func TestParseModifiers(t *testing.T) { for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if err != nil { t.Errorf("ParseFieldString() error = %v", err) @@ -112,6 +124,7 @@ func TestParseModifiers(t *testing.T) { } func TestParseValidations(t *testing.T) { + t.Parallel() fd, err := ParseFieldString("string [min:5, max:100, email]") if err != nil { t.Fatalf("ParseFieldString() error = %v", err) @@ -129,6 +142,7 @@ func TestParseValidations(t *testing.T) { } func TestParseDefaults(t *testing.T) { + t.Parallel() tests := []struct { input string wantDefault string @@ -141,6 +155,7 @@ func TestParseDefaults(t *testing.T) { for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if err != nil { t.Errorf("ParseFieldString() error = %v", err) @@ -157,10 +172,11 @@ func TestParseDefaults(t *testing.T) { } func TestParseArrayDefault(t *testing.T) { + t.Parallel() tests := []struct { - input string - wantDefault string - wantArray bool + input string + wantDefault string + wantArray bool wantElementType string }{ {"array(string) [optional, default:[a, b, c]]", "[a, b, c]", true, "string"}, @@ -171,6 +187,7 @@ func TestParseArrayDefault(t *testing.T) { for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if err != nil { t.Errorf("ParseFieldString() error = %v", err) @@ -195,6 +212,7 @@ func TestParseArrayDefault(t *testing.T) { } func TestParseOnDelete(t *testing.T) { + t.Parallel() tests := []struct { input string wantBehavior string @@ -209,6 +227,7 @@ func TestParseOnDelete(t *testing.T) { for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { + t.Parallel() fd, err := ParseFieldString(tt.input) if (err != nil) != tt.wantErr { t.Errorf("ParseFieldString() error = %v, wantErr %v", err, tt.wantErr) @@ -222,6 +241,7 @@ func TestParseOnDelete(t *testing.T) { } func TestParseOldName(t *testing.T) { + t.Parallel() fd, err := ParseFieldString("string [required, old_name: title]") if err != nil { t.Fatalf("ParseFieldString() error = %v", err) @@ -244,6 +264,7 @@ func TestParseOldName(t *testing.T) { } func TestParseOldNameInvalid(t *testing.T) { + t.Parallel() tests := []string{ "string [old_name:]", "string [old_name: not valid name]", @@ -251,6 +272,7 @@ func TestParseOldNameInvalid(t *testing.T) { } for _, input := range tests { t.Run(input, func(t *testing.T) { + t.Parallel() if _, err := ParseFieldString(input); err == nil { t.Errorf("ParseFieldString(%q) expected an error", input) } @@ -259,6 +281,7 @@ func TestParseOldNameInvalid(t *testing.T) { } func TestParseArrayType(t *testing.T) { + t.Parallel() fd, err := ParseFieldString("array(int)") if err != nil { t.Fatalf("ParseFieldString() error = %v", err) @@ -273,6 +296,7 @@ func TestParseArrayType(t *testing.T) { } func TestParseEnumType(t *testing.T) { + t.Parallel() fd, err := ParseFieldString("enum(Status)") if err != nil { t.Fatalf("ParseFieldString() error = %v", err) @@ -287,6 +311,7 @@ func TestParseEnumType(t *testing.T) { } func TestParseComplexField(t *testing.T) { + t.Parallel() // Complex case: title: string [required, min:5, max:120] fd, err := ParseFieldString("string [required, min:5, max:120]") if err != nil { @@ -308,6 +333,7 @@ func TestParseComplexField(t *testing.T) { } func TestParseRelationEmptyTarget(t *testing.T) { + t.Parallel() _, err := ParseFieldString("relation()") if err == nil { t.Fatal("expected error for empty relation target") @@ -318,6 +344,7 @@ func TestParseRelationEmptyTarget(t *testing.T) { } func TestParseArrayEmptyType(t *testing.T) { + t.Parallel() _, err := ParseFieldString("array()") if err == nil { t.Fatal("expected error for empty array type") @@ -328,6 +355,7 @@ func TestParseArrayEmptyType(t *testing.T) { } func TestParseEnumEmptyName(t *testing.T) { + t.Parallel() _, err := ParseFieldString("enum()") if err == nil { t.Fatal("expected error for empty enum name") @@ -338,6 +366,7 @@ func TestParseEnumEmptyName(t *testing.T) { } func TestParsePrimaryKeyIsRequired(t *testing.T) { + t.Parallel() // The lexer no longer normalizes primary→required; that's the parser's job. // The lexer only parses syntax; semantic normalization happens in parser.parseField. fd, err := ParseFieldString("uuid [primary]") @@ -354,6 +383,7 @@ func TestParsePrimaryKeyIsRequired(t *testing.T) { } func TestParsePrimaryKeyWithExplicitRequired(t *testing.T) { + t.Parallel() fd, err := ParseFieldString("uuid [primary, required]") if err != nil { t.Fatalf("ParseFieldString() error = %v", err) @@ -367,6 +397,7 @@ func TestParsePrimaryKeyWithExplicitRequired(t *testing.T) { } func TestParseOnDeleteOnNonRelationField(t *testing.T) { + t.Parallel() _, err := ParseFieldString("string [on_delete:cascade]") if err == nil { t.Fatal("expected error for on_delete on non-relation field") @@ -377,6 +408,7 @@ func TestParseOnDeleteOnNonRelationField(t *testing.T) { } func TestParseManyOnNonRelationField(t *testing.T) { + t.Parallel() _, err := ParseFieldString("string [many]") if err == nil { t.Fatal("expected error for many on non-relation field") @@ -387,6 +419,7 @@ func TestParseManyOnNonRelationField(t *testing.T) { } func TestParseRequiredOptionalConflict(t *testing.T) { + t.Parallel() _, err := ParseFieldString("string [required, optional]") if err == nil { t.Fatal("expected error for required+optional conflict") @@ -395,3 +428,60 @@ func TestParseRequiredOptionalConflict(t *testing.T) { t.Errorf("unexpected error: %v", err) } } + +func TestLexerRejectsUnclosedTypeDeclaration(t *testing.T) { + t.Parallel() + cases := []struct { + input string + wantErr bool + wantType string + wantInner string + }{ + {input: "array(int", wantErr: true}, + {input: "relation(User", wantErr: true}, + // The unclosed enum form is enum(Status; enum(Status) is valid. + {input: "enum(Status", wantErr: true}, + {input: "array(int)", wantType: "array", wantInner: "int"}, + {input: "relation(User)", wantType: "relation", wantInner: "User"}, + {input: "enum(Status)", wantType: "enum", wantInner: "Status"}, + } + for _, c := range cases { + t.Run(c.input, func(t *testing.T) { + t.Parallel() + fd, err := ParseFieldString(c.input) + if c.wantErr { + if err == nil { + t.Fatalf("ParseFieldString(%q) accepted an unclosed declaration", c.input) + } + if !strings.Contains(err.Error(), "closing parenthesis") { + t.Errorf("unexpected error: %v", err) + } + return + } + if err != nil { + t.Fatalf("ParseFieldString(%q) error = %v", c.input, err) + } + if fd.Type != c.wantType { + t.Errorf("Type = %q, want %q", fd.Type, c.wantType) + } + got := fd.TargetType + if fd.Type == "relation" { + got = fd.TargetEntity + } + if got != c.wantInner { + t.Errorf("target = %q, want %q", got, c.wantInner) + } + }) + } +} + +func TestLexerAcceptsInjectedStringModifier(t *testing.T) { + t.Parallel() + fd, err := parse("string [startsWith:foo]", []string{"startsWith"}) + if err != nil { + t.Fatalf("parse() error = %v", err) + } + if got := fd.Validations["startsWith"]; got != "foo" { + t.Errorf("Validations[startsWith] = %q, want foo", got) + } +} diff --git a/internal/netutil/netutil.go b/internal/netutil/netutil.go new file mode 100644 index 0000000..e58f72e --- /dev/null +++ b/internal/netutil/netutil.go @@ -0,0 +1,127 @@ +// Package netutil holds the shared HTTP primitives used by remote probes and +// downloads. It is stdlib-only and carries no language- or bridge-specific +// policy: callers supply the client, the body cap and their redirect rule. +package netutil + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" +) + +// DefaultMaxBodyBytes caps remote responses in the bridge cache and package +// registry. Both paths fetch the same kind of untrusted remote manifest. +const DefaultMaxBodyBytes = 1 << 20 + +// NewBoundedClient builds an HTTP client with a fixed timeout and an optional +// transport. Shared construction keeps remote probes from drifting apart. +func NewBoundedClient(timeout time.Duration, transport http.RoundTripper) *http.Client { + return &http.Client{Timeout: timeout, Transport: transport} +} + +// RedactedURL reduces a URL to scheme and host for error messages. Userinfo, +// path, query and fragment are dropped: any of them can carry a secret. +func RedactedURL(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Hostname() == "" { + return "" + } + return u.Scheme + "://" + u.Hostname() +} + +// RedactURLError drops the raw URL carried by *url.Error while keeping the +// underlying reason available for %w wrapping. Nested url.Errors are unwrapped +// as well, since a transport may add its own URL-bearing error. Remote probes +// share this rule so error messages cannot leak tokens from different callers. +func RedactURLError(err error) error { + for { + var urlErr *url.Error + if !errors.As(err, &urlErr) || urlErr.Err == nil { + return err + } + err = urlErr.Err + } +} + +// ValidateRedirect checks a redirect target before the client follows it. A +// returned error stops the request. +type ValidateRedirect func(*url.URL) error + +// RedirectPolicy turns a ValidateRedirect into an http.Client CheckRedirect +// hook. It runs for every hop before the client issues the follow-up request, +// so a forbidden host is never contacted. Returned errors are redacted: only +// the scheme and hostname of the target are named, never userinfo, path or +// query (which may carry tokens). +func RedirectPolicy(validate ValidateRedirect) func(*http.Request, []*http.Request) error { + if validate == nil { + return nil + } + return func(req *http.Request, _ []*http.Request) error { + if err := validate(req.URL); err != nil { + return fmt.Errorf("redirect from %s: %w", RedactedURL(req.URL.String()), RedactURLError(err)) + } + return nil + } +} + +// ReadBoundedBody reads a successful GET response, capping the body at +// maxBytes. A larger body is an error, never a silently truncated success. +// validateRedirect (when non-nil) sees the final request URL when it differs +// from the original URL, i.e. after a redirect the client followed. A direct +// response to the original URL is not a redirect and is not validated here. +func ReadBoundedBody(resp *http.Response, rawURL string, maxBytes int64, validateRedirect ValidateRedirect) ([]byte, error) { + defer func() { _ = resp.Body.Close() }() + scope := RedactedURL(rawURL) + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("http %d for %s", resp.StatusCode, scope) + } + if validateRedirect != nil && resp.Request != nil && resp.Request.URL != nil && + resp.Request.URL.String() != rawURL { + if err := validateRedirect(resp.Request.URL); err != nil { + return nil, fmt.Errorf("redirect from %s: %w", scope, RedactURLError(err)) + } + } + if maxBytes <= 0 { + return nil, fmt.Errorf("invalid response limit %d for %s", maxBytes, scope) + } + + // Read one byte past the cap so an oversized body is rejected instead of + // being truncated into a plausible-looking manifest or binary. + data, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes+1)) + if err != nil { + return nil, fmt.Errorf("read %s: %w", scope, RedactURLError(err)) + } + if int64(len(data)) > maxBytes { + return nil, fmt.Errorf("response from %s exceeds %d bytes", scope, maxBytes) + } + return data, nil +} + +// BoundedGet performs a GET bound to ctx, using client and capping the response +// body at maxBytes. All errors name only the redacted scheme+host of rawURL. +// The caller keeps ownership of the client: BoundedGet never mutates it. When +// validateRedirect is non-nil, a shallow copy carries a CheckRedirect hook that +// validates every hop before the follow-up request is issued; ReadBoundedBody +// re-checks the final URL as a second line of defence. +func BoundedGet(ctx context.Context, client *http.Client, rawURL string, maxBytes int64, validateRedirect ValidateRedirect) ([]byte, error) { + scope := RedactedURL(rawURL) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, fmt.Errorf("build request for %s: %w", scope, RedactURLError(err)) + } + if validateRedirect != nil { + guarded := *client + guarded.CheckRedirect = RedirectPolicy(validateRedirect) + client = &guarded + } + resp, err := client.Do(req) //nolint:bodyclose // ReadBoundedBody closes the body + if err != nil { + return nil, fmt.Errorf("request %s: %w", scope, RedactURLError(err)) + } + return ReadBoundedBody(resp, rawURL, maxBytes, validateRedirect) +} diff --git a/internal/netutil/netutil_test.go b/internal/netutil/netutil_test.go new file mode 100644 index 0000000..7b5149a --- /dev/null +++ b/internal/netutil/netutil_test.go @@ -0,0 +1,168 @@ +package netutil + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestRedactedURL(t *testing.T) { + cases := []struct { + name string + raw string + want string + }{ + {"userinfo query and fragment", "https://user:secret@github.com/dc?token=abc#f", "https://github.com"}, + {"port and path are dropped", "https://github.com:8443/releases/download/dc", "https://github.com"}, + {"plain", "https://api.github.com/repos/owner/repo", "https://api.github.com"}, + {"malformed", "https://[::1", ""}, + {"no scheme", "github.com/dc", ""}, + {"no host", "https:///dc", ""}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := RedactedURL(tt.raw); got != tt.want { + t.Errorf("RedactedURL(%q) = %q, want %q", tt.raw, got, tt.want) + } + }) + } +} + +func responseFor(t *testing.T, status int, body string, finalURL string) *http.Response { + t.Helper() + u, err := url.Parse(finalURL) + if err != nil { + t.Fatal(err) + } + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(strings.NewReader(body)), + Request: &http.Request{URL: u}, + } +} + +func TestReadBoundedBodyRejectsOversize(t *testing.T) { + raw := "https://user:secret@github.com/dc?token=abc" + for _, tt := range []struct { + name string + body string + wantErr bool + }{ + {"at the cap", "1234", false}, + {"one byte over", "12345", true}, + } { + t.Run(tt.name, func(t *testing.T) { + got, err := ReadBoundedBody(responseFor(t, http.StatusOK, tt.body, raw), raw, 4, nil) //nolint:bodyclose // ReadBoundedBody closes the body + if tt.wantErr { + if err == nil || !strings.Contains(err.Error(), "exceeds") { + t.Fatalf("err = %v, want an oversize error", err) + } + } else if err != nil || string(got) != tt.body { + t.Fatalf("body = %q, %v; want %q", got, err, tt.body) + } + if err != nil && (strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token=abc")) { + t.Errorf("error leaked credentials: %q", err) + } + }) + } +} + +func TestReadBoundedBodyChecksRedirect(t *testing.T) { + raw := "https://user:secret@github.com/dc?token=abc" + reject := func(u *url.URL) error { + if u.Hostname() != "github.com" { + return fmt.Errorf("host %q is not allowed", u.Hostname()) + } + return nil + } + + if _, err := ReadBoundedBody(responseFor(t, http.StatusOK, "ok", "https://evil.example/asset"), raw, 16, reject); err == nil { //nolint:bodyclose // ReadBoundedBody closes the body + t.Fatal("redirect to a foreign host was accepted") + } else { + if !strings.Contains(err.Error(), "redirect from") { + t.Errorf("error = %q, want a redirect error", err) + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token=abc") { + t.Errorf("error leaked credentials: %q", err) + } + } + + got, err := ReadBoundedBody(responseFor(t, http.StatusOK, "ok", "https://github.com/asset?sig=abc"), raw, 16, reject) //nolint:bodyclose // ReadBoundedBody closes the body + if err != nil || string(got) != "ok" { + t.Fatalf("allowed redirect: body = %q, err = %v", got, err) + } +} + +func TestReadBoundedBodyRejectsNonOKStatus(t *testing.T) { + raw := "https://user:secret@github.com/dc?token=abc" + _, err := ReadBoundedBody(responseFor(t, http.StatusForbidden, "", raw), raw, 16, nil) //nolint:bodyclose // ReadBoundedBody closes the body + if err == nil || !strings.Contains(err.Error(), "http 403 for https://github.com") { + t.Fatalf("err = %v, want a redacted status error", err) + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token=abc") { + t.Errorf("error leaked credentials: %q", err) + } +} + +type contextTransport struct { + seen context.Context +} + +func (tr *contextTransport) RoundTrip(req *http.Request) (*http.Response, error) { + tr.seen = req.Context() + return nil, errors.New("transport stopped") +} + +func TestBoundedGetUsesContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + tr := &contextTransport{} + client := &http.Client{Transport: tr} + + _, err := BoundedGet(ctx, client, "https://github.com/dc", 16, nil) + if err == nil { + t.Fatal("expected an error for a cancelled context") + } + if tr.seen == nil || !errors.Is(tr.seen.Err(), context.Canceled) { + t.Errorf("request context = %v, want context.Canceled", tr.seen) + } +} + +func TestBoundedGetRedactsTransportErrors(t *testing.T) { + client := &http.Client{Transport: &contextTransport{}} + _, err := BoundedGet(context.Background(), client, "https://user:secret@github.com/dc?token=abc", 16, nil) + if err == nil { + t.Fatal("expected a transport error") + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token=abc") { + t.Errorf("error leaked credentials: %q", err) + } +} + +func TestBoundedGetEnforcesCapAndStatus(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/big": + _, _ = w.Write([]byte("123456789")) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + + raw := strings.Replace(server.URL, "http://", "http://user:secret@", 1) + if _, err := BoundedGet(context.Background(), server.Client(), raw+"/big?token=abc", 4, nil); err == nil || !strings.Contains(err.Error(), "exceeds") { + t.Fatalf("oversized body: err = %v, want an oversize error", err) + } else if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token=abc") { + t.Errorf("error leaked credentials: %q", err) + } + if _, err := BoundedGet(context.Background(), server.Client(), raw+"/missing?token=abc", 4, nil); err == nil || !strings.Contains(err.Error(), "http 404 for http://") { + t.Fatalf("404 response: err = %v, want a redacted status error", err) + } +} diff --git a/internal/packages/cache.go b/internal/packages/cache.go index 09923db..cb63cb5 100644 --- a/internal/packages/cache.go +++ b/internal/packages/cache.go @@ -1,8 +1,12 @@ package packages import ( + "encoding/json" + "errors" + "fmt" "os" "path/filepath" + "sync" "time" "github.com/DomainCraft/DomainCraft/internal/appdir" @@ -24,35 +28,41 @@ type versionEntry struct { StoredAt time.Time `json:"stored_at"` } -// cacheKey derives a stable key for a (registry, package) pair. -func cacheKey(registryURL, packageID string) string { - return registryURL + "\x00" + packageID -} - -// resolveVersionFn is the actual registry lookup performed on a cache miss. It -// is a variable so tests can substitute a fake (avoiding a real network call). -var resolveVersionFn = ResolveVersion - // resolveVersionForFrameworkFn is the TFM-aware lookup used by renderers. It is -// a separate seam so the version-filtering logic can be tested offline. +// a seam so the version-filtering logic can be tested offline. var resolveVersionForFrameworkFn = ResolveVersionForFramework +// persistVersionCacheFn is the cache write used by both resolve paths. It is a +// seam for testing write failures without manipulating filesystem permissions. +var persistVersionCacheFn = persistVersionCache + +// cacheMu serializes the read-modify-write cycle on a cache file. Two bridge +// layers resolving packages concurrently must not overwrite each other's +// entries or lose a freshly resolved version. It is a single global mutex, so +// resolution across all bridges is serialized; correctness does not depend on +// that serialization, and per-bridge locks are a possible future optimization. +var cacheMu sync.Mutex + // versionStore loads (or initializes) the package-version cache file for a // single bridge. Every bridge keeps its own file // (~/.domaincraft/cache//packages.json), so with many bridges the // caches never mix and a corrupt one only affects its own bridge. func versionStore(bridgeID string) (map[string]versionEntry, error) { - dir, err := appdir.CacheDir(bridgeID) - if err != nil { - return nil, err - } + dir := appdir.CacheDir(bridgeID) var data struct { Entries map[string]versionEntry `json:"entries"` } // A missing or corrupt cache file yields an empty cache rather than an - // error, so a broken cache never breaks the caller. - if err := fsutil.ReadJSON(filepath.Join(dir, CacheFileName), &data); err != nil && !os.IsNotExist(err) { - return nil, err + // error; the normal resolve -> persist path then overwrites the unusable + // bytes. Genuine storage failures (permissions, I/O) must not be masked as + // a cache miss — that would overwrite the file and hide the real fault. + if err := fsutil.ReadJSON(filepath.Join(dir, CacheFileName), &data); err != nil { + var syntaxErr *json.SyntaxError + var typeErr *json.UnmarshalTypeError + if !errors.Is(err, os.ErrNotExist) && !errors.As(err, &syntaxErr) && !errors.As(err, &typeErr) { + return nil, fmt.Errorf("read package version cache for %q: %w", bridgeID, err) + } + data.Entries = make(map[string]versionEntry) } if data.Entries == nil { data.Entries = make(map[string]versionEntry) @@ -60,34 +70,48 @@ func versionStore(bridgeID string) (map[string]versionEntry, error) { return data.Entries, nil } -// persistVersionCache writes the cache file atomically. Best-effort: a failed -// write must not fail generation (only cache warmth is lost). -func persistVersionCache(bridgeID string, entries map[string]versionEntry) { - if dir, err := appdir.CacheDir(bridgeID); err == nil { - _ = fsutil.WriteJSON(filepath.Join(dir, CacheFileName), struct { - Entries map[string]versionEntry `json:"entries"` - }{Entries: entries}) +// persistVersionCache writes the cache file atomically and reports failures. +// A failed write is surfaced to the caller (the renderer logs it as a warning); +// silently discarding it made a broken cache path indistinguishable from a +// successful resolution. +func persistVersionCache(bridgeID string, entries map[string]versionEntry) error { + dir := appdir.CacheDir(bridgeID) + if err := fsutil.WriteJSON(filepath.Join(dir, CacheFileName), struct { + Entries map[string]versionEntry `json:"entries"` + }{Entries: entries}); err != nil { + return fmt.Errorf("write package version cache for %q: %w", bridgeID, err) } + return nil } -// ResolveVersionCached resolves the latest stable version of a package from its -// registry, caching the result per bridge for DefaultCacheTTL. A fresh cached -// value avoids a network round-trip on every generation; a stale one triggers a -// refresh. A corrupt or missing cache is ignored and simply re-resolved. -func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, error) { - key := cacheKey(registryURL, packageID) - +// resolveVersionCached is the single cache pipeline shared by both exported +// resolvers. key identifies the (registry, package[, framework]) entry; resolve +// performs the registry lookup on a miss. Both callers keep their own resolver +// seam, but the lock/store/TTL/resolve/persist sequence lives here once. +func resolveVersionCached(bridgeID, key string, resolve func() (string, error)) (string, error) { + cacheMu.Lock() entries, err := versionStore(bridgeID) if err != nil { - // Cache directory unusable — resolve uncached rather than fail. - return resolveVersionFn(registryURL, packageID) + cacheMu.Unlock() + // Cache directory unusable — resolve uncached rather than fail, but + // report the cause so the caller can warn instead of silently using a + // cacheless result. Renderer treats a non-fatal error exactly like a + // cache write failure: warn once and keep the resolved version. + version, resolveErr := resolve() + if resolveErr != nil { + return "", resolveErr + } + return version, fmt.Errorf("read package version cache for %q: %w", bridgeID, err) } - if e, ok := entries[key]; ok && e.Value != "" && time.Since(e.StoredAt) <= DefaultCacheTTL { + cacheMu.Unlock() return e.Value, nil } + cacheMu.Unlock() - version, err := resolveVersionFn(registryURL, packageID) + // A registry lookup can take seconds. Do not hold the cache lock across it: + // other layers must keep resolving while one upstream is slow. + version, err := resolve() if err != nil { return "", err } @@ -95,33 +119,41 @@ func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, erro return "", nil } - entries[key] = versionEntry{Value: version, StoredAt: time.Now()} - persistVersionCache(bridgeID, entries) - return version, nil -} - -// ResolveVersionCachedForFramework is the TFM-aware counterpart of -// ResolveVersionCached. The framework is part of the cache key: the same bridge -// regenerated for net10.0 and net11.0 must not reuse an incompatible version. -func ResolveVersionCachedForFramework(bridgeID, registryURL, packageID, targetFramework string) (string, error) { - key := cacheKey(registryURL, packageID) + "\x00" + targetFramework - - entries, err := versionStore(bridgeID) + cacheMu.Lock() + defer cacheMu.Unlock() + // Another goroutine may have resolved and stored this key meanwhile. + entries, err = versionStore(bridgeID) if err != nil { - return resolveVersionForFrameworkFn(registryURL, packageID, targetFramework) + return version, fmt.Errorf("reread package version cache for %q: %w", bridgeID, err) } if e, ok := entries[key]; ok && e.Value != "" && time.Since(e.StoredAt) <= DefaultCacheTTL { return e.Value, nil } - - version, err := resolveVersionForFrameworkFn(registryURL, packageID, targetFramework) - if err != nil { - return "", err - } - if version == "" { - return "", nil - } entries[key] = versionEntry{Value: version, StoredAt: time.Now()} - persistVersionCache(bridgeID, entries) + if err := persistVersionCacheFn(bridgeID, entries); err != nil { + // The version is real: a broken cache must not turn a successful + // registry lookup into a package-less generated project. Report the + // write failure non-fatally and let the caller warn once. + return version, fmt.Errorf("persist package version cache for %q: %w", bridgeID, err) + } return version, nil } + +// frameworkCacheKey derives the cache key for a TFM-aware resolution. The +// framework is part of the key: the same bridge regenerated for net10.0 and +// net11.0 must never reuse an incompatible version. +func frameworkCacheKey(registryURL, packageID, targetFramework string) string { + return registryURL + "\x00" + packageID + "\x00" + targetFramework +} + +// ResolveVersionCachedForFramework resolves the latest stable version of a +// package compatible with targetFramework, caching the result per bridge for +// DefaultCacheTTL. A fresh cached value avoids a network round-trip on every +// generation; a stale one triggers a refresh. A corrupt or missing cache is +// ignored and simply re-resolved. +func ResolveVersionCachedForFramework(bridgeID, registryURL, packageID, targetFramework string) (string, error) { + key := frameworkCacheKey(registryURL, packageID, targetFramework) + return resolveVersionCached(bridgeID, key, func() (string, error) { + return resolveVersionForFrameworkFn(registryURL, packageID, targetFramework) + }) +} diff --git a/internal/packages/cache_test.go b/internal/packages/cache_test.go index 3b7defb..d89df54 100644 --- a/internal/packages/cache_test.go +++ b/internal/packages/cache_test.go @@ -1,8 +1,11 @@ package packages import ( + "encoding/json" + "errors" "os" "path/filepath" + "strings" "testing" "time" @@ -10,6 +13,12 @@ import ( "github.com/DomainCraft/DomainCraft/internal/fsutil" ) +const ( + testRegistryURL = "https://reg.example/{id}" + testPackageID = "demo.pkg" + testFramework = "net10.0" +) + // resetCacheRoot points the app base dir at a fresh temp dir for a test. func resetCacheRoot(t *testing.T) { t.Helper() @@ -19,23 +28,17 @@ func resetCacheRoot(t *testing.T) { // seedVersion writes an entry directly into a bridge's cache file with the // given stored-at time, bypassing the normal time.Now() used on resolution. -func seedVersion(t *testing.T, bridgeID, key, version string, storedAt time.Time) { +// The key matches the live ResolveVersionCachedForFramework path, so a seeded +// entry is visible to the resolver under test. +func seedVersion(t *testing.T, bridgeID, registryURL, packageID, framework, version string, storedAt time.Time) { t.Helper() - dir, err := appdir.CacheDir(bridgeID) - if err != nil { - t.Fatal(err) - } + key := frameworkCacheKey(registryURL, packageID, framework) + dir := appdir.CacheDir(bridgeID) path := filepath.Join(dir, CacheFileName) if err := fsutil.WriteJSON(path, struct { - Entries map[string]struct { - Value string `json:"value"` - StoredAt time.Time `json:"stored_at"` - } `json:"entries"` + Entries map[string]versionEntry `json:"entries"` }{ - Entries: map[string]struct { - Value string `json:"value"` - StoredAt time.Time `json:"stored_at"` - }{ + Entries: map[string]versionEntry{ key: {Value: version, StoredAt: storedAt}, }, }); err != nil { @@ -59,7 +62,7 @@ func TestCachedVersionIsPerFramework(t *testing.T) { } for _, framework := range []string{"net10.0", "net11.0", "net10.0"} { - if _, err := ResolveVersionCachedForFramework("csharp-rest", "https://reg.example/{id}", "ef", framework); err != nil { + if _, err := ResolveVersionCachedForFramework("csharp-rest", testRegistryURL, "ef", framework); err != nil { t.Fatal(err) } } @@ -71,43 +74,40 @@ func TestCachedVersionIsPerFramework(t *testing.T) { func TestVersionStoreIsPerBridge(t *testing.T) { resetCacheRoot(t) - dir, err := appdir.CacheDir("csharp-restful") - if err != nil { - t.Fatalf("CacheDir: %v", err) - } + dir := appdir.CacheDir("csharp-restful") want := filepath.Join(dir, CacheFileName) - old := resolveVersionFn - resolveVersionFn = func(_, _ string) (string, error) { return "1.0.0", nil } - defer func() { resolveVersionFn = old }() + old := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "1.0.0", nil } + defer func() { resolveVersionForFrameworkFn = old }() - if _, err := ResolveVersionCached("csharp-restful", "https://reg.example/{id}", "demo.pkg"); err != nil { - t.Fatalf("ResolveVersionCached: %v", err) + if _, err := ResolveVersionCachedForFramework("csharp-restful", testRegistryURL, testPackageID, testFramework); err != nil { + t.Fatalf("ResolveVersionCachedForFramework: %v", err) } if _, err := os.Stat(want); err != nil { t.Fatalf("expected per-bridge cache file at %s: %v", want, err) } } -// TestResolveVersionCachedFreshHit verifies that a fresh cache entry short- -// circuits the registry lookup (no network, no resolveFn call). -func TestResolveVersionCachedFreshHit(t *testing.T) { +// TestResolveVersionCachedForFrameworkFreshHit verifies that a fresh cache +// entry short-circuits the registry lookup (no network, no resolver call). +func TestResolveVersionCachedForFrameworkFreshHit(t *testing.T) { resetCacheRoot(t) - seedVersion(t, "demo", cacheKey("https://reg.example/{id}", "demo.pkg"), "1.0.0", time.Now()) + seedVersion(t, "demo", testRegistryURL, testPackageID, testFramework, "1.0.0", time.Now()) // Guard: if the cache path is not taken, the fake below would be called. called := false - old := resolveVersionFn - resolveVersionFn = func(_, _ string) (string, error) { + old := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { called = true return "9.9.9", nil } - defer func() { resolveVersionFn = old }() + defer func() { resolveVersionForFrameworkFn = old }() - got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) if err != nil { - t.Fatalf("ResolveVersionCached: %v", err) + t.Fatalf("ResolveVersionCachedForFramework: %v", err) } if got != "1.0.0" { t.Fatalf("expected cached version 1.0.0, got %q", got) @@ -117,71 +117,171 @@ func TestResolveVersionCachedFreshHit(t *testing.T) { } } -// TestResolveVersionCachedStaleRefreshes verifies that an expired entry is -// re-resolved and the new version replaces it in the cache. -func TestResolveVersionCachedStaleRefreshes(t *testing.T) { +// TestResolveVersionCachedForFrameworkStaleRefreshes verifies that an expired +// entry is re-resolved and the new version replaces it in the cache. +func TestResolveVersionCachedForFrameworkStaleRefreshes(t *testing.T) { resetCacheRoot(t) - key := cacheKey("https://reg.example/{id}", "demo.pkg") - seedVersion(t, "demo", key, "1.0.0", time.Now().Add(-48*time.Hour)) + seedVersion(t, "demo", testRegistryURL, testPackageID, testFramework, "1.0.0", time.Now().Add(-48*time.Hour)) - oldFn := resolveVersionFn - resolveVersionFn = func(_, _ string) (string, error) { + oldFn := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "2.0.0", nil } - defer func() { resolveVersionFn = oldFn }() + defer func() { resolveVersionForFrameworkFn = oldFn }() - got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) if err != nil { - t.Fatalf("ResolveVersionCached: %v", err) + t.Fatalf("ResolveVersionCachedForFramework: %v", err) } if got != "2.0.0" { t.Fatalf("expected refreshed version 2.0.0, got %q", got) } // The refreshed value must be persisted and now serve as a fresh hit. - resolveVersionFn = func(_, _ string) (string, error) { + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { t.Fatal("must not contact registry after refresh") return "", nil } - got2, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + got2, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) if err != nil || got2 != "2.0.0" { t.Fatalf("expected persisted refresh to serve 2.0.0, got %q (err %v)", got2, err) } } -// TestResolveVersionCachedIsolation verifies caches are per bridge: a version -// cached for one bridge is not served to another. -func TestResolveVersionCachedIsolation(t *testing.T) { +// TestResolveVersionCachedForFrameworkTTLBoundary pins the 24h cutoff: just +// inside the TTL is a hit, just outside is a miss. +func TestResolveVersionCachedForFrameworkTTLBoundary(t *testing.T) { + tests := []struct { + name string + storedAt time.Time + wantHit bool + }{ + {name: "just inside TTL", storedAt: time.Now().Add(-DefaultCacheTTL + time.Second), wantHit: true}, + {name: "just outside TTL", storedAt: time.Now().Add(-DefaultCacheTTL - time.Second)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetCacheRoot(t) + seedVersion(t, "demo", testRegistryURL, testPackageID, testFramework, "1.0.0", tt.storedAt) + + called := false + old := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { + called = true + return "2.0.0", nil + } + defer func() { resolveVersionForFrameworkFn = old }() + + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) + if err != nil { + t.Fatal(err) + } + if called == tt.wantHit { + t.Fatalf("registry called = %v, wantHit %v", called, tt.wantHit) + } + want := "2.0.0" + if tt.wantHit { + want = "1.0.0" + } + if got != want { + t.Fatalf("version = %q, want %q", got, want) + } + }) + } +} + +// TestResolveVersionCachedForFrameworkRegistryFailures covers the two paths +// where no version may be cached: a registry error and an empty result. +func TestResolveVersionCachedForFrameworkRegistryFailures(t *testing.T) { + tests := []struct { + name string + version string + err error + }{ + {name: "registry error", err: os.ErrNotExist}, + {name: "empty version", version: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetCacheRoot(t) + old := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return tt.version, tt.err } + defer func() { resolveVersionForFrameworkFn = old }() + + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) + if (err != nil) != (tt.err != nil) || got != tt.version { + t.Fatalf("got %q, %v; want %q, %v", got, err, tt.version, tt.err) + } + + // No entry may be cached from a failed or empty resolution. + called := false + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { + called = true + return "3.0.0", nil + } + got, err = ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) + if err != nil || !called || got != "3.0.0" { + t.Fatalf("second call = %q, %v, called=%v; want 3.0.0 without error", got, err, called) + } + }) + } +} + +// TestResolveVersionCachedForFrameworkIsolation verifies caches are per bridge: +// a version cached for one bridge is not served to another. +func TestResolveVersionCachedForFrameworkIsolation(t *testing.T) { resetCacheRoot(t) - seedVersion(t, "bridge-a", cacheKey("https://reg.example/{id}", "demo.pkg"), "1.0.0", time.Now()) + seedVersion(t, "bridge-a", testRegistryURL, testPackageID, testFramework, "1.0.0", time.Now()) - oldFn := resolveVersionFn - resolveVersionFn = func(_, _ string) (string, error) { + oldFn := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "9.9.9", nil } - defer func() { resolveVersionFn = oldFn }() + defer func() { resolveVersionForFrameworkFn = oldFn }() // bridge-b has no cache -> must resolve (fresh) via the registry fake. - got, err := ResolveVersionCached("bridge-b", "https://reg.example/{id}", "demo.pkg") + got, err := ResolveVersionCachedForFramework("bridge-b", testRegistryURL, testPackageID, testFramework) if err != nil { - t.Fatalf("ResolveVersionCached(bridge-b): %v", err) + t.Fatalf("ResolveVersionCachedForFramework(bridge-b): %v", err) } if got != "9.9.9" { t.Fatalf("bridge-b must not read bridge-a's cache, got %q", got) } } +// A failed cache write must not discard a version that was successfully +// resolved from the registry. +func TestPersistFailureKeepsResolvedVersion(t *testing.T) { + resetCacheRoot(t) + + persistErr := errors.New("disk full") + oldPersist := persistVersionCacheFn + persistVersionCacheFn = func(_ string, _ map[string]versionEntry) error { return persistErr } + defer func() { persistVersionCacheFn = oldPersist }() + + oldResolve := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "10.0.0", nil } + defer func() { resolveVersionForFrameworkFn = oldResolve }() + + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) + if got != "10.0.0" { + t.Fatalf("version = %q, want 10.0.0 (persist failure must not drop it)", got) + } + if !errors.Is(err, persistErr) || !strings.Contains(err.Error(), "persist package version cache") { + t.Fatalf("err = %v, want a non-fatal persist failure", err) + } +} + // TestLoadCacheIgnoresCorruptFile ensures a corrupt cache file degrades // gracefully (fresh empty cache) instead of failing generation. func TestLoadCacheIgnoresCorruptFile(t *testing.T) { resetCacheRoot(t) - dir, err := appdir.CacheDir("demo") - if err != nil { - t.Fatal(err) - } + dir := appdir.CacheDir("demo") path := filepath.Join(dir, CacheFileName) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) @@ -192,15 +292,98 @@ func TestLoadCacheIgnoresCorruptFile(t *testing.T) { // A corrupt file must not fail resolution; it should fall through to a // fresh registry lookup. - oldFn := resolveVersionFn - resolveVersionFn = func(_, _ string) (string, error) { return "1.0.0", nil } - defer func() { resolveVersionFn = oldFn }() + oldFn := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "1.0.0", nil } + defer func() { resolveVersionForFrameworkFn = oldFn }() - got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + got, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework) if err != nil { - t.Fatalf("ResolveVersionCached: %v", err) + t.Fatalf("ResolveVersionCachedForFramework: %v", err) } if got != "1.0.0" { t.Fatalf("expected fresh resolve for corrupt cache, got %q", got) } } + +// TestResolveVersionCachedForFrameworkRepairsCorruptCache pins the recovery +// path: after a corrupt packages.json is discarded, the fresh value must be +// persisted so the next run resolves from cache instead of contacting the +// registry again. +func TestResolveVersionCachedForFrameworkRepairsCorruptCache(t *testing.T) { + resetCacheRoot(t) + + dir := appdir.CacheDir("demo") + path := filepath.Join(dir, CacheFileName) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{ not json"), 0o644); err != nil { + t.Fatal(err) + } + + calls := 0 + oldFn := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { + calls++ + return "1.0.0", nil + } + defer func() { resolveVersionForFrameworkFn = oldFn }() + + if _, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework); err != nil { + t.Fatalf("first ResolveVersionCachedForFramework: %v", err) + } + if _, err := ResolveVersionCachedForFramework("demo", testRegistryURL, testPackageID, testFramework); err != nil { + t.Fatalf("second ResolveVersionCachedForFramework: %v", err) + } + if calls != 1 { + t.Fatalf("registry consulted %d times, want 1: corrupt cache was not rewritten", calls) + } + + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var stored struct { + Entries map[string]versionEntry `json:"entries"` + } + if err := json.Unmarshal(body, &stored); err != nil { + t.Fatalf("cache file is still corrupt: %v", err) + } + key := frameworkCacheKey(testRegistryURL, testPackageID, testFramework) + if got := stored.Entries[key].Value; got != "1.0.0" { + t.Fatalf("cached version = %q, want 1.0.0", got) + } +} + +func TestResolveVersionCachedDoesNotHoldLockDuringResolve(t *testing.T) { + resetCacheRoot(t) + started := make(chan struct{}) + release := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = resolveVersionCached("slow", "key-a", func() (string, error) { + close(started) + <-release + return "1.0.0", nil + }) + }() + select { + case <-started: + case <-time.After(10 * time.Second): + t.Fatal("first resolver did not start") + } + + fastDone := make(chan struct{}) + go func() { + defer close(fastDone) + _, _ = resolveVersionCached("slow", "key-b", func() (string, error) { return "2.0.0", nil }) + }() + select { + case <-fastDone: + case <-time.After(10 * time.Second): + t.Error("second resolution was blocked by the first registry lookup") + } + close(release) + <-done +} diff --git a/internal/packages/packages_hardening_test.go b/internal/packages/packages_hardening_test.go new file mode 100644 index 0000000..04ba66c --- /dev/null +++ b/internal/packages/packages_hardening_test.go @@ -0,0 +1,74 @@ +package packages + +import ( + "math" + "os" + "path/filepath" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +func TestVersionStoreReportsStorageErrors(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + dir := appdir.CacheDir("broken-cache") + if err := os.MkdirAll(filepath.Join(dir, CacheFileName), 0o755); err != nil { + t.Fatal(err) + } + if _, err := versionStore("broken-cache"); err == nil { + t.Fatal("versionStore masked a directory ReadJSON error as an empty cache") + } +} + +// An unreadable cache must not silently degrade to a cacheless resolve: the +// resolved version is still usable, but the caller gets the cause to warn on. +func TestCachedResolveReportsUnreadableCache(t *testing.T) { + root := t.TempDir() + appdir.SetBaseForTesting(root) + defer appdir.SetBaseForTesting("") + dir := appdir.CacheDir("broken-cache-resolve") + if err := os.MkdirAll(filepath.Join(dir, CacheFileName), 0o755); err != nil { + t.Fatal(err) + } + + oldResolve := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "9.9.9", nil } + defer func() { resolveVersionForFrameworkFn = oldResolve }() + + version, err := ResolveVersionCachedForFramework("broken-cache-resolve", "https://reg.example/{id}", "demo.pkg", "net10.0") + if version != "9.9.9" { + t.Errorf("version = %q, want 9.9.9", version) + } + if err == nil { + t.Fatal("unreadable cache produced no diagnostic") + } +} + +func TestNumericPrefixHandlesBuildMetadataAndOverflow(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + component string + want int + }{ + {name: "build metadata", component: "3+build", want: 3}, + {name: "plain number", component: "12", want: 12}, + {name: "non-numeric", component: "abc", want: 0}, + {name: "overflow", component: "999999999999999999999999", want: math.MaxInt}, + } { + t.Run(c.name, func(t *testing.T) { + if got := numericPrefix(c.component); got != c.want { + t.Errorf("numericPrefix(%q) = %d, want %d", c.component, got, c.want) + } + }) + } +} + +func TestVersionGreaterWithBuildMetadata(t *testing.T) { + t.Parallel() + if !VersionGreater("1.2.4", "1.2.3+build") { + t.Fatal("VersionGreater ignored the numeric part of a build-metadata component") + } +} diff --git a/internal/packages/registry.go b/internal/packages/registry.go index 23c7e56..56cef86 100644 --- a/internal/packages/registry.go +++ b/internal/packages/registry.go @@ -2,24 +2,155 @@ package packages import ( + "context" "encoding/json" "fmt" - "io" + "math" + "net" "net/http" + "net/url" + "strconv" "strings" "time" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/netutil" ) -var registryClient = &http.Client{Timeout: 5 * time.Second} +// maxRegistryResponseBytes caps a version index read from a registry. +const maxRegistryResponseBytes = netutil.DefaultMaxBodyBytes + +var registryClient = newRegistryClient() + +// newRegistryClient installs a dialer that resolves and checks every address at +// connect time, including addresses reached through a redirect. Checking only +// the literal host in bridge.yaml is not enough: a hostname can resolve to +// loopback, a private network or the cloud metadata address. +func newRegistryClient() *http.Client { + tr := http.DefaultTransport.(*http.Transport).Clone() + // The dialer checks the resolved address. An environment proxy would make + // it check the proxy instead of the host behind CONNECT, so never use one + // for registry lookups. + tr.Proxy = nil + tr.DialContext = restrictedRegistryDialer + client := netutil.NewBoundedClient(5*time.Second, tr) + client.CheckRedirect = func(req *http.Request, _ []*http.Request) error { + if err := validateRegistryURL(req.URL.String()); err != nil { + return err + } + return validateRegistryTarget(req.Context(), req.URL) + } + return client +} + +// allowLocalRegistryForTests is set only by tests using httptest TLS servers. +var allowLocalRegistryForTests bool + +// lookupRegistryIPs is a seam so the SSRF guards can be tested without DNS. +var lookupRegistryIPs = func(ctx context.Context, host string) ([]net.IPAddr, error) { + return net.DefaultResolver.LookupIPAddr(ctx, host) +} + +// allowedRegistryIP rejects addresses that could reach a local service or the +// cloud metadata endpoint (loopback, private, link-local and unspecified). +func allowedRegistryIP(ip net.IP) bool { + if ip == nil { + return false + } + return !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() && + !ip.IsLinkLocalMulticast() && !ip.IsUnspecified() +} + +// validateRegistryURL performs the syntactic checks on a registry URL. The +// address checks happen at dial time so DNS rebinding cannot bypass them. +func validateRegistryURL(raw string) error { + u, err := url.Parse(raw) + if err != nil { + // url.Error repeats the raw URL (including userinfo/query); keep only + // its reason and wrap that instead. + return fmt.Errorf("invalid registry URL %q: %w", netutil.RedactedURL(raw), netutil.RedactURLError(err)) + } + if u.Scheme != "https" || u.Host == "" { + return fmt.Errorf("registry URL must be an absolute https URL: %q", netutil.RedactedURL(raw)) + } + host := strings.ToLower(u.Hostname()) + if allowLocalRegistryForTests { + return nil + } + if host == "localhost" || strings.HasSuffix(host, ".localhost") { + return fmt.Errorf("registry host %q is not allowed", host) + } + if ip := net.ParseIP(host); ip != nil && !allowedRegistryIP(ip) { + return fmt.Errorf("registry host %q is not allowed", host) + } + return nil +} + +// resolveAllowedIPs resolves host and applies the single address policy shared +// by the redirect check and the dial hook. The test bypass lives here so both +// callers cannot drift apart on SSRF rules. +func resolveAllowedIPs(ctx context.Context, host string) ([]net.IPAddr, error) { + if allowLocalRegistryForTests { + return nil, nil + } + ips, err := lookupRegistryIPs(ctx, host) + if err != nil { + return nil, fmt.Errorf("resolve registry host %q: %w", host, err) + } + if len(ips) == 0 { + return nil, fmt.Errorf("registry host %q has no addresses", host) + } + for _, addr := range ips { + if !allowedRegistryIP(addr.IP) { + return nil, fmt.Errorf("registry host %q resolves to disallowed address %s", host, addr.IP) + } + } + return ips, nil +} + +// validateRegistryTarget resolves the host and rejects a disallowed address. +func validateRegistryTarget(ctx context.Context, u *url.URL) error { + _, err := resolveAllowedIPs(ctx, strings.ToLower(u.Hostname())) + return err +} -// ResolveVersion queries a package registry (e.g. NuGet) for the latest stable version -// of a package. The registryURL template must contain {id} which is replaced with the package ID. -func ResolveVersion(registryURL string, packageID string) (string, error) { +// restrictedRegistryDialer is the http.Transport dial hook. It uses the same +// address rule as validateRegistryTarget and connects to the checked IP, so a +// second DNS answer cannot rebind the connection to a private address. +func restrictedRegistryDialer(ctx context.Context, network, addr string) (net.Conn, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, fmt.Errorf("invalid registry address: %w", err) + } + dialer := &net.Dialer{} + if allowLocalRegistryForTests { + return dialer.DialContext(ctx, network, addr) + } + if ip := net.ParseIP(host); ip != nil { + if !allowedRegistryIP(ip) { + return nil, fmt.Errorf("registry address %s is not allowed", netutil.RedactedURL("https://"+addr)) + } + return dialer.DialContext(ctx, network, addr) + } + ips, err := resolveAllowedIPs(ctx, host) + if err != nil { + return nil, err + } + return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].IP.String(), port)) +} + +// resolveLatest is the single fetch + select pipeline. maxMajor caps the major +// version; fallbackUncapped retries without the cap so an over-constrained TFM +// still produces a usable version (the renderer warns about the fallback). +func resolveLatest(registryURL, packageID string, maxMajor int, fallbackUncapped bool) (string, error) { versions, err := fetchVersions(registryURL, packageID) if err != nil { return "", err } - best := latestStable(versions, 0) + best := latestStable(versions, maxMajor) + if best == "" && fallbackUncapped { + best = latestStable(versions, 0) + } if best == "" { return "", fmt.Errorf("no stable versions found for %s", packageID) } @@ -33,19 +164,7 @@ func ResolveVersion(registryURL string, packageID string) (string, error) { // selection unconstrained. If no compatible version exists, the latest stable // one is returned so generation can still complete; the renderer warns about it. func ResolveVersionForFramework(registryURL, packageID, targetFramework string) (string, error) { - versions, err := fetchVersions(registryURL, packageID) - if err != nil { - return "", err - } - maxMajor := MaxMajorForFramework(targetFramework) - best := latestStable(versions, maxMajor) - if best == "" { - best = latestStable(versions, 0) - } - if best == "" { - return "", fmt.Errorf("no stable versions found for %s", packageID) - } - return best, nil + return resolveLatest(registryURL, packageID, MaxMajorForFramework(targetFramework), true) } // MaxMajorForFramework extracts the runtime major from "net10.0" → 10. @@ -58,19 +177,35 @@ func MaxMajorForFramework(framework string) int { if i := strings.IndexAny(major, ".-+ "); i >= 0 { major = major[:i] } - var n int - if _, err := fmt.Sscanf(major, "%d", &n); err != nil || n <= 0 { + return numericPrefix(major) +} + +// numericPrefix parses the leading digits of a version component. Overflow +// clamps to MaxInt instead of silently becoming zero, which would drop a +// framework's major-version cap or misorder two versions. +func numericPrefix(component string) int { + i := 0 + for i < len(component) && component[i] >= '0' && component[i] <= '9' { + i++ + } + if i == 0 { return 0 } - return n + n, err := strconv.ParseInt(component[:i], 10, 64) + if err != nil { + return math.MaxInt + } + if n <= 0 { + return 0 + } + if n > math.MaxInt { + return math.MaxInt + } + return int(n) } func versionMajor(version string) int { - var n int - if _, err := fmt.Sscanf(version, "%d", &n); err != nil { - return 0 - } - return n + return numericPrefix(version) } // latestStable returns the highest stable version whose major is <= maxMajor. @@ -93,9 +228,12 @@ func latestStable(versions []string, maxMajor int) string { // fetchVersions reads the flat-container version index from the registry. func fetchVersions(registryURL string, packageID string) ([]string, error) { - url := strings.ReplaceAll(registryURL, "{id}", strings.ToLower(packageID)) + registryEndpoint := strings.ReplaceAll(registryURL, "{id}", strings.ToLower(packageID)) + if err := validateRegistryURL(registryEndpoint); err != nil { + return nil, err + } - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequestWithContext(bridge.CommandContext(), http.MethodGet, registryEndpoint, nil) if err != nil { return nil, err } @@ -104,17 +242,23 @@ func fetchVersions(registryURL string, packageID string) ([]string, error) { if err != nil { return nil, err } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("registry returned %d for %s", resp.StatusCode, packageID) } + // A bounded read rejects an oversized index instead of silently decoding a + // truncated prefix. The shared helper closes the body; the defer above also + // covers the early return for a non-OK status. + body, err := netutil.ReadBoundedBody(resp, registryEndpoint, int64(maxRegistryResponseBytes), nil) + if err != nil { + return nil, err + } var result struct { Versions []string `json:"versions"` } - // Limit response body to 1MB to prevent OOM from malicious/misconfigured registries. - if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil { + if err := json.Unmarshal(body, &result); err != nil { return nil, err } @@ -125,17 +269,14 @@ func fetchVersions(registryURL string, packageID string) ([]string, error) { func VersionGreater(a, b string) bool { aParts := strings.Split(a, ".") bParts := strings.Split(b, ".") - maxLen := len(aParts) - if len(bParts) > maxLen { - maxLen = len(bParts) - } + maxLen := max(len(aParts), len(bParts)) for i := range maxLen { var ai, bi int if i < len(aParts) { - fmt.Sscanf(aParts[i], "%d", &ai) + ai = numericPrefix(aParts[i]) } if i < len(bParts) { - fmt.Sscanf(bParts[i], "%d", &bi) + bi = numericPrefix(bParts[i]) } if ai > bi { return true diff --git a/internal/packages/registry_test.go b/internal/packages/registry_test.go index 320a985..d805b05 100644 --- a/internal/packages/registry_test.go +++ b/internal/packages/registry_test.go @@ -7,6 +7,46 @@ import ( "testing" ) +// newTestRegistryServer switches the registry client to the TLS test server so +// the https-only guard can stay enabled in production. +func newTestRegistryServer(t *testing.T, handler http.Handler) *httptest.Server { + t.Helper() + srv := httptest.NewTLSServer(handler) + previous := registryClient + registryClient = srv.Client() + allowLocalRegistryForTests = true + t.Cleanup(func() { + registryClient = previous + allowLocalRegistryForTests = false + srv.Close() + }) + return srv +} + +func TestValidateRegistryURLRejectsInternalTargets(t *testing.T) { + tests := []struct { + name string + url string + wantErr bool + }{ + {name: "public https", url: "https://api.nuget.org/v3-flatcontainer/{id}/index.json"}, + {name: "plaintext", url: "http://api.nuget.org/v3/{id}", wantErr: true}, + {name: "loopback ip", url: "https://127.0.0.1:8080/admin/{id}", wantErr: true}, + {name: "localhost", url: "https://localhost/{id}", wantErr: true}, + {name: "link local", url: "https://169.254.169.254/latest/{id}", wantErr: true}, + {name: "private ip", url: "https://10.0.0.5/{id}", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateRegistryURL(tt.url) + if (err != nil) != tt.wantErr { + t.Fatalf("validateRegistryURL(%q) error = %v, wantErr %v", tt.url, err, tt.wantErr) + } + }) + } +} + func TestVersionGreater(t *testing.T) { tests := []struct { name string @@ -35,16 +75,15 @@ func TestVersionGreater(t *testing.T) { } func TestResolveVersionPicksHighestStable(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/newtonsoft.json/index.json" { t.Errorf("unexpected path %q", r.URL.Path) } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"versions":["1.0.0","9.0.1","9.0.2-beta1","10.0.0-rc.2","9.0.2","2.0.0"]}`)) })) - defer srv.Close() - got, err := ResolveVersion(srv.URL+"/{id}/index.json", "Newtonsoft.Json") + got, err := ResolveVersionForFramework(srv.URL+"/{id}/index.json", "Newtonsoft.Json", "") if err != nil { t.Fatalf("ResolveVersion: %v", err) } @@ -68,36 +107,37 @@ func TestMaxMajorForFramework(t *testing.T) { // Regression: the NuGet resolver used to return the newest stable version even // when the generated csproj targets an older runtime (efcore 11.x vs net10.0). func TestResolveVersionForFrameworkRespectsTargetFramework(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"versions":["9.0.9","11.0.0","10.0.0","12.0.0-rc1"]}`)) })) - defer srv.Close() for _, tc := range []struct { + name string framework string want string }{ - {"net10.0", "10.0.0"}, - {"net11.0", "11.0.0"}, - {"netstandard2.0", "11.0.0"}, - {"", "11.0.0"}, + {name: "net10 target", framework: "net10.0", want: "10.0.0"}, + {name: "net11 target", framework: "net11.0", want: "11.0.0"}, + {name: "netstandard", framework: "netstandard2.0", want: "11.0.0"}, + {name: "empty framework", framework: "", want: "11.0.0"}, } { - got, err := ResolveVersionForFramework(srv.URL+"/{id}/index.json", "Microsoft.EntityFrameworkCore", tc.framework) - if err != nil { - t.Fatalf("framework %q: %v", tc.framework, err) - } - if got != tc.want { - t.Errorf("framework %q: version = %q, want %q", tc.framework, got, tc.want) - } + t.Run(tc.name, func(t *testing.T) { + got, err := ResolveVersionForFramework(srv.URL+"/{id}/index.json", "Microsoft.EntityFrameworkCore", tc.framework) + if err != nil { + t.Fatalf("framework %q: %v", tc.framework, err) + } + if got != tc.want { + t.Errorf("framework %q: version = %q, want %q", tc.framework, got, tc.want) + } + }) } } func TestResolveVersionForFrameworkFallsBackWhenNoCompatibleVersion(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"versions":["11.0.0"]}`)) })) - defer srv.Close() got, err := ResolveVersionForFramework(srv.URL+"/{id}/index.json", "demo.pkg", "net10.0") if err != nil || got != "11.0.0" { t.Fatalf("version = %q, %v; want 11.0.0, nil", got, err) @@ -117,13 +157,12 @@ func TestResolveVersionErrors(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(c.status) _, _ = w.Write([]byte(c.body)) })) - defer srv.Close() - got, err := ResolveVersion(srv.URL+"/{id}.json", "Some.Package") + got, err := ResolveVersionForFramework(srv.URL+"/{id}.json", "Some.Package", "") if err == nil { t.Fatalf("expected an error, got version %q", got) } @@ -135,11 +174,28 @@ func TestResolveVersionErrors(t *testing.T) { } func TestResolveVersionUnreachableRegistry(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + srv := newTestRegistryServer(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) url := srv.URL srv.Close() // nothing is listening anymore - if _, err := ResolveVersion(url+"/{id}", "Any"); err == nil { + if _, err := ResolveVersionForFramework(url+"/{id}", "Any", ""); err == nil { t.Fatal("expected a connection error for a dead registry") } } + +// A body larger than the cap must be rejected, not decoded as a truncated +// prefix. The old io.LimitReader decoder silently accepted this response. +func TestResolveVersionRejectsOversizedBody(t *testing.T) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"versions":["1.0.0"]}`)) + _, _ = w.Write([]byte(strings.Repeat(" ", maxRegistryResponseBytes))) + })) + + got, err := ResolveVersionForFramework(srv.URL+"/{id}.json", "demo.pkg", "") + if err == nil { + t.Fatalf("oversized response accepted, version = %q", got) + } + if !strings.Contains(err.Error(), "exceeds") { + t.Errorf("err = %q, want a response-size error", err.Error()) + } +} diff --git a/internal/packages/ssrf_test.go b/internal/packages/ssrf_test.go new file mode 100644 index 0000000..0924600 --- /dev/null +++ b/internal/packages/ssrf_test.go @@ -0,0 +1,214 @@ +package packages + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + +// S4: a hostname is not enough — its resolved addresses are checked at connect +// time, including link-local and unspecified addresses. +func TestRestrictedRegistryDialerRejectsInternalDNS(t *testing.T) { + original := lookupRegistryIPs + defer func() { lookupRegistryIPs = original }() + + tests := []struct { + name string + ips []net.IPAddr + wantErr bool + }{ + {name: "ipv4 loopback", ips: []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, wantErr: true}, + {name: "ipv6 loopback", ips: []net.IPAddr{{IP: net.ParseIP("::1")}}, wantErr: true}, + {name: "private", ips: []net.IPAddr{{IP: net.ParseIP("10.0.0.5")}}, wantErr: true}, + {name: "link local metadata", ips: []net.IPAddr{{IP: net.ParseIP("169.254.169.254")}}, wantErr: true}, + {name: "unspecified", ips: []net.IPAddr{{IP: net.ParseIP("0.0.0.0")}}, wantErr: true}, + {name: "one bad address in a mixed answer", ips: []net.IPAddr{{IP: net.ParseIP("1.1.1.1")}, {IP: net.ParseIP("10.0.0.1")}}, wantErr: true}, + {name: "no addresses", wantErr: true}, + {name: "public address", ips: []net.IPAddr{{IP: net.ParseIP("1.1.1.1")}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + lookupRegistryIPs = func(context.Context, string) ([]net.IPAddr, error) { return tt.ips, nil } + u, err := url.Parse("https://registry.example/{id}") + if err != nil { + t.Fatal(err) + } + err = validateRegistryTarget(context.Background(), u) + if (err != nil) != tt.wantErr { + t.Fatalf("validateRegistryTarget error = %v, wantErr %v", err, tt.wantErr) + } + + // The dial hook must enforce the same rule before connecting. A + // short context keeps the allowed case off the real network. + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _, dialErr := restrictedRegistryDialer(ctx, "tcp", "registry.example:443") + switch { + case tt.wantErr && dialErr == nil: + t.Fatal("restrictedRegistryDialer connected to a disallowed address") + case !tt.wantErr && dialErr != nil && + (strings.Contains(dialErr.Error(), "not allowed") || strings.Contains(dialErr.Error(), "disallowed")): + t.Fatalf("restrictedRegistryDialer rejected a public address: %v", dialErr) + } + }) + } +} + +func TestRestrictedRegistryDialerRejectsLiteralAndRedirectTargets(t *testing.T) { + for _, addr := range []string{"127.0.0.1:443", "[::1]:443", "169.254.169.254:80", "0.0.0.0:443"} { + t.Run(addr, func(t *testing.T) { + _, err := restrictedRegistryDialer(context.Background(), "tcp", addr) + if err == nil { + t.Fatalf("restrictedRegistryDialer(%q) connected to a local address", addr) + } + if !strings.Contains(err.Error(), "not allowed") { + t.Errorf("error = %q, want it to name the disallowed address", err) + } + }) + } + + // CheckRedirect validates the redirect target with the same DNS rule. + original := lookupRegistryIPs + defer func() { lookupRegistryIPs = original }() + lookupRegistryIPs = func(context.Context, string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("10.1.2.3")}}, nil + } + req, err := http.NewRequest(http.MethodGet, "https://redirect.example/index.json", nil) + if err != nil { + t.Fatal(err) + } + if err := registryClient.CheckRedirect(req, nil); err == nil { + t.Error("CheckRedirect accepted a hostname resolving to a private address") + } +} + +func TestAllowLocalRegistryForTestsKeepsTLSServersUsable(t *testing.T) { + original := lookupRegistryIPs + defer func() { lookupRegistryIPs = original }() + lookupRegistryIPs = func(context.Context, string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil + } + allowLocalRegistryForTests = true + defer func() { allowLocalRegistryForTests = false }() + + u, err := url.Parse("https://localhost:8443/index.json") + if err != nil { + t.Fatal(err) + } + if err := validateRegistryTarget(context.Background(), u); err != nil { + t.Fatalf("test seam rejected the local TLS server: %v", err) + } +} + +// S14: URL errors expose only scheme and host. +func TestValidateRegistryURLRedactsSecrets(t *testing.T) { + tests := []struct { + name string + raw string + }{ + {name: "plaintext", raw: "http://user:pass@api.example/v1?token=secret"}, + {name: "malformed", raw: "https://user:pass@[::1/v1?token=secret"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateRegistryURL(tt.raw) + if err == nil { + t.Fatalf("validateRegistryURL(%q) succeeded", tt.raw) + } + for _, secret := range []string{"pass", "secret", "user:"} { + if strings.Contains(err.Error(), secret) { + t.Errorf("error = %q, leaked %q", err, secret) + } + } + }) + } +} + +// S13: concurrent resolutions must not lose each other's cache entries, and a +// failed cache write must be reported to the caller. +func TestVersionCacheConcurrentWrites(t *testing.T) { + resetCacheRoot(t) + old := resolveVersionForFrameworkFn + defer func() { resolveVersionForFrameworkFn = old }() + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "1.0.0", nil } + + const count = 8 + var wg sync.WaitGroup + errs := make(chan error, count) + for i := range count { + wg.Add(1) + go func(i int) { + defer wg.Done() + _, err := ResolveVersionCachedForFramework("shared", "https://reg.example/{id}", fmt.Sprintf("pkg%d", i), "net10.0") + errs <- err + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("ResolveVersionCachedForFramework: %v", err) + } + } + entries, err := versionStore("shared") + if err != nil { + t.Fatal(err) + } + if len(entries) != count { + t.Fatalf("cached entries = %d, want %d", len(entries), count) + } +} + +func TestVersionCacheWriteFailureIsSurfaced(t *testing.T) { + resetCacheRoot(t) + oldResolve, oldPersist := resolveVersionForFrameworkFn, persistVersionCacheFn + defer func() { + resolveVersionForFrameworkFn, persistVersionCacheFn = oldResolve, oldPersist + }() + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "2.0.0", nil } + persistVersionCacheFn = func(string, map[string]versionEntry) error { + return errors.New("disk full") + } + + _, err := ResolveVersionCachedForFramework("demo", "https://reg.example/{id}", "demo.pkg", "net10.0") + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("ResolveVersionCachedForFramework error = %v, want the write failure", err) + } +} + +// S9: registry requests are bound to the command context. +func TestFetchVersionsUsesCommandContext(t *testing.T) { + srv := newTestRegistryServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"versions":["1.0.0"]}`)) + })) + defer srv.Close() + + previous := bridge.CommandContext() + defer bridge.SetCommandContext(previous) + ctx, cancel := context.WithCancel(context.Background()) + bridge.SetCommandContext(ctx) + cancel() + + if _, err := ResolveVersionForFramework(srv.URL+"/{id}", "demo.pkg", ""); err == nil { + t.Fatal("ResolveVersion ignored the cancelled command context") + } +} + +func TestRegistryClientIgnoresEnvironmentProxy(t *testing.T) { + tr, ok := registryClient.Transport.(*http.Transport) + if !ok { + t.Fatalf("registry transport = %T, want *http.Transport", registryClient.Transport) + } + if tr.Proxy != nil { + t.Errorf("registry transport has a proxy function; dial-time SSRF checks would see the proxy host") + } +} diff --git a/internal/parser/integration_test.go b/internal/parser/integration_test.go index 3b53d19..ffc4b0c 100644 --- a/internal/parser/integration_test.go +++ b/internal/parser/integration_test.go @@ -6,6 +6,7 @@ import ( // TestFullSchemaWithAllFeatures tests a full schema using all features func TestFullSchemaWithAllFeatures(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: ECommerce Platform @@ -191,9 +192,9 @@ entities: } // Verify Product relations - categoryId := product.Fields["categoryId"] - if !categoryId.IsOptional || categoryId.OnDelete != "set_null" { - t.Errorf("categoryId should be optional with on_delete:set_null") + categoryID := product.Fields["categoryId"] + if !categoryID.IsOptional || categoryID.OnDelete != "set_null" { + t.Errorf("categoryID should be optional with on_delete:set_null") } tagsField := product.Fields["tags"] @@ -210,9 +211,9 @@ entities: // Verify cascade delete orderItem := schema.Entities["OrderItem"] - orderIdField := orderItem.Fields["orderId"] - if orderIdField.OnDelete != "cascade" { - t.Errorf("orderId should have on_delete:cascade") + orderIDField := orderItem.Fields["orderId"] + if orderIDField.OnDelete != "cascade" { + t.Errorf("orderID should have on_delete:cascade") } // Verify indexes @@ -230,14 +231,15 @@ entities: // Verify Review with cascade delete review := schema.Entities["Review"] - productIdField := review.Fields["productId"] - if productIdField.RelationType != "many-to-one" { - t.Errorf("review.productId should be many-to-one relation") + productIDField := review.Fields["productId"] + if productIDField.RelationType != "many-to-one" { + t.Errorf("review.productID should be many-to-one relation") } } // TestCircularRelationships tests self-referential (circular) relationships func TestCircularRelationships(t *testing.T) { + t.Parallel() // A category can have a parent category -- this is a self-referential relationship yamlData := []byte(` project: @@ -256,18 +258,19 @@ entities: } category := schema.Entities["Category"] - parentId := category.Fields["parentId"] + parentID := category.Fields["parentId"] - if parentId.Type != "relation" || parentId.TargetEntity != "Category" { - t.Errorf("parentId should be self-referential relation to Category") + if parentID.Type != "relation" || parentID.TargetEntity != "Category" { + t.Errorf("parentID should be self-referential relation to Category") } - if !parentId.IsOptional { - t.Errorf("parentId should be optional") + if !parentID.IsOptional { + t.Errorf("parentID should be optional") } } // TestDatabaseColumnNameGeneration tests database column name generation func TestDatabaseColumnNameGeneration(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -304,17 +307,21 @@ entities: } for _, tt := range tests { - if field, ok := user.Fields[tt.fieldName]; ok { - if field.DatabaseColumnName != tt.wantDbName { - t.Errorf("field %s: got db name %v, want %v", - tt.fieldName, field.DatabaseColumnName, tt.wantDbName) + t.Run(tt.fieldName, func(t *testing.T) { + t.Parallel() + if field, ok := user.Fields[tt.fieldName]; ok { + if field.DatabaseColumnName != tt.wantDbName { + t.Errorf("field %s: got db name %v, want %v", + tt.fieldName, field.DatabaseColumnName, tt.wantDbName) + } } - } + }) } } // TestSeedData tests seed data parsing func TestSeedData(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -350,6 +357,7 @@ entities: // TestEntityOrdering tests entity ordering func TestEntityOrdering(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -381,6 +389,7 @@ entities: // TestComplexValidations tests complex validation rules func TestComplexValidations(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test diff --git a/internal/parser/models.go b/internal/parser/models.go index a776a90..1fd3cd1 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -84,6 +84,182 @@ func (e AuthEndpoints) HasSetup() bool { return e.Setup == nil || *e.Setup } type DeployConfig struct { Domain string `yaml:"domain" json:"domain,omitempty"` Port int `yaml:"port" json:"port,omitempty"` + // portSet records whether "port" was present in YAML. An explicit 0 is a + // value, not a missing key, so ParseRawSchema must not default it to 8080. + portSet bool +} + +// walkYAMLMerge is the single alias/sequence/mapping traversal for YAML merge +// values ("<<"). Callers supply what to collect and how to report an invalid +// node; dedupe selects YAML's "earlier entries win" rule. +func walkYAMLMerge(value *yaml.Node, dedupe bool, visit func(key, val *yaml.Node), invalid func(*yaml.Node) error) error { + seen := make(map[string]bool) + var collect func(*yaml.Node) error + collect = func(node *yaml.Node) error { + switch node.Kind { + case yaml.AliasNode: + if node.Alias == nil { + if invalid != nil { + return invalid(node) + } + return nil + } + return collect(node.Alias) + case yaml.SequenceNode: + for _, item := range node.Content { + if err := collect(item); err != nil { + return err + } + } + return nil + case yaml.MappingNode: + for i := 0; i < len(node.Content)-1; i += 2 { + key, val := node.Content[i], node.Content[i+1] + if key.Value == "<<" && key.Tag != "!!str" { + if err := collect(val); err != nil { + return err + } + continue + } + if dedupe && seen[key.Value] { + continue + } + seen[key.Value] = true + visit(key, val) + } + return nil + default: + if invalid != nil { + return invalid(node) + } + return nil + } + } + return collect(value) +} + +// yamlMergeKeyNames returns the key names contributed by a YAML merge value. +// The alias decode applies the merged values; this walk only records which +// keys were present so an explicit zero in a merged block survives. +func yamlMergeKeyNames(value *yaml.Node) []string { + var names []string + _ = walkYAMLMerge(value, false, func(key, _ *yaml.Node) { + names = append(names, key.Value) + }, nil) + return names +} + +// fieldDefPair is one field name together with its definition node, as +// contributed by a YAML merge ("<<") in an entity's `fields` mapping. +type fieldDefPair struct { + name string + value *yaml.Node +} + +// yamlMergeFieldPairs keeps both the key and the value node so each merged +// field definition can be decoded into a string. A merge value may be a +// mapping, an alias to a mapping, or a sequence of such nodes; nested merge +// keys are resolved recursively. Duplicate names keep the first occurrence. +func yamlMergeFieldPairs(value *yaml.Node, mergeKey *yaml.Node) ([]fieldDefPair, error) { + var pairs []fieldDefPair + err := walkYAMLMerge(value, true, + func(key, val *yaml.Node) { + pairs = append(pairs, fieldDefPair{name: key.Value, value: val}) + }, + func(node *yaml.Node) error { + if node.Kind == yaml.AliasNode { + return fmt.Errorf("line %d: '<<' in fields resolves to an undefined alias", mergeKey.Line) + } + return fmt.Errorf("line %d: '<<' in fields must be a mapping or a sequence of mappings, got %s", + mergeKey.Line, strings.ToLower(strings.TrimPrefix(node.ShortTag(), "!!"))) + }, + ) + if err != nil { + return nil, err + } + return pairs, nil +} + +// checkStrictKeys is the single strict-key rule for every nested config block. +// It rejects unknown keys, including ones contributed by a YAML merge ("<<"), +// and optionally records which allowed keys were present. errFn carries the +// block-specific wording; line preserves the source location from the node. +func checkStrictKeys(value *yaml.Node, allowed []string, errFn func(string, int) error, mark func(string)) error { + if value.Kind != yaml.MappingNode { + return nil + } + valid := specmeta.SliceToSet(allowed) + for i := 0; i < len(value.Content)-1; i += 2 { + keyNode := value.Content[i] + key := keyNode.Value + if key == "<<" && keyNode.Tag != "!!str" { + for _, name := range yamlMergeKeyNames(value.Content[i+1]) { + if !valid[name] { + return errFn(name, keyNode.Line) + } + if mark != nil { + mark(name) + } + } + continue + } + if !valid[key] { + return errFn(key, keyNode.Line) + } + if mark != nil { + mark(key) + } + } + return nil +} + +// decodeWithStrictKeys is the shared decode skeleton: non-mapping values are +// decoded as-is, mapping values are checked first. Callers only supply the +// rejection message and an optional presence marker. +func decodeWithStrictKeys(value *yaml.Node, target any, allowed []string, errFn func(string, int) error, mark func(string)) error { + if value.Kind != yaml.MappingNode { + return value.Decode(target) + } + if err := checkStrictKeys(value, allowed, errFn, mark); err != nil { + return err + } + return value.Decode(target) +} + +// decodeStrict decodes a block into an alias target, rejecting unknown keys. +func decodeStrict(value *yaml.Node, target any, allowed []string, reject func(string, int) error) error { + return decodeWithStrictKeys(value, target, allowed, reject, nil) +} + +// unmarshalYAMLWithPresence decodes a config block through target — an alias +// of the concrete config type, so yaml.v3 does not re-enter UnmarshalYAML — +// while recording which of the keys in presence were present. Presence is +// tracked for direct keys and for keys contributed by a YAML merge ("<<"), +// so an explicit zero survives the defaulting pass in ParseRawSchema. +// +// Every key must be listed in allowed. Node.Decode uses a fresh decoder without +// KnownFields(true), so strict decoding is enforced here to keep the root +// decoder's unknown-key behavior inside the block. +func unmarshalYAMLWithPresence(value *yaml.Node, target any, typeName string, allowed []string, presence map[string]func()) error { + errFn := func(key string, line int) error { + return fmt.Errorf("line %d: field %s not found in type parser.%s", line, key, typeName) + } + mark := func(key string) { + if fn, tracked := presence[key]; tracked { + fn() + } + } + return decodeWithStrictKeys(value, target, allowed, errFn, mark) +} + +type deployConfigAlias DeployConfig + +// UnmarshalYAML records key presence before decoding the block. Decoding goes +// through an alias so yaml.v3 does not call this method recursively. +func (d *DeployConfig) UnmarshalYAML(value *yaml.Node) error { + return unmarshalYAMLWithPresence(value, (*deployConfigAlias)(d), "DeployConfig", + []string{"domain", "port"}, + map[string]func(){"port": func() { d.portSet = true }}) } // CacheConfig represents cache configuration (agnostic — no language/platform specifics). @@ -112,12 +288,46 @@ type RateLimitConfig struct { Policy string `yaml:"policy" json:"policy,omitempty"` // fixed | sliding PermitLimit int `yaml:"permit_limit" json:"permit_limit,omitempty"` WindowSeconds int `yaml:"window_seconds" json:"window_seconds,omitempty"` + // Presence flags distinguish an explicit 0 (deny all / no window) from an + // omitted key that must receive the documented default. + permitLimitSet bool + windowSecondsSet bool +} + +type rateLimitConfigAlias RateLimitConfig + +// UnmarshalYAML records key presence before decoding the block. Decoding goes +// through an alias so yaml.v3 does not call this method recursively. +func (r *RateLimitConfig) UnmarshalYAML(value *yaml.Node) error { + return unmarshalYAMLWithPresence(value, (*rateLimitConfigAlias)(r), "RateLimitConfig", + []string{"enabled", "policy", "permit_limit", "window_seconds"}, + map[string]func(){ + "permit_limit": func() { r.permitLimitSet = true }, + "window_seconds": func() { r.windowSecondsSet = true }, + }) } // PaginationConfig represents list pagination sizing. type PaginationConfig struct { DefaultPageSize int `yaml:"default_page_size" json:"default_page_size,omitempty"` MaxPageSize int `yaml:"max_page_size" json:"max_page_size,omitempty"` + // Presence flags distinguish an explicit 0 from an omitted key that must + // receive the documented default. + defaultPageSizeSet bool + maxPageSizeSet bool +} + +type paginationConfigAlias PaginationConfig + +// UnmarshalYAML records key presence before decoding the block. Decoding goes +// through an alias so yaml.v3 does not call this method recursively. +func (p *PaginationConfig) UnmarshalYAML(value *yaml.Node) error { + return unmarshalYAMLWithPresence(value, (*paginationConfigAlias)(p), "PaginationConfig", + []string{"default_page_size", "max_page_size"}, + map[string]func(){ + "default_page_size": func() { p.defaultPageSizeSet = true }, + "max_page_size": func() { p.maxPageSizeSet = true }, + }) } // MultiTenancyConfig holds multi-tenancy settings @@ -128,13 +338,13 @@ type MultiTenancyConfig struct { // RawEntity represents an unprocessed entity from YAML type RawEntity struct { - OldName string `yaml:"old_name" json:"old_name,omitempty"` // hint for the migration engine: previous entity name (rename detection) - Features []string `yaml:"features" json:"features,omitempty"` - Fields map[string]string `yaml:"fields" json:"fields"` - FieldOrder []string `yaml:"-" json:"fieldOrder"` // preserved from YAML — not a yaml tag - Indexes []RawIndex `yaml:"indexes" json:"indexes,omitempty"` - Permissions *RawPermissions `yaml:"permissions" json:"permissions,omitempty"` - Seed []map[string]interface{} `yaml:"seed" json:"seed,omitempty"` + OldName string `yaml:"old_name" json:"old_name,omitempty"` // hint for the migration engine: previous entity name (rename detection) + Features []string `yaml:"features" json:"features,omitempty"` + Fields map[string]string `yaml:"fields" json:"fields"` + FieldOrder []string `yaml:"-" json:"fieldOrder"` // preserved from YAML — not a yaml tag + Indexes []RawIndex `yaml:"indexes" json:"indexes,omitempty"` + Permissions *RawPermissions `yaml:"permissions" json:"permissions,omitempty"` + Seed []map[string]any `yaml:"seed" json:"seed,omitempty"` } // RawPermissions represents entity permissions before parsing. @@ -147,17 +357,11 @@ type RawPermissions struct { // UnmarshalYAML rejects unknown permission keys instead of silently ignoring them. func (p *RawPermissions) UnmarshalYAML(value *yaml.Node) error { - if value.Kind != yaml.MappingNode { - return value.Decode((*rawPermissionsAlias)(p)) + // Unknown keys become errors, including ones smuggled through a YAML merge. + reject := func(key string, _ int) error { + return fmt.Errorf("unknown permission key %q; valid keys: %s", key, strings.Join(specmeta.PermissionKeys, ", ")) } - // Iterate keys explicitly so unknown permission keys become errors. - for i := 0; i < len(value.Content)-1; i += 2 { - key := value.Content[i].Value - if !specmeta.IsPermissionKey(key) { - return fmt.Errorf("unknown permission key %q; valid keys: %s", key, strings.Join(specmeta.PermissionKeys, ", ")) - } - } - return value.Decode((*rawPermissionsAlias)(p)) + return decodeStrict(value, (*rawPermissionsAlias)(p), specmeta.PermissionKeys, reject) } type rawPermissionsAlias RawPermissions @@ -186,20 +390,71 @@ func (e *RawEntity) UnmarshalYAML(value *yaml.Node) error { return err } case "fields": - e.Fields = make(map[string]string) - e.FieldOrder = make([]string, 0, len(valNode.Content)/2) + if valNode.Kind != yaml.MappingNode { + return fmt.Errorf("line %d: fields must be a mapping of field name to definition", valNode.Line) + } + // `fields` stays a mapping of field name → definition string. An + // unquoted `<<` merges fields from an alias to a mapping or from a + // sequence of such mappings/aliases; a quoted `"<<"` is an ordinary + // field name and is not a merge. + // + // Ordering rule: merged fields come first, in merge order (for a + // sequence the earlier entry wins on duplicate names), followed by + // the entity's own declared fields. A direct field overrides a + // merged definition but keeps the merged position, so generated + // field order stays stable when a definition is customized locally. + fields := make(map[string]string) + order := make([]string, 0, len(valNode.Content)/2) + merged := make(map[string]bool) + addField := func(name string, defNode *yaml.Node, fromMerge bool) error { + var def string + if err := defNode.Decode(&def); err != nil { + return fmt.Errorf("field %q: %w", name, err) + } + if _, exists := fields[name]; exists { + if fromMerge { + return nil // first occurrence wins + } + if !merged[name] { + return fmt.Errorf("duplicate field %q in entity fields", name) + } + fields[name] = def // explicit field wins, position is unchanged + merged[name] = false + return nil + } + fields[name] = def + merged[name] = fromMerge + order = append(order, name) + return nil + } + // Two passes: merges always contribute their fields before the + // entity's own fields, regardless of where `<<` appears in YAML. for j := 0; j < len(valNode.Content)-1; j += 2 { - fKey := valNode.Content[j].Value - if _, dup := e.Fields[fKey]; dup { - return fmt.Errorf("duplicate field %q in entity fields", fKey) + key, val := valNode.Content[j], valNode.Content[j+1] + if key.Value != "<<" || key.Tag == "!!str" { + continue } - var fVal string - if err := valNode.Content[j+1].Decode(&fVal); err != nil { + pairs, err := yamlMergeFieldPairs(val, key) + if err != nil { return err } - e.Fields[fKey] = fVal - e.FieldOrder = append(e.FieldOrder, fKey) + for _, pair := range pairs { + if err := addField(pair.name, pair.value, true); err != nil { + return err + } + } } + for j := 0; j < len(valNode.Content)-1; j += 2 { + key, val := valNode.Content[j], valNode.Content[j+1] + if key.Value == "<<" && key.Tag != "!!str" { + continue + } + if err := addField(key.Value, val, false); err != nil { + return err + } + } + e.Fields = fields + e.FieldOrder = order case "indexes": if err := valNode.Decode(&e.Indexes); err != nil { return err @@ -235,17 +490,10 @@ type RawIndex struct { // UnmarshalYAML rejects unknown index keys instead of silently ignoring them. func (r *RawIndex) UnmarshalYAML(value *yaml.Node) error { - if value.Kind != yaml.MappingNode { - return value.Decode((*rawIndexAlias)(r)) - } - valid := specmeta.SliceToSet([]string{"fields", "type", "sort", "unique"}) - for i := 0; i < len(value.Content)-1; i += 2 { - key := value.Content[i].Value - if !valid[key] { - return fmt.Errorf("unknown index key %q; valid keys: fields, type, sort, unique", key) - } + reject := func(key string, _ int) error { + return fmt.Errorf("unknown index key %q; valid keys: %s", key, strings.Join(specmeta.IndexKeys, ", ")) } - return value.Decode((*rawIndexAlias)(r)) + return decodeStrict(value, (*rawIndexAlias)(r), specmeta.IndexKeys, reject) } type rawIndexAlias RawIndex @@ -261,19 +509,19 @@ func ParseRawSchema(data []byte) (*RawSchema, error) { // Set defaults if schema.Database == "" { - schema.Database = specmeta.Databases[0] + schema.Database = specmeta.DefaultDatabase } if schema.Auth.Type == "" { - schema.Auth.Type = specmeta.AuthTypes[len(specmeta.AuthTypes)-1] // "none" + schema.Auth.Type = specmeta.AuthTypeNone } if schema.APIStyle == "" { - schema.APIStyle = specmeta.APIStyles[0] + schema.APIStyle = specmeta.DefaultAPIStyle } // Deploy defaults — consistent with parser setting other defaults. if schema.Project.Deploy == nil { schema.Project.Deploy = &DeployConfig{} } - if schema.Project.Deploy.Port == 0 { + if !schema.Project.Deploy.portSet { schema.Project.Deploy.Port = 8080 } if schema.Project.Deploy.Domain == "" { @@ -295,10 +543,10 @@ func ParseRawSchema(data []byte) (*RawSchema, error) { if schema.Project.RateLimit.Policy == "" { schema.Project.RateLimit.Policy = "fixed" } - if schema.Project.RateLimit.PermitLimit == 0 { + if !schema.Project.RateLimit.permitLimitSet { schema.Project.RateLimit.PermitLimit = 100 } - if schema.Project.RateLimit.WindowSeconds == 0 { + if !schema.Project.RateLimit.windowSecondsSet { schema.Project.RateLimit.WindowSeconds = 60 } @@ -306,10 +554,10 @@ func ParseRawSchema(data []byte) (*RawSchema, error) { if schema.Project.Pagination == nil { schema.Project.Pagination = &PaginationConfig{} } - if schema.Project.Pagination.DefaultPageSize == 0 { + if !schema.Project.Pagination.defaultPageSizeSet { schema.Project.Pagination.DefaultPageSize = 20 } - if schema.Project.Pagination.MaxPageSize == 0 { + if !schema.Project.Pagination.maxPageSizeSet { schema.Project.Pagination.MaxPageSize = 200 } diff --git a/internal/parser/parse_field_test.go b/internal/parser/parse_field_test.go new file mode 100644 index 0000000..0e9a019 --- /dev/null +++ b/internal/parser/parse_field_test.go @@ -0,0 +1,104 @@ +package parser + +import ( + "testing" + + "github.com/DomainCraft/DomainCraft/pkg/textutil" +) + +func TestParseFieldNormalization(t *testing.T) { + t.Parallel() + cases := []struct { + name string + fieldName string + input string + wantRequired bool + wantColumn string + wantRelationTyp string + }{ + { + name: "primary implies required and required validation", + fieldName: "id", + input: "uuid [primary]", + wantRequired: true, + wantColumn: "id", + }, + { + name: "required is mirrored into validations", + fieldName: "title", + input: "string [required]", + wantRequired: true, + wantColumn: "title", + }, + { + name: "optional stays not required", + fieldName: "deletedAt", + input: "datetime [optional]", + wantRequired: false, + wantColumn: "deleted_at", + }, + { + name: "many relation infers many-to-many", + fieldName: "tags", + input: "relation(Tag) [many]", + wantColumn: "tags", + wantRelationTyp: "many-to-many", + }, + { + name: "unique relation infers one-to-one", + fieldName: "owner", + input: "relation(User) [unique]", + wantColumn: "owner", + wantRelationTyp: "one-to-one", + }, + { + name: "plain relation infers many-to-one", + fieldName: "categoryId", + input: "relation(Category)", + wantColumn: "category_id", + wantRelationTyp: "many-to-one", + }, + { + name: "scalar has no relation type", + fieldName: "IPv4Address", + input: "string", + wantColumn: textutil.ToDatabaseColumnName("IPv4Address"), + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + field, err := ParseField(c.fieldName, c.input) + if err != nil { + t.Fatalf("ParseField(%q, %q) error = %v", c.fieldName, c.input, err) + } + if field.Name != c.fieldName { + t.Errorf("Name = %q, want %q", field.Name, c.fieldName) + } + if field.IsRequired != c.wantRequired { + t.Errorf("IsRequired = %v, want %v", field.IsRequired, c.wantRequired) + } + if c.wantRequired && field.Validations["required"] != "true" { + t.Errorf("Validations[required] = %q, want true", field.Validations["required"]) + } + if !c.wantRequired { + if _, ok := field.Validations["required"]; ok { + t.Error("Validations must not contain required when IsRequired is false") + } + } + if field.DatabaseColumnName != c.wantColumn { + t.Errorf("DatabaseColumnName = %q, want %q", field.DatabaseColumnName, c.wantColumn) + } + if field.RelationType != c.wantRelationTyp { + t.Errorf("RelationType = %q, want %q", field.RelationType, c.wantRelationTyp) + } + }) + } +} + +func TestParseFieldInvalidDefinition(t *testing.T) { + t.Parallel() + if _, err := ParseField("id", "unknown"); err == nil { + t.Error("ParseField with unknown type should fail") + } +} diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 9e2aaf2..fd27c0e 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -1,3 +1,4 @@ +// Package parser decodes domain.yaml into the parsed schema used by the validator and IR builder. package parser import ( @@ -37,7 +38,7 @@ type ParsedEntity struct { FieldOrder []string // field order for generation Indexes []*ParsedIndex Permissions *ParsedPermissions - Seed []map[string]interface{} + Seed []map[string]any } // ParsedField represents a fully parsed field @@ -63,10 +64,9 @@ func (f *ParsedField) NavigationName() string { if f.IsMany { name = textutil.Singularize(name) } - // Strip "Id" or "ID" suffix (FK convention), not arbitrary "id" substrings. - if strings.HasSuffix(name, "Id") && len(name) > 2 { - name = name[:len(name)-2] - } else if strings.HasSuffix(name, "ID") && len(name) > 2 { + // Strip an FK id suffix (Id / ID) via the shared specmeta helper. + // Lowercase "id" is not an FK format: fluid and squid keep their names. + if specmeta.HasIDSuffix(name) { name = name[:len(name)-2] } if name == "" { @@ -92,13 +92,16 @@ type ParsedPermissions struct { Delete []string } -// NewParser creates a new Parser -func NewParser(raw *RawSchema) *Parser { +// New creates a new Parser. +func New(raw *RawSchema) *Parser { return &Parser{raw: raw} } // Parse performs full parsing with validation func (p *Parser) Parse() (*ParsedSchema, error) { + if p == nil || p.raw == nil { + return nil, fmt.Errorf("parser: raw schema is nil") + } auth := p.raw.Auth schema := &ParsedSchema{ Project: p.raw.Project, @@ -111,7 +114,8 @@ func (p *Parser) Parse() (*ParsedSchema, error) { } // Parse all entities - for entityName, rawEntity := range p.raw.Entities { + for _, entityName := range slices.Sorted(maps.Keys(p.raw.Entities)) { + rawEntity := p.raw.Entities[entityName] entity, err := p.parseEntity(entityName, rawEntity) if err != nil { return nil, fmt.Errorf("error parsing entity '%s': %w", entityName, err) @@ -120,9 +124,6 @@ func (p *Parser) Parse() (*ParsedSchema, error) { schema.EntityOrder = append(schema.EntityOrder, entityName) } - // Sort for deterministic order - slices.Sort(schema.EntityOrder) - return schema, nil } @@ -138,26 +139,28 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) Indexes: make([]*ParsedIndex, 0), } - // Parse features (behavior macros) + // Parse features (behavior macros). Duplicates are rejected here: the + // Features map cannot carry them, so a later check could never fire. for _, feature := range raw.Features { feature = strings.TrimSpace(feature) if !specmeta.IsFeature(feature) { return nil, fmt.Errorf("unknown feature: %s", feature) } + if entity.Features[feature] { + return nil, fmt.Errorf("duplicate feature: %s", feature) + } entity.Features[feature] = true } // Add automatic fields based on features - if err := p.addFeatureFields(entity); err != nil { - return nil, err - } + p.addFeatureFields(entity) // Parse fields in YAML order (preserved by RawEntity.UnmarshalYAML). for _, fieldName := range raw.FieldOrder { fieldDef := raw.Fields[fieldName] - field, err := p.parseField(fieldName, fieldDef) + field, err := ParseField(fieldName, fieldDef) if err != nil { - return nil, err + return nil, fmt.Errorf("field %q: %w", fieldName, err) } entity.Fields[fieldName] = field // Skip if already added by addFeatureFields (user overriding a feature field). @@ -195,8 +198,11 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) return entity, nil } -// parseField parses a single field using the lexer -func (p *Parser) parseField(name string, fieldDef string) (*ParsedField, error) { +// ParseField parses a single field definition and applies the parser's semantic +// normalization (primary implies required, optional clears required, required is +// mirrored into the validations map, and relation fields get their relation +// type). Both Parser and testutil go through this one function. +func ParseField(name string, fieldDef string) (*ParsedField, error) { fd, err := lexer.ParseFieldString(fieldDef) if err != nil { return nil, err @@ -218,13 +224,14 @@ func (p *Parser) parseField(name string, fieldDef string) (*ParsedField, error) // Infer relation type for relation fields. var relType string - if fd.Type == "relation" { - if fd.IsMany { - relType = "many-to-many" - } else if fd.IsUnique { - relType = "one-to-one" - } else { - relType = "many-to-one" + if fd.Type == specmeta.FieldTypeRelation { + switch { + case fd.IsMany: + relType = specmeta.RelationTypeManyToMany + case fd.IsUnique: + relType = specmeta.RelationTypeOneToOne + default: + relType = specmeta.RelationTypeManyToOne } } @@ -239,7 +246,7 @@ func (p *Parser) parseField(name string, fieldDef string) (*ParsedField, error) // addFeatureFields adds automatic fields based on entity features. // Uses specmeta.FeatureFieldDefs as the single source of truth. -func (p *Parser) addFeatureFields(entity *ParsedEntity) error { +func (p *Parser) addFeatureFields(entity *ParsedEntity) { // Iterate in sorted order for deterministic field generation. names := slices.Sorted(maps.Keys(specmeta.FeatureFieldDefs)) for _, fieldName := range names { @@ -250,7 +257,6 @@ func (p *Parser) addFeatureFields(entity *ParsedEntity) error { entity.Fields[fieldName] = newFeatureField(fieldName, def) entity.FieldOrder = append(entity.FieldOrder, fieldName) } - return nil } // newFeatureField creates a ParsedField for an auto-generated feature field. @@ -287,6 +293,6 @@ func ParseYAML(data []byte) (*ParsedSchema, error) { return nil, fmt.Errorf("error parsing YAML: %w", err) } - parser := NewParser(raw) + parser := New(raw) return parser.Parse() } diff --git a/internal/parser/parser_hardening_test.go b/internal/parser/parser_hardening_test.go new file mode 100644 index 0000000..e5d84b4 --- /dev/null +++ b/internal/parser/parser_hardening_test.go @@ -0,0 +1,239 @@ +package parser + +import ( + "reflect" + "strings" + "testing" +) + +func FuzzParseRawSchema(f *testing.F) { + for _, seed := range []string{ + "project:\n name: Test\nentities: {}\n", + "project:\n name: Test\nentities:\n Item:\n fields:\n id: uuid [primary]\n", + "entities: [\n", + "", + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, data string) { + schema, err := ParseRawSchema([]byte(data)) + if err == nil && schema == nil { + t.Fatal("ParseRawSchema returned neither a schema nor an error") + } + }) +} + +func TestStrictParsingRejectsStructuralShortcuts(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + yaml string + wantText string + }{ + { + name: "fields sequence", + yaml: `project: + name: Test +entities: + Item: + fields: [id, uuid] +`, + wantText: "fields must be a mapping", + }, + { + name: "unknown key through merge", + yaml: `project: + name: Test + rate_limit: + <<: &rl + typo_secret: 1 + permit_limit: 5 +entities: {} +`, + wantText: "field typo_secret not found", + }, + { + name: "unknown permission key through merge", + yaml: `project: + name: Test +entities: + Item: + fields: + id: uuid [primary] + permissions: + <<: &p + typo: [Admin] + read: [Admin] +`, + wantText: "unknown permission key", + }, + { + name: "unknown index key through merge", + yaml: `project: + name: Test +entities: + Item: + fields: + id: uuid [primary] + indexes: + - <<: &i + typo: true + fields: [id] +`, + wantText: "unknown index key", + }, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + _, err := ParseRawSchema([]byte(c.yaml)) + if err == nil || !strings.Contains(err.Error(), c.wantText) { + t.Fatalf("ParseRawSchema error = %v, want substring %q", err, c.wantText) + } + }) + } +} + +// TestFieldsYAMLMerge pins the contract for YAML merge keys ("<<") inside an +// entity's `fields` mapping: merged fields come first, in merge order, and a +// directly declared field overrides a merged definition without moving it. +func TestFieldsYAMLMerge(t *testing.T) { + t.Parallel() + tests := []struct { + name string + yaml string + wantOrder []string + wantFields map[string]string + wantErr string + }{ + { + name: "anchor mapping merged before own fields", + yaml: `project: + name: Test +entities: + Base: + fields: &base + id: uuid [primary] + createdAt: datetime + Item: + fields: + <<: *base + name: string [required] +`, + wantOrder: []string{"id", "createdAt", "name"}, + wantFields: map[string]string{ + "id": "uuid [primary]", + "createdAt": "datetime", + "name": "string [required]", + }, + }, + { + name: "sequence of merge aliases keeps first definition and first position", + yaml: `project: + name: Test +entities: + First: + fields: &first + id: uuid [primary] + title: string [max:10] + Second: + fields: &second + id: int [primary] + title: string [max:20] + price: decimal + Item: + fields: + <<: [*first, *second] + name: string [required] +`, + wantOrder: []string{"id", "title", "price", "name"}, + wantFields: map[string]string{ + "id": "uuid [primary]", + "title": "string [max:10]", + "price": "decimal", + "name": "string [required]", + }, + }, + { + name: "direct field overrides merged definition and keeps merged position", + yaml: `project: + name: Test +entities: + Base: + fields: &base + id: uuid [primary] + name: string [max:10] + price: decimal + Item: + fields: + name: string [required, max:255] + <<: *base +`, + wantOrder: []string{"id", "name", "price"}, + wantFields: map[string]string{ + "id": "uuid [primary]", + "name": "string [required, max:255]", + "price": "decimal", + }, + }, + { + name: "unquoted merge with scalar value is an error", + yaml: `project: + name: Test +entities: + Item: + fields: + <<: oops + name: string [required] +`, + wantErr: "must be a mapping or a sequence of mappings", + }, + { + name: "quoted merge key is an ordinary field", + yaml: `project: + name: Test +entities: + Item: + fields: + "<<": string + id: uuid [primary] +`, + wantOrder: []string{"<<", "id"}, + wantFields: map[string]string{ + "<<": "string", + "id": "uuid [primary]", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + schema, err := ParseRawSchema([]byte(tt.yaml)) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("ParseRawSchema error = %v, want substring %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("ParseRawSchema error = %v", err) + } + entity, ok := schema.Entities["Item"] + if !ok { + t.Fatalf("entity Item not found in %v", schema.Entities) + } + if !reflect.DeepEqual(entity.FieldOrder, tt.wantOrder) { + t.Errorf("FieldOrder = %v, want %v", entity.FieldOrder, tt.wantOrder) + } + if !reflect.DeepEqual(entity.Fields, tt.wantFields) { + t.Errorf("Fields = %v, want %v", entity.Fields, tt.wantFields) + } + }) + } +} + +func TestParseNilRawSchema(t *testing.T) { + t.Parallel() + if _, err := New(nil).Parse(); err == nil { + t.Fatal("expected an error for nil raw schema") + } +} diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index b32f61b..39de52c 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -1,11 +1,15 @@ package parser import ( + "fmt" "strings" "testing" + + "gopkg.in/yaml.v3" ) func TestParseStrictRejectsUnknownKeys(t *testing.T) { + t.Parallel() tests := []struct { name string yaml string @@ -70,9 +74,40 @@ entities: {} `, wantErr: "field typo_field not found in type parser.ProjectConfig", }, + { + name: "unknown deploy key", + yaml: `project: + name: Test + deploy: + typo_field: 1 +entities: {} +`, + wantErr: "field typo_field not found in type parser.DeployConfig", + }, + { + name: "unknown rate limit key", + yaml: `project: + name: Test + rate_limit: + typo_field: 1 +entities: {} +`, + wantErr: "field typo_field not found in type parser.RateLimitConfig", + }, + { + name: "unknown pagination key", + yaml: `project: + name: Test + pagination: + typo_field: 1 +entities: {} +`, + wantErr: "field typo_field not found in type parser.PaginationConfig", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() _, err := ParseRawSchema([]byte(tt.yaml)) if err == nil { t.Fatalf("ParseRawSchema() expected error containing %q, got nil", tt.wantErr) @@ -84,7 +119,53 @@ entities: {} } } +// TestUnmarshalYAMLHelpersRejectUnknownKeysForAllConfigs pins the shared +// presence-aware UnmarshalYAML helper: every config block that opts into it +// must reject unknown keys with the same strict-decoding message, and must +// still accept its own keys (the latter is covered by the explicit-zero tests). +func TestUnmarshalYAMLHelpersRejectUnknownKeysForAllConfigs(t *testing.T) { + t.Parallel() + cases := []struct { + name string + newValue func() any + yaml string + wantErr string + }{ + { + name: "DeployConfig", + newValue: func() any { return &DeployConfig{} }, + yaml: "port: 8080\ntypo_field: 1\n", + wantErr: "field typo_field not found in type parser.DeployConfig", + }, + { + name: "RateLimitConfig", + newValue: func() any { return &RateLimitConfig{} }, + yaml: "permit_limit: 100\nwindow_seconds: 60\ntypo_field: 1\n", + wantErr: "field typo_field not found in type parser.RateLimitConfig", + }, + { + name: "PaginationConfig", + newValue: func() any { return &PaginationConfig{} }, + yaml: "default_page_size: 20\nmax_page_size: 200\ntypo_field: 1\n", + wantErr: "field typo_field not found in type parser.PaginationConfig", + }, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := yaml.Unmarshal([]byte(tt.yaml), tt.newValue()) + if err == nil { + t.Fatalf("yaml.Unmarshal() expected error containing %q, got nil", tt.wantErr) + } + if !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("yaml.Unmarshal() error = %q, want it to contain %q", err.Error(), tt.wantErr) + } + }) + } +} + func TestParseRawSchema(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test Project @@ -116,6 +197,7 @@ entities: } func TestParseDefaults(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -139,6 +221,7 @@ entities: {} } func TestParseEntity(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -189,6 +272,7 @@ entities: } func TestParseFeatures(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -224,6 +308,7 @@ entities: } func TestParseRelations(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -242,32 +327,33 @@ entities: product := parsed.Entities["Product"] - // Check categoryId - categoryId := product.Fields["categoryId"] - if categoryId.Type != "relation" { - t.Errorf("categoryId type should be relation") + // Check categoryID + categoryID := product.Fields["categoryId"] + if categoryID.Type != "relation" { + t.Errorf("categoryID type should be relation") } - if categoryId.TargetEntity != "Category" { - t.Errorf("categoryId target should be Category") + if categoryID.TargetEntity != "Category" { + t.Errorf("categoryID target should be Category") } - if !categoryId.IsOptional { - t.Errorf("categoryId should be optional") + if !categoryID.IsOptional { + t.Errorf("categoryID should be optional") } - if categoryId.OnDelete != "set_null" { - t.Errorf("categoryId on_delete should be set_null") + if categoryID.OnDelete != "set_null" { + t.Errorf("categoryID on_delete should be set_null") } - // Check supplierId - supplierId := product.Fields["supplierId"] - if supplierId.TargetEntity != "User" { - t.Errorf("supplierId target should be User") + // Check supplierID + supplierID := product.Fields["supplierId"] + if supplierID.TargetEntity != "User" { + t.Errorf("supplierID target should be User") } - if supplierId.IsOptional { - t.Errorf("supplierId should not be optional") + if supplierID.IsOptional { + t.Errorf("supplierID should not be optional") } } func TestParseIndexes(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -306,6 +392,7 @@ entities: } func TestPluralizeNames(t *testing.T) { + t.Parallel() tests := []struct { singular string plural string @@ -318,17 +405,21 @@ func TestPluralizeNames(t *testing.T) { } for _, tt := range tests { - // Test via ParseYAML since pluralize is an internal function - yamlData := []byte("project:\n name: Test\nentities:\n " + tt.singular + ":\n fields:\n id: uuid [primary]") - parsed, _ := ParseYAML(yamlData) - entity := parsed.Entities[tt.singular] - if entity.NamePlural != tt.plural { - t.Errorf("pluralize(%s) = %s, want %s", tt.singular, entity.NamePlural, tt.plural) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + // Test via ParseYAML since pluralize is an internal function + yamlData := []byte("project:\n name: Test\nentities:\n " + tt.singular + ":\n fields:\n id: uuid [primary]") + parsed, _ := ParseYAML(yamlData) + entity := parsed.Entities[tt.singular] + if entity.NamePlural != tt.plural { + t.Errorf("pluralize(%s) = %s, want %s", tt.singular, entity.NamePlural, tt.plural) + } + }) } } func TestDatabaseColumnNames(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -359,15 +450,19 @@ entities: } for _, tt := range tests { - if field, ok := user.Fields[tt.fieldName]; ok { - if field.DatabaseColumnName != tt.wantDbName { - t.Errorf("field %s: got db name %v, want %v", tt.fieldName, field.DatabaseColumnName, tt.wantDbName) + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if field, ok := user.Fields[tt.fieldName]; ok { + if field.DatabaseColumnName != tt.wantDbName { + t.Errorf("field %s: got db name %v, want %v", tt.fieldName, field.DatabaseColumnName, tt.wantDbName) + } } - } + }) } } func TestParsePermissions(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -398,6 +493,7 @@ entities: } func TestParsePrimaryImpliesRequired(t *testing.T) { + t.Parallel() // Parser normalizes primary→required (lexer no longer does this). yamlData := []byte(` project: @@ -422,6 +518,7 @@ entities: } func TestParseOptionalImpliesNotRequired(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -446,6 +543,7 @@ entities: } func TestParseRelationTypeInference(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -481,14 +579,18 @@ entities: {"categoryIds", "many-to-many"}, } for _, tt := range tests { - f := order.Fields[tt.field] - if f.RelationType != tt.wantType { - t.Errorf("field %s: RelationType = %q, want %q", tt.field, f.RelationType, tt.wantType) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + f := order.Fields[tt.field] + if f.RelationType != tt.wantType { + t.Errorf("field %s: RelationType = %q, want %q", tt.field, f.RelationType, tt.wantType) + } + }) } } func TestParseDeployDefaults(t *testing.T) { + t.Parallel() // Parser should set deploy defaults (port=8080, domain=localhost). yamlData := []byte(` project: @@ -514,6 +616,7 @@ entities: } func TestParseDeployExplicitValues(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -538,6 +641,7 @@ entities: } func TestParseVersioningRateLimitPaginationDefaults(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -583,6 +687,7 @@ entities: } func TestParseVersioningRateLimitExplicit(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -621,6 +726,7 @@ entities: } func TestParseUnknownEntityKey(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -639,6 +745,7 @@ entities: } func TestParseOldName(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -662,6 +769,7 @@ entities: } func TestParseDuplicateField(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -693,6 +801,7 @@ entities: // RawSchema decoding cannot silently reintroduce the overwrite-on-duplicate // behaviour. func TestParseDuplicateEntity(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -716,3 +825,245 @@ entities: t.Errorf("unexpected error: %v", err) } } + +// TestParseDuplicateFeature pins that a feature listed twice is rejected at +// parse time — the Features map collapses duplicates, so a validator-side +// check could never see them. +func TestParseDuplicateFeature(t *testing.T) { + t.Parallel() + tests := []struct { + name string + features string + }{ + {name: "adjacent", features: "[audit, audit]"}, + {name: "separated", features: "[audit, soft_delete, audit]"}, + {name: "whitespace", features: "[audit, ' audit ']"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test +entities: + User: + features: ` + tt.features + ` + fields: + id: uuid [primary] + email: string [required, unique] +`) + _, err := ParseYAML(yamlData) + if err == nil { + t.Fatal("expected error for duplicate feature") + } + if !strings.Contains(err.Error(), "duplicate feature: audit") { + t.Errorf("unexpected error: %v", err) + } + }) + } +} + +// TestParseRawSchemaExplicitZerosPreserved pins the contract that an explicit +// zero in domain.yaml survives parsing. The old defaults treated 0 as "unset", +// silently replacing permit_limit: 0 with 100 (and likewise for the other +// numeric project settings). +func TestParseRawSchemaExplicitZerosPreserved(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test + deploy: + port: 0 + rate_limit: + permit_limit: 0 + window_seconds: 0 + pagination: + default_page_size: 0 + max_page_size: 0 +entities: {} +`) + + parsed, err := ParseRawSchema(yamlData) + if err != nil { + t.Fatalf("ParseRawSchema() error = %v", err) + } + if parsed.Project.Deploy.Port != 0 { + t.Errorf("Deploy.Port = %d, want explicit 0", parsed.Project.Deploy.Port) + } + if parsed.Project.RateLimit.PermitLimit != 0 { + t.Errorf("RateLimit.PermitLimit = %d, want explicit 0", parsed.Project.RateLimit.PermitLimit) + } + if parsed.Project.RateLimit.WindowSeconds != 0 { + t.Errorf("RateLimit.WindowSeconds = %d, want explicit 0", parsed.Project.RateLimit.WindowSeconds) + } + if parsed.Project.Pagination.DefaultPageSize != 0 { + t.Errorf("Pagination.DefaultPageSize = %d, want explicit 0", parsed.Project.Pagination.DefaultPageSize) + } + if parsed.Project.Pagination.MaxPageSize != 0 { + t.Errorf("Pagination.MaxPageSize = %d, want explicit 0", parsed.Project.Pagination.MaxPageSize) + } +} + +// TestParseYAMLPreservesExplicitZeros checks that ParseYAML (the entry point +// used by the CLI and WASM validator) carries the preserved zeros into the +// ParsedSchema the validator sees. +func TestParseYAMLPreservesExplicitZeros(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test + deploy: + port: 0 + rate_limit: + permit_limit: 0 + window_seconds: 0 + pagination: + default_page_size: 0 + max_page_size: 0 +entities: + User: + fields: + id: uuid [primary] +`) + + parsed, err := ParseYAML(yamlData) + if err != nil { + t.Fatalf("ParseYAML() error = %v", err) + } + if parsed.Project.Deploy.Port != 0 { + t.Errorf("Deploy.Port = %d, want explicit 0", parsed.Project.Deploy.Port) + } + if parsed.Project.RateLimit.PermitLimit != 0 { + t.Errorf("RateLimit.PermitLimit = %d, want explicit 0", parsed.Project.RateLimit.PermitLimit) + } + if parsed.Project.RateLimit.WindowSeconds != 0 { + t.Errorf("RateLimit.WindowSeconds = %d, want explicit 0", parsed.Project.RateLimit.WindowSeconds) + } + if parsed.Project.Pagination.DefaultPageSize != 0 { + t.Errorf("Pagination.DefaultPageSize = %d, want explicit 0", parsed.Project.Pagination.DefaultPageSize) + } + if parsed.Project.Pagination.MaxPageSize != 0 { + t.Errorf("Pagination.MaxPageSize = %d, want explicit 0", parsed.Project.Pagination.MaxPageSize) + } +} + +// TestParseRawSchemaOmittedKeysUseDefaults pins the other half of the +// presence contract: a config block with omitted numeric keys still receives +// the documented defaults. +func TestParseRawSchemaOmittedKeysUseDefaults(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test + deploy: {} + rate_limit: {} + pagination: {} +entities: {} +`) + + parsed, err := ParseRawSchema(yamlData) + if err != nil { + t.Fatalf("ParseRawSchema() error = %v", err) + } + if parsed.Project.Deploy.Port != 8080 { + t.Errorf("Deploy.Port = %d, want default 8080", parsed.Project.Deploy.Port) + } + if parsed.Project.RateLimit.PermitLimit != 100 { + t.Errorf("RateLimit.PermitLimit = %d, want default 100", parsed.Project.RateLimit.PermitLimit) + } + if parsed.Project.RateLimit.WindowSeconds != 60 { + t.Errorf("RateLimit.WindowSeconds = %d, want default 60", parsed.Project.RateLimit.WindowSeconds) + } + if parsed.Project.Pagination.DefaultPageSize != 20 { + t.Errorf("Pagination.DefaultPageSize = %d, want default 20", parsed.Project.Pagination.DefaultPageSize) + } + if parsed.Project.Pagination.MaxPageSize != 200 { + t.Errorf("Pagination.MaxPageSize = %d, want default 200", parsed.Project.Pagination.MaxPageSize) + } +} + +// TestParseRawSchemaPartialExplicitZeros checks that presence is tracked per +// key: an explicit zero does not suppress defaults for its siblings. +func TestParseRawSchemaPartialExplicitZeros(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test + deploy: + port: 0 + domain: api.example.com + rate_limit: + permit_limit: 0 + pagination: + max_page_size: 0 +entities: {} +`) + + parsed, err := ParseRawSchema(yamlData) + if err != nil { + t.Fatalf("ParseRawSchema() error = %v", err) + } + if parsed.Project.Deploy.Port != 0 { + t.Errorf("Deploy.Port = %d, want explicit 0", parsed.Project.Deploy.Port) + } + if parsed.Project.Deploy.Domain != "api.example.com" { + t.Errorf("Deploy.Domain = %q, want api.example.com", parsed.Project.Deploy.Domain) + } + if parsed.Project.RateLimit.PermitLimit != 0 { + t.Errorf("RateLimit.PermitLimit = %d, want explicit 0", parsed.Project.RateLimit.PermitLimit) + } + if parsed.Project.RateLimit.WindowSeconds != 60 { + t.Errorf("RateLimit.WindowSeconds = %d, want default 60", parsed.Project.RateLimit.WindowSeconds) + } + if parsed.Project.Pagination.DefaultPageSize != 20 { + t.Errorf("Pagination.DefaultPageSize = %d, want default 20", parsed.Project.Pagination.DefaultPageSize) + } + if parsed.Project.Pagination.MaxPageSize != 0 { + t.Errorf("Pagination.MaxPageSize = %d, want explicit 0", parsed.Project.Pagination.MaxPageSize) + } +} + +// TestNavigationNameStripsIdAndIDSuffixOnly pins the FK convention shared with +// the validator: only Id and ID are stripped. Lowercase id is not an FK format, +// so categoryid keeps its final two letters in the navigation name. +func TestNavigationNameStripsIdAndIDSuffixOnly(t *testing.T) { + t.Parallel() + yamlData := []byte(` +project: + name: Test +entities: + Category: + fields: + id: uuid [primary] + Order: + fields: + id: uuid [primary] + categoryId: relation(Category) + categoryID: relation(Category) + categoryid: relation(Category) +`) + parsed, err := ParseYAML(yamlData) + if err != nil { + t.Fatalf("ParseYAML() error = %v", err) + } + order := parsed.Entities["Order"] + if order == nil { + t.Fatal("Order entity not parsed") + } + for _, tt := range []struct { + fieldName string + want string + }{ + {fieldName: "categoryId", want: "Category"}, + {fieldName: "categoryID", want: "Category"}, + {fieldName: "categoryid", want: "Categoryid"}, + } { + field := order.Fields[tt.fieldName] + if field == nil { + t.Fatalf("field %q not parsed", tt.fieldName) + } + if got := field.NavigationName(); got != tt.want { + t.Errorf("%s.NavigationName() = %q, want %q", tt.fieldName, got, tt.want) + } + } +} diff --git a/internal/renderer/bridgefuncs_test.go b/internal/renderer/bridgefuncs_test.go index 568193b..4618fc0 100644 --- a/internal/renderer/bridgefuncs_test.go +++ b/internal/renderer/bridgefuncs_test.go @@ -1,7 +1,14 @@ package renderer import ( + "bytes" + "io" + "maps" + "math" + "slices" + "strings" "testing" + "text/template" "github.com/DomainCraft/DomainCraft/pkg/logger" ) @@ -35,7 +42,42 @@ func testMappings() *typeMappings { } } +// The FuncMap key set is the bridge contract. Splitting the registrars must +// neither add a core-invented key nor drop a bridge-declared one; columnSize and +// inputType exist only when the bridge declared their mappings. +func TestBuildBridgeFuncsKeySet(t *testing.T) { + t.Parallel() + cases := []struct { + name string + m *typeMappings + want []string + }{ + {name: "nil mappings", m: nil}, + { + name: "minimal mappings", + m: &typeMappings{Types: map[string]string{"int": "int"}}, + want: []string{"arrayLiteralClose", "arrayLiteralOpen", "deleteBehaviorName", "isValueType", "languageType", "literalDefault", "literalMember", "literalValue"}, + }, + { + name: "full mappings", + m: testMappings(), + want: []string{"arrayLiteralClose", "arrayLiteralOpen", "columnSize", "deleteBehaviorName", "inputType", "isValueType", "languageType", "literalDefault", "literalMember", "literalValue"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := slices.Sorted(maps.Keys(buildBridgeFuncs(tc.m, logger.New()))) + want := slices.Sorted(slices.Values(tc.want)) + if !slices.Equal(got, want) { + t.Errorf("FuncMap keys = %v, want %v", got, want) + } + }) + } +} + func TestBuildBridgeFuncs_NilMappings(t *testing.T) { + t.Parallel() funcs := buildBridgeFuncs(nil, logger.New()) if _, ok := funcs["languageType"]; ok { t.Error("nil mappings should produce no bridge funcs") @@ -43,6 +85,7 @@ func TestBuildBridgeFuncs_NilMappings(t *testing.T) { } func TestBuildBridgeFuncs_LanguageType(t *testing.T) { + t.Parallel() fn := buildBridgeFuncs(testMappings(), logger.New())["languageType"].(func(string, bool) string) cases := []struct { @@ -60,6 +103,7 @@ func TestBuildBridgeFuncs_LanguageType(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() if got := fn(c.dbType, c.nullable); got != c.want { t.Errorf("languageType(%q, %v) = %q, want %q", c.dbType, c.nullable, got, c.want) } @@ -81,6 +125,7 @@ func TestBuildBridgeFuncs_LanguageType(t *testing.T) { } func TestBuildBridgeFuncs_DefaultArrayFormatAndOptionalFuncs(t *testing.T) { + t.Parallel() m := &typeMappings{Types: map[string]string{"int": "int32"}} funcs := buildBridgeFuncs(m, logger.New()) @@ -91,15 +136,62 @@ func TestBuildBridgeFuncs_DefaultArrayFormatAndOptionalFuncs(t *testing.T) { t.Error("inputType must be absent when no input_types are declared") } arr := funcs["languageType"].(func(string, bool) string) - if got := arr("array(int)", false); got != "int32[]" { - t.Errorf("default array format = %q, want int32[]", got) + if got := arr("array(int)", false); got != "" { + t.Errorf("array type without array_format = %q, want an empty expression (no core-side syntax)", got) } if got := arr("int", true); got != "int32" { t.Errorf("empty nullable_format must not append a suffix, got %q", got) } } +// With no literal/array/input specs declared, the core must emit no C# or UI +// syntax of its own. Missing specs produce empty expressions and a warning. +func TestBuildBridgeFuncsRequiresLiteralSpecs(t *testing.T) { + t.Parallel() + m := &typeMappings{ + Types: map[string]string{"int": "MyInt"}, + InputTypes: map[string]string{"string": "textbox"}, + } + funcs := buildBridgeFuncs(m, logger.New()) + + literalDefault := funcs["literalDefault"].(func(string) string) + for _, dbType := range []string{"boolean", "OrderStatus", "array(int)"} { + if got := literalDefault(dbType); got != "" { + t.Errorf("literalDefault(%q) = %q, want an empty expression", dbType, got) + } + } + literalMember := funcs["literalMember"].(func(string, string) string) + if got := literalMember("OrderStatus", "draft"); got != "" { + t.Errorf("literalMember = %q, want an empty expression", got) + } + arrayOpen := funcs["arrayLiteralOpen"].(func(string) string) + if got := arrayOpen("array(int)"); got != "" { + t.Errorf("arrayLiteralOpen = %q, want an empty expression", got) + } + if got := funcs["arrayLiteralClose"].(func() string)(); got != "" { + t.Errorf("arrayLiteralClose = %q, want an empty expression", got) + } + languageType := funcs["languageType"].(func(string, bool) string) + if got := languageType("array(int)", false); got != "" { + t.Errorf("languageType(array(int)) = %q, want an empty expression without array_format", got) + } + inputType := funcs["inputType"].(func(string) string) + if got := inputType("unknown"); got != "" { + t.Errorf("inputType(unknown) = %q, want an empty expression", got) + } + + // A bridge that declares the generic enum zero spec keeps its own syntax: + // the core reads it from type_mappings.yaml, never hardcodes it. + withZero := testMappings() + withZero.Literals["enum"] = LiteralSpec{Zero: "(%s)0"} + declared := buildBridgeFuncs(withZero, logger.New())["literalDefault"].(func(string) string) + if got := declared("OrderStatus"); got != "(OrderStatus)0" { + t.Errorf("declared enum zero = %q, want (OrderStatus)0", got) + } +} + func TestBuildBridgeFuncs_LiteralValue(t *testing.T) { + t.Parallel() literalValue := buildBridgeFuncs(testMappings(), logger.New())["literalValue"].(func(string, any) string) cases := []struct { @@ -117,6 +209,7 @@ func TestBuildBridgeFuncs_LiteralValue(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() if got := literalValue(c.dbType, c.value); got != c.want { t.Errorf("literalValue(%q, %v) = %q, want %q", c.dbType, c.value, got, c.want) } @@ -125,17 +218,19 @@ func TestBuildBridgeFuncs_LiteralValue(t *testing.T) { } func TestBuildBridgeFuncs_LiteralDefault(t *testing.T) { + t.Parallel() literalDefault := buildBridgeFuncs(testMappings(), logger.New())["literalDefault"].(func(string) string) cases := []struct{ name, dbType, want string }{ {"declared default expression", "uuid", "Guid.NewGuid()"}, {"scalar default literal", "decimal", "0m"}, - {"no default spec falls back to default(T)", "boolean", "default(boolean)"}, - {"enum generic zero fallback", "OrderStatus", "(OrderStatus)0"}, + {"no default spec emits no language syntax", "boolean", ""}, + {"no enum zero spec emits no language syntax", "OrderStatus", ""}, {"empty array literal", "array(int)", "new List()"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() if got := literalDefault(c.dbType); got != c.want { t.Errorf("literalDefault(%q) = %q, want %q", c.dbType, got, c.want) } @@ -152,6 +247,7 @@ func TestBuildBridgeFuncs_LiteralDefault(t *testing.T) { } func TestBuildBridgeFuncs_LiteralMember(t *testing.T) { + t.Parallel() literalMember := buildBridgeFuncs(testMappings(), logger.New())["literalMember"].(func(string, string) string) if got := literalMember("OrderStatus", "in_transit"); got != "OrderStatus.InTransit" { @@ -162,14 +258,15 @@ func TestBuildBridgeFuncs_LiteralMember(t *testing.T) { } m := testMappings() - m.Literals["enum"] = LiteralSpec{} // Member unset → Type.Value fallback + m.Literals["enum"] = LiteralSpec{} // Member unset → no core-side Type.Member syntax fallback := buildBridgeFuncs(m, logger.New())["literalMember"].(func(string, string) string) - if got := fallback("OrderStatus", "draft"); got != "OrderStatus.Draft" { - t.Errorf("member fallback = %q, want OrderStatus.Draft", got) + if got := fallback("OrderStatus", "draft"); got != "" { + t.Errorf("member fallback = %q, want an empty expression", got) } } func TestBuildBridgeFuncs_ArrayLiteralAndHelpers(t *testing.T) { + t.Parallel() raw := buildBridgeFuncs(testMappings(), logger.New()) open := raw["arrayLiteralOpen"].(func(string) string) @@ -211,12 +308,13 @@ func TestBuildBridgeFuncs_ArrayLiteralAndHelpers(t *testing.T) { if got := inputType("array(datetime)"); got != "DatePicker" { t.Errorf("inputType(array(datetime)) = %q, want the inner type's mapping", got) } - if got := inputType("unknown"); got != "Input" { - t.Errorf("inputType(unknown) = %q, want the Input fallback", got) + if got := inputType("unknown"); got != "" { + t.Errorf("inputType(unknown) = %q, want an empty UI type when no mapping is declared", got) } } func TestMergeTypeMappings_AdapterWinsOnConflicts(t *testing.T) { + t.Parallel() base := &typeMappings{ Types: map[string]string{"uuid": "Guid", "int": "int"}, Literals: map[string]LiteralSpec{"uuid": {Parse: "Base(%s)"}, "decimal": {Suffix: "m"}}, @@ -251,7 +349,109 @@ func TestMergeTypeMappings_AdapterWinsOnConflicts(t *testing.T) { if !merged.EnumNullable { t.Error("enum_nullable should OR-merge across the chain") } - if mergeLiterals(nil, nil) != nil { + if mergeMaps[LiteralSpec](nil, nil) != nil { t.Error("merging two empty literal maps should yield nil") } } + +func TestMergeTypeMappingsAllFields(t *testing.T) { + t.Parallel() + base := &typeMappings{ + Types: map[string]string{"uuid": "BaseId", "int": "int"}, + Behaviors: map[string]string{"cascade": "BaseCascade", "restrict": "Restrict"}, + ValueTypes: []string{"BaseId"}, + ArrayFormat: "BaseArray<%s>", + NullableFormat: "?", + InputTypes: map[string]string{"string": "base-input", "int": "base-number"}, + Literals: map[string]LiteralSpec{"uuid": {Default: "base"}, "int": {Default: "0"}}, + Array: ArrayLiteralSpec{Open: "base(", Close: "base)", Empty: "baseEmpty"}, + ColumnSizes: map[string]string{"string": "100", "uuid": "36"}, + } + overlay := &typeMappings{ + Types: map[string]string{"uuid": "AdapterId"}, + Behaviors: map[string]string{"cascade": "AdapterCascade"}, + InputTypes: map[string]string{"string": "adapter-input"}, + Literals: map[string]LiteralSpec{"uuid": {Default: "adapter"}}, + ColumnSizes: map[string]string{"string": "255"}, + ArrayFormat: "AdapterArray<%s>", + NullableFormat: " | null", + EnumNullable: true, + ValueTypes: []string{"AdapterId"}, + Array: ArrayLiteralSpec{Open: "adapter(", Close: "adapter)", Empty: "adapterEmpty"}, + } + + merged := mergeTypeMappings(base, overlay) + if merged.Types["uuid"] != "AdapterId" || merged.Types["int"] != "int" { + t.Errorf("Types = %v, want adapter override and base entry", merged.Types) + } + if merged.Behaviors["cascade"] != "AdapterCascade" || merged.Behaviors["restrict"] != "Restrict" { + t.Errorf("Behaviors = %v, want adapter override and base entry", merged.Behaviors) + } + if merged.InputTypes["string"] != "adapter-input" || merged.InputTypes["int"] != "base-number" { + t.Errorf("InputTypes = %v, want adapter override and base entry", merged.InputTypes) + } + if merged.ColumnSizes["string"] != "255" || merged.ColumnSizes["uuid"] != "36" { + t.Errorf("ColumnSizes = %v, want adapter override and base entry", merged.ColumnSizes) + } + if merged.Literals["uuid"].Default != "adapter" || merged.Literals["int"].Default != "0" { + t.Errorf("Literals = %v, want adapter override and base entry", merged.Literals) + } + if merged.ArrayFormat != "AdapterArray<%s>" || merged.NullableFormat != " | null" || + !merged.EnumNullable || len(merged.ValueTypes) != 1 || merged.ValueTypes[0] != "AdapterId" { + t.Errorf("scalar fields = %+v, want the adapter's values", merged) + } + if merged.Array != overlay.Array { + t.Errorf("Array = %+v, want %+v", merged.Array, overlay.Array) + } +} + +func TestMergeTypeMappingsClonesValueTypes(t *testing.T) { + t.Parallel() + base := &typeMappings{ValueTypes: []string{"BaseId"}} + merged := mergeTypeMappings(base, &typeMappings{}) + merged.ValueTypes[0] = "Mutated" + if base.ValueTypes[0] != "BaseId" { + t.Errorf("merged mapping aliased the base value types: %v", base.ValueTypes) + } +} + +func TestJSONValueReturnsErrorOnUnsupportedValue(t *testing.T) { + t.Parallel() + if _, err := jsonValue(make(chan int)); err == nil { + t.Error("jsonValue on an unsupported value must return an error") + } + tpl := template.Must(template.New("t").Funcs(template.FuncMap{"jsonValue": jsonValue}).Parse(`{{ jsonValue . }}`)) + if err := tpl.Execute(io.Discard, math.NaN()); err == nil { + t.Error("jsonValue in a template must surface the marshal error") + } +} + +func TestLiteralValueWarnsAndFallsBackOnUnencodableValue(t *testing.T) { + t.Parallel() + var out bytes.Buffer + log := logger.New() + log.SetWriter(&out) + fn := buildBridgeFuncs(testMappings(), log)["literalValue"].(func(string, any) string) + if got := fn("string", math.NaN()); got != "NaN" { + t.Errorf("literalValue(NaN) = %q, want the plain fallback NaN", got) + } + if !strings.Contains(out.String(), "NaN") { + t.Errorf("expected a warning about the unencodable value, got %q", out.String()) + } +} + +func TestBuildBridgeFuncsWarnsOncePerMissingSpec(t *testing.T) { + t.Parallel() + var out bytes.Buffer + log := logger.New() + log.SetWriter(&out) + m := testMappings() + delete(m.Types, "jsonb") + fn := buildBridgeFuncs(m, log)["languageType"].(func(string, bool) string) + for range 5 { + fn("jsonb", false) + } + if n := strings.Count(out.String(), `no type for "jsonb"`); n != 1 { + t.Errorf("missing-type warning printed %d times, want 1: %q", n, out.String()) + } +} diff --git a/internal/renderer/bundled_bridges_test.go b/internal/renderer/bundled_bridges_test.go index d665fd0..57f7998 100644 --- a/internal/renderer/bundled_bridges_test.go +++ b/internal/renderer/bundled_bridges_test.go @@ -15,9 +15,16 @@ import ( // that starts depending on a newer contract — long before it ships. The // byte-identical output half is a follow-up golden test. func TestBundledBridgesLoad(t *testing.T) { + t.Parallel() root := filepath.Join("..", "..", "bridges") if _, err := os.Stat(root); err != nil { - t.Skipf("no bundled bridges tree at %s: %v", root, err) + // In a standalone checkout the monorepo tree is absent. Skipping is only + // acceptable when the developer explicitly opts into that local-dev mode; + // otherwise a missing tree would silently certify zero bridges in CI. + if os.Getenv("DOMAINCRAFT_LOCAL_DEV") != "" { + t.Skipf("no bundled bridges tree at %s (DOMAINCRAFT_LOCAL_DEV set): %v", root, err) + } + t.Fatalf("bundled bridges tree missing at %s: %v", root, err) } var found int diff --git a/internal/renderer/contract_test.go b/internal/renderer/contract_test.go index 2eaafdb..f6823bb 100644 --- a/internal/renderer/contract_test.go +++ b/internal/renderer/contract_test.go @@ -2,27 +2,21 @@ package renderer import ( "bytes" - "os" - "path/filepath" + "slices" "strings" "testing" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/logger" ) func writeBridgeConfig(t *testing.T, yamlContent string) string { t.Helper() - dir := filepath.Join(t.TempDir(), "b") - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "bridge.yaml"), []byte(yamlContent), 0o644); err != nil { - t.Fatal(err) - } - return dir + return writeBridge(t, map[string]string{"bridge.yaml": yamlContent}) } func TestLoadSourceRejectsNewerContract(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\ncontract_version: 99\n") _, err := loadSource(dir) if err == nil { @@ -30,28 +24,45 @@ func TestLoadSourceRejectsNewerContract(t *testing.T) { } } -func TestLoadSourceDefaultsAbsentContractTo1(t *testing.T) { +func TestLoadSourceDefaultsAbsentContractToCurrent(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\n") src, err := loadSource(dir) if err != nil { t.Fatalf("loadSource: %v", err) } - if src.config.ContractVersion != 1 { - t.Errorf("contract_version = %d, want default 1", src.config.ContractVersion) + if src.config.ContractVersion != specmeta.ContractVersion { + t.Errorf("contract_version = %d, want default %d", src.config.ContractVersion, specmeta.ContractVersion) } if src.contractDeclared { t.Error("contractDeclared = true, want false (field was absent)") } } +// A negative declaration used to pass the loader (it only rejected values +// above the core's version) while the update gate rejected it. Both sides now +// share one parser, so the loader must fail closed too. +func TestLoadSourceRejectsNegativeContractVersion(t *testing.T) { + t.Parallel() + dir := writeBridgeConfig(t, "name: b\ncontract_version: -1\n") + _, err := loadSource(dir) + if err == nil { + t.Fatal("expected an error for a bridge declaring a negative contract") + } + if !strings.Contains(err.Error(), "contract") { + t.Errorf("error = %q, want it to name the bad contract version", err) + } +} + func TestLoadSourceAcceptsMatchingContract(t *testing.T) { - dir := writeBridgeConfig(t, "name: b\ncontract_version: 1\n") + t.Parallel() + dir := writeBridgeConfig(t, "name: b\ncontract_version: 2\n") src, err := loadSource(dir) if err != nil { t.Fatalf("loadSource: %v", err) } - if src.config.ContractVersion != 1 { - t.Errorf("contract_version = %d, want 1", src.config.ContractVersion) + if src.config.ContractVersion != 2 { + t.Errorf("contract_version = %d, want 2", src.config.ContractVersion) } if !src.contractDeclared { t.Error("contractDeclared = false, want true (field was present)") @@ -59,6 +70,7 @@ func TestLoadSourceAcceptsMatchingContract(t *testing.T) { } func TestNewWarnsWhenContractAbsent(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\n") var buf bytes.Buffer log := logger.New() @@ -70,3 +82,54 @@ func TestNewWarnsWhenContractAbsent(t *testing.T) { t.Errorf("expected a deprecation warning for missing contract_version, got: %q", buf.String()) } } + +// An unknown `when:` used to hit shouldRenderContext's defensive default and +// render the template unconditionally. Loading must reject it outright. +func TestLoadSourceRejectsUnknownWhenCondition(t *testing.T) { + t.Parallel() + cases := []struct { + name string + when string + }{ + {name: "plain unknown", when: "hasEverything"}, + {name: "unknown prefix", when: "hasFeature:audit"}, + {name: "typo in addon prefix", when: "hasAddons:dapr"}, + {name: "trimmed unknown prefix", when: " hasFeature : audit"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + yamlContent := "name: b\ntemplates:\n - for: project\n source: t.tmpl\n target: out.txt\n when: \"" + c.when + "\"\n" + _, err := loadSource(writeBridgeConfig(t, yamlContent)) + if err == nil { + t.Fatalf("loadSource accepted unknown when condition %q", c.when) + } + if !strings.Contains(err.Error(), "when condition") || !strings.Contains(err.Error(), c.when) { + t.Errorf("error = %q, want it to name the bad condition %q", err.Error(), c.when) + } + }) + } +} + +// Positive control: every recognized condition (including both addon prefix +// forms and the empty condition) loads cleanly. +func TestLoadSourceAcceptsKnownWhenConditions(t *testing.T) { + t.Parallel() + conditions := []string{""} + for name, spec := range whenSpecs { + conditions = append(conditions, name) + if spec.colon { + conditions = append(conditions, name+":dapr") + } + } + slices.Sort(conditions) + for _, when := range conditions { + t.Run(when, func(t *testing.T) { + t.Parallel() + yamlContent := "name: b\ntemplates:\n - for: project\n source: t.tmpl\n target: out.txt\n when: \"" + when + "\"\n" + if _, err := loadSource(writeBridge(t, map[string]string{"bridge.yaml": yamlContent})); err != nil { + t.Fatalf("loadSource rejected known condition %q: %v", when, err) + } + }) + } +} diff --git a/internal/renderer/enum_array_test.go b/internal/renderer/enum_array_test.go new file mode 100644 index 0000000..a699422 --- /dev/null +++ b/internal/renderer/enum_array_test.go @@ -0,0 +1,164 @@ +package renderer + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/parser" +) + +// TestTSCoreRendersEnumArrayType guards the bridge-owned array syntax. The core +// deliberately has no language-specific fallback: an enum array only renders as +// `PaymentMethod[]` when ts-core declares `array_format` in type_mappings.yaml. +// Without it the generated field is an empty expression (` | null`), which the +// TypeScript TCK catches at tck/type-contract.ts:70. +func TestTSCoreRendersEnumArrayType(t *testing.T) { + t.Parallel() + + project := enumArrayProject(t) + bridgeDir := filepath.Join("..", "..", "bridges", "typescript", "core") + if _, err := os.Stat(filepath.Join(bridgeDir, "bridge.yaml")); err != nil { + t.Fatalf("bundled ts-core bridge missing at %s: %v", bridgeDir, err) + } + + got := renderTSCoreTypes(t, bridgeDir, project) + const want = "supportedPaymentMethods: PaymentMethod[] | null;" + if !strings.Contains(got, want) { + t.Errorf("ts-core output has no %q line:\n%s", want, excerptAround(got, "supportedPaymentMethods")) + } + + // Prove the assertion above is really driven by the bridge's array_format: + // the same render against a copy with that single line removed must produce + // the empty expression. This keeps the check self-contained — the repository + // is never mutated — and fails if the core ever reintroduces a fallback. + t.Run("without array format renders empty", func(t *testing.T) { + withoutFormat := copyTSCoreWithoutArrayFormat(t, bridgeDir) + got := renderTSCoreTypes(t, withoutFormat, project) + const broken = "supportedPaymentMethods: | null;" + if !strings.Contains(got, broken) { + t.Errorf("bridge without array_format should render %q, got:\n%s", broken, excerptAround(got, "supportedPaymentMethods")) + } + if strings.Contains(got, want) { + t.Errorf("bridge without array_format still rendered %q (core fallback returned?):\n%s", want, excerptAround(got, "supportedPaymentMethods")) + } + }) +} + +func enumArrayProject(t *testing.T) *ir.Project { + t.Helper() + domain := []byte(` +project: + name: EnumArrayRegression +database: postgresql +api_style: rest +enums: + PaymentMethod: + - CreditCard + - PayPal +entities: + Product: + fields: + id: uuid [primary] + supportedPaymentMethods: array(PaymentMethod) [optional] +`) + schema, err := parser.ParseYAML(domain) + if err != nil { + t.Fatalf("parse domain.yaml: %v", err) + } + project, err := ir.Build(schema) + if err != nil { + t.Fatalf("build IR: %v", err) + } + return project +} + +func renderTSCoreTypes(t *testing.T, bridgeDir string, project *ir.Project) string { + t.Helper() + r, err := New(bridgeDir, nil) + if err != nil { + t.Fatalf("New(%s): %v", bridgeDir, err) + } + outDir := t.TempDir() + if _, _, err := r.Render(project, outDir); err != nil { + t.Fatalf("Render(%s): %v", bridgeDir, err) + } + data, err := os.ReadFile(filepath.Join(outDir, "src", "generated", "types.ts")) + if err != nil { + t.Fatalf("read generated types.ts: %v", err) + } + return string(data) +} + +// copyTSCoreWithoutArrayFormat copies only the files the renderer loads +// (bridge.yaml, type_mappings.yaml, templates/) into a temp dir, then drops the +// array_format line from the copy. The tck/ tree with node_modules is skipped. +func copyTSCoreWithoutArrayFormat(t *testing.T, src string) string { + t.Helper() + dst := t.TempDir() + + copyFile := func(rel string) { + t.Helper() + data, err := os.ReadFile(filepath.Join(src, rel)) + if err != nil { + t.Fatalf("read bridge file %s: %v", rel, err) + } + target := filepath.Join(dst, rel) + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + t.Fatalf("mkdir for %s: %v", rel, err) + } + if err := os.WriteFile(target, data, 0o644); err != nil { + t.Fatalf("write bridge file %s: %v", rel, err) + } + } + + copyFile("bridge.yaml") + copyFile("type_mappings.yaml") + templates, err := os.ReadDir(filepath.Join(src, "templates")) + if err != nil { + t.Fatalf("read bridge templates: %v", err) + } + for _, entry := range templates { + if !entry.IsDir() { + copyFile(filepath.Join("templates", entry.Name())) + } + } + + path := filepath.Join(dst, "type_mappings.yaml") + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read copied type_mappings.yaml: %v", err) + } + lines := strings.Split(string(data), "\n") + kept := make([]string, 0, len(lines)) + for _, line := range lines { + if strings.HasPrefix(strings.TrimSpace(line), "array_format:") { + continue + } + kept = append(kept, line) + } + if len(kept) == len(lines) { + t.Fatal("bundled ts-core type_mappings.yaml has no array_format line to remove") + } + if err := os.WriteFile(path, []byte(strings.Join(kept, "\n")), 0o644); err != nil { + t.Fatalf("write type_mappings.yaml without array_format: %v", err) + } + return dst +} + +// excerptAround keeps a failure readable when the generated file is large. +func excerptAround(content, needle string) string { + lines := strings.Split(content, "\n") + var out []string + for _, line := range lines { + if strings.Contains(line, needle) { + out = append(out, line) + } + } + if len(out) == 0 { + return "(no line containing " + needle + ")" + } + return strings.Join(out, "\n") +} diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go new file mode 100644 index 0000000..f0c780f --- /dev/null +++ b/internal/renderer/hardening_test.go @@ -0,0 +1,690 @@ +package renderer + +import ( + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +// writeBridge lays out a bridge fixture. Keys are forward-slash relative paths; +// parent directories are created as needed. +func writeBridge(t *testing.T, files map[string]string) string { + t.Helper() + dir := t.TempDir() + for name, content := range files { + path := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir %s: %v", name, err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + return dir +} + +// R1: a symlink at the final target component must be rejected before the +// rename, and the file it points to must stay untouched. +func TestRenderRejectsSymlinkAtFinalComponent(t *testing.T) { + t.Parallel() + base := t.TempDir() + outside := filepath.Join(base, "outside.txt") + if err := os.WriteFile(outside, []byte("keep"), 0o644); err != nil { + t.Fatalf("write outside file: %v", err) + } + + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +templates: + - for: project + source: templates/p.tmpl + target: "leak.txt" +`, + "templates/p.tmpl": `generated`, + }) + out := filepath.Join(base, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + link := filepath.Join(out, "leak.txt") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render accepted a symlink at the final target component") + } + + data, err := os.ReadFile(outside) + if err != nil || string(data) != "keep" { + t.Errorf("outside file changed: data=%q err=%v", data, err) + } + info, err := os.Lstat(link) + if err != nil || info.Mode()&os.ModeSymlink == 0 { + t.Errorf("target link was replaced or removed: info=%v err=%v", info, err) + } +} + +// F15: the bridge-source symlink check must use an absolute bridge directory. +// With a relative bridge dir, a symlinked final source component used to be +// compared against a relative base and slipped through. +func TestRenderRejectsSymlinkWithRelativeBridgeDir(t *testing.T) { + t.Run("symlinked template source", func(t *testing.T) { + base := t.TempDir() + // CI on Windows puts the checkout (D:) and the system temp dir (C:) on + // different volumes; filepath.Rel cannot express a cross-volume path. + // Chdir into base so the bridge and cwd share a volume. This test does + // not call t.Parallel, and the testing package keeps parallel tests + // paused until sequential tests finish. + t.Chdir(base) + outside := filepath.Join(base, "outside.tmpl") + if err := os.WriteFile(outside, []byte("leaked"), 0o644); err != nil { + t.Fatalf("write outside template: %v", err) + } + manifest := func(source string) string { + return `name: demo +contract_version: 1 +templates: + - for: project + source: ` + source + ` + target: "out.txt" +` + } + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": manifest("templates/good.tmpl"), + "templates/good.tmpl": `good`, + }) + cwd, err := os.Getwd() + if err != nil { + t.Fatalf("getwd: %v", err) + } + relBridge, err := filepath.Rel(cwd, bridge) + if err != nil { + t.Fatalf("relative bridge dir: %v", err) + } + out := filepath.Join(base, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + // Positive control: a relative bridge dir alone must work. + r, err := New(relBridge, nil) + if err != nil { + t.Fatalf("New(%q) error = %v", relBridge, err) + } + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err != nil { + t.Fatalf("Render with relative bridge dir failed: %v", err) + } + if err := os.Remove(filepath.Join(out, "out.txt")); err != nil { + t.Fatalf("remove control output: %v", err) + } + + // Same relative dir, but the source's final component is a symlink out. + if err := os.WriteFile(filepath.Join(bridge, "bridge.yaml"), []byte(manifest("templates/p.tmpl")), 0o644); err != nil { + t.Fatalf("rewrite bridge.yaml: %v", err) + } + if err := os.Symlink(outside, filepath.Join(bridge, "templates", "p.tmpl")); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + r, err = New(relBridge, nil) + if err != nil { + t.Fatalf("New(%q) error = %v", relBridge, err) + } + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render accepted a symlinked template source in a relative bridge dir") + } + if _, err := os.Stat(filepath.Join(out, "out.txt")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("target was written despite rejected source: %v", err) + } + }) +} + +// R2: a template that parses but fails during Execute must not truncate the +// previous contents of the target, and must leave no temp file behind. +func TestRenderExecuteErrorPreservesPreviousOutput(t *testing.T) { + t.Parallel() + tmp := t.TempDir() + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +templates: + - for: project + source: templates/p.tmpl + target: "value.txt" +`, + // Parse succeeds; index out of range fails only at execution time. + "templates/p.tmpl": `{{ index .Project.Entities 99 }}`, + }) + out := filepath.Join(tmp, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + target := filepath.Join(out, "value.txt") + if err := os.WriteFile(target, []byte("valid"), 0o644); err != nil { + t.Fatalf("write prior output: %v", err) + } + + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render succeeded despite an execute error") + } + + data, err := os.ReadFile(target) + if err != nil || string(data) != "valid" { + t.Errorf("prior output destroyed: data=%q err=%v", data, err) + } + assertNoRenderTemps(t, out) +} + +// R3: an error in a later template must not leave earlier files written. The +// second template fails to parse, so no file may reach outputDir at all. +func TestRenderFailureRollsBackPriorWrites(t *testing.T) { + t.Parallel() + tests := []struct { + name string + prior string // contents of a.txt before the run; empty = absent + wantContent string // expected contents after failure; empty = absent + }{ + {name: "new file removed on later error", prior: "", wantContent: ""}, + {name: "existing file restored on later error", prior: "original", wantContent: "original"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + tmp := t.TempDir() + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +templates: + - for: project + source: templates/good.tmpl + target: "a.txt" + - for: project + source: templates/bad.tmpl + target: "b.txt" +`, + "templates/good.tmpl": `new-content`, + "templates/bad.tmpl": `{{ if }}`, // parse error + }) + out := filepath.Join(tmp, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + a := filepath.Join(out, "a.txt") + if tt.prior != "" { + if err := os.WriteFile(a, []byte(tt.prior), 0o644); err != nil { + t.Fatalf("write prior a.txt: %v", err) + } + } + + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render succeeded despite a parse error in the second template") + } + + data, statErr := os.ReadFile(a) + if tt.wantContent == "" { + if !errors.Is(statErr, os.ErrNotExist) { + t.Errorf("a.txt should be absent after rollback: data=%q err=%v", data, statErr) + } + } else if statErr != nil || string(data) != tt.wantContent { + t.Errorf("a.txt = %q (err=%v), want %q", data, statErr, tt.wantContent) + } + if _, err := os.Stat(filepath.Join(out, "b.txt")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("b.txt should not exist after failed render: %v", err) + } + assertNoRenderTemps(t, out) + }) + } +} + +// F24: a target that existed at staging but was deleted before commit must be +// rolled back as a new file (removed). Commit leaves no backup in that case, +// so rollback removes the file instead of restoring a nonexistent original. +func TestRenderRollbackRemovesTargetDeletedBeforeCommit(t *testing.T) { + base := t.TempDir() + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +contract_version: 1 +templates: + - for: project + source: templates/good.tmpl + target: "a.txt" + - for: project + source: templates/block.tmpl + target: "b.txt" +`, + "templates/good.tmpl": `new-content`, + "templates/block.tmpl": `never-committed`, + }) + out := filepath.Join(base, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + a := filepath.Join(out, "a.txt") + if err := os.WriteFile(a, []byte("original"), 0o644); err != nil { + t.Fatalf("write prior a.txt: %v", err) + } + // Symlinks are rejected by the Phase 2 check, but only ones that appear + // after staging reach that check: Phase 1 rejects them too. + outside := filepath.Join(base, "outside.txt") + if err := os.WriteFile(outside, []byte("keep"), 0o644); err != nil { + t.Fatalf("write outside file: %v", err) + } + probe := filepath.Join(base, "probe.link") + if err := os.Symlink(outside, probe); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + _ = os.Remove(probe) + + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + r.setBeforeCommitHook(func() { + if err := os.Remove(a); err != nil && !errors.Is(err, os.ErrNotExist) { + t.Errorf("remove staged target: %v", err) + } + if err := os.Symlink(outside, filepath.Join(out, "b.txt")); err != nil { + t.Errorf("plant symlink before commit: %v", err) + } + }) + t.Cleanup(func() { r.setBeforeCommitHook(nil) }) + + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render succeeded despite a blocked commit") + } + if _, err := os.Stat(a); !errors.Is(err, os.ErrNotExist) { + data, readErr := os.ReadFile(a) + t.Errorf("a.txt survived rollback: statErr=%v data=%q readErr=%v", err, data, readErr) + } + assertNoRenderTemps(t, out) +} + +// A directory swapped for a symlink after staging must not redirect the commit. +// A plain os.Lstat at commit time sees only the leaf and would miss this; the +// whole write path now goes through os.Root, which refuses to follow the link. +func TestRenderRejectsParentSymlinkPlantedBeforeCommit(t *testing.T) { + base := t.TempDir() + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +contract_version: 1 +templates: + - for: project + source: templates/good.tmpl + target: "src/App.cs" +`, + "templates/good.tmpl": `generated`, + }) + out := filepath.Join(base, "out") + src := filepath.Join(out, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatalf("mkdir src: %v", err) + } + outside := filepath.Join(base, "outside") + if err := os.MkdirAll(outside, 0o755); err != nil { + t.Fatalf("mkdir outside: %v", err) + } + probe := filepath.Join(base, "probe.link") + if err := os.Symlink(outside, probe); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + _ = os.Remove(probe) + + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + r.setBeforeCommitHook(func() { + if err := os.RemoveAll(src); err != nil { + t.Errorf("remove staged src: %v", err) + } + if err := os.Symlink(outside, src); err != nil { + t.Errorf("plant parent symlink: %v", err) + } + }) + t.Cleanup(func() { r.setBeforeCommitHook(nil) }) + + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { + t.Fatal("Render succeeded after parent directory was replaced by a symlink") + } + if _, err := os.Stat(filepath.Join(outside, "App.cs")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("rendered file escaped outputDir through a parent symlink") + } + assertNoRenderTemps(t, out) +} + +func assertNoRenderTemps(t *testing.T, dir string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read output dir: %v", err) + } + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".domaincraft-render-") { + t.Errorf("leftover render temp file: %s", e.Name()) + } + } +} + +// F17: a failed restore used to be discarded silently while the comment claimed +// no half-written output. Make the restore target's directory unwritable and +// require the failure to surface. +func TestRollbackWritesReportsRestoreFailure(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "a.txt") + backup := filepath.Join(dir, "a.txt.bak") + if err := os.WriteFile(target, []byte("new"), 0o644); err != nil { + t.Fatalf("write target: %v", err) + } + if err := os.WriteFile(backup, []byte("original"), 0o644); err != nil { + t.Fatalf("write backup: %v", err) + } + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatalf("chmod dir: %v", err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + // Some platforms (or a root test process) ignore directory write bits. + probe := filepath.Join(dir, ".probe") + if err := os.WriteFile(probe, []byte("x"), 0o644); err == nil { + _ = os.Remove(probe) + t.Skip("directory permissions are not enforced on this host") + } + + err := rollbackWrites(nil, []stagedWrite{{target: target, backup: backup}}) + if err == nil { + t.Fatal("rollbackWrites silently discarded a failed restore") + } + if !strings.Contains(err.Error(), "restore") { + t.Errorf("error = %q, want it to name the failed restore", err.Error()) + } +} + +// The primary rendering error stays first and both errors remain inspectable +// via errors.Is. +func TestRollbackErrorKeepsOriginalPrimary(t *testing.T) { + t.Parallel() + primary := errors.New("commit failed") + rollback := errors.New("restore failed") + got := rollbackError(primary, rollback) + if !errors.Is(got, primary) || !errors.Is(got, rollback) { + t.Fatalf("errors.Join lost a cause: %v", got) + } + if !strings.HasPrefix(got.Error(), primary.Error()) { + t.Errorf("primary error is not first: %q", got.Error()) + } + if !errors.Is(rollbackError(primary, nil), primary) { + t.Error("no-op rollback must return the original error unchanged") + } +} + +func TestCustomTemplateStagedOncePerRun(t *testing.T) { + t.Parallel() + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +templates: + - for: entity + source: templates/custom.tmpl + target: "custom.txt" + overwrite: false +`, + "templates/custom.tmpl": `entity-{{ .Entity.Name }}`, + }) + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + project := &ir.Project{Name: "P", Entities: []ir.Entity{ + {Name: "Alpha"}, + {Name: "Beta"}, + }} + out := filepath.Join(t.TempDir(), "out") + _, manifest, err := r.Render(project, out) + if err != nil { + t.Fatalf("Render() error = %v", err) + } + if len(manifest) != 2 { + t.Fatalf("manifest has %d entries, want 2: %v", len(manifest), manifest) + } + if !manifest[0].Written || manifest[1].Written { + t.Fatalf("scaffold-once manifest = %v, want first written and second skipped", manifest) + } + data, err := os.ReadFile(filepath.Join(out, "custom.txt")) + if err != nil { + t.Fatal(err) + } + if string(data) != "entity-Alpha" { + t.Fatalf("custom file = %q, want entity-Alpha", data) + } +} + +// TestRenderPhasesPreserveManifestAndRollback pins the contract spanning all +// three phases: staging records manifest entries in template/context/target +// order (including skipped scaffolds), and a failure during commit rolls back +// partial writes while returning neither paths nor a manifest. +func TestRenderPhasesPreserveManifestAndRollback(t *testing.T) { + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +templates: + - for: entity + source: templates/entity.tmpl + target: "{{ .Entity.Name }}.txt" + - for: project + source: templates/shared.tmpl + target: "shared.txt" + - for: project + source: templates/custom.tmpl + target: "custom.txt" + overwrite: false +`, + "templates/entity.tmpl": `entity-{{ .Entity.Name }}`, + "templates/shared.tmpl": `shared`, + "templates/custom.tmpl": `custom`, + }) + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + project := &ir.Project{Name: "P", Entities: []ir.Entity{ + {Name: "Alpha", NamePlural: "Alphas"}, + {Name: "Beta", NamePlural: "Betas"}, + }} + + out := filepath.Join(t.TempDir(), "out") + wantManifest := []RenderedFile{ + {Path: "Alpha.txt", Entity: "Alpha", Written: true}, + {Path: "Beta.txt", Entity: "Beta", Written: true}, + {Path: "shared.txt", Written: true}, + {Path: "custom.txt", Custom: true, Written: true}, + } + wantWritten := []string{ + filepath.Join(out, "Alpha.txt"), + filepath.Join(out, "Beta.txt"), + filepath.Join(out, "shared.txt"), + filepath.Join(out, "custom.txt"), + } + + written, manifest, err := r.Render(project, out) + if err != nil { + t.Fatalf("Render() 1 error = %v", err) + } + if !reflect.DeepEqual(manifest, wantManifest) { + t.Errorf("manifest = %+v, want %+v", manifest, wantManifest) + } + if !reflect.DeepEqual(written, wantWritten) { + t.Errorf("written = %q, want %q", written, wantWritten) + } + + // A skipped scaffold keeps its slot in the manifest with Written=false. + written, manifest, err = r.Render(project, out) + if err != nil { + t.Fatalf("Render() 2 error = %v", err) + } + wantManifest[3].Written = false + wantWritten = wantWritten[:3] + if !reflect.DeepEqual(manifest, wantManifest) { + t.Errorf("manifest on second run = %+v, want %+v", manifest, wantManifest) + } + if !reflect.DeepEqual(written, wantWritten) { + t.Errorf("written on second run = %q, want %q", written, wantWritten) + } + data, err := os.ReadFile(filepath.Join(out, "custom.txt")) + if err != nil || string(data) != "custom" { + t.Errorf("developer-owned file changed: data=%q err=%v", data, err) + } + + // A symlink planted after staging blocks a later commit. The earlier files + // must be rolled back and the failure must carry no paths or manifest. + t.Run("commit failure rolls back partial writes", func(t *testing.T) { + base := t.TempDir() + outside := filepath.Join(base, "outside.txt") + if err := os.WriteFile(outside, []byte("keep"), 0o644); err != nil { + t.Fatalf("write outside file: %v", err) + } + probe := filepath.Join(base, "probe.link") + if err := os.Symlink(outside, probe); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + _ = os.Remove(probe) + + out2 := filepath.Join(base, "out") + if err := os.MkdirAll(out2, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + alpha := filepath.Join(out2, "Alpha.txt") + if err := os.WriteFile(alpha, []byte("original"), 0o644); err != nil { + t.Fatalf("write prior Alpha.txt: %v", err) + } + + r.setBeforeCommitHook(func() { + if err := os.Symlink(outside, filepath.Join(out2, "shared.txt")); err != nil { + t.Errorf("plant symlink before commit: %v", err) + } + }) + t.Cleanup(func() { r.setBeforeCommitHook(nil) }) + + written, manifest, err := r.Render(project, out2) + if err == nil { + t.Fatal("Render succeeded despite a symlink planted before commit") + } + if !strings.Contains(err.Error(), "shared.txt") || !strings.Contains(err.Error(), "symlink") { + t.Errorf("error = %q, want it to name the blocked target and symlink", err) + } + if written != nil || manifest != nil { + t.Errorf("failed render returned paths=%q manifest=%+v, want both nil", written, manifest) + } + + data, err := os.ReadFile(alpha) + if err != nil || string(data) != "original" { + t.Errorf("backed-up target not restored: data=%q err=%v", data, err) + } + if _, err := os.Stat(filepath.Join(out2, "Beta.txt")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("newly committed file survived rollback: %v", err) + } + outsideData, err := os.ReadFile(outside) + if err != nil || string(outsideData) != "keep" { + t.Errorf("outside file changed: data=%q err=%v", outsideData, err) + } + entries, err := os.ReadDir(out2) + if err != nil { + t.Fatalf("read output dir: %v", err) + } + for _, e := range entries { + name := e.Name() + if strings.HasPrefix(name, ".domaincraft-render-") || strings.HasSuffix(name, ".bak") { + t.Errorf("leftover phase artifact: %s", name) + } + } + }) +} + +// TestRenderCommitPreservesCustomFileCreatedBeforeCommit closes the staging→ +// commit race for overwrite:false targets. Staging skipped a custom file that +// already existed, but commit backed up and replaced whatever was there and +// cleanupBackups then deleted the backup, silently losing developer-owned +// bytes. Earlier committed writes must still roll back when the race is hit. +func TestRenderCommitPreservesCustomFileCreatedBeforeCommit(t *testing.T) { + bridge := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +contract_version: 1 +templates: + - for: project + source: templates/existing.tmpl + target: "existing.txt" + - for: project + source: templates/fresh.tmpl + target: "fresh.txt" + - for: project + source: templates/custom.tmpl + target: "custom.txt" + overwrite: false +`, + "templates/existing.tmpl": `generated-existing`, + "templates/fresh.tmpl": `generated-fresh`, + "templates/custom.tmpl": `generated-custom`, + }) + r, err := New(bridge, nil) + if err != nil { + t.Fatalf("New() error = %v", err) + } + out := filepath.Join(t.TempDir(), "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatalf("mkdir output: %v", err) + } + existing := filepath.Join(out, "existing.txt") + if err := os.WriteFile(existing, []byte("original"), 0o644); err != nil { + t.Fatalf("write prior output: %v", err) + } + custom := filepath.Join(out, "custom.txt") + r.setBeforeCommitHook(func() { + if err := os.WriteFile(custom, []byte("developer-owned"), 0o644); err != nil { + t.Errorf("create custom file before commit: %v", err) + } + }) + t.Cleanup(func() { r.setBeforeCommitHook(nil) }) + + written, manifest, err := r.Render(&ir.Project{Name: "P"}, out) + if err == nil { + t.Fatal("Render succeeded after a custom file appeared before commit") + } + if written != nil || manifest != nil { + t.Errorf("failed render returned paths=%q manifest=%+v, want both nil", written, manifest) + } + if !strings.Contains(err.Error(), "custom.txt") || !strings.Contains(err.Error(), "preserved") { + t.Errorf("error = %q, want it to name the preserved custom file", err) + } + + data, err := os.ReadFile(custom) + if err != nil || string(data) != "developer-owned" { + t.Errorf("custom file was replaced: data=%q err=%v", data, err) + } + data, err = os.ReadFile(existing) + if err != nil || string(data) != "original" { + t.Errorf("earlier committed write not rolled back: data=%q err=%v", data, err) + } + if _, err := os.Stat(filepath.Join(out, "fresh.txt")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("newly committed file survived rollback: %v", err) + } + entries, err := os.ReadDir(out) + if err != nil { + t.Fatalf("read output dir: %v", err) + } + for _, e := range entries { + name := e.Name() + if strings.HasPrefix(name, ".domaincraft-render-") || strings.HasSuffix(name, ".bak") { + t.Errorf("leftover phase artifact: %s", name) + } + } +} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index d212a0c..191d844 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -3,22 +3,19 @@ package renderer import ( "fmt" "os" - "path/filepath" "regexp" + "slices" + "strings" + "sync" "text/template" + "github.com/DomainCraft/DomainCraft/internal/bridge" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/pkg/logger" "gopkg.in/yaml.v3" ) -// ContractVersion is the version of the bridge contract the core implements. A -// bridge may declare the contract it was authored against via `contract_version` -// in bridge.yaml. The core rejects bridges written against a newer contract and -// treats an absent declaration as contract 1 (with a deprecation notice). -const ContractVersion = 1 - // sourceConfig is one bridge directory plus its parsed bridge.yaml. A composed // renderer holds several of these, ordered base-first, with the adapter last. type sourceConfig struct { @@ -44,8 +41,17 @@ type Renderer struct { seedData *ir.SeedDataset // mockData is the deterministic mock seed (set via SetMockData). mockData *ir.SeedDataset + // beforeCommitHook is a test-only seam called between staging and commit. + // It lives on the instance, not in package state, so concurrent renders are + // isolated and no save/restore is needed in tests. + beforeCommitHook func() } +// setBeforeCommitHook installs a hook called once between staging and commit. +// Production code never calls it; tests in this package use it to mutate the +// filesystem at the exact point where the commit's path checks must hold. +func (r *Renderer) setBeforeCommitHook(fn func()) { r.beforeCommitHook = fn } + // config returns the topmost (adapter) bridge config, which owns the effective // output_dir, name, delimiters and migration commands. func (r *Renderer) config() BridgeConfig { @@ -65,14 +71,156 @@ func (r *Renderer) adapterDir() string { var layerRe = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) +// The closed vocabulary of `when:` conditions. The evaluator in +// shouldRenderContext must use these same names: an unknown condition used to +// fall through its defensive default and render unconditionally. +const ( + whenSeed = "hasSeed" + whenEnums = "hasEnums" + whenOwnerTokens = "hasOwnerTokens" + whenAuth = "hasAuth" + whenMigration = "hasMigration" + whenMockData = "hasMockData" + whenAddon = "hasAddon" + whenNotAddon = "notHasAddon" +) + +// whenSpec is one entry of the closed `when:` vocabulary. Validation and +// evaluation both read this table, so a condition can never be accepted by one +// and rejected (or silently rendered) by the other. +type whenSpec struct { + eval func(RenderContext, string) bool + colon bool // accepts a name after ':' (addon conditions) +} + +var whenSpecs = map[string]whenSpec{ + whenSeed: {eval: func(c RenderContext, _ string) bool { return c.HasSeedData() }}, + whenEnums: {eval: func(c RenderContext, _ string) bool { return c.Project != nil && len(c.Project.Enums) > 0 }}, + whenOwnerTokens: {eval: func(c RenderContext, _ string) bool { + if c.Project == nil { + return false + } + for _, e := range c.Project.Entities { + if e.Permissions != nil && e.Permissions.HasOwnerToken() { + return true + } + } + return false + }}, + whenAuth: {eval: func(c RenderContext, _ string) bool { return c.Project != nil && c.Project.HasAuth() }}, + whenMigration: {eval: func(c RenderContext, _ string) bool { return c.HasMigration() }}, + whenMockData: {eval: func(c RenderContext, _ string) bool { return c.HasMockData() }}, + whenAddon: {colon: true, eval: func(c RenderContext, name string) bool { + if c.Project == nil { + return false + } + if name == "" { + return len(c.Project.Addons) > 0 + } + return c.Project.HasAddon(strings.TrimSpace(name)) + }}, + whenNotAddon: {colon: true, eval: func(c RenderContext, name string) bool { + if c.Project == nil { + return true + } + if name == "" { + return len(c.Project.Addons) == 0 + } + return !c.Project.HasAddon(strings.TrimSpace(name)) + }}, +} + +// allowedWhenConditions builds the diagnostic from the same table that drives +// validation and evaluation. +func allowedWhenConditions() string { + names := make([]string, 0, len(whenSpecs)) + for name, spec := range whenSpecs { + if spec.colon { + names = append(names, name+":") + } else { + names = append(names, name) + } + } + slices.Sort(names) + return strings.Join(names, ", ") +} + +// validateWhenConditions rejects any condition outside the closed vocabulary, +// including unknown colon-prefixed forms such as "hasFeature:audit". Bare +// addon names stay valid: the evaluator treats them as "any addon". +func validateWhenConditions(bridgeName string, templates []TemplateSpec) error { + for i, spec := range templates { + when := spec.When + if when == "" { + continue + } + prefix, name, hasColon := strings.Cut(when, ":") + entry, ok := whenSpecs[strings.TrimSpace(prefix)] + if !ok || (hasColon && !entry.colon) || (!hasColon && strings.TrimSpace(when) != prefix) { + return fmt.Errorf("bridge %q template %d: unknown when condition %q (allowed: %s)", bridgeName, i, when, allowedWhenConditions()) + } + _ = name + } + return nil +} + +// maxParsedSourceCacheEntries bounds the parse cache. In a one-shot CLI it +// lives for one run, but a long-lived host edits bridge.yaml repeatedly and +// would otherwise accumulate one key per edit. +const maxParsedSourceCacheEntries = 64 + +// parsedSourceCache shares one parsed bridge.yaml between the resolution walk +// (bridgechain asks for Extends) and the render setup (New + AttachBases asks +// for the same configs again). The key includes the file bytes: a bridge +// updated mid-command — by --update-bridges or a manual edit — gets a new key +// and is parsed again, so a cached config can never go stale. +// +// A plain map under an RWMutex makes the cap check + clear + store one atomic +// operation; concurrent loads take the read lock. +var parsedSourceCache = struct { + sync.RWMutex + entries map[string]sourceConfig +}{entries: make(map[string]sourceConfig)} + +// loadParsedSource looks up one cached config by its content-derived key. +func loadParsedSource(key string) (sourceConfig, bool) { + parsedSourceCache.RLock() + src, ok := parsedSourceCache.entries[key] + parsedSourceCache.RUnlock() + return src, ok +} + +// storeParsedSource inserts into the parse cache, clearing it once the cap is +// reached. Clearing is safe: the key includes the bridge path and the full +// config bytes, so an entry is only ever reused for an identical manifest. No +// correctness depends on older entries — evicting them just makes the next +// identical load re-parse once. +func storeParsedSource(key string, src sourceConfig) { + parsedSourceCache.Lock() + defer parsedSourceCache.Unlock() + + if len(parsedSourceCache.entries) >= maxParsedSourceCacheEntries { + parsedSourceCache.entries = make(map[string]sourceConfig, maxParsedSourceCacheEntries) + } + parsedSourceCache.entries[key] = src +} + // loadSource loads a single bridge directory (its bridge.yaml). func loadSource(bridgePath string) (sourceConfig, error) { - bridgeDir, configPath := resolveBridgePath(bridgePath) - data, err := os.ReadFile(configPath) + bridgeDir, configPath, err := bridge.LocalBridgePaths(bridgePath) + if err != nil { + return sourceConfig{}, err + } + data, err := os.ReadFile(configPath) //nolint:gosec // resolved from validated bridge refs by bridge.LocalBridgePaths if err != nil { return sourceConfig{}, fmt.Errorf("read bridge config: %w", err) } + key := bridgeDir + "\x00" + configPath + "\x00" + string(data) + if src, ok := loadParsedSource(key); ok { + return src, nil + } + var config BridgeConfig if err := yaml.Unmarshal(data, &config); err != nil { return sourceConfig{}, fmt.Errorf("parse bridge config: %w", err) @@ -80,21 +228,27 @@ func loadSource(bridgePath string) (sourceConfig, error) { if config.Layer != "" && !layerRe.MatchString(config.Layer) { return sourceConfig{}, fmt.Errorf("invalid layer %q: must match %s", config.Layer, layerRe.String()) } + if err := validateWhenConditions(config.Name, config.Templates); err != nil { + return sourceConfig{}, err + } if config.OutputDir == "" { config.OutputDir = "generated" } - // Contract version: absent (0) means contract 1, with a deprecation notice - // (emitted by the caller); a newer contract is a hard error. - contractDeclared := config.ContractVersion != 0 - if config.ContractVersion == 0 { - config.ContractVersion = 1 + // Contract version: use the same parser/gate as the bridge update path so + // a manifest cannot be accepted on one side and rejected on the other. + // An absent declaration defaults to the core's version (with a deprecation + // notice from the caller); a negative or newer declaration is a hard error. + contractVersion, contractDeclared, err := bridge.ParseContractVersion(data) + if err != nil { + return sourceConfig{}, err } - if config.ContractVersion > ContractVersion { - return sourceConfig{}, fmt.Errorf( - "bridge %q requires contract v%d, but this DomainCraft core implements contract v%d", - config.Name, config.ContractVersion, ContractVersion) + if err := bridge.CheckContractVersion(contractVersion); err != nil { + return sourceConfig{}, fmt.Errorf("bridge %q: %w", config.Name, err) } - return sourceConfig{dir: bridgeDir, config: config, contractDeclared: contractDeclared}, nil + config.ContractVersion = contractVersion + src := sourceConfig{dir: bridgeDir, config: config, contractDeclared: contractDeclared} + storeParsedSource(key, src) + return src, nil } // New loads a single (leaf) bridge. @@ -104,7 +258,7 @@ func New(bridgePath string, log *logger.Logger) (*Renderer, error) { return nil, err } if !src.contractDeclared && log != nil { - log.Warn("bridge %q does not declare `contract_version`; assuming contract v1 (deprecated — please add it)", src.config.Name) + log.Warn("bridge %q does not declare `contract_version`; assuming contract v%d (deprecated — please add it)", src.config.Name, src.config.ContractVersion) } return &Renderer{sources: []sourceConfig{src}, log: log}, nil } @@ -137,8 +291,8 @@ func (r *Renderer) AttachBases(basePaths []string) error { // so a persistence bridge's migrations are found even when the top adapter // has no migrations (e.g. csharp-rest → csharp-efcore). func (r *Renderer) MigrationConfig() *MigrationConfig { - for i := len(r.sources) - 1; i >= 0; i-- { - cfg := r.sources[i].config.Migrations + for _, src := range slices.Backward(r.sources) { + cfg := src.config.Migrations if cfg != nil && cfg.Enabled { return cfg } @@ -181,15 +335,3 @@ func (r *Renderer) applyDelimiters(t *template.Template) *template.Template { } return t } - -func resolveBridgePath(bridgePath string) (string, string) { - info, err := os.Stat(bridgePath) - if err != nil { - // Path does not exist or is not accessible — treat as file path. - return filepath.Dir(bridgePath), bridgePath - } - if info.IsDir() { - return bridgePath, filepath.Join(bridgePath, "bridge.yaml") - } - return filepath.Dir(bridgePath), bridgePath -} diff --git a/internal/renderer/load_test.go b/internal/renderer/load_test.go new file mode 100644 index 0000000..ddc5f78 --- /dev/null +++ b/internal/renderer/load_test.go @@ -0,0 +1,270 @@ +package renderer + +import ( + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + +// TestResolveBridgePath covers the four local-path shapes through the shared +// bridge.LocalBridgePaths normalization. The renderer used to accept a missing +// path as a config file and failed only on read; it must now fail at resolution. +func TestResolveBridgePath(t *testing.T) { + t.Parallel() + root := t.TempDir() + + withConfig := filepath.Join(root, "with-config") + if err := os.MkdirAll(withConfig, 0o755); err != nil { + t.Fatal(err) + } + configFile := filepath.Join(withConfig, "bridge.yaml") + if err := os.WriteFile(configFile, []byte("name: test\n"), 0o644); err != nil { + t.Fatal(err) + } + withoutConfig := filepath.Join(root, "without-config") + if err := os.MkdirAll(withoutConfig, 0o755); err != nil { + t.Fatal(err) + } + missing := filepath.Join(root, "missing") + + cases := []struct { + name string + input string + wantDir string + wantConfig string + wantErrPart string + }{ + {name: "existing directory with bridge.yaml", input: withConfig, wantDir: withConfig, wantConfig: configFile}, + {name: "existing directory without bridge.yaml", input: withoutConfig, wantErrPart: "does not contain bridge.yaml"}, + {name: "file path", input: configFile, wantDir: withConfig, wantConfig: configFile}, + {name: "missing path", input: missing, wantErrPart: "bridge path"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + dir, config, err := bridge.LocalBridgePaths(tc.input) + if tc.wantErrPart != "" { + if err == nil { + t.Fatalf("bridge.LocalBridgePaths(%q) = (%q, %q), want error containing %q", tc.input, dir, config, tc.wantErrPart) + } + if !strings.Contains(err.Error(), tc.wantErrPart) { + t.Fatalf("error = %q, want it to contain %q", err, tc.wantErrPart) + } + return + } + if err != nil { + t.Fatalf("bridge.LocalBridgePaths(%q): %v", tc.input, err) + } + if dir != tc.wantDir || config != tc.wantConfig { + t.Errorf("bridge.LocalBridgePaths(%q) = (%q, %q), want (%q, %q)", tc.input, dir, config, tc.wantDir, tc.wantConfig) + } + }) + } +} + +// TestLoadSourceCacheFollowsContentChanges pins the shared parse cache: a +// second load of an unchanged manifest reuses the parsed config, while a bridge +// refreshed mid-command (--update-bridges or a manual edit) is parsed anew. +func TestLoadSourceCacheFollowsContentChanges(t *testing.T) { + dir := t.TempDir() + configPath := filepath.Join(dir, "bridge.yaml") + writeManifest := func(name string) { + t.Helper() + if err := os.WriteFile(configPath, []byte("name: "+name+"\ncontract_version: 1\n"), 0o644); err != nil { + t.Fatal(err) + } + } + + writeManifest("first") + for i := range 2 { + src, err := loadSource(dir) + if err != nil { + t.Fatal(err) + } + if src.config.Name != "first" { + t.Fatalf("load %d: name = %q, want first", i, src.config.Name) + } + } + + writeManifest("second") + src, err := loadSource(dir) + if err != nil { + t.Fatal(err) + } + if src.config.Name != "second" { + t.Fatalf("name = %q, want second after the file changed", src.config.Name) + } +} + +func TestLoadSourceFailsClosedOnMissingBridgeYaml(t *testing.T) { + t.Parallel() + dir := t.TempDir() + if _, err := loadSource(dir); err == nil || !strings.Contains(err.Error(), "does not contain bridge.yaml") { + t.Fatalf("loadSource on a directory without bridge.yaml = %v, want a hard error naming bridge.yaml", err) + } +} + +// TestParsedSourceCacheEvictsOldEntries pins the bound on the shared parse +// cache: more inserts than the cap leave at most cap entries. The cache is +// package-global, so this test must not run in parallel with other loadSource +// users. +func TestParsedSourceCacheEvictsOldEntries(t *testing.T) { + clearCache := func() { + parsedSourceCache.Lock() + parsedSourceCache.entries = make(map[string]sourceConfig) + parsedSourceCache.Unlock() + } + t.Cleanup(clearCache) + clearCache() + + inserts := maxParsedSourceCacheEntries + 10 + for i := range inserts { + storeParsedSource("evict-probe-"+strconv.Itoa(i), sourceConfig{}) + } + + parsedSourceCache.RLock() + n := len(parsedSourceCache.entries) + parsedSourceCache.RUnlock() + if n > maxParsedSourceCacheEntries { + t.Fatalf("cache has %d entries after %d inserts, want at most %d", + n, inserts, maxParsedSourceCacheEntries) + } +} + +// MigrationConfig scans the composed chain from the adapter downwards and +// returns the first *enabled* config. The adapter wins when both layers enable +// migrations; a disabled adapter defers to an enabled persistence base. +func TestMigrationConfigFirstEnabledWins(t *testing.T) { + t.Parallel() + baseEnabled := writeBridgeConfig(t, `name: base +migrations: + enabled: true + commands: + - "base command" +`) + baseDisabled := writeBridgeConfig(t, `name: base +migrations: + enabled: false + commands: + - "base command" +`) + adapterEnabled := writeBridgeConfig(t, `name: adapter +migrations: + enabled: true + commands: + - "adapter command" +`) + adapterDisabled := writeBridgeConfig(t, `name: adapter +migrations: + enabled: false + commands: + - "adapter command" +`) + + cases := []struct { + name string + base string + adapter string + wantSource int // index in r.sources: 0 = base, 1 = adapter + wantCommands []string + }{ + {name: "both enabled: adapter wins", base: baseEnabled, adapter: adapterEnabled, wantSource: 1, wantCommands: []string{"adapter command"}}, + {name: "adapter disabled: enabled base wins", base: baseEnabled, adapter: adapterDisabled, wantSource: 0, wantCommands: []string{"base command"}}, + {name: "base disabled: enabled adapter wins", base: baseDisabled, adapter: adapterEnabled, wantSource: 1, wantCommands: []string{"adapter command"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + r, err := New(tc.adapter, nil) + if err != nil { + t.Fatalf("New(adapter): %v", err) + } + if err := r.AttachBases([]string{tc.base}); err != nil { + t.Fatalf("AttachBases: %v", err) + } + got := r.MigrationConfig() + if got == nil { + t.Fatal("MigrationConfig() = nil, want an enabled config") + } + if !got.Enabled { + t.Error("MigrationConfig() returned a disabled config") + } + if got != r.sources[tc.wantSource].config.Migrations { + t.Errorf("MigrationConfig() did not come from source %d", tc.wantSource) + } + if !slices.Equal(got.Commands, tc.wantCommands) { + t.Errorf("commands = %v, want %v", got.Commands, tc.wantCommands) + } + }) + } +} + +func TestMigrationConfigAbsentReturnsNil(t *testing.T) { + t.Parallel() + t.Run("no bridge declares migrations", func(t *testing.T) { + t.Parallel() + base := writeBridgeConfig(t, "name: base\n") + adapter := writeBridgeConfig(t, "name: adapter\n") + r, err := New(adapter, nil) + if err != nil { + t.Fatalf("New(adapter): %v", err) + } + if err := r.AttachBases([]string{base}); err != nil { + t.Fatalf("AttachBases: %v", err) + } + if got := r.MigrationConfig(); got != nil { + t.Errorf("MigrationConfig() = %+v, want nil", got) + } + }) + t.Run("all declared configs disabled", func(t *testing.T) { + t.Parallel() + base := writeBridgeConfig(t, "name: base\nmigrations:\n enabled: false\n commands:\n - \"never\"\n") + adapter := writeBridgeConfig(t, "name: adapter\nmigrations:\n enabled: false\n commands:\n - \"never\"\n") + r, err := New(adapter, nil) + if err != nil { + t.Fatalf("New(adapter): %v", err) + } + if err := r.AttachBases([]string{base}); err != nil { + t.Fatalf("AttachBases: %v", err) + } + if got := r.MigrationConfig(); got != nil { + t.Errorf("MigrationConfig() = %+v, want nil when no config is enabled", got) + } + }) +} + +func TestMigrationConfigMergesCommandsInDeclaredOrder(t *testing.T) { + t.Parallel() + want := []string{ + "dotnet ef migrations add Sync", + "dotnet ef database update", + "echo done", + } + dir := writeBridgeConfig(t, `name: persistence +migrations: + enabled: true + commands: + - "dotnet ef migrations add Sync" + - "dotnet ef database update" + - "echo done" +`) + r, err := New(dir, nil) + if err != nil { + t.Fatalf("New: %v", err) + } + got := r.MigrationConfig() + if got == nil { + t.Fatal("MigrationConfig() = nil, want an enabled config") + } + if !got.Enabled { + t.Error("MigrationConfig().Enabled = false, want true") + } + if !slices.Equal(got.Commands, want) { + t.Errorf("commands = %v, want declared order %v", got.Commands, want) + } +} diff --git a/internal/renderer/models.go b/internal/renderer/models.go index 280eb0b..042893b 100644 --- a/internal/renderer/models.go +++ b/internal/renderer/models.go @@ -1,6 +1,8 @@ package renderer import ( + "slices" + "github.com/DomainCraft/DomainCraft/internal/ir" ) @@ -16,6 +18,7 @@ type BridgeConfig struct { Helpers string `yaml:"helpers"` // Optional shared template file with named templates RegistryURL string `yaml:"registry_url"` // URL template for package registry ({id} = lowercase package ID) RegistryPackages map[string]string `yaml:"registry_packages"` // logical key -> registry package ID (used with registry_url) + TargetFramework string `yaml:"target_framework"` // Language-specific TFM for package version resolution (e.g. net10.0); declared by the bridge, never defaulted by the core Templates []TemplateSpec `yaml:"templates"` Delimiters []string `yaml:"delimiters"` // Optional custom delimiters [left, right], default ["{{", "}}"] Migrations *MigrationConfig `yaml:"migrations"` // Optional database migration commands run by `domaincraft generate --migrate` @@ -68,8 +71,8 @@ func (s TemplateSpec) TargetPatterns() []string { // RenderContext is passed to templates. type RenderContext struct { - Project *ir.IRProject - Entity *ir.IREntity + Project *ir.Project + Entity *ir.Entity Bridge *BridgeConfig // Bridge-level config available as .Bridge Packages map[string]string // Resolved package versions for the current platform // Migration is the abstract schema-migration plan computed by the core from @@ -119,7 +122,7 @@ func (c RenderContext) HasOptimisticLock() bool { } // Permissions exposes the current entity permissions to templates. -func (c RenderContext) Permissions() *ir.IRPermissions { +func (c RenderContext) Permissions() *ir.Permissions { if c.Entity == nil { return nil } @@ -127,7 +130,7 @@ func (c RenderContext) Permissions() *ir.IRPermissions { } // PermissionPlan exposes the core-computed authorization plan for one operation. -func (c RenderContext) PermissionPlan(operation string) *ir.IRPermissionPlan { +func (c RenderContext) PermissionPlan(operation string) *ir.PermissionPlan { if c.Entity == nil { return nil } @@ -135,7 +138,7 @@ func (c RenderContext) PermissionPlan(operation string) *ir.IRPermissionPlan { } // Endpoints exposes the standard HTTP endpoint contract for the current entity. -func (c RenderContext) Endpoints() []ir.IREndpoint { +func (c RenderContext) Endpoints() []ir.Endpoint { if c.Entity == nil { return nil } @@ -143,7 +146,7 @@ func (c RenderContext) Endpoints() []ir.IREndpoint { } // AllIndexes exposes the normalized index list (declared + implicit unique). -func (c RenderContext) AllIndexes() []ir.IRIndex { +func (c RenderContext) AllIndexes() []ir.Index { if c.Entity == nil { return nil } @@ -159,12 +162,16 @@ func (c RenderContext) Seed() []ir.SeedRecord { if c.Entity != nil { for i := range c.SeedData.Entities { if c.SeedData.Entities[i].Name == c.Entity.Name { - return c.SeedData.Entities[i].Records + return slices.Clone(c.SeedData.Entities[i].Records) } } return nil } - var out []ir.SeedRecord + total := 0 + for i := range c.SeedData.Entities { + total += len(c.SeedData.Entities[i].Records) + } + out := make([]ir.SeedRecord, 0, total) for i := range c.SeedData.Entities { out = append(out, c.SeedData.Entities[i].Records...) } @@ -205,11 +212,6 @@ func (c RenderContext) HasSeedData() bool { return false } -// HasFeature reports whether the current entity has the named feature enabled. -func (c RenderContext) HasFeature(name string) bool { - return c.Entity != nil && c.Entity.HasFeature(name) -} - // HasAddon reports whether the named infrastructure addon is enabled at the // project level (e.g. "dapr"). Templates use this to toggle addon-specific code. func (c RenderContext) HasAddon(name string) bool { @@ -227,7 +229,7 @@ func (c RenderContext) HasCacheable() bool { } // ReadFields exposes the current entity's read-DTO projection to templates. -func (c RenderContext) ReadFields() []ir.IRField { +func (c RenderContext) ReadFields() []ir.Field { if c.Entity == nil { return nil } @@ -235,7 +237,7 @@ func (c RenderContext) ReadFields() []ir.IRField { } // CreateFields exposes the current entity's create-DTO projection to templates. -func (c RenderContext) CreateFields() []ir.IRField { +func (c RenderContext) CreateFields() []ir.Field { if c.Entity == nil { return nil } @@ -243,7 +245,7 @@ func (c RenderContext) CreateFields() []ir.IRField { } // UpdateFields exposes the current entity's update-DTO projection to templates. -func (c RenderContext) UpdateFields() []ir.IRField { +func (c RenderContext) UpdateFields() []ir.Field { if c.Entity == nil { return nil } @@ -253,7 +255,7 @@ func (c RenderContext) UpdateFields() []ir.IRField { // PatchFields exposes the current entity's patch-DTO projection to templates: // the core's patchable surface (scalars + single foreign keys) plus the // optimistic-lock concurrency token. -func (c RenderContext) PatchFields() []ir.IRField { +func (c RenderContext) PatchFields() []ir.Field { if c.Entity == nil { return nil } @@ -261,7 +263,7 @@ func (c RenderContext) PatchFields() []ir.IRField { } // SearchableFields exposes the scalar text fields eligible for free-text search. -func (c RenderContext) SearchableFields() []ir.IRField { +func (c RenderContext) SearchableFields() []ir.Field { if c.Entity == nil { return nil } @@ -269,7 +271,7 @@ func (c RenderContext) SearchableFields() []ir.IRField { } // SortableFields exposes the scalar fields a list endpoint may order by. -func (c RenderContext) SortableFields() []ir.IRField { +func (c RenderContext) SortableFields() []ir.Field { if c.Entity == nil { return nil } @@ -277,23 +279,14 @@ func (c RenderContext) SortableFields() []ir.IRField { } // FilterableFields exposes the scalar fields that may be filtered by value, -// each carrying its supported operators via IRField.FilterOperators(). -func (c RenderContext) FilterableFields() []ir.IRField { +// each carrying its supported operators via Field.FilterOperators(). +func (c RenderContext) FilterableFields() []ir.Field { if c.Entity == nil { return nil } return c.Entity.FilterableFields() } -// FilterablePaths exposes the complete filter path schema: scalar fields, -// one-hop relation paths and JSON roots, each with its allowed operators. -func (c RenderContext) FilterablePaths() []ir.FilterPathSpec { - if c.Entity == nil { - return nil - } - return c.Entity.FilterablePaths() -} - // QuerySchema exposes the entity's whole list-query surface (search + sort + // filter) in one object — the single entry point for a bridge's runtime query // validator. @@ -327,7 +320,7 @@ func (c RenderContext) HasMockData() bool { // CursorField returns the keyset-pagination cursor field (the PK when it is a // monotonic integer), or nil when keyset is unsupported for this entity. -func (c RenderContext) CursorField() *ir.IRField { +func (c RenderContext) CursorField() *ir.Field { if c.Entity == nil { return nil } @@ -335,7 +328,7 @@ func (c RenderContext) CursorField() *ir.IRField { } // PrimaryKey returns the primary key field of the current entity, or nil if not found. -func (c RenderContext) PrimaryKey() *ir.IRField { +func (c RenderContext) PrimaryKey() *ir.Field { if c.Entity == nil { return nil } diff --git a/internal/renderer/models_test.go b/internal/renderer/models_test.go new file mode 100644 index 0000000..82d5f51 --- /dev/null +++ b/internal/renderer/models_test.go @@ -0,0 +1,39 @@ +package renderer + +import ( + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +func TestSeedReturnsDefensiveCopy(t *testing.T) { + t.Parallel() + ctx := RenderContext{ + Entity: &ir.Entity{Name: "Order"}, + SeedData: &ir.SeedDataset{ + Entities: []ir.SeedEntity{ + { + Name: "Order", + Records: []ir.SeedRecord{ + {Fields: []ir.SeedValue{{Field: "id", DBType: "uuid", Value: "a"}}}, + }, + }, + }, + }, + } + + got := ctx.Seed() + if len(got) != 1 { + t.Fatalf("got %d records, want 1", len(got)) + } + got[0] = ir.SeedRecord{} + _ = append(got, ir.SeedRecord{}) + + records := ctx.SeedData.Entities[0].Records + if len(records) != 1 { + t.Fatalf("source records slice changed: got %d, want 1", len(records)) + } + if len(records[0].Fields) != 1 || records[0].Fields[0].Value != "a" { + t.Errorf("source record changed: got %+v", records[0]) + } +} diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 28774c2..187b22c 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -1,46 +1,189 @@ +// Package renderer renders the IR through bridge templates. package renderer import ( + "errors" "fmt" + "maps" "os" "path/filepath" + "slices" "strings" "text/template" + "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/internal/packages" ) -func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, []RenderedFile, error) { - if project == nil { - return nil, nil, fmt.Errorf("IR project is nil") +// readBridgeSource reads a template, helper or mapping declared by bridge.yaml. +// The path is confined to the bridge directory and read through one os.Root +// transaction, so a component swapped for a symlink between the check and the +// read cannot pull contents from outside the bridge. +func readBridgeSource(dir, rel string) ([]byte, error) { + path, relative, err := fsutil.LocalPathWithin(dir, rel) + if err != nil { + return nil, fmt.Errorf("unsafe bridge source path %q: %w", rel, err) } - if outputDir == "" { - outputDir = r.config().OutputDir + absDir, err := filepath.Abs(dir) + if err != nil { + return nil, fmt.Errorf("resolve bridge dir: %w", err) } + realDir, err := filepath.EvalSymlinks(absDir) + if err != nil { + return nil, fmt.Errorf("resolve bridge dir: %w", err) + } + if resolved, err := filepath.EvalSymlinks(path); err == nil && + resolved != realDir && !strings.HasPrefix(resolved, realDir+string(filepath.Separator)) { + return nil, fmt.Errorf("bridge source path %q escapes the bridge directory", rel) + } + root, err := os.OpenRoot(realDir) + if err != nil { + return nil, fmt.Errorf("open bridge root: %w", err) + } + defer func() { _ = root.Close() }() + return root.ReadFile(relative) +} - funcMap, err := r.buildFuncMap() +// safeOutputPathChecked is the shared implementation: lexical containment, +// absolute output dir, then the caller's symlink policy. Both wrappers keep the +// same error messages and return the same absolute target. +func safeOutputPathChecked(outputDir, renderedTarget string, refuse func(base, target string) error) (string, error) { + absTarget, _, err := fsutil.LocalPathWithin(outputDir, renderedTarget) if err != nil { - return nil, nil, fmt.Errorf("build template functions: %w", err) + return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) + } + absOutput, err := filepath.Abs(outputDir) + if err != nil { + return "", fmt.Errorf("resolve output directory: %w", err) + } + if err := refuse(absOutput, absTarget); err != nil { + return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) } + return absTarget, nil +} - // Resolve package versions once — avoids repeated HTTP requests per template. - // The target framework constrains the major version (net10.0 cannot use - // packages that only ship for net11.0). - pkgs := r.resolvePackages(project) +// safeOutputPath resolves a rendered template target against outputDir. It keeps +// the lexical containment check and additionally rejects a symlink at every +// existing path component (including the final one): os.Rename follows a +// symlink at the leaf, so a planted link would let a template write outside the +// output tree even when the lexical path is clean. Missing components are left +// to the caller's MkdirAll and are re-checked before the file is committed. +func safeOutputPath(outputDir, renderedTarget string) (string, error) { + return safeOutputPathChecked(outputDir, renderedTarget, fsutil.RefuseSymlinks) +} + +// safeOutputPathCached mirrors safeOutputPath but reuses directory components +// verified by earlier containment checks in the same Render. The final target +// component is always re-inspected. A nil cache gives a fully fresh walk. +func safeOutputPathCached(outputDir, renderedTarget string, verified map[string]bool) (string, error) { + return safeOutputPathChecked(outputDir, renderedTarget, func(base, target string) error { + return fsutil.RefuseSymlinksCached(base, target, verified) + }) +} + +// failWithTempCleanup closes and removes a staged temp file, joining any +// cleanup failure to the primary error so a leftover file cannot go unnoticed. +func failWithTempCleanup(err error, tmp *os.File, path string) error { + cleanup := []error{err} + // The helper is also used after a failed Close: a second Close returns + // ErrClosed, which is not a new cleanup failure. + if cerr := tmp.Close(); cerr != nil && !errors.Is(cerr, os.ErrClosed) { + cleanup = append(cleanup, cerr) + } + if rerr := os.Remove(path); rerr != nil && !errors.Is(rerr, os.ErrNotExist) { + cleanup = append(cleanup, rerr) + } + return errors.Join(cleanup...) +} + +// stagedWrite is a fully rendered file held in a temp file next to its target. +// backup is the rename-aside path of the previous target, created only at +// commit time; an empty backup means the target was created by this run. +type stagedWrite struct { + temp string // absolute temp path, for staging cleanup and messages + target string // absolute target path, for the returned list and messages + backup string // absolute backup path, for messages + + // parentDir was verified free of symlinks at staging. dirRoot is opened + // from it at commit; every commit/rename goes through that handle, so a + // directory swapped for a symlink afterwards cannot redirect the write. + parentDir string + parentInfo os.FileInfo + dirRoot *os.Root + leaf string // target name inside parentDir + tempLeaf string // temp name inside parentDir + backupLeaf string // backup name inside parentDir + + custom bool // overwrite:false — developer-owned, must not be replaced at commit + record RenderedFile +} + +// rollbackWrites undoes committed writes in reverse order and removes every +// staged temp file. It is best-effort: every restore/remove failure is joined +// into the returned error so the caller can report it, while the original +// rendering error stays the primary cause. +func rollbackWrites(staged, committed []stagedWrite) error { + var failures []error + for _, w := range slices.Backward(committed) { + if w.backup != "" { + // The previous file was moved aside before the new one landed; + // moving it back restores bytes, mode and timestamps exactly. + var err error + if w.dirRoot != nil { + err = w.dirRoot.Rename(w.backupLeaf, w.leaf) + } else { + err = os.Rename(w.backup, w.target) + } + if err != nil { + failures = append(failures, fmt.Errorf("restore %s: %w", w.target, err)) + } + continue + } + // commitWrites always creates a backup for an existing target, so + // there is no in-memory restore path here: a new file is removed. + var err error + if w.dirRoot != nil { + err = w.dirRoot.Remove(w.leaf) + } else { + err = os.Remove(w.target) + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + failures = append(failures, fmt.Errorf("remove %s: %w", w.target, err)) + } + } + // Staged writes have no dirRoot: handles are opened only for committed + // files at commit time, so temp cleanup goes through the plain path. + for _, w := range staged { + if err := os.Remove(w.temp); err != nil && !errors.Is(err, os.ErrNotExist) { + failures = append(failures, fmt.Errorf("remove temp %s: %w", w.temp, err)) + } + } + return errors.Join(failures...) +} - // Parse shared helper templates from every bridge in the chain (base first, - // adapter last). They define named templates ({{ define "name" }}) that all - // other templates can call; a composed adapter inherits its bases' helpers. +// rollbackError attaches rollback failures to the error that triggered them. +// The original error stays first, so it remains the primary cause for callers +// inspecting errors.Is / Error(). +func rollbackError(err, rollbackErr error) error { + if rollbackErr == nil { + return err + } + return errors.Join(err, fmt.Errorf("rollback writes: %w", rollbackErr)) +} + +// parseHelpers loads the named templates ({{ define "name" }}) declared by +// every bridge in the chain. Bases are parsed first so a composed adapter +// inherits their helpers; the adapter's definitions win on conflicts. +func (r *Renderer) parseHelpers(funcMap template.FuncMap) (*template.Template, error) { var helpersTemplate *template.Template for _, src := range r.sources { if src.config.Helpers == "" { continue } - helperPath := filepath.Join(src.dir, src.config.Helpers) - helperBytes, err := os.ReadFile(helperPath) + helperBytes, err := readBridgeSource(src.dir, src.config.Helpers) if err != nil { - return nil, nil, fmt.Errorf("read helpers %s: %w", src.config.Helpers, err) + return nil, fmt.Errorf("read helpers %s: %w", src.config.Helpers, err) } if helpersTemplate == nil { helpersTemplate, err = r.applyDelimiters(template.New("helpers").Funcs(funcMap)).Parse(string(helperBytes)) @@ -48,44 +191,124 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] helpersTemplate, err = helpersTemplate.Parse(string(helperBytes)) } if err != nil { - return nil, nil, fmt.Errorf("parse helpers %s: %w", src.config.Helpers, err) + return nil, fmt.Errorf("parse helpers %s: %w", src.config.Helpers, err) } } + return helpersTemplate, nil +} + +// renderSession carries the mutable state shared by the three Render phases. +// verified is local to one Render and never reused across the pre- and +// post-MkdirAll containment passes: MkdirAll can create components, so the +// latter pass always walks the path freshly. +type renderSession struct { + outputDir string + project *ir.Project + funcMap template.FuncMap + pkgs map[string]string + helpers *template.Template + + verified map[string]bool + // parentInfos is captured once per directory during staging; roots holds + // one os.Root per directory, opened at commit and reused by all its files. + parentInfos map[string]os.FileInfo + roots map[string]*os.Root + staged []stagedWrite + committed []stagedWrite + manifest []RenderedFile + // customTargets tracks scaffold-once paths planned in this run. Without + // it, two contexts with the same constant target both see "missing" on + // disk and the second write overwrites the first. + customTargets map[string]bool +} + +// dirRoot returns the handle for a staged file's parent directory. The handle +// is opened at commit and checked against the FileInfo captured at staging: +// if the directory was replaced in between, the mismatch aborts the render +// instead of following the replacement. +// +// Scope is deliberate: only the two renames per file go through Root. Opening +// every staging operation (MkdirAll, Lstat, CreateTemp) through Root re-resolves +// each component and makes a warm render ~2.9x slower — see the A/B numbers in +// BenchmarkSafeOutputPathWarm. The symlink containment checks already cover +// staging, so Root is needed only for the final check-then-use window. +func (s *renderSession) dirRoot(w *stagedWrite) (*os.Root, error) { + if root := s.roots[w.parentDir]; root != nil { + return root, nil + } + root, err := os.OpenRoot(w.parentDir) + if err != nil { + return nil, fmt.Errorf("open output directory %s: %w", w.parentDir, err) + } + info, err := root.Stat(".") + if err != nil { + _ = root.Close() + return nil, fmt.Errorf("inspect output directory %s: %w", w.parentDir, err) + } + if !os.SameFile(w.parentInfo, info) { + _ = root.Close() + return nil, fmt.Errorf("output directory %s was replaced before commit", w.parentDir) + } + if s.roots == nil { + s.roots = make(map[string]*os.Root) + } + s.roots[w.parentDir] = root + return root, nil +} - writtenFiles := make([]string, 0) - manifest := make([]RenderedFile, 0) +// fail drops every staged temp file and restores committed files, attaching +// any rollback failure to the primary error. The phase that detects a failure +// calls it once, while the session still holds the exact writes performed. +func (s *renderSession) fail(err error) error { + return rollbackError(err, rollbackWrites(s.staged, s.committed)) +} + +// stageTemplates parses each selected template and renders every target into a +// temp file next to it. Nothing is written to outputDir until all templates +// executed successfully; a failure drops the temp files staged so far. +func (r *Renderer) stageTemplates(s *renderSession) error { for _, src := range r.sources { for _, spec := range src.config.Templates { // Check if template should be rendered based on "When" condition - if !r.shouldRender(spec, project, pkgs) { + if !r.shouldRender(spec, s.project, s.pkgs) { continue } - sourcePath := filepath.Join(src.dir, spec.Source) - tplBytes, err := os.ReadFile(sourcePath) + tplBytes, err := readBridgeSource(src.dir, spec.Source) if err != nil { - return nil, nil, fmt.Errorf("read template %s: %w", spec.Source, err) + return s.fail(fmt.Errorf("read template %s: %w", spec.Source, err)) } tplName := filepath.Base(spec.Source) var parsedTemplate *template.Template - if helpersTemplate != nil { + if s.helpers != nil { // Clone helpers so all named templates are available - parsedTemplate, err = helpersTemplate.Clone() + parsedTemplate, err = s.helpers.Clone() if err != nil { - return nil, nil, fmt.Errorf("clone helpers for %s: %w", spec.Source, err) + return s.fail(fmt.Errorf("clone helpers for %s: %w", spec.Source, err)) } parsedTemplate, err = r.applyDelimiters(parsedTemplate.New(tplName)).Parse(string(tplBytes)) } else { - parsedTemplate, err = r.applyDelimiters(template.New(tplName).Funcs(funcMap)).Parse(string(tplBytes)) + parsedTemplate, err = r.applyDelimiters(template.New(tplName).Funcs(s.funcMap)).Parse(string(tplBytes)) } if err != nil { - return nil, nil, fmt.Errorf("parse template %s: %w", spec.Source, err) + return s.fail(fmt.Errorf("parse template %s: %w", spec.Source, err)) } - contexts, err := r.renderContexts(spec.For, project, pkgs) + contexts, err := r.renderContexts(spec.For, s.project, s.pkgs) if err != nil { - return nil, nil, err + return s.fail(err) + } + + // A target pattern is static for the spec; only the context changes. + // Parse once instead of once per (entity, pattern) pair. + targetPatterns := spec.TargetPatterns() + targetTemplates := make([]*template.Template, len(targetPatterns)) + for i, pattern := range targetPatterns { + targetTemplates[i], err = template.New("path").Funcs(s.funcMap).Parse(pattern) + if err != nil { + return s.fail(fmt.Errorf("parse target path %q: %w", pattern, err)) + } } for _, context := range contexts { @@ -99,72 +322,293 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] entityName = context.Entity.Name } - for _, targetPattern := range spec.TargetPatterns() { - renderedTarget, err := renderTemplateString(targetPattern, context, funcMap) - if err != nil { - return nil, nil, fmt.Errorf("render target path: %w", err) + for _, targetTpl := range targetTemplates { + if err := stageOneTarget(s, spec, context, parsedTemplate, targetTpl, entityName); err != nil { + return err } + } + } + } + } + return nil +} - absoluteTarget := filepath.Join(outputDir, filepath.FromSlash(renderedTarget)) - absOutput, err := filepath.Abs(outputDir) - if err != nil { - return nil, nil, fmt.Errorf("resolve output directory: %w", err) - } - absTarget, err := filepath.Abs(absoluteTarget) - if err != nil { - return nil, nil, fmt.Errorf("resolve target path: %w", err) - } - if !strings.HasPrefix(absTarget, absOutput+string(filepath.Separator)) { - return nil, nil, fmt.Errorf("template target path escapes output directory: %s", renderedTarget) - } +// resolvedTarget is one rendered target path plus the manifest record shared +// by the scaffold gate and the staging step. +type resolvedTarget struct { + rendered string // raw rendered target, used verbatim in error messages + abs string // absolute, containment-checked destination + record RenderedFile +} - relPath := filepath.ToSlash(renderedTarget) - record := RenderedFile{ - Path: relPath, - Entity: entityName, - Custom: spec.IsCustom(), - Written: true, - } +// resolveTargetPath executes the target pattern, re-checks containment with +// the per-render cache and builds the manifest record. +func (s *renderSession) resolveTargetPath(target *template.Template, context RenderContext, spec TemplateSpec, entityName string) (resolvedTarget, error) { + renderedTarget, err := executeTemplateString(target, context) + if err != nil { + return resolvedTarget{}, fmt.Errorf("render target path: %w", err) + } + absTarget, err := safeOutputPathCached(s.outputDir, renderedTarget, s.verified) + if err != nil { + return resolvedTarget{}, err + } + return resolvedTarget{ + rendered: renderedTarget, + abs: absTarget, + record: RenderedFile{ + Path: filepath.ToSlash(renderedTarget), + Entity: entityName, + Custom: spec.IsCustom(), + Written: true, + }, + }, nil +} - // Scaffold semantics: overwrite: false files are created only once. - // The developer owns them afterwards, so they survive regeneration. - if spec.IsCustom() { - if _, statErr := os.Stat(absoluteTarget); statErr == nil { - record.Written = false - manifest = append(manifest, record) - continue - } - } +// scaffoldAllowed applies overwrite:false semantics: a target planned earlier +// in this run or already present on disk stays developer-owned. A skipped +// target is recorded in the manifest with Written=false and is not staged. +func (s *renderSession) scaffoldAllowed(path resolvedTarget) bool { + if !path.record.Custom { + return true + } + if s.customTargets[path.abs] { + path.record.Written = false + s.manifest = append(s.manifest, path.record) + return false + } + if _, statErr := os.Stat(path.abs); statErr == nil { + path.record.Written = false + s.manifest = append(s.manifest, path.record) + return false + } + s.customTargets[path.abs] = true + return true +} - if err := os.MkdirAll(filepath.Dir(absoluteTarget), 0o755); err != nil { - return nil, nil, fmt.Errorf("create output dir: %w", err) - } +// stageTempFile creates the parent directory, re-checks containment after +// MkdirAll, captures the parent's identity and the previous file mode, then +// renders the body into a temp file next to the target. On success the staged +// write and its manifest record are appended; on failure the temp file is +// cleaned up. +func (s *renderSession) stageTempFile(path resolvedTarget, body *template.Template, context RenderContext) error { + if err := os.MkdirAll(filepath.Dir(path.abs), 0o755); err != nil { //nolint:gosec // generated project dirs must stay world-readable + return fmt.Errorf("create output dir: %w", err) + } + // MkdirAll may have created the missing components above; re-check + // with a fully fresh walk (no cached directories) so a symlink + // planted in the meantime is still rejected. + if _, err := safeOutputPath(s.outputDir, path.rendered); err != nil { + return err + } + // Capture the verified parent directory now. Commit opens an + // os.Root from this path and compares the directory identity, + // so a swap before commit is detected instead of followed. + parentDir := filepath.Dir(path.abs) + parentInfo, ok := s.parentInfos[parentDir] + if !ok { + info, err := os.Lstat(parentDir) + if err != nil { + return fmt.Errorf("inspect output directory for %s: %w", path.rendered, err) + } + parentInfo = info + s.parentInfos[parentDir] = parentInfo + } - file, err := os.Create(absoluteTarget) - if err != nil { - return nil, nil, fmt.Errorf("create output file: %w", err) - } + mode := os.FileMode(0o644) // os.Create's default under the usual umask + if info, statErr := os.Lstat(path.abs); statErr == nil { + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("template target path escapes output directory through a symlink: %s", path.rendered) + } + mode = info.Mode().Perm() + // The previous bytes are not read here: the commit phase moves + // the whole file aside and moves it back on rollback. + } else if !errors.Is(statErr, os.ErrNotExist) { + return fmt.Errorf("inspect output file %s: %w", path.rendered, statErr) + } - if err := parsedTemplate.Execute(file, context); err != nil { - _ = file.Close() - _ = os.Remove(absoluteTarget) - return nil, nil, fmt.Errorf("execute template: %w", err) - } - if err := file.Close(); err != nil { - _ = os.Remove(absoluteTarget) - return nil, nil, err - } - writtenFiles = append(writtenFiles, absoluteTarget) - manifest = append(manifest, record) - } + // Render into a temp file in the target's own directory so the + // final rename stays on the same filesystem. The prior file is + // never truncated, even if Execute or Close fails. + tmp, err := os.CreateTemp(filepath.Dir(path.abs), ".domaincraft-render-*") + if err != nil { + return fmt.Errorf("create temp output file: %w", err) + } + tmpPath := tmp.Name() + // CreateTemp uses 0600; generated files stay readable as before. + if err := tmp.Chmod(mode); err != nil { + return failWithTempCleanup(fmt.Errorf("set mode on temp output %s: %w", tmpPath, err), tmp, tmpPath) + } + if err := body.Execute(tmp, context); err != nil { + return failWithTempCleanup(fmt.Errorf("execute template: %w", err), tmp, tmpPath) + } + if err := tmp.Close(); err != nil { + return failWithTempCleanup(fmt.Errorf("close temp output %s: %w", tmpPath, err), tmp, tmpPath) + } + s.staged = append(s.staged, stagedWrite{ + temp: tmpPath, + target: path.abs, + parentDir: parentDir, + parentInfo: parentInfo, + leaf: filepath.Base(path.abs), + tempLeaf: filepath.Base(tmpPath), + custom: path.record.Custom, + record: path.record, + }) + s.manifest = append(s.manifest, path.record) + return nil +} + +// stageOneTarget resolves one rendered target path, applies the scaffold and +// symlink policies, and stages the rendered bytes. The order of the three +// steps is load-bearing: it is preserved verbatim from the original loop. +func stageOneTarget(s *renderSession, spec TemplateSpec, context RenderContext, body, target *template.Template, entityName string) error { + path, err := s.resolveTargetPath(target, context, spec, entityName) + if err != nil { + return s.fail(err) + } + if !s.scaffoldAllowed(path) { + return nil + } + if err := s.stageTempFile(path, body, context); err != nil { + return s.fail(err) + } + return nil +} + +// commitWrites commits staged files in order. An existing target is renamed +// aside into a sibling backup before the rendered temp file takes its place; +// rollback moves the backup back, so no prior content is read into memory. +func (r *Renderer) commitWrites(s *renderSession) error { + if hook := r.beforeCommitHook; hook != nil { + hook() + } + for _, w := range s.staged { + root, err := s.dirRoot(&w) + if err != nil { + return s.fail(err) + } + w.dirRoot = root + // os.Lstat sees only the leaf, which is enough here: the renames below + // go through root, so a parent swapped for a symlink cannot redirect + // them even if this stat saw a regular file. + if info, err := os.Lstat(w.target); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + return s.fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) + } + // A scaffold-once target was missing at staging but appeared before + // commit: it is now developer-owned. Backing it up and deleting the + // backup after commit would silently replace it, so preserve it and + // abort. Rollback still restores writes committed earlier in this run. + if w.custom { + return s.fail(fmt.Errorf("custom file %s appeared before commit and was preserved", w.record.Path)) + } + // The staged temp name is already unique in this directory. + w.backup = w.temp + ".bak" + w.backupLeaf = w.tempLeaf + ".bak" + if err := root.Rename(w.leaf, w.backupLeaf); err != nil { + return s.fail(fmt.Errorf("back up output file %s: %w", w.record.Path, err)) } + } else if errors.Is(err, os.ErrNotExist) { + // The target vanished after staging: rollback must remove the new + // file rather than restore a backup that was never created. + w.backup = "" + } else { + return s.fail(fmt.Errorf("inspect output file %s: %w", w.record.Path, err)) + } + // Record the write before the final rename so a failure here still + // restores the backup and removes the staged temp file. + s.committed = append(s.committed, w) + if err := root.Rename(w.tempLeaf, w.leaf); err != nil { + return s.fail(fmt.Errorf("commit output file %s: %w", w.record.Path, err)) + } + } + return nil +} + +// cleanupBackups removes the rename-aside backups after a successful commit. +// A leftover backup is only warned about: the generated files are correct and +// rollback no longer consumes those backups. +func (r *Renderer) cleanupBackups(s *renderSession) { + for _, w := range s.committed { + if w.backup != "" { + var err error + if w.dirRoot != nil { + err = w.dirRoot.Remove(w.backupLeaf) + } else { + err = os.Remove(w.backup) + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + r.log.Warn("remove backup %s: %v", w.backup, err) + } + } + } +} + +// Render renders the IR through every bridge in the chain and returns the +// written paths and the file manifest. Rendering is staged in temp files and +// committed only after every template succeeded; a failure at any point removes +// the staged files and restores any output files that were already replaced. +func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []RenderedFile, error) { + if project == nil { + return nil, nil, errors.New("ir project is nil") + } + if outputDir == "" { + outputDir = r.config().OutputDir + } + + funcMap, err := r.buildFuncMap() + if err != nil { + return nil, nil, fmt.Errorf("build template functions: %w", err) + } + + // Resolve package versions once — avoids repeated HTTP requests per template. + // The project's platform constrains the major version; the core bakes in no + // language-specific framework default. + pkgs := r.resolvePackages(project) + + helpersTemplate, err := r.parseHelpers(funcMap) + if err != nil { + return nil, nil, err + } + + session := &renderSession{ + outputDir: outputDir, + project: project, + funcMap: funcMap, + pkgs: pkgs, + helpers: helpersTemplate, + verified: make(map[string]bool), + parentInfos: make(map[string]os.FileInfo), + roots: make(map[string]*os.Root), + staged: make([]stagedWrite, 0), + // committed is empty during staging; commitWrites appends as files land. + committed: make([]stagedWrite, 0), + manifest: make([]RenderedFile, 0), + customTargets: make(map[string]bool), + } + + defer func() { + for _, root := range session.roots { + _ = root.Close() } + }() + + if err := r.stageTemplates(session); err != nil { + return nil, nil, err + } + if err := r.commitWrites(session); err != nil { + return nil, nil, err } + r.cleanupBackups(session) - return writtenFiles, manifest, nil + written := make([]string, 0, len(session.committed)) + for _, w := range session.committed { + written = append(written, w.target) + } + return written, session.manifest, nil } -func (r *Renderer) shouldRender(spec TemplateSpec, project *ir.IRProject, pkgs map[string]string) bool { +func (r *Renderer) shouldRender(spec TemplateSpec, project *ir.Project, pkgs map[string]string) bool { // Entity-level When conditions are checked per-context in shouldRenderContext. // Project-level When conditions are checked here. if spec.When == "" || spec.For == "entity" { @@ -178,60 +622,15 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) if spec.When == "" { return true } - // Addon conditions accept a suffix after a colon, e.g. "hasAddon:dapr" / - // "notHasAddon:dapr". Bare "hasAddon" treats the presence of any addon as - // true. - if cond, name, ok := strings.Cut(spec.When, ":"); ok { - switch strings.TrimSpace(cond) { - case "hasAddon": - if context.Project != nil { - if name == "" { - return len(context.Project.Addons) > 0 - } - return context.Project.HasAddon(strings.TrimSpace(name)) - } - return false - case "notHasAddon": - if context.Project != nil { - if name == "" { - return len(context.Project.Addons) == 0 - } - return !context.Project.HasAddon(strings.TrimSpace(name)) - } - return true - } - } - switch spec.When { - case "hasSeed": - // Only render seed templates if there's actual seed data. - return context.HasSeedData() - case "hasEnums": - // Only render enum templates if there are enums defined - if context.Project != nil && len(context.Project.Enums) > 0 { - return true - } - return false - case "hasOwnerTokens": - // Only render owner resolver if any entity uses @Owner tokens - if context.Project != nil { - for _, e := range context.Project.Entities { - if e.Permissions != nil && e.Permissions.HasOwnerToken() { - return true - } - } - } - return false - case "hasAuth": - return context.Project != nil && context.Project.HasAuth() - case "hasMigration": - // True when the core computed a non-empty schema migration plan. - return context.HasMigration() - case "hasMockData": - // True when the context carries generated mock data. - return context.HasMockData() - default: + cond, name, _ := strings.Cut(spec.When, ":") + entry, ok := whenSpecs[strings.TrimSpace(cond)] + if !ok { + // Defensive only: loaded manifests are validated against the closed + // vocabulary in validateWhenConditions, so this is unreachable for + // bridge.yaml-driven templates. return true } + return entry.eval(context, name) } // resolvePackages resolves all package versions from the package registry, @@ -239,22 +638,29 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) // When the renderer is composed (extends chain), registry_packages from all // bridges are merged base-first so inner layers can declare their own // dependencies; the adapter's values win on conflicts. -func (r *Renderer) resolvePackages(project *ir.IRProject) map[string]string { - framework := "" - if project != nil { - framework = project.Platform +// targetFramework returns the project's declared platform, then the framework +// declared by the bridge chain (adapter first, base later). An absent framework +// leaves version selection unconstrained — the core bakes in no TFM. +func (r *Renderer) targetFramework(project *ir.Project) string { + if project != nil && project.Platform != "" { + return project.Platform } - if framework == "" { - framework = "net10.0" // same default as the C# csproj templates + for _, src := range slices.Backward(r.sources) { + if fw := src.config.TargetFramework; fw != "" { + return fw + } } + return "" +} + +func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { + framework := r.targetFramework(project) // Merge registry_packages from all sources in the chain (base-first, // adapter wins on conflicts — consistent with type_mappings merge). merged := make(map[string]string) for _, src := range r.sources { - for k, v := range src.config.RegistryPackages { - merged[k] = v - } + maps.Copy(merged, src.config.RegistryPackages) } if len(merged) == 0 { return nil @@ -263,9 +669,9 @@ func (r *Renderer) resolvePackages(project *ir.IRProject) map[string]string { // Use the adapter's registry_url; fall back to any source with one. registryURL := r.config().RegistryURL if registryURL == "" { - for i := len(r.sources) - 1; i >= 0; i-- { - if r.sources[i].config.RegistryURL != "" { - registryURL = r.sources[i].config.RegistryURL + for _, src := range slices.Backward(r.sources) { + if src.config.RegistryURL != "" { + registryURL = src.config.RegistryURL break } } @@ -276,11 +682,13 @@ func (r *Renderer) resolvePackages(project *ir.IRProject) map[string]string { } result := make(map[string]string, len(merged)) - for key, packageID := range merged { + for _, key := range slices.Sorted(maps.Keys(merged)) { + packageID := merged[key] version, err := packages.ResolveVersionCachedForFramework(r.cacheNamespace(), registryURL, packageID, framework) if err != nil { + // A cache-write failure still carries the resolved version; warn + // once and use it instead of emitting a package-less project. r.log.Warn("failed to resolve package %s: %v", packageID, err) - continue } if version != "" { result[key] = version @@ -310,7 +718,7 @@ func (r *Renderer) cacheNamespace() string { return b.String() } -func (r *Renderer) renderContexts(scope string, project *ir.IRProject, pkgs map[string]string) ([]RenderContext, error) { +func (r *Renderer) renderContexts(scope string, project *ir.Project, pkgs map[string]string) ([]RenderContext, error) { cfg := r.config() switch strings.ToLower(strings.TrimSpace(scope)) { case "", "entity": diff --git a/internal/renderer/render_bench_test.go b/internal/renderer/render_bench_test.go new file mode 100644 index 0000000..dc28279 --- /dev/null +++ b/internal/renderer/render_bench_test.go @@ -0,0 +1,120 @@ +package renderer + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +// benchmarkRenderFixture builds the bridge, project and pre-existing output +// tree shared by BenchmarkRenderWarm and TestBenchmarkRenderWarmGolden. One +// fixture keeps the golden digest tied to exactly what the benchmark measures. +func benchmarkRenderFixture(tb testing.TB, size int) (*Renderer, string, *ir.Project) { + tb.Helper() + dir := tb.TempDir() + bridgeDir := filepath.Join(dir, "bridge") + if err := os.MkdirAll(filepath.Join(bridgeDir, "templates"), 0o755); err != nil { + tb.Fatal(err) + } + manifest := `name: benchmark +contract_version: 1 +templates: + - for: entity + source: templates/entity.tmpl + target: "src/{{ .Entity.Name }}.txt" +` + if err := os.WriteFile(filepath.Join(bridgeDir, "bridge.yaml"), []byte(manifest), 0o644); err != nil { + tb.Fatal(err) + } + if err := os.WriteFile(filepath.Join(bridgeDir, "templates", "entity.tmpl"), []byte("generated {{ .Entity.Name }}\n"), 0o644); err != nil { + tb.Fatal(err) + } + out := filepath.Join(dir, "out") + project := &ir.Project{Name: "Bench"} + for i := range size { + name := fmt.Sprintf("E%04d", i) + project.Entities = append(project.Entities, ir.Entity{Name: name, NamePlural: name + "s"}) + target := filepath.Join(out, "src", name+".txt") + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + tb.Fatal(err) + } + if err := os.WriteFile(target, []byte("previous\n"), 0o644); err != nil { + tb.Fatal(err) + } + } + r, err := New(bridgeDir, nil) + if err != nil { + tb.Fatal(err) + } + return r, out, project +} + +// BenchmarkRenderWarm measures regeneration where every target already exists. +// That is the common case for a warm rebuild and used to read every prior file +// into memory solely to support rollback. +func BenchmarkRenderWarm(b *testing.B) { + for _, size := range []int{100, 500, 2000} { + b.Run(fmt.Sprintf("entities=%d", size), func(b *testing.B) { + r, out, project := benchmarkRenderFixture(b, size) + for b.Loop() { + if _, _, err := r.Render(project, out); err != nil { + b.Fatal(err) + } + } + }) + } +} + +// benchmarkSafePathFixture builds the output tree shared by +// BenchmarkSafeOutputPathWarm, its golden test and its allocation guard. +func benchmarkSafePathFixture(tb testing.TB, size int) (string, []string) { + tb.Helper() + out := filepath.Join(tb.TempDir(), "out") + targets := make([]string, 0, size) + for i := range size { + rel := fmt.Sprintf("src/E%04d.txt", i) + target := filepath.Join(out, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + tb.Fatal(err) + } + if err := os.WriteFile(target, []byte("previous\n"), 0o644); err != nil { + tb.Fatal(err) + } + targets = append(targets, rel) + } + return out, targets +} + +// BenchmarkSafeOutputPathWarm isolates the symlink-containment work that +// BenchmarkRenderWarm performs twice per file (before and after MkdirAll). +// Measured on Windows/amd64 at 2000 entities: containment 213 ms for 2000 +// calls (~106 us/call, x2 per file) vs 3.80 s total render — about 11%. +// The first pass is cached per Render (directories only); the second stays +// fresh. A/B at 2000 entities: 4.32 s -> 4.17 s median warm render. +// +// A full os.Root rewrite of staging + commit is NOT acceptable: every Root +// operation re-resolves each path component through directory handles, which +// measured 10.43 s/op vs 3.65 s/op baseline (2.86x). The commit-phase fix +// instead captures each parent directory once during staging, opens one +// os.Root per parent at commit, and routes only the two rename calls through +// it (single-component names): 4.14 s/op (1.13x). Do not move staging file +// creation, Lstat or containment checks onto Root — that reintroduces the +// 2.9x regression. Keep this benchmark as the measurement baseline. +func BenchmarkSafeOutputPathWarm(b *testing.B) { + for _, size := range []int{100, 500, 2000} { + b.Run(fmt.Sprintf("entities=%d", size), func(b *testing.B) { + out, targets := benchmarkSafePathFixture(b, size) + for b.Loop() { + for _, rel := range targets { + if _, err := safeOutputPath(out, rel); err != nil { + b.Fatal(err) + } + } + } + }) + } +} + diff --git a/internal/renderer/renderer_test.go b/internal/renderer/render_test.go similarity index 73% rename from internal/renderer/renderer_test.go rename to internal/renderer/render_test.go index a78bb76..9de1740 100644 --- a/internal/renderer/renderer_test.go +++ b/internal/renderer/render_test.go @@ -1,23 +1,22 @@ package renderer import ( + "fmt" "net/http" "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/DomainCraft/DomainCraft/internal/ir" ) func TestRenderEntityTemplate(t *testing.T) { + t.Parallel() tmpDir := t.TempDir() - bridgeDir := filepath.Join(tmpDir, "bridge") - if err := os.MkdirAll(filepath.Join(bridgeDir, "templates"), 0o755); err != nil { - t.Fatalf("mkdir bridge: %v", err) - } - - bridgeYAML := []byte(`name: demo + bridgeDir := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo output_dir: generated templates: - for: entity @@ -25,23 +24,18 @@ templates: targets: - "{{ .Entity.Name }}.txt" - "nested/{{ .Entity.Name }}.txt" -`) - templateBytes := []byte(`{{ .Entity.Name }} -> {{ .Project.Name }}`) - if err := os.WriteFile(filepath.Join(bridgeDir, "bridge.yaml"), bridgeYAML, 0o644); err != nil { - t.Fatalf("write bridge: %v", err) - } - if err := os.WriteFile(filepath.Join(bridgeDir, "templates", "entity.tmpl"), templateBytes, 0o644); err != nil { - t.Fatalf("write template: %v", err) - } +`, + "templates/entity.tmpl": `{{ .Entity.Name }} -> {{ .Project.Name }}`, + }) r, err := New(bridgeDir, nil) if err != nil { t.Fatalf("New() error = %v", err) } - project := &ir.IRProject{ + project := &ir.Project{ Name: "TestProject", - Entities: []ir.IREntity{{Name: "User", NamePlural: "Users"}}, + Entities: []ir.Entity{{Name: "User", NamePlural: "Users"}}, } written, _, err := r.Render(project, filepath.Join(tmpDir, "out")) if err != nil { @@ -58,7 +52,48 @@ templates: } } +// TestRenderTargetPathsUsePerEntityContext guards the target-template fast +// path: one parsed pattern must still be executed with each entity's context. +func TestRenderTargetPathsUsePerEntityContext(t *testing.T) { + t.Parallel() + tmpDir := t.TempDir() + bridgeDir := writeBridge(t, map[string]string{ + "bridge.yaml": `name: demo +output_dir: generated +templates: + - for: entity + source: templates/entity.tmpl + targets: + - "{{ .Entity.Name }}.txt" + - "nested/{{ lower .Entity.Name }}.txt" +`, + "templates/entity.tmpl": `{{ .Entity.Name }}`, + }) + + r, err := New(bridgeDir, nil) + if err != nil { + t.Fatal(err) + } + project := &ir.Project{ + Name: "TestProject", + Entities: []ir.Entity{{Name: "User"}, {Name: "Item"}}, + } + written, _, err := r.Render(project, filepath.Join(tmpDir, "out")) + if err != nil { + t.Fatalf("Render() error = %v", err) + } + if len(written) != 4 { + t.Fatalf("got %d files, want 4", len(written)) + } + for _, name := range []string{"User.txt", "Item.txt", "nested/user.txt", "nested/item.txt"} { + if _, err := os.Stat(filepath.Join(tmpDir, "out", name)); err != nil { + t.Errorf("expected generated file %s: %v", name, err) + } + } +} + func TestComposeAttachBases(t *testing.T) { + t.Parallel() tmpDir := t.TempDir() write := func(dir, name, content string) { @@ -102,7 +137,7 @@ templates: t.Fatalf("AttachBases() error = %v", err) } - project := &ir.IRProject{Name: "TestProject"} + project := &ir.Project{Name: "TestProject"} written, _, err := r.Render(project, filepath.Join(tmpDir, "out")) if err != nil { t.Fatalf("Render() error = %v", err) @@ -129,6 +164,7 @@ templates: } func TestMergeTypeMappingsOverlay(t *testing.T) { + t.Parallel() base := &typeMappings{ Types: map[string]string{"string": "str", "int": "num"}, ArrayFormat: "%s[]", @@ -159,6 +195,7 @@ func TestMergeTypeMappingsOverlay(t *testing.T) { } func TestRenderOverwriteFalseScaffoldsOnce(t *testing.T) { + t.Parallel() tmpDir := t.TempDir() bridgeDir := filepath.Join(tmpDir, "bridge") if err := os.MkdirAll(filepath.Join(bridgeDir, "templates"), 0o755); err != nil { @@ -193,9 +230,9 @@ templates: t.Fatalf("New() error = %v", err) } - project := &ir.IRProject{ + project := &ir.Project{ Name: "TestProject", - Entities: []ir.IREntity{{Name: "User", NamePlural: "Users"}}, + Entities: []ir.Entity{{Name: "User", NamePlural: "Users"}}, } outDir := filepath.Join(tmpDir, "out") @@ -236,36 +273,10 @@ templates: } } -func TestRenderContext_HasFeature(t *testing.T) { - tests := []struct { - name string - features map[string]bool - feature string - want bool - }{ - {"audit enabled", map[string]bool{"audit": true}, "audit", true}, - {"audit disabled", map[string]bool{"audit": false}, "audit", false}, - {"nil features", nil, "audit", false}, - {"nil entity", nil, "audit", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := RenderContext{ - Entity: &ir.IREntity{Features: tt.features}, - } - if tt.name == "nil entity" { - ctx.Entity = nil - } - if got := ctx.HasFeature(tt.feature); got != tt.want { - t.Errorf("HasFeature(%q) = %v, want %v", tt.feature, got, tt.want) - } - }) - } -} - func TestRenderContext_HasAudit(t *testing.T) { + t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Features: map[string]bool{"audit": true}}, + Entity: &ir.Entity{Features: map[string]bool{"audit": true}}, } if !ctx.HasAudit() { t.Error("HasAudit() = false, want true") @@ -278,8 +289,9 @@ func TestRenderContext_HasAudit(t *testing.T) { } func TestRenderContext_HasSoftDelete(t *testing.T) { + t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Features: map[string]bool{"soft_delete": true}}, + Entity: &ir.Entity{Features: map[string]bool{"soft_delete": true}}, } if !ctx.HasSoftDelete() { t.Error("HasSoftDelete() = false, want true") @@ -287,8 +299,9 @@ func TestRenderContext_HasSoftDelete(t *testing.T) { } func TestRenderContext_HasOptimisticLock(t *testing.T) { + t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Features: map[string]bool{"optimistic_lock": true}}, + Entity: &ir.Entity{Features: map[string]bool{"optimistic_lock": true}}, } if !ctx.HasOptimisticLock() { t.Error("HasOptimisticLock() = false, want true") @@ -296,8 +309,9 @@ func TestRenderContext_HasOptimisticLock(t *testing.T) { } func TestRenderContext_HasAuditLog(t *testing.T) { + t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Features: map[string]bool{"audit_log": true}}, + Entity: &ir.Entity{Features: map[string]bool{"audit_log": true}}, } if !ctx.HasAuditLog() { t.Error("HasAuditLog() = false, want true") @@ -305,14 +319,15 @@ func TestRenderContext_HasAuditLog(t *testing.T) { } func TestRenderContext_Permissions(t *testing.T) { + t.Parallel() ctx := RenderContext{Entity: nil} if ctx.Permissions() != nil { t.Error("Permissions() should return nil for nil entity") } - perms := &ir.IRPermissions{Read: []string{"Admin"}} + perms := &ir.Permissions{Read: []string{"Admin"}} ctx2 := RenderContext{ - Entity: &ir.IREntity{Permissions: perms}, + Entity: &ir.Entity{Permissions: perms}, } if ctx2.Permissions() != perms { t.Error("Permissions() should return entity permissions") @@ -320,14 +335,15 @@ func TestRenderContext_Permissions(t *testing.T) { } func TestRenderContext_PrimaryKey(t *testing.T) { + t.Parallel() ctx := RenderContext{Entity: nil} if ctx.PrimaryKey() != nil { t.Error("PrimaryKey() should return nil for nil entity") } ctx2 := RenderContext{ - Entity: &ir.IREntity{ - Fields: []ir.IRField{ + Entity: &ir.Entity{ + Fields: []ir.Field{ {Name: "id", IsPrimary: true}, {Name: "name"}, }, @@ -339,25 +355,87 @@ func TestRenderContext_PrimaryKey(t *testing.T) { } } +// The core must not bake in a language-specific TFM: the project declares its +// platform, otherwise the bridge chain declares it in bridge.yaml. +func TestResolvePackagesHasNoLanguageSpecificFrameworkDefault(t *testing.T) { + t.Parallel() + r := &Renderer{} + if got := r.targetFramework(nil); got != "" { + t.Errorf("targetFramework(nil) = %q, want empty (no core-side default)", got) + } + if got := r.targetFramework(&ir.Project{}); got != "" { + t.Errorf("targetFramework(empty project) = %q, want empty (no core-side default)", got) + } + if got := r.targetFramework(&ir.Project{Platform: "net11.0"}); got != "net11.0" { + t.Errorf("targetFramework(net11.0) = %q, want the declared platform", got) + } + + bridge := &Renderer{sources: []sourceConfig{ + {config: BridgeConfig{TargetFramework: "net10.0"}}, // base + {config: BridgeConfig{}}, // adapter, silent + }} + if got := bridge.targetFramework(&ir.Project{}); got != "net10.0" { + t.Errorf("targetFramework() = %q, want the bridge-declared net10.0", got) + } + // Project platform wins over the bridge declaration. + if got := bridge.targetFramework(&ir.Project{Platform: "net11.0"}); got != "net11.0" { + t.Errorf("targetFramework() = %q, want the project platform", got) + } +} + func TestResolvePackagesNilLoggerDoesNotPanic(t *testing.T) { - // A nil logger is valid (silent mode). Failed package resolution must not - // panic when the logger is nil — Warn is a no-op on a nil Logger. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Parallel() + // A nil logger is valid (silent mode). A failed registry lookup must not + // panic or abort the render. Drive this through the public New()/Render() + // API so the test covers the same path a CLI run takes. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) })) defer server.Close() - r := &Renderer{log: nil, sources: []sourceConfig{{config: BridgeConfig{ - RegistryURL: server.URL + "/{id}/index.json", - RegistryPackages: map[string]string{"jwt_bearer": "Microsoft.AspNetCore.Authentication.JwtBearer"}, - }}}} - got := r.resolvePackages(nil) - if len(got) != 0 { - t.Fatalf("resolvePackages() = %v, want no resolved versions on failure", got) + tmp := t.TempDir() + bridgeDir := filepath.Join(tmp, "bridge") + if err := os.MkdirAll(filepath.Join(bridgeDir, "templates"), 0o755); err != nil { + t.Fatalf("mkdir bridge: %v", err) + } + bridgeYAML := fmt.Sprintf(`name: demo +registry_url: %s/{id}/index.json +registry_packages: + jwt_bearer: Microsoft.AspNetCore.Authentication.JwtBearer +templates: + - for: project + source: templates/pkg.tmpl + target: pkg.txt +`, server.URL) + if err := os.WriteFile(filepath.Join(bridgeDir, "bridge.yaml"), []byte(bridgeYAML), 0o644); err != nil { + t.Fatalf("write bridge: %v", err) + } + if err := os.WriteFile(filepath.Join(bridgeDir, "templates", "pkg.tmpl"), []byte(`{{ printf "%v" .Packages }}`), 0o644); err != nil { + t.Fatalf("write template: %v", err) + } + + r, err := New(bridgeDir, nil) // nil logger is intentional + if err != nil { + t.Fatalf("New() error = %v", err) + } + written, _, err := r.Render(&ir.Project{Name: "P"}, filepath.Join(tmp, "out")) + if err != nil { + t.Fatalf("Render() error = %v", err) + } + if len(written) != 1 { + t.Fatalf("got %d written files, want 1", len(written)) + } + data, err := os.ReadFile(filepath.Join(tmp, "out", "pkg.txt")) + if err != nil { + t.Fatalf("read pkg.txt: %v", err) + } + if got := strings.TrimSpace(string(data)); got != "map[]" { + t.Fatalf("Packages = %q, want %q (failed resolution yields no versions)", got, "map[]") } } func TestRenderHasMigrationCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T, when string) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -384,7 +462,7 @@ templates: return r } - project := &ir.IRProject{Name: "P"} + project := &ir.Project{Name: "P"} // No migration plan set -> hasMigration is false, no file written. r := newRenderer(t, "hasMigration") @@ -409,6 +487,7 @@ templates: } func TestRenderHasMockDataCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -435,7 +514,7 @@ templates: return r } - project := &ir.IRProject{Name: "P", Entities: []ir.IREntity{{Name: "Order", NamePlural: "Orders"}}} + project := &ir.Project{Name: "P", Entities: []ir.Entity{{Name: "Order", NamePlural: "Orders"}}} // No mock data -> hasMockData is false. r := newRenderer(t) @@ -460,6 +539,7 @@ templates: } func TestRenderHasSeedCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -486,7 +566,7 @@ templates: return r } - project := &ir.IRProject{Name: "P", Entities: []ir.IREntity{{Name: "Order", NamePlural: "Orders"}}} + project := &ir.Project{Name: "P", Entities: []ir.Entity{{Name: "Order", NamePlural: "Orders"}}} // No seed -> hasSeed is false. r := newRenderer(t) @@ -511,21 +591,23 @@ templates: } func TestRenderContext_SeedAccessor(t *testing.T) { + t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Name: "Order"}, + Entity: &ir.Entity{Name: "Order"}, SeedData: &ir.SeedDataset{Entities: []ir.SeedEntity{{Name: "Order", Records: []ir.SeedRecord{{Fields: []ir.SeedValue{{Field: "id", Value: "x"}}}}}}}, } got := ctx.Seed() if len(got) != 1 || len(got[0].Fields) != 1 || got[0].Fields[0].Value != "x" { t.Errorf("Seed() = %+v, want one normalized record", got) } - if empty := (RenderContext{Entity: &ir.IREntity{Name: "Order"}}).Seed(); empty != nil { + if empty := (RenderContext{Entity: &ir.Entity{Name: "Order"}}).Seed(); empty != nil { t.Errorf("Seed() with no dataset should be nil, got %+v", empty) } } func TestRenderContext_DTOAccessors(t *testing.T) { - e := &ir.IREntity{Name: "User", Fields: []ir.IRField{ + t.Parallel() + e := &ir.Entity{Name: "User", Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, {Name: "password", DatabaseType: "string"}, diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index 8863a7e..5f219ac 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -3,10 +3,13 @@ package renderer import ( "cmp" "encoding/json" + "errors" "fmt" + "maps" "os" - "path/filepath" + "slices" "strings" + "sync" "text/template" "github.com/DomainCraft/DomainCraft/internal/ir" @@ -18,30 +21,53 @@ import ( "gopkg.in/yaml.v3" ) +// seedKind is the language-agnostic value kind of a seed field. It is derived +// from the IR database type; the typed constants keep template formatters from +// comparing free-form strings. +type seedKind string + +const ( + seedArray seedKind = "array" + seedUUID seedKind = "uuid" + seedText seedKind = "text" + seedInt seedKind = "int" + seedBigInt seedKind = "bigint" + seedFloat seedKind = "float" + seedDecimal seedKind = "decimal" + seedBool seedKind = "bool" + seedDate seedKind = "date" + seedDateTime seedKind = "datetime" + seedJSON seedKind = "json" + seedEnum seedKind = "enum" +) + +func kindOfSeed(dbType string) seedKind { return seedKind(ir.KindOf(dbType)) } + // LiteralSpec declares how a bridge writes a scalar literal of one IR type in // its target language. Loaded from type_mappings.yaml `literals:` (keyed by IR // database type; "enum" is a reserved key for user-declared enums). type LiteralSpec struct { - // Parse is a printf template (one %s) that turns a serialized value into an - // expression, e.g. "Guid.Parse(%s)" or "JsonDocument.Parse(%s, default)". + // Parse is a printf template (one %s) that turns a serialized value into a + // target-language expression (a parse call in languages that need one). Parse string `yaml:"parse"` - // Suffix is appended to a bare numeric literal, e.g. "L" (long) or "m" (decimal). + // Suffix is appended to a bare numeric literal, e.g. a long or decimal marker. Suffix string `yaml:"suffix"` - // Default is the value-less default expression, e.g. "Guid.NewGuid()" or "0m". + // Default is the value-less default expression, e.g. a fresh identifier or + // a numeric zero, in the bridge's target language. Default string `yaml:"default"` - // Member (enums) is a printf template (type, value) for a compile-time member - // reference, e.g. "%s.%s" -> "OrderStatus.Draft". + // Member (enums) is a printf template (type, value) for a compile-time + // reference to an enum member, e.g. "%s.%s". Member string `yaml:"member"` - // Zero (enums) is a printf template (type) for a zero-valued enum, e.g. "(%s)0". + // Zero (enums) is a printf template (type) for a zero-valued enum expression. Zero string `yaml:"zero"` } // ArrayLiteralSpec declares how a bridge writes array literals. %s placeholders -// are filled with the bridge's array type (e.g. "List"). +// are filled with the bridge's array type. type ArrayLiteralSpec struct { - Open string `yaml:"open"` // e.g. "new %s { " - Close string `yaml:"close"` // e.g. " }" - Empty string `yaml:"empty"` // e.g. "new %s()" + Open string `yaml:"open"` // bridge-specific opening delimiter/expression + Close string `yaml:"close"` // bridge-specific closing delimiter + Empty string `yaml:"empty"` // bridge-specific empty-array expression } // typeMappings is the raw shape of a bridge's type_mappings.yaml. A composed @@ -72,9 +98,7 @@ func (r *Renderer) buildFuncMap() (template.FuncMap, error) { if err != nil { return nil, err } - for key, value := range bridgeFuncs { - funcMap[key] = value - } + maps.Copy(funcMap, bridgeFuncs) return funcMap, nil } @@ -82,9 +106,11 @@ func (r *Renderer) buildFuncMap() (template.FuncMap, error) { // (no error) when the file is absent — a bridge with no mappings contributes // nothing, and the merged result drives the language functions. func (r *Renderer) loadTypeMappings(dir string) (*typeMappings, error) { - data, err := os.ReadFile(filepath.Join(dir, "type_mappings.yaml")) + // Same guard as templates and helpers: a symlinked mapping file must not + // pull configuration from outside the bridge directory. + data, err := readBridgeSource(dir, "type_mappings.yaml") if err != nil { - if os.IsNotExist(err) { + if errors.Is(err, os.ErrNotExist) { return nil, nil } return nil, err @@ -106,29 +132,16 @@ func mergeTypeMappings(base, overlay *typeMappings) *typeMappings { if overlay == nil { overlay = &typeMappings{} } - mergeStrings := func(dst, src map[string]string) map[string]string { - if len(dst) == 0 && len(src) == 0 { - return nil - } - m := make(map[string]string, len(dst)+len(src)) - for k, v := range dst { - m[k] = v - } - for k, v := range src { - m[k] = v - } - return m - } out := &typeMappings{ - Types: mergeStrings(base.Types, overlay.Types), - Behaviors: mergeStrings(base.Behaviors, overlay.Behaviors), - InputTypes: mergeStrings(base.InputTypes, overlay.InputTypes), - ColumnSizes: mergeStrings(base.ColumnSizes, overlay.ColumnSizes), + Types: mergeMaps(base.Types, overlay.Types), + Behaviors: mergeMaps(base.Behaviors, overlay.Behaviors), + InputTypes: mergeMaps(base.InputTypes, overlay.InputTypes), + ColumnSizes: mergeMaps(base.ColumnSizes, overlay.ColumnSizes), ArrayFormat: cmp.Or(overlay.ArrayFormat, base.ArrayFormat), NullableFormat: cmp.Or(overlay.NullableFormat, base.NullableFormat), EnumNullable: overlay.EnumNullable || base.EnumNullable, - ValueTypes: overlay.ValueTypes, - Literals: mergeLiterals(base.Literals, overlay.Literals), + ValueTypes: slices.Clone(overlay.ValueTypes), + Literals: mergeMaps(base.Literals, overlay.Literals), Array: ArrayLiteralSpec{ Open: cmp.Or(overlay.Array.Open, base.Array.Open), Close: cmp.Or(overlay.Array.Close, base.Array.Close), @@ -136,29 +149,27 @@ func mergeTypeMappings(base, overlay *typeMappings) *typeMappings { }, } if len(out.ValueTypes) == 0 { - out.ValueTypes = base.ValueTypes + out.ValueTypes = slices.Clone(base.ValueTypes) } return out } -func mergeLiterals(base, overlay map[string]LiteralSpec) map[string]LiteralSpec { - if len(base) == 0 && len(overlay) == 0 { +// mergeMaps overlays src on dst without mutating either input. Two empty maps +// merge to nil so bridges with no mapping keep a zero-valued result. +func mergeMaps[V any](dst, src map[string]V) map[string]V { + if len(dst) == 0 && len(src) == 0 { return nil } - m := make(map[string]LiteralSpec, len(base)+len(overlay)) - for k, v := range base { - m[k] = v - } - for k, v := range overlay { - m[k] = v - } + m := make(map[string]V, len(dst)+len(src)) + maps.Copy(m, dst) + maps.Copy(m, src) return m } // getBridgeSpecificFuncs loads type_mappings from every bridge in the chain // (base-first, adapter last) and merges them before building the language // functions, so an adapter inherits its base's type mapping and can override it. -func (r *Renderer) getBridgeSpecificFuncs() (map[string]interface{}, error) { +func (r *Renderer) getBridgeSpecificFuncs() (map[string]any, error) { var merged *typeMappings for _, src := range r.sources { m, err := r.loadTypeMappings(src.dir) @@ -170,46 +181,81 @@ func (r *Renderer) getBridgeSpecificFuncs() (map[string]interface{}, error) { return buildBridgeFuncs(merged, r.log), nil } +// formatSpec renders a bridge-declared printf spec. An absent spec yields an +// empty expression — the core never substitutes syntax a bridge did not declare. +func formatSpec(format string, args ...any) string { + if format == "" { + return "" + } + return fmt.Sprintf(format, args...) +} + +// dedupWarn emits each identical warning once per Render. A missing spec is +// discovered once per field otherwise, burying the useful diagnostics under +// dozens of identical lines. +type dedupWarn struct { + mu sync.Mutex + log *logger.Logger + seen map[string]bool +} + +func (w *dedupWarn) Warn(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + w.mu.Lock() + if w.seen[msg] { + w.mu.Unlock() + return + } + w.seen[msg] = true + w.mu.Unlock() + w.log.Warn("%s", msg) +} + +// warnMissingSpec reports a spec the bridge must declare in type_mappings.yaml. +// Logger.Warn is nil-safe, so silent mode needs no extra guard. +func warnMissingSpec(w *dedupWarn, kind, key string) { + w.Warn("type_mappings.yaml has no %s for %q; emitting an empty expression", kind, key) +} + // buildBridgeFuncs turns a merged type_mappings into the template func map that // bridges use to map IR types into language-specific code. A nil mapping (no // type_mappings.yaml anywhere in the chain) yields no bridge-specific funcs. -func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]interface{} { - bridgeFuncs := make(map[string]interface{}) +// Each registrar owns one group of keys; the map keys and closure behavior are +// the contract, so splitting the registrars does not change any value. +func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { + bridgeFuncs := make(map[string]any) if m == nil { return bridgeFuncs } - mapping := m - arrayFormat := mapping.ArrayFormat - if arrayFormat == "" { - arrayFormat = "%s[]" // default: generic array syntax (override in type_mappings.yaml for target language) - } - - nullableSuffix := mapping.NullableFormat - if nullableSuffix == "" { - nullableSuffix = "" // no default — bridges must set nullable_format explicitly - } + w := &dedupWarn{log: log, seen: make(map[string]bool)} + languageType := registerTypeFuncs(bridgeFuncs, m, w) + registerLiteralFuncs(bridgeFuncs, m, w, languageType) + registerValueFuncs(bridgeFuncs, m, w) + return bridgeFuncs +} +// registerTypeFuncs registers languageType and isValueType. It returns the +// languageType closure so the literal registrars reuse the very same mapping. +func registerTypeFuncs(funcs map[string]any, m *typeMappings, w *dedupWarn) func(string, bool) string { // wrapNullable applies the bridge-specific nullable format to a type name. wrapNullable := func(typeName string) string { - return typeName + nullableSuffix - } - - // Build set of value types for quick lookup - valueTypeSet := make(map[string]bool, len(mapping.ValueTypes)) - for _, vt := range mapping.ValueTypes { - valueTypeSet[vt] = true + return typeName + m.NullableFormat } // wrapArray wraps a type name in the bridge-specific array format. wrapArray := func(elementType string) string { - return fmt.Sprintf(arrayFormat, elementType) + if m.ArrayFormat == "" { + warnMissingSpec(w, "array_format", elementType) + return "" + } + return fmt.Sprintf(m.ArrayFormat, elementType) } // languageType maps IR database types to language-specific types via type_mappings.yaml languageType := func(dbType string, nullable bool) string { // Check explicit type mapping first (covers primitives and arrays) - if mapped, ok := mapping.Types[dbType]; ok { + if mapped, ok := m.Types[dbType]; ok { if nullable && !specmeta.IsArrayType(dbType) { return wrapNullable(mapped) } @@ -224,7 +270,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]interface{ if specmeta.IsArrayType(dbType) { return wrapArray(formatted) } - if nullable && mapping.EnumNullable { + if nullable && m.EnumNullable { return wrapNullable(formatted) } return formatted @@ -232,94 +278,189 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]interface{ // Primitive array not in explicit mapping — wrap inner type if specmeta.IsArrayType(dbType) { - if mapped, ok := mapping.Types[inner]; ok { + if mapped, ok := m.Types[inner]; ok { return wrapArray(mapped) } - log.Warn("type_mappings.yaml has no type for %q; emitting raw type name %q", inner, inner) + w.Warn("type_mappings.yaml has no type for %q; emitting raw type name %q", inner, inner) return wrapArray(inner) } - log.Warn("type_mappings.yaml has no type for %q; emitting raw type name %q", dbType, dbType) + w.Warn("type_mappings.yaml has no type for %q; emitting raw type name %q", dbType, dbType) return dbType } - bridgeFuncs["languageType"] = languageType + funcs["languageType"] = languageType + + // Build set of value types for quick lookup + valueTypeSet := make(map[string]bool, len(m.ValueTypes)) + for _, vt := range m.ValueTypes { + valueTypeSet[vt] = true + } + funcs["isValueType"] = func(typeName string) bool { + if mapped, ok := m.Types[typeName]; ok { + return valueTypeSet[mapped] + } + return false + } + return languageType +} + +// literalContext carries the bridge-owned specs and the shared formatter +// closure through one literal-formatting call. +type literalContext struct { + specs *typeMappings + warn *dedupWarn + languageType func(string, bool) string +} + +// kindFormatters holds the three literal operations for one seed kind. A nil +// operation falls back to the language-neutral JSON expression; that fallback +// is what an array value or an unknown kind gets from literalValue today. +type kindFormatters struct { + value func(*literalContext, string, any) string + def func(*literalContext, string) string + member func(*literalContext, string, string) string +} + +// literalFormattersByKind is the single kind → formatter table. Adding a kind +// means adding one row here, not editing three switch statements. +var literalFormattersByKind = map[seedKind]kindFormatters{ + seedArray: {def: arrayDefault}, + seedEnum: {value: enumLiteral, def: enumDefault, member: enumMember}, + seedText: {value: jsonLiteral, def: scalarDefault}, + seedInt: {value: numericLiteral, def: scalarDefault}, + seedBigInt: {value: numericLiteral, def: scalarDefault}, + seedFloat: {value: numericLiteral, def: scalarDefault}, + seedDecimal: {value: numericLiteral, def: scalarDefault}, + seedBool: {value: numericLiteral, def: scalarDefault}, + seedUUID: {value: parseLiteral, def: scalarDefault}, + seedDate: {value: parseLiteral, def: scalarDefault}, + seedDateTime: {value: parseLiteral, def: scalarDefault}, + seedJSON: {value: parseLiteral, def: scalarDefault}, +} + +func jsonLiteral(ctx *literalContext, _ string, value any) string { + return jsonValueOrFallback(ctx.warn, value) +} + +func numericLiteral(ctx *literalContext, dbType string, value any) string { + return fmt.Sprintf("%v", value) + ctx.specs.Literals[dbType].Suffix +} + +func parseLiteral(ctx *literalContext, dbType string, value any) string { + spec := ctx.specs.Literals[dbType] + if spec.Parse == "" { + warnMissingSpec(ctx.warn, "literals.parse", dbType) + return jsonValueOrFallback(ctx.warn, value) // JSON literal is language-neutral, not a target-language expression + } + return formatSpec(spec.Parse, jsonValueOrFallback(ctx.warn, value)) +} + +func enumLiteral(ctx *literalContext, dbType string, value any) string { + spec := ctx.specs.Literals["enum"] + if spec.Parse == "" { + warnMissingSpec(ctx.warn, "literals.enum.parse", dbType) + return jsonValueOrFallback(ctx.warn, value) + } + member := textutil.PascalCase(fmt.Sprintf("%v", value)) + return formatSpec(spec.Parse, ctx.languageType(dbType, false), jsonValueOrFallback(ctx.warn, member)) +} + +func scalarDefault(ctx *literalContext, dbType string) string { + spec := ctx.specs.Literals[dbType] + if spec.Default == "" { + warnMissingSpec(ctx.warn, "literals.default", dbType) + return "" + } + return spec.Default +} + +func enumDefault(ctx *literalContext, dbType string) string { + spec := ctx.specs.Literals[dbType] + if spec.Zero == "" { + spec = ctx.specs.Literals["enum"] // generic enum spec covers user-declared enums + } + if spec.Zero == "" { + warnMissingSpec(ctx.warn, "literals.zero", dbType) + return "" + } + return formatSpec(spec.Zero, ctx.languageType(dbType, false)) +} + +func arrayDefault(ctx *literalContext, dbType string) string { + if ctx.specs.Array.Empty == "" { + warnMissingSpec(ctx.warn, "array.empty", dbType) + return "" + } + return formatSpec(ctx.specs.Array.Empty, ctx.languageType(dbType, false)) +} + +func enumMember(ctx *literalContext, dbType, value string) string { + spec := ctx.specs.Literals["enum"] + if spec.Member == "" { + warnMissingSpec(ctx.warn, "literals.enum.member", dbType) + return "" + } + return formatSpec(spec.Member, ctx.languageType(dbType, false), textutil.PascalCase(value)) +} + +// registerLiteralFuncs registers the literal/array expression funcs. languageType +// is the closure returned by registerTypeFuncs; literal specs are bridge-owned. +func registerLiteralFuncs(funcs map[string]any, m *typeMappings, w *dedupWarn, languageType func(string, bool) string) { + ctx := &literalContext{specs: m, warn: w, languageType: languageType} // literalValue renders a scalar value of an IR database type as a bridge // literal/parse expression. value is a native Go value (string, int64, // float64, bool) or the raw string from a domain.yaml default. - bridgeFuncs["literalValue"] = func(dbType string, value any) string { - kind := ir.KindOf(dbType) - spec := mapping.Literals[dbType] - switch kind { - case "text": - return jsonValue(value) - case "int", "bigint", "float", "decimal", "bool": - return fmt.Sprintf("%v", value) + spec.Suffix - case "uuid", "date", "datetime", "json": - if spec.Parse == "" { - return jsonValue(value) - } - return fmt.Sprintf(spec.Parse, jsonValue(value)) - case "enum": - e := mapping.Literals["enum"] - if e.Parse == "" { - return jsonValue(value) - } - return fmt.Sprintf(e.Parse, languageType(dbType, false), jsonValue(textutil.PascalCase(fmt.Sprintf("%v", value)))) + funcs["literalValue"] = func(dbType string, value any) string { + f := literalFormattersByKind[kindOfSeed(dbType)] + if f.value == nil { + return jsonLiteral(ctx, dbType, value) } - return jsonValue(value) + return f.value(ctx, dbType, value) } // literalDefault renders the value-less default expression for a type: - // a scalar default, a zero-valued enum, or an empty array. - bridgeFuncs["literalDefault"] = func(dbType string) string { - if ir.KindOf(dbType) == "array" { - return fmt.Sprintf(mapping.Array.Empty, languageType(dbType, false)) - } - spec := mapping.Literals[dbType] - if ir.KindOf(dbType) == "enum" { - if spec.Zero != "" { - return fmt.Sprintf(spec.Zero, languageType(dbType, false)) - } - return fmt.Sprintf("(%s)0", languageType(dbType, false)) - } - if spec.Default == "" { - return "default(" + languageType(dbType, false) + ")" + // a scalar default, a zero-valued enum, or an empty array. Missing specs + // produce an empty expression and a warning; the core never invents one. + funcs["literalDefault"] = func(dbType string) string { + f := literalFormattersByKind[kindOfSeed(dbType)] + if f.def == nil { + return scalarDefault(ctx, dbType) } - return spec.Default + return f.def(ctx, dbType) } // literalMember renders a compile-time enum member reference (Type.Value), // used for enum defaults in domain.yaml. - bridgeFuncs["literalMember"] = func(dbType string, value string) string { - if ir.KindOf(dbType) == "enum" { - if spec := mapping.Literals["enum"]; spec.Member != "" { - return fmt.Sprintf(spec.Member, languageType(dbType, false), textutil.PascalCase(value)) - } - return languageType(dbType, false) + "." + textutil.PascalCase(value) + funcs["literalMember"] = func(dbType string, value string) string { + f := literalFormattersByKind[kindOfSeed(dbType)] + if f.member == nil { + return jsonLiteral(ctx, dbType, value) } - return jsonValue(value) + return f.member(ctx, dbType, value) } - // arrayLiteralOpen/Close wrap rendered elements in the bridge's array - // syntax (e.g. "new List { " ... " }"). - bridgeFuncs["arrayLiteralOpen"] = func(dbType string) string { - return fmt.Sprintf(mapping.Array.Open, languageType(dbType, false)) - } - bridgeFuncs["arrayLiteralClose"] = func() string { - return mapping.Array.Close - } - - bridgeFuncs["isValueType"] = func(typeName string) bool { - if mapped, ok := mapping.Types[typeName]; ok { - return valueTypeSet[mapped] + // arrayLiteralOpen/Close wrap rendered elements in the bridge's configured + // array delimiters. + funcs["arrayLiteralOpen"] = func(dbType string) string { + if m.Array.Open == "" { + warnMissingSpec(w, "array.open", dbType) + return "" } - return false + return formatSpec(m.Array.Open, languageType(dbType, false)) + } + funcs["arrayLiteralClose"] = func() string { + return m.Array.Close } +} - bridgeFuncs["deleteBehaviorName"] = func(value string) string { +// registerValueFuncs registers the remaining bridge-specific value/config +// helpers. columnSize and inputType are conditional: they exist only when the +// bridge declared the corresponding mapping (no core-side fallback is added). +func registerValueFuncs(funcs map[string]any, m *typeMappings, w *dedupWarn) { + funcs["deleteBehaviorName"] = func(value string) string { key := strings.ToLower(strings.TrimSpace(value)) - if v, ok := mapping.Behaviors[key]; ok { + if v, ok := m.Behaviors[key]; ok { return v } return textutil.PascalCase(value) @@ -331,35 +472,33 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]interface{ // they live in type_mappings.yaml `column_sizes:`, keyed by IR type name. // The input is the IR type name (element type for arrays, the field type // otherwise). - if len(mapping.ColumnSizes) > 0 { - bridgeFuncs["columnSize"] = func(dbType string) string { - return mapping.ColumnSizes[dbType] + if len(m.ColumnSizes) > 0 { + funcs["columnSize"] = func(dbType string) string { + return m.ColumnSizes[dbType] } } - // inputType maps IR database types to UI input components (e.g. "string" -> "Input", "datetime" -> "DatePicker"). - // Bridges that generate UI code define input_types in their type_mappings.yaml. - if len(mapping.InputTypes) > 0 { - bridgeFuncs["inputType"] = func(dbType string) string { + // inputType maps IR database types to UI input components. Bridges that + // generate UI code declare input_types in their type_mappings.yaml. + if len(m.InputTypes) > 0 { + funcs["inputType"] = func(dbType string) string { inner := specmeta.ParseArrayInner(dbType) - if mapped, ok := mapping.InputTypes[inner]; ok { + if mapped, ok := m.InputTypes[inner]; ok { return mapped } - if mapped, ok := mapping.InputTypes[dbType]; ok { + if mapped, ok := m.InputTypes[dbType]; ok { return mapped } - return "Input" + warnMissingSpec(w, "input type", dbType) + return "" } } - - return bridgeFuncs } -func renderTemplateString(pattern string, data any, funcMap template.FuncMap) (string, error) { - tpl, err := template.New("path").Funcs(funcMap).Parse(pattern) - if err != nil { - return "", err - } +// executeTemplateString renders an already-parsed template with one context. +// Target-path patterns are parsed once per spec by the render loop; parsing +// them for every entity would repeat identical work on the hot render path. +func executeTemplateString(tpl *template.Template, data any) (string, error) { var builder strings.Builder if err := tpl.Execute(&builder, data); err != nil { return "", err @@ -367,10 +506,25 @@ func renderTemplateString(pattern string, data any, funcMap template.FuncMap) (s return builder.String(), nil } -func jsonValue(value any) string { +// jsonValue serializes a value as a language-neutral JSON literal. A value +// json.Marshal cannot encode returns an error instead of silently emitting a +// plain-text fallback. text/template surfaces that error at execution time. +func jsonValue(value any) (string, error) { encoded, err := json.Marshal(value) if err != nil { + return "", fmt.Errorf("encode %T as JSON: %w", value, err) + } + return string(encoded), nil +} + +// jsonValueOrFallback is for literal formatters whose contract is to keep +// emitting an expression: it warns once about the bad value and falls back to +// the previous plain-text representation. +func jsonValueOrFallback(w *dedupWarn, value any) string { + encoded, err := jsonValue(value) + if err != nil { + w.Warn("%v; emitting the plain value %v", err, value) return fmt.Sprintf("%v", value) } - return string(encoded) -} \ No newline at end of file + return encoded +} diff --git a/internal/renderer/version_test.go b/internal/renderer/version_test.go index 446cdf1..ed564d5 100644 --- a/internal/renderer/version_test.go +++ b/internal/renderer/version_test.go @@ -3,26 +3,45 @@ package renderer import ( "strings" "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" ) +// TestContractVersionAliasesSpecmeta pins the single source of truth: a bridge +// that omits `contract_version` resolves to the specmeta contract, never a copy. +func TestContractVersionAliasesSpecmeta(t *testing.T) { + t.Parallel() + dir := writeBridgeConfig(t, "name: b\n") + r, err := New(dir, nil) + if err != nil { + t.Fatalf("New: %v", err) + } + if got := r.Config().ContractVersion; got != specmeta.ContractVersion { + t.Fatalf("default contract version = %d, specmeta.ContractVersion = %d", got, specmeta.ContractVersion) + } +} + // TestContractVersionMatrix is the compatibility oracle for bridge contracts: -// absent → 1 (accepted, deprecated); equal → accepted; newer → rejected whose a -// hard error naming both versions. This is the core guard against silent -// incompatibility between a bridge and the core. +// absent → the core version (accepted); older and equal → accepted; newer → +// rejected with a hard error naming both versions. This is the core guard +// against silent incompatibility between a bridge and the core. func TestContractVersionMatrix(t *testing.T) { + t.Parallel() cases := []struct { name string yaml string wantOK bool wantVer int }{ - {"absent defaults to 1", "name: b\n", true, 1}, - {"explicit 1 accepted", "name: b\ncontract_version: 1\n", true, 1}, - {"newer 2 rejected", "name: b\ncontract_version: 2\n", false, 0}, + {"absent defaults to current", "name: b\n", true, specmeta.ContractVersion}, + {"older 1 accepted", "name: b\ncontract_version: 1\n", true, 1}, + {"explicit current accepted", "name: b\ncontract_version: 2\n", true, 2}, + {"newer 3 rejected", "name: b\ncontract_version: 3\n", false, 0}, {"much newer 9 rejected", "name: b\ncontract_version: 9\n", false, 0}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, c.yaml) r, err := New(dir, nil) if c.wantOK { @@ -47,6 +66,7 @@ func TestContractVersionMatrix(t *testing.T) { // TestBridgeVersionParsed ensures the bridge `version:` field (independent per // bridge) is parsed and surfaced — it feeds the lock file and version reporting. func TestBridgeVersionParsed(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\nversion: \"2.3.4\"\n") r, err := New(dir, nil) if err != nil { @@ -61,7 +81,8 @@ func TestBridgeVersionParsed(t *testing.T) { // composed chain: an adapter that is fine must still fail when a base bridge // declares a newer contract. func TestNewerContractRejectedInBase(t *testing.T) { - base := writeBridgeConfig(t, "name: base\ncontract_version: 2\n") + t.Parallel() + base := writeBridgeConfig(t, "name: base\ncontract_version: 3\n") adapter := writeBridgeConfig(t, "name: adapter\nextends: "+base+"\n") r, err := New(adapter, nil) @@ -76,7 +97,8 @@ func TestNewerContractRejectedInBase(t *testing.T) { // TestMatchingContractAcceptedInBase is the positive control: an equal-contract // base attaches cleanly. func TestMatchingContractAcceptedInBase(t *testing.T) { - base := writeBridgeConfig(t, "name: base\ncontract_version: 1\n") + t.Parallel() + base := writeBridgeConfig(t, "name: base\ncontract_version: 2\n") adapter := writeBridgeConfig(t, "name: adapter\nextends: "+base+"\n") r, err := New(adapter, nil) diff --git a/internal/seed/seed.go b/internal/seed/seed.go index 3e82531..829ef7e 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -13,6 +13,7 @@ package seed import ( "fmt" + "math" "strconv" "strings" @@ -30,7 +31,10 @@ type Options struct { } // Generate builds deterministic mock seed for every entity in the project. -func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { +func Generate(project *ir.Project, opts Options) *ir.SeedDataset { + if project == nil { + return &ir.SeedDataset{} + } if opts.CountPerEntity <= 0 { opts.CountPerEntity = 2 } @@ -39,8 +43,8 @@ func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { // Primary keys generated so far, keyed by entity name, so FK references can // point at real, already-generated parent rows (project.Entities is already // topologically sorted by the IR builder). - generated := map[string][]interface{}{} - counter := opts.Seed + generated := map[string][]any{} + g := &genContext{project: project, generated: generated, counter: opts.Seed} for i := range project.Entities { entity := &project.Entities[i] @@ -56,14 +60,7 @@ func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { if field.IsSensitive() || field.IsFeatureField() { continue } - v := valueFor(field, entity, project, generated, &counter, n) - rec.Fields = append(rec.Fields, ir.SeedValue{ - Field: field.Name, - DBType: field.DatabaseType, - IsRelation: field.IsRelation, - IsMany: field.IsMany, - Value: v, - }) + rec.Fields = append(rec.Fields, seedValue(field, valueFor(g, field, n))) } em.Records = append(em.Records, rec) @@ -81,11 +78,23 @@ func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { return ds } +// seedValue is the single constructor for a typed seed field, shared by the +// generated and the developer-provided seed paths. +func seedValue(field ir.Field, value any) ir.SeedValue { + return ir.SeedValue{ + Field: field.Name, + DBType: field.DatabaseType, + IsRelation: field.IsRelation, + IsMany: field.IsMany, + Value: value, + } +} + // Normalize converts the developer's explicit `seed:` rows (raw maps) into the // same typed SeedRecord shape Generate produces. Values are coerced to native // Go types based on the field's IR database type, so a bridge serializes both // explicit and generated seed through one code path. -func Normalize(project *ir.IRProject) *ir.SeedDataset { +func Normalize(project *ir.Project) *ir.SeedDataset { if project == nil { return &ir.SeedDataset{} } @@ -105,13 +114,7 @@ func Normalize(project *ir.IRProject) *ir.SeedDataset { if !ok { continue } - rec.Fields = append(rec.Fields, ir.SeedValue{ - Field: field.Name, - DBType: field.DatabaseType, - IsRelation: field.IsRelation, - IsMany: field.IsMany, - Value: coerceValue(val, field.DatabaseType), - }) + rec.Fields = append(rec.Fields, seedValue(field, coerceValue(val, field.DatabaseType))) } em.Records = append(em.Records, rec) } @@ -121,7 +124,7 @@ func Normalize(project *ir.IRProject) *ir.SeedDataset { } // primaryKey returns the entity's primary key field, or nil. -func primaryKey(entity *ir.IREntity) *ir.IRField { +func primaryKey(entity *ir.Entity) *ir.Field { for i := range entity.Fields { if entity.Fields[i].IsPrimary { return &entity.Fields[i] @@ -130,67 +133,86 @@ func primaryKey(entity *ir.IREntity) *ir.IRField { return nil } +// genContext is the state shared by one mock-seed generation run: the project +// contract, the PKs generated so far (for FK references) and the UUID counter. +type genContext struct { + project *ir.Project + generated map[string][]any + counter int +} + // valueFor produces one field value for generated mock seed, honoring type, // validations, defaults and relations. -func valueFor(field ir.IRField, entity *ir.IREntity, project *ir.IRProject, generated map[string][]interface{}, counter *int, record int) interface{} { +func valueFor(g *genContext, field ir.Field, record int) any { // Default value wins when the model declares one (and it's not a function). if field.DefaultValue != "" && !field.DefaultIsFunc { + // The lexer stores `default:[a, b]` as a raw string; the same parser + // is used by coerceValue for developer-provided seed values. + if out, ok := coerceArrayDefault(field.DefaultValue, field.DatabaseType); ok { + return out + } return coerceValue(field.DefaultValue, field.DatabaseType) } if field.IsRelation { - return relationValue(field, generated) + return relationValue(g, field, record) } - return scalarValue(field, project, counter, record) + return scalarValue(g, field, record) } // relationValue returns a reference to an existing parent row. For a [many] // collection the value is nil (the child side owns the FK); for a single FK it -// returns the parent's primary-key value. When no parent was generated yet -// (self-reference or a dependency cycle) it falls back to nil. -func relationValue(field ir.IRField, generated map[string][]interface{}) interface{} { +// cycles through the parent's primary keys by record index, so a [unique] FK +// can back a one-to-one relation without colliding with a sibling row. When no +// parent was generated yet (self-reference or a dependency cycle) it falls +// back to nil. +func relationValue(g *genContext, field ir.Field, record int) any { if field.IsMany { return nil } - pks, ok := generated[field.RelationTarget] + pks, ok := g.generated[field.RelationTarget] if !ok || len(pks) == 0 { return nil } - return pks[0] + if record < 0 { + record = 0 + } + return pks[record%len(pks)] } // scalarValue produces a scalar value from the field's type and constraints. -func scalarValue(field ir.IRField, project *ir.IRProject, counter *int, record int) interface{} { +func scalarValue(g *genContext, field ir.Field, record int) any { dbType := field.DatabaseType if field.IsArray() { inner := specmeta.ParseArrayInner(dbType) - elem := innerValue(inner, field, project, counter, record) - return []interface{}{elem} + elem := innerValue(g, inner, field, record) + return []any{elem} } - switch dbType { + // FieldKind is the single classification shared with the validator and IR. + switch specmeta.FieldKind(strings.ToLower(dbType)) { case "uuid": - *counter = *counter + 1 - return fmt.Sprintf("00000000-0000-0000-0000-%012d", *counter) - case "string", "text": + g.counter++ + return fmt.Sprintf("00000000-0000-0000-0000-%012d", g.counter) + case "text": return stringValue(field, record) case "int", "bigint": return intValue(field, record) case "float", "decimal": return floatValue(field, record) - case "boolean": + case "bool": return true case "date": return "2024-01-01" case "datetime": return "2024-01-01T00:00:00Z" - case "json", "jsonb": + case "json": return "{}" default: // Enum (or unknown) — use the first declared value when available. - if values, ok := project.Enums[dbType]; ok && len(values) > 0 { + if values, ok := g.project.Enums[dbType]; ok && len(values) > 0 { return values[0] } return "" @@ -198,12 +220,12 @@ func scalarValue(field ir.IRField, project *ir.IRProject, counter *int, record i } // innerValue produces a scalar for an array element type. -func innerValue(dbType string, field ir.IRField, project *ir.IRProject, counter *int, record int) interface{} { - inner := ir.IRField{Name: field.Name, DatabaseType: dbType} +func innerValue(g *genContext, dbType string, field ir.Field, record int) any { + inner := ir.Field{Name: field.Name, DatabaseType: dbType} if specmeta.IsPrimitive(strings.ToLower(dbType)) { - return scalarValue(inner, project, counter, record) + return scalarValue(g, inner, record) } - if values, ok := project.Enums[dbType]; ok && len(values) > 0 { + if values, ok := g.project.Enums[dbType]; ok && len(values) > 0 { return values[0] } return "" @@ -211,7 +233,7 @@ func innerValue(dbType string, field ir.IRField, project *ir.IRProject, counter // stringValue returns a valid mock string, honoring email/url validations and // min/max length constraints (via the normalized ValidationRules contract). -func stringValue(field ir.IRField, record int) string { +func stringValue(field ir.Field, record int) string { isEmail, isURL := false, false minLen, maxLen := "", "" for _, r := range field.ValidationRules() { @@ -237,31 +259,61 @@ func stringValue(field ir.IRField, record int) string { v = fmt.Sprintf("mock_%s_%d", strings.ToLower(field.Name), record+1) } - if n, err := strconv.Atoi(minLen); err == nil && len(v) < n { + if n, err := strconv.Atoi(minLen); err == nil && n > 0 && len(v) < n { v += strings.Repeat("x", n-len(v)) } - if n, err := strconv.Atoi(maxLen); err == nil && len(v) > n { - v = v[:n] + // Clamp defensively: a hand-built IR may bypass the validator, so a + // negative max must never reach a slice index and an oversized max must + // never exceed the string length. + if n, err := strconv.Atoi(maxLen); err == nil { + v = v[:min(max(n, 0), len(v))] } return v } -// intValue returns an int honoring the numeric min/max bounds (inclusive or -// exclusive) from the normalized ValidationRules contract. -func intValue(field ir.IRField, record int) int64 { - v := int64(record + 1) - for _, r := range field.ValidationRules() { - n, err := strconv.ParseInt(r.Value, 10, 64) +// stepExclusiveInt64 moves one representable unit away from an exclusive +// integer bound. At MaxInt64/MinInt64 there is no next value, so adding or +// subtracting one would wrap to the opposite end; keep the bound instead. +func stepExclusiveInt64(v int64, delta int) int64 { + if delta > 0 { + if v == math.MaxInt64 { + return v + } + return v + 1 + } + if v == math.MinInt64 { + return v + } + return v - 1 +} + +// stepExclusiveFloat64 moves one unit away from an exclusive float bound. +// Float64 has no integer wraparound. +func stepExclusiveFloat64(v float64, delta int) float64 { + if delta > 0 { + return v + 1 + } + return v - 1 +} + +// clampNumericBounds applies the normalized min_value/max_value rules to a +// numeric mock value. An exclusive bound steps one unit past the bound; an +// inclusive bound lands on it. Rules are applied in their normalized order, +// each one clamping the current value. Int and float paths share this loop so +// their bound semantics cannot drift apart. +func clampNumericBounds[T ~int64 | ~float64](v T, rules []ir.ValidationRule, parse func(string) (T, error), step func(T, int) T) T { + for _, r := range rules { + n, err := parse(r.Value) if err != nil { continue } switch { case r.Kind == "min_value" && r.Exclusive && v <= n: - v = n + 1 + v = step(n, 1) case r.Kind == "min_value" && v < n: v = n case r.Kind == "max_value" && r.Exclusive && v >= n: - v = n - 1 + v = step(n, -1) case r.Kind == "max_value" && v > n: v = n } @@ -269,63 +321,80 @@ func intValue(field ir.IRField, record int) int64 { return v } +// intValue returns an int honoring the numeric min/max bounds (inclusive or +// exclusive) from the normalized ValidationRules contract. +func intValue(field ir.Field, record int) int64 { + parse := func(s string) (int64, error) { return strconv.ParseInt(s, 10, 64) } + return clampNumericBounds(int64(record+1), field.ValidationRules(), parse, stepExclusiveInt64) +} + // floatValue returns a float honoring the numeric min/max bounds (inclusive or // exclusive) from the normalized ValidationRules contract. -func floatValue(field ir.IRField, record int) float64 { - v := float64(record+1) + 0.5 - for _, r := range field.ValidationRules() { - n, err := strconv.ParseFloat(r.Value, 64) - if err != nil { - continue - } - switch { - case r.Kind == "min_value" && r.Exclusive && v <= n: - v = n + 1 - case r.Kind == "min_value" && v < n: - v = n - case r.Kind == "max_value" && r.Exclusive && v >= n: - v = n - 1 - case r.Kind == "max_value" && v > n: - v = n - } +func floatValue(field ir.Field, record int) float64 { + parse := func(s string) (float64, error) { return strconv.ParseFloat(s, 64) } + return clampNumericBounds(float64(record+1)+0.5, field.ValidationRules(), parse, stepExclusiveFloat64) +} + +// coerceArrayDefault parses a bracketed array default the same way for +// generated mock data and for developer-provided seed values. +func coerceArrayDefault(raw, dbType string) ([]any, bool) { + if !specmeta.IsArrayType(dbType) || !strings.HasPrefix(raw, "[") || !strings.HasSuffix(raw, "]") { + return nil, false } - return v + inner := specmeta.ParseArrayInner(dbType) + elements := specmeta.SplitArrayDefault(raw) + out := make([]any, 0, len(elements)) + for _, element := range elements { + out = append(out, coerceValue(element, inner)) + } + return out, true } // coerceValue converts a declared seed/default value (from YAML: string, number, // bool, list or map) to the field's native Go type. -func coerceValue(value interface{}, dbType string) interface{} { +func coerceValue(value any, dbType string) any { inner := specmeta.ParseArrayInner(dbType) // Arrays produce a slice of coerced elements. if specmeta.IsArrayType(dbType) { - if list, ok := value.([]interface{}); ok { - out := make([]interface{}, 0, len(list)) + if list, ok := value.([]any); ok { + out := make([]any, 0, len(list)) for _, item := range list { out = append(out, coerceValue(item, inner)) } return out } - return []interface{}{} + if raw, ok := value.(string); ok { + if out, parsed := coerceArrayDefault(raw, dbType); parsed { + return out + } + } + return []any{} } - switch { - case specmeta.IsNumeric(inner): - if inner == "int" || inner == "bigint" { - switch v := value.(type) { - case int: - return int64(v) - case int64: - return v - case float64: + switch specmeta.FieldKind(strings.ToLower(inner)) { + case "int", "bigint": + switch v := value.(type) { + case int: + return int64(v) + case int64: + return v + case float64: + // Truncation of a fraction is the established contract; wrapping an + // out-of-range float is not. Normalize accepts hand-built IR too, so + // guard the conversion against producing a value nobody declared. + const twoPow63 = 9223372036854775808.0 + if v >= -twoPow63 && v < twoPow63 { return int64(v) - case string: - if n, err := strconv.ParseInt(v, 10, 64); err == nil { - return n - } } return int64(0) + case string: + if n, err := strconv.ParseInt(v, 10, 64); err == nil { + return n + } } + return int64(0) + case "float", "decimal": switch v := value.(type) { case float64: return v @@ -339,7 +408,7 @@ func coerceValue(value interface{}, dbType string) interface{} { } } return float64(0) - case specmeta.IsBooleanType(inner): + case "bool": switch v := value.(type) { case bool: return v @@ -349,9 +418,7 @@ func coerceValue(value interface{}, dbType string) interface{} { } } return false - case inner == "uuid", inner == "string", inner == "text", inner == "date", inner == "datetime": - return fmt.Sprintf("%v", value) - case inner == "json", inner == "jsonb": + case specmeta.FieldKindJSON: return value // keep maps/slices/strings as-is for the bridge's JSON serializer default: // Enum value name (or unknown) — keep as a string. diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index 29ae41a..956cc26 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -1,6 +1,7 @@ package seed import ( + "math" "strings" "testing" @@ -8,13 +9,14 @@ import ( ) func TestGenerateBasicTypes(t *testing.T) { - project := &ir.IRProject{ + t.Parallel() + project := &ir.Project{ Enums: map[string][]string{"Status": {"pending", "active"}}, - Entities: []ir.IREntity{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, {Name: "price", DatabaseType: "decimal"}, @@ -37,7 +39,7 @@ func TestGenerateBasicTypes(t *testing.T) { } first := em.Records[0].Fields - vals := map[string]interface{}{} + vals := map[string]any{} for _, sv := range first { vals[sv.Field] = sv.Value } @@ -56,7 +58,7 @@ func TestGenerateBasicTypes(t *testing.T) { if vals["status"] != "pending" { t.Errorf("status = %v, want pending (first enum value)", vals["status"]) } - if arr, ok := vals["tags"].([]interface{}); !ok || len(arr) != 1 { + if arr, ok := vals["tags"].([]any); !ok || len(arr) != 1 { t.Errorf("tags should be a 1-element slice, got %#v", vals["tags"]) } if _, ok := vals["payload"].(string); !ok { @@ -64,18 +66,62 @@ func TestGenerateBasicTypes(t *testing.T) { } } +func TestGenerateHonorsArrayDefaults(t *testing.T) { + t.Parallel() + tests := []struct { + name string + dbType string + defaultVal string + want []any + }{ + {name: "string elements", dbType: "array(string)", defaultVal: "[alpha, beta]", want: []any{"alpha", "beta"}}, + {name: "int elements", dbType: "array(int)", defaultVal: "[1, 2]", want: []any{int64(1), int64(2)}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ + { + Name: "Tagged", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "tags", DatabaseType: tt.dbType, DefaultValue: tt.defaultVal}, + }, + }, + }, + } + ds := Generate(project, Options{CountPerEntity: 1}) + got := ds.Entities[0].Records[0].Fields[1].Value + arr, ok := got.([]any) + if !ok { + t.Fatalf("tags = %#v, want []any", got) + } + if len(arr) != len(tt.want) { + t.Fatalf("tags = %#v, want %#v", arr, tt.want) + } + for i := range tt.want { + if arr[i] != tt.want[i] { + t.Fatalf("tags[%d] = %#v, want %#v (full value %#v)", i, arr[i], tt.want[i], arr) + } + } + }) + } +} + func TestGenerateReferencesParentPK(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Category", NamePlural: "Categories", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "categoryId", DatabaseType: "uuid", IsRelation: true, RelationTarget: "Category"}, {Name: "images", DatabaseType: "uuid", IsRelation: true, IsMany: true, RelationTarget: "Image"}, @@ -85,7 +131,7 @@ func TestGenerateReferencesParentPK(t *testing.T) { } ds := Generate(project, Options{CountPerEntity: 1}) - var categoryPK interface{} + var categoryPK any for _, sv := range ds.Entities[0].Records[0].Fields { if sv.Field == "id" { categoryPK = sv.Value @@ -106,11 +152,12 @@ func TestGenerateReferencesParentPK(t *testing.T) { } func TestNormalizeCoercesTypes(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Doc", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "title", DatabaseType: "string"}, {Name: "count", DatabaseType: "int"}, @@ -118,14 +165,14 @@ func TestNormalizeCoercesTypes(t *testing.T) { {Name: "enabled", DatabaseType: "boolean"}, {Name: "tags", DatabaseType: "array(string)"}, }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ { "id": "550e8400-e29b-41d4-a716-446655440000", "title": "hello", "count": 7, "ratio": 2.5, "enabled": true, - "tags": []interface{}{"a", "b"}, + "tags": []any{"a", "b"}, }, }, }, @@ -136,7 +183,7 @@ func TestNormalizeCoercesTypes(t *testing.T) { if len(ds.Entities) != 1 { t.Fatalf("got %d entities, want 1", len(ds.Entities)) } - vals := map[string]interface{}{} + vals := map[string]any{} for _, sv := range ds.Entities[0].Records[0].Fields { vals[sv.Field] = sv.Value } @@ -149,16 +196,17 @@ func TestNormalizeCoercesTypes(t *testing.T) { if vals["enabled"] != true { t.Errorf("enabled = %#v, want true", vals["enabled"]) } - if arr, ok := vals["tags"].([]interface{}); !ok || len(arr) != 2 || arr[0] != "a" { + if arr, ok := vals["tags"].([]any); !ok || len(arr) != 2 || arr[0] != "a" { t.Errorf("tags = %#v, want [a b]", vals["tags"]) } } func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ - {Name: "Empty", Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}}, - {Name: "Seeded", Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, Seed: []map[string]interface{}{{"id": "x"}}}, + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ + {Name: "Empty", Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}}, + {Name: "Seeded", Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, Seed: []map[string]any{{"id": "x"}}}, }, } ds := Normalize(project) @@ -168,15 +216,16 @@ func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { } func TestNormalizeIncludesRelationFlags(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Order", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "customerId", DatabaseType: "uuid", IsRelation: true, RelationTarget: "Customer"}, }, - Seed: []map[string]interface{}{{"customerId": "550e8400-e29b-41d4-a716-446655440000"}}, + Seed: []map[string]any{{"customerId": "550e8400-e29b-41d4-a716-446655440000"}}, }, }, } @@ -191,25 +240,26 @@ func TestNormalizeIncludesRelationFlags(t *testing.T) { } func TestGenerateHonorsNumericBounds(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Bounds", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, - {Name: "qtyInclusiveMin", DatabaseType: "int", Validations: []ir.IRValidation{{Name: "gte", Value: "10"}}}, - {Name: "qtyExclusiveMin", DatabaseType: "int", Validations: []ir.IRValidation{{Name: "gt", Value: "5"}}}, - {Name: "qtyExclusiveMax", DatabaseType: "bigint", Validations: []ir.IRValidation{{Name: "lt", Value: "3"}}}, - {Name: "qtyClampedByExclusiveMax", DatabaseType: "int", Validations: []ir.IRValidation{{Name: "lt", Value: "1"}}}, - {Name: "priceInclusiveMax", DatabaseType: "decimal", Validations: []ir.IRValidation{{Name: "lte", Value: "0.25"}}}, + {Name: "qtyInclusiveMin", DatabaseType: "int", Validations: []ir.Validation{{Name: "gte", Value: "10"}}}, + {Name: "qtyExclusiveMin", DatabaseType: "int", Validations: []ir.Validation{{Name: "gt", Value: "5"}}}, + {Name: "qtyExclusiveMax", DatabaseType: "bigint", Validations: []ir.Validation{{Name: "lt", Value: "3"}}}, + {Name: "qtyClampedByExclusiveMax", DatabaseType: "int", Validations: []ir.Validation{{Name: "lt", Value: "1"}}}, + {Name: "priceInclusiveMax", DatabaseType: "decimal", Validations: []ir.Validation{{Name: "lte", Value: "0.25"}}}, }, }, }, } ds := Generate(project, Options{CountPerEntity: 2}) - vals := func(record int) map[string]interface{} { - m := map[string]interface{}{} + vals := func(record int) map[string]any { + m := map[string]any{} for _, sv := range ds.Entities[0].Records[record].Fields { m[sv.Field] = sv.Value } @@ -236,24 +286,78 @@ func TestGenerateHonorsNumericBounds(t *testing.T) { } } +// TestGenerateRespectsExclusiveBounds pins the mock value at the bound for +// inclusive rules and one unit past it for exclusive ones, across every +// numeric database type. Int/bigint start at record+1 (1 here), float/decimal +// at record+1+0.5 (1.5 here), so a bound equal to the base exercises the +// exclusive branch while an inclusive bound keeps the base unchanged. +func TestGenerateRespectsExclusiveBounds(t *testing.T) { + t.Parallel() + tests := []struct { + name string + dbType string + validations []ir.Validation + want any + }{ + {name: "int exclusive min steps above bound", dbType: "int", validations: []ir.Validation{{Name: "gt", Value: "5"}}, want: int64(6)}, + {name: "bigint exclusive min steps above bound", dbType: "bigint", validations: []ir.Validation{{Name: "gt", Value: "5"}}, want: int64(6)}, + {name: "int exclusive max steps below bound", dbType: "int", validations: []ir.Validation{{Name: "lt", Value: "1"}}, want: int64(0)}, + {name: "bigint exclusive max steps below bound", dbType: "bigint", validations: []ir.Validation{{Name: "lt", Value: "1"}}, want: int64(0)}, + {name: "int inclusive min holds bound", dbType: "int", validations: []ir.Validation{{Name: "gte", Value: "1"}}, want: int64(1)}, + {name: "bigint inclusive max holds bound", dbType: "bigint", validations: []ir.Validation{{Name: "lte", Value: "1"}}, want: int64(1)}, + {name: "float exclusive min steps above bound", dbType: "float", validations: []ir.Validation{{Name: "gt", Value: "1.5"}}, want: float64(2.5)}, + {name: "decimal exclusive min steps above bound", dbType: "decimal", validations: []ir.Validation{{Name: "gt", Value: "1.5"}}, want: float64(2.5)}, + {name: "float exclusive max steps below bound", dbType: "float", validations: []ir.Validation{{Name: "lt", Value: "1.5"}}, want: float64(0.5)}, + {name: "decimal exclusive max steps below bound", dbType: "decimal", validations: []ir.Validation{{Name: "lt", Value: "1.5"}}, want: float64(0.5)}, + {name: "float inclusive min holds bound", dbType: "float", validations: []ir.Validation{{Name: "gte", Value: "1.5"}}, want: float64(1.5)}, + {name: "decimal inclusive max holds bound", dbType: "decimal", validations: []ir.Validation{{Name: "lte", Value: "1.5"}}, want: float64(1.5)}, + {name: "int exclusive min at MaxInt64 saturates", dbType: "int", validations: []ir.Validation{{Name: "gt", Value: "9223372036854775807"}}, want: int64(math.MaxInt64)}, + {name: "bigint exclusive min at MaxInt64 saturates", dbType: "bigint", validations: []ir.Validation{{Name: "gt", Value: "9223372036854775807"}}, want: int64(math.MaxInt64)}, + {name: "int exclusive max at MinInt64 saturates", dbType: "int", validations: []ir.Validation{{Name: "lt", Value: "-9223372036854775808"}}, want: int64(math.MinInt64)}, + {name: "bigint exclusive max at MinInt64 saturates", dbType: "bigint", validations: []ir.Validation{{Name: "lt", Value: "-9223372036854775808"}}, want: int64(math.MinInt64)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + project := &ir.Project{ + Entities: []ir.Entity{ + { + Name: "Bounds", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "amount", DatabaseType: tt.dbType, Validations: tt.validations}, + }, + }, + }, + } + ds := Generate(project, Options{CountPerEntity: 1}) + got := ds.Entities[0].Records[0].Fields[1].Value + if got != tt.want { + t.Errorf("amount = %#v, want %#v", got, tt.want) + } + }) + } +} + func TestGenerateHonorsStringValidations(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Strings", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, - {Name: "email", DatabaseType: "string", Validations: []ir.IRValidation{{Name: "email"}}}, - {Name: "homepage", DatabaseType: "string", Validations: []ir.IRValidation{{Name: "url"}}}, - {Name: "padded", DatabaseType: "string", Validations: []ir.IRValidation{{Name: "min", Value: "30"}}}, - {Name: "short", DatabaseType: "string", Validations: []ir.IRValidation{{Name: "max", Value: "4"}}}, + {Name: "email", DatabaseType: "string", Validations: []ir.Validation{{Name: "email"}}}, + {Name: "homepage", DatabaseType: "string", Validations: []ir.Validation{{Name: "url"}}}, + {Name: "padded", DatabaseType: "string", Validations: []ir.Validation{{Name: "min", Value: "30"}}}, + {Name: "short", DatabaseType: "string", Validations: []ir.Validation{{Name: "max", Value: "4"}}}, }, }, }, } ds := Generate(project, Options{CountPerEntity: 1}) - vals := map[string]interface{}{} + vals := map[string]any{} for _, sv := range ds.Entities[0].Records[0].Fields { vals[sv.Field] = sv.Value } @@ -271,15 +375,19 @@ func TestGenerateHonorsStringValidations(t *testing.T) { } } +// Integral floats (1.0) survive coercion to int64; fractional floats are +// truncated (7.9 -> 7), and the validator rejects them before seed generation. func TestNormalizeCoerceEdgeCases(t *testing.T) { - project := &ir.IRProject{ + t.Parallel() + project := &ir.Project{ Enums: map[string][]string{"Status": {"draft", "live"}}, - Entities: []ir.IREntity{ + Entities: []ir.Entity{ { Name: "Edges", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "count", DatabaseType: "int"}, + {Name: "whole", DatabaseType: "int"}, {Name: "big", DatabaseType: "bigint"}, {Name: "ratio", DatabaseType: "float"}, {Name: "enabled", DatabaseType: "boolean"}, @@ -288,16 +396,17 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { {Name: "meta", DatabaseType: "jsonb"}, {Name: "status", DatabaseType: "Status"}, }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ { "id": "550e8400-e29b-41d4-a716-446655440000", "count": "not-a-number", + "whole": float64(1.0), "big": float64(7.9), "ratio": "also-not-a-number", "enabled": "not-a-bool", "tags": "oops-not-a-list", - "statuses": []interface{}{"draft", "live"}, - "meta": map[string]interface{}{"k": "v"}, + "statuses": []any{"draft", "live"}, + "meta": map[string]any{"k": "v"}, "status": "draft", }, }, @@ -306,15 +415,18 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { } ds := Normalize(project) - vals := map[string]interface{}{} + vals := map[string]any{} for _, sv := range ds.Entities[0].Records[0].Fields { vals[sv.Field] = sv.Value } if vals["count"] != int64(0) { t.Errorf("unparseable int = %#v, want the zero value int64(0)", vals["count"]) } + if vals["whole"] != int64(1) { + t.Errorf("integral float = %#v, want int64(1)", vals["whole"]) + } if vals["big"] != int64(7) { - t.Errorf("float for bigint = %#v, want truncated int64(7)", vals["big"]) + t.Errorf("fractional float for bigint = %#v, want truncated int64(7)", vals["big"]) } if vals["ratio"] != float64(0) { t.Errorf("unparseable float = %#v, want the zero value float64(0)", vals["ratio"]) @@ -322,14 +434,14 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { if vals["enabled"] != false { t.Errorf("unparseable bool = %#v, want false", vals["enabled"]) } - if arr, ok := vals["tags"].([]interface{}); !ok || len(arr) != 0 { + if arr, ok := vals["tags"].([]any); !ok || len(arr) != 0 { t.Errorf("non-list for an array field = %#v, want an empty slice", vals["tags"]) } - arr, ok := vals["statuses"].([]interface{}) + arr, ok := vals["statuses"].([]any) if !ok || len(arr) != 2 || arr[0] != "draft" { t.Errorf("enum array = %#v, want [draft live]", vals["statuses"]) } - if m, ok := vals["meta"].(map[string]interface{}); !ok || m["k"] != "v" { + if m, ok := vals["meta"].(map[string]any); !ok || m["k"] != "v" { t.Errorf("jsonb should keep its native shape, got %#v", vals["meta"]) } if vals["status"] != "draft" { @@ -337,12 +449,168 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { } } +func TestNormalizeOutOfRangeIntegralSeedDoesNotWrap(t *testing.T) { + t.Parallel() + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Edges", + Fields: []ir.Field{{Name: "big", DatabaseType: "bigint"}}, + Seed: []map[string]any{{"big": float64(1e30)}}, + }}} + ds := Normalize(project) + got := ds.Entities[0].Records[0].Fields[0].Value + if got != int64(0) { + t.Errorf("out-of-range float seed = %#v, want int64(0) instead of a wrapped value", got) + } +} + +func TestStepExclusiveInt64DoesNotWrapAtBounds(t *testing.T) { + t.Parallel() + if got := stepExclusiveInt64(math.MaxInt64, 1); got != math.MaxInt64 { + t.Errorf("step above MaxInt64 = %d, want MaxInt64", got) + } + if got := stepExclusiveInt64(math.MinInt64, -1); got != math.MinInt64 { + t.Errorf("step below MinInt64 = %d, want MinInt64", got) + } +} + +func TestGenerateClampsNonPositiveMaxLength(t *testing.T) { + t.Parallel() + tests := []struct { + name string + max string + want string + }{ + {name: "zero", max: "0", want: ""}, + {name: "negative", max: "-1", want: ""}, + {name: "oversized", max: "1000", want: "mock_name_1"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + project := &ir.Project{ + Entities: []ir.Entity{ + { + Name: "Item", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "name", DatabaseType: "string", Validations: []ir.Validation{{Name: "max", Value: tt.max}}}, + }, + }, + }, + } + + ds := Generate(project, Options{CountPerEntity: 1}) + got := ds.Entities[0].Records[0].Fields[1].Value + if got != tt.want { + t.Errorf("name = %v, want %q", got, tt.want) + } + }) + } +} + +// TestStringValueMaxLengthClamp pins the defensive max_length clamp on a +// hand-built field: an oversized max leaves the base string untouched, a zero +// (or negative) max empties it, and a smaller max truncates to that length. +func TestStringValueMaxLengthClamp(t *testing.T) { + t.Parallel() + const base = "mock_name_1" // len(base) == 11 + tests := []struct { + name string + max string + want string + }{ + {name: "max above length is a no-op", max: "1000", want: base}, + {name: "max equal to length is a no-op", max: "11", want: base}, + {name: "max zero is empty", max: "0", want: ""}, + {name: "max negative is empty", max: "-1", want: ""}, + {name: "max below length truncates", max: "4", want: "mock"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + field := ir.Field{ + Name: "name", + DatabaseType: "string", + Validations: []ir.Validation{{Name: "max", Value: tt.max}}, + } + got := stringValue(field, 0) + if got != tt.want { + t.Errorf("stringValue(max=%q) = %q, want %q", tt.max, got, tt.want) + } + }) + } +} + +func TestGenerateRotatesRelationPKs(t *testing.T) { + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ + { + Name: "Category", + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + }, + { + Name: "Product", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "categoryId", DatabaseType: "uuid", IsRelation: true, IsUnique: true, RelationTarget: "Category"}, + }, + }, + }, + } + + ds := Generate(project, Options{CountPerEntity: 3}) + parentPKs := make([]any, 0, 3) + for _, rec := range ds.Entities[0].Records { + parentPKs = append(parentPKs, rec.Fields[0].Value) + } + for i, rec := range ds.Entities[1].Records { + got := rec.Fields[1].Value + want := parentPKs[i%len(parentPKs)] + if got != want { + t.Errorf("record %d FK = %v, want %v", i, got, want) + } + } + if ds.Entities[1].Records[0].Fields[1].Value == ds.Entities[1].Records[1].Fields[1].Value { + t.Fatal("two children point at the same parent PK; unique FK rotation failed") + } +} + +func TestRelationValueRotatesParentPKs(t *testing.T) { + t.Parallel() + tests := []struct { + name string + field ir.Field + pks []any + record int + want any + }{ + {name: "first parent", field: ir.Field{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 0, want: "a"}, + {name: "second parent", field: ir.Field{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 1, want: "b"}, + {name: "wraps around", field: ir.Field{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 3, want: "a"}, + {name: "single parent", field: ir.Field{RelationTarget: "Category"}, pks: []any{"a"}, record: 5, want: "a"}, + {name: "no parents", field: ir.Field{RelationTarget: "Category"}, pks: nil, record: 2}, + {name: "many relation", field: ir.Field{RelationTarget: "Category", IsMany: true}, pks: []any{"a", "b"}, record: 0}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := &genContext{generated: map[string][]any{"Category": tt.pks}} + got := relationValue(g, tt.field, tt.record) + if got != tt.want { + t.Errorf("relationValue() = %v, want %v", got, tt.want) + } + }) + } +} + func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Defaults", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "country", DatabaseType: "string", DefaultValue: "DE"}, {Name: "attempts", DatabaseType: "int", DefaultValue: "3"}, @@ -352,7 +620,7 @@ func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { } ds := Generate(project, Options{CountPerEntity: 1}) - vals := map[string]interface{}{} + vals := map[string]any{} for _, sv := range ds.Entities[0].Records[0].Fields { vals[sv.Field] = sv.Value } diff --git a/internal/snapshot/hardening_test.go b/internal/snapshot/hardening_test.go new file mode 100644 index 0000000..c2b0c71 --- /dev/null +++ b/internal/snapshot/hardening_test.go @@ -0,0 +1,334 @@ +package snapshot + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/renderer" +) + +func TestDeleteFileIsIdempotent(t *testing.T) { + if err := DeleteFile(t.TempDir(), "already-gone.cs"); err != nil { + t.Fatalf("DeleteFile on a missing file = %v, want nil", err) + } +} + +func TestRenameEntityFileLeavesExistingDestination(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "ProductService.cs") + dst := filepath.Join(dir, "ItemService.cs") + if err := os.WriteFile(src, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(dst, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + _, renamed, err := RenameEntityFile(dir, "ProductService.cs", "Product", "Item") + if err != nil || renamed { + t.Fatalf("RenameEntityFile = %v, %v; want no rename", renamed, err) + } + data, err := os.ReadFile(dst) + if err != nil { + t.Fatal(err) + } + if string(data) != "keep" { + t.Errorf("destination overwritten: %q", data) + } + if _, err := os.Stat(src); err != nil { + t.Errorf("source removed despite existing destination: %v", err) + } +} + +func TestRenameEntityFileWithUnchangedNameIsNoop(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "ItemService.cs") + if err := os.WriteFile(path, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + newRel, renamed, err := RenameEntityFile(dir, "ItemService.cs", "Item", "Item") + if err != nil || renamed || newRel != "ItemService.cs" { + t.Fatalf("RenameEntityFile = %q, %v, %v; want unchanged no-op", newRel, renamed, err) + } +} + +func TestComputeDiffReportsSkippedManifestPaths(t *testing.T) { + old := &Snapshot{Files: []renderer.RenderedFile{{Path: "../escape.cs", Entity: "User", Custom: true}}} + var warnings []string + ComputeDiff(old, testProject("User"), t.TempDir(), func(format string, args ...any) { + warnings = append(warnings, fmt.Sprintf(format, args...)) + }) + if len(warnings) == 0 { + t.Fatal("unsafe manifest path was dropped without a warning") + } +} + +// R4: Save must leave a complete, parseable snapshot even when replacing an +// existing one (atomic write, no leftover temp files). +func TestSaveReplacesSnapshotWithoutTempLeftovers(t *testing.T) { + t.Parallel() + dir := t.TempDir() + path := Path(dir) + + if err := Save(path, New("demo", testProject("Product"), nil)); err != nil { + t.Fatalf("initial Save() error = %v", err) + } + if err := Save(path, New("demo", testProject("Item"), nil)); err != nil { + t.Fatalf("replacement Save() error = %v", err) + } + loaded, err := Load(path) + if err != nil { + t.Fatalf("saved snapshot is not valid JSON: %v", err) + } + if _, ok := loaded.Entities["Item"]; !ok { + t.Errorf("replacement snapshot lost the new entity: %+v", loaded.Entities) + } + entries, err := os.ReadDir(filepath.Dir(path)) + if err != nil { + t.Fatalf("read snapshot dir: %v", err) + } + for _, e := range entries { + if strings.Contains(e.Name(), ".tmp-") { + t.Errorf("leftover snapshot temp file: %s", e.Name()) + } + } +} + +// R5 (content): replacement text must never be rescanned, so an entity renamed +// to a name containing the old name cannot double-apply the plural variant. +func TestRewriteEntityContentDoesNotRescanReplacement(t *testing.T) { + t.Parallel() + tests := []struct { + name, in, want string + }{ + { + name: "plural and singular", + in: "Products Product ProductService", + want: "ProductItems ProductItem ProductItemService", + }, + { + name: "camel forms", + in: "var products = productService;", + want: "var productItems = productItemService;", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := string(RewriteEntityContent([]byte(tt.in), "Product", "ProductItem")) + if got != tt.want { + t.Errorf("rewrite\ngot: %q\nwant: %q", got, tt.want) + } + }) + } +} + +// R5 (path): RenameRelPath uses the same single-pass matcher, so plural/singular +// replacements in file paths cannot be applied twice. +func TestRenameRelPathDoesNotRescanReplacement(t *testing.T) { + t.Parallel() + tests := []struct { + name, in, want string + }{ + { + name: "plural controller", + in: "src/WebApi/Controllers/ProductsController.cs", + want: "src/WebApi/Controllers/ProductItemsController.cs", + }, + { + name: "singular entity", + in: "src/Domain/Entities/Product.cs", + want: "src/Domain/Entities/ProductItem.cs", + }, + { + name: "singular service", + in: "src/Services/ProductService.cs", + want: "src/Services/ProductItemService.cs", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := RenameRelPath(tt.in, "Product", "ProductItem"); got != tt.want { + t.Errorf("RenameRelPath(%q) = %q, want %q", tt.in, got, tt.want) + } + }) + } +} + +// R8: identifier boundaries must be rune-aware. Non-ASCII letters before the +// old token are identifier characters, so "caféProduct" must not be rewritten. +func TestRewriteEntityContentUnicodeIdentifierBoundaries(t *testing.T) { + t.Parallel() + tests := []struct { + name, in, want string + }{ + { + name: "latin accent before token", + in: "var caféProduct = 1; var Product = 2;", + want: "var caféProduct = 1; var Item = 2;", + }, + { + name: "cyrillic before token", + in: "var приветProduct = 1; var Product = 2;", + want: "var приветProduct = 1; var Item = 2;", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := string(RewriteEntityContent([]byte(tt.in), "Product", "Item")) + if got != tt.want { + t.Errorf("rewrite\ngot: %q\nwant: %q", got, tt.want) + } + }) + } +} + +// R6: --prune follows symlinks, so a snapshot path through a symlink that +// leaves the output tree must be rejected even though it is lexically local. +func TestSafeRelPathRejectsSymlinkEscape(t *testing.T) { + t.Parallel() + root := t.TempDir() + outside := t.TempDir() + if err := os.WriteFile(filepath.Join(outside, "victim.txt"), []byte("keep"), 0o644); err != nil { + t.Fatalf("write victim: %v", err) + } + if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + if _, err := safeRelPath(root, "escape/victim.txt"); err == nil { + t.Fatal("safeRelPath accepted a path that follows a symlink outside outputDir") + } +} + +// R7: every snapshot-supplied path (orphan files, custom files and namespace +// checks) goes through safeRelPath before os.Stat/os.ReadFile. +func TestComputeDiffIgnoresSnapshotPathsThroughSymlinks(t *testing.T) { + t.Parallel() + root := t.TempDir() + outside := t.TempDir() + victim := filepath.Join(outside, "victim.txt") + if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + + t.Run("orphan file list", func(t *testing.T) { + if err := os.WriteFile(victim, []byte("keep"), 0o644); err != nil { + t.Fatalf("write victim: %v", err) + } + old := &Snapshot{ + Entities: map[string]EntityState{"Product": {Fields: map[string]string{"id": "uuid"}}}, + Files: []renderer.RenderedFile{ + {Path: "escape/victim.txt", Entity: "Product", Custom: true}, + }, + } + diff := ComputeDiff(old, testProject("User"), root) + if len(diff.Deleted) != 1 { + t.Fatalf("got %d deleted entities, want 1", len(diff.Deleted)) + } + if len(diff.Deleted[0].Files) != 0 { + t.Errorf("symlink-escaped file leaked into orphan list: %+v", diff.Deleted[0].Files) + } + }) + + t.Run("namespace mismatch", func(t *testing.T) { + if err := os.WriteFile(victim, []byte("namespace OldNs.App;"), 0o644); err != nil { + t.Fatalf("write victim: %v", err) + } + old := &Snapshot{ + ProjectNamespace: "OldNs", + Files: []renderer.RenderedFile{ + {Path: "escape/victim.txt", Custom: true}, + }, + } + project := testProject("User") + project.Name = "NewNs" + if n := ComputeDiff(old, project, root).NamespaceRename; n != nil { + t.Errorf("symlink-escaped file leaked into namespace mismatch: %+v", n) + } + }) +} + +// Snapshot metadata must not carry a wall-clock timestamp: two runs on the +// same domain.yaml have to produce byte-identical output. +func TestSnapshotJSONHasNoTimestamp(t *testing.T) { + t.Parallel() + dir := t.TempDir() + path := Path(dir) + other := Path(filepath.Join(dir, "second-run")) + + if err := Save(path, New("demo", testProject("Product"), nil)); err != nil { + t.Fatalf("Save() error = %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("ReadFile() error = %v", err) + } + if strings.Contains(string(data), "created_at") { + t.Errorf("snapshot.json contains a wall-clock timestamp") + } + + // Identical input saved to a different path must produce identical bytes. + if err := Save(other, New("demo", testProject("Product"), nil)); err != nil { + t.Fatalf("second Save() error = %v", err) + } + otherData, err := os.ReadFile(other) + if err != nil { + t.Fatalf("ReadFile(second) error = %v", err) + } + if !bytes.Equal(data, otherData) { + t.Errorf("two saves of the same model differ:\nfirst: %s\nsecond: %s", data, otherData) + } +} + +// The mutation helpers must refuse symlinks even when the link stays inside +// outputDir: os.Root confines the operation, RefuseSymlinks rejects the link. +func TestDeleteFileRefusesInternalSymlink(t *testing.T) { + t.Parallel() + root := t.TempDir() + realDir := filepath.Join(root, "real") + if err := os.MkdirAll(realDir, 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + target := filepath.Join(realDir, "Product.cs") + if err := os.WriteFile(target, []byte("keep"), 0o644); err != nil { + t.Fatalf("write target: %v", err) + } + if err := os.Symlink(realDir, filepath.Join(root, "link")); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + if err := DeleteFile(root, "link/Product.cs"); err == nil { + t.Fatal("DeleteFile followed a symlink inside outputDir") + } + data, err := os.ReadFile(target) + if err != nil || string(data) != "keep" { + t.Errorf("DeleteFile removed the symlink target: data=%q err=%v", data, err) + } +} + +func TestRenameEntityFileRefusesBrokenSymlinkDestination(t *testing.T) { + t.Parallel() + root := t.TempDir() + source := filepath.Join(root, "ProductService.cs") + if err := os.WriteFile(source, []byte("custom"), 0o644); err != nil { + t.Fatalf("write source: %v", err) + } + dest := filepath.Join(root, "ItemService.cs") + if err := os.Symlink(filepath.Join(root, "missing-target"), dest); err != nil { + t.Skipf("symlinks unavailable on this host: %v", err) + } + _, renamed, err := RenameEntityFile(root, "ProductService.cs", "Product", "Item") + if err == nil { + t.Fatal("RenameEntityFile accepted a symlink as destination") + } + if renamed { + t.Error("rename reported success despite the symlink destination") + } + if _, err := os.Stat(source); err != nil { + t.Errorf("source was moved despite the symlink destination: %v", err) + } +} diff --git a/internal/snapshot/migration.go b/internal/snapshot/migration.go index 77ab297..1c54c80 100644 --- a/internal/snapshot/migration.go +++ b/internal/snapshot/migration.go @@ -18,40 +18,22 @@ import ( "github.com/DomainCraft/DomainCraft/pkg/textutil" ) -// tableName returns the snake_case plural table name for an entity name, the -// same convention the IR entity's NamePlural follows. -func tableName(entityName string) string { - return textutil.ToDatabaseColumnName(textutil.Pluralize(entityName)) -} - // ComputeMigrationPlan builds the abstract migration tree. -func ComputeMigrationPlan(old *Snapshot, project *ir.IRProject) *ir.MigrationPlan { +func ComputeMigrationPlan(old *Snapshot, project *ir.Project) *ir.MigrationPlan { plan := &ir.MigrationPlan{} if old == nil || project == nil { return plan } oldEntities := old.Entities - newByOldName := make(map[string]*ir.IREntity, len(project.Entities)) // old_name -> new entity - newByName := make(map[string]*ir.IREntity, len(project.Entities)) // name -> new entity - for i := range project.Entities { - e := &project.Entities[i] - newByName[e.Name] = e - if e.OldName != "" { - newByOldName[e.OldName] = e - } - } + idx := newEntityIndex(project) + newEntityNames := slices.Sorted(maps.Keys(idx.byName)) // --- table-level operations ------------------------------------------- // CreateTable: entity is new (not in the old model and not a rename). - newEntityNames := make([]string, 0, len(project.Entities)) - for _, e := range project.Entities { - newEntityNames = append(newEntityNames, e.Name) - } - slices.Sort(newEntityNames) for _, name := range newEntityNames { - e := newByName[name] + e := idx.byName[name] if _, existed := oldEntities[name]; existed { continue } @@ -60,61 +42,52 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.IRProject) *ir.MigrationPla continue // handled as a rename below } } - op := ir.MigrationOp{Kind: ir.OpCreateTable, Entity: e.Name, Table: tableName(e.Name)} + op := ir.MigrationOp{Kind: ir.OpCreateTable, Entity: e.Name, Table: e.TableName()} for _, f := range e.Fields { - column := f.ColumnName() - op.Columns = append(op.Columns, ir.MigrationColumn{ - Name: f.Name, - Column: column, - DBType: f.DatabaseType, - Nullable: f.IsNullable, - IsPrimary: f.IsPrimary, - IsRelation: f.IsRelation, - RelationTarget: f.RelationTarget, - }) + op.Columns = append(op.Columns, migrationColumn(f)) } plan.Operations = append(plan.Operations, op) } // RenameTable: entity declares old_name pointing at a previously existing entity. - renamedOldNames := make([]string, 0) - for oldName := range newByOldName { + renamedOldNames := make([]string, 0, len(idx.byOldName)) + for oldName := range idx.byOldName { if _, existed := oldEntities[oldName]; existed { renamedOldNames = append(renamedOldNames, oldName) } } slices.Sort(renamedOldNames) for _, oldName := range renamedOldNames { - e := newByOldName[oldName] + e := idx.byName[idx.byOldName[oldName]] plan.Operations = append(plan.Operations, ir.MigrationOp{ Kind: ir.OpRenameTable, Entity: e.Name, OldName: oldName, - Table: tableName(e.Name), - OldTable: tableName(oldName), + Table: e.TableName(), + OldTable: ir.TableNameFor(oldName), }) } // DropTable: entity existed before but is gone now (and not renamed). oldEntityNames := slices.Sorted(maps.Keys(oldEntities)) for _, name := range oldEntityNames { - if _, stillExists := newByName[name]; stillExists { + if _, stillExists := idx.byName[name]; stillExists { continue } - if _, renamed := newByOldName[name]; renamed { + if _, renamed := idx.byOldName[name]; renamed { continue } plan.Operations = append(plan.Operations, ir.MigrationOp{ Kind: ir.OpDropTable, Entity: name, - Table: tableName(name), + Table: ir.TableNameFor(name), }) } // --- column-level operations ----------------------------------------- // For entities that survive (same name, or renamed), diff their fields. for _, name := range newEntityNames { - e := newByName[name] + e := idx.byName[name] // The old state this entity corresponds to (rename resolution). oldName := name if e.OldName != "" { @@ -126,44 +99,73 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.IRProject) *ir.MigrationPla if !ok { continue // brand-new entity already handled by CreateTable } - diffColumns(plan, oldState, e) + diffColumns(plan, oldState, &e) } return plan } +// migrationColumn is the single projection from an IR field to a column +// descriptor, shared by CreateTable and AddColumn so new field attributes +// cannot be added to one path and forgotten in the other. +func migrationColumn(f ir.Field) ir.MigrationColumn { + return ir.MigrationColumn{ + Name: f.Name, + Column: f.ColumnName(), + DBType: f.DatabaseType, + Nullable: f.IsNullable, + IsPrimary: f.IsPrimary, + IsRelation: f.IsRelation, + RelationTarget: f.RelationTarget, + } +} + // diffColumns appends AddColumn / DropColumn / RenameColumn / AlterColumn ops // for one surviving entity. -func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { - oldFields := oldState.Fields // field name -> IR database type - newFieldByName := make(map[string]*ir.IRField, len(e.Fields)) +// fieldPointersByName is the migration plan's field index; the diff uses the +// type-only fieldsByName helper, so both agree on field names by construction. +func fieldPointersByName(e *ir.Entity) map[string]*ir.Field { + fields := make(map[string]*ir.Field, len(e.Fields)) for i := range e.Fields { f := &e.Fields[i] - newFieldByName[f.Name] = f + fields[f.Name] = f } + return fields +} - table := tableName(e.Name) +func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.Entity) { + oldFields := oldState.Fields // field name -> IR database type + newFieldByName := fieldPointersByName(e) - // RenameColumn: new field declares old_name pointing at a field that existed. - renamedFields := make([]string, 0) - for _, f := range e.Fields { + table := e.TableName() + + // A rename is only clean when the old field existed AND the new name was + // not already present in the previous model. Deciding this once here keeps + // RenameColumn, AddColumn and DropColumn in agreement — previously + // renameTarget omitted the shadow check and suppressed a needed DropColumn. + renamedFromOld := make(map[string]*ir.Field) + for i := range e.Fields { + f := &e.Fields[i] if f.OldName == "" { continue } - if _, existed := oldFields[f.OldName]; existed { - // Ambiguous: the new name also existed before — not a clean rename. - if _, shadowed := oldFields[f.Name]; shadowed { - continue - } - renamedFields = append(renamedFields, f.Name) + if _, existed := oldFields[f.OldName]; !existed { + continue + } + if _, shadowed := oldFields[f.Name]; shadowed { + continue } + renamedFromOld[f.OldName] = f } - slices.Sort(renamedFields) - for _, fieldName := range renamedFields { - f := newFieldByName[fieldName] - oldColumn := f.OldDatabaseColumnName + oldNames := slices.Sorted(maps.Keys(renamedFromOld)) + for _, oldName := range oldNames { + f := renamedFromOld[oldName] + // Prefer the column recorded in the snapshot: it is the canonical name + // (FK-aware, original name in a chained rename). Fall back for snapshots + // written before Columns existed. + oldColumn := oldState.Columns[oldName] if oldColumn == "" { - oldColumn = textutil.ToDatabaseColumnName(f.OldName) + oldColumn = f.OldColumnName() } newColumn := f.ColumnName() plan.Operations = append(plan.Operations, ir.MigrationOp{ @@ -173,7 +175,7 @@ func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { Column: newColumn, OldColumn: oldColumn, DBType: f.DatabaseType, - OldDBType: oldFields[f.OldName], + OldDBType: oldFields[oldName], }) // A rename that also changed type is two logical operations for most // migration systems (RenameColumn then AlterColumn). Emit both so a bridge @@ -195,27 +197,17 @@ func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { if _, existed := oldFields[f.Name]; existed { continue } - if f.OldName != "" { - if _, wasRenamed := oldFields[f.OldName]; wasRenamed { - continue // handled by RenameColumn above - } + if _, wasRenamed := renamedFromOld[f.OldName]; wasRenamed { + continue // handled by RenameColumn above } column := f.ColumnName() plan.Operations = append(plan.Operations, ir.MigrationOp{ - Kind: ir.OpAddColumn, - Entity: e.Name, - Table: table, - Column: column, - DBType: f.DatabaseType, - Columns: []ir.MigrationColumn{{ - Name: f.Name, - Column: column, - DBType: f.DatabaseType, - Nullable: f.IsNullable, - IsPrimary: f.IsPrimary, - IsRelation: f.IsRelation, - RelationTarget: f.RelationTarget, - }}, + Kind: ir.OpAddColumn, + Entity: e.Name, + Table: table, + Column: column, + DBType: f.DatabaseType, + Columns: []ir.MigrationColumn{migrationColumn(f)}, }) } @@ -225,14 +217,18 @@ func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { if _, stillExists := newFieldByName[fn]; stillExists { continue } - if renamedTo := renameTarget(e, fn); renamedTo != "" { + if _, wasRenamed := renamedFromOld[fn]; wasRenamed { continue } + column := oldState.Columns[fn] + if column == "" { + column = textutil.ToDatabaseColumnName(fn) + } plan.Operations = append(plan.Operations, ir.MigrationOp{ Kind: ir.OpDropColumn, Entity: e.Name, Table: table, - Column: textutil.ToDatabaseColumnName(fn), + Column: column, }) } @@ -255,13 +251,3 @@ func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { } } } - -// renameTarget returns the new field name that renames from oldField, or "". -func renameTarget(e *ir.IREntity, oldField string) string { - for i := range e.Fields { - if e.Fields[i].OldName == oldField { - return e.Fields[i].Name - } - } - return "" -} diff --git a/internal/snapshot/migration_test.go b/internal/snapshot/migration_test.go index b388a7c..56516e1 100644 --- a/internal/snapshot/migration_test.go +++ b/internal/snapshot/migration_test.go @@ -7,6 +7,7 @@ import ( ) func TestComputeMigrationPlanCreateAndDropTables(t *testing.T) { + t.Parallel() old := &Snapshot{ Entities: map[string]EntityState{ "Product": {Fields: map[string]string{"id": "uuid"}}, @@ -14,55 +15,53 @@ func TestComputeMigrationPlanCreateAndDropTables(t *testing.T) { }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, { Name: "Order", NamePlural: "Orders", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, }, } plan := ComputeMigrationPlan(old, project) - kinds := map[ir.MigrationOpKind]ir.MigrationOp{} - for _, op := range plan.Operations { - kinds[op.Kind] = op + // Exact slice: a map keyed by kind would hide duplicate or extra ops. + if len(plan.Operations) != 2 { + t.Fatalf("operations = %+v, want CreateTable(orders) then DropTable(legacies)", plan.Operations) } - - create, ok := kinds[ir.OpCreateTable] - if !ok || create.Table != "orders" { - t.Errorf("expected CreateTable(orders), got %+v", kinds[ir.OpCreateTable]) + create, drop := plan.Operations[0], plan.Operations[1] + if create.Kind != ir.OpCreateTable || create.Table != "orders" { + t.Errorf("first op = %+v, want CreateTable(orders)", create) } if len(create.Columns) != 1 || create.Columns[0].Column != "id" { t.Errorf("CreateTable should carry columns, got %+v", create.Columns) } - - drop, ok := kinds[ir.OpDropTable] - if !ok || drop.Table != "legacies" { - t.Errorf("expected DropTable(legacies), got %+v", kinds[ir.OpDropTable]) + if drop.Kind != ir.OpDropTable || drop.Table != "legacies" { + t.Errorf("second op = %+v, want DropTable(legacies)", drop) } } func TestComputeMigrationPlanRenameTable(t *testing.T) { + t.Parallel() old := &Snapshot{ Entities: map[string]EntityState{ "Product": {Fields: map[string]string{"id": "uuid"}}, }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, }, } @@ -78,6 +77,7 @@ func TestComputeMigrationPlanRenameTable(t *testing.T) { } func TestComputeMigrationPlanColumnOps(t *testing.T) { + t.Parallel() old := &Snapshot{ Entities: map[string]EntityState{ "Product": { @@ -91,12 +91,12 @@ func TestComputeMigrationPlanColumnOps(t *testing.T) { }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "name", @@ -113,6 +113,9 @@ func TestComputeMigrationPlanColumnOps(t *testing.T) { } plan := ComputeMigrationPlan(old, project) + if len(plan.Operations) != 4 { + t.Fatalf("operations = %+v, want exactly 4 (rename, alter, add, drop)", plan.Operations) + } byKind := map[ir.MigrationOpKind][]ir.MigrationOp{} for _, op := range plan.Operations { byKind[op.Kind] = append(byKind[op.Kind], op) @@ -146,28 +149,228 @@ func TestComputeMigrationPlanColumnOps(t *testing.T) { } } +// A relation field's DB column is the FK column (category -> category_id). +// The old snapshot did not keep column names, so DropColumn re-derived the name +// from the logical field and emitted DROP COLUMN category — a no-op that left +// the real FK column behind. New snapshots carry ir.Field.ColumnName(). +func TestDropColumnUsesCanonicalRelationColumn(t *testing.T) { + t.Parallel() + + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Product", + NamePlural: "Products", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true, DatabaseColumnName: "id"}, + {Name: "category", DatabaseType: "uuid", IsRelation: true, DatabaseColumnName: "category_id"}, + }, + }}} + snap := New("demo", project, nil) + state := snap.Entities["Product"] + if got := state.Columns["category"]; got != "category_id" { + t.Fatalf("snapshot column for relation field = %q, want category_id", got) + } + + // The relation field is gone from the current model. + project.Entities[0].Fields = project.Entities[0].Fields[:1] + plan := ComputeMigrationPlan(snap, project) + if len(plan.Operations) != 1 { + t.Fatalf("operations = %+v, want one DropColumn", plan.Operations) + } + op := plan.Operations[0] + if op.Kind != ir.OpDropColumn || op.Column != "category_id" { + t.Errorf("got %+v, want DropColumn(category_id)", op) + } +} + +// Snapshots written before Columns existed must keep working: the old +// snake_case fallback still applies to them. +func TestDropColumnFallsBackForLegacySnapshot(t *testing.T) { + t.Parallel() + old := &Snapshot{Entities: map[string]EntityState{ + "Product": {Fields: map[string]string{"category": "uuid"}}, + }} + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Product", + NamePlural: "Products", + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + }}} + plan := ComputeMigrationPlan(old, project) + var drop *ir.MigrationOp + for i := range plan.Operations { + if plan.Operations[i].Kind == ir.OpDropColumn { + drop = &plan.Operations[i] + } + } + if drop == nil || drop.Column != "category" { + t.Errorf("operations = %+v, want DropColumn(category)", plan.Operations) + } +} + +// A rename is ambiguous when the new field name already existed in the old +// model. renamedFields skipped such a rename, but renameTarget (used by the +// DropColumn pass) did not — so the old column was never dropped. +func TestShadowedRenameStillDropsOldColumn(t *testing.T) { + t.Parallel() + old := &Snapshot{Entities: map[string]EntityState{ + "Product": { + Fields: map[string]string{"id": "uuid", "title": "string", "name": "string"}, + Columns: map[string]string{"id": "id", "title": "title", "name": "name"}, + }, + }} + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Product", + NamePlural: "Products", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true, DatabaseColumnName: "id"}, + {Name: "name", OldName: "title", DatabaseType: "string", DatabaseColumnName: "name", OldDatabaseColumnName: "title"}, + }, + }}} + plan := ComputeMigrationPlan(old, project) + var drop *ir.MigrationOp + for i := range plan.Operations { + if plan.Operations[i].Kind == ir.OpDropColumn { + drop = &plan.Operations[i] + } + } + if drop == nil || drop.Column != "title" { + t.Errorf("operations = %+v, want DropColumn(title)", plan.Operations) + } +} + +// In a chained rename the physical column may be several names behind the +// declared old_name. Use the column recorded in the snapshot, not a re-derived +// snake_case of old_name, so RenameColumn targets a column that exists. +func TestChainedRenameUsesSnapshotColumn(t *testing.T) { + t.Parallel() + old := &Snapshot{Entities: map[string]EntityState{ + "Product": { + Fields: map[string]string{"id": "uuid", "title": "string"}, + Columns: map[string]string{"id": "id", "title": "original_title"}, + FieldOldNames: map[string]string{"title": "headline"}, + }, + }} + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Product", + NamePlural: "Products", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true, DatabaseColumnName: "id"}, + {Name: "heading", OldName: "title", DatabaseType: "string", DatabaseColumnName: "heading", OldDatabaseColumnName: "title"}, + }, + }}} + plan := ComputeMigrationPlan(old, project) + var rename *ir.MigrationOp + for i := range plan.Operations { + if plan.Operations[i].Kind == ir.OpRenameColumn { + rename = &plan.Operations[i] + } + } + if rename == nil || rename.OldColumn != "original_title" || rename.Column != "heading" { + t.Errorf("operations = %+v, want RenameColumn(original_title -> heading)", plan.Operations) + } +} + +// The rename report is developer-facing and must name the same physical +// columns as the migration plan. For a relation field that means FK columns. +func TestFieldRenameReportUsesCanonicalColumns(t *testing.T) { + t.Parallel() + old := &Snapshot{Entities: map[string]EntityState{ + "Product": { + Fields: map[string]string{"id": "uuid", "category": "uuid"}, + Columns: map[string]string{"id": "id", "category": "category_id"}, + }, + }} + project := &ir.Project{Entities: []ir.Entity{{ + Name: "Product", + NamePlural: "Products", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true, DatabaseColumnName: "id"}, + {Name: "cat", OldName: "category", DatabaseType: "uuid", IsRelation: true, DatabaseColumnName: "category_id"}, + }, + }}} + diff := ComputeDiff(old, project, t.TempDir()) + if len(diff.FieldRenames) != 1 { + t.Fatalf("field renames = %+v, want 1", diff.FieldRenames) + } + fr := diff.FieldRenames[0] + if fr.OldColumn != "category_id" || fr.NewColumn != "cat_id" { + t.Errorf("columns = %s -> %s, want category_id -> cat_id", fr.OldColumn, fr.NewColumn) + } +} + +// The migration plan used to derive table names with its own +// ToDatabaseColumnName(Pluralize(...)) helper. It must agree with the IR's +// TableName()/TableNameFor on acronym names, where a hand-rolled snake_case +// diverges (IPv4Address -> i_pv4addresses, not i_pv4_addresses). +func TestMigrationPlanTableNameMatchesIRForAcronymEntity(t *testing.T) { + t.Parallel() + const name = "IPv4Address" + const oldName = "IPv6Address" + + entity := ir.Entity{ + Name: name, + NamePlural: "IPv4Addresses", + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + } + if got := entity.TableName(); got != "i_pv4addresses" { + t.Fatalf("Entity.TableName() = %q, want i_pv4addresses", got) + } + if got := ir.TableNameFor(name); got != entity.TableName() { + t.Errorf("TableNameFor(%q) = %q, want %q", name, got, entity.TableName()) + } + + t.Run("rename table", func(t *testing.T) { + old := &Snapshot{Entities: map[string]EntityState{oldName: {Fields: map[string]string{"id": "uuid"}}}} + renamed := entity + renamed.OldName = oldName + plan := ComputeMigrationPlan(old, &ir.Project{Entities: []ir.Entity{renamed}}) + if len(plan.Operations) != 1 || plan.Operations[0].Kind != ir.OpRenameTable { + t.Fatalf("operations = %+v, want one RenameTable", plan.Operations) + } + op := plan.Operations[0] + if op.Table != renamed.TableName() || op.OldTable != ir.TableNameFor(oldName) { + t.Errorf("rename = %s -> %s, want %s -> %s", op.OldTable, op.Table, ir.TableNameFor(oldName), renamed.TableName()) + } + if op.OldTable != "i_pv6addresses" { + t.Errorf("OldTable = %q, want i_pv6addresses", op.OldTable) + } + }) + + t.Run("drop table", func(t *testing.T) { + old := &Snapshot{Entities: map[string]EntityState{name: {Fields: map[string]string{"id": "uuid"}}}} + plan := ComputeMigrationPlan(old, &ir.Project{}) + if len(plan.Operations) != 1 || plan.Operations[0].Kind != ir.OpDropTable { + t.Fatalf("operations = %+v, want one DropTable", plan.Operations) + } + if got := plan.Operations[0].Table; got != ir.TableNameFor(name) { + t.Errorf("DropTable table = %q, want %q", got, ir.TableNameFor(name)) + } + }) +} + func TestComputeMigrationPlanNilInputs(t *testing.T) { + t.Parallel() if plan := ComputeMigrationPlan(nil, nil); !plan.IsEmpty() { t.Error("nil inputs should produce an empty plan") } - if plan := ComputeMigrationPlan(&Snapshot{}, &ir.IRProject{}); !plan.IsEmpty() { + if plan := ComputeMigrationPlan(&Snapshot{}, &ir.Project{}); !plan.IsEmpty() { t.Error("empty inputs should produce an empty plan") } } func TestComputeMigrationPlanRenameWithTypeChange(t *testing.T) { + t.Parallel() // A field renamed AND retyped must emit RenameColumn + AlterColumn, not Drop+Add. old := &Snapshot{ Entities: map[string]EntityState{ "Product": {Fields: map[string]string{"id": "uuid", "title": "string"}}, }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "name", diff --git a/internal/snapshot/paths.go b/internal/snapshot/paths.go new file mode 100644 index 0000000..d5accf0 --- /dev/null +++ b/internal/snapshot/paths.go @@ -0,0 +1,68 @@ +package snapshot + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/DomainCraft/DomainCraft/internal/fsutil" +) + +// safeRelPath resolves a snapshot file path against outputDir and rejects +// anything that escapes it. The snapshot lives in the output directory, is +// often shared or committed, and --prune applies its paths without prompting; +// a "path": "../../..." entry must never reach os.Remove, os.Rename or a write. +// +// It uses the same symlink policy as the renderer and the mutation helpers: +// every existing component, including outputDir itself, must be a real +// directory or file. A link that resolves back inside outputDir is refused too, +// so a snapshot path means the same thing for reads, writes and cleanup. +func safeRelPath(outputDir, relPath string) (string, error) { + abs, _, err := fsutil.LocalPathWithin(outputDir, relPath) + if err != nil { + return "", fmt.Errorf("unsafe snapshot path %q: %w", relPath, err) + } + absOutput, err := filepath.Abs(outputDir) + if err != nil { + return "", fmt.Errorf("resolve output dir %q: %w", outputDir, err) + } + if err := fsutil.RefuseSymlinks(absOutput, abs); err != nil { + return "", fmt.Errorf("unsafe snapshot path %q: %w", relPath, err) + } + return abs, nil +} + +// openRootFor validates relPath against outputDir and returns a root confined +// to that directory plus the OS-form path relative to it. Mutating operations +// must use the returned root so a component replaced by a symlink after the +// lexical and symlink checks cannot redirect the write or delete. +// withRoot runs fn with one output-confined root and always closes it, even +// when fn fails. Two-root mutations nest calls in source -> destination order, +// so the close order stays the reverse of the open order. +func withRoot(outputDir, relPath string, fn func(*os.Root, string) error) error { + root, rel, err := openRootFor(outputDir, relPath) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + return fn(root, rel) +} + +func openRootFor(outputDir, relPath string) (*os.Root, string, error) { + // LocalPathWithin covers lexical containment; OpenRootFor performs the + // symlink check and pins the verified base. Calling safeRelPath here would + // run the symlink walk twice on every mutation. + absOutput, err := filepath.Abs(outputDir) + if err != nil { + return nil, "", fmt.Errorf("resolve output dir %q: %w", outputDir, err) + } + abs, _, err := fsutil.LocalPathWithin(absOutput, relPath) + if err != nil { + return nil, "", fmt.Errorf("unsafe snapshot path %q: %w", relPath, err) + } + root, rel, err := fsutil.OpenRootFor(absOutput, abs) + if err != nil { + return nil, "", fmt.Errorf("unsafe snapshot path %q: %w", relPath, err) + } + return root, rel, nil +} diff --git a/internal/snapshot/paths_test.go b/internal/snapshot/paths_test.go new file mode 100644 index 0000000..e75146e --- /dev/null +++ b/internal/snapshot/paths_test.go @@ -0,0 +1,104 @@ +package snapshot + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { + t.Parallel() + root := t.TempDir() + absRoot, err := filepath.Abs(root) + if err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + path string + wantErr bool + }{ + {name: "plain path", path: "src/File.cs"}, + {name: "dot", path: "."}, + {name: "parent escape", path: "../../.ssh/authorized_keys", wantErr: true}, + {name: "absolute path", path: "/etc/passwd", wantErr: true}, + } + + if runtime.GOOS == "windows" { + tests = append(tests, struct { + name string + path string + wantErr bool + }{name: "drive path", path: `C:\Users\secret`, wantErr: true}) + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, err := safeRelPath(root, tt.path) + if (err != nil) != tt.wantErr { + t.Fatalf("safeRelPath(%q) error = %v, wantErr %v", tt.path, err, tt.wantErr) + } + if err == nil && !strings.HasPrefix(got, absRoot+string(filepath.Separator)) && got != absRoot { + t.Fatalf("safeRelPath(%q) = %q, outside %q", tt.path, got, absRoot) + } + }) + } +} + +func TestDeleteFileRejectsSnapshotEscape(t *testing.T) { + t.Parallel() + root := t.TempDir() + victim := filepath.Join(filepath.Dir(root), "dc-victim-"+filepath.Base(root)+".txt") + if err := os.WriteFile(victim, []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + + err := DeleteFile(root, "../"+filepath.Base(victim)) + if err == nil { + t.Fatal("DeleteFile accepted a path outside outputDir") + } + data, err := os.ReadFile(victim) + if err != nil || string(data) != "keep" { + t.Fatalf("victim changed: data=%q err=%v", data, err) + } +} + +func TestReplaceScaffoldedFileRejectsSnapshotEscape(t *testing.T) { + t.Parallel() + root := t.TempDir() + victim := filepath.Join(filepath.Dir(root), "dc-replace-victim-"+filepath.Base(root)+".txt") + if err := os.WriteFile(victim, []byte("Product"), 0o600); err != nil { + t.Fatal(err) + } + + err := ReplaceScaffoldedFile(root, "../"+filepath.Base(victim), "dest.txt", EntityTransform("Product", "Item")) + if err == nil { + t.Fatal("ReplaceScaffoldedFile accepted a source path outside outputDir") + } + data, err := os.ReadFile(victim) + if err != nil || string(data) != "Product" { + t.Fatalf("victim changed: data=%q err=%v", data, err) + } +} + +func TestRewriteFileRejectsSnapshotEscape(t *testing.T) { + t.Parallel() + root := t.TempDir() + victim := filepath.Join(filepath.Dir(root), "dc-rewrite-victim-"+filepath.Base(root)+".txt") + if err := os.WriteFile(victim, []byte("Product"), 0o600); err != nil { + t.Fatal(err) + } + + written, err := RewriteFile(root, "../"+filepath.Base(victim), EntityTransform("Product", "Item")) + if err == nil || written { + t.Fatalf("RewriteFile accepted a path outside outputDir: written=%v err=%v", written, err) + } + data, err := os.ReadFile(victim) + if err != nil || string(data) != "Product" { + t.Fatalf("victim changed: data=%q err=%v", data, err) + } +} diff --git a/internal/snapshot/rewrite.go b/internal/snapshot/rewrite.go index d6beec0..271de9e 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -10,153 +10,166 @@ package snapshot // Python or a bare `product` in TS are all rewritten by the same rules. import ( - "bytes" "cmp" "os" - "path/filepath" "slices" "strings" + "unicode" + "unicode/utf8" "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) -// rewriteCasings replaces each old identifier with new inside content. Variants -// are applied longest-first (so a plural form like `Products` is rewritten as a -// whole before its singular head `Product` could consume it), then -// alphabetically, keeping output deterministic. -func rewriteCasings(content []byte, variants map[string]string) []byte { +// replaceLongest scans content once, decoding it as runes so non-ASCII +// identifiers are handled correctly. At each position the longest matching +// variant that passes ok is applied (ties break alphabetically for determinism) +// and unmatched runes are copied verbatim. Scanning resumes after the ORIGINAL +// token, so replacement text is never rescanned: Product -> ProductItem cannot +// turn `Products` into `ProductItemItems`. +// onMatch is optional: a caller that only needs to know whether a token is +// present can stop at the first match instead of allocating a rewritten copy. +func replaceLongest(content []byte, variants map[string]string, ok func([]rune, int, int) bool, onMatch ...func([]byte) bool) []byte { if len(variants) == 0 { return content } - keys := make([]string, 0, len(variants)) - for k := range variants { - keys = append(keys, k) + type variant struct { + old []rune + value []rune + valueBytes []byte } - slices.SortFunc(keys, func(a, b string) int { - if c := cmp.Compare(len(b), len(a)); c != 0 { + vars := make([]variant, 0, len(variants)) + for old, value := range variants { + if old == "" || old == value { + continue + } + vars = append(vars, variant{old: []rune(old), value: []rune(value), valueBytes: []byte(value)}) + } + slices.SortFunc(vars, func(a, b variant) int { + if c := cmp.Compare(len(b.old), len(a.old)); c != 0 { return c } - return cmp.Compare(a, b) + return cmp.Compare(string(a.old), string(b.old)) }) - out := content - for _, old := range keys { - new := variants[old] - if old == "" || old == new { - continue - } - out = replaceToken(out, []byte(old), []byte(new)) - } - return out -} - -// replaceToken replaces every structural occurrence of the exact identifier old -// with new. An occurrence begins at an identifier boundary (not preceded by an -// identifier character) and stops before any identifier character that is a -// lowercase ASCII letter. This lets `ProductService` become `ItemService` while -// both `myProduct` (inner) and `Productivity` (lowercase continuation) survive. -func replaceToken(content, old, new []byte) []byte { - if len(old) == 0 { - return content + // Decode for matching only. Unmatched positions are copied from the + // original bytes: []rune(string(content)) would replace invalid UTF-8 with + // U+FFFD and silently corrupt developer-owned files in legacy encodings. + rs := make([]rune, 0, len(content)) + starts := make([]int, 0, len(content)) + for i := 0; i < len(content); { + r, size := utf8.DecodeRune(content[i:]) + rs = append(rs, r) + starts = append(starts, i) + i += size } out := make([]byte, 0, len(content)) - i := 0 - for i < len(content) { - rel := bytes.Index(content[i:], old) - if rel < 0 { - out = append(out, content[i:]...) + for i := 0; i < len(rs); { + matched := false + for _, v := range vars { + if i+len(v.old) > len(rs) { + continue + } + if !hasPrefixRunes(rs[i:], v.old) { + continue + } + if !ok(rs, i, len(v.old)) { + continue + } + if len(onMatch) > 0 && onMatch[0] != nil && onMatch[0](v.valueBytes) { + return content + } + out = append(out, v.valueBytes...) + i += len(v.old) // replacement text is never scanned again + matched = true break } - idx := i + rel - out = append(out, content[i:idx]...) - if tokenOK(content, idx, old) { - out = append(out, new...) - } else { - out = append(out, old...) + if !matched { + end := len(content) + if i+1 < len(rs) { + end = starts[i+1] + } + out = append(out, content[starts[i]:end]...) + i++ } - i = idx + len(old) } return out } -// tokenOK reports whether content[idx:idx+len(old)] is a standalone identifier -// occurrence. An occurrence must begin at a word boundary (possibly after a -// single uppercase marker/interface prefix such as `I` in `IProductService`, so -// that `myProduct` stays untouched) and its following rune, when it is an -// identifier character, must not be a lowercase ASCII letter (so `Productivity` -// survives). -func tokenOK(content []byte, idx int, old []byte) bool { - if idx > 0 { - prev := content[idx-1] - // A lone uppercase prefix letter counts as a boundary (I, X, Z prefixes). - prefixOK := prev >= 'A' && prev <= 'Z' && (idx < 2 || !isIdentChar(content[idx-2])) - if isIdentChar(prev) && !prefixOK { - return false - } +func hasPrefixRunes(s, prefix []rune) bool { + if len(prefix) > len(s) { + return false } - j := idx + len(old) - if j < len(content) && isIdentChar(content[j]) { - if content[j] >= 'a' && content[j] <= 'z' { + for i, r := range prefix { + if s[i] != r { return false } } return true } -func isIdentChar(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' -} - -// entityCasings builds the casing-variant table for an entity rename. -func entityCasings(oldName, newName string) map[string]string { - oldPascal := textutil.PascalCase(oldName) - newPascal := textutil.PascalCase(newName) - return map[string]string{ - oldPascal: newPascal, // Product -> Item - textutil.CamelCase(oldName): textutil.CamelCase(newName), // product -> item - strings.ToUpper(oldPascal): strings.ToUpper(newPascal), // PRODUCT -> ITEM - textutil.Pluralize(oldPascal): textutil.Pluralize(newPascal), // Products -> Items - textutil.CamelCase(textutil.Pluralize(oldName)): textutil.CamelCase(textutil.Pluralize(newName)), // products -> items - strings.ToUpper(textutil.Pluralize(oldPascal)): strings.ToUpper(textutil.Pluralize(newPascal)), // PRODUCTS -> ITEMS +// tokenOK reports whether rs[idx:idx+length] is a standalone identifier +// occurrence. It begins at a word boundary (possibly after a single uppercase +// marker prefix such as `I` in `IProductService`, so `myProduct` stays +// untouched) and its following rune, when it is an identifier character, must +// not be a lowercase letter (so `Productivity` survives). Rune decoding keeps +// this correct for non-ASCII identifiers. +func tokenOK(rs []rune, idx, length int) bool { + if idx > 0 { + prev := rs[idx-1] + prefixOK := unicode.IsUpper(prev) && (idx < 2 || !specmeta.IsIdentifierRune(rs[idx-2])) + if specmeta.IsIdentifierRune(prev) && !prefixOK { + return false + } } -} - -// fieldCasings builds the casing-variant table for a field rename. -func fieldCasings(oldField, newField string) map[string]string { - oldPascal := textutil.PascalCase(oldField) - newPascal := textutil.PascalCase(newField) - return map[string]string{ - oldPascal: newPascal, // Title -> Name - textutil.CamelCase(oldField): textutil.CamelCase(newField), // title -> name - strings.ToUpper(oldPascal): strings.ToUpper(newPascal), // TITLE -> NAME + j := idx + length + if j < len(rs) { + next := rs[j] + if specmeta.IsIdentifierRune(next) && unicode.IsLower(next) { + return false + } } + return true } -// namespaceCasings builds the casing-variant table for a root-namespace rename. -func namespaceCasings(oldNs, newNs string) map[string]string { - return map[string]string{ - oldNs: newNs, - textutil.CamelCase(oldNs): textutil.CamelCase(newNs), - strings.ToUpper(oldNs): strings.ToUpper(newNs), - } +// casingVariants builds the one casing-variant table used by every rename +// rewrite (content and paths). Callers pass the base form they need: PascalCase +// for entities and fields, the declared identifier for a project namespace. +// withPlural adds the plural forms on top of Pascal / camel / UPPER. +func casingVariants(oldName, newName string, withPlural bool) map[string]string { + variants := map[string]string{ + oldName: newName, // Product -> Item + textutil.CamelCase(oldName): textutil.CamelCase(newName), // product -> item + strings.ToUpper(oldName): strings.ToUpper(newName), // PRODUCT -> ITEM + } + if withPlural { + oldPlural := textutil.Pluralize(oldName) + newPlural := textutil.Pluralize(newName) + variants[oldPlural] = newPlural // Products -> Items + variants[textutil.CamelCase(oldPlural)] = textutil.CamelCase(newPlural) // products -> items + variants[strings.ToUpper(oldPlural)] = strings.ToUpper(newPlural) // PRODUCTS -> ITEMS + } + return variants } // RewriteEntityContent rewrites identifier references to an old entity name back // to the new one (Pascal / camel / UPPER / plural forms). func RewriteEntityContent(content []byte, oldName, newName string) []byte { - return rewriteCasings(content, entityCasings(oldName, newName)) + variants := casingVariants(textutil.PascalCase(oldName), textutil.PascalCase(newName), true) + return replaceLongest(content, variants, tokenOK) } // RewriteFieldContent rewrites identifier references to an old field back to the // new one (Pascal / camel / UPPER forms). func RewriteFieldContent(content []byte, oldField, newField string) []byte { - return rewriteCasings(content, fieldCasings(oldField, newField)) + variants := casingVariants(textutil.PascalCase(oldField), textutil.PascalCase(newField), false) + return replaceLongest(content, variants, tokenOK) } // RewriteNamespaceContent rewrites the old root-namespace identifier to the new one. func RewriteNamespaceContent(content []byte, oldNs, newNs string) []byte { - return rewriteCasings(content, namespaceCasings(oldNs, newNs)) + return replaceLongest(content, casingVariants(oldNs, newNs, false), tokenOK) } // EntityTransform returns a transform rewriting an old entity identifier to its @@ -167,9 +180,6 @@ func EntityTransform(oldName, newName string) func([]byte) []byte { // NamespaceTransform returns a transform rewriting the old root namespace. func NamespaceTransform(n *NamespaceMismatch) func([]byte) []byte { - if n == nil { - return func(b []byte) []byte { return b } - } oldNs, newNs := n.OldNamespace, n.NewNamespace return func(b []byte) []byte { return RewriteNamespaceContent(b, oldNs, newNs) } } @@ -208,23 +218,27 @@ func RewriteFile(outputDir, relPath string, transforms ...func([]byte) []byte) ( if len(transforms) == 0 { return false, nil } - abs := filepath.Join(outputDir, filepath.FromSlash(relPath)) - data, err := os.ReadFile(abs) - if err != nil { - if os.IsNotExist(err) { - return false, nil + written := false + err := withRoot(outputDir, relPath, func(root *os.Root, rel string) error { + data, err := root.ReadFile(rel) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err } - return false, err - } - out := data - for _, t := range transforms { - out = t(out) - } - if string(out) == string(data) { - return false, nil - } - if err := fsutil.AtomicWrite(abs, out); err != nil { - return false, err - } - return true, nil + out := data + for _, t := range transforms { + out = t(out) + } + if string(out) == string(data) { + return nil + } + if err := fsutil.AtomicWriteRoot(root, rel, out); err != nil { + return err + } + written = true + return nil + }) + return written, err } diff --git a/internal/snapshot/rewrite_test.go b/internal/snapshot/rewrite_test.go index 438bb5a..b73dd85 100644 --- a/internal/snapshot/rewrite_test.go +++ b/internal/snapshot/rewrite_test.go @@ -1,12 +1,14 @@ package snapshot import ( + "maps" "os" "path/filepath" "testing" ) func TestRewriteEntityContent(t *testing.T) { + t.Parallel() cases := []struct{ name, in, want string }{ {"pascal standalone", "using AcmeShop.Domain.Entities; var p = new Product();", "using AcmeShop.Domain.Entities; var p = new Item();"}, {"compound service", "class ProductService : IProductService", "class ItemService : IItemService"}, @@ -14,6 +16,8 @@ func TestRewriteEntityContent(t *testing.T) { {"plural pascal", "List Products = null;", "List Items = null;"}, {"plural camel", "var products = new list;", "var items = new list;"}, {"does not touch longer word", "Productivity", "Productivity"}, + {"inner identifier survives", "var myProduct = 1;", "var myProduct = 1;"}, + {"single uppercase prefix", "XProductService", "XItemService"}, {"snake token", "product_name", "item_name"}, {"upper", "PRODUCTS", "ITEMS"}, {"namespace untouched by entity rewrite", "namespace AcmeShop.App;", "namespace AcmeShop.App;"}, @@ -21,6 +25,7 @@ func TestRewriteEntityContent(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { + t.Parallel() got := string(RewriteEntityContent([]byte(tc.in), "Product", "Item")) if got != tc.want { t.Errorf("RewriteEntityContent mismatch\n got: %q\nwant: %q", got, tc.want) @@ -29,7 +34,24 @@ func TestRewriteEntityContent(t *testing.T) { } } +// Regression: a field rename declared in the diff was dropped from the +// compound transform, leaving stale Title/title/TITLE identifiers in custom +// files after an entity rename. +func TestRenameTransformsIncludesFieldRenames(t *testing.T) { + t.Parallel() + d := &Diff{FieldRenames: []FieldRename{{Entity: "Item", OldField: "title", NewField: "name"}}} + content := []byte("class ItemService { public string Title; var title = 1; }") + for _, transform := range RenameTransforms("Product", "Item", d) { + content = transform(content) + } + want := "class ItemService { public string Name; var name = 1; }" + if string(content) != want { + t.Errorf("field rename dropped\n got: %q\nwant: %q", content, want) + } +} + func TestRewriteFieldContent(t *testing.T) { + t.Parallel() in := "entity.Title == prev.Title; var title = Title; TITLE;" want := "entity.Name == prev.Name; var name = Name; NAME;" if got := string(RewriteFieldContent([]byte(in), "title", "name")); got != want { @@ -38,6 +60,7 @@ func TestRewriteFieldContent(t *testing.T) { } func TestRewriteNamespaceContent(t *testing.T) { + t.Parallel() in := "namespace AcmeShop.Application.Services;\nusing AcmeShop.Domain.Entities;" want := "namespace AcmeStore.Application.Services;\nusing AcmeStore.Domain.Entities;" got := string(RewriteNamespaceContent([]byte(in), "AcmeShop", "AcmeStore")) @@ -47,6 +70,7 @@ func TestRewriteNamespaceContent(t *testing.T) { } func TestRewriteFileRoundTrip(t *testing.T) { + t.Parallel() dir := t.TempDir() rel := "src/Services/ItemService.cs" original := "public partial class ProductService { Task GetAsync(); }" @@ -72,7 +96,102 @@ func TestRewriteFileRoundTrip(t *testing.T) { } } +// casingVariants is the one variant table shared by content and path rewrites. +// Pin the exact set so neither caller grows or loses a casing silently. +func TestCasingVariants(t *testing.T) { + t.Parallel() + tests := []struct { + name string + old, new string + plural bool + want map[string]string + }{ + { + name: "entity with plural", + old: "Product", + new: "Item", + plural: true, + want: map[string]string{ + "Product": "Item", + "product": "item", + "PRODUCT": "ITEM", + "Products": "Items", + "products": "items", + "PRODUCTS": "ITEMS", + }, + }, + { + name: "field without plural", + old: "Title", + new: "Name", + plural: false, + want: map[string]string{ + "Title": "Name", + "title": "name", + "TITLE": "NAME", + }, + }, + { + name: "namespace keeps declared casing", + old: "AcmeShop", + new: "AcmeStore", + plural: false, + want: map[string]string{ + "AcmeShop": "AcmeStore", + "acmeShop": "acmeStore", + "ACMESHOP": "ACMESTORE", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := casingVariants(tt.old, tt.new, tt.plural) + if !maps.Equal(got, tt.want) { + t.Errorf("casingVariants(%q, %q, %v) = %v, want %v", tt.old, tt.new, tt.plural, got, tt.want) + } + }) + } +} + +// A RewriteFile pass rewrites a developer-owned file in place. The atomic +// write must not change its permissions. Windows normalises permission bits +// (0644 reads back as 0666), so compare the observed before/after mode. +func TestRewriteFilePreservesExistingMode(t *testing.T) { + t.Parallel() + dir := t.TempDir() + rel := "src/Services/ItemService.cs" + abs := filepath.Join(dir, "src", "Services", "ItemService.cs") + if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(abs, []byte("class ProductService {}"), 0o644); err != nil { + t.Fatal(err) + } + before, err := os.Lstat(abs) + if err != nil { + t.Fatal(err) + } + modeBefore := before.Mode().Perm() + + rewrote, err := RewriteFile(dir, rel, EntityTransform("Product", "Item")) + if err != nil { + t.Fatal(err) + } + if !rewrote { + t.Fatal("expected file to be rewritten") + } + after, err := os.Lstat(abs) + if err != nil { + t.Fatal(err) + } + if got := after.Mode().Perm(); got != modeBefore { + t.Errorf("mode = %04o, want %04o (unchanged from the 0644 seed)", got, modeBefore) + } +} + func TestRewriteFileNoop(t *testing.T) { + t.Parallel() dir := t.TempDir() rel := "a.cs" content := "var unrelated = 1;" @@ -93,6 +212,7 @@ func TestRewriteFileNoop(t *testing.T) { } func TestRewriteFileMissing(t *testing.T) { + t.Parallel() dir := t.TempDir() rewrote, err := RewriteFile(dir, "does/not/exist.cs", EntityTransform("Product", "Item")) if err != nil { diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 70a1690..3a32946 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -10,15 +10,17 @@ package snapshot import ( + "bytes" "cmp" "encoding/json" + "errors" "fmt" "os" "path/filepath" "slices" "strings" - "time" + "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/internal/renderer" "github.com/DomainCraft/DomainCraft/pkg/textutil" @@ -40,6 +42,13 @@ const ( type EntityState struct { OldName string `json:"old_name,omitempty"` Fields map[string]string `json:"fields"` // field name -> IR database type + // Columns carries the canonical DB column name for every field. It is the + // snapshot's copy of ir.Field.ColumnName(), so a later diff never re-derives + // column names from logical field names: a relation field's column is the + // FK column (category -> category_id), not the field name. Absent in + // snapshots written before this field existed; callers fall back to the + // old snake_case rule in that case. + Columns map[string]string `json:"columns,omitempty"` // field name -> DB column name // FieldOldNames records the field-level `old_name` rename hints (previous // field name) declared in the CURRENT model, so the next diff can recognize // a safe column rename instead of a destructive drop + add. @@ -50,21 +59,20 @@ type EntityState struct { type Snapshot struct { FormatVersion int `json:"format_version"` Bridge string `json:"bridge"` - CreatedAt string `json:"created_at"` ProjectNamespace string `json:"project_namespace,omitempty"` // pascal-cased project name used as the C#/other root namespace Files []renderer.RenderedFile `json:"files"` Entities map[string]EntityState `json:"entities"` } -// SnapshotPath returns the absolute path of the snapshot for an output dir. -func SnapshotPath(outputDir string) string { +// Path returns the absolute path of the snapshot for an output dir. +func Path(outputDir string) string { return filepath.Join(outputDir, DirName, FileName) } // Load reads a snapshot from path. It returns (nil, nil) when the snapshot // does not exist yet (first generation run). func Load(path string) (*Snapshot, error) { - data, err := os.ReadFile(path) + data, err := os.ReadFile(path) //nolint:gosec // path is the output-rooted snapshot.json if err != nil { if os.IsNotExist(err) { return nil, nil @@ -75,42 +83,52 @@ func Load(path string) (*Snapshot, error) { if err := json.Unmarshal(data, &snap); err != nil { return nil, fmt.Errorf("parse snapshot %s: %w", path, err) } + // Fail closed on any version we did not write ourselves. A snapshot with + // format_version 0 predates the field: its shape is unknown, and treating + // it as current could make `--prune` delete custom files or run DB + // migrations against a model the developer never declared. Future versions + // (and negative values) are equally untrusted. Regenerating the project + // from scratch is the only safe recovery. + if snap.FormatVersion != FormatVersion { + return nil, fmt.Errorf("incompatible snapshot %s: expected format_version %d, got %d", path, FormatVersion, snap.FormatVersion) + } return &snap, nil } // Save persists the snapshot to path, creating the parent directory. func Save(path string, snap *Snapshot) error { - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { //nolint:gosec // generated project dirs must stay world-readable return fmt.Errorf("create snapshot dir: %w", err) } - data, err := json.MarshalIndent(snap, "", " ") - if err != nil { - return fmt.Errorf("marshal snapshot: %w", err) - } - if err := os.WriteFile(path, append(data, '\n'), 0o644); err != nil { + // Atomic write: a crash mid-save must leave the previous snapshot intact. + // A truncated snapshot could make the next run compute destructive + // migrations against a model the developer never declared. No timestamp is + // persisted, so two runs on the same model produce byte-identical files. + if err := fsutil.WriteJSONWithNewline(path, snap, true); err != nil { return fmt.Errorf("write snapshot: %w", err) } return nil } // New builds a fresh snapshot from the current IR and the renderer file manifest. -func New(bridge string, project *ir.IRProject, files []renderer.RenderedFile) *Snapshot { +func New(bridge string, project *ir.Project, files []renderer.RenderedFile) *Snapshot { entities := make(map[string]EntityState, len(project.Entities)) for _, e := range project.Entities { fields := make(map[string]string, len(e.Fields)) + columns := make(map[string]string, len(e.Fields)) fieldOldNames := make(map[string]string) for _, f := range e.Fields { fields[f.Name] = f.DatabaseType + columns[f.Name] = f.ColumnName() if f.OldName != "" { fieldOldNames[f.Name] = f.OldName } } - entities[e.Name] = EntityState{OldName: e.OldName, Fields: fields, FieldOldNames: fieldOldNames} + entities[e.Name] = EntityState{OldName: e.OldName, Fields: fields, Columns: columns, FieldOldNames: fieldOldNames} } return &Snapshot{ FormatVersion: FormatVersion, Bridge: bridge, - CreatedAt: time.Now().UTC().Format(time.RFC3339), ProjectNamespace: textutil.PascalCase(project.Name), Files: files, Entities: entities, @@ -185,88 +203,168 @@ type Diff struct { NamespaceRename *NamespaceMismatch } +// hasEntityChanges is the single definition of "the model changed", shared by +// IsEmpty and HasSchemaChanges so adding a new change kind cannot update one +// and forget the other. +func (d *Diff) hasEntityChanges() bool { + return len(d.Deleted) > 0 || len(d.Renamed) > 0 || len(d.FieldRenames) > 0 || len(d.TypeChanges) > 0 +} + // IsEmpty reports whether the diff contains nothing actionable. func (d *Diff) IsEmpty() bool { - return len(d.Deleted) == 0 && len(d.Renamed) == 0 && len(d.TypeChanges) == 0 && len(d.FieldRenames) == 0 && d.NamespaceRename == nil + return !d.hasEntityChanges() && d.NamespaceRename == nil } // HasSchemaChanges reports whether the diff contains changes that must reach the // database (deleted/renamed entities, field renames or type changes). Used to // decide whether `domaincraft generate --prune` should run the bridge's migration // commands automatically. -func (d *Diff) HasSchemaChanges() bool { - return len(d.Deleted) > 0 || len(d.Renamed) > 0 || len(d.FieldRenames) > 0 || len(d.TypeChanges) > 0 +func (d *Diff) HasSchemaChanges() bool { return d.hasEntityChanges() } + +// entityIndex is the shared old/new name resolution for the diff passes and +// the migration plan. A rename hint (old_name) maps an old entity to its new +// name; byName holds the current entities. +type entityIndex struct { + byName map[string]ir.Entity + byOldName map[string]string // old name -> new name +} + +func newEntityIndex(project *ir.Project) entityIndex { + idx := entityIndex{ + byName: make(map[string]ir.Entity, len(project.Entities)), + byOldName: make(map[string]string), + } + for _, e := range project.Entities { + idx.byName[e.Name] = e + if e.OldName != "" { + idx.byOldName[e.OldName] = e.Name + } + } + return idx +} + +// resolve returns the current entity and name corresponding to an old entity +// name, honouring a rename hint. +func (idx entityIndex) resolve(oldName string) (ir.Entity, string, bool) { + newName := oldName + if mapped, ok := idx.byOldName[oldName]; ok { + newName = mapped + } + e, ok := idx.byName[newName] + return e, newName, ok +} + +// fieldsByName is the single field->database-type projection used by the +// diff and the migration plan. +func fieldsByName(e *ir.Entity) map[string]string { + fields := make(map[string]string, len(e.Fields)) + for _, f := range e.Fields { + fields[f.Name] = f.DatabaseType + } + return fields } // ComputeDiff compares an old snapshot against the current IR project. // File lists are filtered to those that still exist on disk under outputDir. -func ComputeDiff(old *Snapshot, project *ir.IRProject, outputDir string) *Diff { +func ComputeDiff(old *Snapshot, project *ir.Project, outputDir string, warn ...func(string, ...any)) *Diff { + warnf := func(format string, args ...any) { + for _, w := range warn { + if w != nil { + w(format, args...) + } + } + } diff := &Diff{} if old == nil || project == nil { return diff } - newEntities := make(map[string]ir.IREntity, len(project.Entities)) - renamedByOld := make(map[string]string) // old name -> new name - for _, e := range project.Entities { - newEntities[e.Name] = e - if e.OldName != "" { - renamedByOld[e.OldName] = e.Name - } - } + idx := newEntityIndex(project) - // Group old entity-scoped files by entity name. + // Group old entity-scoped files by entity name. The custom-file path lists + // are derived here once, so neither change pass has to rescan the manifest. filesByEntity := make(map[string][]renderer.RenderedFile) for _, f := range old.Files { if f.Entity != "" { filesByEntity[f.Entity] = append(filesByEntity[f.Entity], f) } } + // Stat each entity-scoped file once, not once per diff pass. The custom-file + // list is derived from the same existing refs, so renamed/deleted/type/field + // passes all share one on-disk snapshot without changing their contents. + existingRefsByEntity := make(map[string][]FileRef, len(filesByEntity)) + existingCustomByEntity := make(map[string][]string, len(filesByEntity)) + for entityName, files := range filesByEntity { + refs := existingFileRefs(outputDir, files, warnf) + existingRefsByEntity[entityName] = refs + custom := make([]string, 0, len(refs)) + for _, ref := range refs { + if ref.Custom { + custom = append(custom, ref.Path) + } + } + existingCustomByEntity[entityName] = custom + } + + diff.computeEntityMoves(old, idx, existingRefsByEntity) + diff.computeTypeChanges(old, idx, existingCustomByEntity) + + // Field renames (via the field-level `old_name` modifier). Detected when the + // current field declares a previous name that exists in the old snapshot and + // the current field name did not exist there (a true rename, not a shadow). + // A safe RenameColumn preserves the data — a Drop+Add would destroy it. + diff.computeFieldRenames(old, idx, existingCustomByEntity) - // Renamed entities (declared via old_name). - for oldName, newName := range renamedByOld { + // Project rename: custom (overwrite: false) files carry the old root namespace + // because they are scaffolded once. Detect them by scanning their content so the + // developer gets an actionable list instead of a compile error later. + currentNamespace := textutil.PascalCase(project.Name) + if old.ProjectNamespace != "" && old.ProjectNamespace != currentNamespace { + diff.NamespaceRename = detectNamespaceMismatch(outputDir, old, old.ProjectNamespace, currentNamespace, warnf) + } + + return diff +} + +// computeEntityMoves collects renamed and deleted entities from one rename-aware +// index, instead of resolving old names in two independent passes. +func (d *Diff) computeEntityMoves(old *Snapshot, idx entityIndex, refs map[string][]FileRef) { + for oldName, newName := range idx.byOldName { if _, ok := old.Entities[oldName]; !ok { continue } - files := existingFileRefs(outputDir, filesByEntity[oldName]) - diff.Renamed = append(diff.Renamed, Rename{OldName: oldName, NewName: newName, Files: files}) + d.Renamed = append(d.Renamed, Rename{OldName: oldName, NewName: newName, Files: refs[oldName]}) } - slices.SortFunc(diff.Renamed, func(a, b Rename) int { return cmp.Compare(a.OldName, b.OldName) }) + slices.SortFunc(d.Renamed, func(a, b Rename) int { return cmp.Compare(a.OldName, b.OldName) }) - // Deleted entities (in the snapshot, not in the current model, not renamed). for oldName := range old.Entities { - if _, ok := newEntities[oldName]; ok { + if _, ok := idx.byName[oldName]; ok { continue } - if _, renamed := renamedByOld[oldName]; renamed { + if _, renamed := idx.byOldName[oldName]; renamed { continue } - files := existingFileRefs(outputDir, filesByEntity[oldName]) - diff.Deleted = append(diff.Deleted, DeletedEntity{Name: oldName, Files: files}) + d.Deleted = append(d.Deleted, DeletedEntity{Name: oldName, Files: refs[oldName]}) } - slices.SortFunc(diff.Deleted, func(a, b DeletedEntity) int { return cmp.Compare(a.Name, b.Name) }) + slices.SortFunc(d.Deleted, func(a, b DeletedEntity) int { return cmp.Compare(a.Name, b.Name) }) +} - // Field type changes for entities that still exist (possibly under a new name). +// computeTypeChanges reports fields whose database type changed in entities +// that still exist (possibly under a new name). +func (d *Diff) computeTypeChanges(old *Snapshot, idx entityIndex, custom map[string][]string) { for oldName, oldState := range old.Entities { - newName := oldName - if mapped, ok := renamedByOld[oldName]; ok { - newName = mapped - } - newEntity, ok := newEntities[newName] + newEntity, newName, ok := idx.resolve(oldName) if !ok { continue } - newFields := make(map[string]string, len(newEntity.Fields)) - for _, f := range newEntity.Fields { - newFields[f.Name] = f.DatabaseType - } - customFiles := existingFilePaths(outputDir, customEntityFiles(old.Files, oldName)) + newFields := fieldsByName(&newEntity) + customFiles := custom[oldName] for fieldName, oldType := range oldState.Fields { newType, ok := newFields[fieldName] if !ok || oldType == newType { continue } - diff.TypeChanges = append(diff.TypeChanges, TypeChange{ + d.TypeChanges = append(d.TypeChanges, TypeChange{ Entity: newName, Field: fieldName, OldType: oldType, @@ -275,27 +373,23 @@ func ComputeDiff(old *Snapshot, project *ir.IRProject, outputDir string) *Diff { }) } } - slices.SortFunc(diff.TypeChanges, func(a, b TypeChange) int { + slices.SortFunc(d.TypeChanges, func(a, b TypeChange) int { if c := cmp.Compare(a.Entity, b.Entity); c != 0 { return c } return cmp.Compare(a.Field, b.Field) }) +} - // Field renames (via the field-level `old_name` modifier). Detected when the - // current field declares a previous name that exists in the old snapshot and - // the current field name did not exist there (a true rename, not a shadow). - // A safe RenameColumn preserves the data — a Drop+Add would destroy it. +// computeFieldRenames reports field-level old_name hints that describe a safe +// rename rather than a drop+add. +func (d *Diff) computeFieldRenames(old *Snapshot, idx entityIndex, custom map[string][]string) { for oldName, oldState := range old.Entities { - newName := oldName - if mapped, ok := renamedByOld[oldName]; ok { - newName = mapped - } - newEntity, ok := newEntities[newName] + newEntity, newName, ok := idx.resolve(oldName) if !ok { continue } - customFiles := existingFilePaths(outputDir, customEntityFiles(old.Files, oldName)) + customFiles := custom[oldName] for _, f := range newEntity.Fields { if f.OldName == "" { continue @@ -304,59 +398,53 @@ func ComputeDiff(old *Snapshot, project *ir.IRProject, outputDir string) *Diff { if !wasPresent { continue } - // Ambiguous: the new field name already existed in the previous model, - // so this is not a clean rename (two different columns would be involved). + // Ambiguous: the new name already existed before — not a clean rename. if _, already := oldState.Fields[f.Name]; already { continue } - diff.FieldRenames = append(diff.FieldRenames, FieldRename{ - Entity: newName, - OldField: f.OldName, - NewField: f.Name, - OldColumn: f.OldDatabaseColumnName, - NewColumn: f.DatabaseColumnName, - OldType: oldFieldType, - NewType: f.DatabaseType, + oldColumn := oldState.Columns[f.OldName] + if oldColumn == "" { + oldColumn = f.OldColumnName() + } + d.FieldRenames = append(d.FieldRenames, FieldRename{ + Entity: newName, OldField: f.OldName, NewField: f.Name, + OldColumn: oldColumn, NewColumn: f.ColumnName(), + OldType: oldFieldType, NewType: f.DatabaseType, CustomFiles: customFiles, - // The source of this rename was itself a rename in the previous - // snapshot — the developer renamed again before applying it. - Chained: oldState.FieldOldNames[f.OldName] != "", + Chained: oldState.FieldOldNames[f.OldName] != "", }) } } - slices.SortFunc(diff.FieldRenames, func(a, b FieldRename) int { + slices.SortFunc(d.FieldRenames, func(a, b FieldRename) int { if c := cmp.Compare(a.Entity, b.Entity); c != 0 { return c } return cmp.Compare(a.OldField, b.OldField) }) - - // Project rename: custom (overwrite: false) files carry the old root namespace - // because they are scaffolded once. Detect them by scanning their content so the - // developer gets an actionable list instead of a compile error later. - currentNamespace := textutil.PascalCase(project.Name) - if old.ProjectNamespace != "" && old.ProjectNamespace != currentNamespace { - diff.NamespaceRename = detectNamespaceMismatch(outputDir, old, old.ProjectNamespace, currentNamespace) - } - - return diff } // detectNamespaceMismatch finds custom files from the old snapshot (still present // on disk) whose content references the old root namespace. -func detectNamespaceMismatch(outputDir string, old *Snapshot, oldNamespace, newNamespace string) *NamespaceMismatch { +func detectNamespaceMismatch(outputDir string, old *Snapshot, oldNamespace, newNamespace string, warn func(string, ...any)) *NamespaceMismatch { var affected []string - for _, f := range old.Files { - if !f.Custom { + // The same on-disk filter as every other diff pass: one Stat per file, + // unsafe paths and disappeared files reported through the shared warning. + for _, ref := range existingFileRefs(outputDir, old.Files, warn) { + if !ref.Custom { + continue + } + abs, err := safeRelPath(outputDir, ref.Path) + if err != nil { + warn("skipping custom file %q while checking the namespace: %v", ref.Path, err) continue } - abs := filepath.Join(outputDir, filepath.FromSlash(f.Path)) - data, err := os.ReadFile(abs) + data, err := os.ReadFile(abs) //nolint:gosec // abs passed safeRelPath validation if err != nil { + warn("cannot read custom file %q while checking the namespace: %v", ref.Path, err) continue } if referencesNamespace(string(data), oldNamespace) { - affected = append(affected, f.Path) + affected = append(affected, ref.Path) } } if len(affected) == 0 { @@ -366,22 +454,22 @@ func detectNamespaceMismatch(outputDir string, old *Snapshot, oldNamespace, newN return &NamespaceMismatch{OldNamespace: oldNamespace, NewNamespace: newNamespace, Files: affected} } -// referencesNamespace reports whether s declares the given root namespace, e.g. -// `namespace EscrowPay...` or `namespace EscrowPay;`. +// referencesNamespace reports whether s mentions the old root namespace as a +// standalone identifier. It deliberately does not assume C# syntax: the same +// token appears in `namespace X;`, TypeScript imports and Python module paths. +// The shared identifier-aware rewriter supplies the boundary rules. func referencesNamespace(s, namespace string) bool { - for _, line := range strings.Split(s, "\n") { - line = strings.TrimSpace(line) - if !strings.HasPrefix(line, "namespace ") { - continue - } - rest := strings.TrimPrefix(line, "namespace ") - rest = strings.TrimSuffix(rest, ";") - rest = strings.TrimSpace(rest) - if rest == namespace || strings.HasPrefix(rest, namespace+".") { - return true - } - } - return false + if namespace == "" { + return false + } + found := false + // The same identifier-aware scanner as the rewrites, but with an early + // stop: no sentinel replacement and no full copy of the file content. + replaceLongest([]byte(s), casingVariants(namespace, namespace+"__", false), tokenOK, func([]byte) bool { + found = true + return true + }) + return found } // NamespaceRenameReport returns a human-readable report for the project-namespace @@ -402,60 +490,64 @@ func (d *Diff) NamespaceRenameReport() string { return b.String() } -// customEntityFiles returns the relative paths of custom (overwrite: false) -// files that were generated for the given entity in the old snapshot. -func customEntityFiles(files []renderer.RenderedFile, entityName string) []string { - var paths []string - for _, f := range files { - if f.Entity == entityName && f.Custom { - paths = append(paths, f.Path) +// existingItems is the single safeRelPath + Stat + skip + sort filter used by +// every caller that turns snapshot-supplied paths into on-disk facts. Items +// whose path escapes outputDir or is missing are dropped; the rest stay in +// deterministic path order. +func existingItems[T any](outputDir string, items []T, relPath func(T) string, warn func(string, ...any)) []T { + var result []T + for _, item := range items { + path := relPath(item) + abs, err := safeRelPath(outputDir, path) + if err != nil { + warn("skipping manifest file %q during migration diff: %v", path, err) + continue + } + if _, err := os.Stat(abs); err != nil { + warn("manifest file %q is no longer on disk: %v", path, err) + continue } + result = append(result, item) } - return paths + slices.SortFunc(result, func(a, b T) int { return cmp.Compare(relPath(a), relPath(b)) }) + return result } // existingFileRefs filters old entity-scoped files to those that still exist // on disk, preserving whether each is a custom (overwrite: false) file. -func existingFileRefs(outputDir string, files []renderer.RenderedFile) []FileRef { - var refs []FileRef - for _, f := range files { - if _, err := os.Stat(filepath.Join(outputDir, filepath.FromSlash(f.Path))); err != nil { - continue - } +func existingFileRefs(outputDir string, files []renderer.RenderedFile, warn func(string, ...any)) []FileRef { + existing := existingItems(outputDir, files, func(f renderer.RenderedFile) string { return f.Path }, warn) + refs := make([]FileRef, 0, len(existing)) + for _, f := range existing { refs = append(refs, FileRef{Path: f.Path, Custom: f.Custom}) } - slices.SortFunc(refs, func(a, b FileRef) int { return cmp.Compare(a.Path, b.Path) }) return refs } -// existingFilePaths filters relative paths to those that still exist on disk. -func existingFilePaths(outputDir string, relPaths []string) []string { - var result []string - for _, rel := range relPaths { - if _, err := os.Stat(filepath.Join(outputDir, filepath.FromSlash(rel))); err == nil { - result = append(result, rel) - } - } - slices.Sort(result) - return result -} - // RenameRelPath maps an entity-scoped file path to its path after the entity -// rename oldName -> newName. Both the plural and the singular forms of the old -// name are replaced (plural first, since it is more specific). +// rename oldName -> newName. It uses the same casing-variant table as content +// rewrites, so singular/plural paths in any casing are renamed consistently. func RenameRelPath(relPath, oldName, newName string) string { - out := strings.ReplaceAll(relPath, textutil.Pluralize(oldName), textutil.Pluralize(newName)) - out = strings.ReplaceAll(out, oldName, newName) - return out + // Single pass, longest match first. Two sequential ReplaceAll calls would + // rescan the replacement of the plural form and rewrite the singular head in + // it: Product -> ProductItem would turn Products into ProductItemItems. + variants := casingVariants(oldName, newName, true) + return string(replaceLongest([]byte(relPath), variants, tokenOK)) } // DeleteFile removes an entity-scoped file (path relative to outputDir). func DeleteFile(outputDir, relPath string) error { - abs := filepath.Join(outputDir, filepath.FromSlash(relPath)) - if err := os.Remove(abs); err != nil { - return fmt.Errorf("remove %s: %w", relPath, err) - } - return nil + return withRoot(outputDir, relPath, func(root *os.Root, rel string) error { + if err := root.Remove(rel); err != nil { + // The diff only includes files that existed at scan time; another + // run may have removed one since. Treat that as the end state. + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("remove %s: %w", relPath, err) + } + return nil + }) } // RenameEntityFile renames an entity-scoped file after the entity rename @@ -467,18 +559,70 @@ func RenameEntityFile(outputDir, relPath, oldName, newName string) (newRel strin if newRel == relPath { return newRel, false, nil } - abs := filepath.Join(outputDir, filepath.FromSlash(relPath)) - newAbs := filepath.Join(outputDir, filepath.FromSlash(newRel)) - if _, err := os.Stat(newAbs); err == nil { - return newRel, false, nil - } - if err := os.MkdirAll(filepath.Dir(newAbs), 0o755); err != nil { - return newRel, false, fmt.Errorf("create parent dir for %s: %w", newRel, err) - } - if err := os.Rename(abs, newAbs); err != nil { - return newRel, false, fmt.Errorf("rename %s to %s: %w", relPath, newRel, err) - } - return newRel, true, nil + err = withRoot(outputDir, relPath, func(srcRoot *os.Root, srcRel string) error { + return withRoot(outputDir, newRel, func(dstRoot *os.Root, dstRel string) error { + if _, err := dstRoot.Lstat(dstRel); err == nil { + return nil + } else if !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("check destination %s: %w", newRel, err) + } + if err := dstRoot.MkdirAll(filepath.Dir(dstRel), 0o755); err != nil { + return fmt.Errorf("create parent dir for %s: %w", newRel, err) + } + // Re-check immediately before the rename: a file created between + // the first check and here would otherwise be overwritten. + if _, err := dstRoot.Lstat(dstRel); err == nil { + return nil + } else if !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("check destination %s: %w", newRel, err) + } + if err := srcRoot.Rename(srcRel, dstRel); err != nil { + return fmt.Errorf("rename %s to %s: %w", relPath, newRel, err) + } + renamed = true + return nil + }) + }) + return newRel, renamed, err +} + +// removeFileFn is a seam for testing the failure path of ReplaceScaffoldedFile. +var removeFileFn = func(root *os.Root, name string) error { return root.Remove(name) } + +// ReplaceScaffoldedFile replaces a scaffolded custom file at destRel with the +// developer's existing custom file at sourceRel, applying transforms to its +// content in memory first. The destination is committed atomically before the +// source is removed, so a failed write or transform never destroys either copy. +// A failed source removal is reported: the destination is already correct and +// the developer can remove the leftover manually. +func ReplaceScaffoldedFile(outputDir, sourceRel, destRel string, transforms ...func([]byte) []byte) error { + return withRoot(outputDir, sourceRel, func(srcRoot *os.Root, srcRel string) error { + return withRoot(outputDir, destRel, func(dstRoot *os.Root, dstRel string) error { + data, err := srcRoot.ReadFile(srcRel) + if err != nil { + return fmt.Errorf("read %s: %w", sourceRel, err) + } + out := data + for _, transform := range transforms { + out = transform(out) + } + existing, readErr := dstRoot.ReadFile(dstRel) + switch { + case readErr == nil && bytes.Equal(existing, out): + // Already up to date: avoid a temp file and mtime reset. + case readErr != nil && !errors.Is(readErr, os.ErrNotExist): + return fmt.Errorf("read %s: %w", destRel, readErr) + default: + if err := fsutil.AtomicWriteRoot(dstRoot, dstRel, out); err != nil { + return fmt.Errorf("write %s: %w", destRel, err) + } + } + if err := removeFileFn(srcRoot, srcRel); err != nil { + return fmt.Errorf("remove replaced %s: %w", sourceRel, err) + } + return nil + }) + }) } // FieldRenameReport returns a human-readable report for the field renames in diff --git a/internal/snapshot/snapshot_bench_test.go b/internal/snapshot/snapshot_bench_test.go new file mode 100644 index 0000000..47b1779 --- /dev/null +++ b/internal/snapshot/snapshot_bench_test.go @@ -0,0 +1,161 @@ +package snapshot + +import ( + "flag" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/internal/testutil" +) + +var updateGolden = flag.Bool("update", false, "regenerate benchmark golden files") + +// benchmarkDiffData builds an old snapshot with five manifest files per entity +// and a current project where every entity has both a type change and a field +// rename hint, so ComputeDiff visits customEntityFiles on both passes. +func benchmarkDiffData(tb testing.TB, entities int, onDisk, custom bool) (string, *Snapshot, *ir.Project) { + tb.Helper() + dir := tb.TempDir() + oldNamespace := "OldProject" + if !onDisk { + // Keep the namespace identical so the benchmark measures only the + // per-entity change passes, not file content scanning. + oldNamespace = "NewProject" + } + old := &Snapshot{ + FormatVersion: FormatVersion, + ProjectNamespace: oldNamespace, + Files: make([]renderer.RenderedFile, 0, entities*5), + Entities: make(map[string]EntityState, entities), + } + project := &ir.Project{ + Name: "NewProject", + Entities: make([]ir.Entity, 0, entities), + } + for i := range entities { + name := fmt.Sprintf("E%04d", i) + for j := range 5 { + rel := fmt.Sprintf("src/%s/f%d.g.cs", name, j) + if onDisk { + abs := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { + tb.Fatal(err) + } + if err := os.WriteFile(abs, []byte("generated\n"), 0o644); err != nil { + tb.Fatal(err) + } + } + old.Files = append(old.Files, renderer.RenderedFile{ + Path: rel, Entity: name, Custom: custom && j == 0, Written: true, + }) + } + old.Entities[name] = EntityState{ + Fields: map[string]string{"value": "string", "previous": "uuid"}, + FieldOldNames: map[string]string{"previous": "original"}, + } + project.Entities = append(project.Entities, ir.Entity{ + Name: name, + Fields: []ir.Field{ + {Name: "value", DatabaseType: "int"}, + {Name: "current", OldName: "previous", DatabaseType: "uuid", DatabaseColumnName: "current", OldDatabaseColumnName: "previous"}, + }, + }) + } + return dir, old, project +} + +// benchmarkDiffModes is shared by the benchmark and the golden test so a new +// mode cannot be measured without being pinned. +var benchmarkDiffModes = []struct { + name string + onDisk bool + custom bool +}{ + {name: "no-custom", onDisk: false, custom: false}, + {name: "manifest", onDisk: false, custom: true}, + {name: "on-disk", onDisk: true, custom: true}, +} + +func BenchmarkComputeDiff(b *testing.B) { + for _, mode := range benchmarkDiffModes { + b.Run(mode.name, func(b *testing.B) { + for _, size := range []int{100, 500, 2000} { + b.Run(fmt.Sprintf("entities=%d", size), func(b *testing.B) { + dir, old, project := benchmarkDiffData(b, size, mode.onDisk, mode.custom) + for b.Loop() { + diff := ComputeDiff(old, project, dir) + if diff == nil || len(diff.TypeChanges) != size || len(diff.FieldRenames) != size { + b.Fatalf("unexpected diff: %d type changes, %d field renames", len(diff.TypeChanges), len(diff.FieldRenames)) + } + } + }) + } + }) + } +} + +// diffDigest serializes every diff field into canonical sorted lines. The +// slices produced by ComputeDiff are sorted again here so the digest never +// depends on map iteration order inside the core. +func diffDigest(t *testing.T, diff *Diff) string { + t.Helper() + fileRefs := func(refs []FileRef) string { + paths := make([]string, 0, len(refs)) + for _, ref := range refs { + paths = append(paths, fmt.Sprintf("%s:custom=%t", ref.Path, ref.Custom)) + } + slices.Sort(paths) + return strings.Join(paths, ",") + } + customFiles := func(paths []string) string { + sorted := slices.Clone(paths) + slices.Sort(sorted) + return strings.Join(sorted, ",") + } + var lines []string + for _, d := range diff.Deleted { + lines = append(lines, fmt.Sprintf("deleted\t%s\tfiles=[%s]", d.Name, fileRefs(d.Files))) + } + for _, r := range diff.Renamed { + lines = append(lines, fmt.Sprintf("renamed\t%s->%s\tfiles=[%s]", r.OldName, r.NewName, fileRefs(r.Files))) + } + for _, c := range diff.TypeChanges { + lines = append(lines, fmt.Sprintf("typechange\t%s.%s\t%s->%s\tcustom=[%s]", c.Entity, c.Field, c.OldType, c.NewType, customFiles(c.CustomFiles))) + } + for _, r := range diff.FieldRenames { + lines = append(lines, fmt.Sprintf("fieldrename\t%s\t%s->%s\t%s->%s\t%s->%s\tchained=%t\tcustom=[%s]", + r.Entity, r.OldField, r.NewField, r.OldColumn, r.NewColumn, r.OldType, r.NewType, r.Chained, customFiles(r.CustomFiles))) + } + if n := diff.NamespaceRename; n != nil { + lines = append(lines, fmt.Sprintf("namespace\t%s->%s\tfiles=[%s]", n.OldNamespace, n.NewNamespace, customFiles(n.Files))) + } + slices.Sort(lines) + return testutil.HashLines(lines) +} + +// TestBenchmarkComputeDiffGolden pins the diff result for every benchmark +// mode, using the same fixture builder as BenchmarkComputeDiff. It uses small +// entity counts on purpose: the golden checks behavior, not speed. Running the +// benchmark's 100/500/2000 sizes here added ~157 s to every `go test` run — +// those sizes belong in BenchmarkComputeDiff and in scripts/bench-check.sh. +func TestBenchmarkComputeDiffGolden(t *testing.T) { + lines := make([]string, 0, len(benchmarkDiffModes)*2) + for _, mode := range benchmarkDiffModes { + for _, size := range []int{10, 50} { + dir, old, project := benchmarkDiffData(t, size, mode.onDisk, mode.custom) + diff := ComputeDiff(old, project, dir) + if diff == nil { + t.Fatalf("%s/%d: ComputeDiff returned nil", mode.name, size) + } + lines = append(lines, fmt.Sprintf("%s/%d\tdeleted=%d\trenamed=%d\ttypechanges=%d\tfieldrenames=%d\tnamespace=%t\tsha256=%s", + mode.name, size, len(diff.Deleted), len(diff.Renamed), len(diff.TypeChanges), len(diff.FieldRenames), diff.NamespaceRename != nil, diffDigest(t, diff))) + } + } + testutil.CheckGolden(t, "compute-diff.golden.txt", strings.Join(lines, "\n"), *updateGolden) +} diff --git a/internal/snapshot/snapshot_hardening_test.go b/internal/snapshot/snapshot_hardening_test.go new file mode 100644 index 0000000..711836f --- /dev/null +++ b/internal/snapshot/snapshot_hardening_test.go @@ -0,0 +1,50 @@ +package snapshot + +import ( + "bytes" + "testing" +) + +func TestRewritePreservesInvalidUTF8Bytes(t *testing.T) { + t.Parallel() + + t.Run("unrelated invalid byte survives", func(t *testing.T) { + t.Parallel() + content := []byte{0x61, 0xe9, 0x62} + if out := RewriteEntityContent(content, "Product", "Item"); !bytes.Equal(out, content) { + t.Fatalf("rewrite changed bytes: got %x, want %x", out, content) + } + }) + + t.Run("identifiers around invalid byte are rewritten", func(t *testing.T) { + t.Parallel() + content := append([]byte("Product "), 0xe9, ' ', 'P', 'r', 'o', 'd', 'u', 'c', 't') + want := append([]byte("Item "), 0xe9, ' ', 'I', 't', 'e', 'm') + out := RewriteEntityContent(content, "Product", "Item") + if !bytes.Equal(out, want) { + t.Fatalf("rewrite = %x, want %x", out, want) + } + }) +} + +func TestReferencesNamespaceIsLanguageAgnostic(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + src string + want bool + }{ + {name: "csharp", src: "namespace Old.Root;", want: true}, + {name: "typescript", src: `import { Api } from "Old.Root/api";`, want: true}, + {name: "python", src: "from Old.Root import api", want: true}, + {name: "different namespace", src: "namespace Other.Root;", want: false}, + {name: "embedded in identifier", src: "MyOld.RootThing", want: false}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := referencesNamespace(c.src, "Old.Root"); got != c.want { + t.Fatalf("referencesNamespace(%q) = %t, want %t", c.src, got, c.want) + } + }) + } +} diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index e4006c6..51db919 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -1,6 +1,7 @@ package snapshot import ( + "fmt" "os" "path/filepath" "strings" @@ -11,8 +12,9 @@ import ( ) func TestSaveLoadRoundtrip(t *testing.T) { + t.Parallel() dir := t.TempDir() - path := SnapshotPath(dir) + path := Path(dir) snap := New("csharp-restful", testProject("Product"), []renderer.RenderedFile{ {Path: "src/Domain/Entities/Product.cs", Entity: "Product", Written: true}, @@ -46,6 +48,7 @@ func TestSaveLoadRoundtrip(t *testing.T) { } func TestLoadMissingSnapshotReturnsNil(t *testing.T) { + t.Parallel() loaded, err := Load(filepath.Join(t.TempDir(), "nope", "snapshot.json")) if err != nil { t.Fatalf("Load() error = %v", err) @@ -55,7 +58,58 @@ func TestLoadMissingSnapshotReturnsNil(t *testing.T) { } } +func TestLoadRejectsIncompatibleFormatVersion(t *testing.T) { + t.Parallel() + tests := []struct { + name string + version int + wantErr bool + }{ + {name: "legacy zero", version: 0, wantErr: true}, + {name: "future version", version: 2, wantErr: true}, + {name: "negative version", version: -1, wantErr: true}, + {name: "current version", version: FormatVersion, wantErr: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + dir := t.TempDir() + path := Path(dir) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + data := []byte(fmt.Sprintf(`{"format_version":%d,"bridge":"demo","entities":{},"files":[]}`, tt.version)) + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatalf("write snapshot: %v", err) + } + + loaded, err := Load(path) + if tt.wantErr { + if err == nil { + t.Fatalf("Load() accepted format_version %d, want error", tt.version) + } + if loaded != nil { + t.Errorf("Load() returned a snapshot on error: %+v", loaded) + } + for _, want := range []string{path, fmt.Sprint(FormatVersion), fmt.Sprint(tt.version)} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q missing %q", err.Error(), want) + } + } + return + } + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if loaded == nil || loaded.FormatVersion != FormatVersion { + t.Fatalf("loaded snapshot = %+v, want format_version %d", loaded, FormatVersion) + } + }) + } +} + func TestComputeDiffDeletedEntity(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Product.cs") writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -87,6 +141,7 @@ func TestComputeDiffDeletedEntity(t *testing.T) { } func TestComputeDiffRenameAndTypeChange(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Product.cs") writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -102,13 +157,13 @@ func TestComputeDiffRenameAndTypeChange(t *testing.T) { } // Product -> Item (via old_name) and id type changed uuid -> int. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "int", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, }, @@ -140,6 +195,7 @@ func TestComputeDiffRenameAndTypeChange(t *testing.T) { } func TestRenameRelPath(t *testing.T) { + t.Parallel() tests := []struct { rel, old, new, want string }{ @@ -152,13 +208,17 @@ func TestRenameRelPath(t *testing.T) { {"src/Shared/Constants.cs", "Product", "Item", "src/Shared/Constants.cs"}, } for _, tt := range tests { - if got := RenameRelPath(tt.rel, tt.old, tt.new); got != tt.want { - t.Errorf("RenameRelPath(%q, %q, %q) = %q, want %q", tt.rel, tt.old, tt.new, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := RenameRelPath(tt.rel, tt.old, tt.new); got != tt.want { + t.Errorf("RenameRelPath(%q, %q, %q) = %q, want %q", tt.rel, tt.old, tt.new, got, tt.want) + } + }) } } func TestDeleteFileAndRenameEntityFile(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -183,6 +243,7 @@ func TestDeleteFileAndRenameEntityFile(t *testing.T) { } func TestComputeDiffNamespaceRename(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Application/Services/UserService.cs") writeTestFile(t, dir, "src/WebApi/Program.cs") @@ -220,6 +281,7 @@ func TestComputeDiffNamespaceRename(t *testing.T) { } func TestComputeDiffFieldRename(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Application/Services/ProductService.cs") @@ -236,12 +298,12 @@ func TestComputeDiffFieldRename(t *testing.T) { } // name: string [required, old_name: title] — title -> name, same string type. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "name", @@ -279,6 +341,7 @@ func TestComputeDiffFieldRename(t *testing.T) { } func TestComputeDiffChainedFieldRename(t *testing.T) { + t.Parallel() // The developer renamed title -> name, generated, but NEVER applied the // migration. Then they renamed name -> description and generated again. The // previous snapshot shows that `name` was itself a rename (of `title`), so the @@ -293,12 +356,12 @@ func TestComputeDiffChainedFieldRename(t *testing.T) { }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "description", @@ -327,6 +390,7 @@ func TestComputeDiffChainedFieldRename(t *testing.T) { } func TestComputeDiffFieldRenameSkipsTypeChangeOnly(t *testing.T) { + t.Parallel() dir := t.TempDir() // Field keeps its name but the type changes — that is a type change, not a rename. @@ -334,7 +398,7 @@ func TestComputeDiffFieldRenameSkipsTypeChangeOnly(t *testing.T) { Entities: map[string]EntityState{"Product": {Fields: map[string]string{"price": "int"}}}, } project := testProject("Product") - project.Entities[0].Fields = []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "price", DatabaseType: "decimal", DatabaseColumnName: "price"}} + project.Entities[0].Fields = []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "price", DatabaseType: "decimal", DatabaseColumnName: "price"}} diff := ComputeDiff(old, project, dir) if len(diff.FieldRenames) != 0 { @@ -346,6 +410,7 @@ func TestComputeDiffFieldRenameSkipsTypeChangeOnly(t *testing.T) { } func TestComputeDiffDeletedEntityWithoutFiles(t *testing.T) { + t.Parallel() dir := t.TempDir() // Files are NOT created on disk — should filter them out. @@ -368,6 +433,7 @@ func TestComputeDiffDeletedEntityWithoutFiles(t *testing.T) { } func TestComputeDiffMultipleDeletedEntities(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Product.cs") writeTestFile(t, dir, "src/Domain/Entities/Category.cs") @@ -414,6 +480,7 @@ func TestComputeDiffMultipleDeletedEntities(t *testing.T) { } func TestComputeDiffEntityRenameOnly(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Product.cs") writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -429,13 +496,13 @@ func TestComputeDiffEntityRenameOnly(t *testing.T) { } // Product -> Item, fields unchanged. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, }, @@ -466,6 +533,7 @@ func TestComputeDiffEntityRenameOnly(t *testing.T) { } func TestComputeDiffEntityRenameWithoutFiles(t *testing.T) { + t.Parallel() dir := t.TempDir() // No files created on disk. @@ -478,13 +546,13 @@ func TestComputeDiffEntityRenameWithoutFiles(t *testing.T) { }, } - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, }, } @@ -499,6 +567,7 @@ func TestComputeDiffEntityRenameWithoutFiles(t *testing.T) { } func TestComputeDiffFieldRenameWithTypeChange(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -515,12 +584,12 @@ func TestComputeDiffFieldRenameWithTypeChange(t *testing.T) { } // title: string -> name: text [old_name: title] — rename AND type change. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Product", NamePlural: "Products", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "name", @@ -559,6 +628,7 @@ func TestComputeDiffFieldRenameWithTypeChange(t *testing.T) { } func TestComputeDiffSimultaneousChanges(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Item.cs") writeTestFile(t, dir, "src/Services/ItemService.cs") @@ -582,13 +652,13 @@ func TestComputeDiffSimultaneousChanges(t *testing.T) { // Product -> Item (rename), title -> name (field rename), price int -> decimal (type change). // Category: deleted. // User: unchanged. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, { Name: "name", @@ -603,7 +673,7 @@ func TestComputeDiffSimultaneousChanges(t *testing.T) { { Name: "User", NamePlural: "Users", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "email", DatabaseType: "string"}, }, @@ -660,6 +730,7 @@ func TestComputeDiffSimultaneousChanges(t *testing.T) { } func TestComputeDiffMultipleRenames(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Domain/Entities/Item.cs") writeTestFile(t, dir, "src/Domain/Entities/Group.cs") @@ -678,24 +749,24 @@ func TestComputeDiffMultipleRenames(t *testing.T) { } // Product -> Item, Category -> Group, User unchanged. - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", OldName: "Product", NamePlural: "Items", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, { Name: "Group", OldName: "Category", NamePlural: "Groups", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, { Name: "User", NamePlural: "Users", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, }, } @@ -717,6 +788,7 @@ func TestComputeDiffMultipleRenames(t *testing.T) { } func TestComputeDiffExistingFileFiltersDeleted(t *testing.T) { + t.Parallel() dir := t.TempDir() // Only create A.cs — B.cs does not exist on disk. writeTestFile(t, dir, "src/Services/A.cs") @@ -745,10 +817,10 @@ func TestComputeDiffExistingFileFiltersDeleted(t *testing.T) { } } -func testProject(entityName string) *ir.IRProject { - return &ir.IRProject{ - Entities: []ir.IREntity{ - {Name: entityName, NamePlural: entityName + "s", Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}}, +func testProject(entityName string) *ir.Project { + return &ir.Project{ + Entities: []ir.Entity{ + {Name: entityName, NamePlural: entityName + "s", Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}}, }, } } @@ -765,7 +837,9 @@ func writeTestFile(t *testing.T, root, rel string) { } func TestTypeChangeReport(t *testing.T) { + t.Parallel() t.Run("empty diff yields empty report", func(t *testing.T) { + t.Parallel() d := &Diff{} if got := d.TypeChangeReport(); got != "" { t.Errorf("report = %q, want empty", got) @@ -773,6 +847,7 @@ func TestTypeChangeReport(t *testing.T) { }) t.Run("lists changes and custom files", func(t *testing.T) { + t.Parallel() d := &Diff{TypeChanges: []TypeChange{ {Entity: "Product", Field: "price", OldType: "decimal", NewType: "int", CustomFiles: []string{"src/Services/ProductService.cs"}}, {Entity: "Order", Field: "note", OldType: "text", NewType: "string"}, @@ -792,3 +867,85 @@ func TestTypeChangeReport(t *testing.T) { } }) } + +// TestReplaceScaffoldedFileKeepsSourceOnRemoveFailure guards the --prune +// replace path: a failed source removal must never destroy the developer's +// file, and the destination must already hold the transformed content. +func TestReplaceScaffoldedFileKeepsSourceOnRemoveFailure(t *testing.T) { + // This test mutates the removeFileFn seam, so it must not run in parallel. + dir := t.TempDir() + sourceRel := "src/Services/ProductService.cs" + destRel := "src/Services/ItemService.cs" + source := filepath.Join(dir, filepath.FromSlash(sourceRel)) + dest := filepath.Join(dir, filepath.FromSlash(destRel)) + if err := os.MkdirAll(filepath.Dir(source), 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := os.WriteFile(source, []byte("// developer hook for ProductService\n"), 0o644); err != nil { + t.Fatalf("write source: %v", err) + } + if err := os.WriteFile(dest, []byte("// scaffolded ItemService\n"), 0o644); err != nil { + t.Fatalf("write destination: %v", err) + } + + original := removeFileFn + t.Cleanup(func() { removeFileFn = original }) + removeFileFn = func(*os.Root, string) error { return fmt.Errorf("remove failed") } + + transform := func(b []byte) []byte { + return []byte(strings.ReplaceAll(string(b), "Product", "Item")) + } + err := ReplaceScaffoldedFile(dir, sourceRel, destRel, transform) + if err == nil { + t.Fatal("expected error from failed source removal") + } + + gotDest, err := os.ReadFile(dest) + if err != nil { + t.Fatalf("read destination: %v", err) + } + if !strings.Contains(string(gotDest), "developer hook for ItemService") { + t.Errorf("destination lost the developer content: %q", gotDest) + } + if strings.Contains(string(gotDest), "scaffolded") { + t.Errorf("destination still holds the scaffolded content: %q", gotDest) + } + if _, err := os.Stat(source); err != nil { + t.Errorf("source was removed before the destination was committed: %v", err) + } +} + +func TestReplaceScaffoldedFileSucceeds(t *testing.T) { + t.Parallel() + dir := t.TempDir() + sourceRel := "src/Services/ProductService.cs" + destRel := "src/Services/ItemService.cs" + source := filepath.Join(dir, filepath.FromSlash(sourceRel)) + dest := filepath.Join(dir, filepath.FromSlash(destRel)) + if err := os.MkdirAll(filepath.Dir(source), 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := os.WriteFile(source, []byte("// developer hook for ProductService\n"), 0o644); err != nil { + t.Fatalf("write source: %v", err) + } + if err := os.WriteFile(dest, []byte("// scaffolded ItemService\n"), 0o644); err != nil { + t.Fatalf("write destination: %v", err) + } + + transform := func(b []byte) []byte { + return []byte(strings.ReplaceAll(string(b), "Product", "Item")) + } + if err := ReplaceScaffoldedFile(dir, sourceRel, destRel, transform); err != nil { + t.Fatalf("ReplaceScaffoldedFile() error = %v", err) + } + gotDest, err := os.ReadFile(dest) + if err != nil { + t.Fatalf("read destination: %v", err) + } + if !strings.Contains(string(gotDest), "developer hook for ItemService") { + t.Errorf("destination = %q, want transformed developer content", gotDest) + } + if _, err := os.Stat(source); !os.IsNotExist(err) { + t.Errorf("source still exists or stat failed: %v", err) + } +} diff --git a/internal/snapshot/testdata/compute-diff.golden.txt b/internal/snapshot/testdata/compute-diff.golden.txt new file mode 100644 index 0000000..a39f144 --- /dev/null +++ b/internal/snapshot/testdata/compute-diff.golden.txt @@ -0,0 +1,6 @@ +no-custom/10 deleted=0 renamed=0 typechanges=10 fieldrenames=10 namespace=false sha256=5d5eafdff0a489fa535a783f75baed53d9286815da3e7a13e4db58a4d7426a24 +no-custom/50 deleted=0 renamed=0 typechanges=50 fieldrenames=50 namespace=false sha256=aa283d3f7f823f338c892a8bb2df7272a45c0cc52537fcda1dbc25d1f0b1c125 +manifest/10 deleted=0 renamed=0 typechanges=10 fieldrenames=10 namespace=false sha256=5d5eafdff0a489fa535a783f75baed53d9286815da3e7a13e4db58a4d7426a24 +manifest/50 deleted=0 renamed=0 typechanges=50 fieldrenames=50 namespace=false sha256=aa283d3f7f823f338c892a8bb2df7272a45c0cc52537fcda1dbc25d1f0b1c125 +on-disk/10 deleted=0 renamed=0 typechanges=10 fieldrenames=10 namespace=false sha256=b99a4450cde87aadd902f263c44151cf96225f1168530d71bf70fda36ad02597 +on-disk/50 deleted=0 renamed=0 typechanges=50 fieldrenames=50 namespace=false sha256=38ec253a2412cb99a51933f3bd5be5ae2d8354feb3061ee1b4de471b32d80cca diff --git a/internal/specmeta/specmeta.go b/internal/specmeta/specmeta.go index 72d7042..c49225d 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -1,6 +1,46 @@ +// Package specmeta is the single source of truth for specification constants. package specmeta -import "strings" +import ( + "slices" + "strings" + "unicode" +) + +// Field type constants. The lexer, validator and IR use these names instead of +// retyping the literals from the spec. +const ( + FieldTypeRelation = "relation" + + // Relation types are part of the IR contract. Bridges compare these strings, + // so only their names may be centralized — their values must not change. + RelationTypeOneToOne = "one-to-one" + RelationTypeManyToOne = "many-to-one" + RelationTypeOneToMany = "one-to-many" + RelationTypeManyToMany = "many-to-many" + FieldTypeArray = "array" + FieldTypeEnum = "enum" + + FieldTypeString = "string" + FieldTypeText = "text" + FieldTypeInt = "int" + FieldTypeBigint = "bigint" + FieldTypeFloat = "float" + FieldTypeDecimal = "decimal" + FieldTypeBoolean = "boolean" + FieldTypeDate = "date" + FieldTypeDatetime = "datetime" + FieldTypeUUID = "uuid" + FieldTypeJSON = "json" + FieldTypeJSONB = "jsonb" + + AuthTypeJWT = "jwt" + AuthTypeNone = "none" + OnDeleteCascade = "cascade" + OnDeleteSetNull = "set_null" + OnDeleteRestrict = "restrict" + OnDeleteNoAction = "no_action" +) // FeatureFieldDef describes a field auto-injected by a feature macro. type FeatureFieldDef struct { @@ -12,12 +52,23 @@ type FeatureFieldDef struct { DefaultValue string `json:"defaultValue"` } +// Databases lists the supported database backends. var Databases = []string{"postgresql", "mysql", "sqlite", "mssql", "mongodb", "appwrite"} +// DefaultDatabase is the parser default. It is a name, not an index into +// Databases, so reordering the list cannot silently change the default. +const DefaultDatabase = "postgresql" + +// APIStyles lists the supported API styles. var APIStyles = []string{"rest", "graphql", "grpc"} -var AuthTypes = []string{"jwt", "none"} +// DefaultAPIStyle is the parser default, independent of APIStyles ordering. +const DefaultAPIStyle = "rest" + +// AuthTypes lists the supported authentication types. +var AuthTypes = []string{AuthTypeJWT, AuthTypeNone} +// Features lists the entity features the core injects fields for. var Features = []string{"audit", "audit_log", "soft_delete", "optimistic_lock", "event_sourced", "cacheable"} // Addons are optional infrastructure accelerators that a bridge can opt into @@ -30,91 +81,160 @@ var Features = []string{"audit", "audit_log", "soft_delete", "optimistic_lock", // (OpenTelemetry/Jaeger) for bridges that opt in. var Addons = []string{"dapr", "observability"} -// Infrastructure providers declared in project.infrastructure. These are the -// building blocks Dapr (and similar addons) wire up at runtime. +// InfraQueues lists supported queue providers declared in project.infrastructure. var InfraQueues = []string{"pubsub", "rabbitmq", "kafka", "redis", "nats", "in-memory"} + +// InfraCacheStores lists supported cache providers. var InfraCacheStores = []string{"redis", "memcached", "in-memory"} + +// InfraSecretStores lists supported secret stores. var InfraSecretStores = []string{"local", "kubernetes", "azure-keyvault", "aws-secrets"} + +// InfraStores lists supported object stores. var InfraStores = []string{"local", "s3", "azure-blob", "gcs"} -var MetaFieldTypes = []string{"relation", "array", "enum"} +// MetaFieldTypes lists the non-primitive field types. +var MetaFieldTypes = []string{FieldTypeRelation, FieldTypeArray, FieldTypeEnum} +// FieldTypes lists every valid field type. var FieldTypes = append(append([]string{}, PrimitiveFieldTypes...), MetaFieldTypes...) +// FeatureFieldDefs maps injected field names to their feature definition. var FeatureFieldDefs = map[string]FeatureFieldDef{ - "createdAt": {Feature: "audit", Type: "datetime", DBColumn: "created_at", IsFuncDefault: true, DefaultValue: "now"}, - "updatedAt": {Feature: "audit", Type: "datetime", DBColumn: "updated_at", IsFuncDefault: true, DefaultValue: "now"}, - "createdBy": {Feature: "audit_log", Type: "uuid", DBColumn: "created_by"}, - "updatedBy": {Feature: "audit_log", Type: "uuid", DBColumn: "updated_by"}, - "deletedAt": {Feature: "soft_delete", Type: "datetime", DBColumn: "deleted_at", IsOptional: true}, - "version": {Feature: "optimistic_lock", Type: "int", DBColumn: "version", DefaultValue: "0"}, + "createdAt": {Feature: "audit", Type: FieldTypeDatetime, DBColumn: "created_at", IsFuncDefault: true, DefaultValue: "now"}, + "updatedAt": {Feature: "audit", Type: FieldTypeDatetime, DBColumn: "updated_at", IsFuncDefault: true, DefaultValue: "now"}, + "createdBy": {Feature: "audit_log", Type: FieldTypeUUID, DBColumn: "created_by"}, + "updatedBy": {Feature: "audit_log", Type: FieldTypeUUID, DBColumn: "updated_by"}, + "deletedAt": {Feature: "soft_delete", Type: FieldTypeDatetime, DBColumn: "deleted_at", IsOptional: true}, + "version": {Feature: "optimistic_lock", Type: FieldTypeInt, DBColumn: "version", DefaultValue: "0"}, } -var OnDeleteValues = []string{"cascade", "set_null", "restrict", "no_action"} +// OnDeleteValues lists the valid on_delete modifier values. +var OnDeleteValues = []string{OnDeleteCascade, OnDeleteSetNull, OnDeleteRestrict, OnDeleteNoAction} +// PrimitiveFieldTypes lists the scalar field types. var PrimitiveFieldTypes = []string{ - "string", "text", "int", "bigint", "float", "decimal", - "boolean", "date", "datetime", "uuid", "json", "jsonb", + FieldTypeString, FieldTypeText, FieldTypeInt, FieldTypeBigint, FieldTypeFloat, FieldTypeDecimal, + FieldTypeBoolean, FieldTypeDate, FieldTypeDatetime, FieldTypeUUID, FieldTypeJSON, FieldTypeJSONB, } -var NumericFieldTypes = []string{"int", "bigint", "float", "decimal"} +// IntegralFieldTypes lists the integral scalar types. +var IntegralFieldTypes = []string{FieldTypeInt, FieldTypeBigint} + +// FloatFieldTypes lists the floating-point scalar types. +var FloatFieldTypes = []string{FieldTypeFloat, FieldTypeDecimal} -var StringFieldTypes = []string{"string", "text"} +// NumericFieldTypes lists the numeric scalar types. +var NumericFieldTypes = append(append([]string{}, IntegralFieldTypes...), FloatFieldTypes...) +// StringFieldTypes lists the string scalar types. +var StringFieldTypes = []string{FieldTypeString, FieldTypeText} + +// NumericValidationModifiers lists numeric validation modifier names. var NumericValidationModifiers = []string{"gte", "gt", "lte", "lt"} -var StringValidationModifiers = []string{"min", "max", "email", "url", "ipv4", "regex"} +// stringValidationModifiers lists string validation modifier names. It is +// private so another package cannot mutate the spec at runtime; the lexer's +// internal parse seam accepts explicit extras for extended specs. +// min/max are also valid on numeric fields (length vs value bounds). +var stringValidationModifiers = []string{"min", "max", "email", "url", "ipv4", "regex"} + +// StringOnlyValidationModifiers lists validators that never apply to numeric fields. +var StringOnlyValidationModifiers = []string{"email", "url", "ipv4", "regex"} + +// StringFlagValidationModifiers lists string validations usable as bare flags. +var StringFlagValidationModifiers = []string{"email", "url", "ipv4"} +// IndexTypes lists the supported database index types. var IndexTypes = []string{"btree", "hash", "gist", "gin", "brin"} -var CacheProviders = []string{"redis", "memcached", "in-memory"} +// CacheProviders lists the supported cache providers. It is the same vocabulary +// as InfraCacheStores: project.cache.provider and +// project.infrastructure.cache.store accept exactly the same values, so the two +// names share one backing slice and cannot drift apart. +var CacheProviders = InfraCacheStores +// MultiTenancyModes lists the supported multi-tenancy modes. var MultiTenancyModes = []string{"column", "schema", "database"} +// RateLimitPolicies lists the supported rate-limit policies. var RateLimitPolicies = []string{"fixed", "sliding"} +// PermissionKeys lists the four permission operations. var PermissionKeys = []string{"read", "create", "update", "delete"} +// IndexKeys lists the accepted keys of an index block. The parser uses it for +// strict decoding and for the error message, so both stay in sync. +var IndexKeys = []string{"fields", "type", "sort", "unique"} + +// SortDirections lists the valid sort directions. var SortDirections = []string{"asc", "desc"} -var BooleanFieldTypes = []string{"boolean"} +// BooleanFieldTypes lists the boolean scalar types. +var BooleanFieldTypes = []string{FieldTypeBoolean} +// FuncDefaults maps default functions to their compatible field types. var FuncDefaults = map[string][]string{ - "now": {"date", "datetime"}, - "uuid": {"uuid"}, + "now": {FieldTypeDate, FieldTypeDatetime}, + "uuid": {FieldTypeUUID}, } -const DefaultFieldType = "string" +// DefaultFieldType is the fallback type for unresolvable fields. +const DefaultFieldType = FieldTypeString + +// ContractVersion is the bridge-contract version this core implements. Bridges +// declare their own version via `contract_version` in bridge.yaml; a declared +// version above this constant is not supported. +// v2 drops the uppercase IR helper aliases (IsUUID/IsJSON/IsJSONB): templates +// use IsUuid/IsJson/IsJsonB, now the only spelling. +const ContractVersion = 2 + +// EffectiveContractVersion returns the contract version to use for a declared +// value. An absent or zero declaration (the legacy default) resolves to +// ContractVersion; any positive declaration is taken as-is, so callers can still +// reject a bridge that declares a newer contract than this core implements. +func EffectiveContractVersion(declared int) int { + if declared > 0 { + return declared + } + return ContractVersion +} var ( - primitiveSet map[string]bool - numericSet map[string]bool - stringSet map[string]bool - booleanSet map[string]bool - fieldTypeSet map[string]bool - onDeleteSet map[string]bool - featureSet map[string]bool - indexTypeSet map[string]bool - cacheProviderSet map[string]bool - multiTenancyModeSet map[string]bool - rateLimitPolicySet map[string]bool - permissionKeySet map[string]bool - stringValidationModSet map[string]bool - numericValidationModSet map[string]bool - sortDirectionSet map[string]bool - databaseSet map[string]bool - apiStyleSet map[string]bool - authTypeSet map[string]bool - addonSet map[string]bool - infraQueueSet map[string]bool - infraCacheStoreSet map[string]bool - infraSecretStoreSet map[string]bool - infraStoreSet map[string]bool + primitiveSet map[string]bool + numericSet map[string]bool + integralSet map[string]bool + floatSet map[string]bool + stringSet map[string]bool + booleanSet map[string]bool + fieldTypeSet map[string]bool + onDeleteSet map[string]bool + featureSet map[string]bool + indexTypeSet map[string]bool + cacheProviderSet map[string]bool + multiTenancyModeSet map[string]bool + rateLimitPolicySet map[string]bool + permissionKeySet map[string]bool + numericValidationModSet map[string]bool + stringValidationModSet map[string]bool + stringOnlyValidationModSet map[string]bool + stringFlagValidationModSet map[string]bool + sortDirectionSet map[string]bool + databaseSet map[string]bool + apiStyleSet map[string]bool + authTypeSet map[string]bool + addonSet map[string]bool + infraQueueSet map[string]bool + infraCacheStoreSet map[string]bool + infraSecretStoreSet map[string]bool + infraStoreSet map[string]bool ) func init() { primitiveSet = SliceToSet(PrimitiveFieldTypes) numericSet = SliceToSet(NumericFieldTypes) + integralSet = SliceToSet(IntegralFieldTypes) + floatSet = SliceToSet(FloatFieldTypes) stringSet = SliceToSet(StringFieldTypes) booleanSet = SliceToSet(BooleanFieldTypes) fieldTypeSet = SliceToSet(FieldTypes) @@ -125,8 +245,10 @@ func init() { multiTenancyModeSet = SliceToSet(MultiTenancyModes) rateLimitPolicySet = SliceToSet(RateLimitPolicies) permissionKeySet = SliceToSet(PermissionKeys) - stringValidationModSet = SliceToSet(StringValidationModifiers) numericValidationModSet = SliceToSet(NumericValidationModifiers) + stringValidationModSet = SliceToSet(stringValidationModifiers) + stringOnlyValidationModSet = SliceToSet(StringOnlyValidationModifiers) + stringFlagValidationModSet = SliceToSet(StringFlagValidationModifiers) sortDirectionSet = SliceToSet(SortDirections) databaseSet = SliceToSet(Databases) apiStyleSet = SliceToSet(APIStyles) @@ -138,30 +260,100 @@ func init() { infraStoreSet = SliceToSet(InfraStores) } -func IsPrimitive(typeName string) bool { return primitiveSet[typeName] } -func IsNumeric(typeName string) bool { return numericSet[typeName] } -func IsStringType(typeName string) bool { return stringSet[typeName] } -func IsBooleanType(typeName string) bool { return booleanSet[typeName] } -func IsSortDirection(value string) bool { return sortDirectionSet[value] } -func IsFieldType(typeName string) bool { return fieldTypeSet[typeName] } -func IsOnDeleteValue(value string) bool { return onDeleteSet[value] } -func IsFeature(name string) bool { return featureSet[name] } -func IsIndexType(value string) bool { return indexTypeSet[value] } -func IsCacheProvider(value string) bool { return cacheProviderSet[value] } -func IsMultiTenancyMode(value string) bool { return multiTenancyModeSet[value] } -func IsRateLimitPolicy(value string) bool { return rateLimitPolicySet[value] } -func IsPermissionKey(value string) bool { return permissionKeySet[value] } -func IsDatabase(value string) bool { return databaseSet[value] } -func IsAPIStyle(value string) bool { return apiStyleSet[value] } -func IsAuthType(value string) bool { return authTypeSet[value] } -func IsAddon(value string) bool { return addonSet[value] } -func IsInfraQueue(value string) bool { return infraQueueSet[value] } -func IsInfraCacheStore(value string) bool { return infraCacheStoreSet[value] } -func IsInfraSecretStore(value string) bool { return infraSecretStoreSet[value] } -func IsInfraStore(value string) bool { return infraStoreSet[value] } -func IsStringValidationModifier(mod string) bool { return stringValidationModSet[mod] } +// IsPrimitive reports whether typeName is a built-in field type. +func IsPrimitive(typeName string) bool { return primitiveSet[typeName] } + +// IsNumeric reports whether typeName is a numeric field type. +func IsNumeric(typeName string) bool { return numericSet[typeName] } + +// IsIntegralType reports whether typeName is an integral field type (int or bigint). +func IsIntegralType(typeName string) bool { return integralSet[typeName] } + +// IsFloatType reports whether typeName is a floating-point field type (float or decimal). +func IsFloatType(typeName string) bool { return floatSet[typeName] } + +// IsStringType reports whether typeName is a string or text field type. +func IsStringType(typeName string) bool { return stringSet[typeName] } + +// IsBooleanType reports whether typeName is a boolean field type. +func IsBooleanType(typeName string) bool { return booleanSet[typeName] } + +// IsSortDirection reports whether value is a supported sort direction. +func IsSortDirection(value string) bool { return sortDirectionSet[value] } + +// IsFieldType reports whether typeName is any allowed field type. +func IsFieldType(typeName string) bool { return fieldTypeSet[typeName] } + +// IsOnDeleteValue reports whether value is an allowed on_delete behavior. +func IsOnDeleteValue(value string) bool { return onDeleteSet[value] } + +// IsFeature reports whether name is an allowed entity feature. +func IsFeature(name string) bool { return featureSet[name] } + +// IsIndexType reports whether value is an allowed index type. +func IsIndexType(value string) bool { return indexTypeSet[value] } + +// IsCacheProvider reports whether value is an allowed cache provider. +func IsCacheProvider(value string) bool { return cacheProviderSet[value] } + +// IsMultiTenancyMode reports whether value is an allowed multi-tenancy mode. +func IsMultiTenancyMode(value string) bool { return multiTenancyModeSet[value] } + +// IsRateLimitPolicy reports whether value is an allowed rate-limit policy. +func IsRateLimitPolicy(value string) bool { return rateLimitPolicySet[value] } + +// IsPermissionKey reports whether value is an allowed permission operation. +func IsPermissionKey(value string) bool { return permissionKeySet[value] } + +// IsDatabase reports whether value is a supported database. +func IsDatabase(value string) bool { return databaseSet[value] } + +// IsAPIStyle reports whether value is a supported API style. +func IsAPIStyle(value string) bool { return apiStyleSet[value] } + +// IsAuthType reports whether value is a supported auth type. +func IsAuthType(value string) bool { return authTypeSet[value] } + +// IsAuthEnabled reports whether an auth type enables the auth flow. An unset +// type is disabled, matching the parser default ("none"), so hand-built +// schemas behave like parsed ones. +func IsAuthEnabled(value string) bool { return value != "" && value != AuthTypeNone } + +// IsAddon reports whether value is a known infrastructure addon. +func IsAddon(value string) bool { return addonSet[value] } + +// IsInfraQueue reports whether value is a supported queue backend. +func IsInfraQueue(value string) bool { return infraQueueSet[value] } + +// IsInfraCacheStore reports whether value is a supported cache store. +func IsInfraCacheStore(value string) bool { return infraCacheStoreSet[value] } + +// IsInfraSecretStore reports whether value is a supported secret store. +func IsInfraSecretStore(value string) bool { return infraSecretStoreSet[value] } + +// IsInfraStore reports whether value is a supported object store. +func IsInfraStore(value string) bool { return infraStoreSet[value] } + +// IsStringValidationModifier reports whether mod applies to string fields. +func IsStringValidationModifier(mod string) bool { return stringValidationModSet[mod] } + +// IsValidationModifier reports whether mod may appear as a `mod:value` +// modifier, including bridge-provided extras. Validation rules and the lexer +// share this predicate so the accepted vocabulary cannot drift. +func IsValidationModifier(mod string, extra []string) bool { + return IsStringValidationModifier(mod) || IsNumericValidationModifier(mod) || slices.Contains(extra, mod) +} + +// IsStringOnlyValidationModifier reports whether mod is invalid on numeric fields. +func IsStringOnlyValidationModifier(mod string) bool { return stringOnlyValidationModSet[mod] } + +// IsStringFlagValidationModifier reports whether mod is a bare string flag. +func IsStringFlagValidationModifier(mod string) bool { return stringFlagValidationModSet[mod] } + +// IsNumericValidationModifier reports whether mod applies to numeric fields. func IsNumericValidationModifier(mod string) bool { return numericValidationModSet[mod] } +// SliceToSet converts a slice to a set for constant-time membership checks. func SliceToSet(items []string) map[string]bool { set := make(map[string]bool, len(items)) for _, item := range items { @@ -170,17 +362,141 @@ func SliceToSet(items []string) map[string]bool { return set } +// IsArrayType reports whether dbType is a closed array declaration. An +// unclosed `array(int` is not an array — it fails closed everywhere. func IsArrayType(dbType string) bool { - return strings.HasPrefix(dbType, "array(") + return strings.HasPrefix(dbType, FieldTypeArray+"(") && strings.HasSuffix(strings.TrimSpace(dbType), ")") } +// ParseArrayInner returns the element type of a closed array declaration, or +// dbType unchanged. An unclosed declaration is never silently repaired. func ParseArrayInner(dbType string) string { if !IsArrayType(dbType) { return dbType } - return strings.TrimSuffix(strings.TrimPrefix(dbType, "array("), ")") + return strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(dbType), FieldTypeArray+"("), ")") +} + +// SplitRespectingQuotes splits on commas that are outside quotes and outside +// square brackets. It is the single splitter for modifier clauses and array +// defaults, so a comma inside a quoted value cannot be read as a separator by +// one consumer and as data by another. +func SplitRespectingQuotes(s string) []string { + var out []string + var cur strings.Builder + depth := 0 + var quote byte + for i := 0; i < len(s); i++ { + c := s[i] + if quote != 0 { + cur.WriteByte(c) + if c == quote { + quote = 0 + } + continue + } + switch c { + case '\'', '"': + quote = c + cur.WriteByte(c) + case '[': + depth++ + cur.WriteByte(c) + case ']': + if depth > 0 { + depth-- + } + cur.WriteByte(c) + case ',': + if depth == 0 { + out = append(out, cur.String()) + cur.Reset() + continue + } + cur.WriteByte(c) + default: + cur.WriteByte(c) + } + } + return append(out, cur.String()) +} + +// SplitArrayDefault splits an array literal into its elements. A scalar is +// returned as a single element; an unclosed literal fails closed as one element +// so the type checker can reject it. Shared by validation and seed generation +// so both paths parse a bracketed default the same way. +func SplitArrayDefault(defaultVal string) []string { + if !strings.HasPrefix(defaultVal, "[") || !strings.HasSuffix(defaultVal, "]") { + return []string{defaultVal} + } + inner := strings.TrimSpace(defaultVal[1 : len(defaultVal)-1]) + if inner == "" { + return nil + } + parts := SplitRespectingQuotes(inner) + for i := range parts { + parts[i] = strings.TrimSpace(parts[i]) + } + return parts +} + +// IsSingleBackRelationField reports whether a single relation points from a +// target entity back to a source entity. The validator and the IR builder share +// this rule when pairing a `[many]` relation with the FK on its target. +func IsSingleBackRelationField(isRelation, isMany bool, targetName, sourceName string) bool { + return isRelation && !isMany && targetName != "" && targetName == sourceName +} + +// HasIDSuffix reports whether name ends with a supported FK suffix (Id or ID) +// and is long enough to strip it without losing the whole name. Lowercase "id" +// is not an FK format in this project: words such as fluid or squid keep it. +func HasIDSuffix(name string) bool { + return len(name) > 2 && (strings.HasSuffix(name, "Id") || strings.HasSuffix(name, "ID")) +} + +// FieldKindJSON is the value kind returned for json and jsonb columns. It is +// shared by the validator and seed generator so a rename cannot silently +// disconnect either consumer from FieldKind. +const FieldKindJSON = "json" + +// FieldKindEnum is the value kind returned for non-primitive (user-declared) +// types. +const FieldKindEnum = "enum" + +// FieldKind returns the language-agnostic value kind of a primitive type. +func FieldKind(dbType string) string { + switch { + case IsStringType(dbType): + return "text" + case dbType == FieldTypeInt: + return "int" + case dbType == FieldTypeBigint: + return "bigint" + case dbType == FieldTypeFloat: + return "float" + case dbType == FieldTypeDecimal: + return "decimal" + case IsBooleanType(dbType): + return "bool" + case dbType == FieldTypeDate: + return "date" + case dbType == FieldTypeDatetime: + return "datetime" + case dbType == FieldTypeUUID: + return "uuid" + case dbType == FieldTypeJSON || dbType == FieldTypeJSONB: + return FieldKindJSON + case !IsPrimitive(dbType): + return FieldKindEnum + default: + // Defensive fallback for a future primitive added to specmeta without + // a matching case above. TestFieldKindCoversEveryPrimitive makes that + // omission visible instead of letting it pass silently as "text". + return "text" + } } +// FindAuthEntity returns the first entity with email and password fields. func FindAuthEntity(entityOrder []string, entityFields map[string][]string) string { for _, name := range entityOrder { if HasEmailAndPassword(entityFields[name]) { @@ -190,6 +506,7 @@ func FindAuthEntity(entityOrder []string, entityFields map[string][]string) stri return "" } +// HasEmailAndPassword reports whether the field list contains both auth fields. func HasEmailAndPassword(fieldNames []string) bool { hasEmail, hasPassword := AuthFieldState(fieldNames) return hasEmail && hasPassword @@ -209,6 +526,7 @@ func AuthFieldState(fieldNames []string) (hasEmail, hasPassword bool) { return hasEmail, hasPassword } +// BuildEntityFields maps each entity name to its field names in declaration order. func BuildEntityFields(entityOrder []string, getFields func(name string) []string) map[string][]string { result := make(map[string][]string, len(entityOrder)) for _, name := range entityOrder { @@ -228,3 +546,35 @@ func IsOwnershipToken(role string) bool { return strings.HasPrefix(role, "@") } func IsReservedPermissionToken(role string) bool { return IsPublicPermission(role) || IsOwnershipToken(role) } + +// IsValidIdentifier reports whether s is a valid domain.yaml identifier. The +// rule is the one shared by entity, field, enum and role names: a non-empty +// ASCII string starting with a letter or underscore, followed by letters, +// digits or underscores. It is the single source of truth for this rule — the +// parser, lexer and validator must not re-derive it. +func IsValidIdentifier(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + letter := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') + if i == 0 { + if !letter && c != '_' { + return false + } + continue + } + if !letter && (c < '0' || c > '9') && c != '_' { + return false + } + } + return true +} + +// IsIdentifierRune reports whether r can appear inside an identifier in source +// text. It is intentionally wider than IsValidIdentifier: rename rewriting must +// recognise Unicode identifiers that domain.yaml itself does not allow. +func IsIdentifierRune(r rune) bool { + return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' +} diff --git a/internal/specmeta/specmeta_json.go b/internal/specmeta/specmeta_json.go index 97f7f8d..d968769 100644 --- a/internal/specmeta/specmeta_json.go +++ b/internal/specmeta/specmeta_json.go @@ -1,38 +1,44 @@ package specmeta -// SpecmetaJSON returns every specmeta constant as a JSON-ready map. This is the +import ( + "maps" + "slices" +) + +// JSON returns every specmeta constant as a JSON-ready map. This is the // single source of the shape exposed to the GUI via the WASM bridge // (cmd/wasm-validator -> goSpecmeta). The GUI loads it once at boot into its // live SPECMETA object — no other copy is shipped. // // Keep the keys in sync with the Specmeta type in // domaincraft-studio/src/lib/specmeta.ts. -func SpecmetaJSON() map[string]any { +func JSON() map[string]any { + strings := func(s []string) []string { return slices.Clone(s) } return map[string]any{ - "primitiveFieldTypes": PrimitiveFieldTypes, - "stringFieldTypes": StringFieldTypes, - "numericFieldTypes": NumericFieldTypes, - "booleanFieldTypes": BooleanFieldTypes, - "metaFieldTypes": MetaFieldTypes, - "fieldTypes": FieldTypes, - "onDeleteValues": OnDeleteValues, - "features": Features, - "addons": Addons, - "indexTypes": IndexTypes, - "databases": Databases, - "apiStyles": APIStyles, - "authTypes": AuthTypes, - "cacheProviders": CacheProviders, - "multiTenancyModes": MultiTenancyModes, - "rateLimitPolicies": RateLimitPolicies, - "permissionKeys": PermissionKeys, - "sortDirections": SortDirections, - "stringValidationModifiers": StringValidationModifiers, - "numericValidationModifiers": NumericValidationModifiers, - "infraQueues": InfraQueues, - "infraCacheStores": InfraCacheStores, - "infraSecretStores": InfraSecretStores, - "infraStores": InfraStores, - "featureFieldDefs": FeatureFieldDefs, + "primitiveFieldTypes": strings(PrimitiveFieldTypes), + "stringFieldTypes": strings(StringFieldTypes), + "numericFieldTypes": strings(NumericFieldTypes), + "booleanFieldTypes": strings(BooleanFieldTypes), + "metaFieldTypes": strings(MetaFieldTypes), + "fieldTypes": strings(FieldTypes), + "onDeleteValues": strings(OnDeleteValues), + "features": strings(Features), + "addons": strings(Addons), + "indexTypes": strings(IndexTypes), + "databases": strings(Databases), + "apiStyles": strings(APIStyles), + "authTypes": strings(AuthTypes), + "cacheProviders": strings(CacheProviders), + "multiTenancyModes": strings(MultiTenancyModes), + "rateLimitPolicies": strings(RateLimitPolicies), + "permissionKeys": strings(PermissionKeys), + "sortDirections": strings(SortDirections), + "stringValidationModifiers": strings(stringValidationModifiers), + "numericValidationModifiers": strings(NumericValidationModifiers), + "infraQueues": strings(InfraQueues), + "infraCacheStores": strings(InfraCacheStores), + "infraSecretStores": strings(InfraSecretStores), + "infraStores": strings(InfraStores), + "featureFieldDefs": maps.Clone(FeatureFieldDefs), } } diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index 55c32db..d2896c8 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -1,8 +1,13 @@ package specmeta -import "testing" +import ( + "fmt" + "strings" + "testing" +) func TestIsPrimitive(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -19,23 +24,27 @@ func TestIsPrimitive(t *testing.T) { {"uuid", true}, {"json", true}, {"jsonb", true}, - {"STRING", false}, // case-sensitive, callers must lowercase + {"STRING", false}, // case-sensitive, callers must lowercase {"ProductStatus", false}, // enum - {"enum", false}, // meta-type - {"array", false}, // meta-type - {"relation", false}, // meta-type + {"enum", false}, // meta-type + {"array", false}, // meta-type + {"relation", false}, // meta-type {"", false}, } for _, tt := range tests { - got := IsPrimitive(tt.input) - if got != tt.want { - t.Errorf("IsPrimitive(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + got := IsPrimitive(tt.input) + if got != tt.want { + t.Errorf("IsPrimitive(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestFieldTypesDerivedCorrectly(t *testing.T) { + t.Parallel() expected := len(PrimitiveFieldTypes) + len(MetaFieldTypes) if len(FieldTypes) != expected { t.Errorf("len(FieldTypes) = %d, want %d (= PrimitiveFieldTypes + MetaFieldTypes)", len(FieldTypes), expected) @@ -50,6 +59,7 @@ func TestFieldTypesDerivedCorrectly(t *testing.T) { } func TestIsNumeric(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -65,13 +75,17 @@ func TestIsNumeric(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsNumeric(tt.input); got != tt.want { - t.Errorf("IsNumeric(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsNumeric(tt.input); got != tt.want { + t.Errorf("IsNumeric(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsStringType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -83,13 +97,17 @@ func TestIsStringType(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsStringType(tt.input); got != tt.want { - t.Errorf("IsStringType(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsStringType(tt.input); got != tt.want { + t.Errorf("IsStringType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsBooleanType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -101,13 +119,17 @@ func TestIsBooleanType(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsBooleanType(tt.input); got != tt.want { - t.Errorf("IsBooleanType(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsBooleanType(tt.input); got != tt.want { + t.Errorf("IsBooleanType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsIndexType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -121,13 +143,17 @@ func TestIsIndexType(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsIndexType(tt.input); got != tt.want { - t.Errorf("IsIndexType(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsIndexType(tt.input); got != tt.want { + t.Errorf("IsIndexType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsCacheProvider(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -139,13 +165,57 @@ func TestIsCacheProvider(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsCacheProvider(tt.input); got != tt.want { - t.Errorf("IsCacheProvider(%q) = %v, want %v", tt.input, got, tt.want) + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsCacheProvider(tt.input); got != tt.want { + t.Errorf("IsCacheProvider(%q) = %v, want %v", tt.input, got, tt.want) + } + }) + } +} + +func TestCacheProvidersShareInfraCacheStores(t *testing.T) { + t.Parallel() + if len(CacheProviders) != len(InfraCacheStores) || len(CacheProviders) == 0 { + t.Fatalf("cache vocabularies differ in length: %d vs %d", len(CacheProviders), len(InfraCacheStores)) + } + for i := range CacheProviders { + if CacheProviders[i] != InfraCacheStores[i] { + t.Errorf("CacheProviders[%d] = %q, InfraCacheStores[%d] = %q", i, CacheProviders[i], i, InfraCacheStores[i]) + } + } + // Both names must share one backing slice, not two copies that can drift. + if &CacheProviders[0] != &InfraCacheStores[0] { + t.Error("CacheProviders and InfraCacheStores do not share the same backing slice") + } +} + +func TestStringModifierPredicatesMatchSlices(t *testing.T) { + t.Parallel() + for _, mod := range stringValidationModifiers { + if !IsStringValidationModifier(mod) { + t.Errorf("IsStringValidationModifier(%q) = false, want true", mod) + } + } + for _, mod := range StringOnlyValidationModifiers { + if !IsStringOnlyValidationModifier(mod) { + t.Errorf("IsStringOnlyValidationModifier(%q) = false, want true", mod) + } + } + for _, mod := range StringFlagValidationModifiers { + if !IsStringFlagValidationModifier(mod) { + t.Errorf("IsStringFlagValidationModifier(%q) = false, want true", mod) + } + } + for _, mod := range []string{"gte", "lte", "unknown", ""} { + if IsStringOnlyValidationModifier(mod) || IsStringFlagValidationModifier(mod) { + t.Errorf("numeric/unknown modifier %q must not be a string-only or string flag modifier", mod) } } } func TestIsMultiTenancyMode(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -157,13 +227,17 @@ func TestIsMultiTenancyMode(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsMultiTenancyMode(tt.input); got != tt.want { - t.Errorf("IsMultiTenancyMode(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsMultiTenancyMode(tt.input); got != tt.want { + t.Errorf("IsMultiTenancyMode(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsPermissionKey(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -176,13 +250,17 @@ func TestIsPermissionKey(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsPermissionKey(tt.input); got != tt.want { - t.Errorf("IsPermissionKey(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsPermissionKey(tt.input); got != tt.want { + t.Errorf("IsPermissionKey(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsStringValidationModifier(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -198,13 +276,17 @@ func TestIsStringValidationModifier(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsStringValidationModifier(tt.input); got != tt.want { - t.Errorf("IsStringValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsStringValidationModifier(tt.input); got != tt.want { + t.Errorf("IsStringValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsNumericValidationModifier(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -218,13 +300,17 @@ func TestIsNumericValidationModifier(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsNumericValidationModifier(tt.input); got != tt.want { - t.Errorf("IsNumericValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsNumericValidationModifier(tt.input); got != tt.want { + t.Errorf("IsNumericValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestFindAuthEntity(t *testing.T) { + t.Parallel() tests := []struct { name string entityOrder []string @@ -264,6 +350,7 @@ func TestFindAuthEntity(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() got := FindAuthEntity(tt.entityOrder, tt.entityFields) if got != tt.want { t.Errorf("FindAuthEntity() = %q, want %q", got, tt.want) @@ -273,6 +360,7 @@ func TestFindAuthEntity(t *testing.T) { } func TestIsSortDirection(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -284,13 +372,17 @@ func TestIsSortDirection(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsSortDirection(tt.input); got != tt.want { - t.Errorf("IsSortDirection(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsSortDirection(tt.input); got != tt.want { + t.Errorf("IsSortDirection(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestHasEmailAndPassword(t *testing.T) { + t.Parallel() tests := []struct { name string fieldNames []string @@ -305,6 +397,7 @@ func TestHasEmailAndPassword(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() if got := HasEmailAndPassword(tt.fieldNames); got != tt.want { t.Errorf("HasEmailAndPassword(%v) = %v, want %v", tt.fieldNames, got, tt.want) } @@ -313,6 +406,7 @@ func TestHasEmailAndPassword(t *testing.T) { } func TestFuncDefaultsContainsExpectedEntries(t *testing.T) { + t.Parallel() if _, ok := FuncDefaults["now"]; !ok { t.Error("FuncDefaults missing 'now'") } @@ -328,6 +422,7 @@ func TestFuncDefaultsContainsExpectedEntries(t *testing.T) { } func TestIsDatabase(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -343,13 +438,17 @@ func TestIsDatabase(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsDatabase(tt.input); got != tt.want { - t.Errorf("IsDatabase(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsDatabase(tt.input); got != tt.want { + t.Errorf("IsDatabase(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsAPIStyle(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -362,31 +461,39 @@ func TestIsAPIStyle(t *testing.T) { {"", false}, } for _, tt := range tests { - if got := IsAPIStyle(tt.input); got != tt.want { - t.Errorf("IsAPIStyle(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsAPIStyle(tt.input); got != tt.want { + t.Errorf("IsAPIStyle(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestIsAuthType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool }{ {"jwt", true}, {"none", true}, - {"JWT", false}, // case-sensitive + {"JWT", false}, // case-sensitive {"oauth", false}, {"", false}, } for _, tt := range tests { - if got := IsAuthType(tt.input); got != tt.want { - t.Errorf("IsAuthType(%q) = %v, want %v", tt.input, got, tt.want) - } + t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Parallel() + if got := IsAuthType(tt.input); got != tt.want { + t.Errorf("IsAuthType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } func TestBuildEntityFields(t *testing.T) { + t.Parallel() entityOrder := []string{"User", "Product"} getFields := func(name string) []string { switch name { @@ -413,8 +520,273 @@ func TestBuildEntityFields(t *testing.T) { } func TestBuildEntityFieldsEmptyOrder(t *testing.T) { - result := BuildEntityFields(nil, func(name string) []string { return nil }) + t.Parallel() + result := BuildEntityFields(nil, func(_ string) []string { return nil }) if len(result) != 0 { t.Errorf("BuildEntityFields(nil) returned %d entries, want 0", len(result)) } } + +func TestNumericFieldTypesDerivedFromGroups(t *testing.T) { + t.Parallel() + want := []string{"int", "bigint", "float", "decimal"} + if len(NumericFieldTypes) != len(want) { + t.Fatalf("NumericFieldTypes = %v, want %v", NumericFieldTypes, want) + } + for i := range want { + if NumericFieldTypes[i] != want[i] { + t.Errorf("NumericFieldTypes[%d] = %q, want %q", i, NumericFieldTypes[i], want[i]) + } + } +} + +// A comma inside a quoted array element is data, not a separator. The lexer +// and the seed/validator paths must agree on the same split. +// Every declared primitive must have an explicit kind. Without this guard a +// new primitive would fall through FieldKind's defensive "text" branch and +// silently change validation and seed coercion. +func TestFieldKindCoversEveryPrimitive(t *testing.T) { + t.Parallel() + for _, name := range PrimitiveFieldTypes { + if got := FieldKind(name); got == FieldKindEnum { + t.Errorf("FieldKind(%q) = enum; add an explicit case", name) + } + } + if got := FieldKind("NotAPrimitive"); got != FieldKindEnum { + t.Errorf("FieldKind(unknown) = %q, want %q", got, FieldKindEnum) + } +} + +func TestSplitArrayDefaultRespectsQuotes(t *testing.T) { + t.Parallel() + got := SplitArrayDefault(`["a,b", "c"]`) + if len(got) != 2 || !strings.Contains(got[0], "a,b") || !strings.Contains(got[1], "c") { + t.Fatalf("SplitArrayDefault = %q, want two elements with the comma inside the first", got) + } + if SplitRespectingQuotes(`default:["a,b", other]`) == nil { + t.Fatal("SplitRespectingQuotes returned nil") + } +} + +func TestEffectiveContractVersion(t *testing.T) { + t.Parallel() + cases := []struct { + name string + declared int + want int + }{ + {name: "absent declaration defaults to shared constant", declared: 0, want: ContractVersion}, + {name: "negative declaration defaults to shared constant", declared: -1, want: ContractVersion}, + {name: "explicit version is preserved", declared: 1, want: 1}, + {name: "explicit version is preserved", declared: ContractVersion, want: ContractVersion}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := EffectiveContractVersion(c.declared); got != c.want { + t.Errorf("EffectiveContractVersion(%d) = %d, want %d", c.declared, got, c.want) + } + }) + } +} + +func TestIsIntegralType(t *testing.T) { + t.Parallel() + cases := []struct { + name string + in string + want bool + }{ + {name: "int", in: "int", want: true}, + {name: "bigint", in: "bigint", want: true}, + {name: "float is not integral", in: "float"}, + {name: "decimal is not integral", in: "decimal"}, + {name: "enum is not integral", in: "Status"}, + {name: "empty", in: ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := IsIntegralType(c.in); got != c.want { + t.Errorf("IsIntegralType(%q) = %v, want %v", c.in, got, c.want) + } + }) + } +} + +func TestIsFloatType(t *testing.T) { + t.Parallel() + cases := []struct { + name string + in string + want bool + }{ + {name: "float", in: "float", want: true}, + {name: "decimal", in: "decimal", want: true}, + {name: "int is not float", in: "int"}, + {name: "bigint is not float", in: "bigint"}, + {name: "enum is not float", in: "Status"}, + {name: "empty", in: ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := IsFloatType(c.in); got != c.want { + t.Errorf("IsFloatType(%q) = %v, want %v", c.in, got, c.want) + } + }) + } +} + +func TestIsValidIdentifier(t *testing.T) { + t.Parallel() + cases := []struct { + name string + in string + want bool + }{ + {name: "single letter", in: "A", want: true}, + {name: "underscore", in: "_", want: true}, + {name: "mixed case with digits", in: "Order_2Item", want: true}, + {name: "leading digit rejected", in: "2Item"}, + {name: "hyphen rejected", in: "order-item"}, + {name: "space rejected", in: "order item"}, + {name: "non-ASCII rejected", in: "продукт"}, + {name: "empty rejected", in: ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := IsValidIdentifier(c.in); got != c.want { + t.Errorf("IsValidIdentifier(%q) = %v, want %v", c.in, got, c.want) + } + }) + } +} + +func TestArrayDeclarationRequiresClosingParen(t *testing.T) { + t.Parallel() + for _, dbType := range []string{"array(int", "array(Status", "array(", "array"} { + if IsArrayType(dbType) { + t.Errorf("IsArrayType(%q) = true, want false", dbType) + } + if got := ParseArrayInner(dbType); got != dbType { + t.Errorf("ParseArrayInner(%q) = %q, want unchanged", dbType, got) + } + } + for _, c := range []struct{ in, want string }{ + {in: "array(int)", want: "int"}, + {in: "array(Status)", want: "Status"}, + } { + if !IsArrayType(c.in) { + t.Errorf("IsArrayType(%q) = false, want true", c.in) + } + if got := ParseArrayInner(c.in); got != c.want { + t.Errorf("ParseArrayInner(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestIsSingleBackRelationField(t *testing.T) { + t.Parallel() + cases := []struct { + name string + isRelation, isMany bool + targetName, sourceName string + want bool + }{ + {name: "single FK back", isRelation: true, targetName: "Order", sourceName: "Order", want: true}, + {name: "many is not a back FK", isRelation: true, isMany: true, targetName: "Order", sourceName: "Order"}, + {name: "points elsewhere", isRelation: true, targetName: "User", sourceName: "Order"}, + {name: "scalar field", targetName: "Order", sourceName: "Order"}, + {name: "empty target", isRelation: true, sourceName: "Order"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := IsSingleBackRelationField(c.isRelation, c.isMany, c.targetName, c.sourceName); got != c.want { + t.Errorf("IsSingleBackRelationField(%t, %t, %q, %q) = %t, want %t", + c.isRelation, c.isMany, c.targetName, c.sourceName, got, c.want) + } + }) + } +} + +func TestFieldKind(t *testing.T) { + t.Parallel() + want := map[string]string{ + FieldTypeUUID: "uuid", FieldTypeString: "text", FieldTypeText: "text", + FieldTypeInt: "int", FieldTypeBigint: "bigint", FieldTypeFloat: "float", FieldTypeDecimal: "decimal", + FieldTypeBoolean: "bool", FieldTypeDate: "date", FieldTypeDatetime: "datetime", + FieldTypeJSON: "json", FieldTypeJSONB: "json", + } + for _, typ := range PrimitiveFieldTypes { + expected, ok := want[typ] + if !ok { + t.Fatalf("no expected kind for primitive type %q", typ) + } + if got := FieldKind(typ); got != expected { + t.Errorf("FieldKind(%q) = %q, want %q", typ, got, expected) + } + } + if got := FieldKind("Status"); got != "enum" { + t.Errorf("FieldKind(Status) = %q, want enum", got) + } +} + +func TestHasIDSuffix(t *testing.T) { + t.Parallel() + for _, name := range []string{"categoryId", "categoryID"} { + if !HasIDSuffix(name) { + t.Errorf("HasIDSuffix(%q) = false, want true", name) + } + } + for _, name := range []string{"id", "category", "", "fluid", "squid", "avoid", "categoryid"} { + if HasIDSuffix(name) { + t.Errorf("HasIDSuffix(%q) = true, want false", name) + } + } +} + +func TestIsIdentifierRune(t *testing.T) { + t.Parallel() + cases := []struct { + name string + in rune + want bool + }{ + {name: "ascii letter", in: 'a', want: true}, + {name: "ascii digit", in: '7', want: true}, + {name: "underscore", in: '_', want: true}, + {name: "unicode letter", in: 'é', want: true}, + {name: "unicode digit", in: '७', want: true}, + {name: "dash", in: '-', want: false}, + {name: "space", in: ' ', want: false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := IsIdentifierRune(c.in); got != c.want { + t.Errorf("IsIdentifierRune(%q) = %v, want %v", c.in, got, c.want) + } + }) + } +} + +func TestJSONReturnsDefensiveCopies(t *testing.T) { + t.Parallel() + before := len(PrimitiveFieldTypes) + out := JSON() + list := out["primitiveFieldTypes"].([]string) + list[0] = "mutated" + if PrimitiveFieldTypes[0] == "mutated" || len(PrimitiveFieldTypes) != before { + t.Fatal("mutating JSON() changed the canonical primitive field types") + } + defs := out["featureFieldDefs"].(map[string]FeatureFieldDef) + for key := range defs { + delete(defs, key) + } + if len(FeatureFieldDefs) == 0 { + t.Fatal("mutating JSON() emptied the canonical feature field defs") + } +} diff --git a/internal/templatefuncs/templatefuncs.go b/internal/templatefuncs/templatefuncs.go index 50cedc1..6648e8a 100644 --- a/internal/templatefuncs/templatefuncs.go +++ b/internal/templatefuncs/templatefuncs.go @@ -7,6 +7,7 @@ package templatefuncs import ( "fmt" + "math" "path" "reflect" "strconv" @@ -23,40 +24,40 @@ import ( // silently missing function. func FuncMap() template.FuncMap { return template.FuncMap{ - "add": Add, - "any": Any, - "append": Append, - "atoi": Atoi, - "base": path.Base, - "camelcase": CamelCase, - "contains": Contains, - "default": Default, - "dict": Dict, - "fkName": textutil.FKName, - "hasPrefix": HasPrefix, - "humanize": Humanize, - "join": Join, - "kebabcase": textutil.KebabCase, - "kindIs": KindIs, - "kindOf": KindOf, - "list": List, - "lower": strings.ToLower, - "lowercase": strings.ToLower, - "now": time.Now, + "add": Add, + "any": Any, + "append": Append, + "atoi": func(s string) int { return AtoiOrDefault(s, 0) }, + "base": path.Base, + "camelcase": CamelCase, + "contains": Contains, + "default": Default, + "dict": Dict, + "fkName": textutil.FKName, + "hasPrefix": HasPrefix, + "humanize": Humanize, + "join": Join, + "kebabcase": textutil.KebabCase, + "kindIs": KindIs, + "kindOf": KindOf, + "list": List, + "lower": strings.ToLower, + "lowercase": strings.ToLower, + "now": time.Now, "pascalcase": PascalCase, - "pluralize": textutil.Pluralize, - "set": Set, - "snakecase": textutil.SnakeCase, - "splitList": SplitList, - "title": strings.Title, - "toString": ToString, - "upper": strings.ToUpper, - "uppercase": strings.ToUpper, + "pluralize": textutil.Pluralize, + "set": Set, + "snakecase": textutil.SnakeCase, + "splitList": SplitList, + "title": strings.Title, //nolint:staticcheck // published template contract; cases.Title would change word boundaries + "toString": ToString, + "upper": strings.ToUpper, + "uppercase": strings.ToUpper, } } // Add sums all arguments as int64. -func Add(i ...interface{}) int64 { +func Add(i ...any) int64 { var a int64 for _, b := range i { a += toInt64(b) @@ -65,7 +66,7 @@ func Add(i ...interface{}) int64 { } // Any reports whether any argument is non-empty. -func Any(v ...interface{}) bool { +func Any(v ...any) bool { for _, val := range v { if !empty(val) { return true @@ -74,27 +75,37 @@ func Any(v ...interface{}) bool { return false } -// Atoi parses s as an integer, returning 0 on error. -func Atoi(s string) int { - i, _ := strconv.Atoi(s) +// Atoi parses s as an integer. Invalid input is an error, not a silent zero. +func Atoi(s string) (int, error) { + return strconv.Atoi(s) +} + +// AtoiOrDefault parses s and returns fallback when s is not an integer. It is +// the explicit tolerant form used by the template `atoi` contract, which has +// always rendered 0 for an unparseable value. +func AtoiOrDefault(s string, fallback int) int { + i, err := Atoi(s) + if err != nil { + return fallback + } return i } // Append appends v to a slice (any slice kind) and returns the result as -// []interface{}. It panics on a non-slice, which text/template surfaces as a -// render error. -func Append(list interface{}, v interface{}) []interface{} { +// []any. A non-slice is a returned error rather than a panic; text/template +// surfaces either as a render error. +func Append(list any, v any) ([]any, error) { val := reflect.ValueOf(list) switch val.Kind() { case reflect.Slice, reflect.Array: l := val.Len() - nl := make([]interface{}, l) + nl := make([]any, l) for i := range l { nl[i] = val.Index(i).Interface() } - return append(nl, v) + return append(nl, v), nil default: - panic("append: not a slice") + return nil, fmt.Errorf("append: not a slice, got %T", list) } } @@ -137,24 +148,24 @@ func stringArg(v any) string { // Default returns d unless the first given value is empty (zero values are // considered unset). -func Default(d interface{}, given ...interface{}) interface{} { +func Default(d any, given ...any) any { if empty(given) || empty(given[0]) { return d } return given[0] } -// Dict builds a map[string]interface{} from key/value pairs. An odd trailing +// Dict builds a map[string]any from key/value pairs. An odd trailing // key is assigned an empty string. -func Dict(v ...interface{}) map[string]interface{} { - dict := make(map[string]interface{}, len(v)/2+1) +func Dict(v ...any) map[string]any { + dict := make(map[string]any, len(v)/2+1) for i := 0; i < len(v); i += 2 { key := ToString(v[i]) if i+1 >= len(v) { dict[key] = "" continue } - dict[key] = v[i+1] + dict[key] = v[i+1] //nolint:gosec // i+1 is guarded by the length check above } return dict } @@ -165,31 +176,34 @@ func HasPrefix(prefix, str string) bool { return strings.HasPrefix(str, prefix) } -// Join joins the elements of v (a []string, []interface{}, or any slice) with +// Join joins the elements of v (a []string, []any, or any slice) with // sep (sep comes first when called as a pipeline). -func Join(sep string, v interface{}) string { +func Join(sep string, v any) string { return strings.Join(strslice(v), sep) } // KindIs reports whether src's reflect.Kind equals target (e.g. "slice"). -func KindIs(target string, src interface{}) bool { +func KindIs(target string, src any) bool { return target == KindOf(src) } -// List returns its arguments as a []interface{}. With no arguments it yields +// List returns its arguments as a []any. With no arguments it yields // an empty slice, which is the common "start a list, then append" idiom in // templates. -func List(v ...interface{}) []interface{} { +func List(v ...any) []any { return v } // KindOf returns the reflect.Kind name of src (e.g. "string", "slice"). -func KindOf(src interface{}) string { +func KindOf(src any) string { return reflect.ValueOf(src).Kind().String() } // Set assigns value under key in d and returns d. -func Set(d map[string]interface{}, key string, value interface{}) map[string]interface{} { +func Set(d map[string]any, key string, value any) map[string]any { + if d == nil { + d = make(map[string]any) + } d[key] = value return d } @@ -202,7 +216,7 @@ func SplitList(sep, orig string) []string { // ToString renders v as a string (strings pass through, fmt.Stringer values // use String(), everything else is fmt.Sprint'ed). -func ToString(v interface{}) string { +func ToString(v any) string { switch v := v.(type) { case string: return v @@ -219,7 +233,7 @@ func ToString(v interface{}) string { // empty reports whether given holds the zero value for its type (the same // semantics text/template's isTrue uses). -func empty(given interface{}) bool { +func empty(given any) bool { g := reflect.ValueOf(given) if !g.IsValid() { return true @@ -245,11 +259,11 @@ func empty(given interface{}) bool { } // strslice converts v into []string (used by Join). -func strslice(v interface{}) []string { +func strslice(v any) []string { switch v := v.(type) { case []string: return v - case []interface{}: + case []any: b := make([]string, 0, len(v)) for _, s := range v { if s != nil { @@ -281,7 +295,7 @@ func strslice(v interface{}) []string { // toInt64 coerces v to int64 for Add. It covers the numeric and string forms // templates realistically pass; anything else yields 0. -func toInt64(v interface{}) int64 { +func toInt64(v any) int64 { switch val := v.(type) { case int: return int64(val) @@ -294,6 +308,9 @@ func toInt64(v interface{}) int64 { case int64: return val case uint: + if val > math.MaxInt64 { + return math.MaxInt64 + } return int64(val) case uint8: return int64(val) @@ -302,6 +319,9 @@ func toInt64(v interface{}) int64 { case uint32: return int64(val) case uint64: + if val > math.MaxInt64 { + return math.MaxInt64 + } return int64(val) case float32: return int64(val) diff --git a/internal/templatefuncs/templatefuncs_hardening_test.go b/internal/templatefuncs/templatefuncs_hardening_test.go new file mode 100644 index 0000000..d19849d --- /dev/null +++ b/internal/templatefuncs/templatefuncs_hardening_test.go @@ -0,0 +1,11 @@ +package templatefuncs + +import "testing" + +func TestSetInitializesNilMap(t *testing.T) { + t.Parallel() + got := Set(nil, "key", "value") + if got == nil || got["key"] != "value" { + t.Fatalf("Set(nil, ...) = %v, want map with key=value", got) + } +} diff --git a/internal/templatefuncs/templatefuncs_test.go b/internal/templatefuncs/templatefuncs_test.go index cd3e5ca..ed70e53 100644 --- a/internal/templatefuncs/templatefuncs_test.go +++ b/internal/templatefuncs/templatefuncs_test.go @@ -1,13 +1,16 @@ package templatefuncs import ( + "io" "reflect" "testing" + "text/template" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) func TestContainsAndHasPrefixArgOrder(t *testing.T) { + t.Parallel() // The reversed argument order (substr first) must be preserved. if !Contains("ell", "hello") { t.Error("Contains('ell', 'hello') = false, want true") @@ -18,6 +21,7 @@ func TestContainsAndHasPrefixArgOrder(t *testing.T) { } func TestAdd(t *testing.T) { + t.Parallel() got := Add(1, 2, 3) if got != 6 { t.Errorf("Add(1,2,3) = %d, want 6", got) @@ -25,15 +29,34 @@ func TestAdd(t *testing.T) { } func TestAtoi(t *testing.T) { - if got := Atoi("42"); got != 42 { - t.Errorf("Atoi('42') = %d, want 42", got) + t.Parallel() + if got, err := Atoi("42"); err != nil || got != 42 { + t.Errorf("Atoi('42') = (%d, %v), want (42, nil)", got, err) } - if got := Atoi("nope"); got != 0 { - t.Errorf("Atoi('nope') = %d, want 0", got) + if got, err := Atoi("nope"); err == nil || got != 0 { + t.Errorf("Atoi('nope') = (%d, %v), want an error", got, err) + } + if got := AtoiOrDefault("nope", 7); got != 7 { + t.Errorf("AtoiOrDefault('nope', 7) = %d, want 7", got) + } + if got := AtoiOrDefault("42", 7); got != 42 { + t.Errorf("AtoiOrDefault('42', 7) = %d, want 42", got) + } +} + +func TestTemplateAtoiKeepsZeroFallback(t *testing.T) { + t.Parallel() + fn := FuncMap()["atoi"].(func(string) int) + if got := fn("nope"); got != 0 { + t.Errorf("template atoi('nope') = %d, want 0", got) + } + if got := fn("42"); got != 42 { + t.Errorf("template atoi('42') = %d, want 42", got) } } func TestDefault(t *testing.T) { + t.Parallel() if got := Default("fallback", ""); got != "fallback" { t.Errorf("Default(fallback, empty) = %v, want fallback", got) } @@ -46,20 +69,22 @@ func TestDefault(t *testing.T) { } func TestDict(t *testing.T) { + t.Parallel() got := Dict("a", 1, "b", "two") - want := map[string]interface{}{"a": 1, "b": "two"} + want := map[string]any{"a": 1, "b": "two"} if !reflect.DeepEqual(got, want) { t.Errorf("Dict = %v, want %v", got, want) } // Odd trailing key gets empty string. got = Dict("k") - if !reflect.DeepEqual(got, map[string]interface{}{"k": ""}) { + if !reflect.DeepEqual(got, map[string]any{"k": ""}) { t.Errorf("Dict(k) = %v, want {k: ''}", got) } } func TestSet(t *testing.T) { - d := map[string]interface{}{} + t.Parallel() + d := map[string]any{} got := Set(d, "x", 7) if got["x"] != 7 { t.Errorf("Set = %v, want x=7", got) @@ -67,22 +92,48 @@ func TestSet(t *testing.T) { } func TestListAppend(t *testing.T) { + t.Parallel() l := List() if len(l) != 0 { t.Errorf("List() = %v, want empty", l) } - l = Append(l, "a") - l = Append(l, 2) - if !reflect.DeepEqual(l, []interface{}{"a", 2}) { + var err error + l, err = Append(l, "a") + if err != nil { + t.Fatalf("Append: %v", err) + } + l, err = Append(l, 2) + if err != nil { + t.Fatalf("Append: %v", err) + } + if !reflect.DeepEqual(l, []any{"a", 2}) { t.Errorf("Append chain = %v, want [a 2]", l) } // Append also works on typed slices (converted via reflection). - if got := Append([]string{"x", "y"}, "z"); !reflect.DeepEqual(got, []interface{}{"x", "y", "z"}) { - t.Errorf("Append([]string) = %v, want [x y z]", got) + got, err := Append([]string{"x", "y"}, "z") + if err != nil || !reflect.DeepEqual(got, []any{"x", "y", "z"}) { + t.Errorf("Append([]string) = (%v, %v), want ([x y z], nil)", got, err) + } + if _, err := Append(42, "z"); err == nil { + t.Error("Append(non-slice) should return an error, not panic") + } +} + +func TestTemplateAppendReturnsErrorOnNonSlice(t *testing.T) { + t.Parallel() + fm := FuncMap() + // Execution of a two-result function is valid in a pipeline; the error + // surfaces here instead of a panic from the Go helper. + if err := template.Must(template.New("t").Funcs(fm).Parse(`{{ $_ := append 42 "z" }}`)).Execute(io.Discard, nil); err == nil { + t.Error("template append on a non-slice should fail") + } + if err := template.Must(template.New("t").Funcs(fm).Parse(`{{ $_ := append (list "a") "b" }}`)).Execute(io.Discard, nil); err != nil { + t.Errorf("template append on a list failed: %v", err) } } func TestSplitList(t *testing.T) { + t.Parallel() got := SplitList(" ", "a b c") if !reflect.DeepEqual(got, []string{"a", "b", "c"}) { t.Errorf("SplitList = %v, want [a b c]", got) @@ -90,11 +141,12 @@ func TestSplitList(t *testing.T) { } func TestJoin(t *testing.T) { + t.Parallel() if got := Join(",", []string{"a", "b"}); got != "a,b" { t.Errorf("Join = %q, want a,b", got) } - if got := Join("-", []interface{}{1, 2, 3}); got != "1-2-3" { - t.Errorf("Join([]interface{}) = %q, want 1-2-3", got) + if got := Join("-", []any{1, 2, 3}); got != "1-2-3" { + t.Errorf("Join([]any) = %q, want 1-2-3", got) } if got := Join(",", nil); got != "" { t.Errorf("Join(nil) = %q, want empty", got) @@ -102,6 +154,7 @@ func TestJoin(t *testing.T) { } func TestKindOf(t *testing.T) { + t.Parallel() if got := KindOf("x"); got != "string" { t.Errorf("KindOf('x') = %q, want string", got) } @@ -111,6 +164,7 @@ func TestKindOf(t *testing.T) { } func TestToString(t *testing.T) { + t.Parallel() if got := ToString("s"); got != "s" { t.Errorf("ToString(string) = %q, want s", got) } @@ -120,6 +174,7 @@ func TestToString(t *testing.T) { } func TestAny(t *testing.T) { + t.Parallel() if Any("", 0, false, nil) { t.Error("Any(all empty) = true, want false") } @@ -129,6 +184,7 @@ func TestAny(t *testing.T) { } func TestFuncMapContainsAllExpected(t *testing.T) { + t.Parallel() fm := FuncMap() expected := []string{ "add", "any", "append", "atoi", "base", "camelcase", "contains", @@ -145,6 +201,7 @@ func TestFuncMapContainsAllExpected(t *testing.T) { } func TestPascalCamelCase(t *testing.T) { + t.Parallel() if got := PascalCase("first_name"); got != "FirstName" { t.Errorf("PascalCase(first_name) = %q, want FirstName", got) } @@ -158,6 +215,7 @@ func TestPascalCamelCase(t *testing.T) { } func TestHumanizePluralizeFKName(t *testing.T) { + t.Parallel() if got := Humanize("createdAt"); got != "created At" { t.Errorf("Humanize(createdAt) = %q, want 'created At'", got) } @@ -173,30 +231,33 @@ func TestHumanizePluralizeFKName(t *testing.T) { } func TestSnakeKebabCase(t *testing.T) { + t.Parallel() fm := FuncMap() snake := fm["snakecase"].(func(string) string) kebab := fm["kebabcase"].(func(string) string) cases := []struct { - in, snake, kebab string + name, in, snake, kebab string }{ - {"FirstName", "first_name", "first-name"}, - {"HTTPServer", "http_server", "http-server"}, - {"NoHTTPS", "no_https", "no-https"}, - {"GO_PATH", "go_path", "go-path"}, - {"GO PATH", "go_path", "go-path"}, - {"GO-PATH", "go_path", "go-path"}, - {"http2xx", "http_2xx", "http-2xx"}, - {"HTTP20xOK", "http_20x_ok", "http-20x-ok"}, - {"Duration2m3s", "duration_2m3s", "duration-2m3s"}, - {"Bld4Floor3rd", "bld4_floor_3rd", "bld4-floor-3rd"}, - {"IPv4Address", "i_pv4_address", "i-pv4-address"}, + {"firstName", "FirstName", "first_name", "first-name"}, + {"httpServer", "HTTPServer", "http_server", "http-server"}, + {"noHTTPS", "NoHTTPS", "no_https", "no-https"}, + {"go_path", "GO_PATH", "go_path", "go-path"}, + {"go path", "GO PATH", "go_path", "go-path"}, + {"go-path", "GO-PATH", "go_path", "go-path"}, + {"http2xx", "http2xx", "http_2xx", "http-2xx"}, + {"HTTP20xOK", "HTTP20xOK", "http_20x_ok", "http-20x-ok"}, + {"duration2m3s", "Duration2m3s", "duration_2m3s", "duration-2m3s"}, + {"bld4Floor3rd", "Bld4Floor3rd", "bld4_floor_3rd", "bld4-floor-3rd"}, + {"IPv4Address", "IPv4Address", "i_pv4_address", "i-pv4-address"}, } for _, c := range cases { - if got := snake(c.in); got != c.snake { - t.Errorf("snakecase(%q) = %q, want %q", c.in, got, c.snake) - } - if got := kebab(c.in); got != c.kebab { - t.Errorf("kebabcase(%q) = %q, want %q", c.in, got, c.kebab) - } + t.Run(c.name, func(t *testing.T) { + if got := snake(c.in); got != c.snake { + t.Errorf("snakecase(%q) = %q, want %q", c.in, got, c.snake) + } + if got := kebab(c.in); got != c.kebab { + t.Errorf("kebabcase(%q) = %q, want %q", c.in, got, c.kebab) + } + }) } } diff --git a/internal/testutil/golden.go b/internal/testutil/golden.go new file mode 100644 index 0000000..357599c --- /dev/null +++ b/internal/testutil/golden.go @@ -0,0 +1,46 @@ +package testutil + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "strings" + "testing" +) + +// CheckGolden compares got with testdata/. CRLF and one trailing newline +// are normalized so a golden file checks out identically on Windows and Linux. +// Pass update=true from a package-local -update flag to rewrite the file +// deliberately; a mismatch otherwise fails the test with both values. +func CheckGolden(t *testing.T, name, got string, update bool) { + t.Helper() + path := filepath.Join("testdata", name) + if update { + if err := os.MkdirAll("testdata", 0o755); err != nil { //nolint:gosec // golden fixtures must stay readable in the repo + t.Fatalf("mkdir testdata: %v", err) + } + if err := os.WriteFile(path, []byte(got+"\n"), 0o644); err != nil { //nolint:gosec // committed golden files use the repo's 0644 convention + t.Fatalf("write golden %s: %v", path, err) + } + return + } + data, err := os.ReadFile(path) //nolint:gosec // name is a package-local testdata filename, not user input + if err != nil { + t.Fatalf("read golden %s (run this package's tests with -update to create): %v", path, err) + } + data = bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n")) + // CheckGolden writes exactly one trailing newline; trimming only that one + // keeps an accidental extra blank line in a golden visible. + if want := strings.TrimSuffix(string(data), "\n"); want != got { + t.Errorf("output differs from golden %s\nwant:\n%s\ngot:\n%s", path, want, got) + } +} + +// HashLines digests canonical lines into a stable, host-independent value. +// Callers sort and format their own lines before hashing. +func HashLines(lines []string) string { + sum := sha256.Sum256([]byte(strings.Join(lines, "\n"))) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 905db8d..6f14d83 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -4,22 +4,20 @@ package testutil import ( "testing" - "github.com/DomainCraft/DomainCraft/internal/lexer" "github.com/DomainCraft/DomainCraft/internal/parser" - "github.com/DomainCraft/DomainCraft/pkg/textutil" ) -// MustParsedField parses a field definition string and returns a *ParsedField. -// Fails the test if parsing fails. +// MustParsedField parses a field definition the same way the parser does, then +// returns the resulting *ParsedField. Fails the test if parsing fails. +// +// It calls parser.ParseField so test fixtures carry the parser's normalization +// (primary implies required, optional clears required, required is mirrored into +// Validations, and relation fields get their RelationType). func MustParsedField(t *testing.T, name, input string) *parser.ParsedField { t.Helper() - fieldDef, err := lexer.ParseFieldString(input) + field, err := parser.ParseField(name, input) if err != nil { - t.Fatalf("ParseFieldString(%q) error = %v", input, err) - } - fieldDef.Name = name - return &parser.ParsedField{ - FieldDefinition: fieldDef, - DatabaseColumnName: textutil.ToDatabaseColumnName(name), + t.Fatalf("ParseField(%q, %q) error = %v", name, input, err) } + return field } diff --git a/internal/testutil/testutil_test.go b/internal/testutil/testutil_test.go new file mode 100644 index 0000000..e4a5020 --- /dev/null +++ b/internal/testutil/testutil_test.go @@ -0,0 +1,32 @@ +package testutil + +import "testing" + +// Independent oracle: expectations are literals, not the function the helper +// wraps. A regression in parser normalization must fail this test. +func TestMustParsedFieldMatchesParserNormalization(t *testing.T) { + t.Parallel() + cases := []struct { + name string + input string + required bool + relType string + column string + oldName string + }{ + {name: "primary implies required", input: "uuid [primary]", required: true, column: "field"}, + {name: "relation gets relation type", input: "relation(User) [many]", relType: "many-to-many", column: "field"}, + {name: "quoted old name survives", input: `string [required, old_name:"previousTitle"]`, required: true, column: "field", oldName: "previousTitle"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + got := MustParsedField(t, "field", c.input) + if got.IsRequired != c.required || got.RelationType != c.relType || + got.DatabaseColumnName != c.column || got.OldName != c.oldName { + t.Errorf("MustParsedField(%q) = (required=%v, rel=%q, column=%q, old=%q)", + c.input, got.IsRequired, got.RelationType, got.DatabaseColumnName, got.OldName) + } + }) + } +} diff --git a/internal/validator/validator.go b/internal/validator/validator.go index 7b90f1d..ee7b3ed 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -1,3 +1,4 @@ +// Package validator checks the parsed schema for logical consistency. package validator import ( @@ -5,6 +6,7 @@ import ( "encoding/json" "fmt" "maps" + "math" "regexp" "slices" "strconv" @@ -13,6 +15,7 @@ import ( "github.com/DomainCraft/DomainCraft/internal/parser" "github.com/DomainCraft/DomainCraft/internal/specmeta" + "github.com/DomainCraft/DomainCraft/pkg/textutil" ) // ValidationError describes a logical validation error. @@ -23,11 +26,38 @@ type ValidationError struct { Warning bool // non-fatal hint, not a hard error } +// Error formats the entity, optional field and message of one validation error. func (e ValidationError) Error() string { if e.Field != "" { - return fmt.Sprintf("Error in entity '%s', field '%s': %s", e.Entity, e.Field, e.Message) + return fmt.Sprintf("entity %q field %q: %s", e.Entity, e.Field, e.Message) } - return fmt.Sprintf("Error in entity '%s': %s", e.Entity, e.Message) + return fmt.Sprintf("entity %q: %s", e.Entity, e.Message) +} + +// newValidationErr is the single constructor behind all four diagnostic +// helpers, so the Warning flag and entity/field placement cannot drift. +func newValidationErr(warning bool, entity, field, message string) ValidationError { + return ValidationError{Entity: entity, Field: field, Message: message, Warning: warning} +} + +// invalid builds a non-warning validation error for an entity and field. +func invalid(entity, field, message string) ValidationError { + return newValidationErr(false, entity, field, message) +} + +// warn builds a warning validation error for an entity and field. +func warn(entity, field, message string) ValidationError { + return newValidationErr(true, entity, field, message) +} + +// invalidf builds a non-warning validation error with a formatted message. +func invalidf(entity, field, format string, args ...any) ValidationError { + return newValidationErr(false, entity, field, fmt.Sprintf(format, args...)) +} + +// warnf builds a warning validation error with a formatted message. +func warnf(entity, field, format string, args ...any) ValidationError { + return newValidationErr(true, entity, field, fmt.Sprintf(format, args...)) } // Validator checks ParsedSchema for logical consistency. @@ -35,15 +65,15 @@ type Validator struct { schema *parser.ParsedSchema } +// New creates a Validator for the parsed schema. func New(schema *parser.ParsedSchema) *Validator { return &Validator{schema: schema} } -var validIdentifier = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) - // boolValues are valid boolean default values. var boolValues = map[string]bool{"true": true, "false": true} +// Validate returns all logical errors and warnings in deterministic order. func (v *Validator) Validate() []ValidationError { if v == nil || v.schema == nil { return []ValidationError{{Entity: "", Message: "schema is nil"}} @@ -58,7 +88,8 @@ func (v *Validator) Validate() []ValidationError { if v.schema.Enums != nil { for _, entityName := range v.schema.EntityOrder { if _, isEnum := v.schema.Enums[entityName]; isEnum { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("entity name %q collides with an enum of the same name; templates may produce ambiguous output", entityName), Warning: true}) + errs = append(errs, warnf(entityName, "", + "entity name %q collides with an enum of the same name; templates may produce ambiguous output", entityName)) } } } @@ -83,7 +114,10 @@ func (v *Validator) Validate() []ValidationError { if c := cmp.Compare(a.Entity, b.Entity); c != 0 { return c } - return cmp.Compare(a.Field, b.Field) + if c := cmp.Compare(a.Field, b.Field); c != 0 { + return c + } + return cmp.Compare(a.Message, b.Message) }) return errs @@ -96,106 +130,140 @@ func (v *Validator) validateProject() []ValidationError { p := v.schema.Project if strings.TrimSpace(p.Name) == "" { - errs = append(errs, ValidationError{Entity: "", Message: "project name must not be empty"}) + errs = append(errs, invalid("", "", "project name must not be empty")) } - if len(v.schema.Entities) == 0 { - errs = append(errs, ValidationError{Entity: "", Message: "no entities defined", Warning: true}) + errs = append(errs, warn("", "", "no entities defined")) } - if v.schema.Database != "" && !specmeta.IsDatabase(v.schema.Database) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown database %q; allowed: %s", v.schema.Database, strings.Join(specmeta.Databases, ", "))}) + errs = append(errs, invalidf("", "", + "unknown database %q; allowed: %s", v.schema.Database, strings.Join(specmeta.Databases, ", "))) } - // Auth validation if v.schema.Auth != nil { errs = append(errs, v.validateAuth()...) } if v.schema.APIStyle != "" && !specmeta.IsAPIStyle(v.schema.APIStyle) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown api_style %q; allowed: %s", v.schema.APIStyle, strings.Join(specmeta.APIStyles, ", "))}) - } - - // Multi-tenancy - if p.MultiTenancy != nil && p.MultiTenancy.Enabled { - if p.MultiTenancy.Mode != "" && !specmeta.IsMultiTenancyMode(p.MultiTenancy.Mode) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown multi_tenancy.mode %q; allowed: %s", p.MultiTenancy.Mode, strings.Join(specmeta.MultiTenancyModes, ", "))}) - } + errs = append(errs, invalidf("", "", + "unknown api_style %q; allowed: %s", v.schema.APIStyle, strings.Join(specmeta.APIStyles, ", "))) } - - // Cache - if p.Cache != nil && p.Cache.Enabled { - if p.Cache.Provider != "" && !specmeta.IsCacheProvider(p.Cache.Provider) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown cache.provider %q; allowed: %s", p.Cache.Provider, strings.Join(specmeta.CacheProviders, ", "))}) - } - if p.Cache.TTLSeconds < 0 { - errs = append(errs, ValidationError{Entity: "", Message: "cache.ttl_seconds must be non-negative", Warning: true}) - } + if p.MultiTenancy != nil && p.MultiTenancy.Enabled && p.MultiTenancy.Mode != "" && + !specmeta.IsMultiTenancyMode(p.MultiTenancy.Mode) { + errs = append(errs, invalidf("", "", + "unknown multi_tenancy.mode %q; allowed: %s", p.MultiTenancy.Mode, strings.Join(specmeta.MultiTenancyModes, ", "))) } - if p.Cache != nil && !p.Cache.Enabled && (p.Cache.Provider != "" || p.Cache.ConnectionString != "") { - errs = append(errs, ValidationError{Entity: "", Message: "cache.provider or cache.connection_string specified but cache.enabled is false", Warning: true}) - } - if p.Cache != nil && p.Cache.Enabled && p.Cache.Provider != "" && p.Cache.ConnectionString == "" { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("cache.provider %q specified but cache.connection_string is empty", p.Cache.Provider), Warning: true}) - } - - // CORS if p.CORS != nil && p.CORS.Enabled && len(p.CORS.Origins) == 0 { - errs = append(errs, ValidationError{Entity: "", Message: "cors.enabled is true but no origins specified", Warning: true}) + errs = append(errs, warn("", "", "cors.enabled is true but no origins specified")) } - - // Deploy - if p.Deploy != nil { - if p.Deploy.Port != 0 && (p.Deploy.Port < 1 || p.Deploy.Port > 65535) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("deploy.port must be between 1 and 65535, got %d", p.Deploy.Port)}) - } + if p.Deploy != nil && (p.Deploy.Port < 0 || p.Deploy.Port > 65535) { + errs = append(errs, invalidf("", "", + "deploy.port must be between 1 and 65535, got %d", p.Deploy.Port)) } - - // Versioning if p.Versioning != nil && p.Versioning.Enabled && p.Versioning.DefaultVersion == "" { - errs = append(errs, ValidationError{Entity: "", Message: "versioning.enabled is true but default_version is empty", Warning: true}) + errs = append(errs, warn("", "", "versioning.enabled is true but default_version is empty")) } - // Rate limiting - if p.RateLimit != nil { - if p.RateLimit.Policy != "" && !specmeta.IsRateLimitPolicy(p.RateLimit.Policy) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown rate_limit.policy %q; allowed: %s", p.RateLimit.Policy, strings.Join(specmeta.RateLimitPolicies, ", "))}) + errs = append(errs, validateCacheConfig(p)...) + errs = append(errs, validateRateLimitConfig(p)...) + errs = append(errs, validatePaginationConfig(p)...) + errs = append(errs, validateInfrastructureConfig(p)...) + return errs +} + +// validateCacheConfig keeps the three cache rules together: they describe one +// policy (enabled, provider and connection string must agree). +func validateCacheConfig(p parser.ProjectConfig) []ValidationError { + var errs []ValidationError + c := p.Cache + if c == nil { + return nil + } + if c.Enabled { + if c.Provider != "" && !specmeta.IsCacheProvider(c.Provider) { + errs = append(errs, invalidf("", "", + "unknown cache.provider %q; allowed: %s", c.Provider, strings.Join(specmeta.CacheProviders, ", "))) } - if p.RateLimit.PermitLimit < 0 { - errs = append(errs, ValidationError{Entity: "", Message: "rate_limit.permit_limit must be non-negative", Warning: true}) + if c.TTLSeconds < 0 { + errs = append(errs, warn("", "", "cache.ttl_seconds must be non-negative")) } - if p.RateLimit.WindowSeconds < 1 { - errs = append(errs, ValidationError{Entity: "", Message: "rate_limit.window_seconds must be at least 1", Warning: true}) + if c.Provider != "" && c.ConnectionString == "" { + errs = append(errs, warnf("", "", + "cache.provider %q specified but cache.connection_string is empty", c.Provider)) } + return errs + } + if c.Provider != "" || c.ConnectionString != "" { + errs = append(errs, warn("", "", + "cache.provider or cache.connection_string specified but cache.enabled is false")) } + return errs +} - // Pagination - if p.Pagination != nil { - if p.Pagination.DefaultPageSize < 1 { - errs = append(errs, ValidationError{Entity: "", Message: "pagination.default_page_size must be at least 1", Warning: true}) - } - if p.Pagination.MaxPageSize < 1 { - errs = append(errs, ValidationError{Entity: "", Message: "pagination.max_page_size must be at least 1", Warning: true}) - } - if p.Pagination.DefaultPageSize > p.Pagination.MaxPageSize { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("pagination.default_page_size (%d) must not exceed max_page_size (%d)", p.Pagination.DefaultPageSize, p.Pagination.MaxPageSize), Warning: true}) - } +func validateRateLimitConfig(p parser.ProjectConfig) []ValidationError { + var errs []ValidationError + r := p.RateLimit + if r == nil { + return nil } + if r.Policy != "" && !specmeta.IsRateLimitPolicy(r.Policy) { + errs = append(errs, invalidf("", "", + "unknown rate_limit.policy %q; allowed: %s", r.Policy, strings.Join(specmeta.RateLimitPolicies, ", "))) + } + if r.PermitLimit < 0 { + errs = append(errs, warn("", "", "rate_limit.permit_limit must be non-negative")) + } + // An explicit 0 means "no window"; only negatives are invalid. The parser + // fills in 60 when the key is omitted, so 0 never means "unset" here. + if r.WindowSeconds < 0 { + errs = append(errs, warn("", "", "rate_limit.window_seconds must be non-negative")) + } + return errs +} - // Infrastructure (provider-agnostic backing services used by addons such as Dapr) - if p.Infrastructure != nil { - if p.Infrastructure.Queue != "" && !specmeta.IsInfraQueue(p.Infrastructure.Queue) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown infrastructure.queue %q; allowed: %s", p.Infrastructure.Queue, strings.Join(specmeta.InfraQueues, ", "))}) - } - if p.Infrastructure.Cache != "" && !specmeta.IsInfraCacheStore(p.Infrastructure.Cache) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown infrastructure.cache %q; allowed: %s", p.Infrastructure.Cache, strings.Join(specmeta.InfraCacheStores, ", "))}) - } - if p.Infrastructure.Secrets != "" && !specmeta.IsInfraSecretStore(p.Infrastructure.Secrets) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown infrastructure.secrets %q; allowed: %s", p.Infrastructure.Secrets, strings.Join(specmeta.InfraSecretStores, ", "))}) - } - if p.Infrastructure.Storage != "" && !specmeta.IsInfraStore(p.Infrastructure.Storage) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown infrastructure.storage %q; allowed: %s", p.Infrastructure.Storage, strings.Join(specmeta.InfraStores, ", "))}) - } +func validatePaginationConfig(p parser.ProjectConfig) []ValidationError { + var errs []ValidationError + pg := p.Pagination + if pg == nil { + return nil + } + // An explicit 0 is meaningful (no default / no cap); only negatives are invalid. + if pg.DefaultPageSize < 0 { + errs = append(errs, warn("", "", "pagination.default_page_size must be non-negative")) } + if pg.MaxPageSize < 0 { + errs = append(errs, warn("", "", "pagination.max_page_size must be non-negative")) + } + if pg.DefaultPageSize > 0 && pg.MaxPageSize > 0 && pg.DefaultPageSize > pg.MaxPageSize { + errs = append(errs, warnf("", "", + "pagination.default_page_size (%d) must not exceed max_page_size (%d)", pg.DefaultPageSize, pg.MaxPageSize)) + } + return errs +} +// validateInfrastructureConfig checks the provider-agnostic backing services +// used by addons such as Dapr. +func validateInfrastructureConfig(p parser.ProjectConfig) []ValidationError { + var errs []ValidationError + i := p.Infrastructure + if i == nil { + return nil + } + checks := []struct { + value string + valid func(string) bool + kind string + allowed []string + }{ + {i.Queue, specmeta.IsInfraQueue, "queue", specmeta.InfraQueues}, + {i.Cache, specmeta.IsInfraCacheStore, "cache", specmeta.InfraCacheStores}, + {i.Secrets, specmeta.IsInfraSecretStore, "secrets", specmeta.InfraSecretStores}, + {i.Storage, specmeta.IsInfraStore, "storage", specmeta.InfraStores}, + } + for _, c := range checks { + if c.value != "" && !c.valid(c.value) { + errs = append(errs, invalidf("", "", + "unknown infrastructure.%s %q; allowed: %s", c.kind, c.value, strings.Join(c.allowed, ", "))) + } + } return errs } @@ -250,18 +318,11 @@ func (v *Validator) validateCircularRelations() []ValidationError { case white: dfs(target) case gray: - // Back-edge found: mark everything from target up the stack. - marking := false - for _, n := range stack { - if n == target { - marking = true - } - if marking { - inCycle[n] = true - } + // Back-edge found: target is gray, so it is on the stack. + // Mark everything from target up to the current node. + for _, n := range stack[slices.Index(stack, target):] { + inCycle[n] = true } - case black: - // already fully explored } } stack = stack[:len(stack)-1] @@ -275,11 +336,8 @@ func (v *Validator) validateCircularRelations() []ValidationError { } for _, entityName := range slices.Sorted(maps.Keys(inCycle)) { - errs = append(errs, ValidationError{ - Entity: entityName, - Message: "entity is part of a circular relation chain (A → B → … → A); generated delete/seed ordering may be ambiguous", - Warning: true, - }) + errs = append(errs, warn(entityName, "", + "entity is part of a circular relation chain (A → B → … → A); generated delete/seed ordering may be ambiguous")) } return errs @@ -290,10 +348,11 @@ func (v *Validator) validateAuth() []ValidationError { auth := v.schema.Auth if auth.Type != "" && !specmeta.IsAuthType(auth.Type) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("unknown auth.type %q; allowed: %s", auth.Type, strings.Join(specmeta.AuthTypes, ", "))}) + errs = append(errs, invalidf("", "", + "unknown auth.type %q; allowed: %s", auth.Type, strings.Join(specmeta.AuthTypes, ", "))) } - if auth.Type == "none" { + if !specmeta.IsAuthEnabled(auth.Type) { return errs } @@ -301,33 +360,39 @@ func (v *Validator) validateAuth() []ValidationError { if auth.Entity != "" { entity, ok := v.schema.Entities[auth.Entity] if !ok { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("auth.entity %q does not exist", auth.Entity)}) - } else if !specmeta.HasEmailAndPassword(entity.FieldOrder) { - hasEmail, hasPassword := specmeta.AuthFieldState(entity.FieldOrder) - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("auth.entity %q must have both 'email' and 'password' fields (missing: %s)", auth.Entity, missingFields(!hasEmail, !hasPassword))}) + errs = append(errs, invalidf("", "", + "auth.entity %q does not exist", auth.Entity)) + } else if hasEmail, hasPassword := specmeta.AuthFieldState(entity.FieldOrder); !hasEmail || !hasPassword { + errs = append(errs, invalidf("", "", + "auth.entity %q must have both 'email' and 'password' fields (missing: %s)", auth.Entity, + missingFields(!hasEmail, !hasPassword))) } } else { // Auto-detect: find entity with email + password using specmeta helper. entityFields := v.buildEntityFields() if specmeta.FindAuthEntity(v.schema.EntityOrder, entityFields) == "" { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("auth.type is %q but no entity has both 'email' and 'password' fields; specify auth.entity explicitly", auth.Type), Warning: true}) + errs = append(errs, invalidf("", "", + "auth.type is %q but no entity has both 'email' and 'password' fields; specify auth.entity explicitly", auth.Type)) } } + if auth.Type == specmeta.AuthTypeJWT && len(auth.Roles) == 0 { + errs = append(errs, invalidf("", "", + "auth.roles must declare at least one role when auth.type is \"jwt\"")) + } + // Roles must be valid identifiers for _, role := range auth.Roles { - if !validIdentifier.MatchString(role) { - errs = append(errs, ValidationError{Entity: "", Message: fmt.Sprintf("auth.roles: %q is not a valid identifier", role)}) + if !specmeta.IsValidIdentifier(role) { + errs = append(errs, invalidf("", "", + "auth.roles: %q is not a valid identifier", role)) } } // Validate that auth roles are used in at least one entity's permissions. // When auth.roles is non-empty, check that permission roles are declared. // When auth.roles is empty, warn if any entity references named roles. - roleSet := make(map[string]bool, len(auth.Roles)) - for _, r := range auth.Roles { - roleSet[r] = true - } + roleSet := specmeta.SliceToSet(auth.Roles) for _, entityName := range v.schema.EntityOrder { entity := v.schema.Entities[entityName] if entity == nil || entity.Permissions == nil { @@ -344,17 +409,11 @@ func (v *Validator) validateAuth() []ValidationError { continue } if len(auth.Roles) > 0 && !roleSet[r] { - errs = append(errs, ValidationError{ - Entity: entityName, - Message: fmt.Sprintf("permission role %q is not defined in auth.roles; add it to auth.roles or remove from permissions", r), - Warning: true, - }) + errs = append(errs, warnf(entityName, "", + "permission role %q is not defined in auth.roles; add it to auth.roles or remove from permissions", r)) } else if len(auth.Roles) == 0 { - errs = append(errs, ValidationError{ - Entity: entityName, - Message: fmt.Sprintf("permission role %q is used but auth.roles is empty; define auth.roles to declare valid roles", r), - Warning: true, - }) + errs = append(errs, warnf(entityName, "", + "permission role %q is used but auth.roles is empty; define auth.roles to declare valid roles", r)) } } } @@ -385,7 +444,7 @@ func (v *Validator) singleFKBack(target *parser.ParsedEntity, sourceName string) } for _, fieldName := range target.FieldOrder { field := target.Fields[fieldName] - if field != nil && field.IsRelation() && !field.IsMany && field.TargetEntity == sourceName { + if field != nil && specmeta.IsSingleBackRelationField(field.IsRelation(), field.IsMany, field.TargetEntity, sourceName) { return field } } @@ -394,24 +453,33 @@ func (v *Validator) singleFKBack(target *parser.ParsedEntity, sourceName string) func (v *Validator) validateEnums() []ValidationError { var errs []ValidationError - for name, values := range v.schema.Enums { - if !validIdentifier.MatchString(name) { - errs = append(errs, ValidationError{Entity: "", Field: name, Message: "enum name is not a valid identifier"}) + for _, name := range slices.Sorted(maps.Keys(v.schema.Enums)) { + values := v.schema.Enums[name] + if !specmeta.IsValidIdentifier(name) { + errs = append(errs, invalid("", name, + "enum name is not a valid identifier")) } if len(values) == 0 { - errs = append(errs, ValidationError{Entity: "", Field: name, Message: "enum must have at least one value"}) + errs = append(errs, invalid("", name, + "enum must have at least one value")) continue } - seen := make(map[string]bool, len(values)) + // The IR derives each enum's wire value with textutil.ToDatabaseColumnName. + // Use the same canonicalization here: two declared values that map to one + // wire value produce duplicate members in every bridge. + seen := make(map[string]string, len(values)) for _, val := range values { if val == "" { - errs = append(errs, ValidationError{Entity: "", Field: name, Message: "enum value must not be empty"}) + errs = append(errs, invalid("", name, + "enum value must not be empty")) } - lower := strings.ToLower(val) - if seen[lower] { - errs = append(errs, ValidationError{Entity: "", Field: name, Message: fmt.Sprintf("duplicate enum value %q (case-insensitive collision)", val), Warning: true}) + wire := textutil.ToDatabaseColumnName(val) + if first, exists := seen[wire]; exists { + errs = append(errs, invalidf("", name, + "enum values %q and %q map to the same wire value %q", first, val, wire)) + continue } - seen[lower] = true + seen[wire] = val } } @@ -426,17 +494,18 @@ func (v *Validator) validateEnums() []ValidationError { if field == nil { continue } - if field.Type == "enum" && field.TargetType != "" { + if field.Type == specmeta.FieldTypeEnum && field.TargetType != "" { usedEnums[field.TargetType] = true } - if field.Type == "array" && field.TargetType != "" { + if field.Type == specmeta.FieldTypeArray && field.TargetType != "" { usedEnums[field.TargetType] = true } } } for _, enumName := range slices.Sorted(maps.Keys(v.schema.Enums)) { if !usedEnums[enumName] { - errs = append(errs, ValidationError{Entity: "", Field: enumName, Message: "enum is declared but never used by any entity field", Warning: true}) + errs = append(errs, warn("", enumName, + "enum is declared but never used by any entity field")) } } } @@ -450,32 +519,42 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit var errs []ValidationError // Entity name must be a valid identifier. - if !validIdentifier.MatchString(entityName) { - errs = append(errs, ValidationError{Entity: entityName, Message: "entity name is not a valid identifier"}) + if !specmeta.IsValidIdentifier(entityName) { + errs = append(errs, invalid(entityName, "", + "entity name is not a valid identifier")) + } + + // old_name is a rename hint; like a field's old_name it must be a valid + // identifier and must not point back at the entity itself. + if entity.OldName != "" { + if !specmeta.IsValidIdentifier(entity.OldName) { + errs = append(errs, invalid(entityName, "", + "old_name is not a valid identifier")) + } + if entity.OldName == entityName { + errs = append(errs, invalid(entityName, "", + "old_name cannot equal the entity name (it is the entity's previous name)")) + } } // Must have at least one field. if len(entity.Fields) == 0 { - errs = append(errs, ValidationError{Entity: entityName, Message: "entity has no fields"}) + errs = append(errs, invalid(entityName, "", + "entity has no fields")) } // Must have a primary key. pkCount := countPrimaryKeys(entity) if pkCount == 0 { - errs = append(errs, ValidationError{Entity: entityName, Message: "entity must have at least one primary key"}) + errs = append(errs, invalid(entityName, "", + "entity must have at least one primary key")) } else if pkCount > 1 { // Must not have duplicate primary keys. - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("entity has %d primary keys; expected exactly one", pkCount)}) - } - - // Duplicate feature names. - featureSeen := make(map[string]bool) - for f := range entity.Features { - if featureSeen[f] { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("duplicate feature %q", f), Warning: true}) - } - featureSeen[f] = true + errs = append(errs, invalidf(entityName, "", + "entity has %d primary keys; expected exactly one", pkCount)) } + // A relation cannot be a primary key: validatePrimaryKeyField reports it + // once per field; repeating the check here produced duplicate errors. // Track DB column names for collision detection. columnNames := make(map[string]string) // column -> field name @@ -496,21 +575,20 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit // field currently on the entity. if field.OldName != "" { if field.OldName == fieldName { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "old_name cannot equal the field name (it is the field's previous name)"}) + errs = append(errs, invalid(entityName, fieldName, + "old_name cannot equal the field name (it is the field's previous name)")) } if prev, exists := entity.Fields[field.OldName]; exists && prev != field { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("old_name '%s' collides with an existing field '%s' on the same entity", field.OldName, prev.Name)}) + errs = append(errs, invalidf(entityName, fieldName, + "old_name '%s' collides with an existing field '%s' on the same entity", field.OldName, prev.Name)) } } // DB column collision. col := field.DatabaseColumnName if prev, exists := columnNames[col]; exists && prev != fieldName { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("database column '%s' collides with field '%s'", col, prev), - }) + errs = append(errs, invalidf(entityName, fieldName, + "database column '%s' collides with field '%s'", col, prev)) } columnNames[col] = fieldName @@ -519,11 +597,8 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit if field.IsRelation() { nav := field.NavigationName() if prev, exists := navigationNames[nav]; exists && prev != fieldName { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("navigation name '%s' collides with field '%s'", nav, prev), - }) + errs = append(errs, invalidf(entityName, fieldName, + "navigation name '%s' collides with field '%s'", nav, prev)) } navigationNames[nav] = fieldName } @@ -554,18 +629,16 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit } if len(uniqueFields) > 0 { for i, seedEntry := range entity.Seed { - for fieldName, values := range uniqueFields { + for _, fieldName := range slices.Sorted(maps.Keys(uniqueFields)) { + values := uniqueFields[fieldName] seedVal, ok := seedEntry[fieldName] if !ok { continue } valStr := fmt.Sprintf("%v", seedVal) if values[valStr] { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q for unique field '%s' is duplicated in seed data", i, valStr, fieldName), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q for unique field '%s' is duplicated in seed data", i, valStr, fieldName)) } values[valStr] = true } @@ -578,137 +651,229 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit // --- field-level --- +// validateField runs field rules in their canonical order so error ordering +// and messages stay stable. func (v *Validator) validateField(entityName string, fieldName string, field *parser.ParsedField) []ValidationError { var errs []ValidationError + errs = append(errs, validateFieldName(entityName, fieldName, field)...) + errs = append(errs, v.validateRelationField(entityName, fieldName, field)...) + errs = append(errs, validatePrimaryKeyField(entityName, fieldName, field)...) + errs = append(errs, v.validateEnumField(entityName, fieldName, field)...) + errs = append(errs, v.validateArrayField(entityName, fieldName, field)...) + errs = append(errs, validateFieldValidations(entityName, fieldName, field)...) + errs = append(errs, v.validateFieldDefault(entityName, fieldName, field)...) + return errs +} + +// validateFieldName checks the identifier and feature-field collisions. +func validateFieldName(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError // Field name must be a valid identifier. - if !validIdentifier.MatchString(fieldName) { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "field name is not a valid identifier"}) + if !specmeta.IsValidIdentifier(fieldName) { + errs = append(errs, invalid(entityName, fieldName, + "field name is not a valid identifier")) } // Feature field collision — warn only if user-defined type differs from auto-generated type. if fdef, isFeatureField := specmeta.FeatureFieldDefs[fieldName]; isFeatureField { userType := strings.ToLower(field.Type) if userType != "" && userType != fdef.Type { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("user-defined type '%s' overrides feature field '%s' (auto-generated type: '%s')", field.Type, fieldName, fdef.Type), - Warning: true, - }) + errs = append(errs, warnf(entityName, fieldName, + "user-defined type '%s' overrides feature field '%s' (auto-generated type: '%s')", field.Type, fieldName, + fdef.Type)) } } - // Relation-specific checks. + return errs +} + +// validateRelationField checks the cross-entity and semantic rules the lexer +// cannot perform. +func (v *Validator) validateRelationField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { // Note: on_delete value, set_null+optional, many+on_delete, and many+relation // constraints are already enforced by the lexer. Only cross-entity and semantic // checks that the lexer cannot perform belong here. - if field.IsRelation() { - if field.TargetEntity == "" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "relation field must specify a target entity"}) - } - if _, ok := v.schema.Entities[field.TargetEntity]; !ok && field.TargetEntity != "" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("relation target '%s' does not exist", field.TargetEntity)}) - } - if field.IsMany && field.IsUnique { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "unique is contradictory on a many-to-many relation"}) - } - // on_delete is meaningless on many-to-many relations (join table has no FK to delete). - if field.IsMany && field.OnDelete != "" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "on_delete is meaningless on a many-to-many relation; remove it or use a many-to-one relation instead", Warning: true}) - } - // A [many] relation whose target also declares a single FK back to this - // entity is reconciled into ONE one-to-many (the FK lives on the target, - // the collection on this entity) — not a many-to-many join. - if field.IsMany { - if target, ok := v.schema.Entities[field.TargetEntity]; ok { - if back := v.singleFKBack(target, entityName); back != nil { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("[many] relation is reconciled with FK '%s' on %s into a one-to-many relationship (collection on %s); remove one side if you meant a many-to-many join", back.Name, field.TargetEntity, entityName), - Warning: true, - }) - } + if !field.IsRelation() { + return nil + } + + var errs []ValidationError + if field.TargetEntity == "" { + errs = append(errs, invalid(entityName, fieldName, + "relation field must specify a target entity")) + } else { + target, ok := v.schema.Entities[field.TargetEntity] + if !ok { + errs = append(errs, invalidf(entityName, fieldName, + "relation target '%s' does not exist", field.TargetEntity)) + } else if field.IsMany { + // A [many] relation whose target also declares a single FK back to + // this entity is reconciled into ONE one-to-many, not a join table. + if back := v.singleFKBack(target, entityName); back != nil { + errs = append(errs, warnf(entityName, fieldName, + "[many] relation is reconciled with FK '%s' on %s into a one-to-many relationship (collection on %s); remove "+ + "one side if you meant a many-to-many join", back.Name, field.TargetEntity, entityName)) } } - // Self-referential required cascade is dangerous. - if field.TargetEntity == entityName && !field.IsOptional && field.OnDelete == "cascade" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "self-referential required cascade delete may cause recursive deletion", Warning: true}) - } - // Required relation without on_delete — warn. - if !field.IsOptional && !field.IsMany && field.OnDelete == "" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "required relation has no on_delete specified; default behavior may not match expectations", Warning: true}) - } } + if field.IsMany && field.IsUnique { + errs = append(errs, invalid(entityName, fieldName, + "unique is contradictory on a many-to-many relation")) + } + // on_delete is meaningless on many-to-many relations (join table has no FK to delete). + if field.IsMany && field.OnDelete != "" { + errs = append(errs, warn(entityName, fieldName, + "on_delete is meaningless on a many-to-many relation; remove it or use a many-to-one relation instead")) + } + // Self-referential required cascade is dangerous. + if field.TargetEntity == entityName && !field.IsOptional && field.OnDelete == specmeta.OnDeleteCascade { + errs = append(errs, warn(entityName, fieldName, + "self-referential required cascade delete may cause recursive deletion")) + } + // Required relation without on_delete — warn. + if !field.IsOptional && !field.IsMany && field.OnDelete == "" { + errs = append(errs, warn(entityName, fieldName, + "required relation has no on_delete specified; default behavior may not match expectations")) + } + return errs +} + +// validatePrimaryKeyField checks constraints on a primary-key field. +func validatePrimaryKeyField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError // Primary key constraints. if field.IsPrimary { - if field.Type == "array" { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: "primary key cannot be an array type"}) + if field.Type == specmeta.FieldTypeArray { + errs = append(errs, invalid(entityName, fieldName, + "primary key cannot be an array type")) + } + if field.IsRelation() { + errs = append(errs, invalidf(entityName, fieldName, + "primary key cannot be a relation field (target '%s'); use a scalar id field", field.TargetEntity)) } } - // Enum reference. - if field.Type == "enum" && field.TargetType != "" { - if _, ok := v.schema.Enums[field.TargetType]; !ok { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("enum '%s' is not defined in enums section", field.TargetType)}) - } + return errs +} + +// validateEnumReference is the single "is this enum declared?" check shared +// by scalar enum fields and array element types. The caller owns the message +// so each diagnostic stays specific. +func (v *Validator) validateEnumReference(entityName, fieldName, target, message string) []ValidationError { + if target == "" { + return nil } + if _, ok := v.schema.Enums[target]; ok { + return nil + } + return []ValidationError{invalidf(entityName, fieldName, message, target)} +} - // Array element type. - if field.Type == "array" && field.TargetType != "" { - inner := strings.ToLower(field.TargetType) - if !specmeta.IsPrimitive(inner) { - if _, ok := v.schema.Enums[field.TargetType]; !ok { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("array element type '%s' is not a primitive or defined enum", field.TargetType)}) - } - } +// validateEnumField checks that an enum reference is declared. +func (v *Validator) validateEnumField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + if field.Type != specmeta.FieldTypeEnum { + return nil + } + return v.validateEnumReference(entityName, fieldName, field.TargetType, + "enum '%s' is not defined in enums section") +} + +// validateArrayField checks that an array element type is primitive or a +// declared enum. +func (v *Validator) validateArrayField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + if field.Type != specmeta.FieldTypeArray || field.TargetType == "" { + return nil + } + if specmeta.IsPrimitive(strings.ToLower(field.TargetType)) { + return nil } + return v.validateEnumReference(entityName, fieldName, field.TargetType, + "array element type '%s' is not a primitive or defined enum") +} + +// validateFieldValidations checks modifier applicability, numeric values and +// contradictory ranges. +func validateFieldValidations(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError // Validation modifiers must be type-appropriate. ftype := strings.ToLower(field.Type) isNumeric := specmeta.IsNumeric(ftype) isString := specmeta.IsStringType(ftype) - for mod, val := range field.Validations { - if specmeta.IsStringValidationModifier(mod) && !isString { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("validation '%s' is only applicable to string/text fields, not %s", mod, ftype), Warning: true}) + for _, mod := range slices.Sorted(maps.Keys(field.Validations)) { + val := field.Validations[mod] + if specmeta.IsStringOnlyValidationModifier(mod) && !isString { + errs = append(errs, warnf(entityName, fieldName, + "validation '%s' is only applicable to string/text fields, not %s", mod, ftype)) } if specmeta.IsNumericValidationModifier(mod) && !isNumeric { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("validation '%s' is only applicable to numeric fields, not %s", mod, ftype), Warning: true}) + errs = append(errs, warnf(entityName, fieldName, + "validation '%s' is only applicable to numeric fields, not %s", mod, ftype)) + } + if (mod == "min" || mod == "max") && !isString && !isNumeric { + errs = append(errs, warnf(entityName, fieldName, + "validation '%s' is only applicable to string/text or numeric fields, not %s", mod, ftype)) + } + if val == "" { + continue } - // Validate that numeric validation values are actually numeric - // (numeric modifiers AND string min/max, which are also numeric). - if (specmeta.IsNumericValidationModifier(mod) || mod == "min" || mod == "max") && val != "" { + switch { + case mod == "min" || mod == "max": + // String bounds are lengths and numeric bounds are values, but both + // must be integers: IR emits min_value/max_value as numeric literals. + n, err := strconv.ParseInt(val, 10, 64) + if err != nil { + errs = append(errs, invalidf(entityName, fieldName, + "validation '%s' value %q must be an integer", mod, val)) + } else if isString && n <= 0 { + // String length bounds drive seed truncation; a non-positive + // maximum would slice with a negative index. + errs = append(errs, invalidf(entityName, fieldName, + "validation '%s' must be positive for string length, got %q", mod, val)) + } + case specmeta.IsNumericValidationModifier(mod): if _, err := strconv.ParseFloat(val, 64); err != nil { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("validation '%s' value %q is not a valid number", mod, val)}) + errs = append(errs, invalidf(entityName, fieldName, + "validation '%s' value %q is not a valid number", mod, val)) } } } // Check for contradictory range validations. - errs = append(errs, validateContradictoryRanges(entityName, fieldName, field, isNumeric, isString)...) + errs = append(errs, validateContradictoryRanges(entityName, fieldName, field.Validations, isNumeric, isString)...) + + return errs +} + +// validateFieldDefault checks default value types and enum membership. +func (v *Validator) validateFieldDefault(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError + + ftype := strings.ToLower(field.Type) + inner := ftype + isArray := ftype == specmeta.FieldTypeArray && field.TargetType != "" + if isArray { + inner = field.TargetType + } // Default value type check. if field.DefaultValue != "" && field.DefaultIsFunc { errs = append(errs, validateFuncDefault(entityName, fieldName, ftype, field.DefaultValue)...) } else if field.DefaultValue != "" { - errs = append(errs, validateDefaultValue(entityName, fieldName, ftype, field.DefaultValue)...) + errs = append(errs, validateDefaultValue(entityName, fieldName, inner, isArray, field.DefaultValue)...) } // Enum default must be one of the declared enum values. - if field.Type == "enum" && field.TargetType != "" && field.DefaultValue != "" && !field.DefaultIsFunc { + if field.Type == specmeta.FieldTypeEnum && field.TargetType != "" && field.DefaultValue != "" && !field.DefaultIsFunc { if enumValues, ok := v.schema.Enums[field.TargetType]; ok { - found := false - for _, v := range enumValues { - if v == field.DefaultValue { - found = true - break - } - } + found := slices.Contains(enumValues, field.DefaultValue) if !found { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not a declared value of enum '%s'; valid values: %s", field.DefaultValue, field.TargetType, strings.Join(enumValues, ", "))}) + errs = append(errs, invalidf(entityName, fieldName, + "default value '%s' is not a declared value of enum '%s'; valid values: %s", field.DefaultValue, field.TargetType, + strings.Join(enumValues, ", "))) } } } @@ -716,60 +881,89 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa return errs } -func validateDefaultValue(entityName, fieldName, ftype, defaultVal string) []ValidationError { +// validateDefaultValue checks one scalar default, or every element of an array +// default, against the field's already-unwrapped element type inner. isArray +// selects per-element checking; defaults never get re-encoded as array(...). +// Numeric defaults must parse as a number — the legacy true/false values no +// longer slip through. +func validateDefaultValue(entityName, fieldName, inner string, isArray bool, defaultVal string) []ValidationError { var errs []ValidationError - switch { - case specmeta.IsNumeric(ftype): - if boolValues[defaultVal] { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not valid for numeric type %s", defaultVal, ftype), Warning: true}) - } - case ftype == "boolean": - if !boolValues[defaultVal] { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not valid for boolean (expected true/false)", defaultVal), Warning: true}) - } - case ftype == "date": - if !isValidDate(defaultVal) { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not a valid date (expected YYYY-MM-DD)", defaultVal), Warning: true}) - } - case ftype == "datetime": - if !isValidDatetime(defaultVal) { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", defaultVal), Warning: true}) - } - case ftype == "uuid": - if !isValidUUID(defaultVal) { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default value '%s' is not a valid UUID", defaultVal), Warning: true}) + values := []string{defaultVal} + if isArray { + values = specmeta.SplitArrayDefault(defaultVal) + } + + for _, value := range values { + switch { + case specmeta.IsIntegralType(inner), specmeta.IsFloatType(inner): + errs = append(errs, validateNumericDefault(entityName, fieldName, inner, value)...) + case inner == specmeta.FieldTypeBoolean: + if !boolValues[value] { + errs = append(errs, invalidf(entityName, fieldName, + "default value '%s' is not valid for boolean (expected true/false)", value)) + } + case inner == specmeta.FieldTypeDate: + if !isValidDate(value) { + errs = append(errs, invalidf(entityName, fieldName, + "default value '%s' is not a valid date (expected YYYY-MM-DD)", value)) + } + case inner == specmeta.FieldTypeDatetime: + if !isValidDatetime(value) { + errs = append(errs, invalidf(entityName, fieldName, + "default value '%s' is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", value)) + } + case inner == specmeta.FieldTypeUUID: + if !isValidUUID(value) { + errs = append(errs, invalidf(entityName, fieldName, + "default value '%s' is not a valid UUID", value)) + } } } return errs } +// validateNumericDefault parses a numeric default with the parser matching its +// kind: integral types reject decimals, float types accept them. Both kinds +// share one diagnostic so the message cannot drift between them. +func validateNumericDefault(entityName, fieldName, inner, value string) []ValidationError { + if specmeta.IsIntegralType(inner) { + if _, err := strconv.ParseInt(value, 10, 64); err != nil { + return []ValidationError{invalidf(entityName, fieldName, + "default value '%s' is not valid for numeric type %s", value, inner)} + } + return nil + } + if _, err := strconv.ParseFloat(value, 64); err != nil { + return []ValidationError{invalidf(entityName, fieldName, + "default value '%s' is not valid for numeric type %s", value, inner)} + } + return nil +} + // validateFuncDefault checks that function-style defaults (e.g. now(), uuid()) are used on appropriate types. func validateFuncDefault(entityName, fieldName, ftype, funcName string) []ValidationError { var errs []ValidationError allowedTypes, ok := specmeta.FuncDefaults[funcName] if !ok { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("unknown default function '%s()'", funcName)}) + errs = append(errs, invalidf(entityName, fieldName, + "unknown default function '%s()'", funcName)) return errs } - allowed := false - for _, t := range allowedTypes { - if ftype == t { - allowed = true - break - } - } + allowed := slices.Contains(allowedTypes, ftype) if !allowed { - errs = append(errs, ValidationError{Entity: entityName, Field: fieldName, Message: fmt.Sprintf("default '%s()' is not valid for type %s; allowed types: %s", funcName, ftype, strings.Join(allowedTypes, ", "))}) + errs = append(errs, invalidf(entityName, fieldName, + "default '%s()' is not valid for type %s; allowed types: %s", funcName, ftype, strings.Join(allowedTypes, ", "))) } return errs } // validateContradictoryRanges checks for impossible validation ranges (e.g. min > max, gte > lt). -func validateContradictoryRanges(entityName, fieldName string, field *parser.ParsedField, isNumeric, isString bool) []ValidationError { +func validateContradictoryRanges(entityName, fieldName string, validations map[string]string, + isNumeric, isString bool) []ValidationError { var errs []ValidationError getFloat := func(key string) (float64, bool) { - val, ok := field.Validations[key] + val, ok := validations[key] if !ok || val == "" { return 0, false } @@ -781,37 +975,61 @@ func validateContradictoryRanges(entityName, fieldName string, field *parser.Par } if isString { + // String min/max are length bounds; keep their dedicated diagnostic. minVal, hasMin := getFloat("min") maxVal, hasMax := getFloat("max") if hasMin && hasMax && minVal > maxVal { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("validation min (%.0f) is greater than max (%.0f)", minVal, maxVal), - }) + errs = append(errs, invalidf(entityName, fieldName, + "validation min (%g) is greater than max (%g)", minVal, maxVal)) } } if isNumeric { - // Check gte vs lt (strict upper bound) - gteVal, hasGte := getFloat("gte") - ltVal, hasLt := getFloat("lt") - if hasGte && hasLt && gteVal >= ltVal { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("validation gte (%.0f) must be less than lt (%.0f)", gteVal, ltVal), - }) - } - // Check gt vs lte (non-strict bounds) - gtVal, hasGt := getFloat("gt") - lteVal, hasLte := getFloat("lte") - if hasGt && hasLte && gtVal >= lteVal { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("validation gt (%.0f) must be less than lte (%.0f)", gtVal, lteVal), - }) + // Compare the effective bounds, not just the four original pairs: + // gte/lte, gt/lt and numeric min/max must be checked too, and one + // contradictory range must produce one error. + type bound struct { + name string + value float64 + strict bool + } + var lower, upper *bound + addLower := func(b bound) { + if lower == nil || b.value > lower.value || (b.value == lower.value && b.strict) { + chosen := b + lower = &chosen + } + } + addUpper := func(b bound) { + if upper == nil || b.value < upper.value || (b.value == upper.value && b.strict) { + chosen := b + upper = &chosen + } + } + if value, ok := getFloat("gte"); ok { + addLower(bound{name: "gte", value: value}) + } + if value, ok := getFloat("gt"); ok { + addLower(bound{name: "gt", value: value, strict: true}) + } + // Numeric min/max are value bounds (IR maps them to min_value/max_value), + // so they belong in the same effective-range check as gte/lte and gt/lt. + if value, ok := getFloat("min"); ok { + addLower(bound{name: "min", value: value}) + } + if value, ok := getFloat("lte"); ok { + addUpper(bound{name: "lte", value: value}) + } + if value, ok := getFloat("lt"); ok { + addUpper(bound{name: "lt", value: value, strict: true}) + } + if value, ok := getFloat("max"); ok { + addUpper(bound{name: "max", value: value}) + } + if lower != nil && upper != nil && + (lower.value > upper.value || (lower.value == upper.value && (lower.strict || upper.strict))) { + errs = append(errs, invalidf(entityName, fieldName, + "validation %s (%g) must be less than %s (%g)", lower.name, lower.value, upper.name, upper.value)) } } @@ -832,42 +1050,50 @@ func missingFields(missingEmail, missingPassword bool) string { // --- index-level --- -func (v *Validator) validateIndex(entityName string, idxNum int, idx *parser.ParsedIndex, entity *parser.ParsedEntity) []ValidationError { +func (v *Validator) validateIndex(entityName string, idxNum int, idx *parser.ParsedIndex, + entity *parser.ParsedEntity) []ValidationError { var errs []ValidationError if len(idx.Fields) == 0 { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("index %d has no fields", idxNum)}) + errs = append(errs, invalidf(entityName, "", + "index %d has no fields", idxNum)) } // Duplicate fields in index. fieldSeen := make(map[string]bool) for _, f := range idx.Fields { if fieldSeen[f] { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("index %d has duplicate field '%s'", idxNum, f), Warning: true}) + errs = append(errs, warnf(entityName, "", + "index %d has duplicate field '%s'", idxNum, f)) } fieldSeen[f] = true if _, ok := entity.Fields[f]; !ok { - errs = append(errs, ValidationError{Entity: entityName, Field: f, Message: fmt.Sprintf("index %d references unknown field '%s'", idxNum, f)}) - } else if entity.Fields[f].IsRelation() && !isFKFieldName(f) { - errs = append(errs, ValidationError{Entity: entityName, Field: f, Message: fmt.Sprintf("index %d references relation field '%s'; index the FK field instead (e.g. '%sId')", idxNum, f, f), Warning: true}) + errs = append(errs, invalidf(entityName, f, + "index %d references unknown field '%s'", idxNum, f)) + } else if entity.Fields[f].IsRelation() && !specmeta.HasIDSuffix(f) { + errs = append(errs, warnf(entityName, f, + "index %d references relation field '%s'; index the FK field instead (e.g. '%sId')", idxNum, f, f)) } } // Index type. if idx.Type != "" && !specmeta.IsIndexType(idx.Type) { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("index %d has unknown type %q; allowed: %s", idxNum, idx.Type, strings.Join(specmeta.IndexTypes, ", "))}) + errs = append(errs, invalidf(entityName, "", + "index %d has unknown type %q; allowed: %s", idxNum, idx.Type, strings.Join(specmeta.IndexTypes, ", "))) } // Sort array length must match fields length. if len(idx.Sort) > 0 && len(idx.Sort) != len(idx.Fields) { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("index %d: sort array length (%d) does not match fields length (%d)", idxNum, len(idx.Sort), len(idx.Fields))}) + errs = append(errs, invalidf(entityName, "", + "index %d: sort array length (%d) does not match fields length (%d)", idxNum, len(idx.Sort), len(idx.Fields))) } // Sort values must be asc or desc. for _, s := range idx.Sort { if !specmeta.IsSortDirection(s) { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("index %d: invalid sort value %q; allowed: %s", idxNum, s, strings.Join(specmeta.SortDirections, ", "))}) + errs = append(errs, invalidf(entityName, "", + "index %d: invalid sort value %q; allowed: %s", idxNum, s, strings.Join(specmeta.SortDirections, ", "))) } } @@ -882,15 +1108,17 @@ func (v *Validator) validatePermissions(entityName string, perms *parser.ParsedP validateRoles := func(operation string, roles []string) { for _, role := range roles { if role == "" { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("permission '%s' has an empty role", operation)}) + errs = append(errs, invalidf(entityName, "", + "permission '%s' has an empty role", operation)) continue } // Skip special tokens: * (public) and @... (ownership tokens) if specmeta.IsReservedPermissionToken(role) { continue } - if !validIdentifier.MatchString(role) { - errs = append(errs, ValidationError{Entity: entityName, Message: fmt.Sprintf("permission '%s' role %q is not a valid identifier", operation, role), Warning: true}) + if !specmeta.IsValidIdentifier(role) { + errs = append(errs, warnf(entityName, "", + "permission '%s' role %q is not a valid identifier", operation, role)) } } } @@ -905,27 +1133,33 @@ func (v *Validator) validatePermissions(entityName string, perms *parser.ParsedP // --- seed-level --- -func (v *Validator) validateSeedEntry(entityName string, entity *parser.ParsedEntity, entryIdx int, entry map[string]interface{}) []ValidationError { +func (v *Validator) validateSeedEntry(entityName string, entity *parser.ParsedEntity, + entryIdx int, entry map[string]any) []ValidationError { var errs []ValidationError + seedFields := slices.Sorted(maps.Keys(entry)) // Check that seed fields exist. - for seedField := range entry { + for _, seedField := range seedFields { if _, ok := entity.Fields[seedField]; !ok { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: seedField, - Message: fmt.Sprintf("seed entry %d references unknown field '%s'", entryIdx, seedField), - }) + errs = append(errs, invalidf(entityName, seedField, + "seed entry %d references unknown field '%s'", entryIdx, seedField)) } } // Check seed value types against field types. - for seedField, seedValue := range entry { + for _, seedField := range seedFields { + seedValue := entry[seedField] field := entity.Fields[seedField] if field == nil { continue } - errs = append(errs, v.validateSeedValueType(entityName, seedField, entryIdx, field, seedValue)...) + errs = append(errs, v.validateSeedValueType(seedValueContext{ + entityName: entityName, + fieldName: seedField, + entryIdx: entryIdx, + field: field, + seedValue: seedValue, + })...) } // Check required relation FK dependencies. @@ -942,210 +1176,179 @@ func (v *Validator) validateSeedEntry(entityName string, entity *parser.ParsedEn } target := v.schema.Entities[field.TargetEntity] if target == nil || len(target.Seed) == 0 { - errs = append(errs, ValidationError{ - Entity: entityName, - Field: fieldName, - Message: fmt.Sprintf("seed entry %d: required relation '%s' -> '%s' is not seeded (add FK value to seed or add seed data to %s)", entryIdx, fieldName, field.TargetEntity, field.TargetEntity), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: required relation '%s' -> '%s' is not seeded (add FK value to seed or add seed data to %s)", + entryIdx, fieldName, field.TargetEntity, field.TargetEntity)) } } return errs } +// isNativeNumeric reports whether value has one of the numeric types YAML +// decoding produces. Shared by the integral and float seed checks so the +// accepted Go shapes cannot drift apart. +func isNativeNumeric(value any) bool { + switch value.(type) { + case int, int32, int64, float32, float64: + return true + default: + return false + } +} + +// isFractionalFloat reports whether a numeric seed value is a float with a +// fractional part. Integral fields cannot hold such a value: the seed generator +// would truncate it (1.9 -> 1) without warning. +func isFractionalFloat(value any) bool { + switch n := value.(type) { + case float32: + return math.Trunc(float64(n)) != float64(n) + case float64: + return math.Trunc(n) != n + default: + return false + } +} + +// seedValueContext groups the five inputs of one seed-value check. errf adds +// the shared "seed entry N:" prefix so each branch states only its own problem. +type seedValueContext struct { + entityName string + fieldName string + entryIdx int + field *parser.ParsedField + seedValue any +} + +func (c seedValueContext) errf(format string, args ...any) ValidationError { + return invalidf(c.entityName, c.fieldName, "seed entry %d: "+format, + append([]any{c.entryIdx}, args...)...) +} + // validateSeedValueType checks that a seed value is type-compatible with its field. -func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx int, field *parser.ParsedField, seedValue interface{}) []ValidationError { +func (v *Validator) validateSeedValueType(c seedValueContext) []ValidationError { var errs []ValidationError - ftype := strings.ToLower(field.Type) + add := func(e ValidationError) { errs = append(errs, e) } + ftype := strings.ToLower(c.field.Type) - switch ftype { - case "string", "text": + switch { + case specmeta.IsStringType(ftype): // String-like fields accept strings or JSON string values; numbers/bools are // accepted too (YAML coercion) but must not be a map/slice. - if _, isMap := seedValue.(map[string]interface{}); isMap { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype), - }) - } else if _, isSlice := seedValue.([]interface{}); isSlice { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype), - }) - } - case "int", "bigint": - switch seedValue.(type) { - case int, int32, int64, float32, float64: - // numeric OK - case string: - // string representation — OK if it parses - default: - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype), - }) - } - case "float", "decimal": - switch seedValue.(type) { - case int, int32, int64, float32, float64: - // numeric OK - case string: - // string representation — OK - default: - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype), - }) + switch c.seedValue.(type) { + case map[string]any, []any: + add(c.errf("value %v is not compatible with type %s", c.seedValue, ftype)) + } + case specmeta.IsIntegralType(ftype): + if s, ok := c.seedValue.(string); ok { + // A string must parse; otherwise seed coercion silently yields 0. + if _, err := strconv.ParseInt(s, 10, 64); err != nil { + add(c.errf("value %q is not a valid %s", s, ftype)) + } + } else if !isNativeNumeric(c.seedValue) { + add(c.errf("value %v is not compatible with type %s", c.seedValue, ftype)) + } else if isFractionalFloat(c.seedValue) { + // A fractional float would be silently truncated by the seed generator. + add(c.errf("value %v is not compatible with type %s", c.seedValue, ftype)) + } + case specmeta.IsFloatType(ftype): + if s, ok := c.seedValue.(string); ok { + if _, err := strconv.ParseFloat(s, 64); err != nil { + add(c.errf("value %q is not a valid %s", s, ftype)) + } + } else if !isNativeNumeric(c.seedValue) { + add(c.errf("value %v is not compatible with type %s", c.seedValue, ftype)) } - case "boolean": - switch seedValue.(type) { + case ftype == specmeta.FieldTypeBoolean: + switch b := c.seedValue.(type) { case bool: - // OK case string: - s := strings.ToLower(seedValue.(string)) - if s != "true" && s != "false" { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not valid for boolean type", entryIdx, seedValue), - }) + if s := strings.ToLower(b); s != "true" && s != "false" { + add(c.errf("value %q is not valid for boolean type", c.seedValue)) } default: - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with boolean type", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with boolean type", c.seedValue)) } - case "date": - s, ok := seedValue.(string) + case ftype == specmeta.FieldTypeDate: + s, ok := c.seedValue.(string) if !ok { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with date type (expected string YYYY-MM-DD)", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with date type (expected string YYYY-MM-DD)", c.seedValue)) } else if !isValidDate(s) { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not a valid date (expected YYYY-MM-DD)", entryIdx, s), - }) + add(c.errf("value %q is not a valid date (expected YYYY-MM-DD)", s)) } - case "uuid": - s, ok := seedValue.(string) + case ftype == specmeta.FieldTypeUUID: + s, ok := c.seedValue.(string) if !ok { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with uuid type (expected string)", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with uuid type (expected string)", c.seedValue)) } else if !isValidUUID(s) { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not a valid UUID (expectedxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s), - }) + add(c.errf("value %q is not a valid UUID (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", s)) } - case "datetime": - s, ok := seedValue.(string) + case ftype == specmeta.FieldTypeDatetime: + s, ok := c.seedValue.(string) if !ok { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with datetime type (expected string)", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with datetime type (expected string)", c.seedValue)) } else if !isValidDatetime(s) { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", entryIdx, s), - }) + add(c.errf("value %q is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", s)) } - case "json", "jsonb": + case specmeta.FieldKind(ftype) == specmeta.FieldKindJSON: // JSON values can be any valid JSON — accept any type. // String values are validated as parseable JSON. - if s, ok := seedValue.(string); ok { - if !isValidJSON(s) { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not valid JSON", entryIdx, s), - }) - } + if s, ok := c.seedValue.(string); ok && !isValidJSON(s) { + add(c.errf("value %q is not valid JSON", s)) } - case "enum": + case ftype == specmeta.FieldTypeEnum: // The value must be one of the declared enum values. - sv, ok := seedValue.(string) + sv, ok := c.seedValue.(string) if !ok { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with enum type (expected string)", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with enum type (expected string)", c.seedValue)) break } - if values, defined := v.schema.Enums[field.TargetType]; defined { - found := false - for _, val := range values { - if val == sv { - found = true - break - } - } - if !found { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not a declared value of enum '%s'; valid values: %s", entryIdx, sv, field.TargetType, strings.Join(values, ", ")), - }) - } + if values, defined := v.schema.Enums[c.field.TargetType]; defined && !slices.Contains(values, sv) { + add(c.errf("value %q is not a declared value of enum '%s'; valid values: %s", sv, c.field.TargetType, + strings.Join(values, ", "))) } - case "array": + case ftype == specmeta.FieldTypeArray: // Accept a YAML list. String values are accepted as JSON arrays. - switch v := seedValue.(type) { - case []interface{}: - // OK — list of elements - case []string: - // OK + switch sv := c.seedValue.(type) { + case []any, []string: case string: - if !isValidJSONArray(v) { - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %q is not a valid JSON array for array type", entryIdx, v), - }) + if !isValidJSONArray(sv) { + add(c.errf("value %q is not a valid JSON array for array type", sv)) } default: - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with array type (expected a list)", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with array type (expected a list)", c.seedValue)) } - case "relation": + case ftype == specmeta.FieldTypeRelation: // FK values reference the target entity's PK. Accept scalar values // (string/number/bool matching the target PK type); more precise // cross-entity type checking is left to the seed FK dependency check. - switch seedValue.(type) { + switch c.seedValue.(type) { case string, int, int32, int64, float32, float64, bool: - // OK default: - errs = append(errs, ValidationError{ - Entity: entityName, Field: fieldName, - Message: fmt.Sprintf("seed entry %d: value %v is not compatible with relation FK type", entryIdx, seedValue), - }) + add(c.errf("value %v is not compatible with relation FK type", c.seedValue)) } } return errs } +// isValidDate is shared by default-value and seed validation. Each caller +// builds its own diagnostic, so the message stays out of the helper. func isValidDate(s string) bool { t, err := time.Parse("2006-01-02", s) return err == nil && t.Year() >= 1970 && t.Year() <= 2100 } func isValidJSONArray(s string) bool { - var arr []interface{} + var arr []any return json.Unmarshal([]byte(s), &arr) == nil } -// isFKFieldName reports whether a field name is already an FK-style name -// (ends with "Id"/"id"), in which case indexing it maps to a real FK column. -func isFKFieldName(name string) bool { - return strings.HasSuffix(name, "Id") || strings.HasSuffix(name, "id") -} - var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +// isValidUUID is shared by default-value and seed validation; each caller +// keeps its own diagnostic text. func isValidUUID(s string) bool { return uuidPattern.MatchString(s) } @@ -1159,6 +1362,8 @@ var datetimePatterns = []string{ "2006-01-02", } +// isValidDatetime is shared by default-value and seed validation; each caller +// keeps its own diagnostic text. func isValidDatetime(s string) bool { for _, pattern := range datetimePatterns { if t, err := time.Parse(pattern, s); err == nil && t.Year() >= 1970 && t.Year() <= 2100 { @@ -1169,7 +1374,7 @@ func isValidDatetime(s string) bool { } func isValidJSON(s string) bool { - var v interface{} + var v any return json.Unmarshal([]byte(s), &v) == nil } diff --git a/internal/validator/validator_hardening_test.go b/internal/validator/validator_hardening_test.go new file mode 100644 index 0000000..86c5fa4 --- /dev/null +++ b/internal/validator/validator_hardening_test.go @@ -0,0 +1,168 @@ +package validator + +import ( + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/testutil" +) + +func TestAuthJWTRequiresEntityAndRoles(t *testing.T) { + t.Parallel() + + t.Run("no auth entity is an error", func(t *testing.T) { + t.Parallel() + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + Auth: &parser.AuthConfig{Type: "jwt"}, + EntityOrder: []string{"Item"}, + Entities: map[string]*parser.ParsedEntity{ + "Item": {Name: "Item", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }}, + }, + } + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "no entity has both 'email' and 'password'") { + found = true + } + } + if !found { + t.Fatalf("expected hard error about missing auth entity, got %v", errs) + } + }) + + t.Run("empty roles are an error", func(t *testing.T) { + t.Parallel() + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + Auth: &parser.AuthConfig{Type: "jwt"}, + EntityOrder: []string{"User"}, + Entities: map[string]*parser.ParsedEntity{ + "User": {Name: "User", FieldOrder: []string{"id", "email", "password"}, Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string"), + "password": testutil.MustParsedField(t, "password", "string"), + }}, + }, + } + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "auth.roles must declare at least one role") { + found = true + } + } + if !found { + t.Fatalf("expected hard error about empty auth roles, got %v", errs) + } + }) +} + +func TestRelationPrimaryKeyReportedOnce(t *testing.T) { + t.Parallel() + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"User", "Item"}, + Entities: map[string]*parser.ParsedEntity{ + "User": {Name: "User", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }}, + "Item": {Name: "Item", FieldOrder: []string{"owner"}, Fields: map[string]*parser.ParsedField{ + "owner": testutil.MustParsedField(t, "owner", "relation(User) [primary]"), + }}, + }, + } + errs := nonWarnings(New(schema).Validate()) + count := 0 + for _, e := range errs { + if strings.Contains(e.Message, "primary key cannot be a relation field") { + count++ + } + } + if count != 1 { + t.Fatalf("got %d relation primary key errors, want 1: %v", count, errs) + } +} + +func TestContradictoryRangePairs(t *testing.T) { + t.Parallel() + cases := []struct { + name string + def string + wantErr bool + }{ + {name: "gte greater than lte", def: "int [gte:10, lte:2]", wantErr: true}, + {name: "gt equal to lt", def: "int [gt:2, lt:2]", wantErr: true}, + {name: "numeric min greater than max", def: "int [min:10, max:2]", wantErr: true}, + {name: "numeric min greater than lte", def: "int [min:100, lte:10]", wantErr: true}, + {name: "gte greater than numeric max", def: "int [gte:100, max:10]", wantErr: true}, + {name: "gt equal to numeric max", def: "int [gt:5, max:5]", wantErr: true}, + {name: "gte equal to lte is valid", def: "int [gte:2, lte:2]"}, + {name: "numeric min below max is valid", def: "int [min:1, max:10]"}, + {name: "numeric min below lte is valid", def: "int [min:1, lte:10]"}, + {name: "gte equal to numeric max is valid", def: "int [gte:2, max:2]"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + field := testutil.MustParsedField(t, "value", c.def) + errs := nonWarnings(validateFieldValidations("Item", "value", field)) + if c.wantErr && len(errs) != 1 { + t.Fatalf("%s produced %d errors, want 1: %v", c.def, len(errs), errs) + } + if !c.wantErr && len(errs) != 0 { + t.Fatalf("%s produced errors, want none: %v", c.def, errs) + } + }) + } +} + +func TestStringLengthBoundsMustBeIntegers(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + def string + wantErr bool + }{ + {name: "fractional max rejected", def: "string [max:1.5]", wantErr: true}, + {name: "integer max accepted", def: "string [max:5]"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + field := testutil.MustParsedField(t, "name", c.def) + errs := nonWarnings(validateFieldValidations("Item", "name", field)) + if got := len(errs) > 0; got != c.wantErr { + t.Fatalf("%s errors = %v, wantErr %t", c.def, errs, c.wantErr) + } + }) + } +} + +func TestInvalidDefaultsAreErrors(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + def string + wantErr bool + }{ + {name: "invalid integer default", def: "int [default:abc]", wantErr: true}, + {name: "invalid boolean default", def: "boolean [default:maybe]", wantErr: true}, + {name: "valid boolean default", def: "boolean [default:true]"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + field := testutil.MustParsedField(t, "value", c.def) + errs := New(&parser.ParsedSchema{}).validateFieldDefault("Item", "value", field) + if got := len(errs) > 0; got != c.wantErr { + t.Fatalf("%s errors = %v, wantErr %t", c.def, errs, c.wantErr) + } + if c.wantErr && errs[0].Warning { + t.Fatalf("%s produced a warning, want an error", c.def) + } + }) + } +} diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index d51069e..d7a52db 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -7,10 +7,54 @@ import ( "testing" "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/internal/testutil" ) +// TestValidationDiagnosticsAreDeterministic guards the rule that diagnostics +// use the same order on every run. Several checks iterate maps internally; an +// unordered range made `validate` and the WASM result change line order. +func TestValidationDiagnosticsAreDeterministic(t *testing.T) { + t.Parallel() + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Item"}, + Entities: map[string]*parser.ParsedEntity{ + "Item": { + Name: "Item", + FieldOrder: []string{"id", "status", "count"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(Zebra)"), + "count": testutil.MustParsedField(t, "count", "int [min:abc, max:x]"), + }, + }, + }, + Enums: map[string][]string{"Zebra": {}, "Alpha": {}}, + } + + var want string + for range 20 { + var got strings.Builder + for _, e := range New(schema).Validate() { + got.WriteString(e.Message) + got.WriteByte('\n') + } + if want == "" { + want = got.String() + continue + } + if got.String() != want { + t.Fatalf("validation diagnostics are not deterministic:\nfirst:\n%s\nnext:\n%s", want, got.String()) + } + } + if !strings.Contains(want, "enum must have at least one value") { + t.Fatalf("fixture did not produce the enum diagnostic: %s", want) + } +} + func TestValidateDetectsMissingPrimaryKey(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -19,7 +63,7 @@ func TestValidateDetectsMissingPrimaryKey(t *testing.T) { Name: "User", FieldOrder: []string{"email"}, Fields: map[string]*parser.ParsedField{ - "email": mustParsedField(t, "email", "string"), + "email": testutil.MustParsedField(t, "email", "string"), }, }, }, @@ -36,20 +80,11 @@ func TestValidateDetectsMissingPrimaryKey(t *testing.T) { } func TestValidateRejectsOldNameEqualToFieldName(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [required, old_name:name]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "name", "string [required, old_name:name]", + ) errs := New(schema).Validate() errs = nonWarnings(errs) @@ -65,21 +100,12 @@ func TestValidateRejectsOldNameEqualToFieldName(t *testing.T) { } func TestValidateRejectsOldNameCollidingWithExistingField(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "title", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "title": mustParsedField(t, "title", "string"), - "name": mustParsedField(t, "name", "string [required, old_name:title]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "title", "string", + "name", "string [required, old_name:title]", + ) errs := New(schema).Validate() errs = nonWarnings(errs) @@ -95,20 +121,11 @@ func TestValidateRejectsOldNameCollidingWithExistingField(t *testing.T) { } func TestValidateAcceptsValidOldName(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [required, old_name:title]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "name", "string [required, old_name:title]", + ) errs := nonWarnings(New(schema).Validate()) for _, e := range errs { @@ -119,20 +136,11 @@ func TestValidateAcceptsValidOldName(t *testing.T) { } func TestValidateDetectsDuplicatePrimaryKey(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "code"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "code": mustParsedField(t, "code", "string [primary]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "code", "string [primary]", + ) errs := New(schema).Validate() errs = nonWarnings(errs) @@ -148,20 +156,11 @@ func TestValidateDetectsDuplicatePrimaryKey(t *testing.T) { } func TestValidateDetectsBrokenRelation(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "categoryId"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category)"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid", + "categoryId", "relation(Category)", + ) product := schema.Entities["Product"] product.Fields["id"].IsPrimary = true @@ -172,7 +171,8 @@ func TestValidateDetectsBrokenRelation(t *testing.T) { } } -func TestValidateDetectsSetNullOnRequiredField(t *testing.T) { +func TestValidatorAcceptsSetNullOnOptionalField(t *testing.T) { + t.Parallel() // Note: on_delete:set_null on a required relation is caught by the lexer, not the validator. // This test verifies the schema passes validation when the lexer constraint is respected. schema := &parser.ParsedSchema{ @@ -183,15 +183,15 @@ func TestValidateDetectsSetNullOnRequiredField(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "categoryId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category) [optional]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "categoryId": testutil.MustParsedField(t, "categoryId", "relation(Category) [optional]"), }, }, "Category": { Name: "Category", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -209,21 +209,12 @@ func TestValidateDetectsSetNullOnRequiredField(t *testing.T) { } func TestValidateDetectsUndefinedEnum(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Enums: map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(NoSuchEnum)"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(NoSuchEnum)", + ) + schema.Enums = map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}} schema.Entities["Product"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -239,22 +230,13 @@ func TestValidateDetectsUndefinedEnum(t *testing.T) { } func TestValidatePassesValidEnums(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Enums: map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status", "tags"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(ProductStatus)"), - "tags": mustParsedField(t, "tags", "array(ProductStatus)"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(ProductStatus)", + "tags", "array(ProductStatus)", + ) + schema.Enums = map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}} schema.Entities["Product"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -265,18 +247,11 @@ func TestValidatePassesValidEnums(t *testing.T) { } func TestValidateDetectsEmptyProjectName(t *testing.T) { - schema := &parser.ParsedSchema{ - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Project.Name = "" schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -291,22 +266,13 @@ func TestValidateDetectsEmptyProjectName(t *testing.T) { } } -func TestValidateDetectsManyOnNonRelation(t *testing.T) { +func TestValidatorAcceptsValidSchemaAfterLexerRejectsMany(t *testing.T) { + t.Parallel() // Note: "many" on non-relation is caught by the lexer, not the validator. // This test verifies the lexer catches it before validation. - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true // Valid schema should pass — the lexer rejects "many" on non-relation at parse time. @@ -317,22 +283,13 @@ func TestValidateDetectsManyOnNonRelation(t *testing.T) { } } -func TestValidateDetectsOnDeleteOnNonRelation(t *testing.T) { +func TestValidatorAcceptsValidSchemaAfterLexerRejectsOnDelete(t *testing.T) { + t.Parallel() // Note: on_delete on non-relation is caught by the lexer, not the validator. // This test verifies the lexer catches it before validation. - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true // Valid schema should pass — the lexer rejects on_delete on non-relation at parse time. @@ -344,20 +301,11 @@ func TestValidateDetectsOnDeleteOnNonRelation(t *testing.T) { } func TestValidateDetectsEmptyEnum(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Enums: map[string][]string{"Status": {}}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Enums = map[string][]string{"Status": {}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -373,22 +321,11 @@ func TestValidateDetectsEmptyEnum(t *testing.T) { } func TestValidateDetectsEmptyIndexFields(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - Indexes: []*parser.ParsedIndex{ - {Fields: []string{}, Type: "btree"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Entities["User"].Indexes = []*parser.ParsedIndex{{Fields: []string{}, Type: "btree"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -404,23 +341,12 @@ func TestValidateDetectsEmptyIndexFields(t *testing.T) { } func TestValidateDetectsSortLengthMismatch(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), - }, - Indexes: []*parser.ParsedIndex{ - {Fields: []string{"id", "email"}, Sort: []string{"asc"}, Type: "btree"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string", + ) + schema.Entities["User"].Indexes = []*parser.ParsedIndex{{Fields: []string{"id", "email"}, Sort: []string{"asc"}, Type: "btree"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -435,10 +361,6 @@ func TestValidateDetectsSortLengthMismatch(t *testing.T) { } } -func mustParsedField(t *testing.T, name, input string) *parser.ParsedField { - return testutil.MustParsedField(t, name, input) -} - func nonWarnings(errs []ValidationError) []ValidationError { var result []ValidationError for _, e := range errs { @@ -450,21 +372,12 @@ func nonWarnings(errs []ValidationError) []ValidationError { } func TestValidateAuthEntityMissingEmailPassword(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - Auth: &parser.AuthConfig{Type: "jwt", Entity: "Product"}, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "name", "string", + ) + schema.Auth = &parser.AuthConfig{Type: "jwt", Entity: "Product"} schema.Entities["Product"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -480,22 +393,13 @@ func TestValidateAuthEntityMissingEmailPassword(t *testing.T) { } func TestValidateAuthEntityValidEmailPassword(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - Auth: &parser.AuthConfig{Type: "jwt", Entity: "User"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email", "password"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), - "password": mustParsedField(t, "password", "string"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string", + "password", "string", + ) + schema.Auth = &parser.AuthConfig{Type: "jwt", Entity: "User"} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -508,20 +412,11 @@ func TestValidateAuthEntityValidEmailPassword(t *testing.T) { } func TestValidateDefaultNowOnNonDatetime(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "count"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "count": mustParsedField(t, "count", "int [default:now()]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "count", "int [default:now()]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -537,20 +432,11 @@ func TestValidateDefaultNowOnNonDatetime(t *testing.T) { } func TestValidateDefaultNowOnDatetime(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "created"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "created": mustParsedField(t, "created", "datetime [default:now()]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "created", "datetime [default:now()]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -563,20 +449,11 @@ func TestValidateDefaultNowOnDatetime(t *testing.T) { } func TestValidateDefaultUuidOnNonUuid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [default:uuid()]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "name", "string [default:uuid()]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -592,6 +469,7 @@ func TestValidateDefaultUuidOnNonUuid(t *testing.T) { } func TestValidateDeployPortRange(t *testing.T) { + t.Parallel() tests := []struct { name string port int @@ -606,22 +484,11 @@ func TestValidateDeployPortRange(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{ - Name: "Test", - Deploy: &parser.DeployConfig{Port: tt.port}, - }, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Project = parser.ProjectConfig{Name: "Test", Deploy: &parser.DeployConfig{Port: tt.port}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -643,7 +510,9 @@ func TestValidateDeployPortRange(t *testing.T) { } func TestValidateCacheConfigWarnings(t *testing.T) { + t.Parallel() t.Run("provider without connection_string", func(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{ Name: "Test", @@ -658,7 +527,7 @@ func TestValidateCacheConfigWarnings(t *testing.T) { Name: "User", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -678,6 +547,7 @@ func TestValidateCacheConfigWarnings(t *testing.T) { }) t.Run("provider specified but disabled", func(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{ Name: "Test", @@ -692,7 +562,7 @@ func TestValidateCacheConfigWarnings(t *testing.T) { Name: "User", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -713,6 +583,7 @@ func TestValidateCacheConfigWarnings(t *testing.T) { } func TestValidateIndexOnRelationFieldWithoutIdSuffix(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product", "Category"}, @@ -721,8 +592,8 @@ func TestValidateIndexOnRelationFieldWithoutIdSuffix(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "category"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "category": mustParsedField(t, "category", "relation(Category)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "category": testutil.MustParsedField(t, "category", "relation(Category)"), }, Indexes: []*parser.ParsedIndex{ {Fields: []string{"category"}, Type: "btree"}, @@ -732,7 +603,7 @@ func TestValidateIndexOnRelationFieldWithoutIdSuffix(t *testing.T) { Name: "Category", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -752,6 +623,7 @@ func TestValidateIndexOnRelationFieldWithoutIdSuffix(t *testing.T) { } func TestValidateIndexOnFKFieldNoWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product", "Category"}, @@ -760,8 +632,8 @@ func TestValidateIndexOnFKFieldNoWarning(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "categoryId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "categoryId": testutil.MustParsedField(t, "categoryId", "relation(Category)"), }, Indexes: []*parser.ParsedIndex{ {Fields: []string{"categoryId"}, Type: "btree"}, @@ -771,7 +643,7 @@ func TestValidateIndexOnFKFieldNoWarning(t *testing.T) { Name: "Category", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -787,23 +659,12 @@ func TestValidateIndexOnFKFieldNoWarning(t *testing.T) { } func TestValidateIndexOnPrimitiveField(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), - }, - Indexes: []*parser.ParsedIndex{ - {Fields: []string{"email"}, Type: "btree"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string", + ) + schema.Entities["User"].Indexes = []*parser.ParsedIndex{{Fields: []string{"email"}, Type: "btree"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -816,21 +677,12 @@ func TestValidateIndexOnPrimitiveField(t *testing.T) { } func TestValidateEnumDefaultMustMatchDeclaredValues(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Enums: map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(ProductStatus) [default:DRAFTT]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(ProductStatus) [default:DRAFTT]", + ) + schema.Enums = map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}} schema.Entities["Product"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -847,21 +699,12 @@ func TestValidateEnumDefaultMustMatchDeclaredValues(t *testing.T) { } func TestValidateEnumDefaultValidValue(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Product"}, - Enums: map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(ProductStatus) [default:DRAFT]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(ProductStatus) [default:DRAFT]", + ) + schema.Enums = map[string][]string{"ProductStatus": {"DRAFT", "PUBLISHED"}} schema.Entities["Product"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -874,20 +717,11 @@ func TestValidateEnumDefaultValidValue(t *testing.T) { } func TestValidateNumericValidationValueNotNumeric(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "age"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int [gte:notanumber]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "age", "int [gte:notanumber]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -904,20 +738,11 @@ func TestValidateNumericValidationValueNotNumeric(t *testing.T) { } func TestValidateNumericValidationValueValid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "age"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int [gte:0, lt:150]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "age", "int [gte:0, lt:150]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -930,20 +755,11 @@ func TestValidateNumericValidationValueValid(t *testing.T) { } func TestValidateEntityEnumNameCollision(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Status"}, - Enums: map[string][]string{"Status": {"ACTIVE", "INACTIVE"}}, - Entities: map[string]*parser.ParsedEntity{ - "Status": { - Name: "Status", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Status", + "id", "uuid [primary]", + ) + schema.Enums = map[string][]string{"Status": {"ACTIVE", "INACTIVE"}} schema.Entities["Status"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -959,25 +775,14 @@ func TestValidateEntityEnumNameCollision(t *testing.T) { } func TestValidatePermissionRolesEmptyAuthRoles(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - Auth: &parser.AuthConfig{Type: "jwt"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email", "password"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), - "password": mustParsedField(t, "password", "string"), - }, - Permissions: &parser.ParsedPermissions{ - Read: []string{"Admin"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string", + "password", "string", + ) + schema.Auth = &parser.AuthConfig{Type: "jwt"} + schema.Entities["User"].Permissions = &parser.ParsedPermissions{Read: []string{"Admin"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -993,20 +798,11 @@ func TestValidatePermissionRolesEmptyAuthRoles(t *testing.T) { } func TestValidateContradictoryStringMinMax(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [min:10, max:5]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "name", "string [min:10, max:5]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1023,20 +819,11 @@ func TestValidateContradictoryStringMinMax(t *testing.T) { } func TestValidateValidStringMinMax(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [min:2, max:50]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "name", "string [min:2, max:50]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1049,20 +836,11 @@ func TestValidateValidStringMinMax(t *testing.T) { } func TestValidateContradictoryNumericGteLt(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "age"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int [gte:100, lt:10]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "age", "int [gte:100, lt:10]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1079,20 +857,11 @@ func TestValidateContradictoryNumericGteLt(t *testing.T) { } func TestValidateContradictoryNumericGtLte(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "score"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "score": mustParsedField(t, "score", "int [gt:50, lte:50]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "score", "int [gt:50, lte:50]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1109,20 +878,11 @@ func TestValidateContradictoryNumericGtLte(t *testing.T) { } func TestValidateValidNumericRange(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "age"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int [gte:0, lt:150]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "age", "int [gte:0, lt:150]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1135,21 +895,12 @@ func TestValidateValidNumericRange(t *testing.T) { } func TestValidateUnusedEnumWarning(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Enums: map[string][]string{"Role": {"ADMIN", "USER"}, "Status": {"ACTIVE", "INACTIVE"}}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "role"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "role": mustParsedField(t, "role", "enum(Role)"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "role", "enum(Role)", + ) + schema.Enums = map[string][]string{"Role": {"ADMIN", "USER"}, "Status": {"ACTIVE", "INACTIVE"}} schema.Entities["User"].Fields["id"].IsPrimary = true schema.Entities["User"].Fields["role"].Type = "enum" schema.Entities["User"].Fields["role"].TargetType = "Role" @@ -1167,21 +918,12 @@ func TestValidateUnusedEnumWarning(t *testing.T) { } func TestValidateUsedEnumNoWarning(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Enums: map[string][]string{"Role": {"ADMIN", "USER"}}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "role"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "role": mustParsedField(t, "role", "enum(Role)"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "role", "enum(Role)", + ) + schema.Enums = map[string][]string{"Role": {"ADMIN", "USER"}} schema.Entities["User"].Fields["id"].IsPrimary = true schema.Entities["User"].Fields["role"].Type = "enum" schema.Entities["User"].Fields["role"].TargetType = "Role" @@ -1194,7 +936,8 @@ func TestValidateUsedEnumNoWarning(t *testing.T) { } } -func TestValidateOnDeleteValueInvalid(t *testing.T) { +func TestValidatorAcceptsValidSchemaAfterLexerRejectsOnDeleteValue(t *testing.T) { + t.Parallel() // Note: invalid on_delete values are caught by the lexer, not the validator. // This test verifies the lexer catches it before validation. schema := &parser.ParsedSchema{ @@ -1205,14 +948,14 @@ func TestValidateOnDeleteValueInvalid(t *testing.T) { Name: "Order", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, "User": { Name: "User", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -1229,22 +972,13 @@ func TestValidateOnDeleteValueInvalid(t *testing.T) { } func TestValidateSeedValueTypeMismatch(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "age"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "age": true}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "age", "int", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "age": true}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1262,22 +996,13 @@ func TestValidateSeedValueTypeMismatch(t *testing.T) { } func TestValidateSeedBooleanTypeMismatch(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Config"}, - Entities: map[string]*parser.ParsedEntity{ - "Config": { - Name: "Config", - FieldOrder: []string{"id", "enabled"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "enabled": mustParsedField(t, "enabled", "boolean"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "enabled": "notabool"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Config", + "id", "uuid [primary]", + "enabled", "boolean", + ) + schema.Entities["Config"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "enabled": "notabool"}, } schema.Entities["Config"].Fields["id"].IsPrimary = true @@ -1295,6 +1020,7 @@ func TestValidateSeedBooleanTypeMismatch(t *testing.T) { } func TestValidateOnDeleteOnManyToManyWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product", "Tag"}, @@ -1303,15 +1029,15 @@ func TestValidateOnDeleteOnManyToManyWarning(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Tag": { Name: "Tag", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -1332,6 +1058,7 @@ func TestValidateOnDeleteOnManyToManyWarning(t *testing.T) { } func TestValidateOnDeleteOnManyToManyNoWarningWithoutOnDelete(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product", "Tag"}, @@ -1340,15 +1067,15 @@ func TestValidateOnDeleteOnManyToManyNoWarningWithoutOnDelete(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Tag": { Name: "Tag", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -1365,6 +1092,7 @@ func TestValidateOnDeleteOnManyToManyNoWarningWithoutOnDelete(t *testing.T) { } func TestValidateReconciledOneToManyWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Article", "Tag"}, @@ -1373,16 +1101,16 @@ func TestValidateReconciledOneToManyWarning(t *testing.T) { Name: "Article", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Tag": { Name: "Tag", FieldOrder: []string{"id", "article"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "article": mustParsedField(t, "article", "relation(Article)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "article": testutil.MustParsedField(t, "article", "relation(Article)"), }, }, }, @@ -1405,6 +1133,7 @@ func TestValidateReconciledOneToManyWarning(t *testing.T) { // Regression: the hint must print the FK field name as declared. Appending a // second "Id" to a field already named `articleId` produced `articleIdId`. func TestValidateReconciledWarningKeepsFKName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Article", "Tag"}, @@ -1413,16 +1142,16 @@ func TestValidateReconciledWarningKeepsFKName(t *testing.T) { Name: "Article", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Tag": { Name: "Tag", FieldOrder: []string{"id", "articleId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "articleId": mustParsedField(t, "articleId", "relation(Article)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "articleId": testutil.MustParsedField(t, "articleId", "relation(Article)"), }, }, }, @@ -1450,6 +1179,7 @@ func TestValidateReconciledWarningKeepsFKName(t *testing.T) { // The shipped example must not emit warnings: an example is a template users copy. func TestExampleDomainHasNoWarnings(t *testing.T) { + t.Parallel() data, err := os.ReadFile(filepath.Join("..", "..", "examples", "domain.yaml")) if err != nil { t.Fatalf("read example: %v", err) @@ -1468,6 +1198,7 @@ func TestExampleDomainHasNoWarnings(t *testing.T) { // TestValidateGenuineManyToManyHasNoReconciliationWarning ensures that a real // many-to-many (target has no FK back) does NOT trigger the reconciliation hint. func TestValidateGenuineManyToManyHasNoReconciliationWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product", "Tag"}, @@ -1476,15 +1207,15 @@ func TestValidateGenuineManyToManyHasNoReconciliationWarning(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "relation(Tag) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "relation(Tag) [many]"), }, }, "Tag": { Name: "Tag", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -1499,23 +1230,14 @@ func TestValidateGenuineManyToManyHasNoReconciliationWarning(t *testing.T) { } func TestValidateSeedUniqueConstraintViolation(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string [unique]"), - }, - Seed: []map[string]interface{}{ - {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, - {"id": "22222222-2222-2222-2222-222222222222", "email": "a@test.com"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string [unique]", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, + {"id": "22222222-2222-2222-2222-222222222222", "email": "a@test.com"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1533,23 +1255,14 @@ func TestValidateSeedUniqueConstraintViolation(t *testing.T) { } func TestValidateSeedUniqueConstraintPass(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "email"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string [unique]"), - }, - Seed: []map[string]interface{}{ - {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, - {"id": "22222222-2222-2222-2222-222222222222", "email": "b@test.com"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "email", "string [unique]", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, + {"id": "22222222-2222-2222-2222-222222222222", "email": "b@test.com"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1563,21 +1276,12 @@ func TestValidateSeedUniqueConstraintPass(t *testing.T) { } func TestValidateSeedInvalidUUID(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - Seed: []map[string]interface{}{ - {"id": "not-a-uuid"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "not-a-uuid"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1595,21 +1299,12 @@ func TestValidateSeedInvalidUUID(t *testing.T) { } func TestValidateSeedValidUUID(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1623,22 +1318,13 @@ func TestValidateSeedValidUUID(t *testing.T) { } func TestValidateSeedInvalidDatetime(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "createdAt"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "createdAt": mustParsedField(t, "createdAt", "datetime"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "not-a-date"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "createdAt", "datetime", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "not-a-date"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1656,22 +1342,13 @@ func TestValidateSeedInvalidDatetime(t *testing.T) { } func TestValidateSeedValidDatetime(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "createdAt"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "createdAt": mustParsedField(t, "createdAt", "datetime"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "2024-01-15T10:30:00Z"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "createdAt", "datetime", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "2024-01-15T10:30:00Z"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1685,22 +1362,13 @@ func TestValidateSeedValidDatetime(t *testing.T) { } func TestValidateSeedInvalidJSON(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "metadata"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "metadata": mustParsedField(t, "metadata", "json"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": "{invalid json}"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "metadata", "json", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": "{invalid json}"}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1718,22 +1386,13 @@ func TestValidateSeedInvalidJSON(t *testing.T) { } func TestValidateSeedValidJSON(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "metadata"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "metadata": mustParsedField(t, "metadata", "json"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": `{"key":"value"}`}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "metadata", "json", + ) + schema.Entities["User"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": `{"key":"value"}`}, } schema.Entities["User"].Fields["id"].IsPrimary = true @@ -1747,22 +1406,11 @@ func TestValidateSeedValidJSON(t *testing.T) { } func TestValidatePermissionRoleIdentifierInvalid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - Permissions: &parser.ParsedPermissions{ - Read: []string{"valid-role", "123invalid"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Entities["User"].Permissions = &parser.ParsedPermissions{Read: []string{"valid-role", "123invalid"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1778,23 +1426,11 @@ func TestValidatePermissionRoleIdentifierInvalid(t *testing.T) { } func TestValidatePermissionRoleSpecialTokensAllowed(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - }, - Permissions: &parser.ParsedPermissions{ - Read: []string{"*", "@Owner"}, - Create: []string{"Admin"}, - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + ) + schema.Entities["User"].Permissions = &parser.ParsedPermissions{Read: []string{"*", "@Owner"}, Create: []string{"Admin"}} schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -1806,22 +1442,13 @@ func TestValidatePermissionRoleSpecialTokensAllowed(t *testing.T) { } func TestValidateSeedDateTypeMismatch(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Event"}, - Entities: map[string]*parser.ParsedEntity{ - "Event": { - Name: "Event", - FieldOrder: []string{"id", "started_on"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "started_on": mustParsedField(t, "started_on", "date"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "not-a-date"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Event", + "id", "uuid [primary]", + "started_on", "date", + ) + schema.Entities["Event"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "not-a-date"}, } schema.Entities["Event"].Fields["id"].IsPrimary = true @@ -1839,22 +1466,13 @@ func TestValidateSeedDateTypeMismatch(t *testing.T) { } func TestValidateSeedDateValid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Event"}, - Entities: map[string]*parser.ParsedEntity{ - "Event": { - Name: "Event", - FieldOrder: []string{"id", "started_on"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "started_on": mustParsedField(t, "started_on", "date"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "2024-05-01"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Event", + "id", "uuid [primary]", + "started_on", "date", + ) + schema.Entities["Event"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "2024-05-01"}, } schema.Entities["Event"].Fields["id"].IsPrimary = true @@ -1868,25 +1486,16 @@ func TestValidateSeedDateValid(t *testing.T) { } func TestValidateSeedEnumInvalidValue(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - Enums: map[string][]string{ - "Status": {"ACTIVE", "INACTIVE"}, - }, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "BOGUS"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(Status)", + ) + schema.Enums = map[string][]string{ + "Status": {"ACTIVE", "INACTIVE"}, + } + schema.Entities["Product"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "BOGUS"}, } schema.Entities["Product"].Fields["id"].IsPrimary = true @@ -1904,25 +1513,16 @@ func TestValidateSeedEnumInvalidValue(t *testing.T) { } func TestValidateSeedEnumValidValue(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - Enums: map[string][]string{ - "Status": {"ACTIVE", "INACTIVE"}, - }, - EntityOrder: []string{"Product"}, - Entities: map[string]*parser.ParsedEntity{ - "Product": { - Name: "Product", - FieldOrder: []string{"id", "status"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "ACTIVE"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Product", + "id", "uuid [primary]", + "status", "enum(Status)", + ) + schema.Enums = map[string][]string{ + "Status": {"ACTIVE", "INACTIVE"}, + } + schema.Entities["Product"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "ACTIVE"}, } schema.Entities["Product"].Fields["id"].IsPrimary = true @@ -1936,22 +1536,13 @@ func TestValidateSeedEnumValidValue(t *testing.T) { } func TestValidateSeedArrayInvalidValue(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Item"}, - Entities: map[string]*parser.ParsedEntity{ - "Item": { - Name: "Item", - FieldOrder: []string{"id", "tags"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "array(string)"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": "not-json"}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Item", + "id", "uuid [primary]", + "tags", "array(string)", + ) + schema.Entities["Item"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": "not-json"}, } schema.Entities["Item"].Fields["id"].IsPrimary = true @@ -1969,22 +1560,13 @@ func TestValidateSeedArrayInvalidValue(t *testing.T) { } func TestValidateSeedArrayValidValue(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Item"}, - Entities: map[string]*parser.ParsedEntity{ - "Item": { - Name: "Item", - FieldOrder: []string{"id", "tags"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "array(string)"), - }, - Seed: []map[string]interface{}{ - {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": []interface{}{"a", "b"}}, - }, - }, - }, + t.Parallel() + schema := schemaWithFields(t, "Item", + "id", "uuid [primary]", + "tags", "array(string)", + ) + schema.Entities["Item"].Seed = []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": []any{"a", "b"}}, } schema.Entities["Item"].Fields["id"].IsPrimary = true @@ -1998,26 +1580,17 @@ func TestValidateSeedArrayValidValue(t *testing.T) { } func TestValidateStringMinMaxNonNumeric(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"User"}, - Entities: map[string]*parser.ParsedEntity{ - "User": { - Name: "User", - FieldOrder: []string{"id", "name"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [max:abc]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "User", + "id", "uuid [primary]", + "name", "string [max:abc]", + ) schema.Entities["User"].Fields["id"].IsPrimary = true errs := New(schema).Validate() found := false for _, e := range errs { - if strings.Contains(e.Message, "'max' value \"abc\" is not a valid number") { + if !e.Warning && strings.Contains(e.Message, "'max' value \"abc\" must be an integer") { found = true } } @@ -2027,6 +1600,7 @@ func TestValidateStringMinMaxNonNumeric(t *testing.T) { } func TestValidateCircularRelationWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User", "Team"}, @@ -2035,16 +1609,16 @@ func TestValidateCircularRelationWarning(t *testing.T) { Name: "User", FieldOrder: []string{"id", "team"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "team": mustParsedField(t, "team", "relation(Team)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "team": testutil.MustParsedField(t, "team", "relation(Team)"), }, }, "Team": { Name: "Team", FieldOrder: []string{"id", "lead"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "lead": mustParsedField(t, "lead", "relation(User)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "lead": testutil.MustParsedField(t, "lead", "relation(User)"), }, }, }, @@ -2065,6 +1639,7 @@ func TestValidateCircularRelationWarning(t *testing.T) { } func TestValidateNoCircularRelationWarningForAcyclic(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User", "Team"}, @@ -2073,15 +1648,15 @@ func TestValidateNoCircularRelationWarningForAcyclic(t *testing.T) { Name: "User", FieldOrder: []string{"id", "team"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "team": mustParsedField(t, "team", "relation(Team)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "team": testutil.MustParsedField(t, "team", "relation(Team)"), }, }, "Team": { Name: "Team", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -2098,20 +1673,11 @@ func TestValidateNoCircularRelationWarningForAcyclic(t *testing.T) { } func TestValidateNoCircularRelationWarningForSelfReference(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Category"}, - Entities: map[string]*parser.ParsedEntity{ - "Category": { - Name: "Category", - FieldOrder: []string{"id", "parentId"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "parentId": mustParsedField(t, "parentId", "relation(Category) [optional]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Category", + "id", "uuid [primary]", + "parentId", "relation(Category) [optional]", + ) schema.Entities["Category"].Fields["id"].IsPrimary = true errs := New(schema).Validate() @@ -2123,6 +1689,7 @@ func TestValidateNoCircularRelationWarningForSelfReference(t *testing.T) { } func TestValidateNoCircularRelationWarningForManyToMany(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Order", "OrderItem"}, @@ -2131,16 +1698,16 @@ func TestValidateNoCircularRelationWarningForManyToMany(t *testing.T) { Name: "Order", FieldOrder: []string{"id", "items"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "items": mustParsedField(t, "items", "relation(OrderItem) [many]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "items": testutil.MustParsedField(t, "items", "relation(OrderItem) [many]"), }, }, "OrderItem": { Name: "OrderItem", FieldOrder: []string{"id", "orderId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "orderId": mustParsedField(t, "orderId", "relation(Order)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "orderId": testutil.MustParsedField(t, "orderId", "relation(Order)"), }, }, }, @@ -2157,60 +1724,42 @@ func TestValidateNoCircularRelationWarningForManyToMany(t *testing.T) { } func TestValidateDefaultDateInvalid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Event"}, - Entities: map[string]*parser.ParsedEntity{ - "Event": { - Name: "Event", - FieldOrder: []string{"id", "started_on"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "started_on": mustParsedField(t, "started_on", "date [default:not-a-date]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Event", + "id", "uuid [primary]", + "started_on", "date [default:not-a-date]", + ) schema.Entities["Event"].Fields["id"].IsPrimary = true errs := New(schema).Validate() found := false for _, e := range errs { - if e.Warning && strings.Contains(e.Message, "not a valid date") { + if !e.Warning && strings.Contains(e.Message, "not a valid date") { found = true } } if !found { - t.Fatalf("expected warning about invalid date default, got %v", errs) + t.Fatalf("expected error about invalid date default, got %v", errs) } } func TestValidateDefaultUuidInvalid(t *testing.T) { - schema := &parser.ParsedSchema{ - Project: parser.ProjectConfig{Name: "Test"}, - EntityOrder: []string{"Doc"}, - Entities: map[string]*parser.ParsedEntity{ - "Doc": { - Name: "Doc", - FieldOrder: []string{"id", "external_id"}, - Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "external_id": mustParsedField(t, "external_id", "uuid [default:not-a-uuid]"), - }, - }, - }, - } + t.Parallel() + schema := schemaWithFields(t, "Doc", + "id", "uuid [primary]", + "external_id", "uuid [default:not-a-uuid]", + ) schema.Entities["Doc"].Fields["id"].IsPrimary = true errs := New(schema).Validate() found := false for _, e := range errs { - if e.Warning && strings.Contains(e.Message, "not a valid UUID") { + if !e.Warning && strings.Contains(e.Message, "not a valid UUID") { found = true } } if !found { - t.Fatalf("expected warning about invalid uuid default, got %v", errs) + t.Fatalf("expected error about invalid uuid default, got %v", errs) } } @@ -2219,6 +1768,7 @@ func TestValidateDefaultUuidInvalid(t *testing.T) { // spurious "collides with field ''" error. Self-collisions are silently // ignored; only genuine collisions between two different fields are reported. func TestValidateColumnSelfCollisionGuard(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -2227,8 +1777,8 @@ func TestValidateColumnSelfCollisionGuard(t *testing.T) { Name: "User", FieldOrder: []string{"id", "isSystemTag", "isSystemTag"}, // duplicate entry Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "isSystemTag": mustParsedField(t, "isSystemTag", "boolean [default:false]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "isSystemTag": testutil.MustParsedField(t, "isSystemTag", "boolean [default:false]"), }, }, }, @@ -2241,3 +1791,507 @@ func TestValidateColumnSelfCollisionGuard(t *testing.T) { } } } + +func TestValidateRejectsRelationPrimaryKey(t *testing.T) { + t.Parallel() + tests := []struct { + name string + pkDef string + wantErr bool + }{ + {name: "relation primary key", pkDef: "relation(Parent) [primary]", wantErr: true}, + {name: "scalar primary key", pkDef: "uuid [primary]"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schema := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Child", "Parent"}, + Entities: map[string]*parser.ParsedEntity{ + "Child": { + Name: "Child", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", tt.pkDef), + }, + }, + "Parent": { + Name: "Parent", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }, + }, + }, + } + + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "primary key cannot be a relation field") { + found = true + } + } + if found != tt.wantErr { + t.Fatalf("relation primary key error = %v, want %v; errors: %v", found, tt.wantErr, errs) + } + }) + } +} + +func TestValidateRejectsNonPositiveStringBounds(t *testing.T) { + t.Parallel() + tests := []struct { + name string + def string + wantErr bool + }{ + {name: "zero max", def: "string [max:0]", wantErr: true}, + {name: "negative max", def: "string [max:-1]", wantErr: true}, + {name: "zero min", def: "string [min:0]", wantErr: true}, + {name: "negative min", def: "string [min:-5]", wantErr: true}, + {name: "valid bounds", def: "string [min:3, max:255]"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schema := schemaWithFields(t, "Doc", + "id", "uuid [primary]", + "name", tt.def, + ) + + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "must be positive for string length") { + found = true + } + } + if found != tt.wantErr { + t.Fatalf("positive bound error = %v, want %v; errors: %v", found, tt.wantErr, errs) + } + }) + } +} + +func TestValidateRejectsEnumWireValueCollision(t *testing.T) { + t.Parallel() + tests := []struct { + name string + values []string + }{ + {name: "case-only collision", values: []string{"DRAFT", "draft"}}, + {name: "camel case collision", values: []string{"InProgress", "in_progress"}}, + {name: "acronym collision", values: []string{"HTTPPort", "http_port"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schema := schemaWithFields(t, "Doc", + "id", "uuid [primary]", + "status", "enum(Status)", + ) + schema.Enums = map[string][]string{"Status": tt.values} + + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "map to the same wire value") { + found = true + } + } + if !found { + t.Fatalf("expected a hard error for wire-value collision, got %v", errs) + } + }) + } +} + +func TestValidateRejectsUnparseableNumericSeed(t *testing.T) { + t.Parallel() + tests := []struct { + name string + field string + value any + wantErr bool + }{ + {name: "int string", field: "count", value: "7"}, + {name: "int unparseable string", field: "count", value: "abc", wantErr: true}, + {name: "bigint unparseable string", field: "big", value: "12x", wantErr: true}, + {name: "decimal string", field: "price", value: "2.5"}, + {name: "decimal unparseable string", field: "price", value: "nope", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schema := schemaWithFields(t, "Doc", + "id", "uuid [primary]", + "count", "int", + "big", "bigint", + "price", "decimal", + ) + schema.Entities["Doc"].Seed = []map[string]any{{"id": "550e8400-e29b-41d4-a716-446655440000", tt.field: tt.value}} + + errs := nonWarnings(New(schema).Validate()) + found := false + for _, e := range errs { + if e.Field == tt.field && strings.Contains(e.Message, "seed entry 0") { + found = true + } + } + if found != tt.wantErr { + t.Fatalf("seed parse error = %v, want %v; errors: %v", found, tt.wantErr, errs) + } + }) + } +} + +func TestValidateSortsErrorsByMessageTiebreaker(t *testing.T) { + t.Parallel() + schema := schemaWithFields(t, "Doc", + "id", "uuid [primary]", + "status", "enum(Status)", + ) + schema.Enums = map[string][]string{"Status": {"A", "a", ""}} + + errs := nonWarnings(New(schema).Validate()) + if len(errs) < 2 { + t.Fatalf("got %d errors, want at least 2: %v", len(errs), errs) + } + for i := 1; i < len(errs); i++ { + if errs[i-1].Entity != "" || errs[i].Entity != "" { + continue + } + if errs[i-1].Field != "Status" || errs[i].Field != "Status" { + continue + } + if errs[i-1].Message > errs[i].Message { + t.Fatalf("enum errors are not sorted by message: %q before %q", errs[i-1].Message, errs[i].Message) + } + } + if !strings.Contains(errs[0].Message, "enum value must not be empty") { + t.Fatalf("first error = %q, want the empty-value error", errs[0].Message) + } +} + +// schemaWithFields builds a minimal one-entity schema from "name", "type +// [modifiers]" pairs. It mirrors the parser's field order and marks the id +// field primary (or the first field when there is no id) unless a definition +// already declares a primary key. +func schemaWithFields(t *testing.T, entityName string, defs ...string) *parser.ParsedSchema { + t.Helper() + fields := make(map[string]*parser.ParsedField, len(defs)/2) + order := make([]string, 0, len(defs)/2) + hasPrimary := false + for i := 0; i+1 < len(defs); i += 2 { + name, def := defs[i], defs[i+1] + field := testutil.MustParsedField(t, name, def) + fields[name] = field + order = append(order, name) + hasPrimary = hasPrimary || field.IsPrimary + } + if !hasPrimary && len(order) > 0 { + pk := order[0] + if _, ok := fields["id"]; ok { + pk = "id" + } + fields[pk].IsPrimary = true + } + return &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{entityName}, + Entities: map[string]*parser.ParsedEntity{ + entityName: { + Name: entityName, + FieldOrder: order, + Fields: fields, + }, + }, + } +} + +// schemaWithSeedValue builds a minimal valid schema with one integral field +// carrying a single seed value. +func schemaWithSeedValue(t *testing.T, fieldType string, value any) *parser.ParsedSchema { + t.Helper() + return &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Doc"}, + Entities: map[string]*parser.ParsedEntity{ + "Doc": { + Name: "Doc", + FieldOrder: []string{"id", "count"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "count": testutil.MustParsedField(t, "count", fieldType), + }, + Seed: []map[string]any{{"id": "550e8400-e29b-41d4-a716-446655440000", "count": value}}, + }, + }, + } +} + +func TestValidateRejectsFractionalSeedForIntegralField(t *testing.T) { + t.Parallel() + tests := []struct { + name string + fieldType string + value any + }{ + {name: "float64 1.9 for int", fieldType: "int", value: float64(1.9)}, + {name: "float32 1.9 for int", fieldType: "int", value: float32(1.9)}, + {name: "float64 2.5 for bigint", fieldType: "bigint", value: float64(2.5)}, + {name: "negative float32 for bigint", fieldType: "bigint", value: float32(-2.5)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + errs := nonWarnings(New(schemaWithSeedValue(t, tt.fieldType, tt.value)).Validate()) + found := false + for _, e := range errs { + if e.Field == "count" && strings.Contains(e.Message, "seed entry 0") && + strings.Contains(e.Message, "not compatible with type "+tt.fieldType) { + found = true + } + } + if !found { + t.Fatalf("expected fractional seed error, got %v", errs) + } + }) + } +} + +func TestValidateAcceptsIntegralValuedFloatSeed(t *testing.T) { + t.Parallel() + tests := []struct { + name string + fieldType string + value any + }{ + {name: "float64 1.0 for int", fieldType: "int", value: float64(1.0)}, + {name: "float32 1.0 for int", fieldType: "int", value: float32(1.0)}, + {name: "float64 3.0 for bigint", fieldType: "bigint", value: float64(3.0)}, + {name: "float32 3.0 for bigint", fieldType: "bigint", value: float32(3.0)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + errs := nonWarnings(New(schemaWithSeedValue(t, tt.fieldType, tt.value)).Validate()) + if len(errs) != 0 { + t.Fatalf("expected integral-valued float seed to be accepted, got %v", errs) + } + }) + } +} + +// schemaWithEntityOldName builds a minimal valid schema with an entity rename hint. +func schemaWithEntityOldName(t *testing.T, entityName, oldName string) *parser.ParsedSchema { + t.Helper() + return &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{entityName}, + Entities: map[string]*parser.ParsedEntity{ + entityName: { + Name: entityName, + OldName: oldName, + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }, + }, + }, + } +} + +func TestValidateRejectsInvalidEntityOldName(t *testing.T) { + t.Parallel() + for _, oldName := range []string{"bad-name", "has space", "123abc", "Product.Id"} { + t.Run(oldName, func(t *testing.T) { + t.Parallel() + errs := nonWarnings(New(schemaWithEntityOldName(t, "Item", oldName)).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "old_name is not a valid identifier") { + found = true + } + } + if !found { + t.Fatalf("expected invalid entity old_name error for %q, got %v", oldName, errs) + } + }) + } +} + +func TestValidateRejectsSelfReferentialEntityOldName(t *testing.T) { + t.Parallel() + errs := nonWarnings(New(schemaWithEntityOldName(t, "Product", "Product")).Validate()) + found := false + for _, e := range errs { + if strings.Contains(e.Message, "old_name cannot equal the entity name") { + found = true + } + } + if !found { + t.Fatalf("expected self-referential entity old_name error, got %v", errs) + } +} + +func TestValidateAcceptsValidEntityOldName(t *testing.T) { + t.Parallel() + errs := nonWarnings(New(schemaWithEntityOldName(t, "Item", "Product")).Validate()) + if len(errs) != 0 { + t.Fatalf("expected a valid entity old_name to be accepted, got %v", errs) + } +} + +// schemaWithProjectConfig builds a schema with one valid entity so only the +// supplied project-level settings can produce diagnostics. +func schemaWithProjectConfig(t *testing.T, project parser.ProjectConfig) *parser.ParsedSchema { + t.Helper() + project.Name = "Test" + return &parser.ParsedSchema{ + Project: project, + EntityOrder: []string{"User"}, + Entities: map[string]*parser.ParsedEntity{ + "User": { + Name: "User", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + }, + }, + }, + } +} + +// TestValidateAcceptsExplicitZeroProjectNumericValues pins that an explicit 0 +// (which the parser now preserves) is a valid value rather than "unset". +func TestValidateAcceptsExplicitZeroProjectNumericValues(t *testing.T) { + t.Parallel() + tests := []struct { + name string + project parser.ProjectConfig + }{ + {"port", parser.ProjectConfig{Deploy: &parser.DeployConfig{Port: 0}}}, + {"permit limit", parser.ProjectConfig{RateLimit: &parser.RateLimitConfig{PermitLimit: 0}}}, + {"window seconds", parser.ProjectConfig{RateLimit: &parser.RateLimitConfig{WindowSeconds: 0}}}, + {"default page size", parser.ProjectConfig{Pagination: &parser.PaginationConfig{DefaultPageSize: 0}}}, + {"max page size", parser.ProjectConfig{Pagination: &parser.PaginationConfig{MaxPageSize: 0}}}, + {"all zeros", parser.ProjectConfig{ + Deploy: &parser.DeployConfig{Port: 0}, + RateLimit: &parser.RateLimitConfig{PermitLimit: 0, WindowSeconds: 0}, + Pagination: &parser.PaginationConfig{DefaultPageSize: 0, MaxPageSize: 0}, + }}, + {"zero default with capped max", parser.ProjectConfig{ + Pagination: &parser.PaginationConfig{DefaultPageSize: 0, MaxPageSize: 200}, + }}, + {"positive default with uncapped max", parser.ProjectConfig{ + Pagination: &parser.PaginationConfig{DefaultPageSize: 20, MaxPageSize: 0}, + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + errs := New(schemaWithProjectConfig(t, tt.project)).Validate() + if len(errs) != 0 { + t.Fatalf("expected no diagnostics for explicit zero, got %v", errs) + } + }) + } +} + +// TestValidateRejectsNegativeProjectNumericValues pins that accepting zero did +// not loosen the existing negative and positive-range checks. +func TestValidateRejectsNegativeProjectNumericValues(t *testing.T) { + t.Parallel() + tests := []struct { + name string + project parser.ProjectConfig + wantText string + wantWarn bool + }{ + {"negative port", parser.ProjectConfig{Deploy: &parser.DeployConfig{Port: -1}}, "deploy.port", false}, + {"port above max", parser.ProjectConfig{Deploy: &parser.DeployConfig{Port: 65536}}, "deploy.port", false}, + {"negative permit limit", parser.ProjectConfig{RateLimit: &parser.RateLimitConfig{PermitLimit: -1}}, "rate_limit.permit_limit must be non-negative", true}, + {"negative window seconds", parser.ProjectConfig{RateLimit: &parser.RateLimitConfig{WindowSeconds: -1}}, "rate_limit.window_seconds must be non-negative", true}, + {"negative default page size", parser.ProjectConfig{Pagination: &parser.PaginationConfig{DefaultPageSize: -1}}, "pagination.default_page_size must be non-negative", true}, + {"negative max page size", parser.ProjectConfig{Pagination: &parser.PaginationConfig{MaxPageSize: -1}}, "pagination.max_page_size must be non-negative", true}, + {"default above max", parser.ProjectConfig{Pagination: &parser.PaginationConfig{DefaultPageSize: 201, MaxPageSize: 200}}, "must not exceed max_page_size", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + errs := New(schemaWithProjectConfig(t, tt.project)).Validate() + found := false + for _, e := range errs { + if strings.Contains(e.Message, tt.wantText) && e.Warning == tt.wantWarn { + found = true + } + } + if !found { + t.Fatalf("expected diagnostic %q (warning=%t), got %v", tt.wantText, tt.wantWarn, errs) + } + }) + } +} + +func TestValidateRejectsInvalidNumericDefault(t *testing.T) { + t.Parallel() + cases := []struct { + name string + ftype string + defaultVal string + wantError bool + }{ + {name: "int rejects text", ftype: specmeta.FieldTypeInt, defaultVal: "abc", wantError: true}, + {name: "int accepts integer", ftype: specmeta.FieldTypeInt, defaultVal: "42"}, + {name: "bigint rejects text", ftype: specmeta.FieldTypeBigint, defaultVal: "twelve", wantError: true}, + {name: "bigint accepts integer", ftype: specmeta.FieldTypeBigint, defaultVal: "-9000000000"}, + {name: "float rejects text", ftype: specmeta.FieldTypeFloat, defaultVal: "1.2.3", wantError: true}, + {name: "float accepts decimal", ftype: specmeta.FieldTypeFloat, defaultVal: "1.25"}, + {name: "decimal rejects text", ftype: specmeta.FieldTypeDecimal, defaultVal: "price", wantError: true}, + {name: "decimal accepts decimal", ftype: specmeta.FieldTypeDecimal, defaultVal: "99.95"}, + {name: "legacy true still fails on int", ftype: specmeta.FieldTypeInt, defaultVal: "true", wantError: true}, + {name: "legacy false still fails on bigint", ftype: specmeta.FieldTypeBigint, defaultVal: "false", wantError: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + errs := validateDefaultValue("Item", "amount", c.ftype, false, c.defaultVal) + if c.wantError { + if len(errs) != 1 || errs[0].Warning { + t.Fatalf("validateDefaultValue(%q, %q) = %v, want one error", c.ftype, c.defaultVal, errs) + } + msg := errs[0].Message + if msg != strings.ToLower(msg) || strings.HasSuffix(msg, ".") { + t.Errorf("error message %q is not lowercase or ends with punctuation", msg) + } + return + } + if len(errs) != 0 { + t.Fatalf("validateDefaultValue(%q, %q) = %v, want no errors", c.ftype, c.defaultVal, errs) + } + }) + } + + // The element type of an array drives the same numeric check. + v := New(&parser.ParsedSchema{}) + for _, c := range []struct { + name string + def string + want int + }{ + {name: "array int accepts numbers", def: "array(int) [default:[1, 2]]", want: 0}, + {name: "array int rejects text", def: "array(int) [default:[1, abc]]", want: 1}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + field := testutil.MustParsedField(t, "scores", c.def) + errs := v.validateFieldDefault("Item", "scores", field) + if len(errs) != c.want { + t.Fatalf("validateFieldDefault(%q) = %v, want %d errors", c.def, errs, c.want) + } + }) + } +} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 0579f5b..61ef1b2 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -1,82 +1,109 @@ +// Package logger provides the CLI's four-level console logger. package logger import ( "fmt" "io" "os" + "sync" + + "golang.org/x/term" ) // Logger is a simple CLI logger with colored output for key stages, warnings, and errors. type Logger struct { writer io.Writer useColors bool + mu sync.Mutex } -// New creates a Logger that writes to stdout with colors enabled. +// New creates a Logger that writes to stderr. Colors are enabled only when +// stderr is a real terminal and NO_COLOR is unset or empty, so redirected +// diagnostics stay free of ANSI escapes. Diagnostics must never share stdout +// with machine-readable command output. func New() *Logger { - return &Logger{ - writer: os.Stdout, - useColors: true, + return NewWithWriter(os.Stderr) +} + +// NewWithWriter creates a Logger for an explicit destination. Colors are +// decided from that writer, not from the process' stderr: a buffer or a pipe +// must never inherit terminal coloring just because the process was started in +// a terminal. Non-*os.File writers are treated as non-terminals. +func NewWithWriter(w io.Writer) *Logger { + if w == nil { + w = os.Stderr + } + colors := false + if f, ok := w.(*os.File); ok { + colors = term.IsTerminal(int(f.Fd())) && os.Getenv("NO_COLOR") == "" } + return &Logger{writer: w, useColors: colors} +} + +// SetColors enables or disables ANSI colors for subsequent log calls. +func (l *Logger) SetColors(enabled bool) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + l.useColors = enabled } // SetWriter overrides the output destination (useful for testing). func (l *Logger) SetWriter(w io.Writer) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() l.writer = w } +// write emits one line while holding the lock, so concurrent calls cannot +// interleave their bytes. The level glyph and its color are fixed per level. +func (l *Logger) write(glyph, color, msg string) { + l.mu.Lock() + defer l.mu.Unlock() + if l.useColors { + _, _ = fmt.Fprintf(l.writer, " \033[%sm%s\033[0m %s\n", color, glyph, msg) + } else { + _, _ = fmt.Fprintf(l.writer, " %s %s\n", glyph, msg) + } +} + // Info logs a key stage message (e.g. "Validating schema..."). // Safe to call on a nil Logger (no-op), so renderers can accept an optional logger. -func (l *Logger) Info(format string, args ...interface{}) { +func (l *Logger) Info(format string, args ...any) { if l == nil { return } - msg := fmt.Sprintf(format, args...) - if l.useColors { - fmt.Fprintf(l.writer, " \033[36m▸\033[0m %s\n", msg) - } else { - fmt.Fprintf(l.writer, " ▸ %s\n", msg) - } + l.write("▸", "36", fmt.Sprintf(format, args...)) } // Success logs a completed stage (e.g. "✓ Generated 12 files"). // Safe to call on a nil Logger (no-op). -func (l *Logger) Success(format string, args ...interface{}) { +func (l *Logger) Success(format string, args ...any) { if l == nil { return } - msg := fmt.Sprintf(format, args...) - if l.useColors { - fmt.Fprintf(l.writer, " \033[32m✓\033[0m %s\n", msg) - } else { - fmt.Fprintf(l.writer, " ✓ %s\n", msg) - } + l.write("✓", "32", fmt.Sprintf(format, args...)) } // Warn logs a non-fatal warning. // Safe to call on a nil Logger (no-op). -func (l *Logger) Warn(format string, args ...interface{}) { +func (l *Logger) Warn(format string, args ...any) { if l == nil { return } - msg := fmt.Sprintf(format, args...) - if l.useColors { - fmt.Fprintf(l.writer, " \033[33m⚠\033[0m %s\n", msg) - } else { - fmt.Fprintf(l.writer, " ⚠ %s\n", msg) - } + l.write("⚠", "33", fmt.Sprintf(format, args...)) } // Error logs an error message (does not exit). // Safe to call on a nil Logger (no-op). -func (l *Logger) Error(format string, args ...interface{}) { +func (l *Logger) Error(format string, args ...any) { if l == nil { return } - msg := fmt.Sprintf(format, args...) - if l.useColors { - fmt.Fprintf(l.writer, " \033[31m✗\033[0m %s\n", msg) - } else { - fmt.Fprintf(l.writer, " ✗ %s\n", msg) - } + l.write("✗", "31", fmt.Sprintf(format, args...)) } diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go new file mode 100644 index 0000000..ca9e206 --- /dev/null +++ b/pkg/logger/logger_test.go @@ -0,0 +1,56 @@ +package logger + +import ( + "bytes" + "os" + "strings" + "testing" +) + +func TestNewWritesDiagnosticsToStderr(t *testing.T) { + if got := New().writer; got != os.Stderr { + t.Errorf("default writer = %v, want os.Stderr", got) + } +} + +// Colors are decided from the destination, not from the process stderr: +// redirecting cmd.ErrOrStderr() to a buffer must never inject ANSI escapes +// just because the test process was started in a terminal. +func TestNewWithWriterNeverColorsBuffers(t *testing.T) { + var buf bytes.Buffer + log := NewWithWriter(&buf) + log.Info("plain") + if bytes.Contains(buf.Bytes(), []byte{0x1B}) { + t.Errorf("buffer received ANSI escapes: %q", buf.String()) + } +} + +func TestLoggerOmitsANSIWhenNotTTY(t *testing.T) { + // No t.Parallel: New() probes the process stderr and NO_COLOR, both global. + var buf bytes.Buffer + log := New() + log.SetWriter(&buf) + log.SetColors(false) + + log.Info("info %d", 1) + log.Success("success %d", 2) + log.Warn("warn %d", 3) + log.Error("error %d", 4) + + out := buf.String() + if bytes.Contains(buf.Bytes(), []byte{0x1B}) { + t.Errorf("output = %q, want no ANSI escape bytes", out) + } + for _, want := range []string{"info 1", "success 2", "warn 3", "error 4"} { + if !strings.Contains(out, want) { + t.Errorf("output = %q, want it to contain %q", out, want) + } + } + + buf.Reset() + log.SetColors(true) + log.Info("colored") + if !bytes.Contains(buf.Bytes(), []byte{0x1B}) { + t.Errorf("output = %q, want an ANSI escape after SetColors(true)", buf.String()) + } +} diff --git a/pkg/textutil/case_convert_test.go b/pkg/textutil/case_convert_test.go index ebbd59f..d85a351 100644 --- a/pkg/textutil/case_convert_test.go +++ b/pkg/textutil/case_convert_test.go @@ -3,58 +3,74 @@ package textutil import "testing" func TestSnakeCase(t *testing.T) { - cases := []struct{ in, want string }{ - {"", ""}, - {"FirstName", "first_name"}, - {"firstName", "first_name"}, - {"HTTPServer", "http_server"}, - {"HTTPStatus", "http_status"}, - {"XMLHttpRequest", "xml_http_request"}, - {"userID", "user_id"}, - {"ALLCAPS", "allcaps"}, - {"ID", "id"}, + t.Parallel() + cases := []struct { + name string + in string + want string + }{ + {"empty", "", ""}, + {"pascal_case", "FirstName", "first_name"}, + {"camel_case", "firstName", "first_name"}, + {"acronym_http_server", "HTTPServer", "http_server"}, + {"acronym_http_status", "HTTPStatus", "http_status"}, + {"acronym_xml_http_request", "XMLHttpRequest", "xml_http_request"}, + {"camel_user_id", "userID", "user_id"}, + {"all_caps", "ALLCAPS", "allcaps"}, + {"acronym_id", "ID", "id"}, // Digit groups: a number attached to the previous word stays with it, // trailing uppercase starts a new word. - {"HTTP20xOK", "http_20x_ok"}, - {"Bld4Floor", "bld4_floor"}, - {"ProductV2", "product_v2"}, - {"V2Product", "v2_product"}, - {"H2O", "h2_o"}, + {"digits_with_acronym", "HTTP20xOK", "http_20x_ok"}, + {"digit_group_bld4", "Bld4Floor", "bld4_floor"}, + {"trailing_digits", "ProductV2", "product_v2"}, + {"leading_digits", "V2Product", "v2_product"}, + {"h2o", "H2O", "h2_o"}, // Documented divergence from ToDatabaseColumnName on acronym+digit runs: // SnakeCase splits "I"+"pv4", DB columns keep "IPv4Address" together. - {"IPv4Address", "i_pv4_address"}, + {"ipv4_acronym_digit", "IPv4Address", "i_pv4_address"}, // Separators normalize to the connector rune. - {"user_id", "user_id"}, - {"kebab-case-name", "kebab_case_name"}, - {"already snake_case", "already_snake_case"}, - {"__leading", "__leading"}, - {"double__under", "double__under"}, + {"snake_case_input", "user_id", "user_id"}, + {"kebab_case_input", "kebab-case-name", "kebab_case_name"}, + {"spaced_input", "already snake_case", "already_snake_case"}, + {"leading_underscores", "__leading", "__leading"}, + {"double_underscore", "double__under", "double__under"}, // Unicode and CJK non-word characters. - {"CJK汉字Test", "cjk_汉字_test"}, + {"unicode_cjk", "CJK汉字Test", "cjk_汉字_test"}, } for _, c := range cases { - if got := SnakeCase(c.in); got != c.want { - t.Errorf("SnakeCase(%q) = %q, want %q", c.in, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := SnakeCase(c.in); got != c.want { + t.Errorf("SnakeCase(%q) = %q, want %q", c.in, got, c.want) + } + }) } } func TestKebabCase(t *testing.T) { - cases := []struct{ in, want string }{ - {"", ""}, - {"FirstName", "first-name"}, - {"HTTPServer", "http-server"}, - {"HTTP20xOK", "http-20x-ok"}, - {"Bld4Floor", "bld4-floor"}, - {"IPv4Address", "i-pv4-address"}, - {"user_id", "user-id"}, - {"already snake_case", "already-snake-case"}, - {"__leading", "--leading"}, + t.Parallel() + cases := []struct { + name string + in string + want string + }{ + {"empty", "", ""}, + {"pascal_case", "FirstName", "first-name"}, + {"acronym", "HTTPServer", "http-server"}, + {"digits_with_acronym", "HTTP20xOK", "http-20x-ok"}, + {"digit_group_bld4", "Bld4Floor", "bld4-floor"}, + {"ipv4_acronym_digit", "IPv4Address", "i-pv4-address"}, + {"snake_case_input", "user_id", "user-id"}, + {"spaced_input", "already snake_case", "already-snake-case"}, + {"leading_underscores", "__leading", "--leading"}, } for _, c := range cases { - if got := KebabCase(c.in); got != c.want { - t.Errorf("KebabCase(%q) = %q, want %q", c.in, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := KebabCase(c.in); got != c.want { + t.Errorf("KebabCase(%q) = %q, want %q", c.in, got, c.want) + } + }) } } @@ -62,30 +78,38 @@ func TestKebabCase(t *testing.T) { // template `snakecase` (which diverges on acronym+digit runs, e.g. // "IPv4Address" -> "i_pv4_address") never silently replaces it. func TestToDatabaseColumnName(t *testing.T) { - cases := []struct{ in, want string }{ - {"", ""}, - {"firstName", "first_name"}, - {"FirstName", "first_name"}, - {"HTTPPort", "http_port"}, - {"userID", "user_id"}, - {"user_id", "user_id"}, - {"kebab-case", "kebab_case"}, - {"spaced name", "spaced_name"}, - {"ALLCAPS", "allcaps"}, - {"ProductV2", "product_v2"}, - {"myURLParser", "my_url_parser"}, + t.Parallel() + cases := []struct { + name string + in string + want string + }{ + {"empty", "", ""}, + {"camel_case", "firstName", "first_name"}, + {"pascal_case", "FirstName", "first_name"}, + {"acronym_http_port", "HTTPPort", "http_port"}, + {"camel_user_id", "userID", "user_id"}, + {"snake_case_input", "user_id", "user_id"}, + {"kebab_case_input", "kebab-case", "kebab_case"}, + {"spaced_input", "spaced name", "spaced_name"}, + {"all_caps", "ALLCAPS", "allcaps"}, + {"product_v2", "ProductV2", "product_v2"}, + {"url_parser", "myURLParser", "my_url_parser"}, // Acronym+digit run stays glued ("i_pv4address") — see CLAUDE.md; // this is why bridges must print DatabaseColumnName instead of // re-deriving it with `snakecase`. - {"IPv4Address", "i_pv4address"}, + {"ipv4_acronym_digit", "IPv4Address", "i_pv4address"}, // Empty parts from leading/trailing separators are dropped. - {"__leading", "leading"}, - {"trailing_", "trailing"}, - {"double__under", "double_under"}, + {"leading_underscores", "__leading", "leading"}, + {"trailing_underscore", "trailing_", "trailing"}, + {"double_underscore", "double__under", "double_under"}, } for _, c := range cases { - if got := ToDatabaseColumnName(c.in); got != c.want { - t.Errorf("ToDatabaseColumnName(%q) = %q, want %q", c.in, got, c.want) - } + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := ToDatabaseColumnName(c.in); got != c.want { + t.Errorf("ToDatabaseColumnName(%q) = %q, want %q", c.in, got, c.want) + } + }) } } diff --git a/pkg/textutil/textutil.go b/pkg/textutil/textutil.go index 8bb6502..a83169c 100644 --- a/pkg/textutil/textutil.go +++ b/pkg/textutil/textutil.go @@ -5,6 +5,7 @@ package textutil import ( "strings" "unicode" + "unicode/utf8" ) // Pluralize converts a singular noun to its plural form. @@ -65,7 +66,10 @@ func PascalCase(value string) string { if parts[i] == "" { continue } - parts[i] = strings.ToUpper(parts[i][:1]) + strings.ToLower(parts[i][1:]) + // The first character may be multi-byte; slicing by byte would split a + // UTF-8 sequence and produce an invalid identifier. + first, size := utf8.DecodeRuneInString(parts[i]) + parts[i] = string(unicode.ToUpper(first)) + strings.ToLower(parts[i][size:]) } return strings.Join(parts, "") } @@ -76,7 +80,8 @@ func CamelCase(value string) string { if value == "" { return "" } - return strings.ToLower(value[:1]) + value[1:] + first, size := utf8.DecodeRuneInString(value) + return string(unicode.ToLower(first)) + value[size:] } // FKName appends the foreign-key "Id" suffix to a relation field name unless it diff --git a/pkg/textutil/textutil_test.go b/pkg/textutil/textutil_test.go index 3c72108..82a3a5d 100644 --- a/pkg/textutil/textutil_test.go +++ b/pkg/textutil/textutil_test.go @@ -1,131 +1,196 @@ package textutil -import "testing" +import ( + "testing" + "unicode/utf8" +) func TestPluralize(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want string }{ - {"User", "Users"}, - {"Category", "Categories"}, - {"Status", "Statuses"}, - {"Box", "Boxes"}, - {"Lady", "Ladies"}, - {"Piano", "Pianoes"}, - {"Tax", "Taxes"}, - {"Quiz", "Quizzes"}, - {"Hero", "Heroes"}, - {"Day", "Days"}, // y after vowel -> -s - {"Key", "Keys"}, // y after vowel -> -s - {"Dish", "Dishes"}, // -sh -> -es + {"user", "User", "Users"}, + {"category", "Category", "Categories"}, + {"status", "Status", "Statuses"}, + {"box", "Box", "Boxes"}, + {"lady", "Lady", "Ladies"}, + {"piano", "Piano", "Pianoes"}, + {"tax", "Tax", "Taxes"}, + {"quiz", "Quiz", "Quizzes"}, + {"hero", "Hero", "Heroes"}, + {"day_vowel_y", "Day", "Days"}, // y after vowel -> -s + {"key_vowel_y", "Key", "Keys"}, // y after vowel -> -s + {"dish_sibilant", "Dish", "Dishes"}, // -sh -> -es } for _, tt := range tests { - got := Pluralize(tt.input) - if got != tt.want { - t.Errorf("Pluralize(%q) = %q, want %q", tt.input, got, tt.want) - } + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := Pluralize(tt.input) + if got != tt.want { + t.Errorf("Pluralize(%q) = %q, want %q", tt.input, got, tt.want) + } + }) } } func TestSingularize(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want string }{ - {"Users", "User"}, - {"Categories", "Category"}, - {"Statuses", "Status"}, - {"Boxes", "Box"}, - {"Quizzes", "Quiz"}, - {"Statuses", "Status"}, - {"Tags", "Tag"}, - {"User", "User"}, // no change + {"users", "Users", "User"}, + {"categories", "Categories", "Category"}, + {"statuses", "Statuses", "Status"}, + {"boxes", "Boxes", "Box"}, + {"quizzes", "Quizzes", "Quiz"}, + {"statuses_again", "Statuses", "Status"}, + {"tags", "Tags", "Tag"}, + {"already_singular", "User", "User"}, // no change } for _, tt := range tests { - got := Singularize(tt.input) - if got != tt.want { - t.Errorf("Singularize(%q) = %q, want %q", tt.input, got, tt.want) - } + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := Singularize(tt.input) + if got != tt.want { + t.Errorf("Singularize(%q) = %q, want %q", tt.input, got, tt.want) + } + }) } } func TestFKName(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want string }{ - {"order", "orderId"}, - {"orderId", "orderId"}, - {"orderid", "orderid"}, - {"ipv4Address", "ipv4AddressId"}, + {"plain", "order", "orderId"}, + {"already_suffixed", "orderId", "orderId"}, + {"lowercase_id", "orderid", "orderid"}, + {"acronym", "ipv4Address", "ipv4AddressId"}, } for _, tt := range tests { - if got := FKName(tt.input); got != tt.want { - t.Errorf("FKName(%q) = %q, want %q", tt.input, got, tt.want) - } + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := FKName(tt.input); got != tt.want { + t.Errorf("FKName(%q) = %q, want %q", tt.input, got, tt.want) + } + }) } } func TestPascalCase(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want string }{ - {"firstName", "FirstName"}, - {"first_name", "FirstName"}, - {"first-name", "FirstName"}, - {"first name", "FirstName"}, - {"HTML", "Html"}, - {"", ""}, - {"a", "A"}, + {"camel_case", "firstName", "FirstName"}, + {"snake_case", "first_name", "FirstName"}, + {"kebab_case", "first-name", "FirstName"}, + {"spaced_input", "first name", "FirstName"}, + {"all_caps", "HTML", "Html"}, + {"empty", "", ""}, + {"single_letter", "a", "A"}, } for _, tt := range tests { - got := PascalCase(tt.input) - if got != tt.want { - t.Errorf("PascalCase(%q) = %q, want %q", tt.input, got, tt.want) - } + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := PascalCase(tt.input) + if got != tt.want { + t.Errorf("PascalCase(%q) = %q, want %q", tt.input, got, tt.want) + } + }) } } func TestCamelCase(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want string }{ - {"first_name", "firstName"}, - {"FirstName", "firstName"}, - {"", ""}, + {"snake_case", "first_name", "firstName"}, + {"pascal_case", "FirstName", "firstName"}, + {"empty", "", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := CamelCase(tt.input) + if got != tt.want { + t.Errorf("CamelCase(%q) = %q, want %q", tt.input, got, tt.want) + } + }) + } +} + +// TestCasingKeepsUnicodeValid pins the rune boundary: project names are only +// checked for non-emptiness, so a multi-byte first letter must survive casing +// instead of becoming U+FFFD in generated identifiers. +func TestCasingKeepsUnicodeValid(t *testing.T) { + t.Parallel() + tests := []struct { + name string + input string + pascal string + camel string + }{ + {"cyrillic", "магазин", "Магазин", "магазин"}, + {"cyrillic snake", "магазин_товары", "МагазинТовары", "магазинТовары"}, } for _, tt := range tests { - got := CamelCase(tt.input) - if got != tt.want { - t.Errorf("CamelCase(%q) = %q, want %q", tt.input, got, tt.want) - } + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + pascal := PascalCase(tt.input) + camel := CamelCase(tt.input) + if pascal != tt.pascal { + t.Errorf("PascalCase(%q) = %q, want %q", tt.input, pascal, tt.pascal) + } + if camel != tt.camel { + t.Errorf("CamelCase(%q) = %q, want %q", tt.input, camel, tt.camel) + } + if !utf8.ValidString(pascal) || !utf8.ValidString(camel) { + t.Errorf("casing produced invalid UTF-8: %q / %q", pascal, camel) + } + }) } } func TestSplitIdentifier(t *testing.T) { + t.Parallel() tests := []struct { + name string input string want []string }{ - {"firstName", []string{"first", "Name"}}, - {"first_name", []string{"first", "name"}}, - {"HTMLParser", []string{"HTML", "Parser"}}, - {"HTTPSServer", []string{"HTTPS", "Server"}}, - {"simple", []string{"simple"}}, + {"camel_case", "firstName", []string{"first", "Name"}}, + {"snake_case", "first_name", []string{"first", "name"}}, + {"acronym", "HTMLParser", []string{"HTML", "Parser"}}, + {"all_caps_acronym", "HTTPSServer", []string{"HTTPS", "Server"}}, + {"simple", "simple", []string{"simple"}}, } for _, tt := range tests { - got := SplitIdentifier(tt.input) - if len(got) != len(tt.want) { - t.Errorf("SplitIdentifier(%q) = %v, want %v", tt.input, got, tt.want) - continue - } - for i := range got { - if got[i] != tt.want[i] { - t.Errorf("SplitIdentifier(%q)[%d] = %q, want %q", tt.input, i, got[i], tt.want[i]) + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := SplitIdentifier(tt.input) + if len(got) != len(tt.want) { + t.Errorf("SplitIdentifier(%q) = %v, want %v", tt.input, got, tt.want) + return + } + for i := range got { + if got[i] != tt.want[i] { + t.Errorf("SplitIdentifier(%q)[%d] = %q, want %q", tt.input, i, got[i], tt.want[i]) + } } - } + }) } } diff --git a/scripts/test-impact.sh b/scripts/test-impact.sh new file mode 100644 index 0000000..b2bcf92 --- /dev/null +++ b/scripts/test-impact.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# Run tests only for packages touched by uncommitted changes and their +# dependents. Core-wide changes (go.mod, IR, specmeta, bundled bridges) fall +# back to the full suite. Logic lives in this file; Makefile only calls it. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PY="" +for candidate in python3 python; do + # Windows installs a Microsoft Store stub named python3 that exits 49. + if command -v "$candidate" >/dev/null 2>&1 && "$candidate" -c 'import sys' >/dev/null 2>&1; then + PY="$candidate" + break + fi +done +[[ -n "$PY" ]] || { echo "error: a working python3 is required" >&2; exit 1; } +cd "$ROOT" + +changed="$(git diff --name-only HEAD -- '*.go' go.mod go.sum bridges/ || true)" +if [[ -z "$changed" ]]; then + echo "test-impact: no changed Go files; running the full suite" + exec go test -count=1 ./... +fi + +packages="$("$PY" - "$changed" <<'PY' +import json, os, subprocess, sys +from collections import deque, defaultdict + +changed = [p.strip().replace("\\", "/") for p in sys.argv[1].splitlines() if p.strip()] +core = ("go.mod", "go.sum", "bridges/", "bridges_embed.go", + "internal/specmeta/", "internal/ir/", "internal/renderer/") +if any(p == c or p.startswith(c) for p in changed for c in core if c.endswith("/")) or \ + any(p == c for p in changed for c in core if not c.endswith("/")): + print("ALL") + sys.exit(0) + +raw = subprocess.check_output(["go", "list", "-json", "./..."], text=True) +dec = json.JSONDecoder() +pkgs, i = [], 0 +while i < len(raw): + while i < len(raw) and raw[i].isspace(): + i += 1 + if i >= len(raw): + break + obj, i = dec.raw_decode(raw, i) + pkgs.append(obj) + +by_dir = {os.path.abspath(p["Dir"]): p["ImportPath"] for p in pkgs} +roots = set() +for path in changed: + if not path.endswith(".go"): + continue + d = os.path.abspath(os.path.dirname(path)) + if d in by_dir: + roots.add(by_dir[d]) + +reverse = defaultdict(set) +for p in pkgs: + for dep in set(p.get("Deps", [])) | set(p.get("Imports", [])) | \ + set(p.get("TestImports", [])) | set(p.get("XTestImports", [])): + reverse[dep].add(p["ImportPath"]) + +seen, q = set(roots), deque(roots) +# A change confined to _test.go files cannot affect other packages. +test_only = all(p.endswith("_test.go") for p in changed if p.endswith(".go")) +if not test_only: + while q: + for dependent in reverse[q.popleft()]: + if dependent not in seen: + seen.add(dependent) + q.append(dependent) + +if not seen: + print("ALL") +else: + print(" ".join(sorted(seen))) +PY +)" + +if [[ "$packages" == "ALL" ]]; then + echo "test-impact: core-wide change; running the full suite" + exec go test -count=1 ./... +fi + +echo "test-impact: $packages" +# shellcheck disable=SC2086 +exec go test -count=1 $packages diff --git a/spec/domain.schema.json b/spec/domain.schema.json index abf3e78..126fcf9 100644 --- a/spec/domain.schema.json +++ b/spec/domain.schema.json @@ -111,7 +111,7 @@ "port": { "description": "Exposed application port (default: 8080)", "maximum": 65535, - "minimum": 1, + "minimum": 0, "type": "integer" } }, @@ -310,12 +310,12 @@ "properties": { "default_page_size": { "description": "Default page size (default: 20)", - "minimum": 1, + "minimum": 0, "type": "integer" }, "max_page_size": { "description": "Hard cap on page size (default: 200)", - "minimum": 1, + "minimum": 0, "type": "integer" } }, @@ -378,7 +378,7 @@ }, "permit_limit": { "description": "Max requests (default: 100)", - "minimum": 1, + "minimum": 0, "type": "integer" }, "policy": { @@ -391,7 +391,7 @@ }, "window_seconds": { "description": "Window duration in seconds (default: 60)", - "minimum": 1, + "minimum": 0, "type": "integer" } }, diff --git a/spec/errors.md b/spec/errors.md index e2a3ee7..b0b7058 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -10,7 +10,7 @@ shape, but both expose the same machine-readable codes. ## 1. Validation rules (from the core) -`IRField.ValidationRules()` returns normalized rules. Each rule carries: +`Field.ValidationRules()` returns normalized rules. Each rule carries: | field | meaning | |------------|----------------------------------------------------------------------| @@ -59,7 +59,7 @@ use a minimal, consistent envelope: | `CONSTRAINT_CONFLICT` | 409 | any other database constraint violation | Unique constraints are core-owned: the core computes the constraint name -(`IRIndex.DatabaseName()`) and the field set (`IREntity.AllIndexes()`), so a +(`Index.DatabaseName()`) and the field set (`Entity.AllIndexes()`), so a bridge can map a database unique violation (PostgreSQL `SqlState 23505`) back to the offending field and report `{ code: "UNIQUE_CONFLICT", message: " must be unique" }` — never a bare 500. @@ -89,7 +89,7 @@ Paginated list endpoints return a `PagedResult`-shaped payload: Field names are part of the contract and must match across bridges (JSON `camelCase`). Request normalization is defined in `spec/query.md` -(`IRPaginationConfig` / `ListQuery.FromQuery`): `limit` wins over `pageSize`, +(`PaginationConfig` / `ListQuery.FromQuery`): `limit` wins over `pageSize`, both clamp to `1..max_page_size`, `page >= 1`. In keyset (cursor) mode `nextCursor` carries the last row's primary key (or `null` at the end); offset mode leaves it `null`. diff --git a/spec/query.md b/spec/query.md index fe5612c..3e4da5c 100644 --- a/spec/query.md +++ b/spec/query.md @@ -4,8 +4,8 @@ The core defines **one** list-query grammar — search, sort, filter and pagination — that every bridge serializes into its own query layer (LINQ, Prisma `where`/`orderBy`, Mongo `$match`/`$sort`, Appwrite `Query.*`, SQL `WHERE`/`ORDER BY`, …). The core emits the *schema* a bridge's runtime validator -consumes — `IREntity.FilterablePaths()`, `SortableFields()`, -`SearchableFields()`, and the pagination policy on `IRProject.Pagination` — and +consumes — `Entity.FilterablePaths()`, `SortableFields()`, +`SearchableFields()`, and the pagination policy on `Project.Pagination` — and the bridge parses and validates the query strings at runtime against that schema. The grammar below is the contract the bridge's parser must implement. @@ -118,7 +118,7 @@ sort := key ( "," key )* key := [ "-" | "+" ] field # "-" = descending, "+"/bare = ascending ``` -- `field` is a scalar field name from `IREntity.SortableFields()`, matched +- `field` is a scalar field name from `Entity.SortableFields()`, matched case-insensitively and canonicalized to the IR field name. - The primary key, relations, enums, arrays, JSON blobs, hidden and feature fields are **not** sortable (the PK is the implicit default order, not an @@ -138,10 +138,10 @@ List endpoints accept two paging modes plus sizing controls: - **Offset (default):** `page` + `pageSize` (and `limit`, an alias for `pageSize`; when both are given, `limit` wins). The effective page size is - clamped to `1 .. MaxPageSize` (`IRProject.Pagination`), `page` is clamped to + clamped to `1 .. MaxPageSize` (`Project.Pagination`), `page` is clamped to `>= 1`. Supports `sort`. - **Keyset (cursor):** `cursor` + `pageSize`. Available only when the primary - key is a monotonic integer (`int`/`bigint`) — `IREntity.CursorField()` returns + key is a monotonic integer (`int`/`bigint`) — `Entity.CursorField()` returns the PK then, nil otherwise. `cursor` is the primary key of the last row seen; the bridge returns rows `WHERE pk > cursor ORDER BY pk` and sets `nextCursor` to the last row's PK (or `null` when no further rows follow). `sort` is @@ -154,7 +154,7 @@ offset-mode only; cursor clients read `nextCursor` (null = end). ## Relation expansion -A bridge eager-loads the entity's relations (`IREntity.EagerLoadRelations()`). +A bridge eager-loads the entity's relations (`Entity.EagerLoadRelations()`). List endpoints accept `include`, a comma-separated list of relation field names (the JSON camelCase names); it restricts which `[many]` collections are loaded: