From be6047d1b2477b586c3be943edac287610dc8287 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:12:59 +0300 Subject: [PATCH 01/83] Core: harden codebase --- .github/workflows/ci.yml | 9 +- .golangci.yml | 17 ++ cmd/domaincraft/commands.go | 64 ++++---- cmd/domaincraft/commands_test.go | 4 + cmd/domaincraft/init.go | 10 +- cmd/domaincraft/notify_test.go | 30 ++++ cmd/domaincraft/update.go | 30 ++-- cmd/domaincraft/update_test.go | 2 +- compliance-suite/regressions.tsv | 10 ++ internal/bridge/clone.go | 28 +++- internal/bridge/embed_test.go | 1 + internal/bridge/id_test.go | 30 ++++ internal/bridge/policy_test.go | 208 ++++++++++++++++++++++++ internal/bridge/registry.go | 10 +- internal/bridge/resolver.go | 3 + internal/bridge/status_test.go | 2 + internal/bridge/update.go | 5 +- internal/bridge/update_test.go | 6 +- internal/fsutil/fsutil.go | 4 +- internal/interactive/prompts.go | 10 +- internal/interactive/terminal.go | 23 ++- internal/ir/models.go | 4 +- internal/ir/typekind.go | 25 ++- internal/lexer/lexer.go | 67 ++++---- internal/packages/registry.go | 69 ++++++-- internal/packages/registry_test.go | 50 +++++- internal/parser/parser.go | 10 +- internal/renderer/render.go | 27 ++- internal/seed/seed.go | 3 + internal/snapshot/paths.go | 28 ++++ internal/snapshot/paths_test.go | 78 +++++++++ internal/snapshot/rewrite.go | 6 +- internal/snapshot/rewrite_test.go | 17 ++ internal/snapshot/snapshot.go | 15 +- internal/specmeta/specmeta.go | 96 ++++++++--- internal/templatefuncs/templatefuncs.go | 56 +++---- internal/validator/validator.go | 11 +- pkg/logger/logger.go | 17 +- 38 files changed, 883 insertions(+), 202 deletions(-) create mode 100644 .golangci.yml create mode 100644 internal/bridge/id_test.go create mode 100644 internal/bridge/policy_test.go create mode 100644 internal/snapshot/paths.go create mode 100644 internal/snapshot/paths_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df12d91..ebe7744 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,13 +32,18 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: '1.27' + go-version: '1.27.4' cache: true cache-dependency-path: go.sum - name: Download dependencies run: go mod download + - name: Lint + uses: golangci/golangci-lint-action@v8 + with: + version: v2.15.0 + - name: Build run: go build ./cmd/domaincraft @@ -59,7 +64,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: '1.27' + go-version: '1.27.4' cache: true cache-dependency-path: go.sum diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..97c6220 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,17 @@ +version: "2" + +run: + timeout: 5m + tests: true + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +linters: + enable: + - govet + - errcheck + - ineffassign + - staticcheck + - unused diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index 5d27d7e..ec28299 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 @@ -280,7 +281,10 @@ func runGenerate(cmd *cobra.Command, args []string) error { 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() + generate, err := interactive.PromptGenerateAdmin() + if err != nil { + return fmt.Errorf("prompt for admin panel: %w", err) + } if generate { adminBridge = "admin-alpine" } @@ -335,19 +339,19 @@ func runGenerate(cmd *cobra.Command, args []string) error { // --- 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) + _, _ = 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) + _, _ = fmt.Fprint(cmd.OutOrStdout(), report) } // --- 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) + _, _ = fmt.Fprint(cmd.OutOrStdout(), report) } // --- Persist the new snapshot --- @@ -387,12 +391,12 @@ func newBridgesCmd() *cobra.Command { 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), @@ -429,11 +433,11 @@ 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 }, } @@ -633,7 +637,10 @@ func resolveChainWithReplacements(entryDir string, reps []replaceEntry, log *log return "", nil, fmt.Errorf("bridge `extends` cycle detected at %q", d) } seenPath[abs] = true - layer, _, _ := bridgeLayerAndName(d, log) + layer, _, err := bridgeLayerAndName(d, log) + if err != nil { + return "", nil, fmt.Errorf("read layer of %s: %w", d, err) + } if layer != "" { if prev, ok := seenLayer[layer]; ok { return "", nil, fmt.Errorf("duplicate layer %q: %q and %q", layer, prev, d) @@ -813,9 +820,9 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co 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)) + _, _ = 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) + _, _ = 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) @@ -833,7 +840,6 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co 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) } } @@ -875,7 +881,7 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg continue } if rewrote { - fmt.Fprintf(out, " ▸ updated namespace %s -> %s in %s\n", diff.NamespaceRename.OldNamespace, diff.NamespaceRename.NewNamespace, rel) + _, _ = fmt.Fprintf(out, " ▸ updated namespace %s -> %s in %s\n", diff.NamespaceRename.OldNamespace, diff.NamespaceRename.NewNamespace, rel) } } } @@ -890,7 +896,7 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg continue } if rewrote { - fmt.Fprintf(out, " ▸ updated field %s -> %s in %s\n", fr.OldField, fr.NewField, rel) + _, _ = fmt.Fprintf(out, " ▸ updated field %s -> %s in %s\n", fr.OldField, fr.NewField, rel) } } } @@ -953,7 +959,7 @@ func handleDeletedEntity(del snapshot.DeletedEntity, fresh map[string]bool, log 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)) + _, _ = fmt.Fprintf(out, " - %s%s\n", f.Path, customMark(f)) } return false, nil } @@ -972,7 +978,7 @@ func handleDeletedEntity(del snapshot.DeletedEntity, fresh map[string]bool, log log.Warn("could not delete %s: %v", f.Path, err) continue } - fmt.Fprintf(out, " ▸ deleted %s\n", f.Path) + _, _ = fmt.Fprintf(out, " ▸ deleted %s\n", f.Path) } return true, nil } @@ -986,7 +992,7 @@ func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, 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)) + _, _ = fmt.Fprintf(out, " - %s -> %s\n", f.Path, snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName)) } return false, nil } @@ -1021,10 +1027,10 @@ func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, 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) + _, _ = fmt.Fprintf(out, " ▸ renamed %s -> %s (content updated)\n", f.Path, newRel) continue } - fmt.Fprintf(out, " ▸ renamed %s -> %s\n", f.Path, newRel) + _, _ = fmt.Fprintf(out, " ▸ renamed %s -> %s\n", f.Path, newRel) } continue } @@ -1033,7 +1039,7 @@ func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, 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) + _, _ = fmt.Fprintf(out, " ▸ removed stale generated file %s\n", f.Path) } return true, nil } @@ -1086,10 +1092,10 @@ func loadAndValidate(out io.Writer) (*parser.ParsedSchema, error) { var hardErrors []validator.ValidationError for _, e := range allErrors { if e.Warning { - fmt.Fprintf(out, "⚠ %s\n", e.Error()) + _, _ = fmt.Fprintf(out, "⚠ %s\n", e.Error()) } else { hardErrors = append(hardErrors, e) - fmt.Fprintln(out, e.Error()) + _, _ = fmt.Fprintln(out, e.Error()) } } diff --git a/cmd/domaincraft/commands_test.go b/cmd/domaincraft/commands_test.go index 4364faa..e5663b5 100644 --- a/cmd/domaincraft/commands_test.go +++ b/cmd/domaincraft/commands_test.go @@ -92,3 +92,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/init.go b/cmd/domaincraft/init.go index 74c5848..9ac2cfb 100644 --- a/cmd/domaincraft/init.go +++ b/cmd/domaincraft/init.go @@ -116,10 +116,12 @@ func newInitCmd() *cobra.Command { return err } - if _, err := os.Stat(domainFile); err == nil && !force { + _, statErr := os.Stat(domainFile) + if statErr == 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) + } + if statErr != nil && !os.IsNotExist(statErr) { + return fmt.Errorf("check %s: %w", domainFile, statErr) } if err := fsutil.AtomicWrite(domainFile, []byte(content)); err != nil { return fmt.Errorf("write %s: %w", domainFile, err) @@ -137,7 +139,7 @@ func newInitCmd() *cobra.Command { } } 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", domainFile, domainFile) return nil } diff --git a/cmd/domaincraft/notify_test.go b/cmd/domaincraft/notify_test.go index f3131c9..e842ced 100644 --- a/cmd/domaincraft/notify_test.go +++ b/cmd/domaincraft/notify_test.go @@ -12,6 +12,7 @@ func TestCachedLatestCoreVersion(t *testing.T) { defer func() { httpGetBodyFn = orig }() appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) httpGetBodyFn = func(url string) ([]byte, error) { if url != releasesLatestURL { @@ -37,3 +38,32 @@ func TestCachedLatestCoreVersion(t *testing.T) { 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) { + orig := httpGetBodyFn + defer func() { httpGetBodyFn = orig }() + + appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) + + calls := 0 + httpGetBodyFn = func(string) ([]byte, error) { + calls++ + return nil, fmt.Errorf("network down") + } + + if _, err := cachedLatestCoreVersion(); 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 := cachedLatestCoreVersion() + 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) + } +} diff --git a/cmd/domaincraft/update.go b/cmd/domaincraft/update.go index 08a3d1f..707f60a 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -77,24 +77,34 @@ func cachedLatestCoreVersion() (string, error) { cachePath := filepath.Join(cacheDir, "core-update.json") if data, rerr := os.ReadFile(cachePath); rerr == nil { 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() if err != nil { + // Record the attempt as well: an offline or blackholed network must not + // make every later invocation wait for the full HTTP timeout again. + writeUpdateCheckCache(cacheDir, cachePath, updateCheckCache{CheckedAt: time.Now()}) 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) - } - } + writeUpdateCheckCache(cacheDir, cachePath, updateCheckCache{CheckedAt: time.Now(), Latest: latest}) return latest, nil } +func writeUpdateCheckCache(cacheDir, cachePath string, c updateCheckCache) { + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + return + } + body, err := json.Marshal(c) + if err != nil { + return + } + _ = fsutil.AtomicWrite(cachePath, body) +} + // newUpdateCmd checks for and installs a newer version of the domaincraft core. func newUpdateCmd() *cobra.Command { var checkOnly bool @@ -147,7 +157,7 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { if err != nil { return err } - defer os.Remove(tmp) + defer func() { _ = os.Remove(tmp) }() exe, err := os.Executable() if err != nil { @@ -205,7 +215,7 @@ func httpGetBody(url string) ([]byte, 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("http %d for %s", resp.StatusCode, url) } @@ -223,10 +233,10 @@ func downloadBinary(url string) (string, error) { if err != nil { return "", err } - defer tmp.Close() + defer func() { _ = tmp.Close() }() if _, err := tmp.Write(data); err != nil { - os.Remove(tmp.Name()) + _ = os.Remove(tmp.Name()) return "", err } if runtime.GOOS != "windows" { diff --git a/cmd/domaincraft/update_test.go b/cmd/domaincraft/update_test.go index ffcd9dd..359d46c 100644 --- a/cmd/domaincraft/update_test.go +++ b/cmd/domaincraft/update_test.go @@ -144,7 +144,7 @@ func TestDownloadAndReplace(t *testing.T) { 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") diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 93de370..b5b8ac4 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -11,3 +11,13 @@ internal/validator/validator_test.go::TestExampleDomainHasNoWarnings #3 shipped 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/bridge/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 +internal/snapshot/paths_test.go::TestDeleteFileRejectsSnapshotEscape #5 poisoned snapshot path deleted a file outside the output dir +internal/snapshot/paths_test.go::TestRewriteFileRejectsSnapshotEscape #5 poisoned snapshot path rewrote a file outside the output dir +internal/packages/registry_test.go::TestValidateRegistryURLRejectsInternalTargets #5 bridge.yaml registry_url allowed requests to internal addresses +cmd/domaincraft/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/policy_test.go::TestMaybeUpdatePolicies #5 bridge update policy decisions had no regression coverage +internal/bridge/policy_test.go::TestApplyUpdateRejectsUnsupportedContract #5 apply path could hard-reset a bridge with an unsupported contract version +internal/snapshot/rewrite_test.go::TestRewriteEntityContent #5 inner identifiers such as myProduct were not protected from rename rewrite diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index db20c3e..317d0f7 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "time" "github.com/DomainCraft/DomainCraft/internal/appdir" @@ -25,6 +26,17 @@ func CachePath(entry RegistryEntry) string { return filepath.Join(BridgeCacheDir(), entry.ID) } +// 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. func IsCached(entry RegistryEntry) bool { bridgeFile := filepath.Join(CachePath(entry), "bridge.yaml") @@ -62,6 +74,9 @@ 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) } @@ -69,9 +84,11 @@ func EnsureBridge(entry RegistryEntry, opts *EnsureOptions) (string, error) { cacheDir := CachePath(entry) 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 { @@ -80,7 +97,7 @@ func EnsureBridge(entry RegistryEntry, opts *EnsureOptions) (string, error) { // Verify the cloned repo contains bridge.yaml. if !IsCached(entry) { - os.RemoveAll(cacheDir) + _ = os.RemoveAll(cacheDir) return "", fmt.Errorf("cloned bridge %q does not contain bridge.yaml", entry.ID) } @@ -170,6 +187,9 @@ func warnOpts(opts *EnsureOptions, format string, args ...any) { // 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") } @@ -183,7 +203,7 @@ func CloneBridge(entry RegistryEntry) error { url := fmt.Sprintf("https://github.com/%s.git", entry.GitHub) cmd := exec.Command("git", "clone", "--depth", "1", url, cacheDir) if out, err := cmd.CombinedOutput(); err != nil { - os.RemoveAll(cacheDir) + _ = os.RemoveAll(cacheDir) return fmt.Errorf("clone %s: %w: %s", url, err, out) } return nil diff --git a/internal/bridge/embed_test.go b/internal/bridge/embed_test.go index 3a2d205..817f1b5 100644 --- a/internal/bridge/embed_test.go +++ b/internal/bridge/embed_test.go @@ -17,6 +17,7 @@ import ( // 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") diff --git a/internal/bridge/id_test.go b/internal/bridge/id_test.go new file mode 100644 index 0000000..026cc88 --- /dev/null +++ b/internal/bridge/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/policy_test.go b/internal/bridge/policy_test.go new file mode 100644 index 0000000..f9fd46d --- /dev/null +++ b/internal/bridge/policy_test.go @@ -0,0 +1,208 @@ +package bridge + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +// fakeUpdateHTTP reports a remote head that differs from the cached commit and, +// optionally, a bridge.yaml with an unsupported contract version. +func fakeUpdateHTTP(t *testing.T, remoteYAML string) { + t.Helper() + original := httpGetBodyFn + t.Cleanup(func() { httpGetBodyFn = original }) + httpGetBodyFn = func(url string) ([]byte, error) { + switch { + case strings.Contains(url, "/commits/main"): + return []byte(`{"sha":"remote-head"}`), nil + case strings.Contains(url, "/repos/"): + return []byte(`{"default_branch":"main"}`), nil + case strings.Contains(url, "bridge.yaml"): + return []byte(remoteYAML), nil + } + return nil, os.ErrNotExist + } +} + +// 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 + confirm func(RegistryEntry, *Update) (bool, error) + wantWarn string + wantConfirm bool + wantErr bool + }{ + { + name: "disabled interval skips the remote", + interval: -1, + remoteYAML: "name: test\ncontract_version: 1\n", + }, + { + name: "fresh cache skips the remote", + interval: 24 * time.Hour, + remoteYAML: "name: test\ncontract_version: 1\n", + }, + { + 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: 2\n", + wantWarn: "skipping update", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + 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) + } + if err := os.WriteFile(filepath.Join(cacheDir, "bridge.yaml"), []byte("name: test\nversion: \"1.0.0\"\n"), 0o644); err != nil { + t.Fatal(err) + } + 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: "cached-head", + Branch: "main", + LastCheckedAt: lastChecked, + }); err != nil { + t.Fatal(err) + } + + fakeUpdateHTTP(t, 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, args ...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) + } + }) + } +} + +// TestApplyUpdateRejectsUnsupportedContract checks the hard invariant at the +// apply site, not only the isolated shouldApplyContract 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 := filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", "main", "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") + + src := filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, "main") + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", "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) + } + + original := httpGetBodyFn + defer func() { httpGetBodyFn = original }() + httpGetBodyFn = func(url string) ([]byte, error) { + switch { + case strings.Contains(url, "/commits/main"): + return []byte(`{"sha":"` + testGit(t, remote, "rev-parse", "HEAD") + `"}`), nil + case strings.Contains(url, "/repos/"): + return []byte(`{"default_branch":"main"}`), nil + } + return nil, os.ErrNotExist + } + + // 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: 2\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") + + 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) + } +} diff --git a/internal/bridge/registry.go b/internal/bridge/registry.go index 595dcdd..1fa7947 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" @@ -122,7 +125,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,14 +135,15 @@ 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 diff --git a/internal/bridge/resolver.go b/internal/bridge/resolver.go index 624649e..f5e8afe 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -66,6 +66,9 @@ func (r *Resolver) Resolve(input string) (string, error) { // ".." 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] != ".." { + if strings.ContainsAny(parts[1], "/\\") || parts[1] == "." || parts[1] == ".." { + return "", fmt.Errorf("bridge %q not found: invalid repository name", input) + } repo, ref := splitPinRef(input) entry := RegistryEntry{ ID: parts[1], diff --git a/internal/bridge/status_test.go b/internal/bridge/status_test.go index 365f628..8e05b04 100644 --- a/internal/bridge/status_test.go +++ b/internal/bridge/status_test.go @@ -10,6 +10,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) @@ -37,6 +38,7 @@ func TestStatusLocalFacts(t *testing.T) { // and reports outdated only for a supported (not newer-contract) bridge. func TestStatusRemoteOnlyWhenRequested(t *testing.T) { appdir.SetBaseForTesting(t.TempDir()) + t.Cleanup(func() { appdir.SetBaseForTesting("") }) orig := httpGetBodyFn defer func() { httpGetBodyFn = orig }() diff --git a/internal/bridge/update.go b/internal/bridge/update.go index 34c949d..6832962 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -134,6 +134,9 @@ 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) branch := "main" @@ -222,7 +225,7 @@ func httpGetBody(url string) ([]byte, 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("http %d for %s", resp.StatusCode, url) } diff --git a/internal/bridge/update_test.go b/internal/bridge/update_test.go index e423705..93119cf 100644 --- a/internal/bridge/update_test.go +++ b/internal/bridge/update_test.go @@ -112,7 +112,7 @@ func TestCheckAndApplyUpdate(t *testing.T) { // Working repo that we push to the remote. src := filepath.Join(root, "src") - os.MkdirAll(src, 0o755) + _ = os.MkdirAll(src, 0o755) makeBridgeRepo(t, src, "main") testGit(t, src, "remote", "add", "origin", remote) testGit(t, src, "push", "-q", "-u", "origin", "main") @@ -206,7 +206,7 @@ func TestEnsureMetaSynthesizesForLegacyCache(t *testing.T) { entry := RegistryEntry{ID: "legacy-bridge", GitHub: "owner/legacy-bridge"} cacheDir := CachePath(entry) - os.MkdirAll(cacheDir, 0o755) + _ = os.MkdirAll(cacheDir, 0o755) makeBridgeRepo(t, cacheDir, "main") // No metadata file exists (legacy cache), but the checkout is usable. @@ -235,7 +235,7 @@ func TestCheckForUpdateViaGitHubAPI(t *testing.T) { entry := RegistryEntry{ID: "github-bridge", GitHub: "owner/github-bridge"} cacheDir := CachePath(entry) - os.MkdirAll(cacheDir, 0o755) + _ = os.MkdirAll(cacheDir, 0o755) writeBridgeYAML(t, cacheDir, "1.0.0") // No .git in the checkout, but metadata records the local commit. diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index 7b5e7a3..e166ba2 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -23,10 +23,10 @@ func AtomicWrite(path string, data []byte) error { return err } tmpName := tmp.Name() - defer os.Remove(tmpName) // no-op once the rename succeeds + defer func() { _ = os.Remove(tmpName) }() // no-op once the rename succeeds if _, err := tmp.Write(data); err != nil { - tmp.Close() + _ = tmp.Close() return err } if err := tmp.Close(); err != nil { diff --git a/internal/interactive/prompts.go b/internal/interactive/prompts.go index ea41f05..2f83bb5 100644 --- a/internal/interactive/prompts.go +++ b/internal/interactive/prompts.go @@ -200,18 +200,18 @@ func confirm(title, description string) (bool, error) { if err != nil { return err } - switch { - case k.kind == keyEnter: + switch k.kind { + case keyEnter: result = cursor == 0 return nil - case k.kind == keyEsc: + case keyEsc: return errAborted - case k.kind == keyLeft: + case keyLeft: if cursor != 0 { cursor = 0 f.draw(build()) } - case k.kind == keyRight: + case keyRight: if cursor != 1 { cursor = 1 f.draw(build()) diff --git a/internal/interactive/terminal.go b/internal/interactive/terminal.go index 79415d9..a87ac24 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 ( @@ -89,7 +90,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() } @@ -268,24 +273,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/ir/models.go b/internal/ir/models.go index 00575b4..32c7078 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -1,6 +1,8 @@ +// Package ir builds the resolved intermediate representation consumed by bridges. package ir import ( + "slices" "strings" "github.com/DomainCraft/DomainCraft/internal/specmeta" @@ -206,7 +208,7 @@ func (e IREntity) RelationFields() []IRField { // 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 + return slices.Clone(e.RelationsOut) } // EagerLoadNavigation returns the navigation property name used to Include a diff --git a/internal/ir/typekind.go b/internal/ir/typekind.go index 42b1903..efb1621 100644 --- a/internal/ir/typekind.go +++ b/internal/ir/typekind.go @@ -22,8 +22,13 @@ 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. -func (f IRField) IsUuid() bool { return f.DatabaseType == "uuid" } +// +// Deprecated: use IsUUID. Kept as an alias for bridges using the old casing. +func (f IRField) IsUuid() bool { return f.IsUUID() } // IsText reports whether the field holds a string/text value. func (f IRField) IsText() bool { @@ -52,15 +57,25 @@ func (f IRField) IsDate() bool { return f.DatabaseType == "date" } // IsDateTime reports whether the field holds a datetime. func (f IRField) IsDateTime() bool { return f.DatabaseType == "datetime" } -// IsJson reports whether the field holds a JSON document (json or jsonb). -func (f IRField) IsJson() bool { +// IsJSON reports whether the field holds a JSON document (json or jsonb). +func (f IRField) IsJSON() bool { return f.DatabaseType == "json" || f.DatabaseType == "jsonb" } -// IsJsonB reports whether the field holds a jsonb document specifically +// IsJson reports whether the field holds a JSON document. +// +// Deprecated: use IsJSON. +func (f IRField) IsJson() bool { return f.IsJSON() } + +// 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 IRField) IsJSONB() bool { return f.DatabaseType == "jsonb" } + +// IsJsonB reports whether the field holds a jsonb document. +// +// Deprecated: use IsJSONB. +func (f IRField) IsJsonB() bool { return f.IsJSONB() } // IsString reports whether the field holds a bounded string column // (as opposed to an unbounded text column, which also satisfies IsText). diff --git a/internal/lexer/lexer.go b/internal/lexer/lexer.go index c5f43db..c6b903e 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 ( @@ -44,8 +45,8 @@ type Lexer struct { input string } -// NewLexer creates a new Lexer -func NewLexer(input string) *Lexer { +// New creates a new Lexer. +func New(input string) *Lexer { return &Lexer{input: strings.TrimSpace(input)} } @@ -128,7 +129,7 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { // 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: string, int, uuid, relation, array, enum, json, text", typeStr) } fd.Type = typeStr @@ -154,33 +155,33 @@ 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 + 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) + } + 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) } - case "on_delete": - if !specmeta.IsOnDeleteValue(value) { - return fmt.Errorf("unknown on_delete value: %s. valid: cascade, set_null, restrict, no_action", value) - } - 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 } @@ -289,7 +290,7 @@ func (fd *FieldDefinition) Validate() error { // 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) } } @@ -308,12 +309,12 @@ func isValidIdentifier(s string) bool { } for i, r := range s { if i == 0 { - if r != '_' && !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') { + 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') { + if r != '_' && (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') { return false } } @@ -322,6 +323,6 @@ func isValidIdentifier(s string) bool { // ParseFieldString is a convenience function for parsing a field string func ParseFieldString(fieldString string) (*FieldDefinition, error) { - lexer := NewLexer(fieldString) + lexer := New(fieldString) return lexer.Parse() } diff --git a/internal/packages/registry.go b/internal/packages/registry.go index 23c7e56..ae94a58 100644 --- a/internal/packages/registry.go +++ b/internal/packages/registry.go @@ -5,12 +5,51 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" + "net/url" + "strconv" "strings" "time" ) -var registryClient = &http.Client{Timeout: 5 * time.Second} +var registryClient = &http.Client{ + Timeout: 5 * time.Second, + CheckRedirect: func(req *http.Request, _ []*http.Request) error { + if err := validateRegistryURL(req.URL.String()); err != nil { + return err + } + return nil + }, +} + +// allowLocalRegistryForTests is set only by tests using httptest TLS servers. +var allowLocalRegistryForTests bool + +// validateRegistryURL keeps registry requests on https and away from loopback, +// private and link-local addresses. registry_url comes from bridge.yaml, which +// may be cloned from an untrusted repository. +func validateRegistryURL(raw string) error { + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("invalid registry URL %q: %w", raw, err) + } + if u.Scheme != "https" || u.Host == "" { + return fmt.Errorf("registry URL must be an absolute https URL: %q", 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 && + (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) { + return fmt.Errorf("registry host %q is not allowed", host) + } + return nil +} // 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. @@ -58,16 +97,23 @@ 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 { + n, err := strconv.Atoi(major) + if err != nil || n <= 0 { return 0 } return n } func versionMajor(version string) int { - var n int - if _, err := fmt.Sscanf(version, "%d", &n); err != nil { + i := 0 + for i < len(version) && version[i] >= '0' && version[i] <= '9' { + i++ + } + if i == 0 { + return 0 + } + n, err := strconv.Atoi(version[:i]) + if err != nil { return 0 } return n @@ -93,9 +139,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.NewRequest("GET", registryEndpoint, nil) if err != nil { return nil, err } @@ -104,7 +153,7 @@ 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) @@ -132,10 +181,10 @@ func VersionGreater(a, b string) bool { for i := range maxLen { var ai, bi int if i < len(aParts) { - fmt.Sscanf(aParts[i], "%d", &ai) + ai, _ = strconv.Atoi(aParts[i]) } if i < len(bParts) { - fmt.Sscanf(bParts[i], "%d", &bi) + bi, _ = strconv.Atoi(bParts[i]) } if ai > bi { return true diff --git a/internal/packages/registry_test.go b/internal/packages/registry_test.go index 320a985..2bfc2db 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,7 +75,7 @@ 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) } @@ -68,7 +108,7 @@ 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, r *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"]}`)) })) @@ -94,7 +134,7 @@ func TestResolveVersionForFrameworkRespectsTargetFramework(t *testing.T) { } 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, r *http.Request) { _, _ = w.Write([]byte(`{"versions":["11.0.0"]}`)) })) defer srv.Close() @@ -117,7 +157,7 @@ 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)) })) @@ -135,7 +175,7 @@ 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 diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 9e2aaf2..17b7cdc 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 ( @@ -92,8 +93,8 @@ 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} } @@ -111,7 +112,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) @@ -287,6 +289,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/renderer/render.go b/internal/renderer/render.go index 28774c2..7417061 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -1,9 +1,13 @@ +// Package renderer renders the IR through bridge templates. package renderer import ( + "errors" "fmt" + "maps" "os" "path/filepath" + "slices" "strings" "text/template" @@ -11,9 +15,11 @@ import ( "github.com/DomainCraft/DomainCraft/internal/packages" ) +// Render renders the IR through every bridge in the chain and returns the +// written paths and the file manifest. func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, []RenderedFile, error) { if project == nil { - return nil, nil, fmt.Errorf("IR project is nil") + return nil, nil, errors.New("IR project is nil") } if outputDir == "" { outputDir = r.config().OutputDir @@ -118,6 +124,20 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] return nil, nil, fmt.Errorf("template target path escapes output directory: %s", renderedTarget) } + // The lexical check does not catch a symlink planted inside the + // output tree. Resolve the parent before creating the file. + parent := filepath.Dir(absoluteTarget) + if realParent, err := filepath.EvalSymlinks(parent); err == nil { + realOutput, err := filepath.EvalSymlinks(absOutput) + if err != nil { + return nil, nil, fmt.Errorf("resolve output directory symlinks: %w", err) + } + realTarget := filepath.Join(realParent, filepath.Base(absoluteTarget)) + if realTarget != realOutput && !strings.HasPrefix(realTarget, realOutput+string(filepath.Separator)) { + return nil, nil, fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget) + } + } + relPath := filepath.ToSlash(renderedTarget) record := RenderedFile{ Path: relPath, @@ -152,7 +172,7 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] } if err := file.Close(); err != nil { _ = os.Remove(absoluteTarget) - return nil, nil, err + return nil, nil, fmt.Errorf("close output file %s: %w", absoluteTarget, err) } writtenFiles = append(writtenFiles, absoluteTarget) manifest = append(manifest, record) @@ -276,7 +296,8 @@ 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 { r.log.Warn("failed to resolve package %s: %v", packageID, err) diff --git a/internal/seed/seed.go b/internal/seed/seed.go index 3e82531..3a397b4 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -31,6 +31,9 @@ type Options struct { // Generate builds deterministic mock seed for every entity in the project. func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { + if project == nil { + return &ir.SeedDataset{} + } if opts.CountPerEntity <= 0 { opts.CountPerEntity = 2 } diff --git a/internal/snapshot/paths.go b/internal/snapshot/paths.go new file mode 100644 index 0000000..25bbe9e --- /dev/null +++ b/internal/snapshot/paths.go @@ -0,0 +1,28 @@ +package snapshot + +import ( + "fmt" + "path/filepath" + "strings" +) + +// 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. +func safeRelPath(outputDir, relPath string) (string, error) { + local := filepath.FromSlash(relPath) + if !filepath.IsLocal(local) { + return "", fmt.Errorf("unsafe snapshot path %q: must be local to output dir", relPath) + } + + absOutput, err := filepath.Abs(outputDir) + if err != nil { + return "", fmt.Errorf("resolve output dir %q: %w", outputDir, err) + } + abs := filepath.Join(absOutput, local) + if abs != absOutput && !strings.HasPrefix(abs, absOutput+string(filepath.Separator)) { + return "", fmt.Errorf("unsafe snapshot path %q: outside output dir", relPath) + } + return abs, nil +} diff --git a/internal/snapshot/paths_test.go b/internal/snapshot/paths_test.go new file mode 100644 index 0000000..38ca0a3 --- /dev/null +++ b/internal/snapshot/paths_test.go @@ -0,0 +1,78 @@ +package snapshot + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { + root := t.TempDir() + + 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) { + 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, root+string(filepath.Separator)) && got != root { + t.Fatalf("safeRelPath(%q) = %q, outside %q", tt.path, got, root) + } + }) + } +} + +func TestDeleteFileRejectsSnapshotEscape(t *testing.T) { + 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 TestRewriteFileRejectsSnapshotEscape(t *testing.T) { + 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..a29c0c3 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -13,7 +13,6 @@ import ( "bytes" "cmp" "os" - "path/filepath" "slices" "strings" @@ -208,7 +207,10 @@ func RewriteFile(outputDir, relPath string, transforms ...func([]byte) []byte) ( if len(transforms) == 0 { return false, nil } - abs := filepath.Join(outputDir, filepath.FromSlash(relPath)) + abs, err := safeRelPath(outputDir, relPath) + if err != nil { + return false, err + } data, err := os.ReadFile(abs) if err != nil { if os.IsNotExist(err) { diff --git a/internal/snapshot/rewrite_test.go b/internal/snapshot/rewrite_test.go index 438bb5a..4503ea2 100644 --- a/internal/snapshot/rewrite_test.go +++ b/internal/snapshot/rewrite_test.go @@ -14,6 +14,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;"}, @@ -29,6 +31,21 @@ 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) { + 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) { in := "entity.Title == prev.Title; var title = Title; TITLE;" want := "entity.Name == prev.Name; var name = Name; NAME;" diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 70a1690..7fc20e8 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -451,7 +451,10 @@ func RenameRelPath(relPath, oldName, newName string) string { // DeleteFile removes an entity-scoped file (path relative to outputDir). func DeleteFile(outputDir, relPath string) error { - abs := filepath.Join(outputDir, filepath.FromSlash(relPath)) + abs, err := safeRelPath(outputDir, relPath) + if err != nil { + return err + } if err := os.Remove(abs); err != nil { return fmt.Errorf("remove %s: %w", relPath, err) } @@ -467,8 +470,14 @@ 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)) + abs, err := safeRelPath(outputDir, relPath) + if err != nil { + return newRel, false, err + } + newAbs, err := safeRelPath(outputDir, newRel) + if err != nil { + return newRel, false, err + } if _, err := os.Stat(newAbs); err == nil { return newRel, false, nil } diff --git a/internal/specmeta/specmeta.go b/internal/specmeta/specmeta.go index 72d7042..4d7dfb2 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -1,3 +1,4 @@ +// Package specmeta is the single source of truth for specification constants. package specmeta import "strings" @@ -138,30 +139,76 @@ 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] } + +// 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] } + +// 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] } + +// 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,10 +217,12 @@ func SliceToSet(items []string) map[string]bool { return set } +// IsArrayType reports whether dbType is an array declaration. func IsArrayType(dbType string) bool { return strings.HasPrefix(dbType, "array(") } +// ParseArrayInner returns the element type of an array declaration, or dbType unchanged. func ParseArrayInner(dbType string) string { if !IsArrayType(dbType) { return dbType @@ -181,6 +230,7 @@ func ParseArrayInner(dbType string) string { return strings.TrimSuffix(strings.TrimPrefix(dbType, "array("), ")") } +// 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 +240,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 +260,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 { diff --git a/internal/templatefuncs/templatefuncs.go b/internal/templatefuncs/templatefuncs.go index 50cedc1..6aee1ec 100644 --- a/internal/templatefuncs/templatefuncs.go +++ b/internal/templatefuncs/templatefuncs.go @@ -23,35 +23,35 @@ 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": 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, "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, } } diff --git a/internal/validator/validator.go b/internal/validator/validator.go index 7b90f1d..f388683 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 ( @@ -25,9 +26,9 @@ type ValidationError struct { 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) } // Validator checks ParsedSchema for logical consistency. @@ -998,11 +999,11 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx }) } case "boolean": - switch seedValue.(type) { + switch v := seedValue.(type) { case bool: // OK case string: - s := strings.ToLower(seedValue.(string)) + s := strings.ToLower(v) if s != "true" && s != "false" { errs = append(errs, ValidationError{ Entity: entityName, Field: fieldName, @@ -1038,7 +1039,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx } 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), + Message: fmt.Sprintf("seed entry %d: value %q is not a valid UUID (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s), }) } case "datetime": diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 0579f5b..f3a4b1c 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -1,3 +1,4 @@ +// Package logger provides the CLI's four-level console logger. package logger import ( @@ -33,9 +34,9 @@ func (l *Logger) Info(format string, args ...interface{}) { } msg := fmt.Sprintf(format, args...) if l.useColors { - fmt.Fprintf(l.writer, " \033[36m▸\033[0m %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " \033[36m▸\033[0m %s\n", msg) } else { - fmt.Fprintf(l.writer, " ▸ %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " ▸ %s\n", msg) } } @@ -47,9 +48,9 @@ func (l *Logger) Success(format string, args ...interface{}) { } msg := fmt.Sprintf(format, args...) if l.useColors { - fmt.Fprintf(l.writer, " \033[32m✓\033[0m %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " \033[32m✓\033[0m %s\n", msg) } else { - fmt.Fprintf(l.writer, " ✓ %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " ✓ %s\n", msg) } } @@ -61,9 +62,9 @@ func (l *Logger) Warn(format string, args ...interface{}) { } msg := fmt.Sprintf(format, args...) if l.useColors { - fmt.Fprintf(l.writer, " \033[33m⚠\033[0m %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " \033[33m⚠\033[0m %s\n", msg) } else { - fmt.Fprintf(l.writer, " ⚠ %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " ⚠ %s\n", msg) } } @@ -75,8 +76,8 @@ func (l *Logger) Error(format string, args ...interface{}) { } msg := fmt.Sprintf(format, args...) if l.useColors { - fmt.Fprintf(l.writer, " \033[31m✗\033[0m %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " \033[31m✗\033[0m %s\n", msg) } else { - fmt.Fprintf(l.writer, " ✗ %s\n", msg) + _, _ = fmt.Fprintf(l.writer, " ✗ %s\n", msg) } } From 396152c8f0055c319bdf91151a9153fb3a3a5c4a Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:23:11 +0300 Subject: [PATCH 02/83] Core: tighten paths and expand regression coverage --- .github/workflows/ci.yml | 3 + cmd/domaincraft/commands.go | 3 +- cmd/domaincraft/prune_test.go | 94 +++++++++++++++++++++++++ cmd/wasm-validator/main.go | 12 ++-- internal/bridge/meta_test.go | 46 ++++++++++++ internal/bridge/resolver.go | 4 +- internal/bridge/testhelpers_test.go | 54 ++++++++++++++ internal/ir/models.go | 2 +- internal/ir/query.go | 3 +- internal/ir/seed.go | 2 +- internal/parser/models.go | 2 +- internal/parser/parser.go | 2 +- internal/renderer/render.go | 28 +++++++- internal/renderer/templates.go | 6 +- internal/seed/seed.go | 22 +++--- internal/snapshot/snapshot.go | 3 +- internal/templatefuncs/templatefuncs.go | 42 +++++------ pkg/logger/logger.go | 8 +-- 18 files changed, 280 insertions(+), 56 deletions(-) create mode 100644 cmd/domaincraft/prune_test.go create mode 100644 internal/bridge/meta_test.go create mode 100644 internal/bridge/testhelpers_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebe7744..63bacdd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,6 +53,9 @@ jobs: - name: Test run: go test ./... + - name: Integration tests + run: go test -tags=integration ./internal/bridge + schema-check: name: Verify generated schema is up to date runs-on: ubuntu-latest diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index ec28299..524afd2 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -321,7 +321,8 @@ func runGenerate(cmd *cobra.Command, args []string) error { autoMigrate = false } shouldMigrate := migrateFlag || autoMigrate - if applied && shouldMigrate && rendererInstance.MigrationConfig() != nil && rendererInstance.MigrationConfig().Enabled { + cfg := rendererInstance.MigrationConfig() + if applied && shouldMigrate && cfg != nil && cfg.Enabled { if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), outputDir, cmd, log); err != nil { if migrateFlag { // Explicit --migrate: a failed migration is a hard error. diff --git a/cmd/domaincraft/prune_test.go b/cmd/domaincraft/prune_test.go new file mode 100644 index 0000000..3e53ee5 --- /dev/null +++ b/cmd/domaincraft/prune_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/DomainCraft/DomainCraft/internal/interactive" + "github.com/DomainCraft/DomainCraft/internal/snapshot" +) + +// TestApplyMigrationActionsRewritesFieldRenames covers the --prune branch that +// rewrites identifiers in developer-owned files. The CLI orchestration was +// previously untested, so a dropped field rename could leave stale names. +func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { + root := t.TempDir() + oldOutput, oldPrune := outputDir, prune + outputDir, prune = root, true + t.Cleanup(func() { + outputDir, prune = oldOutput, oldPrune + }) + + 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 out bytes.Buffer + cmd.SetOut(&out) + + applied, err := applyMigrationActions(diff, map[string]bool{}, nil, 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(out.String(), "updated field title -> name") { + t.Fatalf("missing report line: %q", out.String()) + } +} + +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) { + oldPrune := prune + prune = true + t.Cleanup(func() { prune = oldPrune }) + + selected, err := chooseMigrationFiles(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) { + oldPrune := prune + prune = false + t.Cleanup(func() { prune = oldPrune }) + + selected, err := chooseMigrationFiles(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) + } + }) +} diff --git a/cmd/wasm-validator/main.go b/cmd/wasm-validator/main.go index 315b551..a42f822 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -36,15 +36,15 @@ 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{} { +func specmetaFunc(_ js.Value, _ []js.Value) any { return marshal(specmeta.SpecmetaJSON()) } -func validate(_ js.Value, args []js.Value) interface{} { +func validate(_ js.Value, args []js.Value) any { if len(args) < 1 { return marshal(validationResult{ Errors: []validationError{{Message: "no YAML input provided"}}, @@ -70,7 +70,7 @@ func validate(_ js.Value, args []js.Value) interface{} { return marshal(validationResult{Errors: result}) } -func parseField(_ js.Value, args []js.Value) interface{} { +func parseField(_ js.Value, args []js.Value) any { if len(args) < 1 { return marshal(map[string]string{"error": "no field definition provided"}) } @@ -87,7 +87,7 @@ func parseField(_ js.Value, args []js.Value) interface{} { return marshal(fd) } -func parseDomain(_ js.Value, args []js.Value) interface{} { +func parseDomain(_ js.Value, args []js.Value) any { if len(args) < 1 { return marshal(map[string]string{"error": "no YAML input provided"}) } @@ -98,7 +98,7 @@ func parseDomain(_ js.Value, args []js.Value) interface{} { 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"}) 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/resolver.go b/internal/bridge/resolver.go index f5e8afe..e5c9215 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -65,7 +65,9 @@ func (r *Resolver) Resolve(input string) (string, error) { // 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] != ".." { + parts := strings.SplitN(input, "/", 2) + isOwnerRepo := len(parts) == 2 && parts[0] != "" && parts[1] != "" && parts[0] != "." && parts[0] != ".." + if isOwnerRepo { if strings.ContainsAny(parts[1], "/\\") || parts[1] == "." || parts[1] == ".." { return "", fmt.Errorf("bridge %q not found: invalid repository name", input) } diff --git a/internal/bridge/testhelpers_test.go b/internal/bridge/testhelpers_test.go new file mode 100644 index 0000000..446581e --- /dev/null +++ b/internal/bridge/testhelpers_test.go @@ -0,0 +1,54 @@ +package bridge + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "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") +} + +// 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} +} diff --git a/internal/ir/models.go b/internal/ir/models.go index 32c7078..29cc94d 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -154,7 +154,7 @@ type IREntity struct { RelationsOut []IRRelation RelationsIn []IRRelation Indexes []IRIndex - Seed []map[string]interface{} + Seed []map[string]any Permissions *IRPermissions } diff --git a/internal/ir/query.go b/internal/ir/query.go index d2eb047..b050e2b 100644 --- a/internal/ir/query.go +++ b/internal/ir/query.go @@ -101,8 +101,7 @@ func (e IREntity) SearchableFields() []IRField { // 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 + return f.isFilterableScalar() && !f.IsEnum() }) } diff --git a/internal/ir/seed.go b/internal/ir/seed.go index 206a946..ffc15ca 100644 --- a/internal/ir/seed.go +++ b/internal/ir/seed.go @@ -12,7 +12,7 @@ type SeedValue struct { 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) + Value any // native Go value (string, int64, float64, bool, []any, map, nil) } // Kind returns the language-agnostic value kind for serialization, derived from diff --git a/internal/parser/models.go b/internal/parser/models.go index a776a90..5b3ef93 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -134,7 +134,7 @@ type RawEntity struct { 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"` + Seed []map[string]any `yaml:"seed" json:"seed,omitempty"` } // RawPermissions represents entity permissions before parsing. diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 17b7cdc..f26cac4 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -38,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 diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 7417061..4560d20 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -15,6 +15,24 @@ import ( "github.com/DomainCraft/DomainCraft/internal/packages" ) +// safeBridgeSource resolves a template or helper path declared by bridge.yaml +// and rejects paths that escape the bridge directory. +func safeBridgeSource(dir, rel string) (string, error) { + if !filepath.IsLocal(rel) { + return "", fmt.Errorf("unsafe bridge source path %q", rel) + } + path := filepath.Join(dir, rel) + realDir, err := filepath.EvalSymlinks(dir) + if err != nil { + return "", fmt.Errorf("resolve bridge dir: %w", err) + } + if real, err := filepath.EvalSymlinks(path); err == nil && + real != realDir && !strings.HasPrefix(real, realDir+string(filepath.Separator)) { + return "", fmt.Errorf("bridge source path %q escapes the bridge directory", rel) + } + return path, nil +} + // Render renders the IR through every bridge in the chain and returns the // written paths and the file manifest. func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, []RenderedFile, error) { @@ -43,7 +61,10 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] if src.config.Helpers == "" { continue } - helperPath := filepath.Join(src.dir, src.config.Helpers) + helperPath, err := safeBridgeSource(src.dir, src.config.Helpers) + if err != nil { + return nil, nil, err + } helperBytes, err := os.ReadFile(helperPath) if err != nil { return nil, nil, fmt.Errorf("read helpers %s: %w", src.config.Helpers, err) @@ -67,7 +88,10 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] continue } - sourcePath := filepath.Join(src.dir, spec.Source) + sourcePath, err := safeBridgeSource(src.dir, spec.Source) + if err != nil { + return nil, nil, err + } tplBytes, err := os.ReadFile(sourcePath) if err != nil { return nil, nil, fmt.Errorf("read template %s: %w", spec.Source, err) diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index 8863a7e..ddecbd9 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -158,7 +158,7 @@ func mergeLiterals(base, overlay map[string]LiteralSpec) map[string]LiteralSpec // 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) @@ -173,8 +173,8 @@ func (r *Renderer) getBridgeSpecificFuncs() (map[string]interface{}, error) { // 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{}) +func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { + bridgeFuncs := make(map[string]any) if m == nil { return bridgeFuncs } diff --git a/internal/seed/seed.go b/internal/seed/seed.go index 3a397b4..60a0b77 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -42,7 +42,7 @@ 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{}{} + generated := map[string][]any{} counter := opts.Seed for i := range project.Entities { @@ -59,7 +59,7 @@ func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { if field.IsSensitive() || field.IsFeatureField() { continue } - v := valueFor(field, entity, project, generated, &counter, n) + v := valueFor(field, project, generated, &counter, n) rec.Fields = append(rec.Fields, ir.SeedValue{ Field: field.Name, DBType: field.DatabaseType, @@ -135,7 +135,7 @@ func primaryKey(entity *ir.IREntity) *ir.IRField { // 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(field ir.IRField, project *ir.IRProject, generated map[string][]any, counter *int, record int) any { // Default value wins when the model declares one (and it's not a function). if field.DefaultValue != "" && !field.DefaultIsFunc { return coerceValue(field.DefaultValue, field.DatabaseType) @@ -152,7 +152,7 @@ func valueFor(field ir.IRField, entity *ir.IREntity, project *ir.IRProject, gene // 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{} { +func relationValue(field ir.IRField, generated map[string][]any) any { if field.IsMany { return nil } @@ -164,13 +164,13 @@ func relationValue(field ir.IRField, generated map[string][]interface{}) interfa } // 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(field ir.IRField, project *ir.IRProject, counter *int, record int) any { dbType := field.DatabaseType if field.IsArray() { inner := specmeta.ParseArrayInner(dbType) elem := innerValue(inner, field, project, counter, record) - return []interface{}{elem} + return []any{elem} } switch dbType { @@ -201,7 +201,7 @@ 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{} { +func innerValue(dbType string, field ir.IRField, project *ir.IRProject, counter *int, record int) any { inner := ir.IRField{Name: field.Name, DatabaseType: dbType} if specmeta.IsPrimitive(strings.ToLower(dbType)) { return scalarValue(inner, project, counter, record) @@ -297,19 +297,19 @@ func floatValue(field ir.IRField, record int) float64 { // 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{}{} + return []any{} } switch { diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 7fc20e8..f26c6ba 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -187,7 +187,8 @@ type Diff struct { // 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 + hasNoChanges := len(d.Deleted) == 0 && len(d.Renamed) == 0 && len(d.TypeChanges) == 0 && len(d.FieldRenames) == 0 + return hasNoChanges && d.NamespaceRename == nil } // HasSchemaChanges reports whether the diff contains changes that must reach the diff --git a/internal/templatefuncs/templatefuncs.go b/internal/templatefuncs/templatefuncs.go index 6aee1ec..d48a67f 100644 --- a/internal/templatefuncs/templatefuncs.go +++ b/internal/templatefuncs/templatefuncs.go @@ -56,7 +56,7 @@ func FuncMap() template.FuncMap { } // 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 +65,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 @@ -81,14 +81,14 @@ func Atoi(s string) int { } // 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 +// []any. It panics on a non-slice, which text/template surfaces as a // render error. -func Append(list interface{}, v interface{}) []interface{} { +func Append(list any, v any) []any { 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() } @@ -137,17 +137,17 @@ 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) { @@ -165,31 +165,31 @@ 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 { d[key] = value return d } @@ -202,7 +202,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 +219,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 +245,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 +281,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) diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index f3a4b1c..bffcd7e 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -28,7 +28,7 @@ func (l *Logger) SetWriter(w io.Writer) { // 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 } @@ -42,7 +42,7 @@ func (l *Logger) Info(format string, args ...interface{}) { // 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 } @@ -56,7 +56,7 @@ func (l *Logger) Success(format string, args ...interface{}) { // 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 } @@ -70,7 +70,7 @@ func (l *Logger) Warn(format string, args ...interface{}) { // 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 } From f2a75dc5fe67d2c506e483a7b55a6fe47ac7d9ae Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:35:42 +0300 Subject: [PATCH 03/83] Core: finish hardening sweep --- internal/bridge/safety_test.go | 21 +- internal/bridge/update_contract_test.go | 8 +- internal/bridge/update_test.go | 86 +--- internal/interactive/prompts_test.go | 35 +- internal/interactive/theme_test.go | 19 +- internal/ir/contract_test.go | 24 +- internal/ir/dto_test.go | 10 +- internal/ir/enums_test.go | 41 +- internal/ir/models_test.go | 8 +- internal/ir/query_test.go | 56 ++- internal/ir/typekind_test.go | 154 +++--- internal/packages/cache_test.go | 83 ++++ internal/parser/integration_test.go | 13 +- internal/parser/parser_test.go | 37 +- internal/seed/seed_test.go | 40 +- internal/snapshot/snapshot_test.go | 9 +- internal/specmeta/specmeta_test.go | 126 +++-- internal/templatefuncs/templatefuncs_test.go | 14 +- internal/validator/validator.go | 464 ++++++++++--------- internal/validator/validator_test.go | 34 +- pkg/textutil/case_convert_test.go | 132 +++--- pkg/textutil/textutil_test.go | 152 +++--- 22 files changed, 855 insertions(+), 711 deletions(-) diff --git a/internal/bridge/safety_test.go b/internal/bridge/safety_test.go index 85ac5e1..038e102 100644 --- a/internal/bridge/safety_test.go +++ b/internal/bridge/safety_test.go @@ -45,21 +45,24 @@ func TestIsOfficialBundled(t *testing.T) { // 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 }{ - {"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 + {"plain", "owner/repo", "owner/repo", ""}, + {"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 { - 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) - } + 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_contract_test.go b/internal/bridge/update_contract_test.go index 09b5761..1274ca7 100644 --- a/internal/bridge/update_contract_test.go +++ b/internal/bridge/update_contract_test.go @@ -18,9 +18,11 @@ func TestParseBridgeContractVersion(t *testing.T) { {"garbage defaults to 1", "::: not yaml", 1}, } 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) { + if got := parseBridgeContractVersion([]byte(c.in)); got != c.want { + t.Errorf("%s: parseBridgeContractVersion = %d, want %d", c.name, got, c.want) + } + }) } } diff --git a/internal/bridge/update_test.go b/internal/bridge/update_test.go index 93119cf..53d533e 100644 --- a/internal/bridge/update_test.go +++ b/internal/bridge/update_test.go @@ -1,8 +1,9 @@ +//go:build integration + package bridge import ( "os" - "os/exec" "path/filepath" "strings" "testing" @@ -11,89 +12,6 @@ import ( "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. diff --git a/internal/interactive/prompts_test.go b/internal/interactive/prompts_test.go index 2a311b5..114e225 100644 --- a/internal/interactive/prompts_test.go +++ b/internal/interactive/prompts_test.go @@ -19,28 +19,31 @@ func setInput(s string) { 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) + } + }) } } diff --git a/internal/interactive/theme_test.go b/internal/interactive/theme_test.go index f615769..cc8de81 100644 --- a/internal/interactive/theme_test.go +++ b/internal/interactive/theme_test.go @@ -22,19 +22,22 @@ 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 } 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/contract_test.go b/internal/ir/contract_test.go index 88a1ef4..5d4a790 100644 --- a/internal/ir/contract_test.go +++ b/internal/ir/contract_test.go @@ -65,19 +65,21 @@ func TestValidationRulesCodesAndMessages(t *testing.T) { {"exclusive max_value", IRField{Name: "rating", DatabaseType: "int", Validations: []IRValidation{{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) { + 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) + } + }) } } diff --git a/internal/ir/dto_test.go b/internal/ir/dto_test.go index 07555b4..0815adc 100644 --- a/internal/ir/dto_test.go +++ b/internal/ir/dto_test.go @@ -18,10 +18,12 @@ 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) { + f := IRField{Name: tc.name} + if got := f.IsSensitive(); got != tc.want { + t.Errorf("IsSensitive(%q) = %v, want %v", tc.name, got, tc.want) + } + }) } } diff --git a/internal/ir/enums_test.go b/internal/ir/enums_test.go index d18501c..8987c29 100644 --- a/internal/ir/enums_test.go +++ b/internal/ir/enums_test.go @@ -15,24 +15,27 @@ 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) { + 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 { @@ -59,8 +62,10 @@ 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) { + if got := (IRIndex{Name: c.name}).DatabaseName(); got != c.want { + t.Errorf("DatabaseName(%q) = %q, want %q", c.name, got, c.want) + } + }) } } diff --git a/internal/ir/models_test.go b/internal/ir/models_test.go index 5136e55..455f415 100644 --- a/internal/ir/models_test.go +++ b/internal/ir/models_test.go @@ -171,9 +171,11 @@ func TestCanonicalNameContract(t *testing.T) { {"fallback re-derives from the name", IRField{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) { + if got := c.f.ColumnName(); got != c.want { + t.Errorf("%s: ColumnName() = %q, want %q", c.name, got, c.want) + } + }) } } diff --git a/internal/ir/query_test.go b/internal/ir/query_test.go index 8b8b5f7..9e01b2c 100644 --- a/internal/ir/query_test.go +++ b/internal/ir/query_test.go @@ -64,26 +64,29 @@ func TestSearchableSortableFilterableFields(t *testing.T) { func TestFilterOperators(t *testing.T) { 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) { + f := IRField{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) + } + }) } } @@ -147,21 +150,24 @@ func TestQuerySchema(t *testing.T) { func TestCursorField(t *testing.T) { 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) { + 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) + } + }) } // No PK -> nil. diff --git a/internal/ir/typekind_test.go b/internal/ir/typekind_test.go index 8983c16..ab2d9cd 100644 --- a/internal/ir/typekind_test.go +++ b/internal/ir/typekind_test.go @@ -4,95 +4,101 @@ import "testing" func TestIRFieldTypePredicates(t *testing.T) { cases := []struct { + name string dbType string 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) { + 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) + } + }) } } func TestIRFieldSpecificTypePredicates(t *testing.T) { cases := []struct { + name string dbType string isString, isBigInt, isDecimal 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) { + 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) + } + }) } } @@ -114,9 +120,11 @@ func TestIRFieldIsPatchable(t *testing.T) { {"feature", IRField{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) { + if got := c.f.IsPatchable(); got != c.want { + t.Errorf("%s IsPatchable() = %v, want %v", c.name, got, c.want) + } + }) } } diff --git a/internal/packages/cache_test.go b/internal/packages/cache_test.go index 3b7defb..321516d 100644 --- a/internal/packages/cache_test.go +++ b/internal/packages/cache_test.go @@ -150,6 +150,89 @@ func TestResolveVersionCachedStaleRefreshes(t *testing.T) { } } +// TestResolveVersionCachedTTLBoundary pins the 24h cutoff: just inside the TTL +// is a hit, just outside is a miss. +func TestResolveVersionCachedTTLBoundary(t *testing.T) { + key := cacheKey("https://reg.example/{id}", "demo.pkg") + + 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", key, "1.0.0", tt.storedAt) + + called := false + old := resolveVersionFn + resolveVersionFn = func(_, _ string) (string, error) { + called = true + return "2.0.0", nil + } + defer func() { resolveVersionFn = old }() + + got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + 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) + } + }) + } +} + +// TestResolveVersionCachedRegistryFailures covers the two paths where no +// version may be cached: a registry error and an empty result. +func TestResolveVersionCachedRegistryFailures(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 := resolveVersionFn + resolveVersionFn = func(_, _ string) (string, error) { return tt.version, tt.err } + defer func() { resolveVersionFn = old }() + + got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + 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 + resolveVersionFn = func(_, _ string) (string, error) { + called = true + return "3.0.0", nil + } + got, err = ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + 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) + } + }) + } +} + // TestResolveVersionCachedIsolation verifies caches are per bridge: a version // cached for one bridge is not served to another. func TestResolveVersionCachedIsolation(t *testing.T) { diff --git a/internal/parser/integration_test.go b/internal/parser/integration_test.go index 3b53d19..4b19216 100644 --- a/internal/parser/integration_test.go +++ b/internal/parser/integration_test.go @@ -1,6 +1,7 @@ package parser import ( + "fmt" "testing" ) @@ -304,12 +305,14 @@ 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) { + 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) + } } - } + }) } } diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index b32f61b..35b8db2 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -1,6 +1,7 @@ package parser import ( + "fmt" "strings" "testing" ) @@ -318,13 +319,15 @@ 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) { + // 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) + } + }) } } @@ -359,11 +362,13 @@ 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) { + 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) + } } - } + }) } } @@ -481,10 +486,12 @@ 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) { + f := order.Fields[tt.field] + if f.RelationType != tt.wantType { + t.Errorf("field %s: RelationType = %q, want %q", tt.field, f.RelationType, tt.wantType) + } + }) } } diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index 29ae41a..a235aa9 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -37,7 +37,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 +56,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 { @@ -85,7 +85,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 @@ -118,14 +118,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 +136,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,7 +149,7 @@ 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"]) } } @@ -158,7 +158,7 @@ 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"}}}, + {Name: "Seeded", Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, Seed: []map[string]any{{"id": "x"}}}, }, } ds := Normalize(project) @@ -176,7 +176,7 @@ func TestNormalizeIncludesRelationFlags(t *testing.T) { {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"}}, }, }, } @@ -208,8 +208,8 @@ func TestGenerateHonorsNumericBounds(t *testing.T) { } 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 } @@ -253,7 +253,7 @@ func TestGenerateHonorsStringValidations(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 } @@ -288,7 +288,7 @@ 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", @@ -296,8 +296,8 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { "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,7 +306,7 @@ 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 } @@ -322,14 +322,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" { @@ -352,7 +352,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/snapshot_test.go b/internal/snapshot/snapshot_test.go index e4006c6..e71dddf 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" @@ -152,9 +153,11 @@ 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) { + 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) + } + }) } } diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index 55c32db..c5a1286 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -1,5 +1,7 @@ package specmeta +import "fmt" + import "testing" func TestIsPrimitive(t *testing.T) { @@ -19,19 +21,21 @@ 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) { + got := IsPrimitive(tt.input) + if got != tt.want { + t.Errorf("IsPrimitive(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -65,9 +69,11 @@ 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) { + if got := IsNumeric(tt.input); got != tt.want { + t.Errorf("IsNumeric(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -83,9 +89,11 @@ 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) { + if got := IsStringType(tt.input); got != tt.want { + t.Errorf("IsStringType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -101,9 +109,11 @@ 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) { + if got := IsBooleanType(tt.input); got != tt.want { + t.Errorf("IsBooleanType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -121,9 +131,11 @@ 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) { + if got := IsIndexType(tt.input); got != tt.want { + t.Errorf("IsIndexType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -139,9 +151,11 @@ 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) { + if got := IsCacheProvider(tt.input); got != tt.want { + t.Errorf("IsCacheProvider(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -157,9 +171,11 @@ 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) { + if got := IsMultiTenancyMode(tt.input); got != tt.want { + t.Errorf("IsMultiTenancyMode(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -176,9 +192,11 @@ 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) { + if got := IsPermissionKey(tt.input); got != tt.want { + t.Errorf("IsPermissionKey(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -198,9 +216,11 @@ 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) { + if got := IsStringValidationModifier(tt.input); got != tt.want { + t.Errorf("IsStringValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -218,9 +238,11 @@ 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) { + if got := IsNumericValidationModifier(tt.input); got != tt.want { + t.Errorf("IsNumericValidationModifier(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -284,9 +306,11 @@ 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) { + if got := IsSortDirection(tt.input); got != tt.want { + t.Errorf("IsSortDirection(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -343,9 +367,11 @@ 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) { + if got := IsDatabase(tt.input); got != tt.want { + t.Errorf("IsDatabase(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -362,9 +388,11 @@ 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) { + if got := IsAPIStyle(tt.input); got != tt.want { + t.Errorf("IsAPIStyle(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } @@ -375,14 +403,16 @@ func TestIsAuthType(t *testing.T) { }{ {"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) { + if got := IsAuthType(tt.input); got != tt.want { + t.Errorf("IsAuthType(%q) = %v, want %v", tt.input, got, tt.want) + } + }) } } diff --git a/internal/templatefuncs/templatefuncs_test.go b/internal/templatefuncs/templatefuncs_test.go index cd3e5ca..aa0f6f5 100644 --- a/internal/templatefuncs/templatefuncs_test.go +++ b/internal/templatefuncs/templatefuncs_test.go @@ -47,19 +47,19 @@ func TestDefault(t *testing.T) { func TestDict(t *testing.T) { 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{}{} + d := map[string]any{} got := Set(d, "x", 7) if got["x"] != 7 { t.Errorf("Set = %v, want x=7", got) @@ -73,11 +73,11 @@ func TestListAppend(t *testing.T) { } l = Append(l, "a") l = Append(l, 2) - if !reflect.DeepEqual(l, []interface{}{"a", 2}) { + 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"}) { + if got := Append([]string{"x", "y"}, "z"); !reflect.DeepEqual(got, []any{"x", "y", "z"}) { t.Errorf("Append([]string) = %v, want [x y z]", got) } } @@ -93,8 +93,8 @@ func TestJoin(t *testing.T) { 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) diff --git a/internal/validator/validator.go b/internal/validator/validator.go index f388683..c0a8add 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -31,6 +31,26 @@ func (e ValidationError) Error() string { return fmt.Sprintf("entity %q: %s", e.Entity, e.Message) } +// invalid builds a non-warning validation error for an entity and field. +func invalid(entity, field, message string) ValidationError { + return ValidationError{Entity: entity, Field: field, Message: message} +} + +// warn builds a warning validation error for an entity and field. +func warn(entity, field, message string) ValidationError { + return ValidationError{Entity: entity, Field: field, Message: message, Warning: true} +} + +// invalidf builds a non-warning validation error with a formatted message. +func invalidf(entity, field, format string, args ...any) ValidationError { + return invalid(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 warn(entity, field, fmt.Sprintf(format, args...)) +} + // Validator checks ParsedSchema for logical consistency. type Validator struct { schema *parser.ParsedSchema @@ -59,7 +79,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)) } } } @@ -97,103 +118,129 @@ 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, ", "))}) + errs = append(errs, invalidf("", "", + "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 multi_tenancy.mode %q; allowed: %s", p.MultiTenancy.Mode, strings.Join(specmeta.MultiTenancyModes, ", "))) } } // 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, ", "))}) + errs = append(errs, invalidf("", "", + "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}) + errs = append(errs, warn("", "", + "cache.ttl_seconds must be non-negative")) } } 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}) + errs = append(errs, warn("", "", + "cache.provider or cache.connection_string specified but cache.enabled is false")) } 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}) + errs = append(errs, warnf("", "", + "cache.provider %q specified but cache.connection_string is empty", p.Cache.Provider)) } // 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)}) + 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, invalidf("", "", + "unknown rate_limit.policy %q; allowed: %s", p.RateLimit.Policy, strings.Join(specmeta.RateLimitPolicies, ", "))) } if p.RateLimit.PermitLimit < 0 { - errs = append(errs, ValidationError{Entity: "", Message: "rate_limit.permit_limit must be non-negative", Warning: true}) + errs = append(errs, warn("", "", + "rate_limit.permit_limit 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}) + errs = append(errs, warn("", "", + "rate_limit.window_seconds must be at least 1")) } } // 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}) + errs = append(errs, warn("", "", + "pagination.default_page_size must be at least 1")) } if p.Pagination.MaxPageSize < 1 { - errs = append(errs, ValidationError{Entity: "", Message: "pagination.max_page_size must be at least 1", Warning: true}) + errs = append(errs, warn("", "", + "pagination.max_page_size must be at least 1")) } 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}) + errs = append(errs, warnf("", "", + "pagination.default_page_size (%d) must not exceed max_page_size (%d)", p.Pagination.DefaultPageSize, + p.Pagination.MaxPageSize)) } } // 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, ", "))}) + errs = append(errs, invalidf("", "", + "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, ", "))}) + errs = append(errs, invalidf("", "", + "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, ", "))}) + errs = append(errs, invalidf("", "", + "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, ", "))}) + errs = append(errs, invalidf("", "", + "unknown infrastructure.storage %q; allowed: %s", p.Infrastructure.Storage, + strings.Join(specmeta.InfraStores, ", "))) } } @@ -276,11 +323,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 @@ -291,7 +335,8 @@ 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" { @@ -302,23 +347,28 @@ 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)}) + errs = append(errs, invalidf("", "", + "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 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, warnf("", "", + "auth.type is %q but no entity has both 'email' and 'password' fields; specify auth.entity explicitly", auth.Type)) } } // 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)}) + errs = append(errs, invalidf("", "", + "auth.roles: %q is not a valid identifier", role)) } } @@ -345,17 +395,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)) } } } @@ -397,20 +441,24 @@ 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"}) + 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)) 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}) + errs = append(errs, warnf("", name, + "duplicate enum value %q (case-insensitive collision)", val)) } seen[lower] = true } @@ -437,7 +485,8 @@ func (v *Validator) validateEnums() []ValidationError { } 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")) } } } @@ -452,28 +501,33 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit // 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"}) + errs = append(errs, invalid(entityName, "", + "entity name is not a valid identifier")) } // 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)}) + errs = append(errs, invalidf(entityName, "", + "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}) + errs = append(errs, warnf(entityName, "", + "duplicate feature %q", f)) } featureSeen[f] = true } @@ -497,21 +551,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 @@ -520,11 +573,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 } @@ -562,11 +612,8 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit } 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 } @@ -584,19 +631,17 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa // 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"}) + 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)) } } @@ -606,17 +651,21 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa // 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"}) + errs = append(errs, invalid(entityName, fieldName, + "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)}) + errs = append(errs, invalidf(entityName, fieldName, + "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"}) + 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, 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}) + 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")) } // 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, @@ -624,36 +673,37 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa 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, - }) + 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}) + 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, ValidationError{Entity: entityName, Field: fieldName, Message: "required relation has no on_delete specified; default behavior may not match expectations", Warning: true}) + errs = append(errs, warn(entityName, fieldName, + "required relation has no on_delete specified; default behavior may not match expectations")) } } // 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"}) + errs = append(errs, invalid(entityName, fieldName, + "primary key cannot be an array type")) } } // 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)}) + errs = append(errs, invalidf(entityName, fieldName, + "enum '%s' is not defined in enums section", field.TargetType)) } } @@ -662,7 +712,8 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa 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)}) + errs = append(errs, invalidf(entityName, fieldName, + "array element type '%s' is not a primitive or defined enum", field.TargetType)) } } } @@ -674,16 +725,19 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa 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}) + 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)) } // 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 != "" { 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)) } } } @@ -709,7 +763,9 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } 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, ", "))) } } } @@ -722,23 +778,28 @@ func validateDefaultValue(entityName, fieldName, ftype, defaultVal string) []Val 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}) + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not valid for numeric type %s", defaultVal, ftype)) } 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}) + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not valid for boolean (expected true/false)", defaultVal)) } 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}) + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not a valid date (expected YYYY-MM-DD)", defaultVal)) } 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}) + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", defaultVal)) } 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}) + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not a valid UUID", defaultVal)) } } return errs @@ -749,7 +810,8 @@ func validateFuncDefault(entityName, fieldName, ftype, funcName string) []Valida 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 @@ -760,13 +822,15 @@ func validateFuncDefault(entityName, fieldName, ftype, funcName string) []Valida } } 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, field *parser.ParsedField, + isNumeric, isString bool) []ValidationError { var errs []ValidationError getFloat := func(key string) (float64, bool) { @@ -785,11 +849,8 @@ func validateContradictoryRanges(entityName, fieldName string, field *parser.Par 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 (%.0f) is greater than max (%.0f)", minVal, maxVal)) } } @@ -798,21 +859,15 @@ func validateContradictoryRanges(entityName, fieldName string, field *parser.Par 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "validation gt (%.0f) must be less than lte (%.0f)", gtVal, lteVal)) } } @@ -833,42 +888,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)}) + errs = append(errs, invalidf(entityName, f, + "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, 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, ", "))) } } @@ -883,7 +946,8 @@ 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) @@ -891,7 +955,8 @@ func (v *Validator) validatePermissions(entityName string, perms *parser.ParsedP 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}) + errs = append(errs, warnf(entityName, "", + "permission '%s' role %q is not a valid identifier", operation, role)) } } } @@ -906,17 +971,15 @@ 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 // Check that seed fields exist. for seedField := range entry { 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)) } } @@ -943,11 +1006,9 @@ 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)) } } @@ -955,7 +1016,8 @@ func (v *Validator) validateSeedEntry(entityName string, entity *parser.ParsedEn } // 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(entityName, fieldName string, entryIdx int, + field *parser.ParsedField, seedValue any) []ValidationError { var errs []ValidationError ftype := strings.ToLower(field.Type) @@ -963,16 +1025,12 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx case "string", "text": // 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), - }) + if _, isMap := seedValue.(map[string]any); isMap { + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) + } else if _, isSlice := seedValue.([]any); isSlice { + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } case "int", "bigint": switch seedValue.(type) { @@ -981,10 +1039,8 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } case "float", "decimal": switch seedValue.(type) { @@ -993,10 +1049,8 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } case "boolean": switch v := seedValue.(type) { @@ -1005,75 +1059,56 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx case string: s := strings.ToLower(v) 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not valid for boolean type", entryIdx, 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with boolean type", entryIdx, seedValue)) } case "date": s, ok := 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with date type (expected string YYYY-MM-DD)", entryIdx, 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid date (expected YYYY-MM-DD)", entryIdx, s)) } case "uuid": s, ok := 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with uuid type (expected string)", entryIdx, 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 (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid UUID (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s)) } case "datetime": s, ok := 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with datetime type (expected string)", entryIdx, 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", entryIdx, + s)) } case "json", "jsonb": // 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not valid JSON", entryIdx, s)) } } case "enum": // The value must be one of the declared enum values. sv, ok := 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with enum type (expected string)", entryIdx, seedValue)) break } if values, defined := v.schema.Enums[field.TargetType]; defined { @@ -1085,31 +1120,26 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx } } 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, ", ")), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a declared value of enum '%s'; valid values: %s", entryIdx, sv, field.TargetType, + strings.Join(values, ", "))) } } case "array": // Accept a YAML list. String values are accepted as JSON arrays. switch v := seedValue.(type) { - case []interface{}: + case []any: // OK — list of elements case []string: // OK 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid JSON array for array type", entryIdx, v)) } 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with array type (expected a list)", entryIdx, seedValue)) } case "relation": // FK values reference the target entity's PK. Accept scalar values @@ -1119,10 +1149,8 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx 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), - }) + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with relation FK type", entryIdx, seedValue)) } } @@ -1135,7 +1163,7 @@ func isValidDate(s string) bool { } func isValidJSONArray(s string) bool { - var arr []interface{} + var arr []any return json.Unmarshal([]byte(s), &arr) == nil } @@ -1170,7 +1198,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_test.go b/internal/validator/validator_test.go index d51069e..03f3e1b 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -1240,7 +1240,7 @@ func TestValidateSeedValueTypeMismatch(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "age": mustParsedField(t, "age", "int"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "age": true}, }, }, @@ -1273,7 +1273,7 @@ func TestValidateSeedBooleanTypeMismatch(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "enabled": mustParsedField(t, "enabled", "boolean"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "enabled": "notabool"}, }, }, @@ -1510,7 +1510,7 @@ func TestValidateSeedUniqueConstraintViolation(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "email": mustParsedField(t, "email", "string [unique]"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, {"id": "22222222-2222-2222-2222-222222222222", "email": "a@test.com"}, }, @@ -1544,7 +1544,7 @@ func TestValidateSeedUniqueConstraintPass(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "email": mustParsedField(t, "email", "string [unique]"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, {"id": "22222222-2222-2222-2222-222222222222", "email": "b@test.com"}, }, @@ -1573,7 +1573,7 @@ func TestValidateSeedInvalidUUID(t *testing.T) { Fields: map[string]*parser.ParsedField{ "id": mustParsedField(t, "id", "uuid [primary]"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "not-a-uuid"}, }, }, @@ -1605,7 +1605,7 @@ func TestValidateSeedValidUUID(t *testing.T) { Fields: map[string]*parser.ParsedField{ "id": mustParsedField(t, "id", "uuid [primary]"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000"}, }, }, @@ -1634,7 +1634,7 @@ func TestValidateSeedInvalidDatetime(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "createdAt": mustParsedField(t, "createdAt", "datetime"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "not-a-date"}, }, }, @@ -1667,7 +1667,7 @@ func TestValidateSeedValidDatetime(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "createdAt": mustParsedField(t, "createdAt", "datetime"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "2024-01-15T10:30:00Z"}, }, }, @@ -1696,7 +1696,7 @@ func TestValidateSeedInvalidJSON(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "metadata": mustParsedField(t, "metadata", "json"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": "{invalid json}"}, }, }, @@ -1729,7 +1729,7 @@ func TestValidateSeedValidJSON(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "metadata": mustParsedField(t, "metadata", "json"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": `{"key":"value"}`}, }, }, @@ -1817,7 +1817,7 @@ func TestValidateSeedDateTypeMismatch(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "started_on": mustParsedField(t, "started_on", "date"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "not-a-date"}, }, }, @@ -1850,7 +1850,7 @@ func TestValidateSeedDateValid(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "started_on": mustParsedField(t, "started_on", "date"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "2024-05-01"}, }, }, @@ -1882,7 +1882,7 @@ func TestValidateSeedEnumInvalidValue(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "status": mustParsedField(t, "status", "enum(Status)"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "BOGUS"}, }, }, @@ -1918,7 +1918,7 @@ func TestValidateSeedEnumValidValue(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "status": mustParsedField(t, "status", "enum(Status)"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "ACTIVE"}, }, }, @@ -1947,7 +1947,7 @@ func TestValidateSeedArrayInvalidValue(t *testing.T) { "id": mustParsedField(t, "id", "uuid [primary]"), "tags": mustParsedField(t, "tags", "array(string)"), }, - Seed: []map[string]interface{}{ + Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": "not-json"}, }, }, @@ -1980,8 +1980,8 @@ func TestValidateSeedArrayValidValue(t *testing.T) { "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"}}, + Seed: []map[string]any{ + {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": []any{"a", "b"}}, }, }, }, diff --git a/pkg/textutil/case_convert_test.go b/pkg/textutil/case_convert_test.go index ebbd59f..86ee0e6 100644 --- a/pkg/textutil/case_convert_test.go +++ b/pkg/textutil/case_convert_test.go @@ -3,58 +3,70 @@ 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"}, + 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) { + 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"}, + 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) { + if got := KebabCase(c.in); got != c.want { + t.Errorf("KebabCase(%q) = %q, want %q", c.in, got, c.want) + } + }) } } @@ -62,30 +74,36 @@ 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"}, + 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) { + 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_test.go b/pkg/textutil/textutil_test.go index 3c72108..6e4c55b 100644 --- a/pkg/textutil/textutil_test.go +++ b/pkg/textutil/textutil_test.go @@ -4,128 +4,146 @@ import "testing" func TestPluralize(t *testing.T) { 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) { + 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) { 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) { + 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) { 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) { + 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) { 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) { + 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) { 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 { - 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) { + got := CamelCase(tt.input) + if got != tt.want { + t.Errorf("CamelCase(%q) = %q, want %q", tt.input, got, tt.want) + } + }) } } func TestSplitIdentifier(t *testing.T) { 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) { + 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]) + } } - } + }) } } From a32e3564696fe054d3e7f0f52a93f6651db3ba1e Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:39:31 +0300 Subject: [PATCH 04/83] Core: gate bridge commands and propagate cancellation --- cmd/domaincraft/commands.go | 40 ++++++++++++++++++++++++----------- cmd/domaincraft/main.go | 12 +++++++++++ cmd/domaincraft/prune_test.go | 21 ++++++++++++++++++ internal/bridge/clone.go | 2 +- internal/bridge/context.go | 14 ++++++++++++ internal/bridge/update.go | 2 +- 6 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 internal/bridge/context.go diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index 524afd2..f22ca77 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -15,6 +15,7 @@ package main import ( "cmp" + "context" "encoding/json" "fmt" "io" @@ -44,17 +45,21 @@ import ( ) 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 + 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 + allowBridgeCommands bool // explicit consent to run shell lines declared by community bridges + replaceFlags []string + + // commandCtx is cancelled on interrupt so child processes are not orphaned. + commandCtx = context.Background() // 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). @@ -180,6 +185,7 @@ func newGenerateCmd() *cobra.Command { 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)") // --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().BoolVar(&allowBridgeCommands, "allow-bridge-commands", false, "allow shell commands declared by community bridges (required with --migrate or automatic --prune migrations)") cmd.Flags().StringArrayVar(&replaceFlags, "replace", nil, "replace a bridge in the extends chain: layer=bridgeRef or bridgeId=bridgeRef (repeatable)") return cmd @@ -323,6 +329,9 @@ func runGenerate(cmd *cobra.Command, args []string) error { shouldMigrate := migrateFlag || autoMigrate cfg := rendererInstance.MigrationConfig() if applied && shouldMigrate && cfg != nil && cfg.Enabled { + if !bridgeCommandsAllowed(chainHasCommunity, allowBridgeCommands) { + return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") + } if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), outputDir, cmd, log); err != nil { if migrateFlag { // Explicit --migrate: a failed migration is a hard error. @@ -810,6 +819,13 @@ func generateAdminPanel(irProject *ir.IRProject, seedData, mockDataset *ir.SeedD return adminManifest, 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 @@ -836,7 +852,7 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co shell = "sh" argv = []string{"-c", command} } - c := exec.Command(shell, argv...) + c := exec.CommandContext(commandCtx, shell, argv...) c.Dir = outDir c.Stdout = out c.Stderr = out diff --git a/cmd/domaincraft/main.go b/cmd/domaincraft/main.go index 736ef31..07f3862 100644 --- a/cmd/domaincraft/main.go +++ b/cmd/domaincraft/main.go @@ -1,5 +1,17 @@ package main +import ( + "context" + "os" + "os/signal" + + "github.com/DomainCraft/DomainCraft/internal/bridge" +) + func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + commandCtx = ctx + bridge.SetCommandContext(ctx) Execute() } diff --git a/cmd/domaincraft/prune_test.go b/cmd/domaincraft/prune_test.go index 3e53ee5..afc984c 100644 --- a/cmd/domaincraft/prune_test.go +++ b/cmd/domaincraft/prune_test.go @@ -59,6 +59,27 @@ func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { } } +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"}} diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index 317d0f7..aeaf6f2 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -201,7 +201,7 @@ func CloneBridge(entry RegistryEntry) error { } url := fmt.Sprintf("https://github.com/%s.git", entry.GitHub) - cmd := exec.Command("git", "clone", "--depth", "1", url, cacheDir) + cmd := exec.CommandContext(commandCtx, "git", "clone", "--depth", "1", url, cacheDir) if out, err := cmd.CombinedOutput(); err != nil { _ = os.RemoveAll(cacheDir) return fmt.Errorf("clone %s: %w: %s", url, err, out) diff --git a/internal/bridge/context.go b/internal/bridge/context.go new file mode 100644 index 0000000..72b84d2 --- /dev/null +++ b/internal/bridge/context.go @@ -0,0 +1,14 @@ +package bridge + +import "context" + +// commandCtx is cancelled on interrupt so git children started by bridge +// resolution and updates are never orphaned. main wires the signal context. +var commandCtx = context.Background() + +// SetCommandContext wires the CLI's cancellable context into bridge operations. +func SetCommandContext(ctx context.Context) { + if ctx != nil { + commandCtx = ctx + } +} diff --git a/internal/bridge/update.go b/internal/bridge/update.go index 6832962..a71b14c 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -239,7 +239,7 @@ 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...) + cmd := exec.CommandContext(commandCtx, "git", args...) cmd.Dir = dir cmd.Env = gitScrubbedEnv() out, err := cmd.Output() From 5cd6954b34ef131d108ea5559c6f99f1a30009c9 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:48:01 +0300 Subject: [PATCH 05/83] Tests: parallelize suite and align test file names --- ...tends_test.go => commands_extends_test.go} | 0 .../{init_test.go => commands_init_test.go} | 0 .../{lock_test.go => commands_lock_test.go} | 0 ...notify_test.go => commands_notify_test.go} | 0 .../{prune_test.go => commands_prune_test.go} | 0 ...update_test.go => commands_update_test.go} | 0 cmd/domaincraft/commands_version_test.go | 23 ++++++ cmd/domaincraft/version_test.go | 23 ------ compliance-suite/regressions.tsv | 8 +- .../bridge/{id_test.go => clone_id_test.go} | 0 .../{policy_test.go => clone_policy_test.go} | 0 ...status_test.go => registry_status_test.go} | 0 internal/bridge/resolver_test.go | 12 +-- .../{safety_test.go => update_safety_test.go} | 0 internal/contract/golden_test.go | 4 + internal/fsutil/json_compat_test.go | 41 ++++++++++ internal/ir/build_entities.go | 2 +- ...builder_test.go => build_entities_test.go} | 16 ++++ internal/ir/build_relations.go | 2 +- internal/ir/contract_test.go | 15 ++++ internal/ir/dto_test.go | 25 +++++-- internal/ir/enums_test.go | 5 ++ internal/ir/models_test.go | 16 ++++ internal/ir/query_test.go | 8 ++ internal/ir/seed.go | 10 +-- internal/ir/toposort.go | 2 +- internal/ir/typekind_test.go | 11 +++ internal/lexer/lexer_test.go | 45 ++++++++--- internal/parser/integration_test.go | 7 ++ internal/parser/models.go | 14 ++-- internal/parser/parser_test.go | 25 +++++++ internal/renderer/bridgefuncs_test.go | 11 +++ internal/renderer/bundled_bridges_test.go | 1 + internal/renderer/contract_test.go | 4 + .../{renderer_test.go => render_test.go} | 18 +++++ internal/renderer/templates.go | 2 +- internal/renderer/version_test.go | 5 ++ internal/seed/seed_test.go | 9 +++ internal/snapshot/migration_test.go | 5 ++ internal/snapshot/paths_test.go | 4 + internal/snapshot/rewrite_test.go | 8 ++ internal/snapshot/snapshot_test.go | 22 ++++++ internal/specmeta/specmeta_test.go | 36 +++++++++ internal/templatefuncs/templatefuncs_test.go | 16 ++++ internal/validator/validator_test.go | 74 +++++++++++++++++++ pkg/textutil/case_convert_test.go | 6 ++ pkg/textutil/textutil_test.go | 16 +++- 47 files changed, 483 insertions(+), 68 deletions(-) rename cmd/domaincraft/{extends_test.go => commands_extends_test.go} (100%) rename cmd/domaincraft/{init_test.go => commands_init_test.go} (100%) rename cmd/domaincraft/{lock_test.go => commands_lock_test.go} (100%) rename cmd/domaincraft/{notify_test.go => commands_notify_test.go} (100%) rename cmd/domaincraft/{prune_test.go => commands_prune_test.go} (100%) rename cmd/domaincraft/{update_test.go => commands_update_test.go} (100%) create mode 100644 cmd/domaincraft/commands_version_test.go delete mode 100644 cmd/domaincraft/version_test.go rename internal/bridge/{id_test.go => clone_id_test.go} (100%) rename internal/bridge/{policy_test.go => clone_policy_test.go} (100%) rename internal/bridge/{status_test.go => registry_status_test.go} (100%) rename internal/bridge/{safety_test.go => update_safety_test.go} (100%) create mode 100644 internal/fsutil/json_compat_test.go rename internal/ir/{builder_test.go => build_entities_test.go} (99%) rename internal/renderer/{renderer_test.go => render_test.go} (98%) diff --git a/cmd/domaincraft/extends_test.go b/cmd/domaincraft/commands_extends_test.go similarity index 100% rename from cmd/domaincraft/extends_test.go rename to cmd/domaincraft/commands_extends_test.go diff --git a/cmd/domaincraft/init_test.go b/cmd/domaincraft/commands_init_test.go similarity index 100% rename from cmd/domaincraft/init_test.go rename to cmd/domaincraft/commands_init_test.go diff --git a/cmd/domaincraft/lock_test.go b/cmd/domaincraft/commands_lock_test.go similarity index 100% rename from cmd/domaincraft/lock_test.go rename to cmd/domaincraft/commands_lock_test.go diff --git a/cmd/domaincraft/notify_test.go b/cmd/domaincraft/commands_notify_test.go similarity index 100% rename from cmd/domaincraft/notify_test.go rename to cmd/domaincraft/commands_notify_test.go diff --git a/cmd/domaincraft/prune_test.go b/cmd/domaincraft/commands_prune_test.go similarity index 100% rename from cmd/domaincraft/prune_test.go rename to cmd/domaincraft/commands_prune_test.go diff --git a/cmd/domaincraft/update_test.go b/cmd/domaincraft/commands_update_test.go similarity index 100% rename from cmd/domaincraft/update_test.go rename to cmd/domaincraft/commands_update_test.go diff --git a/cmd/domaincraft/commands_version_test.go b/cmd/domaincraft/commands_version_test.go new file mode 100644 index 0000000..403a794 --- /dev/null +++ b/cmd/domaincraft/commands_version_test.go @@ -0,0 +1,23 @@ +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/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/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index b5b8ac4..3961fe7 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -11,13 +11,13 @@ internal/validator/validator_test.go::TestExampleDomainHasNoWarnings #3 shipped 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/bridge/id_test.go::TestValidateCacheIDRejectsEscapes #5 owner/repo id escaped the bridge cache and could delete an arbitrary path +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 internal/snapshot/paths_test.go::TestDeleteFileRejectsSnapshotEscape #5 poisoned snapshot path deleted a file outside the output dir internal/snapshot/paths_test.go::TestRewriteFileRejectsSnapshotEscape #5 poisoned snapshot path rewrote a file outside the output dir internal/packages/registry_test.go::TestValidateRegistryURLRejectsInternalTargets #5 bridge.yaml registry_url allowed requests to internal addresses -cmd/domaincraft/notify_test.go::TestCachedLatestCoreVersionCachesFailedCheck #5 offline update check repeated the full HTTP timeout on every command +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/policy_test.go::TestMaybeUpdatePolicies #5 bridge update policy decisions had no regression coverage -internal/bridge/policy_test.go::TestApplyUpdateRejectsUnsupportedContract #5 apply path could hard-reset a bridge with an unsupported contract version +internal/bridge/clone_policy_test.go::TestMaybeUpdatePolicies #5 bridge update policy decisions had no regression coverage +internal/bridge/clone_policy_test.go::TestApplyUpdateRejectsUnsupportedContract #5 apply path could hard-reset a bridge with an unsupported contract version internal/snapshot/rewrite_test.go::TestRewriteEntityContent #5 inner identifiers such as myProduct were not protected from rename rewrite diff --git a/internal/bridge/id_test.go b/internal/bridge/clone_id_test.go similarity index 100% rename from internal/bridge/id_test.go rename to internal/bridge/clone_id_test.go diff --git a/internal/bridge/policy_test.go b/internal/bridge/clone_policy_test.go similarity index 100% rename from internal/bridge/policy_test.go rename to internal/bridge/clone_policy_test.go diff --git a/internal/bridge/status_test.go b/internal/bridge/registry_status_test.go similarity index 100% rename from internal/bridge/status_test.go rename to internal/bridge/registry_status_test.go diff --git a/internal/bridge/resolver_test.go b/internal/bridge/resolver_test.go index 7999e71..26c83fe 100644 --- a/internal/bridge/resolver_test.go +++ b/internal/bridge/resolver_test.go @@ -55,12 +55,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 { diff --git a/internal/bridge/safety_test.go b/internal/bridge/update_safety_test.go similarity index 100% rename from internal/bridge/safety_test.go rename to internal/bridge/update_safety_test.go diff --git a/internal/contract/golden_test.go b/internal/contract/golden_test.go index 983c9dc..8cac6dd 100644 --- a/internal/contract/golden_test.go +++ b/internal/contract/golden_test.go @@ -157,9 +157,11 @@ func manifestLines(m map[string]string) []string { // 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 { t.Run(id, func(t *testing.T) { + t.Parallel() got := strings.Join(manifestLines(renderChain(t, []string{bridgeDir(t, id)}, proj)), "\n") goldenPath := filepath.Join("testdata", id+".golden.txt") if *updateGolden { @@ -188,6 +190,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 +198,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/fsutil/json_compat_test.go b/internal/fsutil/json_compat_test.go new file mode 100644 index 0000000..9af0fd3 --- /dev/null +++ b/internal/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/ir/build_entities.go b/internal/ir/build_entities.go index 428df91..8b9a6f8 100644 --- a/internal/ir/build_entities.go +++ b/internal/ir/build_entities.go @@ -298,4 +298,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 99% rename from internal/ir/builder_test.go rename to internal/ir/build_entities_test.go index 8512ec1..a46e078 100644 --- a/internal/ir/builder_test.go +++ b/internal/ir/build_entities_test.go @@ -9,6 +9,7 @@ import ( ) func TestBuildCreatesRelations(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -65,6 +66,7 @@ func TestBuildCreatesRelations(t *testing.T) { } func TestBuildResolvesEnumTypes(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -109,6 +111,7 @@ func TestBuildResolvesEnumTypes(t *testing.T) { } func TestBuildResolvesPrimitiveTypes(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -169,6 +172,7 @@ func mustParsedField(t *testing.T, name, input string) *parser.ParsedField { } func TestNavigationNameStripsIdSuffix(t *testing.T) { + t.Parallel() tests := []struct { name string field *parser.ParsedField @@ -207,6 +211,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 +221,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", @@ -243,6 +249,7 @@ func TestBuildCopiesDescription(t *testing.T) { } func TestBuildCopiesFeaturesMap(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -290,6 +297,7 @@ func TestBuildCopiesFeaturesMap(t *testing.T) { } func TestBuildCircularDependency(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -328,6 +336,7 @@ func TestBuildCircularDependency(t *testing.T) { } func TestBuildCopiesDatabaseColumnName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Database: "postgresql", @@ -368,6 +377,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", @@ -409,6 +419,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", @@ -563,6 +574,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", @@ -643,6 +655,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", @@ -740,6 +753,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", @@ -797,6 +811,7 @@ func TestBuildPairNavigationNameStripsIdSuffix(t *testing.T) { } func TestBuildConvertsAuthAndValidations(t *testing.T) { + t.Parallel() disabled := false schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Shop"}, @@ -878,6 +893,7 @@ func TestBuildConvertsAuthAndValidations(t *testing.T) { } func TestBuildWithoutAuthYieldsNilAuth(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Plain"}, Database: "postgresql", diff --git a/internal/ir/build_relations.go b/internal/ir/build_relations.go index 688ab79..3d0335c 100644 --- a/internal/ir/build_relations.go +++ b/internal/ir/build_relations.go @@ -172,4 +172,4 @@ func hasForwardManyTo(target *IREntity, entityName string) bool { } } return false -} \ No newline at end of file +} diff --git a/internal/ir/contract_test.go b/internal/ir/contract_test.go index 5d4a790..47fb5f7 100644 --- a/internal/ir/contract_test.go +++ b/internal/ir/contract_test.go @@ -3,6 +3,7 @@ package ir import "testing" func TestValidationRules(t *testing.T) { + t.Parallel() f := IRField{ Name: "email", DatabaseType: "string", @@ -33,6 +34,7 @@ func TestValidationRules(t *testing.T) { } func TestValidationRulesNumericBounds(t *testing.T) { + t.Parallel() f := IRField{ Name: "qty", DatabaseType: "int", @@ -51,6 +53,7 @@ func TestValidationRulesNumericBounds(t *testing.T) { } func TestValidationRulesCodesAndMessages(t *testing.T) { + t.Parallel() cases := []struct { name string field IRField @@ -66,6 +69,7 @@ func TestValidationRulesCodesAndMessages(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() rules := c.field.ValidationRules() found := false for _, r := range rules { @@ -84,6 +88,7 @@ func TestValidationRulesCodesAndMessages(t *testing.T) { } func TestValidationRulesNullableNotRequired(t *testing.T) { + t.Parallel() f := IRField{Name: "nick", DatabaseType: "string", IsNullable: true} for _, r := range f.ValidationRules() { if r.Kind == "required" { @@ -93,6 +98,7 @@ func TestValidationRulesNullableNotRequired(t *testing.T) { } func TestAllIndexesMergesUniqueFields(t *testing.T) { + t.Parallel() e := IREntity{ Name: "Order", NamePlural: "Orders", @@ -127,6 +133,7 @@ func TestAllIndexesMergesUniqueFields(t *testing.T) { } func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { + t.Parallel() e := IREntity{ Name: "Order", NamePlural: "Orders", @@ -143,6 +150,7 @@ func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { } func TestPermissionPlan(t *testing.T) { + t.Parallel() p := &IRPermissions{ Read: []string{"*"}, Create: []string{"Admin", "@Owner"}, @@ -171,6 +179,7 @@ func TestPermissionPlan(t *testing.T) { } func TestPermissionPlanNil(t *testing.T) { + t.Parallel() var p *IRPermissions if p.Plan("read") != nil { t.Error("nil permissions should yield nil plan") @@ -178,6 +187,7 @@ func TestPermissionPlanNil(t *testing.T) { } func TestEndpointsContract(t *testing.T) { + t.Parallel() e := IREntity{Name: "Order", NamePlural: "Orders", Features: map[string]bool{"optimistic_lock": true}} eps := e.Endpoints() if len(eps) != 6 { @@ -211,6 +221,7 @@ func TestEndpointsContract(t *testing.T) { } func TestIREntity_PrimaryKey(t *testing.T) { + t.Parallel() e := IREntity{Fields: []IRField{{Name: "name"}, {Name: "id", IsPrimary: true}}} pk := e.PrimaryKey() if pk == nil || pk.Name != "id" { @@ -222,6 +233,7 @@ func TestIREntity_PrimaryKey(t *testing.T) { } func TestIREntity_FieldByName(t *testing.T) { + t.Parallel() e := IREntity{Fields: []IRField{{Name: "firstName"}, {Name: "ID"}}} if f := e.FieldByName("FirstName"); f == nil || f.Name != "firstName" { t.Errorf("FieldByName(FirstName) = %v, want firstName (case-insensitive)", f) @@ -235,6 +247,7 @@ func TestIREntity_FieldByName(t *testing.T) { } func TestIRProject_AuthEntity(t *testing.T) { + t.Parallel() p := &IRProject{ Auth: &IRAuthConfig{Type: "jwt", Entity: "User"}, Entities: []IREntity{{Name: "Order"}, {Name: "User"}}, @@ -253,6 +266,7 @@ func TestIRProject_AuthEntity(t *testing.T) { } func TestIRPermissions_HasOwnerToken(t *testing.T) { + t.Parallel() if (&IRPermissions{Read: []string{"Admin"}, Create: []string{"*"}}).HasOwnerToken() { t.Error("no @Owner token should yield false") } @@ -266,6 +280,7 @@ func TestIRPermissions_HasOwnerToken(t *testing.T) { } func TestAuthEndpoints(t *testing.T) { + t.Parallel() p := &IRProject{Auth: &IRAuthConfig{ Type: "jwt", Entity: "User", diff --git a/internal/ir/dto_test.go b/internal/ir/dto_test.go index 0815adc..d8276c7 100644 --- a/internal/ir/dto_test.go +++ b/internal/ir/dto_test.go @@ -7,6 +7,7 @@ func entityWithFields(fields ...IRField) IREntity { } func TestIRField_IsSensitive(t *testing.T) { + t.Parallel() cases := []struct { name string want bool @@ -19,6 +20,7 @@ func TestIRField_IsSensitive(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { + t.Parallel() f := IRField{Name: tc.name} if got := f.IsSensitive(); got != tc.want { t.Errorf("IsSensitive(%q) = %v, want %v", tc.name, got, tc.want) @@ -28,6 +30,7 @@ func TestIRField_IsSensitive(t *testing.T) { } func TestIRField_IsFeatureField(t *testing.T) { + t.Parallel() if !(IRField{Name: "createdAt"}).IsFeatureField() { t.Error("createdAt should be a feature field") } @@ -40,6 +43,7 @@ func TestIRField_IsFeatureField(t *testing.T) { } func TestIRField_IsConcurrencyToken(t *testing.T) { + t.Parallel() if !(IRField{Name: "version"}).IsConcurrencyToken() { t.Error("version should be a concurrency token") } @@ -49,6 +53,7 @@ func TestIRField_IsConcurrencyToken(t *testing.T) { } func TestIREntity_ReadFields(t *testing.T) { + t.Parallel() e := entityWithFields( IRField{Name: "id", IsPrimary: true, DatabaseType: "uuid"}, IRField{Name: "title", DatabaseType: "string"}, @@ -69,6 +74,7 @@ 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"}, @@ -89,6 +95,7 @@ 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"}, @@ -114,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: "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 + 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 ) got := e.PatchFields() want := []string{"title", "categoryId", "version"} @@ -139,6 +147,7 @@ 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"}, diff --git a/internal/ir/enums_test.go b/internal/ir/enums_test.go index 8987c29..86f53b6 100644 --- a/internal/ir/enums_test.go +++ b/internal/ir/enums_test.go @@ -3,6 +3,7 @@ package ir import "testing" func TestEnumValuesWireValue(t *testing.T) { + t.Parallel() p := &IRProject{ Enums: map[string][]string{ "OrderStatus": {"PENDING", "IN_PROGRESS", "Shipped"}, @@ -26,6 +27,7 @@ func TestEnumValuesWireValue(t *testing.T) { } for _, c := range cases { 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) } @@ -47,6 +49,7 @@ func TestEnumValuesWireValue(t *testing.T) { } func TestEnumValuesNilProject(t *testing.T) { + t.Parallel() var p *IRProject if got := p.EnumValues("X"); got != nil { t.Errorf("nil project EnumValues = %v, want nil", got) @@ -54,6 +57,7 @@ func TestEnumValuesNilProject(t *testing.T) { } func TestIRIndexDatabaseName(t *testing.T) { + t.Parallel() cases := []struct { name string want string @@ -63,6 +67,7 @@ func TestIRIndexDatabaseName(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() if got := (IRIndex{Name: c.name}).DatabaseName(); got != c.want { t.Errorf("DatabaseName(%q) = %q, want %q", c.name, got, c.want) } diff --git a/internal/ir/models_test.go b/internal/ir/models_test.go index 455f415..548c8d8 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,6 +17,7 @@ func TestIRField_IsArray(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() f := IRField{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,6 +40,7 @@ func TestIRField_ArrayElementType(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() f := IRField{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,6 +65,7 @@ func TestIREntity_HasFeature(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() e := IREntity{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,6 +87,7 @@ func TestIREntity_HasAudit(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() e := IREntity{Features: tt.features} if got := e.HasAudit(); got != tt.want { t.Errorf("HasAudit() = %v, want %v", got, tt.want) @@ -89,6 +97,7 @@ func TestIREntity_HasAudit(t *testing.T) { } func TestIREntity_HasAuditLog(t *testing.T) { + t.Parallel() e := IREntity{Features: map[string]bool{"audit_log": true}} if !e.HasAuditLog() { t.Error("HasAuditLog() = false, want true") @@ -100,6 +109,7 @@ func TestIREntity_HasAuditLog(t *testing.T) { } func TestIREntity_HasSoftDelete(t *testing.T) { + t.Parallel() e := IREntity{Features: map[string]bool{"soft_delete": true}} if !e.HasSoftDelete() { t.Error("HasSoftDelete() = false, want true") @@ -107,6 +117,7 @@ func TestIREntity_HasSoftDelete(t *testing.T) { } func TestIREntity_HasOptimisticLock(t *testing.T) { + t.Parallel() e := IREntity{Features: map[string]bool{"optimistic_lock": true}} if !e.HasOptimisticLock() { t.Error("HasOptimisticLock() = false, want true") @@ -114,6 +125,7 @@ func TestIREntity_HasOptimisticLock(t *testing.T) { } func TestIREntity_NonRelationFields(t *testing.T) { + t.Parallel() e := IREntity{ Fields: []IRField{ {Name: "id", IsRelation: false}, @@ -131,6 +143,7 @@ func TestIREntity_NonRelationFields(t *testing.T) { } func TestIREntity_RelationFields(t *testing.T) { + t.Parallel() e := IREntity{ Fields: []IRField{ {Name: "id", IsRelation: false}, @@ -151,6 +164,7 @@ 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) { + t.Parallel() e := IREntity{Name: "OrderItem", NamePlural: "OrderItems"} if got := e.TableName(); got != "order_items" { t.Errorf("TableName() = %q, want order_items", got) @@ -172,6 +186,7 @@ func TestCanonicalNameContract(t *testing.T) { } for _, c := range cases { 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) } @@ -180,6 +195,7 @@ func TestCanonicalNameContract(t *testing.T) { } func TestEagerLoadNavigation(t *testing.T) { + t.Parallel() r := IRRelation{FieldName: "orders", NavigationName: "Order", IsMany: true} if got := r.EagerLoadNavigation(); got != "orders" { t.Errorf("[many] navigation = %q, want the collection property orders", got) diff --git a/internal/ir/query_test.go b/internal/ir/query_test.go index 9e01b2c..33b5c99 100644 --- a/internal/ir/query_test.go +++ b/internal/ir/query_test.go @@ -40,6 +40,7 @@ func testEntity() IREntity { } func TestSearchableSortableFilterableFields(t *testing.T) { + t.Parallel() e := testEntity() names := func(fields []IRField) []string { @@ -63,6 +64,7 @@ func TestSearchableSortableFilterableFields(t *testing.T) { } func TestFilterOperators(t *testing.T) { + t.Parallel() cases := []struct { name string dbType string @@ -78,6 +80,7 @@ func TestFilterOperators(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() f := IRField{DatabaseType: c.dbType} got := f.FilterOperators() if len(got) == 0 && len(c.want) == 0 { @@ -91,6 +94,7 @@ func TestFilterOperators(t *testing.T) { } func TestAllFilterOperators(t *testing.T) { + t.Parallel() got := (IRProject{}).AllFilterOperators() want := []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} if !reflect.DeepEqual(got, want) { @@ -99,6 +103,7 @@ func TestAllFilterOperators(t *testing.T) { } func TestFilterablePaths(t *testing.T) { + t.Parallel() e := testEntity() paths := e.FilterablePaths() @@ -129,6 +134,7 @@ func TestFilterablePaths(t *testing.T) { } func TestQuerySchema(t *testing.T) { + t.Parallel() e := testEntity() q := e.QuerySchema() @@ -149,6 +155,7 @@ func TestQuerySchema(t *testing.T) { } func TestCursorField(t *testing.T) { + t.Parallel() cases := []struct { name string pkType string @@ -162,6 +169,7 @@ func TestCursorField(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() e := IREntity{Fields: []IRField{{Name: "id", DatabaseType: c.pkType, IsPrimary: true}}} got := e.CursorField() if (got != nil) != c.want { diff --git a/internal/ir/seed.go b/internal/ir/seed.go index ffc15ca..8a71564 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 any // native Go value (string, int64, float64, bool, []any, 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 diff --git a/internal/ir/toposort.go b/internal/ir/toposort.go index 1e102b4..7edf1e8 100644 --- a/internal/ir/toposort.go +++ b/internal/ir/toposort.go @@ -98,4 +98,4 @@ func sortEntities(entities []IREntity) []IREntity { } return sorted -} \ No newline at end of file +} diff --git a/internal/ir/typekind_test.go b/internal/ir/typekind_test.go index ab2d9cd..2783621 100644 --- a/internal/ir/typekind_test.go +++ b/internal/ir/typekind_test.go @@ -3,6 +3,7 @@ package ir import "testing" func TestIRFieldTypePredicates(t *testing.T) { + t.Parallel() cases := []struct { name string dbType string @@ -29,6 +30,7 @@ func TestIRFieldTypePredicates(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() f := IRField{DatabaseType: c.dbType} if got := f.IsUuid(); got != c.isUuid { t.Errorf("%q IsUuid() = %v, want %v", c.dbType, got, c.isUuid) @@ -68,6 +70,7 @@ func TestIRFieldTypePredicates(t *testing.T) { } func TestIRFieldSpecificTypePredicates(t *testing.T) { + t.Parallel() cases := []struct { name string dbType string @@ -85,6 +88,7 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { + t.Parallel() f := IRField{DatabaseType: c.dbType} if got := f.IsString(); got != c.isString { t.Errorf("%q IsString() = %v, want %v", c.dbType, got, c.isString) @@ -103,6 +107,7 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { } func TestIRFieldIsPatchable(t *testing.T) { + t.Parallel() cases := []struct { name string f IRField @@ -121,6 +126,7 @@ func TestIRFieldIsPatchable(t *testing.T) { } for _, c := range cases { 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) } @@ -129,6 +135,7 @@ func TestIRFieldIsPatchable(t *testing.T) { } func TestIRFieldIsTextOnly(t *testing.T) { + t.Parallel() if !(IRField{DatabaseType: "text"}).IsTextOnly() { t.Error("text should be IsTextOnly") } @@ -138,6 +145,7 @@ func TestIRFieldIsTextOnly(t *testing.T) { } func TestIREntityTableNameAndForeignKeyColumnName(t *testing.T) { + t.Parallel() e := IREntity{Name: "IPv4Rule", NamePlural: "IPv4Rules"} if got := e.TableName(); got != "i_pv4rules" { t.Errorf("TableName() = %q, want %q (acronyms must match ToDatabaseColumnName)", got, "i_pv4rules") @@ -154,6 +162,7 @@ func TestIREntityTableNameAndForeignKeyColumnName(t *testing.T) { } func TestKindOf(t *testing.T) { + t.Parallel() cases := map[string]string{ "uuid": "uuid", "string": "text", @@ -185,6 +194,7 @@ func TestKindOf(t *testing.T) { } func TestIRPermissionsIsPublic(t *testing.T) { + t.Parallel() p := &IRPermissions{Read: []string{"*"}, Create: []string{"Admin"}, Update: nil, Delete: []string{}} if !p.IsPublic("read") { t.Error("IsPublic(read) = false, want true") @@ -205,6 +215,7 @@ func TestIRPermissionsIsPublic(t *testing.T) { } func TestIREndpointAuthPolicy(t *testing.T) { + t.Parallel() cases := map[string]string{ "list": "Read", "get": "Read", diff --git a/internal/lexer/lexer_test.go b/internal/lexer/lexer_test.go index 62057d8..e85b7b3 100644 --- a/internal/lexer/lexer_test.go +++ b/internal/lexer/lexer_test.go @@ -6,6 +6,7 @@ import ( ) func TestParsePrimitiveTypes(t *testing.T) { + t.Parallel() tests := []struct { input string wantType string @@ -24,6 +25,7 @@ func TestParsePrimitiveTypes(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) @@ -37,6 +39,7 @@ func TestParsePrimitiveTypes(t *testing.T) { } func TestParseRelationType(t *testing.T) { + t.Parallel() tests := []struct { input string wantType string @@ -50,6 +53,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 +73,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 +92,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 +118,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 +136,7 @@ func TestParseValidations(t *testing.T) { } func TestParseDefaults(t *testing.T) { + t.Parallel() tests := []struct { input string wantDefault string @@ -141,6 +149,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 +166,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 +181,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 +206,7 @@ func TestParseArrayDefault(t *testing.T) { } func TestParseOnDelete(t *testing.T) { + t.Parallel() tests := []struct { input string wantBehavior string @@ -209,6 +221,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 +235,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 +258,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 +266,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 +275,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 +290,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 +305,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 +327,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 +338,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 +349,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 +360,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 +377,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 +391,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 +402,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 +413,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") diff --git a/internal/parser/integration_test.go b/internal/parser/integration_test.go index 4b19216..bd9754a 100644 --- a/internal/parser/integration_test.go +++ b/internal/parser/integration_test.go @@ -7,6 +7,7 @@ import ( // TestFullSchemaWithAllFeatures tests a full schema using all features func TestFullSchemaWithAllFeatures(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: ECommerce Platform @@ -239,6 +240,7 @@ entities: // 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: @@ -269,6 +271,7 @@ entities: // TestDatabaseColumnNameGeneration tests database column name generation func TestDatabaseColumnNameGeneration(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -306,6 +309,7 @@ entities: for _, tt := range tests { 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", @@ -318,6 +322,7 @@ entities: // TestSeedData tests seed data parsing func TestSeedData(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -353,6 +358,7 @@ entities: // TestEntityOrdering tests entity ordering func TestEntityOrdering(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -384,6 +390,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 5b3ef93..968a2ad 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -128,13 +128,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]any `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. diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index 35b8db2..e484c15 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -7,6 +7,7 @@ import ( ) func TestParseStrictRejectsUnknownKeys(t *testing.T) { + t.Parallel() tests := []struct { name string yaml string @@ -74,6 +75,7 @@ entities: {} } 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) @@ -86,6 +88,7 @@ entities: {} } func TestParseRawSchema(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test Project @@ -117,6 +120,7 @@ entities: } func TestParseDefaults(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -140,6 +144,7 @@ entities: {} } func TestParseEntity(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -190,6 +195,7 @@ entities: } func TestParseFeatures(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -225,6 +231,7 @@ entities: } func TestParseRelations(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -269,6 +276,7 @@ entities: } func TestParseIndexes(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -307,6 +315,7 @@ entities: } func TestPluralizeNames(t *testing.T) { + t.Parallel() tests := []struct { singular string plural string @@ -320,6 +329,7 @@ func TestPluralizeNames(t *testing.T) { for _, tt := range tests { 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) @@ -332,6 +342,7 @@ func TestPluralizeNames(t *testing.T) { } func TestDatabaseColumnNames(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -363,6 +374,7 @@ entities: for _, tt := range tests { 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) @@ -373,6 +385,7 @@ entities: } func TestParsePermissions(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -403,6 +416,7 @@ entities: } func TestParsePrimaryImpliesRequired(t *testing.T) { + t.Parallel() // Parser normalizes primary→required (lexer no longer does this). yamlData := []byte(` project: @@ -427,6 +441,7 @@ entities: } func TestParseOptionalImpliesNotRequired(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -451,6 +466,7 @@ entities: } func TestParseRelationTypeInference(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -487,6 +503,7 @@ entities: } for _, tt := range tests { 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) @@ -496,6 +513,7 @@ entities: } func TestParseDeployDefaults(t *testing.T) { + t.Parallel() // Parser should set deploy defaults (port=8080, domain=localhost). yamlData := []byte(` project: @@ -521,6 +539,7 @@ entities: } func TestParseDeployExplicitValues(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -545,6 +564,7 @@ entities: } func TestParseVersioningRateLimitPaginationDefaults(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -590,6 +610,7 @@ entities: } func TestParseVersioningRateLimitExplicit(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -628,6 +649,7 @@ entities: } func TestParseUnknownEntityKey(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -646,6 +668,7 @@ entities: } func TestParseOldName(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -669,6 +692,7 @@ entities: } func TestParseDuplicateField(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test @@ -700,6 +724,7 @@ entities: // RawSchema decoding cannot silently reintroduce the overwrite-on-duplicate // behaviour. func TestParseDuplicateEntity(t *testing.T) { + t.Parallel() yamlData := []byte(` project: name: Test diff --git a/internal/renderer/bridgefuncs_test.go b/internal/renderer/bridgefuncs_test.go index 568193b..a0a0560 100644 --- a/internal/renderer/bridgefuncs_test.go +++ b/internal/renderer/bridgefuncs_test.go @@ -36,6 +36,7 @@ func testMappings() *typeMappings { } 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 +44,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 +62,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 +84,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()) @@ -100,6 +104,7 @@ func TestBuildBridgeFuncs_DefaultArrayFormatAndOptionalFuncs(t *testing.T) { } func TestBuildBridgeFuncs_LiteralValue(t *testing.T) { + t.Parallel() literalValue := buildBridgeFuncs(testMappings(), logger.New())["literalValue"].(func(string, any) string) cases := []struct { @@ -117,6 +122,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,6 +131,7 @@ 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 }{ @@ -136,6 +143,7 @@ func TestBuildBridgeFuncs_LiteralDefault(t *testing.T) { } 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 +160,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" { @@ -170,6 +179,7 @@ func TestBuildBridgeFuncs_LiteralMember(t *testing.T) { } func TestBuildBridgeFuncs_ArrayLiteralAndHelpers(t *testing.T) { + t.Parallel() raw := buildBridgeFuncs(testMappings(), logger.New()) open := raw["arrayLiteralOpen"].(func(string) string) @@ -217,6 +227,7 @@ func TestBuildBridgeFuncs_ArrayLiteralAndHelpers(t *testing.T) { } 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"}}, diff --git a/internal/renderer/bundled_bridges_test.go b/internal/renderer/bundled_bridges_test.go index d665fd0..8a30e38 100644 --- a/internal/renderer/bundled_bridges_test.go +++ b/internal/renderer/bundled_bridges_test.go @@ -15,6 +15,7 @@ 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) diff --git a/internal/renderer/contract_test.go b/internal/renderer/contract_test.go index 2eaafdb..968a915 100644 --- a/internal/renderer/contract_test.go +++ b/internal/renderer/contract_test.go @@ -23,6 +23,7 @@ func writeBridgeConfig(t *testing.T, yamlContent string) string { } func TestLoadSourceRejectsNewerContract(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\ncontract_version: 99\n") _, err := loadSource(dir) if err == nil { @@ -31,6 +32,7 @@ func TestLoadSourceRejectsNewerContract(t *testing.T) { } func TestLoadSourceDefaultsAbsentContractTo1(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\n") src, err := loadSource(dir) if err != nil { @@ -45,6 +47,7 @@ func TestLoadSourceDefaultsAbsentContractTo1(t *testing.T) { } func TestLoadSourceAcceptsMatchingContract(t *testing.T) { + t.Parallel() dir := writeBridgeConfig(t, "name: b\ncontract_version: 1\n") src, err := loadSource(dir) if err != nil { @@ -59,6 +62,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() diff --git a/internal/renderer/renderer_test.go b/internal/renderer/render_test.go similarity index 98% rename from internal/renderer/renderer_test.go rename to internal/renderer/render_test.go index a78bb76..b419cbe 100644 --- a/internal/renderer/renderer_test.go +++ b/internal/renderer/render_test.go @@ -11,6 +11,7 @@ import ( ) 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 { @@ -59,6 +60,7 @@ templates: } func TestComposeAttachBases(t *testing.T) { + t.Parallel() tmpDir := t.TempDir() write := func(dir, name, content string) { @@ -129,6 +131,7 @@ templates: } func TestMergeTypeMappingsOverlay(t *testing.T) { + t.Parallel() base := &typeMappings{ Types: map[string]string{"string": "str", "int": "num"}, ArrayFormat: "%s[]", @@ -159,6 +162,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 { @@ -237,6 +241,7 @@ templates: } func TestRenderContext_HasFeature(t *testing.T) { + t.Parallel() tests := []struct { name string features map[string]bool @@ -250,6 +255,7 @@ func TestRenderContext_HasFeature(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() ctx := RenderContext{ Entity: &ir.IREntity{Features: tt.features}, } @@ -264,6 +270,7 @@ func TestRenderContext_HasFeature(t *testing.T) { } func TestRenderContext_HasAudit(t *testing.T) { + t.Parallel() ctx := RenderContext{ Entity: &ir.IREntity{Features: map[string]bool{"audit": true}}, } @@ -278,6 +285,7 @@ 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}}, } @@ -287,6 +295,7 @@ 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}}, } @@ -296,6 +305,7 @@ 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}}, } @@ -305,6 +315,7 @@ 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") @@ -320,6 +331,7 @@ 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") @@ -340,6 +352,7 @@ func TestRenderContext_PrimaryKey(t *testing.T) { } func TestResolvePackagesNilLoggerDoesNotPanic(t *testing.T) { + t.Parallel() // 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) { @@ -358,6 +371,7 @@ func TestResolvePackagesNilLoggerDoesNotPanic(t *testing.T) { } func TestRenderHasMigrationCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T, when string) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -409,6 +423,7 @@ templates: } func TestRenderHasMockDataCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -460,6 +475,7 @@ templates: } func TestRenderHasSeedCondition(t *testing.T) { + t.Parallel() newRenderer := func(t *testing.T) *Renderer { t.Helper() tmpDir := t.TempDir() @@ -511,6 +527,7 @@ templates: } func TestRenderContext_SeedAccessor(t *testing.T) { + t.Parallel() ctx := RenderContext{ Entity: &ir.IREntity{Name: "Order"}, SeedData: &ir.SeedDataset{Entities: []ir.SeedEntity{{Name: "Order", Records: []ir.SeedRecord{{Fields: []ir.SeedValue{{Field: "id", Value: "x"}}}}}}}, @@ -525,6 +542,7 @@ func TestRenderContext_SeedAccessor(t *testing.T) { } func TestRenderContext_DTOAccessors(t *testing.T) { + t.Parallel() e := &ir.IREntity{Name: "User", Fields: []ir.IRField{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "name", DatabaseType: "string"}, diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index ddecbd9..410aa6e 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -373,4 +373,4 @@ func jsonValue(value any) string { return fmt.Sprintf("%v", value) } return string(encoded) -} \ No newline at end of file +} diff --git a/internal/renderer/version_test.go b/internal/renderer/version_test.go index 446cdf1..2ddc792 100644 --- a/internal/renderer/version_test.go +++ b/internal/renderer/version_test.go @@ -10,6 +10,7 @@ import ( // 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 @@ -23,6 +24,7 @@ func TestContractVersionMatrix(t *testing.T) { } 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 +49,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,6 +64,7 @@ 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) { + t.Parallel() base := writeBridgeConfig(t, "name: base\ncontract_version: 2\n") adapter := writeBridgeConfig(t, "name: adapter\nextends: "+base+"\n") @@ -76,6 +80,7 @@ func TestNewerContractRejectedInBase(t *testing.T) { // TestMatchingContractAcceptedInBase is the positive control: an equal-contract // base attaches cleanly. func TestMatchingContractAcceptedInBase(t *testing.T) { + t.Parallel() base := writeBridgeConfig(t, "name: base\ncontract_version: 1\n") adapter := writeBridgeConfig(t, "name: adapter\nextends: "+base+"\n") diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index a235aa9..9c476b7 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -8,6 +8,7 @@ import ( ) func TestGenerateBasicTypes(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Enums: map[string][]string{"Status": {"pending", "active"}}, Entities: []ir.IREntity{ @@ -65,6 +66,7 @@ func TestGenerateBasicTypes(t *testing.T) { } func TestGenerateReferencesParentPK(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { @@ -106,6 +108,7 @@ func TestGenerateReferencesParentPK(t *testing.T) { } func TestNormalizeCoercesTypes(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { @@ -155,6 +158,7 @@ func TestNormalizeCoercesTypes(t *testing.T) { } func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ {Name: "Empty", Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}}, @@ -168,6 +172,7 @@ func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { } func TestNormalizeIncludesRelationFlags(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { @@ -191,6 +196,7 @@ func TestNormalizeIncludesRelationFlags(t *testing.T) { } func TestGenerateHonorsNumericBounds(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { @@ -237,6 +243,7 @@ func TestGenerateHonorsNumericBounds(t *testing.T) { } func TestGenerateHonorsStringValidations(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { @@ -272,6 +279,7 @@ func TestGenerateHonorsStringValidations(t *testing.T) { } func TestNormalizeCoerceEdgeCases(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Enums: map[string][]string{"Status": {"draft", "live"}}, Entities: []ir.IREntity{ @@ -338,6 +346,7 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { } func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { + t.Parallel() project := &ir.IRProject{ Entities: []ir.IREntity{ { diff --git a/internal/snapshot/migration_test.go b/internal/snapshot/migration_test.go index b388a7c..0d36b67 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"}}, @@ -50,6 +51,7 @@ func TestComputeMigrationPlanCreateAndDropTables(t *testing.T) { } func TestComputeMigrationPlanRenameTable(t *testing.T) { + t.Parallel() old := &Snapshot{ Entities: map[string]EntityState{ "Product": {Fields: map[string]string{"id": "uuid"}}, @@ -78,6 +80,7 @@ func TestComputeMigrationPlanRenameTable(t *testing.T) { } func TestComputeMigrationPlanColumnOps(t *testing.T) { + t.Parallel() old := &Snapshot{ Entities: map[string]EntityState{ "Product": { @@ -147,6 +150,7 @@ func TestComputeMigrationPlanColumnOps(t *testing.T) { } func TestComputeMigrationPlanNilInputs(t *testing.T) { + t.Parallel() if plan := ComputeMigrationPlan(nil, nil); !plan.IsEmpty() { t.Error("nil inputs should produce an empty plan") } @@ -156,6 +160,7 @@ func TestComputeMigrationPlanNilInputs(t *testing.T) { } 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{ diff --git a/internal/snapshot/paths_test.go b/internal/snapshot/paths_test.go index 38ca0a3..32837a8 100644 --- a/internal/snapshot/paths_test.go +++ b/internal/snapshot/paths_test.go @@ -9,6 +9,7 @@ import ( ) func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { + t.Parallel() root := t.TempDir() tests := []struct { @@ -32,6 +33,7 @@ func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { 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) @@ -44,6 +46,7 @@ func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { } 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 { @@ -61,6 +64,7 @@ func TestDeleteFileRejectsSnapshotEscape(t *testing.T) { } 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 { diff --git a/internal/snapshot/rewrite_test.go b/internal/snapshot/rewrite_test.go index 4503ea2..e563ba1 100644 --- a/internal/snapshot/rewrite_test.go +++ b/internal/snapshot/rewrite_test.go @@ -7,6 +7,7 @@ import ( ) 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"}, @@ -23,6 +24,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) @@ -35,6 +37,7 @@ func TestRewriteEntityContent(t *testing.T) { // 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) { @@ -47,6 +50,7 @@ func TestRenameTransformsIncludesFieldRenames(t *testing.T) { } 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 { @@ -55,6 +59,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")) @@ -64,6 +69,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(); }" @@ -90,6 +96,7 @@ func TestRewriteFileRoundTrip(t *testing.T) { } func TestRewriteFileNoop(t *testing.T) { + t.Parallel() dir := t.TempDir() rel := "a.cs" content := "var unrelated = 1;" @@ -110,6 +117,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_test.go b/internal/snapshot/snapshot_test.go index e71dddf..bdea039 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -12,6 +12,7 @@ import ( ) func TestSaveLoadRoundtrip(t *testing.T) { + t.Parallel() dir := t.TempDir() path := SnapshotPath(dir) @@ -47,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) @@ -57,6 +59,7 @@ func TestLoadMissingSnapshotReturnsNil(t *testing.T) { } 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") @@ -88,6 +91,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") @@ -141,6 +145,7 @@ func TestComputeDiffRenameAndTypeChange(t *testing.T) { } func TestRenameRelPath(t *testing.T) { + t.Parallel() tests := []struct { rel, old, new, want string }{ @@ -154,6 +159,7 @@ func TestRenameRelPath(t *testing.T) { } for _, tt := range tests { 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) } @@ -162,6 +168,7 @@ func TestRenameRelPath(t *testing.T) { } func TestDeleteFileAndRenameEntityFile(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -186,6 +193,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") @@ -223,6 +231,7 @@ func TestComputeDiffNamespaceRename(t *testing.T) { } func TestComputeDiffFieldRename(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Application/Services/ProductService.cs") @@ -282,6 +291,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 @@ -330,6 +340,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. @@ -349,6 +360,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. @@ -371,6 +383,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") @@ -417,6 +430,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") @@ -469,6 +483,7 @@ func TestComputeDiffEntityRenameOnly(t *testing.T) { } func TestComputeDiffEntityRenameWithoutFiles(t *testing.T) { + t.Parallel() dir := t.TempDir() // No files created on disk. @@ -502,6 +517,7 @@ func TestComputeDiffEntityRenameWithoutFiles(t *testing.T) { } func TestComputeDiffFieldRenameWithTypeChange(t *testing.T) { + t.Parallel() dir := t.TempDir() writeTestFile(t, dir, "src/Services/ProductService.cs") @@ -562,6 +578,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") @@ -663,6 +680,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") @@ -720,6 +738,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") @@ -768,7 +787,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) @@ -776,6 +797,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"}, diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index c5a1286..c07def6 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -5,6 +5,7 @@ import "fmt" import "testing" func TestIsPrimitive(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -31,6 +32,7 @@ func TestIsPrimitive(t *testing.T) { for _, tt := range tests { 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) @@ -40,6 +42,7 @@ func TestIsPrimitive(t *testing.T) { } 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) @@ -54,6 +57,7 @@ func TestFieldTypesDerivedCorrectly(t *testing.T) { } func TestIsNumeric(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -70,6 +74,7 @@ func TestIsNumeric(t *testing.T) { } for _, tt := range tests { 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) } @@ -78,6 +83,7 @@ func TestIsNumeric(t *testing.T) { } func TestIsStringType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -90,6 +96,7 @@ func TestIsStringType(t *testing.T) { } for _, tt := range tests { 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) } @@ -98,6 +105,7 @@ func TestIsStringType(t *testing.T) { } func TestIsBooleanType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -110,6 +118,7 @@ func TestIsBooleanType(t *testing.T) { } for _, tt := range tests { 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) } @@ -118,6 +127,7 @@ func TestIsBooleanType(t *testing.T) { } func TestIsIndexType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -132,6 +142,7 @@ func TestIsIndexType(t *testing.T) { } for _, tt := range tests { 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) } @@ -140,6 +151,7 @@ func TestIsIndexType(t *testing.T) { } func TestIsCacheProvider(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -152,6 +164,7 @@ func TestIsCacheProvider(t *testing.T) { } for _, tt := range tests { 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) } @@ -160,6 +173,7 @@ func TestIsCacheProvider(t *testing.T) { } func TestIsMultiTenancyMode(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -172,6 +186,7 @@ func TestIsMultiTenancyMode(t *testing.T) { } for _, tt := range tests { 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) } @@ -180,6 +195,7 @@ func TestIsMultiTenancyMode(t *testing.T) { } func TestIsPermissionKey(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -193,6 +209,7 @@ func TestIsPermissionKey(t *testing.T) { } for _, tt := range tests { 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) } @@ -201,6 +218,7 @@ func TestIsPermissionKey(t *testing.T) { } func TestIsStringValidationModifier(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -217,6 +235,7 @@ func TestIsStringValidationModifier(t *testing.T) { } for _, tt := range tests { 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) } @@ -225,6 +244,7 @@ func TestIsStringValidationModifier(t *testing.T) { } func TestIsNumericValidationModifier(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -239,6 +259,7 @@ func TestIsNumericValidationModifier(t *testing.T) { } for _, tt := range tests { 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) } @@ -247,6 +268,7 @@ func TestIsNumericValidationModifier(t *testing.T) { } func TestFindAuthEntity(t *testing.T) { + t.Parallel() tests := []struct { name string entityOrder []string @@ -286,6 +308,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) @@ -295,6 +318,7 @@ func TestFindAuthEntity(t *testing.T) { } func TestIsSortDirection(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -307,6 +331,7 @@ func TestIsSortDirection(t *testing.T) { } for _, tt := range tests { 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) } @@ -315,6 +340,7 @@ func TestIsSortDirection(t *testing.T) { } func TestHasEmailAndPassword(t *testing.T) { + t.Parallel() tests := []struct { name string fieldNames []string @@ -329,6 +355,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) } @@ -337,6 +364,7 @@ func TestHasEmailAndPassword(t *testing.T) { } func TestFuncDefaultsContainsExpectedEntries(t *testing.T) { + t.Parallel() if _, ok := FuncDefaults["now"]; !ok { t.Error("FuncDefaults missing 'now'") } @@ -352,6 +380,7 @@ func TestFuncDefaultsContainsExpectedEntries(t *testing.T) { } func TestIsDatabase(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -368,6 +397,7 @@ func TestIsDatabase(t *testing.T) { } for _, tt := range tests { 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) } @@ -376,6 +406,7 @@ func TestIsDatabase(t *testing.T) { } func TestIsAPIStyle(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -389,6 +420,7 @@ func TestIsAPIStyle(t *testing.T) { } for _, tt := range tests { 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) } @@ -397,6 +429,7 @@ func TestIsAPIStyle(t *testing.T) { } func TestIsAuthType(t *testing.T) { + t.Parallel() tests := []struct { input string want bool @@ -409,6 +442,7 @@ func TestIsAuthType(t *testing.T) { } for _, tt := range tests { 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) } @@ -417,6 +451,7 @@ func TestIsAuthType(t *testing.T) { } func TestBuildEntityFields(t *testing.T) { + t.Parallel() entityOrder := []string{"User", "Product"} getFields := func(name string) []string { switch name { @@ -443,6 +478,7 @@ func TestBuildEntityFields(t *testing.T) { } func TestBuildEntityFieldsEmptyOrder(t *testing.T) { + t.Parallel() result := BuildEntityFields(nil, func(name string) []string { return nil }) if len(result) != 0 { t.Errorf("BuildEntityFields(nil) returned %d entries, want 0", len(result)) diff --git a/internal/templatefuncs/templatefuncs_test.go b/internal/templatefuncs/templatefuncs_test.go index aa0f6f5..0e07642 100644 --- a/internal/templatefuncs/templatefuncs_test.go +++ b/internal/templatefuncs/templatefuncs_test.go @@ -8,6 +8,7 @@ import ( ) 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 +19,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,6 +27,7 @@ func TestAdd(t *testing.T) { } func TestAtoi(t *testing.T) { + t.Parallel() if got := Atoi("42"); got != 42 { t.Errorf("Atoi('42') = %d, want 42", got) } @@ -34,6 +37,7 @@ func TestAtoi(t *testing.T) { } func TestDefault(t *testing.T) { + t.Parallel() if got := Default("fallback", ""); got != "fallback" { t.Errorf("Default(fallback, empty) = %v, want fallback", got) } @@ -46,6 +50,7 @@ func TestDefault(t *testing.T) { } func TestDict(t *testing.T) { + t.Parallel() got := Dict("a", 1, "b", "two") want := map[string]any{"a": 1, "b": "two"} if !reflect.DeepEqual(got, want) { @@ -59,6 +64,7 @@ func TestDict(t *testing.T) { } func TestSet(t *testing.T) { + t.Parallel() d := map[string]any{} got := Set(d, "x", 7) if got["x"] != 7 { @@ -67,6 +73,7 @@ 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) @@ -83,6 +90,7 @@ func TestListAppend(t *testing.T) { } 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,6 +98,7 @@ 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) } @@ -102,6 +111,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 +121,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 +131,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 +141,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 +158,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 +172,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,6 +188,7 @@ 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) diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index 03f3e1b..1ca5b1b 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -11,6 +11,7 @@ import ( ) func TestValidateDetectsMissingPrimaryKey(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -36,6 +37,7 @@ func TestValidateDetectsMissingPrimaryKey(t *testing.T) { } func TestValidateRejectsOldNameEqualToFieldName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -65,6 +67,7 @@ func TestValidateRejectsOldNameEqualToFieldName(t *testing.T) { } func TestValidateRejectsOldNameCollidingWithExistingField(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -95,6 +98,7 @@ func TestValidateRejectsOldNameCollidingWithExistingField(t *testing.T) { } func TestValidateAcceptsValidOldName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -119,6 +123,7 @@ func TestValidateAcceptsValidOldName(t *testing.T) { } func TestValidateDetectsDuplicatePrimaryKey(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -148,6 +153,7 @@ func TestValidateDetectsDuplicatePrimaryKey(t *testing.T) { } func TestValidateDetectsBrokenRelation(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -173,6 +179,7 @@ func TestValidateDetectsBrokenRelation(t *testing.T) { } func TestValidateDetectsSetNullOnRequiredField(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{ @@ -209,6 +216,7 @@ func TestValidateDetectsSetNullOnRequiredField(t *testing.T) { } func TestValidateDetectsUndefinedEnum(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -239,6 +247,7 @@ func TestValidateDetectsUndefinedEnum(t *testing.T) { } func TestValidatePassesValidEnums(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -265,6 +274,7 @@ func TestValidatePassesValidEnums(t *testing.T) { } func TestValidateDetectsEmptyProjectName(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ EntityOrder: []string{"User"}, Entities: map[string]*parser.ParsedEntity{ @@ -292,6 +302,7 @@ func TestValidateDetectsEmptyProjectName(t *testing.T) { } func TestValidateDetectsManyOnNonRelation(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{ @@ -318,6 +329,7 @@ func TestValidateDetectsManyOnNonRelation(t *testing.T) { } func TestValidateDetectsOnDeleteOnNonRelation(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{ @@ -344,6 +356,7 @@ func TestValidateDetectsOnDeleteOnNonRelation(t *testing.T) { } func TestValidateDetectsEmptyEnum(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -373,6 +386,7 @@ func TestValidateDetectsEmptyEnum(t *testing.T) { } func TestValidateDetectsEmptyIndexFields(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -404,6 +418,7 @@ func TestValidateDetectsEmptyIndexFields(t *testing.T) { } func TestValidateDetectsSortLengthMismatch(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -450,6 +465,7 @@ func nonWarnings(errs []ValidationError) []ValidationError { } func TestValidateAuthEntityMissingEmailPassword(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Auth: &parser.AuthConfig{Type: "jwt", Entity: "Product"}, @@ -480,6 +496,7 @@ func TestValidateAuthEntityMissingEmailPassword(t *testing.T) { } func TestValidateAuthEntityValidEmailPassword(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Auth: &parser.AuthConfig{Type: "jwt", Entity: "User"}, @@ -508,6 +525,7 @@ func TestValidateAuthEntityValidEmailPassword(t *testing.T) { } func TestValidateDefaultNowOnNonDatetime(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -537,6 +555,7 @@ func TestValidateDefaultNowOnNonDatetime(t *testing.T) { } func TestValidateDefaultNowOnDatetime(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -563,6 +582,7 @@ func TestValidateDefaultNowOnDatetime(t *testing.T) { } func TestValidateDefaultUuidOnNonUuid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -592,6 +612,7 @@ func TestValidateDefaultUuidOnNonUuid(t *testing.T) { } func TestValidateDeployPortRange(t *testing.T) { + t.Parallel() tests := []struct { name string port int @@ -606,6 +627,7 @@ func TestValidateDeployPortRange(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{ Name: "Test", @@ -643,7 +665,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", @@ -678,6 +702,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", @@ -713,6 +738,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"}, @@ -752,6 +778,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"}, @@ -787,6 +814,7 @@ func TestValidateIndexOnFKFieldNoWarning(t *testing.T) { } func TestValidateIndexOnPrimitiveField(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -816,6 +844,7 @@ func TestValidateIndexOnPrimitiveField(t *testing.T) { } func TestValidateEnumDefaultMustMatchDeclaredValues(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -847,6 +876,7 @@ func TestValidateEnumDefaultMustMatchDeclaredValues(t *testing.T) { } func TestValidateEnumDefaultValidValue(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Product"}, @@ -874,6 +904,7 @@ func TestValidateEnumDefaultValidValue(t *testing.T) { } func TestValidateNumericValidationValueNotNumeric(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -904,6 +935,7 @@ func TestValidateNumericValidationValueNotNumeric(t *testing.T) { } func TestValidateNumericValidationValueValid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -930,6 +962,7 @@ func TestValidateNumericValidationValueValid(t *testing.T) { } func TestValidateEntityEnumNameCollision(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Status"}, @@ -959,6 +992,7 @@ func TestValidateEntityEnumNameCollision(t *testing.T) { } func TestValidatePermissionRolesEmptyAuthRoles(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Auth: &parser.AuthConfig{Type: "jwt"}, @@ -993,6 +1027,7 @@ func TestValidatePermissionRolesEmptyAuthRoles(t *testing.T) { } func TestValidateContradictoryStringMinMax(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1023,6 +1058,7 @@ func TestValidateContradictoryStringMinMax(t *testing.T) { } func TestValidateValidStringMinMax(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1049,6 +1085,7 @@ func TestValidateValidStringMinMax(t *testing.T) { } func TestValidateContradictoryNumericGteLt(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1079,6 +1116,7 @@ func TestValidateContradictoryNumericGteLt(t *testing.T) { } func TestValidateContradictoryNumericGtLte(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1109,6 +1147,7 @@ func TestValidateContradictoryNumericGtLte(t *testing.T) { } func TestValidateValidNumericRange(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1135,6 +1174,7 @@ func TestValidateValidNumericRange(t *testing.T) { } func TestValidateUnusedEnumWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1167,6 +1207,7 @@ func TestValidateUnusedEnumWarning(t *testing.T) { } func TestValidateUsedEnumNoWarning(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1195,6 +1236,7 @@ func TestValidateUsedEnumNoWarning(t *testing.T) { } func TestValidateOnDeleteValueInvalid(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{ @@ -1229,6 +1271,7 @@ func TestValidateOnDeleteValueInvalid(t *testing.T) { } func TestValidateSeedValueTypeMismatch(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1262,6 +1305,7 @@ func TestValidateSeedValueTypeMismatch(t *testing.T) { } func TestValidateSeedBooleanTypeMismatch(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Config"}, @@ -1295,6 +1339,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"}, @@ -1332,6 +1377,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"}, @@ -1365,6 +1411,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"}, @@ -1405,6 +1452,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"}, @@ -1450,6 +1498,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 +1517,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"}, @@ -1499,6 +1549,7 @@ func TestValidateGenuineManyToManyHasNoReconciliationWarning(t *testing.T) { } func TestValidateSeedUniqueConstraintViolation(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1533,6 +1584,7 @@ func TestValidateSeedUniqueConstraintViolation(t *testing.T) { } func TestValidateSeedUniqueConstraintPass(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1563,6 +1615,7 @@ func TestValidateSeedUniqueConstraintPass(t *testing.T) { } func TestValidateSeedInvalidUUID(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1595,6 +1648,7 @@ func TestValidateSeedInvalidUUID(t *testing.T) { } func TestValidateSeedValidUUID(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1623,6 +1677,7 @@ func TestValidateSeedValidUUID(t *testing.T) { } func TestValidateSeedInvalidDatetime(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1656,6 +1711,7 @@ func TestValidateSeedInvalidDatetime(t *testing.T) { } func TestValidateSeedValidDatetime(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1685,6 +1741,7 @@ func TestValidateSeedValidDatetime(t *testing.T) { } func TestValidateSeedInvalidJSON(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1718,6 +1775,7 @@ func TestValidateSeedInvalidJSON(t *testing.T) { } func TestValidateSeedValidJSON(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1747,6 +1805,7 @@ func TestValidateSeedValidJSON(t *testing.T) { } func TestValidatePermissionRoleIdentifierInvalid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1778,6 +1837,7 @@ func TestValidatePermissionRoleIdentifierInvalid(t *testing.T) { } func TestValidatePermissionRoleSpecialTokensAllowed(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -1806,6 +1866,7 @@ func TestValidatePermissionRoleSpecialTokensAllowed(t *testing.T) { } func TestValidateSeedDateTypeMismatch(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Event"}, @@ -1839,6 +1900,7 @@ func TestValidateSeedDateTypeMismatch(t *testing.T) { } func TestValidateSeedDateValid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Event"}, @@ -1868,6 +1930,7 @@ func TestValidateSeedDateValid(t *testing.T) { } func TestValidateSeedEnumInvalidValue(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Enums: map[string][]string{ @@ -1904,6 +1967,7 @@ func TestValidateSeedEnumInvalidValue(t *testing.T) { } func TestValidateSeedEnumValidValue(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, Enums: map[string][]string{ @@ -1936,6 +2000,7 @@ func TestValidateSeedEnumValidValue(t *testing.T) { } func TestValidateSeedArrayInvalidValue(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Item"}, @@ -1969,6 +2034,7 @@ func TestValidateSeedArrayInvalidValue(t *testing.T) { } func TestValidateSeedArrayValidValue(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Item"}, @@ -1998,6 +2064,7 @@ func TestValidateSeedArrayValidValue(t *testing.T) { } func TestValidateStringMinMaxNonNumeric(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"User"}, @@ -2027,6 +2094,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"}, @@ -2065,6 +2133,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"}, @@ -2098,6 +2167,7 @@ func TestValidateNoCircularRelationWarningForAcyclic(t *testing.T) { } func TestValidateNoCircularRelationWarningForSelfReference(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Category"}, @@ -2123,6 +2193,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"}, @@ -2157,6 +2228,7 @@ func TestValidateNoCircularRelationWarningForManyToMany(t *testing.T) { } func TestValidateDefaultDateInvalid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Event"}, @@ -2186,6 +2258,7 @@ func TestValidateDefaultDateInvalid(t *testing.T) { } func TestValidateDefaultUuidInvalid(t *testing.T) { + t.Parallel() schema := &parser.ParsedSchema{ Project: parser.ProjectConfig{Name: "Test"}, EntityOrder: []string{"Doc"}, @@ -2219,6 +2292,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"}, diff --git a/pkg/textutil/case_convert_test.go b/pkg/textutil/case_convert_test.go index 86ee0e6..d85a351 100644 --- a/pkg/textutil/case_convert_test.go +++ b/pkg/textutil/case_convert_test.go @@ -3,6 +3,7 @@ package textutil import "testing" func TestSnakeCase(t *testing.T) { + t.Parallel() cases := []struct { name string in string @@ -38,6 +39,7 @@ func TestSnakeCase(t *testing.T) { } for _, c := range cases { 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) } @@ -46,6 +48,7 @@ func TestSnakeCase(t *testing.T) { } func TestKebabCase(t *testing.T) { + t.Parallel() cases := []struct { name string in string @@ -63,6 +66,7 @@ func TestKebabCase(t *testing.T) { } for _, c := range cases { 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) } @@ -74,6 +78,7 @@ 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) { + t.Parallel() cases := []struct { name string in string @@ -101,6 +106,7 @@ func TestToDatabaseColumnName(t *testing.T) { } for _, c := range cases { 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_test.go b/pkg/textutil/textutil_test.go index 6e4c55b..0d4a281 100644 --- a/pkg/textutil/textutil_test.go +++ b/pkg/textutil/textutil_test.go @@ -3,6 +3,7 @@ package textutil import "testing" func TestPluralize(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -17,12 +18,13 @@ func TestPluralize(t *testing.T) { {"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 + {"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 { 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) @@ -32,6 +34,7 @@ func TestPluralize(t *testing.T) { } func TestSingularize(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -48,6 +51,7 @@ func TestSingularize(t *testing.T) { } for _, tt := range tests { 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) @@ -57,6 +61,7 @@ func TestSingularize(t *testing.T) { } func TestFKName(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -69,6 +74,7 @@ func TestFKName(t *testing.T) { } for _, tt := range tests { 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) } @@ -77,6 +83,7 @@ func TestFKName(t *testing.T) { } func TestPascalCase(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -92,6 +99,7 @@ func TestPascalCase(t *testing.T) { } for _, tt := range tests { 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) @@ -101,6 +109,7 @@ func TestPascalCase(t *testing.T) { } func TestCamelCase(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -112,6 +121,7 @@ func TestCamelCase(t *testing.T) { } 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) @@ -121,6 +131,7 @@ func TestCamelCase(t *testing.T) { } func TestSplitIdentifier(t *testing.T) { + t.Parallel() tests := []struct { name string input string @@ -134,6 +145,7 @@ func TestSplitIdentifier(t *testing.T) { } for _, tt := range tests { 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) From 56628f6495293b0ea27ddfb7aa2544068ea51459 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:57:50 +0300 Subject: [PATCH 06/83] CI: avoid duplicate runs and drop vet --- .github/workflows/bridges.yml | 4 +++- .github/workflows/ci.yml | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/bridges.yml b/.github/workflows/bridges.yml index 7976a79..4e55aeb 100644 --- a/.github/workflows/bridges.yml +++ b/.github/workflows/bridges.yml @@ -9,7 +9,9 @@ name: bridges # keeps the toolchain single-language (Go only). on: + # PR checks cover feature branches; push runs once after a merge to main. push: + branches: [main] paths: - 'bridges/**' - 'internal/**' @@ -37,7 +39,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: '1.27' + go-version: '1.27.4' cache: true cache-dependency-path: go.sum diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 63bacdd..98f6423 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/**' @@ -47,9 +50,6 @@ jobs: - name: Build run: go build ./cmd/domaincraft - - name: Vet - run: go vet ./... - - name: Test run: go test ./... From 74ff4b81c8c47037f634a012fb59072ebc10721d Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:32 +0300 Subject: [PATCH 07/83] Core: reject relation primary keys and harden seed generation --- internal/ir/build_entities.go | 16 +- internal/ir/build_entities_test.go | 115 ++++++++++++++ internal/ir/endpoints.go | 10 +- internal/ir/models.go | 4 +- internal/ir/permissions.go | 12 +- internal/ir/query.go | 1 + internal/ir/typekind.go | 3 + internal/ir/typekind_test.go | 26 ++-- internal/seed/seed.go | 29 +++- internal/seed/seed_test.go | 97 ++++++++++++ internal/validator/validator.go | 85 ++++++---- internal/validator/validator_test.go | 223 +++++++++++++++++++++++++++ 12 files changed, 548 insertions(+), 73 deletions(-) diff --git a/internal/ir/build_entities.go b/internal/ir/build_entities.go index 8b9a6f8..bb04a3c 100644 --- a/internal/ir/build_entities.go +++ b/internal/ir/build_entities.go @@ -114,7 +114,7 @@ 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) } @@ -197,12 +197,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,7 +220,7 @@ 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) diff --git a/internal/ir/build_entities_test.go b/internal/ir/build_entities_test.go index a46e078..b6f5a59 100644 --- a/internal/ir/build_entities_test.go +++ b/internal/ir/build_entities_test.go @@ -1,6 +1,7 @@ package ir import ( + "strings" "testing" "github.com/DomainCraft/DomainCraft/internal/lexer" @@ -171,6 +172,120 @@ 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": mustParsedField(t, "id", "relation(Beta) [primary]"), + }, + }, + "Beta": { + Name: "Beta", + NamePlural: "Betas", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": 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 := 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": mustParsedField(t, "userId", "relation(User)"), + }, + }, + "User": { + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": 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 { diff --git a/internal/ir/endpoints.go b/internal/ir/endpoints.go index 4cb8d0e..e201821 100644 --- a/internal/ir/endpoints.go +++ b/internal/ir/endpoints.go @@ -48,15 +48,7 @@ func (e IREndpoint) AuthPolicy() string { // 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 + return e.SuccessStatus == status || slices.Contains(e.ErrorStatuses, status) } // Endpoints returns the standard REST endpoint contract for the entity, in a diff --git a/internal/ir/models.go b/internal/ir/models.go index 29cc94d..1495661 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -114,13 +114,13 @@ type IRDeployConfig struct { Port int // exposed port (default: 8080) } -// Versioning enables/disables API versioning and the default version string. +// IRVersioningConfig controls API versioning and the default version string. type IRVersioningConfig struct { Enabled bool DefaultVersion string } -// RateLimitConfig represents the HTTP request rate limiting policy in IR. +// IRRateLimitConfig represents the HTTP request rate limiting policy in IR. type IRRateLimitConfig struct { Enabled bool Policy string // fixed | sliding diff --git a/internal/ir/permissions.go b/internal/ir/permissions.go index 8d88bc7..7bae330 100644 --- a/internal/ir/permissions.go +++ b/internal/ir/permissions.go @@ -1,6 +1,10 @@ package ir -import "github.com/DomainCraft/DomainCraft/internal/specmeta" +import ( + "slices" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) // IRPermissionPlan is the core-computed authorization plan for one operation // (read/create/update/delete). The bridge no longer parses `*` wildcards or @@ -28,10 +32,8 @@ func (p *IRPermissions) HasOwnerToken() bool { 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 diff --git a/internal/ir/query.go b/internal/ir/query.go index b050e2b..2f2b28b 100644 --- a/internal/ir/query.go +++ b/internal/ir/query.go @@ -16,6 +16,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" diff --git a/internal/ir/typekind.go b/internal/ir/typekind.go index efb1621..b120e47 100644 --- a/internal/ir/typekind.go +++ b/internal/ir/typekind.go @@ -28,6 +28,7 @@ func (f IRField) IsUUID() bool { return f.DatabaseType == "uuid" } // IsUuid reports whether the field holds a UUID. // // Deprecated: use IsUUID. Kept as an alias for bridges using the old casing. +//nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates func (f IRField) IsUuid() bool { return f.IsUUID() } // IsText reports whether the field holds a string/text value. @@ -65,6 +66,7 @@ func (f IRField) IsJSON() bool { // IsJson reports whether the field holds a JSON document. // // Deprecated: use IsJSON. +//nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates func (f IRField) IsJson() bool { return f.IsJSON() } // IsJSONB reports whether the field holds a jsonb document specifically @@ -75,6 +77,7 @@ func (f IRField) IsJSONB() bool { return f.DatabaseType == "jsonb" } // IsJsonB reports whether the field holds a jsonb document. // // Deprecated: use IsJSONB. +//nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates func (f IRField) IsJsonB() bool { return f.IsJSONB() } // IsString reports whether the field holds a bounded string column diff --git a/internal/ir/typekind_test.go b/internal/ir/typekind_test.go index 2783621..3efb1d1 100644 --- a/internal/ir/typekind_test.go +++ b/internal/ir/typekind_test.go @@ -7,12 +7,12 @@ func TestIRFieldTypePredicates(t *testing.T) { 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 }{ - {name: "uuid", dbType: "uuid", isUuid: true, enumName: "uuid"}, + {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"}, @@ -22,8 +22,8 @@ func TestIRFieldTypePredicates(t *testing.T) { {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: "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"}, @@ -32,8 +32,8 @@ func TestIRFieldTypePredicates(t *testing.T) { t.Run(c.name, func(t *testing.T) { t.Parallel() 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.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) @@ -56,8 +56,8 @@ func TestIRFieldTypePredicates(t *testing.T) { 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.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) @@ -75,7 +75,7 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { name string dbType string isString, isBigInt, isDecimal bool - isJsonB bool + isJSONB bool }{ {name: "string", dbType: "string", isString: true}, {name: "text", dbType: "text", isString: false}, @@ -84,7 +84,7 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { {name: "float", dbType: "float"}, {name: "decimal", dbType: "decimal", isDecimal: true}, {name: "json", dbType: "json"}, - {name: "jsonb", dbType: "jsonb", isJsonB: true}, + {name: "jsonb", dbType: "jsonb", isJSONB: true}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -99,8 +99,8 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { 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) + if got := f.IsJsonB(); got != c.isJSONB { + t.Errorf("%q IsJsonB() = %v, want %v", c.dbType, got, c.isJSONB) } }) } diff --git a/internal/seed/seed.go b/internal/seed/seed.go index 60a0b77..db06c7b 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -142,7 +142,7 @@ func valueFor(field ir.IRField, project *ir.IRProject, generated map[string][]an } if field.IsRelation { - return relationValue(field, generated) + return relationValue(field, generated, record) } return scalarValue(field, project, counter, record) @@ -150,9 +150,11 @@ func valueFor(field ir.IRField, project *ir.IRProject, generated map[string][]an // 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][]any) any { +// 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(field ir.IRField, generated map[string][]any, record int) any { if field.IsMany { return nil } @@ -160,7 +162,10 @@ func relationValue(field ir.IRField, generated map[string][]any) any { 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. @@ -240,11 +245,19 @@ 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 { + if n < 0 { + n = 0 + } + if n < len(v) { + v = v[:n] + } } return v } diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index 9c476b7..fe4912a 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -345,6 +345,103 @@ func TestNormalizeCoerceEdgeCases(t *testing.T) { } } +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.IRProject{ + Entities: []ir.IREntity{ + { + Name: "Item", + Fields: []ir.IRField{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "name", DatabaseType: "string", Validations: []ir.IRValidation{{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) + } + }) + } +} + +func TestGenerateRotatesRelationPKs(t *testing.T) { + t.Parallel() + project := &ir.IRProject{ + Entities: []ir.IREntity{ + { + Name: "Category", + Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + }, + { + Name: "Product", + Fields: []ir.IRField{ + {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.IRField + pks []any + record int + want any + }{ + {name: "first parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 0, want: "a"}, + {name: "second parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 1, want: "b"}, + {name: "wraps around", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 3, want: "a"}, + {name: "single parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a"}, record: 5, want: "a"}, + {name: "no parents", field: ir.IRField{RelationTarget: "Category"}, pks: nil, record: 2}, + {name: "many relation", field: ir.IRField{RelationTarget: "Category", IsMany: true}, pks: []any{"a", "b"}, record: 0}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := relationValue(tt.field, map[string][]any{"Category": tt.pks}, tt.record) + if got != tt.want { + t.Errorf("relationValue() = %v, want %v", got, tt.want) + } + }) + } +} + func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { t.Parallel() project := &ir.IRProject{ diff --git a/internal/validator/validator.go b/internal/validator/validator.go index c0a8add..e426421 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -14,6 +14,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. @@ -56,6 +57,7 @@ type Validator struct { schema *parser.ParsedSchema } +// New creates a Validator for the parsed schema. func New(schema *parser.ParsedSchema) *Validator { return &Validator{schema: schema} } @@ -65,6 +67,7 @@ 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"}} @@ -105,7 +108,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 @@ -449,18 +455,22 @@ func (v *Validator) validateEnums() []ValidationError { "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, invalid("", name, "enum value must not be empty")) } - lower := strings.ToLower(val) - if seen[lower] { - errs = append(errs, warnf("", name, - "duplicate enum value %q (case-insensitive collision)", val)) + 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 } } @@ -520,6 +530,17 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit // Must not have duplicate primary keys. errs = append(errs, invalidf(entityName, "", "entity has %d primary keys; expected exactly one", pkCount)) + } else { + // A relation cannot be a primary key: the IR resolves relation types + // through the target's primary key, which recurses on relation-PK cycles. + for _, fieldName := range entity.FieldOrder { + field := entity.Fields[fieldName] + if field != nil && field.IsPrimary && field.IsRelation() { + errs = append(errs, invalidf(entityName, fieldName, + "primary key cannot be a relation field (target '%s'); use a scalar id field", field.TargetEntity)) + break + } + } } // Duplicate feature names. @@ -697,6 +718,10 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa 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. @@ -735,9 +760,14 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa // 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 != "" { - if _, err := strconv.ParseFloat(val, 64); err != nil { + if n, err := strconv.ParseFloat(val, 64); err != nil { errs = append(errs, invalidf(entityName, fieldName, "validation '%s' value %q is not a valid number", mod, val)) + } else if isString && (mod == "min" || mod == "max") && 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)) } } } @@ -755,13 +785,7 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa // Enum default must be one of the declared enum values. if field.Type == "enum" && 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, invalidf(entityName, fieldName, "default value '%s' is not a declared value of enum '%s'; valid values: %s", field.DefaultValue, field.TargetType, @@ -814,13 +838,7 @@ func validateFuncDefault(entityName, fieldName, ftype, funcName string) []Valida "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, invalidf(entityName, fieldName, "default '%s()' is not valid for type %s; allowed types: %s", funcName, ftype, strings.Join(allowedTypes, ", "))) @@ -1033,21 +1051,28 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } case "int", "bigint": - switch seedValue.(type) { + switch n := seedValue.(type) { case int, int32, int64, float32, float64: // numeric OK case string: - // string representation — OK if it parses + // A string must parse; otherwise seed coercion silently yields 0. + if _, err := strconv.ParseInt(n, 10, 64); err != nil { + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid %s", entryIdx, n, ftype)) + } default: errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } case "float", "decimal": - switch seedValue.(type) { + switch n := seedValue.(type) { case int, int32, int64, float32, float64: // numeric OK case string: - // string representation — OK + if _, err := strconv.ParseFloat(n, 64); err != nil { + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %q is not a valid %s", entryIdx, n, ftype)) + } default: errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) @@ -1112,13 +1137,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx break } if values, defined := v.schema.Enums[field.TargetType]; defined { - found := false - for _, val := range values { - if val == sv { - found = true - break - } - } + found := slices.Contains(values, sv) if !found { errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %q is not a declared value of enum '%s'; valid values: %s", entryIdx, sv, field.TargetType, diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index 1ca5b1b..aa3593e 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -2315,3 +2315,226 @@ 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": mustParsedField(t, "id", tt.pkDef), + }, + }, + "Parent": { + Name: "Parent", + FieldOrder: []string{"id"}, + Fields: map[string]*parser.ParsedField{ + "id": 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 := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Doc"}, + Entities: map[string]*parser.ParsedEntity{ + "Doc": { + Name: "Doc", + FieldOrder: []string{"id", "name"}, + Fields: map[string]*parser.ParsedField{ + "id": mustParsedField(t, "id", "uuid [primary]"), + "name": mustParsedField(t, "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 := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Doc"}, + Enums: map[string][]string{"Status": tt.values}, + Entities: map[string]*parser.ParsedEntity{ + "Doc": { + Name: "Doc", + FieldOrder: []string{"id", "status"}, + Fields: map[string]*parser.ParsedField{ + "id": mustParsedField(t, "id", "uuid [primary]"), + "status": mustParsedField(t, "status", "enum(Status)"), + }, + }, + }, + } + + 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 := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Doc"}, + Entities: map[string]*parser.ParsedEntity{ + "Doc": { + Name: "Doc", + FieldOrder: []string{"id", "count", "big", "price"}, + Fields: map[string]*parser.ParsedField{ + "id": mustParsedField(t, "id", "uuid [primary]"), + "count": mustParsedField(t, "count", "int"), + "big": mustParsedField(t, "big", "bigint"), + "price": mustParsedField(t, "price", "decimal"), + }, + 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 := &parser.ParsedSchema{ + Project: parser.ProjectConfig{Name: "Test"}, + EntityOrder: []string{"Doc"}, + Enums: map[string][]string{"Status": {"A", "a", ""}}, + Entities: map[string]*parser.ParsedEntity{ + "Doc": { + Name: "Doc", + FieldOrder: []string{"id", "status"}, + Fields: map[string]*parser.ParsedField{ + "id": mustParsedField(t, "id", "uuid [primary]"), + "status": mustParsedField(t, "status", "enum(Status)"), + }, + }, + }, + } + + 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) + } +} From dcc596349d9e46d3765fed9d035aae97e60e58bb Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:44 +0300 Subject: [PATCH 08/83] Bridges: fail closed on contracts and restrict network and cache paths --- internal/bridge/clone.go | 27 +- internal/bridge/clone_policy_test.go | 14 +- internal/bridge/context.go | 13 +- internal/bridge/embed.go | 73 +++++- internal/bridge/hardening_test.go | 314 ++++++++++++++++++++++++ internal/bridge/meta.go | 4 + internal/bridge/resolve_ext.go | 72 +++++- internal/bridge/resolver.go | 62 +++++ internal/bridge/update.go | 163 +++++++++--- internal/bridge/update_contract_test.go | 47 +++- internal/bridge/update_safety_test.go | 85 ++++++- internal/packages/cache.go | 46 +++- internal/packages/registry.go | 142 +++++++++-- internal/packages/registry_test.go | 4 +- internal/packages/ssrf_test.go | 204 +++++++++++++++ 15 files changed, 1161 insertions(+), 109 deletions(-) create mode 100644 internal/bridge/hardening_test.go create mode 100644 internal/packages/ssrf_test.go diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index aeaf6f2..329e2d3 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -132,6 +132,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 @@ -142,12 +148,16 @@ 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". + c, rerr := remoteContractVersion(entry, update.RemoteBranch) + if rerr != nil { + warnOpts(opts, "skipping update of %q: cannot read remote contract: %v", entry.ID, rerr) + return nil + } + if cerr := shouldApplyContract(c); 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. @@ -196,12 +206,13 @@ func CloneBridge(entry RegistryEntry) error { cacheDir := CachePath(entry) parent := filepath.Dir(cacheDir) - if err := os.MkdirAll(parent, 0o755); err != nil { + 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) } url := fmt.Sprintf("https://github.com/%s.git", entry.GitHub) - cmd := exec.CommandContext(commandCtx, "git", "clone", "--depth", "1", url, cacheDir) + cmd := exec.CommandContext(commandCtx, "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) diff --git a/internal/bridge/clone_policy_test.go b/internal/bridge/clone_policy_test.go index f9fd46d..2d7f935 100644 --- a/internal/bridge/clone_policy_test.go +++ b/internal/bridge/clone_policy_test.go @@ -38,6 +38,7 @@ func TestMaybeUpdatePolicies(t *testing.T) { name string interval time.Duration remoteYAML string + pin string confirm func(RegistryEntry, *Update) (bool, error) wantWarn string wantConfirm bool @@ -76,6 +77,16 @@ func TestMaybeUpdatePolicies(t *testing.T) { remoteYAML: "name: test\ncontract_version: 2\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", + }, } for _, tt := range tests { @@ -102,6 +113,7 @@ func TestMaybeUpdatePolicies(t *testing.T) { Version: "1.0.0", Commit: "cached-head", Branch: "main", + Pin: tt.pin, LastCheckedAt: lastChecked, }); err != nil { t.Fatal(err) @@ -122,7 +134,7 @@ func TestMaybeUpdatePolicies(t *testing.T) { opts := &EnsureOptions{ Interval: tt.interval, ConfirmUpdate: confirm, - Warn: func(format string, args ...any) { warnings = append(warnings, format) }, + Warn: func(format string, _ ...any) { warnings = append(warnings, format) }, } err := maybeUpdate(entry, opts) diff --git a/internal/bridge/context.go b/internal/bridge/context.go index 72b84d2..0859605 100644 --- a/internal/bridge/context.go +++ b/internal/bridge/context.go @@ -2,13 +2,22 @@ package bridge import "context" -// commandCtx is cancelled on interrupt so git children started by bridge -// resolution and updates are never orphaned. main wires the signal context. +// 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() // SetCommandContext wires the CLI's cancellable context into bridge operations. +// A nil context is ignored so a caller cannot clear the cancellation signal. func SetCommandContext(ctx context.Context) { if ctx != nil { commandCtx = ctx } } + +// 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. +func CommandContext() context.Context { + return commandCtx +} diff --git a/internal/bridge/embed.go b/internal/bridge/embed.go index cc0dd77..4b679fe 100644 --- a/internal/bridge/embed.go +++ b/internal/bridge/embed.go @@ -1,6 +1,7 @@ package bridge import ( + "errors" "fmt" "io/fs" "os" @@ -28,7 +29,12 @@ func TryMaterializeEmbedded(entry RegistryEntry, opts *EnsureOptions) (bool, err } 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. + if err := refuseSymlinks(BridgeCacheDir(), dst); 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,7 +49,8 @@ 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 { return fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error { if err != nil { @@ -52,16 +59,72 @@ 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 err := refuseSymlinks(dst, target); err != nil { + return err + } if d.IsDir() { - return os.MkdirAll(target, 0o755) + return os.MkdirAll(target, 0o755) //nolint:gosec // bridge cache dirs must stay readable across CLI runs } data, err := fs.ReadFile(fsys, path) if err != nil { return err } - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { //nolint:gosec // bridge cache dirs must stay readable across CLI runs return err } - return os.WriteFile(target, data, 0o644) + return os.WriteFile(target, data, 0o644) //nolint:gosec // bridge templates are source files read by other users/tools }) } + +// refuseSymlinks lstats base and each existing component of target below it. +// A symlink at any level would let os.WriteFile/MkdirAll escape the cache, so +// the materialization refuses it before touching the filesystem. +func refuseSymlinks(base, target string) error { + baseAbs, err := filepath.Abs(base) + if err != nil { + return err + } + targetAbs, err := filepath.Abs(target) + if err != nil { + return err + } + rel, err := filepath.Rel(baseAbs, targetAbs) + if err != nil { + return fmt.Errorf("resolve cache path %q: %w", target, err) + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return fmt.Errorf("target %q escapes cache directory", target) + } + if err := lstatNoSymlink(baseAbs); err != nil { + return err + } + if rel == "." { + return nil + } + cur := baseAbs + for part := range strings.SplitSeq(rel, string(filepath.Separator)) { + if part == "" || part == "." { + continue + } + cur = filepath.Join(cur, part) + if err := lstatNoSymlink(cur); err != nil { + return err + } + } + return nil +} + +// lstatNoSymlink fails on an existing symlink and ignores missing paths. +func lstatNoSymlink(path string) error { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + 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) + } + return nil +} diff --git a/internal/bridge/hardening_test.go b/internal/bridge/hardening_test.go new file mode 100644 index 0000000..c690b0f --- /dev/null +++ b/internal/bridge/hardening_test.go @@ -0,0 +1,314 @@ +package bridge + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/appdir" +) + +// 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) { + if err := os.Symlink("target", filepath.Join(t.TempDir(), "symlink-probe")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + + 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.Fatal(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.Fatal(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. + if err := refuseSymlinks(t.TempDir(), filepath.Join(t.TempDir(), "elsewhere")); err == nil { + t.Error("refuseSymlinks 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 := filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", "main", "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") + + src := filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, "main") + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", "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) + } + + original := httpGetBodyFn + defer func() { httpGetBodyFn = original }() + httpGetBodyFn = func(url string) ([]byte, error) { + switch { + case strings.Contains(url, "/commits/main"): + return []byte(`{"sha":"` + testGit(t, remote, "rev-parse", "HEAD") + `"}`), nil + case strings.Contains(url, "/repos/"): + return []byte(`{"default_branch":"main"}`), nil + } + return nil, os.ErrNotExist + } + + // 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") + + 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) + } + }) + } +} + +// 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") + } +} diff --git a/internal/bridge/meta.go b/internal/bridge/meta.go index fe52259..b327676 100644 --- a/internal/bridge/meta.go +++ b/internal/bridge/meta.go @@ -25,6 +25,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 diff --git a/internal/bridge/resolve_ext.go b/internal/bridge/resolve_ext.go index 66facc6..6d8c888 100644 --- a/internal/bridge/resolve_ext.go +++ b/internal/bridge/resolve_ext.go @@ -61,18 +61,64 @@ func FindMonorepoBridge(dir, relPath string) string { } } -// 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. +// 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 { + cur, err := filepath.Abs(dir) + if err != nil { + return "" + } + for { + 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") { + return cur + } + } + parent := filepath.Dir(cur) + if parent == cur { + return "" + } + cur = parent + } +} + +// samePath compares two absolute paths using the filesystem's case rules. +func samePath(a, b string) bool { + a, b = filepath.Clean(a), filepath.Clean(b) + if os.PathSeparator == '\\' { + return strings.EqualFold(a, b) + } + return a == b +} + +// 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 "" } - suffix := filepath.Join("bridges", filepath.FromSlash(entryPath)) - if strings.HasSuffix(filepath.Clean(dir), suffix) { - return filepath.ToSlash(suffix) + embedded := "bridges/" + filepath.ToSlash(entryPath) + if _, err := domaincraft.Bridges.ReadDir(embedded); err != nil { + return "" // not a bundled bridge in this binary } - return "" + rel := filepath.Join("bridges", filepath.FromSlash(entryPath)) + abs, err := filepath.Abs(dir) + if err != nil { + return "" + } + root := monorepoRoot(abs) + if root == "" || !samePath(abs, filepath.Join(root, rel)) { + return "" + } + return filepath.ToSlash(rel) } // IsOfficialBundled reports whether dir is a bundled monorepo bridge, i.e. it @@ -122,14 +168,18 @@ func (e RegistryEntry) Status(checkRemote bool) BridgeStatus { if !checkRemote { return s } + // 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 := CheckForUpdate(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. + 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 c, rerr := remoteContractVersion(e, u.RemoteBranch); rerr == nil { if cerr := shouldApplyContract(c); cerr == nil { s.Outdated = true - s.RemoteReachable = true } } } diff --git a/internal/bridge/resolver.go b/internal/bridge/resolver.go index e5c9215..d438695 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "strings" + "time" ) // Resolver maps a bridge identifier to a local filesystem path. @@ -72,6 +73,11 @@ func (r *Resolver) Resolve(input string) (string, error) { return "", fmt.Errorf("bridge %q not found: invalid repository name", input) } repo, ref := splitPinRef(input) + if ref != "" { + if err := validatePinRef(ref); err != nil { + return "", err + } + } entry := RegistryEntry{ ID: parts[1], GitHub: repo, @@ -84,6 +90,11 @@ func (r *Resolver) Resolve(input string) (string, error) { if err := checkoutPinnedRef(path, ref); 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 "", err + } } return path, nil } @@ -100,10 +111,44 @@ func splitPinRef(s string) (repo, ref string) { 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) } @@ -111,6 +156,23 @@ 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 { + meta, err := ensureMeta(entry) + if err != nil { + return err + } + if meta == nil { + meta = newMetaFromCache(entry) + } + meta.Pin = ref + meta.Commit = gitHead(entry) + meta.LastCheckedAt = time.Now() + return WriteMeta(entry, meta) +} + // 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/update.go b/internal/bridge/update.go index a71b14c..a1321d2 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -2,9 +2,11 @@ package bridge import ( "encoding/json" + "errors" "fmt" "io" "net/http" + "net/url" "os" "os/exec" "strings" @@ -32,18 +34,32 @@ const DefaultUpdateInterval = 24 * time.Hour const CoreContractVersion = 1 // parseBridgeContractVersion reads `contract_version` from bridge.yaml bytes. -// An absent field means contract v1. -func parseBridgeContractVersion(data []byte) int { +// An absent field means contract v1. Any other unreadable value is an error: +// a malformed manifest must never be silently downgraded to "supported". +func parseBridgeContractVersion(data []byte) (int, error) { + // A truncated body may still be valid YAML (e.g. a scalar or a list), so + // require the document to be a mapping before reading the version. + var probe any + if err := yaml.Unmarshal(data, &probe); err != nil { + return 0, fmt.Errorf("parse bridge contract version: %w", err) + } + if _, ok := probe.(map[string]any); !ok { + return 0, fmt.Errorf("parse bridge contract version: manifest must be a YAML mapping") + } var cfg struct { ContractVersion int `yaml:"contract_version"` } if err := yaml.Unmarshal(data, &cfg); err != nil { - return 1 + return 0, fmt.Errorf("parse bridge contract version: %w", err) } - if cfg.ContractVersion == 0 { - return 1 + switch { + case cfg.ContractVersion == 0: + return 1, nil + case cfg.ContractVersion < 0: + return 0, fmt.Errorf("invalid contract_version %d", cfg.ContractVersion) + default: + return cfg.ContractVersion, nil } - return cfg.ContractVersion } // shouldApplyContract verifies that a bridge declaring contractVersion is @@ -57,8 +73,9 @@ func shouldApplyContract(contractVersion int) error { } // 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" @@ -67,7 +84,7 @@ func remoteContractVersion(entry RegistryEntry, ref string) (int, error) { if err != nil { return 0, err } - return parseBridgeContractVersion(body), nil + return parseBridgeContractVersion(body) } // Update describes a detected newer version of a cached bridge. Callers hand it @@ -139,6 +156,13 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { } cacheDir := CachePath(entry) + // A pinned checkout has an explicit ref. Remember it so a direct ApplyUpdate + // never leaves the cache on the default branch. + pin := "" + if meta, err := ReadMeta(entry); err == nil && meta != nil { + pin = meta.Pin + } + branch := "main" if u != nil && u.RemoteBranch != "" { branch = u.RemoteBranch @@ -149,14 +173,20 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { // Fast path: update the existing checkout in place. if _, err := runGit(cacheDir, "fetch", "--depth", "1", "origin", branch); err == nil { // 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) + } + contract, perr := parseBridgeContractVersion([]byte(out)) + if perr != nil { + return "", perr + } + if cerr := shouldApplyContract(contract); cerr != nil { + return "", cerr } if _, err := runGit(cacheDir, "reset", "--hard", "FETCH_HEAD"); err == nil { - return syncMetaAfterUpdate(entry, branch) + return finishUpdate(entry, branch, pin) } // reset failed — fall through to a clean re-clone } @@ -168,7 +198,34 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { if err := CloneBridge(entry); err != nil { return "", err } - return syncMetaAfterUpdate(entry, branch) + return finishUpdate(entry, branch, pin) +} + +// 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 != "" { + if err := checkoutPinnedRef(CachePath(entry), pin); err != nil { + return "", fmt.Errorf("restore pinned ref %q after update: %w", pin, err) + } + } + version, err := syncMetaAfterUpdate(entry, branch) + if err != nil || pin == "" { + return version, err + } + meta, err := ReadMeta(entry) + if err != nil { + return version, err + } + if meta == nil { + meta = &CacheMeta{ID: entry.ID, Source: entry.GitHub} + } + meta.Pin = pin + meta.Commit = gitHead(entry) + if err := WriteMeta(entry, meta); err != nil { + return version, err + } + return version, nil } // syncMetaAfterUpdate refreshes the cached checkout's metadata after a @@ -218,18 +275,54 @@ func githubAPIHead(entry RegistryEntry) (branch, commit string, err error) { return repo.DefaultBranch, c.SHA, 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) +// maxProbeBodyBytes caps remote probe responses (bridge.yaml, GitHub JSON). +const maxProbeBodyBytes = 1 << 20 + +// httpGetBody performs a GET bound to the CLI's command context and returns the +// response body. It reads one byte past the limit so an oversized body fails +// instead of being silently truncated into a plausible-looking manifest. +func httpGetBody(rawURL string) ([]byte, error) { + scope := redactedURLScope(rawURL) + req, err := http.NewRequestWithContext(CommandContext(), http.MethodGet, rawURL, nil) if err != nil { - return nil, err + return nil, fmt.Errorf("build probe request for %s: %w", scope, redactURLError(err)) + } + resp, err := httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("probe request to %s failed: %w", scope, redactURLError(err)) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, url) + return nil, fmt.Errorf("http %d for %s", resp.StatusCode, scope) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeBodyBytes+1)) + if err != nil { + return nil, fmt.Errorf("read response from %s: %w", scope, err) } - return io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if len(body) > maxProbeBodyBytes { + return nil, fmt.Errorf("response from %s exceeds %d bytes", scope, maxProbeBodyBytes) + } + return body, nil +} + +// redactURLError drops the raw URL carried by *url.Error (userinfo and query +// could be secrets) while keeping the underlying reason for %w wrapping. +func redactURLError(err error) error { + var urlErr *url.Error + if errors.As(err, &urlErr) && urlErr.Err != nil { + return urlErr.Err + } + return err +} + +// redactedURLScope reduces a URL to scheme and host for error messages, so +// credentials and query strings from a bridge's config never reach the log. +func redactedURLScope(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Hostname() == "" { + return "" + } + return u.Scheme + "://" + u.Hostname() } // runGit runs a git command in dir and returns its trimmed stdout. @@ -239,7 +332,7 @@ 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.CommandContext(commandCtx, "git", args...) + cmd := exec.CommandContext(commandCtx, "git", args...) //nolint:gosec // args passed separately; no shell interpretation cmd.Dir = dir cmd.Env = gitScrubbedEnv() out, err := cmd.Output() @@ -249,16 +342,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]bool{ + "HOME": true, "USERPROFILE": true, "HOMEDRIVE": true, "HOMEPATH": true, + "PATH": true, "PATHEXT": true, "SYSTEMROOT": true, "COMSPEC": true, + "TEMP": true, "TMP": true, "TMPDIR": true, "APPDATA": true, + "LOCALAPPDATA": true, "PROGRAMDATA": true, "LANG": true, "LC_ALL": true, + "LANGUAGE": true, "TZ": true, "SSL_CERT_FILE": true, "SSL_CERT_DIR": true, +} + +// 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 gitEnvironmentNames[strings.ToUpper(name)] { + 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 1274ca7..0adb8f4 100644 --- a/internal/bridge/update_contract_test.go +++ b/internal/bridge/update_contract_test.go @@ -8,19 +8,27 @@ import ( 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 1", in: "name: b\n", want: 1}, + {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 { t.Run(c.name, func(t *testing.T) { - if got := parseBridgeContractVersion([]byte(c.in)); got != c.want { - t.Errorf("%s: parseBridgeContractVersion = %d, want %d", c.name, got, c.want) + got, err := parseBridgeContractVersion([]byte(c.in)) + if (err != nil) != c.wantErr { + t.Fatalf("parseBridgeContractVersion error = %v, wantErr %v", err, c.wantErr) + } + if err == nil && got != c.want { + t.Errorf("parseBridgeContractVersion = %d, want %d", got, c.want) } }) } @@ -48,10 +56,14 @@ func TestRemoteContractVersion(t *testing.T) { if !strings.Contains(url, "/bridge.yaml") { return nil, fmt.Errorf("unexpected url %s", url) } - if strings.Contains(url, "unsupported") { + switch { + case strings.Contains(url, "unsupported"): return []byte("name: b\ncontract_version: 2\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"} @@ -63,4 +75,17 @@ func TestRemoteContractVersion(t *testing.T) { if v, err := remoteContractVersion(bad, "main"); err != nil || v != 2 { t.Errorf("unsupported contract = %d, %v; want 2", 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 } diff --git a/internal/bridge/update_safety_test.go b/internal/bridge/update_safety_test.go index 038e102..f700485 100644 --- a/internal/bridge/update_safety_test.go +++ b/internal/bridge/update_safety_test.go @@ -6,19 +6,28 @@ import ( "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 { +// 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(official, "bridge.yaml"), []byte("name: csharp-core\n"), 0o644); err != nil { + 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) } @@ -40,6 +49,64 @@ func TestIsOfficialBundled(t *testing.T) { 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`. diff --git a/internal/packages/cache.go b/internal/packages/cache.go index 09923db..104dc74 100644 --- a/internal/packages/cache.go +++ b/internal/packages/cache.go @@ -1,8 +1,10 @@ package packages import ( + "fmt" "os" "path/filepath" + "sync" "time" "github.com/DomainCraft/DomainCraft/internal/appdir" @@ -37,6 +39,15 @@ var resolveVersionFn = ResolveVersion // a separate 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. +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 @@ -60,14 +71,21 @@ 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, err := appdir.CacheDir(bridgeID) + if err != nil { + return fmt.Errorf("resolve package cache dir for %q: %w", bridgeID, err) + } + 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 @@ -77,6 +95,9 @@ func persistVersionCache(bridgeID string, entries map[string]versionEntry) { func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, error) { key := cacheKey(registryURL, packageID) + cacheMu.Lock() + defer cacheMu.Unlock() + entries, err := versionStore(bridgeID) if err != nil { // Cache directory unusable — resolve uncached rather than fail. @@ -96,7 +117,9 @@ func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, erro } entries[key] = versionEntry{Value: version, StoredAt: time.Now()} - persistVersionCache(bridgeID, entries) + if err := persistVersionCacheFn(bridgeID, entries); err != nil { + return "", err + } return version, nil } @@ -106,6 +129,9 @@ func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, erro func ResolveVersionCachedForFramework(bridgeID, registryURL, packageID, targetFramework string) (string, error) { key := cacheKey(registryURL, packageID) + "\x00" + targetFramework + cacheMu.Lock() + defer cacheMu.Unlock() + entries, err := versionStore(bridgeID) if err != nil { return resolveVersionForFrameworkFn(registryURL, packageID, targetFramework) @@ -122,6 +148,8 @@ func ResolveVersionCachedForFramework(bridgeID, registryURL, packageID, targetFr return "", nil } entries[key] = versionEntry{Value: version, StoredAt: time.Now()} - persistVersionCache(bridgeID, entries) + if err := persistVersionCacheFn(bridgeID, entries); err != nil { + return "", err + } return version, nil } diff --git a/internal/packages/registry.go b/internal/packages/registry.go index ae94a58..0918828 100644 --- a/internal/packages/registry.go +++ b/internal/packages/registry.go @@ -2,7 +2,9 @@ package packages import ( + "context" "encoding/json" + "errors" "fmt" "io" "net" @@ -11,31 +13,67 @@ import ( "strconv" "strings" "time" + + "github.com/DomainCraft/DomainCraft/internal/bridge" ) -var registryClient = &http.Client{ - Timeout: 5 * time.Second, - CheckRedirect: func(req *http.Request, _ []*http.Request) error { - if err := validateRegistryURL(req.URL.String()); err != nil { - return err - } - return nil - }, +// maxRegistryResponseBytes caps a version index read from a registry. +const maxRegistryResponseBytes = 1 << 20 + +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() + tr.DialContext = restrictedRegistryDialer + return &http.Client{ + Timeout: 5 * time.Second, + Transport: tr, + CheckRedirect: func(req *http.Request, _ []*http.Request) error { + if err := validateRegistryURL(req.URL.String()); err != nil { + return err + } + return validateRegistryTarget(req.Context(), req.URL) + }, + } } // allowLocalRegistryForTests is set only by tests using httptest TLS servers. var allowLocalRegistryForTests bool -// validateRegistryURL keeps registry requests on https and away from loopback, -// private and link-local addresses. registry_url comes from bridge.yaml, which -// may be cloned from an untrusted repository. +// 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 { - return fmt.Errorf("invalid registry URL %q: %w", raw, err) + // url.Error repeats the raw URL (including userinfo/query); keep only + // its reason and wrap that instead. + var urlErr *url.Error + if errors.As(err, &urlErr) && urlErr.Err != nil { + err = urlErr.Err + } + return fmt.Errorf("invalid registry URL %q: %w", redactedRegistryURL(raw), err) } if u.Scheme != "https" || u.Host == "" { - return fmt.Errorf("registry URL must be an absolute https URL: %q", raw) + return fmt.Errorf("registry URL must be an absolute https URL: %q", redactedRegistryURL(raw)) } host := strings.ToLower(u.Hostname()) if allowLocalRegistryForTests { @@ -44,13 +82,76 @@ func validateRegistryURL(raw string) error { if host == "localhost" || strings.HasSuffix(host, ".localhost") { return fmt.Errorf("registry host %q is not allowed", host) } - if ip := net.ParseIP(host); ip != nil && - (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) { + if ip := net.ParseIP(host); ip != nil && !allowedRegistryIP(ip) { return fmt.Errorf("registry host %q is not allowed", host) } return nil } +// validateRegistryTarget resolves the host and rejects a disallowed address. +func validateRegistryTarget(ctx context.Context, u *url.URL) error { + if allowLocalRegistryForTests { + return nil + } + host := strings.ToLower(u.Hostname()) + ips, err := lookupRegistryIPs(ctx, host) + if err != nil { + return fmt.Errorf("resolve registry host %q: %w", host, err) + } + if len(ips) == 0 { + return fmt.Errorf("registry host %q has no addresses", host) + } + for _, addr := range ips { + if !allowedRegistryIP(addr.IP) { + return fmt.Errorf("registry host %q resolves to disallowed address %s", host, addr.IP) + } + } + return nil +} + +// 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", redactedRegistryURL("https://"+addr)) + } + return dialer.DialContext(ctx, network, addr) + } + ips, err := lookupRegistryIPs(ctx, host) + if err != nil { + return nil, fmt.Errorf("resolve registry host: %w", err) + } + if len(ips) == 0 { + return nil, fmt.Errorf("registry host %q has no addresses", host) + } + for _, candidate := range ips { + if !allowedRegistryIP(candidate.IP) { + return nil, fmt.Errorf("registry host %q resolves to disallowed address %s", host, candidate.IP) + } + } + return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].IP.String(), port)) +} + +// redactedRegistryURL keeps only scheme and host for error messages, so +// credentials and query strings from a bridge's config never reach the log. +func redactedRegistryURL(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Hostname() == "" { + return "" + } + return u.Scheme + "://" + u.Hostname() +} + // 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) { @@ -144,7 +245,7 @@ func fetchVersions(registryURL string, packageID string) ([]string, error) { return nil, err } - req, err := http.NewRequest("GET", registryEndpoint, nil) + req, err := http.NewRequestWithContext(bridge.CommandContext(), http.MethodGet, registryEndpoint, nil) if err != nil { return nil, err } @@ -162,8 +263,8 @@ func fetchVersions(registryURL string, packageID string) ([]string, error) { 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 { + // Limit response body to prevent OOM from malicious/misconfigured registries. + if err := json.NewDecoder(io.LimitReader(resp.Body, maxRegistryResponseBytes)).Decode(&result); err != nil { return nil, err } @@ -174,10 +275,7 @@ 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) { diff --git a/internal/packages/registry_test.go b/internal/packages/registry_test.go index 2bfc2db..8aea670 100644 --- a/internal/packages/registry_test.go +++ b/internal/packages/registry_test.go @@ -108,7 +108,7 @@ 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 := newTestRegistryServer(t, 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"]}`)) })) @@ -134,7 +134,7 @@ func TestResolveVersionForFrameworkRespectsTargetFramework(t *testing.T) { } func TestResolveVersionForFrameworkFallsBackWhenNoCompatibleVersion(t *testing.T) { - srv := newTestRegistryServer(t, 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() diff --git a/internal/packages/ssrf_test.go b/internal/packages/ssrf_test.go new file mode 100644 index 0000000..17ee56a --- /dev/null +++ b/internal/packages/ssrf_test.go @@ -0,0 +1,204 @@ +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 := resolveVersionFn + defer func() { resolveVersionFn = old }() + resolveVersionFn = 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 := ResolveVersionCached("shared", "https://reg.example/{id}", fmt.Sprintf("pkg%d", i)) + errs <- err + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("ResolveVersionCached: %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 := resolveVersionFn, persistVersionCacheFn + defer func() { + resolveVersionFn, persistVersionCacheFn = oldResolve, oldPersist + }() + resolveVersionFn = func(_, _ string) (string, error) { return "2.0.0", nil } + persistVersionCacheFn = func(string, map[string]versionEntry) error { + return errors.New("disk full") + } + + _, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("ResolveVersionCached 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 := ResolveVersion(srv.URL+"/{id}", "demo.pkg"); err == nil { + t.Fatal("ResolveVersion ignored the cancelled command context") + } +} From 393164b85668701b587251783b2523cca2163b57 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:52 +0300 Subject: [PATCH 09/83] Renderer: stage writes and make snapshot rewrites atomic --- internal/renderer/bundled_bridges_test.go | 8 +- internal/renderer/hardening_test.go | 190 ++++++++++++++++++ internal/renderer/load.go | 7 +- internal/renderer/render.go | 231 ++++++++++++++++------ internal/renderer/render_test.go | 54 ++++- internal/renderer/templates.go | 30 ++- internal/snapshot/hardening_test.go | 197 ++++++++++++++++++ internal/snapshot/paths.go | 35 ++++ internal/snapshot/rewrite.go | 133 +++++++------ internal/snapshot/snapshot.go | 44 +++-- 10 files changed, 770 insertions(+), 159 deletions(-) create mode 100644 internal/renderer/hardening_test.go create mode 100644 internal/snapshot/hardening_test.go diff --git a/internal/renderer/bundled_bridges_test.go b/internal/renderer/bundled_bridges_test.go index 8a30e38..57f7998 100644 --- a/internal/renderer/bundled_bridges_test.go +++ b/internal/renderer/bundled_bridges_test.go @@ -18,7 +18,13 @@ 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/hardening_test.go b/internal/renderer/hardening_test.go new file mode 100644 index 0000000..a9b152f --- /dev/null +++ b/internal/renderer/hardening_test.go @@ -0,0 +1,190 @@ +package renderer + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +// writeHardeningBridge lays out a minimal bridge directory for the filesystem +// hardening tests. Keys are forward-slash relative paths. +func writeHardeningBridge(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 := writeHardeningBridge(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.IRProject{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) + } +} + +// 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 := writeHardeningBridge(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.IRProject{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 := writeHardeningBridge(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.IRProject{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) + }) + } +} + +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()) + } + } +} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index d212a0c..549e8a7 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "text/template" "github.com/DomainCraft/DomainCraft/internal/ir" @@ -68,7 +69,7 @@ var layerRe = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) // loadSource loads a single bridge directory (its bridge.yaml). func loadSource(bridgePath string) (sourceConfig, error) { bridgeDir, configPath := resolveBridgePath(bridgePath) - data, err := os.ReadFile(configPath) + data, err := os.ReadFile(configPath) //nolint:gosec // resolved from validated bridge refs by resolveBridgePath if err != nil { return sourceConfig{}, fmt.Errorf("read bridge config: %w", err) } @@ -137,8 +138,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 } diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 4560d20..96bdc5f 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -11,6 +11,7 @@ import ( "strings" "text/template" + "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/internal/packages" ) @@ -26,15 +27,86 @@ func safeBridgeSource(dir, rel string) (string, error) { if err != nil { return "", fmt.Errorf("resolve bridge dir: %w", err) } - if real, err := filepath.EvalSymlinks(path); err == nil && - real != realDir && !strings.HasPrefix(real, realDir+string(filepath.Separator)) { + if resolved, err := filepath.EvalSymlinks(path); err == nil && + resolved != realDir && !strings.HasPrefix(resolved, realDir+string(filepath.Separator)) { return "", fmt.Errorf("bridge source path %q escapes the bridge directory", rel) } return path, nil } +// 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) { + absOutput, err := filepath.Abs(outputDir) + if err != nil { + return "", fmt.Errorf("resolve output directory: %w", err) + } + absTarget := filepath.Join(absOutput, filepath.FromSlash(renderedTarget)) + if absTarget != absOutput && !strings.HasPrefix(absTarget, absOutput+string(filepath.Separator)) { + return "", fmt.Errorf("template target path escapes output directory: %s", renderedTarget) + } + rel, err := filepath.Rel(absOutput, absTarget) + if err != nil { + return "", fmt.Errorf("resolve target path: %w", err) + } + cur := absOutput + for comp := range strings.SplitSeq(rel, string(filepath.Separator)) { + if comp == "" || comp == "." { + continue + } + cur = filepath.Join(cur, comp) + info, err := os.Lstat(cur) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return "", fmt.Errorf("inspect output path %q: %w", cur, err) + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget) + } + } + return absTarget, nil +} + +// stagedWrite is a fully rendered file held in a temp file next to its target. +// original holds the target's bytes from before this run so a later failure can +// restore them; existed=false means the target was created by this run. +type stagedWrite struct { + temp string + target string + original []byte + existed bool + mode os.FileMode + record RenderedFile +} + +// rollbackWrites undoes committed writes in reverse order and removes every +// staged temp file. It is best-effort: the original error is always returned to +// the caller, and no output file is left in a half-written state. +func rollbackWrites(staged, committed []stagedWrite) { + for _, w := range slices.Backward(committed) { + if w.existed { + if err := fsutil.AtomicWrite(w.target, w.original); err == nil { + _ = os.Chmod(w.target, w.mode) + } + continue + } + _ = os.Remove(w.target) + } + for _, w := range staged { + _ = os.Remove(w.temp) + } +} + // Render renders the IR through every bridge in the chain and returns the -// written paths and the file manifest. +// 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.IRProject, outputDir string) ([]string, []RenderedFile, error) { if project == nil { return nil, nil, errors.New("IR project is nil") @@ -65,7 +137,7 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] if err != nil { return nil, nil, err } - helperBytes, err := os.ReadFile(helperPath) + helperBytes, err := os.ReadFile(helperPath) //nolint:gosec // helperPath passed safeBridgeSource validation if err != nil { return nil, nil, fmt.Errorf("read helpers %s: %w", src.config.Helpers, err) } @@ -79,8 +151,17 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] } } - writtenFiles := make([]string, 0) + staged := make([]stagedWrite, 0) manifest := make([]RenderedFile, 0) + // fail drops every staged temp file. No output file has been touched during + // staging, so there is nothing to restore yet. + fail := func(err error) ([]string, []RenderedFile, error) { + rollbackWrites(staged, nil) + return nil, nil, err + } + + // Phase 1: parse templates and render each target into a temp file. Nothing + // is written to outputDir until every template has executed successfully. for _, src := range r.sources { for _, spec := range src.config.Templates { // Check if template should be rendered based on "When" condition @@ -90,11 +171,11 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] sourcePath, err := safeBridgeSource(src.dir, spec.Source) if err != nil { - return nil, nil, err + return fail(err) } - tplBytes, err := os.ReadFile(sourcePath) + tplBytes, err := os.ReadFile(sourcePath) //nolint:gosec // sourcePath passed safeBridgeSource validation if err != nil { - return nil, nil, fmt.Errorf("read template %s: %w", spec.Source, err) + return fail(fmt.Errorf("read template %s: %w", spec.Source, err)) } tplName := filepath.Base(spec.Source) @@ -103,19 +184,19 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] // Clone helpers so all named templates are available parsedTemplate, err = helpersTemplate.Clone() if err != nil { - return nil, nil, fmt.Errorf("clone helpers for %s: %w", spec.Source, err) + return 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)) } if err != nil { - return nil, nil, fmt.Errorf("parse template %s: %w", spec.Source, err) + return fail(fmt.Errorf("parse template %s: %w", spec.Source, err)) } contexts, err := r.renderContexts(spec.For, project, pkgs) if err != nil { - return nil, nil, err + return fail(err) } for _, context := range contexts { @@ -132,34 +213,12 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] for _, targetPattern := range spec.TargetPatterns() { renderedTarget, err := renderTemplateString(targetPattern, context, funcMap) if err != nil { - return nil, nil, fmt.Errorf("render target path: %w", err) + return fail(fmt.Errorf("render target path: %w", err)) } - 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) + absTarget, err := safeOutputPath(outputDir, renderedTarget) 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) - } - - // The lexical check does not catch a symlink planted inside the - // output tree. Resolve the parent before creating the file. - parent := filepath.Dir(absoluteTarget) - if realParent, err := filepath.EvalSymlinks(parent); err == nil { - realOutput, err := filepath.EvalSymlinks(absOutput) - if err != nil { - return nil, nil, fmt.Errorf("resolve output directory symlinks: %w", err) - } - realTarget := filepath.Join(realParent, filepath.Base(absoluteTarget)) - if realTarget != realOutput && !strings.HasPrefix(realTarget, realOutput+string(filepath.Separator)) { - return nil, nil, fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget) - } + return fail(err) } relPath := filepath.ToSlash(renderedTarget) @@ -173,39 +232,99 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] // 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 { + if _, statErr := os.Stat(absTarget); statErr == nil { record.Written = false manifest = append(manifest, record) continue } } - if err := os.MkdirAll(filepath.Dir(absoluteTarget), 0o755); err != nil { - return nil, nil, fmt.Errorf("create output dir: %w", err) + if err := os.MkdirAll(filepath.Dir(absTarget), 0o755); err != nil { //nolint:gosec // generated project dirs must stay world-readable + return fail(fmt.Errorf("create output dir: %w", err)) + } + // MkdirAll may have created the missing components above; re-check + // so a symlink planted in the meantime is still rejected. + if _, err := safeOutputPath(outputDir, renderedTarget); err != nil { + return fail(err) } - file, err := os.Create(absoluteTarget) - if err != nil { - return nil, nil, fmt.Errorf("create output file: %w", err) + existed := false + mode := os.FileMode(0o644) // os.Create's default under the usual umask + var original []byte + if info, statErr := os.Lstat(absTarget); statErr == nil { + if info.Mode()&os.ModeSymlink != 0 { + return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget)) + } + existed = true + mode = info.Mode().Perm() + original, err = os.ReadFile(absTarget) //nolint:gosec // absTarget passed safeOutputPath validation + if err != nil { + return fail(fmt.Errorf("read existing output %s: %w", renderedTarget, err)) + } + } else if !errors.Is(statErr, os.ErrNotExist) { + return fail(fmt.Errorf("inspect output file %s: %w", renderedTarget, statErr)) } - if err := parsedTemplate.Execute(file, context); err != nil { - _ = file.Close() - _ = os.Remove(absoluteTarget) - return nil, nil, fmt.Errorf("execute template: %w", err) + // 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(absTarget), ".domaincraft-render-*") + if err != nil { + return fail(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 { + _ = tmp.Close() + _ = os.Remove(tmpPath) + return fail(fmt.Errorf("set mode on temp output %s: %w", tmpPath, err)) + } + if err := parsedTemplate.Execute(tmp, context); err != nil { + _ = tmp.Close() + _ = os.Remove(tmpPath) + return fail(fmt.Errorf("execute template: %w", err)) } - if err := file.Close(); err != nil { - _ = os.Remove(absoluteTarget) - return nil, nil, fmt.Errorf("close output file %s: %w", absoluteTarget, err) + if err := tmp.Close(); err != nil { + _ = os.Remove(tmpPath) + return fail(fmt.Errorf("close temp output %s: %w", tmpPath, err)) } - writtenFiles = append(writtenFiles, absoluteTarget) + staged = append(staged, stagedWrite{ + temp: tmpPath, + target: absTarget, + original: original, + existed: existed, + mode: mode, + record: record, + }) manifest = append(manifest, record) } } } } - return writtenFiles, manifest, nil + // Phase 2: commit staged files. A failed rename rolls back every file that + // was already replaced, so callers never observe a partially updated tree. + committed := make([]stagedWrite, 0, len(staged)) + for _, w := range staged { + if info, err := os.Lstat(w.target); err == nil && info.Mode()&os.ModeSymlink != 0 { + rollbackWrites(staged, committed) + return nil, nil, fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path) + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + rollbackWrites(staged, committed) + return nil, nil, fmt.Errorf("inspect output file %s: %w", w.record.Path, err) + } + if err := os.Rename(w.temp, w.target); err != nil { + rollbackWrites(staged, committed) + return nil, nil, fmt.Errorf("commit output file %s: %w", w.record.Path, err) + } + committed = append(committed, w) + } + + written := make([]string, 0, len(committed)) + for _, w := range committed { + written = append(written, w.target) + } + return written, manifest, nil } func (r *Renderer) shouldRender(spec TemplateSpec, project *ir.IRProject, pkgs map[string]string) bool { @@ -296,9 +415,7 @@ func (r *Renderer) resolvePackages(project *ir.IRProject) map[string]string { // 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 @@ -307,9 +424,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 } } diff --git a/internal/renderer/render_test.go b/internal/renderer/render_test.go index b419cbe..f725355 100644 --- a/internal/renderer/render_test.go +++ b/internal/renderer/render_test.go @@ -1,10 +1,12 @@ package renderer import ( + "fmt" "net/http" "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/DomainCraft/DomainCraft/internal/ir" @@ -353,20 +355,52 @@ func TestRenderContext_PrimaryKey(t *testing.T) { func TestResolvePackagesNilLoggerDoesNotPanic(t *testing.T) { t.Parallel() - // 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) { + // 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.IRProject{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[]") } } diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index 410aa6e..9a719ac 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -4,8 +4,8 @@ import ( "cmp" "encoding/json" "fmt" + "maps" "os" - "path/filepath" "strings" "text/template" @@ -72,9 +72,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,7 +80,13 @@ 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")) + // Use the same guard as templates and helpers: a symlinked mapping file must + // not pull configuration from outside the bridge directory. + path, err := safeBridgeSource(dir, "type_mappings.yaml") + if err != nil { + return nil, err + } + data, err := os.ReadFile(path) //nolint:gosec // path passed safeBridgeSource validation if err != nil { if os.IsNotExist(err) { return nil, nil @@ -111,12 +115,8 @@ func mergeTypeMappings(base, overlay *typeMappings) *typeMappings { 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 - } + maps.Copy(m, dst) + maps.Copy(m, src) return m } out := &typeMappings{ @@ -146,12 +146,8 @@ func mergeLiterals(base, overlay map[string]LiteralSpec) map[string]LiteralSpec 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 - } + maps.Copy(m, base) + maps.Copy(m, overlay) return m } diff --git a/internal/snapshot/hardening_test.go b/internal/snapshot/hardening_test.go new file mode 100644 index 0000000..718d1ad --- /dev/null +++ b/internal/snapshot/hardening_test.go @@ -0,0 +1,197 @@ +package snapshot + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/renderer" +) + +// 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 := SnapshotPath(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) + } + }) +} diff --git a/internal/snapshot/paths.go b/internal/snapshot/paths.go index 25bbe9e..27bb065 100644 --- a/internal/snapshot/paths.go +++ b/internal/snapshot/paths.go @@ -1,7 +1,9 @@ package snapshot import ( + "errors" "fmt" + "os" "path/filepath" "strings" ) @@ -10,6 +12,11 @@ import ( // 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. +// +// The lexical check alone is not enough: --prune follows symlinks. Every +// existing component is therefore resolved with EvalSymlinks and must stay +// inside the resolved output root. The returned path keeps the lexical form so +// callers see paths under outputDir even when that directory is itself a link. func safeRelPath(outputDir, relPath string) (string, error) { local := filepath.FromSlash(relPath) if !filepath.IsLocal(local) { @@ -24,5 +31,33 @@ func safeRelPath(outputDir, relPath string) (string, error) { if abs != absOutput && !strings.HasPrefix(abs, absOutput+string(filepath.Separator)) { return "", fmt.Errorf("unsafe snapshot path %q: outside output dir", relPath) } + + realOutput, err := filepath.EvalSymlinks(absOutput) + if err != nil { + return "", fmt.Errorf("resolve output dir %q: %w", outputDir, err) + } + rel, err := filepath.Rel(absOutput, abs) + if err != nil { + return "", fmt.Errorf("resolve snapshot path %q: %w", relPath, err) + } + cur, realCur := absOutput, realOutput + for comp := range strings.SplitSeq(rel, string(filepath.Separator)) { + if comp == "" || comp == "." { + continue + } + cur = filepath.Join(cur, comp) + realComp, err := filepath.EvalSymlinks(cur) + if errors.Is(err, os.ErrNotExist) { + // The component (and everything below it) has not been created yet. + continue + } + if err != nil { + return "", fmt.Errorf("resolve snapshot path %q: %w", relPath, err) + } + if realComp != realCur && !strings.HasPrefix(realComp, realCur+string(filepath.Separator)) { + return "", fmt.Errorf("unsafe snapshot path %q: follows a symlink outside output dir", relPath) + } + realCur = realComp + } return abs, nil } diff --git a/internal/snapshot/rewrite.go b/internal/snapshot/rewrite.go index a29c0c3..40418b3 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -10,101 +10,116 @@ package snapshot // Python or a bare `product` in TS are all rewritten by the same rules. import ( - "bytes" "cmp" "os" "slices" "strings" + "unicode" "github.com/DomainCraft/DomainCraft/internal/fsutil" "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. +// rewriteCasings replaces old identifiers with new in a single pass. Variants +// are tried longest-first (so `Products` is consumed as a whole before its +// singular head `Product` gets a chance), then alphabetically for determinism. +// After a match, scanning resumes after the ORIGINAL token, so replacement text +// is never rescanned: renaming Product -> ProductItem cannot turn `Products` +// into `ProductItemItems`. func rewriteCasings(content []byte, variants map[string]string) []byte { + return replaceLongest(content, variants, tokenOK) +} + +// 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; unmatched runes are copied verbatim. +func replaceLongest(content []byte, variants map[string]string, ok func([]rune, int, int) 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 } - 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)}) + } + 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 + rs := []rune(string(content)) + out := make([]rune, 0, len(rs)) + 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 + } + out = append(out, v.value...) + i += len(v.old) // replacement text is never scanned again + matched = true + break + } + if !matched { + out = append(out, rs[i]) + i++ } - out = replaceToken(out, []byte(old), []byte(new)) } - return out + return []byte(string(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 +func hasPrefixRunes(s, prefix []rune) bool { + if len(prefix) > len(s) { + return false } - 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:]...) - break - } - idx := i + rel - out = append(out, content[i:idx]...) - if tokenOK(content, idx, old) { - out = append(out, new...) - } else { - out = append(out, old...) + for i, r := range prefix { + if s[i] != r { + return false } - i = idx + len(old) } - return out + return true } -// 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 { +// 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 := 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 { + prev := rs[idx-1] + prefixOK := unicode.IsUpper(prev) && (idx < 2 || !isIdentRune(rs[idx-2])) + if isIdentRune(prev) && !prefixOK { return false } } - j := idx + len(old) - if j < len(content) && isIdentChar(content[j]) { - if content[j] >= 'a' && content[j] <= 'z' { + j := idx + length + if j < len(rs) { + next := rs[j] + if isIdentRune(next) && unicode.IsLower(next) { return false } } return true } -func isIdentChar(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' +func isIdentRune(r rune) bool { + return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' } // entityCasings builds the casing-variant table for an entity rename. @@ -211,7 +226,7 @@ func RewriteFile(outputDir, relPath string, transforms ...func([]byte) []byte) ( if err != nil { return false, err } - data, err := os.ReadFile(abs) + data, err := os.ReadFile(abs) //nolint:gosec // abs passed safeRelPath validation if err != nil { if os.IsNotExist(err) { return false, nil diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index f26c6ba..8117fda 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -19,6 +19,7 @@ import ( "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" @@ -64,7 +65,7 @@ func SnapshotPath(outputDir string) string { // 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 @@ -80,14 +81,17 @@ func Load(path string) (*Snapshot, error) { // 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. + if err := fsutil.AtomicWrite(path, append(data, '\n')); err != nil { return fmt.Errorf("write snapshot: %w", err) } return nil @@ -351,8 +355,11 @@ func detectNamespaceMismatch(outputDir string, old *Snapshot, oldNamespace, newN if !f.Custom { continue } - abs := filepath.Join(outputDir, filepath.FromSlash(f.Path)) - data, err := os.ReadFile(abs) + abs, err := safeRelPath(outputDir, f.Path) + if err != nil { + continue + } + data, err := os.ReadFile(abs) //nolint:gosec // abs passed safeRelPath validation if err != nil { continue } @@ -370,7 +377,7 @@ func detectNamespaceMismatch(outputDir string, old *Snapshot, oldNamespace, newN // referencesNamespace reports whether s declares the given root namespace, e.g. // `namespace EscrowPay...` or `namespace EscrowPay;`. func referencesNamespace(s, namespace string) bool { - for _, line := range strings.Split(s, "\n") { + for line := range strings.SplitSeq(s, "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "namespace ") { continue @@ -420,7 +427,11 @@ func customEntityFiles(files []renderer.RenderedFile, entityName string) []strin 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 { + abs, err := safeRelPath(outputDir, f.Path) + if err != nil { + continue + } + if _, err := os.Stat(abs); err != nil { continue } refs = append(refs, FileRef{Path: f.Path, Custom: f.Custom}) @@ -433,7 +444,11 @@ func existingFileRefs(outputDir string, files []renderer.RenderedFile) []FileRef 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 { + abs, err := safeRelPath(outputDir, rel) + if err != nil { + continue + } + if _, err := os.Stat(abs); err == nil { result = append(result, rel) } } @@ -445,9 +460,14 @@ func existingFilePaths(outputDir string, relPaths []string) []string { // rename oldName -> newName. Both the plural and the singular forms of the old // name are replaced (plural first, since it is more specific). 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 := map[string]string{ + textutil.Pluralize(oldName): textutil.Pluralize(newName), + oldName: newName, + } + return string(replaceLongest([]byte(relPath), variants, tokenOK)) } // DeleteFile removes an entity-scoped file (path relative to outputDir). @@ -482,7 +502,7 @@ func RenameEntityFile(outputDir, relPath, oldName, newName string) (newRel strin if _, err := os.Stat(newAbs); err == nil { return newRel, false, nil } - if err := os.MkdirAll(filepath.Dir(newAbs), 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(newAbs), 0o755); err != nil { //nolint:gosec // generated project dirs must stay world-readable return newRel, false, fmt.Errorf("create parent dir for %s: %w", newRel, err) } if err := os.Rename(abs, newAbs); err != nil { From 4614a4ccd0773170573b8ce3bffe7800d6528d6d Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:51:00 +0300 Subject: [PATCH 10/83] CLI: honor non-interactive mode and verify self-update checksums --- cmd/domaincraft/commands.go | 321 +++++++------- cmd/domaincraft/commands_extends_test.go | 21 +- cmd/domaincraft/commands_hardening_test.go | 326 ++++++++++++++ cmd/domaincraft/commands_lock_test.go | 2 + cmd/domaincraft/commands_notify_test.go | 2 +- cmd/domaincraft/commands_prune_test.go | 20 +- .../commands_update_security_test.go | 401 ++++++++++++++++++ cmd/domaincraft/commands_update_test.go | 6 +- cmd/domaincraft/init.go | 31 +- cmd/domaincraft/main.go | 14 +- .../regression_csharp_role_test.go | 2 +- cmd/domaincraft/update.go | 220 +++++++++- internal/interactive/prompts.go | 14 +- 13 files changed, 1163 insertions(+), 217 deletions(-) create mode 100644 cmd/domaincraft/commands_hardening_test.go create mode 100644 cmd/domaincraft/commands_update_security_test.go diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index f22ca77..d0f93f0 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -17,6 +17,7 @@ import ( "cmp" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -44,23 +45,40 @@ import ( "gopkg.in/yaml.v3" ) -var ( +const ( + defaultDomainFile = "domain.yaml" + defaultOutputDir = "generated" +) + +// 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 - addonsFlag string // --addons "dapr,pulsar": comma-separated infrastructure accelerators - migrateFlag bool // --migrate: run the bridge's database-migration commands after generation + 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 ( // commandCtx is cancelled on interrupt so child processes are not orphaned. commandCtx = context.Background() + // isTerminal is a seam for testing prompt gating without a real TTY. + isTerminal = interactive.IsTerminal + // 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). version = "dev" @@ -96,42 +114,50 @@ func init() { } } -func Execute() { +// 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 { if err := newRootCommand().Execute(); err != nil { - os.Exit(1) + _, _ = fmt.Fprintln(os.Stderr, "Error:", 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) @@ -139,23 +165,25 @@ 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()) + log.SetWriter(cmd.ErrOrStderr()) return log } // --- 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 } @@ -167,62 +195,67 @@ 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. runGenerate validates that pairing. + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runGenerate(opts, cmd, args) + }, } // --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)") + 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().BoolVar(&allowBridgeCommands, "allow-bridge-commands", false, "allow shell commands declared by community bridges (required with --migrate or automatic --prune migrations)") - 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 { +func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { log := commandLogger(cmd) - log.Info("Parsing %s", domainFile) - schema, err := loadAndValidate(cmd.OutOrStdout()) + log.Info("Parsing %s", opts.domainFile) + schema, err := loadAndValidate(opts, cmd) if err != nil { return err } log.Success("Schema valid (%d entities)", len(schema.Entities)) - resolvedPath, bridgeName, err := resolveBridgeInteractive(log) + resolvedPath, bridgeName, err := resolveBridgeInteractive(opts, log) if err != nil { return err } - bridgePath = resolvedPath + opts.bridgePath = resolvedPath log.Info("Building IR") irProject, err := ir.Build(schema) if err != nil { return err } - applyAddons(irProject) + applyAddons(opts, irProject) // --- Schema snapshot / migration diff --- - snapPath := snapshot.SnapshotPath(outputDir) + snapPath := snapshot.SnapshotPath(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) // --- Abstract schema migration plan (smart core / dumb bridge) --- // The core compares the previous model against the current one and @@ -237,28 +270,28 @@ func runGenerate(cmd *cobra.Command, args []string) error { mockDataset := seed.Generate(irProject, seed.Options{}) // Parse --replace flags (layer|bridgeId=bridgeRef). - replacements, err := parseReplaceFlags(replaceFlags) + replacements, err := parseReplaceFlags(opts.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 // 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 append([]string{opts.bridgePath}, basePaths...) { if !bridge.IsOfficialBundled(p) { chainHasCommunity = true break } } - log.Info("Rendering via %s", bridgePath) - rendererInstance, err := renderer.New(bridgePath, log) + log.Info("Rendering via %s", opts.bridgePath) + rendererInstance, err := renderer.New(opts.bridgePath, log) if err != nil { return err } @@ -269,34 +302,36 @@ func runGenerate(cmd *cobra.Command, args []string) error { rendererInstance.SetSeedData(seedData) rendererInstance.SetMockData(mockDataset) - writtenFiles, manifest, err := rendererInstance.Render(irProject, outputDir) + 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] + // still means the default admin-alpine bridge. Any other positional + // argument is rejected by cobra.MaximumNArgs(1) / the check below. + if len(args) > 0 { + if !cmd.Flags().Changed("admin") || opts.adminBridge != "admin-alpine" { + return fmt.Errorf("unexpected positional argument %q: use --admin ", args[0]) + } + opts.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() { + if opts.adminBridge == "" && !cmd.Flags().Changed("admin") && !opts.nonInteractive && isTerminal() { generate, err := interactive.PromptGenerateAdmin() if err != nil { return fmt.Errorf("prompt for admin panel: %w", err) } if generate { - adminBridge = "admin-alpine" + opts.adminBridge = "admin-alpine" } } - if adminBridge != "" { - adminManifest, err := generateAdminPanel(irProject, seedData, mockDataset, log) + if opts.adminBridge != "" { + adminManifest, err := generateAdminPanel(opts, irProject, seedData, mockDataset, log) if err != nil { return err } @@ -311,7 +346,7 @@ func runGenerate(cmd *cobra.Command, args []string) error { fresh[f.Path] = true } } - applied, err := applyMigrationActions(migrationDiff, fresh, log, cmd) + applied, err := applyMigrationActions(opts, migrationDiff, fresh, log, cmd) if err != nil { return err } @@ -321,19 +356,19 @@ func runGenerate(cmd *cobra.Command, args []string) error { // 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() + autoMigrate := opts.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 + shouldMigrate := opts.migrate || autoMigrate cfg := rendererInstance.MigrationConfig() if applied && shouldMigrate && cfg != nil && cfg.Enabled { - if !bridgeCommandsAllowed(chainHasCommunity, allowBridgeCommands) { + if !bridgeCommandsAllowed(chainHasCommunity, opts.allowBridgeCommands) { return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") } - if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), outputDir, cmd, log); err != nil { - if migrateFlag { + if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), opts.outputDir, cmd, log); err != nil { + if opts.migrate { // Explicit --migrate: a failed migration is a hard error. return err } @@ -372,13 +407,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, append([]string{opts.bridgePath}, basePaths...)); err != nil { log.Warn("could not write domaincraft.lock.json: %v", err) } if err := snapshot.Save(snapPath, snapshot.New(bridgeID, irProject, manifest)); err != nil { @@ -390,12 +425,13 @@ 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() @@ -415,7 +451,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: @@ -454,7 +490,7 @@ func newBridgesCmd() *cobra.Command { // --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 } @@ -462,15 +498,15 @@ func newBridgesCmd() *cobra.Command { // --- 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)) +func newBridgeResolver(opts *cliOptions, log *logger.Logger) *bridge.Resolver { + return bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(opts, 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) +func walkBridgeChain(opts *cliOptions, ref, fromDir string, log *logger.Logger) ([]string, error) { + resolver := newBridgeResolver(opts, log) var chain []string visited := make(map[string]bool) for ref != "" { @@ -498,24 +534,24 @@ func walkBridgeChain(ref, fromDir string, log *logger.Logger) ([]string, error) // 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) +func resolveBridgeInteractive(opts *cliOptions, log *logger.Logger) (string, string, error) { + resolver := newBridgeResolver(opts, log) - if bridgePath != "" { + if opts.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 entry := bridge.Default().ByID(opts.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) + resolved, err := resolver.Resolve(opts.bridgePath) return resolved, "", err } - if nonInteractive || !interactive.IsTerminal() { + if opts.nonInteractive || !isTerminal() { return "", "", fmt.Errorf("--bridge is required in non-interactive mode") } @@ -535,8 +571,8 @@ func resolveBridgeInteractive(log *logger.Logger) (string, string, error) { // 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) +func resolveBaseChain(opts *cliOptions, adapterDir, baseRef string, log *logger.Logger) ([]string, error) { + chain, err := walkBridgeChain(opts, baseRef, adapterDir, log) if err != nil { return nil, err } @@ -575,23 +611,23 @@ func bridgeLayerAndName(dir string, log *logger.Logger) (string, string, error) } // 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) +func buildFullChainTopFirst(opts *cliOptions, entryDir string, log *logger.Logger) ([]string, error) { + return walkBridgeChain(opts, 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) { +func resolveChainWithReplacements(opts *cliOptions, 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) + bases, err := resolveBaseChain(opts, entryDir, r.Extends(), log) return entryDir, bases, err } - resolver := newBridgeResolver(log) - fullChain, err := buildFullChainTopFirst(entryDir, log) + resolver := newBridgeResolver(opts, log) + fullChain, err := buildFullChainTopFirst(opts, entryDir, log) if err != nil { return "", nil, err } @@ -630,7 +666,7 @@ func resolveChainWithReplacements(entryDir string, reps []replaceEntry, log *log 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) + rightChain, err := buildFullChainTopFirst(opts, rightPath, log) if err != nil { return "", nil, err } @@ -730,7 +766,7 @@ func writeDomainLock(domainPath string, dirs []string) error { // 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")) + data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) //nolint:gosec // dir comes from validated bridge resolution if err != nil { return "", "", 0, err } @@ -753,46 +789,44 @@ func bridgeMetadata(dir string) (id, version string, contractVersion int, err er // - --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 { +func bridgeEnsureOptions(cli *cliOptions, log *logger.Logger) *bridge.EnsureOptions { opts := &bridge.EnsureOptions{ - Force: updateBridges, + Force: cli.updateBridges, Warn: log.Warn, } switch { - case updateBridges: + 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("Updating bridge %s %s", entry.ID, versionDelta(u)) + log.Info("%s", bridgeUpdateNotice(entry.ID, u)) return true, nil } - case interactive.IsTerminal(): + case !cli.nonInteractive && 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. + // 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 } -// 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) +// 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) } // 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)) +func generateAdminPanel(opts *cliOptions, irProject *ir.IRProject, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { + resolver := bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(opts, log)) - adminID := adminBridge + adminID := opts.adminBridge if adminID == "" { adminID = "admin-alpine" } @@ -810,7 +844,7 @@ func generateAdminPanel(irProject *ir.IRProject, seedData, mockDataset *ir.SeedD adminRenderer.SetSeedData(seedData) adminRenderer.SetMockData(mockDataset) - adminFiles, adminManifest, err := adminRenderer.Render(irProject, outputDir) + adminFiles, adminManifest, err := adminRenderer.Render(irProject, opts.outputDir) if err != nil { return nil, err } @@ -852,7 +886,7 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co shell = "sh" argv = []string{"-c", command} } - c := exec.CommandContext(commandCtx, shell, argv...) + c := exec.CommandContext(commandCtx, shell, argv...) //nolint:gosec // shell line is gated by explicit bridge-command consent c.Dir = outDir c.Stdout = out c.Stderr = out @@ -875,7 +909,7 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co // (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) { +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 } @@ -886,13 +920,13 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg // 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 opts.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)) + rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.NamespaceTransform(diff.NamespaceRename)) if err != nil { log.Warn("could not rewrite namespace in %s: %v", rel, err) continue @@ -907,7 +941,7 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg if fresh[rel] { continue } - rewrote, err := snapshot.RewriteFile(outputDir, rel, snapshot.FieldTransform(fr)) + rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.FieldTransform(fr)) if err != nil { log.Warn("could not rewrite field references in %s: %v", rel, err) continue @@ -924,7 +958,7 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg if len(del.Files) == 0 { continue } - done, err := handleDeletedEntity(del, fresh, log, out) + done, err := handleDeletedEntity(opts, del, fresh, log, out) if err != nil { return false, err } @@ -935,7 +969,7 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg if len(ren.Files) == 0 { continue } - done, err := handleRename(ren, diff, fresh, log, out) + done, err := handleRename(opts, ren, diff, fresh, log, out) if err != nil { return false, err } @@ -947,9 +981,9 @@ func applyMigrationActions(diff *snapshot.Diff, fresh map[string]bool, log *logg // 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) { +func chooseMigrationFiles(opts *cliOptions, files []snapshot.FileRef, prompt func([]interactive.FileChoice) ([]string, error)) (map[string]bool, error) { selected := make(map[string]bool) - if prune { + if opts.prune { for _, f := range files { selected[f.Path] = true } @@ -972,15 +1006,15 @@ func chooseMigrationFiles(files []snapshot.FileRef, prompt func([]interactive.Fi // 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() { +func handleDeletedEntity(opts *cliOptions, del snapshot.DeletedEntity, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { + if !opts.prune && (opts.nonInteractive || !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) { + selected, err := chooseMigrationFiles(opts, del.Files, func(choices []interactive.FileChoice) ([]string, error) { return interactive.PromptDeleteFiles(del.Name, choices) }) if err != nil { @@ -991,7 +1025,7 @@ func handleDeletedEntity(del snapshot.DeletedEntity, fresh map[string]bool, log if !selected[f.Path] || fresh[f.Path] { continue } - if err := snapshot.DeleteFile(outputDir, f.Path); err != nil { + if err := snapshot.DeleteFile(opts.outputDir, f.Path); err != nil { log.Warn("could not delete %s: %v", f.Path, err) continue } @@ -1005,15 +1039,15 @@ func handleDeletedEntity(del snapshot.DeletedEntity, fresh map[string]bool, log // 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() { +func handleRename(opts *cliOptions, ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { + if !opts.prune && (opts.nonInteractive || !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) { + selected, err := chooseMigrationFiles(opts, ren.Files, func(choices []interactive.FileChoice) ([]string, error) { return interactive.PromptRenameFiles(ren.OldName, ren.NewName, choices) }) if err != nil { @@ -1030,18 +1064,18 @@ func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, // 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 { + if err := os.Remove(filepath.Join(opts.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) + newRel, renamed, err := snapshot.RenameEntityFile(opts.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 { + if rewrote, rerr := snapshot.RewriteFile(opts.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) @@ -1052,7 +1086,7 @@ func handleRename(ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, continue } // Generated files have been regenerated under the new name — remove the stale copy. - if err := snapshot.DeleteFile(outputDir, f.Path); err != nil { + if err := snapshot.DeleteFile(opts.outputDir, f.Path); err != nil { log.Warn("could not delete stale generated file %s: %v", f.Path, err) continue } @@ -1077,14 +1111,14 @@ func customMark(f snapshot.FileRef) string { // 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) == "" { +func applyAddons(opts *cliOptions, project *ir.IRProject) { + if strings.TrimSpace(opts.addons) == "" { return } if project.Addons == nil { project.Addons = make(map[string]bool) } - for _, addon := range strings.Split(addonsFlag, ",") { + for addon := range strings.SplitSeq(opts.addons, ",") { addon = strings.TrimSpace(addon) if addon == "" { continue @@ -1095,8 +1129,11 @@ func applyAddons(project *ir.IRProject) { } } -func loadAndValidate(out io.Writer) (*parser.ParsedSchema, error) { - data, err := os.ReadFile(domainFile) +// 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) } @@ -1105,19 +1142,17 @@ func loadAndValidate(out io.Writer) (*parser.ParsedSchema, error) { return nil, err } - allErrors := validator.New(schema).Validate() - var hardErrors []validator.ValidationError - for _, e := range allErrors { + errOut := cmd.ErrOrStderr() + hardErrors := make([]error, 0) + for _, e := range validator.New(schema).Validate() { if e.Warning { - _, _ = fmt.Fprintf(out, "⚠ %s\n", e.Error()) - } else { - hardErrors = append(hardErrors, e) - _, _ = fmt.Fprintln(out, e.Error()) + _, _ = fmt.Fprintf(errOut, "⚠ %s\n", e.Error()) + continue } + hardErrors = append(hardErrors, e) } - if len(hardErrors) > 0 { - return nil, fmt.Errorf("validation failed with %d error(s)", len(hardErrors)) + 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_extends_test.go b/cmd/domaincraft/commands_extends_test.go index 9915880..192a7ab 100644 --- a/cmd/domaincraft/commands_extends_test.go +++ b/cmd/domaincraft/commands_extends_test.go @@ -35,7 +35,7 @@ func TestResolveBaseChainOrdersOutermostBaseFirst(t *testing.T) { 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()) + chain, err := resolveBaseChain(&cliOptions{}, a, b, logger.New()) if err != nil { t.Fatalf("resolveBaseChain: %v", err) } @@ -56,7 +56,7 @@ func TestResolveBaseChainDetectsCycle(t *testing.T) { // 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()) + _, err := resolveBaseChain(&cliOptions{}, a, b, logger.New()) if err == nil { t.Fatal("expected a cycle error") } @@ -137,20 +137,23 @@ func TestResolveExtendsRefFallsBackWhenNoMonorepo(t *testing.T) { } } -func TestVersionDelta(t *testing.T) { +func TestBridgeUpdateNoticeOmitsCachedVersion(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)"}, + {"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) { - if got := versionDelta(c.u); got != c.want { - t.Errorf("versionDelta = %q, want %q", got, c.want) + 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..1a83038 --- /dev/null +++ b/cmd/domaincraft/commands_hardening_test.go @@ -0,0 +1,326 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/bridge" + "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) + var fileOut bytes.Buffer + + applied, err := handleDeletedEntity(opts, snapshotDeleted(rel), map[string]bool{}, log, &fileOut) + if err != nil || applied { + t.Fatalf("handleDeletedEntity = %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 + + applied, err := handleRename(opts, snapshotRename(rel), nil, map[string]bool{}, log, &fileOut) + 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 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 + wantErr bool + }{ + {"root rejects positional argument", "", []string{"extra"}, true}, + {"validate rejects positional argument", "validate", []string{"extra"}, true}, + {"bridges rejects positional argument", "bridges", []string{"extra"}, true}, + {"update rejects positional argument", "update", []string{"extra"}, true}, + {"init rejects positional argument", "init", []string{"extra"}, true}, + {"generate allows one admin argument", "generate", []string{"admin-alpine"}, false}, + {"generate rejects two arguments", "generate", []string{"a", "b"}, 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 + } + 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, oldStderr := os.Args, os.Stderr + os.Args = []string{"domaincraft", "validate", "--domain", filepath.Join(t.TempDir(), "missing.yaml")} + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = w + t.Cleanup(func() { + os.Args, os.Stderr = oldArgs, oldStderr + _ = 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_lock_test.go b/cmd/domaincraft/commands_lock_test.go index 83402ff..3d5a91b 100644 --- a/cmd/domaincraft/commands_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") diff --git a/cmd/domaincraft/commands_notify_test.go b/cmd/domaincraft/commands_notify_test.go index e842ced..aa327e7 100644 --- a/cmd/domaincraft/commands_notify_test.go +++ b/cmd/domaincraft/commands_notify_test.go @@ -30,7 +30,7 @@ func TestCachedLatestCoreVersion(t *testing.T) { } // Network is now down — the fresh cache must still serve the same version. - httpGetBodyFn = func(url string) ([]byte, error) { + httpGetBodyFn = func(_ string) ([]byte, error) { return nil, fmt.Errorf("network down") } latest2, err := cachedLatestCoreVersion() diff --git a/cmd/domaincraft/commands_prune_test.go b/cmd/domaincraft/commands_prune_test.go index afc984c..98a0c06 100644 --- a/cmd/domaincraft/commands_prune_test.go +++ b/cmd/domaincraft/commands_prune_test.go @@ -18,11 +18,7 @@ import ( // previously untested, so a dropped field rename could leave stale names. func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { root := t.TempDir() - oldOutput, oldPrune := outputDir, prune - outputDir, prune = root, true - t.Cleanup(func() { - outputDir, prune = oldOutput, oldPrune - }) + opts := &cliOptions{outputDir: root, prune: true} custom := filepath.Join(root, "src", "ItemService.cs") if err := os.MkdirAll(filepath.Dir(custom), 0o755); err != nil { @@ -43,7 +39,7 @@ func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { var out bytes.Buffer cmd.SetOut(&out) - applied, err := applyMigrationActions(diff, map[string]bool{}, nil, cmd) + applied, err := applyMigrationActions(opts, diff, map[string]bool{}, nil, cmd) if err != nil || !applied { t.Fatalf("applyMigrationActions = %v, %v; want true, nil", applied, err) } @@ -84,11 +80,9 @@ 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) { - oldPrune := prune - prune = true - t.Cleanup(func() { prune = oldPrune }) + opts := &cliOptions{prune: true} - selected, err := chooseMigrationFiles(files, func([]interactive.FileChoice) ([]string, error) { + selected, err := chooseMigrationFiles(opts, files, func([]interactive.FileChoice) ([]string, error) { t.Fatal("prompt must not be called in --prune mode") return nil, nil }) @@ -98,11 +92,9 @@ func TestChooseMigrationFiles(t *testing.T) { }) t.Run("prompt result is respected", func(t *testing.T) { - oldPrune := prune - prune = false - t.Cleanup(func() { prune = oldPrune }) + opts := &cliOptions{} - selected, err := chooseMigrationFiles(files, func(choices []interactive.FileChoice) ([]string, error) { + selected, err := chooseMigrationFiles(opts, files, func(choices []interactive.FileChoice) ([]string, error) { if len(choices) != 2 { t.Fatalf("choices = %d, want 2", len(choices)) } diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go new file mode 100644 index 0000000..caba74f --- /dev/null +++ b/cmd/domaincraft/commands_update_security_test.go @@ -0,0 +1,401 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +const ( + assetURLBase = "https://github.com/DomainCraft/DomainCraft/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 seams for the self-update path. +func stubUpdateRun(t *testing.T, current string, serve func(string) ([]byte, error)) (*bytes.Buffer, *int, *[]byte) { + t.Helper() + oldVersion, oldHTTP := version, httpGetBodyFn + oldExe, oldReplace := executableFn, replaceExecutableFn + version = current + httpGetBodyFn = serve + + calls := 0 + var installed []byte + executableFn = func() (string, error) { return filepath.Join(t.TempDir(), "domaincraft"), nil } + replaceExecutableFn = 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) + t.Cleanup(func() { + version, httpGetBodyFn = oldVersion, oldHTTP + executableFn, replaceExecutableFn = oldExe, oldReplace + }) + return out, &calls, &installed +} + +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) { + cases := []struct { + name string + raw string + want string + }{ + {"credentials and query", "https://user:secret@github.com/dc?token=abc#f", "https://github.com/dc"}, + {"plain", updateAssetURL("dc"), updateAssetURL("dc")}, + {"malformed", "https://[::1", ""}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := redactURL(tt.raw); got != tt.want { + t.Errorf("redactURL = %q, want %q", got, tt.want) + } + }) + } +} + +func TestReadResponseBodyRejectsOversizedPayload(t *testing.T) { + oldLimit := maxResponseBody + maxResponseBody = 4 + t.Cleanup(func() { maxResponseBody = oldLimit }) + + 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 := readResponseBody(resp, u.String()) + 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 = readResponseBody(resp, updateAssetURL("dc")) + if tt.wantErrPart == "" { + if err != nil { + t.Fatalf("readResponseBody: %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, commandCtx + t.Cleanup(func() { httpClient, commandCtx = oldClient, oldCtx }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + commandCtx = 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) { + oldHTTP := httpGetBodyFn + t.Cleanup(func() { httpGetBodyFn = oldHTTP }) + httpGetBodyFn = 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 := releaseChecksum(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 := stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", tt.assets, bodies)) + err := runCoreUpdate(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) + } + }) + } +} diff --git a/cmd/domaincraft/commands_update_test.go b/cmd/domaincraft/commands_update_test.go index 359d46c..45688f9 100644 --- a/cmd/domaincraft/commands_update_test.go +++ b/cmd/domaincraft/commands_update_test.go @@ -23,7 +23,7 @@ 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 } } @@ -135,12 +135,12 @@ func TestReleaseAssetFor(t *testing.T) { func TestDownloadAndReplace(t *testing.T) { oldHTTP := httpGetBodyFn - httpGetBodyFn = func(url string) ([]byte, error) { + httpGetBodyFn = func(_ string) ([]byte, error) { return []byte("new-binary-content"), nil } defer func() { httpGetBodyFn = oldHTTP }() - tmp, err := downloadBinary("https://example/dc") + tmp, err := downloadBinary("https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64") if err != nil { t.Fatalf("downloadBinary: %v", err) } diff --git a/cmd/domaincraft/init.go b/cmd/domaincraft/init.go index 9ac2cfb..fa9c344 100644 --- a/cmd/domaincraft/init.go +++ b/cmd/domaincraft/init.go @@ -78,7 +78,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 +88,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() { + if opts.nonInteractive || !isTerminal() { return 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,38 +117,38 @@ func newInitCmd() *cobra.Command { return err } - _, statErr := os.Stat(domainFile) + _, statErr := os.Stat(opts.domainFile) if statErr == nil && !force { - return fmt.Errorf("%s already exists; use --force to overwrite", domainFile) + return fmt.Errorf("%s already exists; use --force to overwrite", opts.domainFile) } if statErr != nil && !os.IsNotExist(statErr) { - return fmt.Errorf("check %s: %w", domainFile, statErr) + return fmt.Errorf("check %s: %w", opts.domainFile, statErr) } - 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, nil) }, } diff --git a/cmd/domaincraft/main.go b/cmd/domaincraft/main.go index 07f3862..ab61081 100644 --- a/cmd/domaincraft/main.go +++ b/cmd/domaincraft/main.go @@ -4,14 +4,24 @@ import ( "context" "os" "os/signal" + "syscall" "github.com/DomainCraft/DomainCraft/internal/bridge" ) func main() { - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + // 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() commandCtx = ctx bridge.SetCommandContext(ctx) - Execute() + if err := Execute(); err != nil { + return 1 + } + return 0 } diff --git a/cmd/domaincraft/regression_csharp_role_test.go b/cmd/domaincraft/regression_csharp_role_test.go index b2fe03b..8db1fe4 100644 --- a/cmd/domaincraft/regression_csharp_role_test.go +++ b/cmd/domaincraft/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/update.go b/cmd/domaincraft/update.go index 707f60a..66a5152 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -1,10 +1,13 @@ package main import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "io" "net/http" + "net/url" "os" "path/filepath" "runtime" @@ -24,6 +27,23 @@ const coreRepo = "DomainCraft/DomainCraft" const releasesLatestURL = "https://api.github.com/repos/DomainCraft/DomainCraft/releases/latest" +// checksumsAssetName is the release asset holding one SHA-256 digest per binary. +const checksumsAssetName = "checksums.txt" + +// maxResponseBody caps reads from the update endpoints. A response larger than +// this is an error, never a silently truncated success. It is a variable so +// tests can exercise the overflow path without allocating 64 MiB. +var maxResponseBody int64 = 64 << 20 + +// 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 update checks and binary downloads. var httpClient = &http.Client{Timeout: 120 * time.Second} @@ -31,6 +51,13 @@ var httpClient = &http.Client{Timeout: 120 * time.Second} // so tests can substitute a fake and exercise the GitHub code paths offline. var httpGetBodyFn = httpGetBody +// executableFn and replaceExecutableFn are seams for testing the download and +// verification path without replacing the test binary. +var ( + executableFn = os.Executable + replaceExecutableFn = replaceExecutable +) + // githubRelease is the subset of the GitHub releases/latest payload we need. type githubRelease struct { TagName string `json:"tag_name"` @@ -50,9 +77,9 @@ 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. +// 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) { current := strings.TrimPrefix(version, "v") if current == "" || current == "dev" || cmd.Name() == "update" { @@ -63,7 +90,7 @@ func maybeNotifyUpdate(cmd *cobra.Command) { 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(), "ℹ A new domaincraft version is available: v%s (current v%s). Run `domaincraft update` to install it.\n", latest, current) } } @@ -75,7 +102,7 @@ func cachedLatestCoreVersion() (string, error) { cacheDir = os.TempDir() } 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 { return c.Latest, nil @@ -95,7 +122,7 @@ func cachedLatestCoreVersion() (string, error) { } func writeUpdateCheckCache(cacheDir, cachePath string, c updateCheckCache) { - if err := os.MkdirAll(cacheDir, 0o755); err != nil { + if err := os.MkdirAll(cacheDir, 0o755); err != nil { //nolint:gosec // cache dirs must stay readable across CLI runs return } body, err := json.Marshal(c) @@ -112,7 +139,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) }, } @@ -148,22 +176,33 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { 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 + } + wantSum, err := releaseChecksum(release, asset) if err != nil { return err } - tmp, err := downloadBinary(assetURL) if err != nil { return err } defer func() { _ = os.Remove(tmp) }() - exe, err := os.Executable() + if err := verifyFileSHA256(tmp, wantSum); err != nil { + return fmt.Errorf("refusing to install update: %w", err) + } + + exe, err := executableFn() if err != nil { return fmt.Errorf("locate current executable: %w", err) } - if err := replaceExecutable(tmp, exe); err != nil { + if err := replaceExecutableFn(tmp, exe); err != nil { return err } @@ -208,23 +247,160 @@ 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 +} + +// redactURL strips credentials, query and fragment from a URL before it is +// embedded in an error message. +func redactURL(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" } + u.User = nil + u.RawQuery = "" + u.Fragment = "" + return u.String() +} + +// releaseChecksum reads the SHA-256 digest for name from the release's +// checksums.txt asset. A missing, malformed or foreign digest is an error. +func releaseChecksum(rel *githubRelease, name string) (string, error) { + assetURL, err := validatedReleaseAssetURL(rel, checksumsAssetName) + if err != nil { + return "", fmt.Errorf("verify update: %w", err) + } + data, err := httpGetBodyFn(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 +} + +// httpGetBody performs a GET bound to commandCtx and returns the response body, +// capping it at maxResponseBody bytes. An oversized body is an error, not a +// silently truncated success. +func httpGetBody(rawURL string) ([]byte, error) { + req, err := http.NewRequestWithContext(commandCtx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, fmt.Errorf("build request for %s: %w", redactURL(rawURL), err) + } + resp, err := httpClient.Do(req) //nolint:bodyclose // readResponseBody closes the body + if err != nil { + return nil, fmt.Errorf("request %s: %w", redactURL(rawURL), err) + } + return readResponseBody(resp, rawURL) +} + +// readResponseBody reads at most maxResponseBody+1 bytes so an oversized +// response is rejected instead of being silently truncated into a valid binary. +func readResponseBody(resp *http.Response, rawURL string) ([]byte, error) { defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, url) + return nil, fmt.Errorf("http %d for %s", resp.StatusCode, redactURL(rawURL)) } - return io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + // A redirect must not move the download off the allowlist either. + if resp.Request != nil && resp.Request.URL != nil { + if _, err := parseAllowedURL(resp.Request.URL.String()); err != nil { + return nil, fmt.Errorf("redirect from %s: %w", redactURL(rawURL), err) + } + } + data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBody+1)) + if err != nil { + return nil, fmt.Errorf("read %s: %w", redactURL(rawURL), err) + } + if int64(len(data)) > maxResponseBody { + return nil, fmt.Errorf("response from %s exceeds %d bytes", redactURL(rawURL), maxResponseBody) + } + return data, nil } // downloadBinary fetches a release asset into a temp file and returns its path. -func downloadBinary(url string) (string, error) { - data, err := httpGetBodyFn(url) +func downloadBinary(rawURL string) (string, error) { + validURL, err := validateReleaseURL(rawURL) + if err != nil { + return "", fmt.Errorf("download update: %w", err) + } + data, err := httpGetBodyFn(validURL) if err != nil { return "", fmt.Errorf("download update: %w", err) } @@ -240,7 +416,7 @@ func downloadBinary(url string) (string, error) { return "", err } if runtime.GOOS != "windows" { - _ = os.Chmod(tmp.Name(), 0o755) + _ = os.Chmod(tmp.Name(), 0o755) //nolint:gosec // the downloaded binary must be executable } return tmp.Name(), nil } @@ -255,7 +431,7 @@ func replaceExecutable(tmp, exe string) error { 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) + return fmt.Errorf("update in place failed; replace %s manually or run go install: %w", exe, err) } if err := os.Rename(tmp, exe); err != nil { _ = os.Rename(old, exe) // restore the original diff --git a/internal/interactive/prompts.go b/internal/interactive/prompts.go index 2f83bb5..6fea4fb 100644 --- a/internal/interactive/prompts.go +++ b/internal/interactive/prompts.go @@ -162,13 +162,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". From 2af7f74caa4885fe8a9444d0d92013aa13a05d4f Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:51:07 +0300 Subject: [PATCH 11/83] Tests: gate CI on race, lint and vulnerabilities --- .github/workflows/bridges.yml | 10 ++- .github/workflows/ci.yml | 11 +++- .github/workflows/release.yml | 3 +- .golangci.yml | 29 +++++++++ Makefile | 15 +++-- cmd/schema-gen/main.go | 3 +- compliance-suite/certification.yml | 22 ++++--- compliance-suite/regressions.tsv | 53 ++++++++++++++++ compliance-suite/regressions_test.go | 81 ++++++++++++++++++++++++- compliance-suite/suite.js | 4 +- internal/fsutil/fsutil.go | 4 +- internal/parser/integration_test.go | 31 +++++----- internal/parser/parser_test.go | 32 +++++----- internal/specmeta/specmeta.go | 31 +++++++++- internal/specmeta/specmeta_test.go | 2 +- internal/templatefuncs/templatefuncs.go | 9 ++- 16 files changed, 282 insertions(+), 58 deletions(-) diff --git a/.github/workflows/bridges.yml b/.github/workflows/bridges.yml index 4e55aeb..8d4ca39 100644 --- a/.github/workflows/bridges.yml +++ b/.github/workflows/bridges.yml @@ -50,4 +50,12 @@ jobs: run: go build ./cmd/domaincraft - name: Verify every bundled bridge loads (contract gate) - run: go test ./internal/renderer/ -run TestBundledBridgesLoad -v + # DOMAINCRAFT_LOCAL_DEV is the explicit local opt-out for the test; + # CI must never skip the gate. A missing bridges tree is an error. + run: | + unset DOMAINCRAFT_LOCAL_DEV + if [ ! -d bridges ]; then + echo "::error::bridges/ tree missing - contract gate cannot run" + exit 1 + fi + go test ./internal/renderer/ -run TestBundledBridgesLoad -v diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98f6423..c159bca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,16 +42,25 @@ jobs: - name: Download dependencies run: go mod download + - name: Check go.mod/go.sum are tidy + run: | + go mod tidy + git diff --exit-code -- go.mod go.sum + - name: Lint uses: golangci/golangci-lint-action@v8 with: version: v2.15.0 + - name: Vulnerability scan + # Pinned version, not @latest, so the gate is reproducible. + run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... + - name: Build run: go build ./cmd/domaincraft - name: Test - run: go test ./... + run: go test -race -count=1 ./... - name: Integration tests run: go test -tags=integration ./internal/bridge diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e641335..bdfe3ad 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,8 +24,9 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: '1.27' + go-version: '1.27.4' cache: true + cache-dependency-path: go.sum - name: Build all platforms run: | diff --git a/.golangci.yml b/.golangci.yml index 97c6220..06e269a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,3 +15,32 @@ linters: - 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] + # The IR* prefix is the documented template contract. Renaming these + # exported types would break every shipped bridge and the WASM GUI. + - path: 'internal/ir/.*\.go' + linters: [revive] + text: 'stutters' + # specmeta names mirror domain.yaml keys one-to-one. + - path: 'internal/specmeta/.*\.go' + linters: [revive] + text: 'stutters' + # SnapshotPath is part of the snapshot file layout contract. + - path: 'internal/snapshot/snapshot\.go' + linters: [revive] + text: 'stutters' + # Bridge service names are referenced by CLI help and registry docs. + - path: 'internal/bridge/.*\.go' + linters: [revive] + text: 'stutters' diff --git a/Makefile b/Makefile index 087c92d..ed96d9e 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ endif export GOCACHE := $(GO_CACHE_DIR) export GOTMPDIR := $(GO_TMP_DIR) -.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-verbose test-coverage lint fmt clean install-deps check-tidy 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" @@ -51,12 +51,19 @@ help: @echo " make fmt - Format code (gofmt)" @echo " make clean - Clean build artifacts" @echo " make install-deps - Install dependencies" + @echo " make check-tidy - Fail if go mod tidy would change go.mod/go.sum" install-deps: @echo "Installing dependencies..." @go mod download @go mod tidy +# 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))..." @go build -ldflags "-X main.version=$(VERSION)" -o bin/domaincraft ./cmd/domaincraft @@ -114,7 +121,7 @@ else @echo "Copied schema to $(SKILLS_DIR)/domain.schema.json" endif -test: install-deps +test: @echo "Running tests..." @go test ./... @@ -126,11 +133,11 @@ contract-test: contract-golden-update: @go test ./internal/contract/ -run TestGoldenLeafBridges -update -test-verbose: install-deps +test-verbose: @echo "Running tests (verbose)..." @go test -v ./... -test-coverage: install-deps +test-coverage: @echo "Running tests with coverage..." @go test -cover ./... @go test -coverprofile=coverage.out ./... diff --git a/cmd/schema-gen/main.go b/cmd/schema-gen/main.go index e60aa90..1249061 100644 --- a/cmd/schema-gen/main.go +++ b/cmd/schema-gen/main.go @@ -1,3 +1,4 @@ +// Command schema-gen generates spec/domain.schema.json from specmeta. package main import ( @@ -21,7 +22,7 @@ func main() { os.Exit(1) } - if err := os.WriteFile(*outputPath, append(data, '\n'), 0o644); err != nil { + if err := os.WriteFile(*outputPath, append(data, '\n'), 0o600); err != nil { fmt.Fprintln(os.Stderr, "write schema:", err) os.Exit(1) } diff --git a/compliance-suite/certification.yml b/compliance-suite/certification.yml index 3597fb5..edd5bdf 100644 --- a/compliance-suite/certification.yml +++ b/compliance-suite/certification.yml @@ -18,10 +18,13 @@ on: pull_request: branches: ["main"] +permissions: + contents: read + 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 + # Core release tag to check out. Keep in sync with RELEASES.md; pinning + # locks the TCK version instead of tracking an unreleased main branch. + CORE_VERSION: v0.7.0 # 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 @@ -43,18 +46,17 @@ jobs: 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). + # 3. Set up Go. The core requires Go 1.27 (see go.mod); match ci.yml. - name: Set up Go uses: actions/setup-go@v5 with: - go-version: "1.25" + go-version: "1.27" + cache: true + cache-dependency-path: core/go.sum - # 4. Build & install the CLI. `main` maps to the latest release; a pinned - # CORE_VERSION (e.g. v1.2.3) installs that exact release. + # 4. Build & install the CLI at the pinned core release. - name: Install DomainCraft CLI - run: | - go install github.com/DomainCraft/DomainCraft/cmd/domaincraft@${{ env.CORE_VERSION == 'main' && 'latest' || env.CORE_VERSION }} + run: go install github.com/DomainCraft/DomainCraft/cmd/domaincraft@${{ env.CORE_VERSION }} # 5. Generate code from the kitchen-sink domain using the current bridge. - name: Generate Code diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 3961fe7..574ed32 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -21,3 +21,56 @@ internal/snapshot/rewrite_test.go::TestRenameTransformsIncludesFieldRenames #5 f internal/bridge/clone_policy_test.go::TestMaybeUpdatePolicies #5 bridge update policy decisions had no regression coverage internal/bridge/clone_policy_test.go::TestApplyUpdateRejectsUnsupportedContract #5 apply path could hard-reset a bridge with an unsupported contract version internal/snapshot/rewrite_test.go::TestRewriteEntityContent #5 inner identifiers such as myProduct were not protected from rename rewrite +internal/ir/build_entities_test.go::TestBuildDetectsRelationPrimaryKeyCycle #5 relation-typed primary keys overflowed the stack during IR build +internal/ir/build_entities_test.go::TestResolveDatabaseTypeDetectsCycles #5 relation PK cycles were followed recursively without a visited set +internal/validator/validator_test.go::TestValidateRejectsRelationPrimaryKey #5 validator accepted relation-typed primary keys +internal/validator/validator_test.go::TestValidateRejectsNonPositiveStringBounds #5 negative max: modifier reached mock data generation +internal/seed/seed_test.go::TestGenerateClampsNonPositiveMaxLength #5 negative max sliced a string with a negative bound and panicked +internal/validator/validator_test.go::TestValidateRejectsEnumWireValueCollision #5 case-insensitive enum duplicates generated duplicate members +internal/validator/validator_test.go::TestValidateRejectsUnparseableNumericSeed #5 unparseable numeric seed strings silently became zero +internal/seed/seed_test.go::TestGenerateRotatesRelationPKs #5 one-to-one seed rows reused the same parent primary key +internal/seed/seed_test.go::TestRelationValueRotatesParentPKs #5 relation seed ignored unique one-to-one constraints +internal/validator/validator_test.go::TestValidateSortsErrorsByMessageTiebreaker #5 same-field diagnostics had nondeterministic order +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/hardening_test.go::TestRecordPinIsPersisted #5 pinned bridge ref was lost after an update +internal/bridge/hardening_test.go::TestGitScrubbedEnvAllowlist #5 git config and proxy environment variables could redirect bridge operations +internal/bridge/hardening_test.go::TestTryMaterializeEmbeddedRefusesSymlinks #5 cache symlink redirected embedded bridge writes +internal/bridge/hardening_test.go::TestApplyUpdateFailsWhenFetchedManifestIsUnreadable #5 contract gate was skipped when the remote bridge.yaml could not be read +internal/bridge/update_contract_test.go::TestParseBridgeContractVersion #5 malformed remote contract version defaulted to v1 +internal/bridge/update_contract_test.go::TestRemoteContractVersion #5 contract probe error was treated as a supported version +internal/bridge/hardening_test.go::TestHTTPProbeLimitsAndRedaction #5 oversized HTTP bodies were truncated and URL credentials leaked into errors +internal/bridge/hardening_test.go::TestHTTPProbeUsesCommandContext #5 bridge update HTTP probe outlived Ctrl+C +internal/packages/ssrf_test.go::TestRestrictedRegistryDialerRejectsInternalDNS #5 registry hostname resolving to a private address bypassed SSRF checks +internal/packages/ssrf_test.go::TestRestrictedRegistryDialerRejectsLiteralAndRedirectTargets #5 redirect to a private address passed validation +internal/packages/ssrf_test.go::TestValidateRegistryURLRedactsSecrets #5 registry URL userinfo leaked into error messages +internal/packages/ssrf_test.go::TestVersionCacheConcurrentWrites #5 concurrent renders lost package version cache entries +internal/packages/ssrf_test.go::TestVersionCacheWriteFailureIsSurfaced #5 version cache write errors were discarded +internal/packages/ssrf_test.go::TestFetchVersionsUsesCommandContext #5 registry request outlived Ctrl+C +internal/renderer/hardening_test.go::TestRenderRejectsSymlinkAtFinalComponent #5 final-component symlink let a template write outside outputDir +internal/renderer/hardening_test.go::TestRenderExecuteErrorPreservesPreviousOutput #5 template error deleted the previous valid output file +internal/renderer/hardening_test.go::TestRenderFailureRollsBackPriorWrites #5 failed render left partially written files on disk +internal/snapshot/hardening_test.go::TestSaveReplacesSnapshotWithoutTempLeftovers #5 snapshot.json was written non-atomically +internal/snapshot/hardening_test.go::TestRewriteEntityContentDoesNotRescanReplacement #5 rename rewrite rescanned its own output and corrupted identifiers +internal/snapshot/hardening_test.go::TestRenameRelPathDoesNotRescanReplacement #5 renamed path was rewritten twice into ProductItemItems +internal/snapshot/hardening_test.go::TestRewriteEntityContentUnicodeIdentifierBoundaries #5 byte-based boundaries split UTF-8 identifiers +internal/snapshot/hardening_test.go::TestSafeRelPathRejectsSymlinkEscape #5 --prune followed symlinks inside the output directory +internal/snapshot/hardening_test.go::TestComputeDiffIgnoresSnapshotPathsThroughSymlinks #5 poisoned snapshot path escaped the output directory +cmd/domaincraft/commands_hardening_test.go::TestBridgeEnsureOptionsRespectsNonInteractiveOnTTY #5 --non-interactive was ignored by the bridge update prompt +cmd/domaincraft/commands_hardening_test.go::TestMigrationCleanupDeferredOnTTYWhenNonInteractive #5 --non-interactive was ignored by migration file cleanup +cmd/domaincraft/commands_hardening_test.go::TestLoadAndValidateSendsDiagnosticsToStderr #5 validator diagnostics were written to stdout +cmd/domaincraft/commands_hardening_test.go::TestCommandLoggerWritesToStderr #5 CLI logger wrote diagnostics to stdout +cmd/domaincraft/commands_hardening_test.go::TestRootCommandSuppressesCobraErrorNoise #5 usage text was printed on every runtime error +cmd/domaincraft/commands_hardening_test.go::TestCommandTreesHaveIndependentFlags #5 package-global flags leaked between command trees +cmd/domaincraft/commands_hardening_test.go::TestExecutePrintsErrorOnce #5 command errors were printed more than once +cmd/domaincraft/commands_update_security_test.go::TestValidateReleaseURL #5 self-update accepted an unvalidated download URL +cmd/domaincraft/commands_update_security_test.go::TestRedactURL #5 URL credentials leaked into update errors +cmd/domaincraft/commands_update_security_test.go::TestReadResponseBodyRejectsOversizedPayload #5 oversized release body was silently truncated into a corrupt binary +cmd/domaincraft/commands_update_security_test.go::TestReadResponseBodyChecksRedirectHost #5 self-update followed a redirect to an untrusted host +cmd/domaincraft/commands_update_security_test.go::TestHTTPGetBodyUsesCommandContext #5 update request outlived Ctrl+C +cmd/domaincraft/commands_update_security_test.go::TestHTTPGetBodyRedactsURLInErrors #5 update URL credentials leaked into errors +cmd/domaincraft/commands_update_security_test.go::TestReleaseChecksum #5 release checksum was not parsed +cmd/domaincraft/commands_update_security_test.go::TestVerifyFileSHA256 #5 self-update installed a binary without checksum verification +cmd/domaincraft/commands_update_security_test.go::TestRunCoreUpdateFailsClosed #5 failed update path could still replace the executable +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 diff --git a/compliance-suite/regressions_test.go b/compliance-suite/regressions_test.go index 88ff2df..c7b7866 100644 --- a/compliance-suite/regressions_test.go +++ b/compliance-suite/regressions_test.go @@ -1,7 +1,9 @@ package compliance import ( + "fmt" "os" + "path/filepath" "strings" "testing" ) @@ -9,7 +11,9 @@ 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 +// must be non-empty and unique. A `file::TestX` name must still point at +// an existing test file that defines TestX, so a removed or renamed check +// cannot silently pass. This is the enforcement for the rule // "every bug fix adds its check here; a removed name is an error". func TestRegressionsTable(t *testing.T) { data, err := os.ReadFile("regressions.tsv") @@ -18,6 +22,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 +55,78 @@ 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. + } + if !strings.Contains(src, "func "+testName+"(") { + t.Errorf("line %d: %s does not define func %s(", i+1, path, testName) + } + } +} + +// 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/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index e166ba2..5115341 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -14,7 +14,7 @@ import ( // 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 { + if err := os.MkdirAll(dir, 0o755); err != nil { //nolint:gosec // generated project and cache dirs must stay world-readable return err } @@ -47,7 +47,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/parser/integration_test.go b/internal/parser/integration_test.go index bd9754a..ffc4b0c 100644 --- a/internal/parser/integration_test.go +++ b/internal/parser/integration_test.go @@ -1,7 +1,6 @@ package parser import ( - "fmt" "testing" ) @@ -193,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"] @@ -212,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 @@ -232,9 +231,9 @@ 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") } } @@ -259,13 +258,13 @@ 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") } } @@ -308,7 +307,7 @@ entities: } for _, tt := range tests { - t.Run(fmt.Sprintf("%v", tt), func(t *testing.T) { + t.Run(tt.fieldName, func(t *testing.T) { t.Parallel() if field, ok := user.Fields[tt.fieldName]; ok { if field.DatabaseColumnName != tt.wantDbName { diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index e484c15..3bb8549 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -250,28 +250,28 @@ 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") } } diff --git a/internal/specmeta/specmeta.go b/internal/specmeta/specmeta.go index 4d7dfb2..074bd3d 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -13,12 +13,16 @@ type FeatureFieldDef struct { DefaultValue string `json:"defaultValue"` } +// Databases lists the supported database backends. var Databases = []string{"postgresql", "mysql", "sqlite", "mssql", "mongodb", "appwrite"} +// APIStyles lists the supported API styles. var APIStyles = []string{"rest", "graphql", "grpc"} +// AuthTypes lists the supported authentication types. var AuthTypes = []string{"jwt", "none"} +// 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 @@ -31,17 +35,25 @@ 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"} +// MetaFieldTypes lists the non-primitive field types. var MetaFieldTypes = []string{"relation", "array", "enum"} +// 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"}, @@ -51,40 +63,55 @@ var FeatureFieldDefs = map[string]FeatureFieldDef{ "version": {Feature: "optimistic_lock", Type: "int", DBColumn: "version", DefaultValue: "0"}, } +// OnDeleteValues lists the valid on_delete modifier values. var OnDeleteValues = []string{"cascade", "set_null", "restrict", "no_action"} +// PrimitiveFieldTypes lists the scalar field types. var PrimitiveFieldTypes = []string{ "string", "text", "int", "bigint", "float", "decimal", "boolean", "date", "datetime", "uuid", "json", "jsonb", } +// NumericFieldTypes lists the numeric scalar types. var NumericFieldTypes = []string{"int", "bigint", "float", "decimal"} +// StringFieldTypes lists the string scalar types. var StringFieldTypes = []string{"string", "text"} +// NumericValidationModifiers lists numeric validation modifier names. var NumericValidationModifiers = []string{"gte", "gt", "lte", "lt"} +// StringValidationModifiers lists string validation modifier names. var StringValidationModifiers = []string{"min", "max", "email", "url", "ipv4", "regex"} +// IndexTypes lists the supported database index types. var IndexTypes = []string{"btree", "hash", "gist", "gin", "brin"} +// CacheProviders lists the supported cache providers. var CacheProviders = []string{"redis", "memcached", "in-memory"} +// 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"} +// SortDirections lists the valid sort directions. var SortDirections = []string{"asc", "desc"} +// BooleanFieldTypes lists the boolean scalar types. var BooleanFieldTypes = []string{"boolean"} +// FuncDefaults maps default functions to their compatible field types. var FuncDefaults = map[string][]string{ "now": {"date", "datetime"}, "uuid": {"uuid"}, } +// DefaultFieldType is the fallback type for unresolvable fields. const DefaultFieldType = "string" var ( diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index c07def6..cad4b59 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -479,7 +479,7 @@ func TestBuildEntityFields(t *testing.T) { func TestBuildEntityFieldsEmptyOrder(t *testing.T) { t.Parallel() - result := BuildEntityFields(nil, func(name string) []string { return nil }) + result := BuildEntityFields(nil, func(_ string) []string { return nil }) if len(result) != 0 { t.Errorf("BuildEntityFields(nil) returned %d entries, want 0", len(result)) } diff --git a/internal/templatefuncs/templatefuncs.go b/internal/templatefuncs/templatefuncs.go index d48a67f..d7de565 100644 --- a/internal/templatefuncs/templatefuncs.go +++ b/internal/templatefuncs/templatefuncs.go @@ -7,6 +7,7 @@ package templatefuncs import ( "fmt" + "math" "path" "reflect" "strconv" @@ -154,7 +155,7 @@ func Dict(v ...any) map[string]any { 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 } @@ -294,6 +295,9 @@ func toInt64(v any) int64 { case int64: return val case uint: + if val > math.MaxInt64 { + return math.MaxInt64 + } return int64(val) case uint8: return int64(val) @@ -302,6 +306,9 @@ func toInt64(v any) int64 { case uint32: return int64(val) case uint64: + if val > math.MaxInt64 { + return math.MaxInt64 + } return int64(val) case float32: return int64(val) From da53e20090f5225cc0e76d75fdd3279abb287807 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:54:03 +0300 Subject: [PATCH 12/83] Tests: use absolute temp root in safeRelPath check --- internal/snapshot/paths_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/snapshot/paths_test.go b/internal/snapshot/paths_test.go index 32837a8..f245911 100644 --- a/internal/snapshot/paths_test.go +++ b/internal/snapshot/paths_test.go @@ -11,6 +11,10 @@ import ( 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 @@ -38,8 +42,8 @@ func TestSafeRelPathKeepsPathsInsideOutputDir(t *testing.T) { if (err != nil) != tt.wantErr { t.Fatalf("safeRelPath(%q) error = %v, wantErr %v", tt.path, err, tt.wantErr) } - if err == nil && !strings.HasPrefix(got, root+string(filepath.Separator)) && got != root { - t.Fatalf("safeRelPath(%q) = %q, outside %q", tt.path, got, root) + if err == nil && !strings.HasPrefix(got, absRoot+string(filepath.Separator)) && got != absRoot { + t.Fatalf("safeRelPath(%q) = %q, outside %q", tt.path, got, absRoot) } }) } From 6948d3a740cec44c26b2017cc2780fbecc0b7fb0 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:07:17 +0300 Subject: [PATCH 13/83] Core: unstutter public IR and specmeta names --- .golangci.yml | 17 -- CONTRIBUTING.md | 2 +- bridges/csharp/core/tck/QueryContractTests.cs | 2 +- .../csharp/core/templates/_helpers.cs.tmpl | 26 +-- bridges/csharp/core/templates/query.cs.tmpl | 6 +- .../domain/templates/irepository.cs.tmpl | 2 +- .../rest/templates/api-app-extensions.cs.tmpl | 2 +- .../rest/templates/auth-controller.cs.tmpl | 2 +- .../rest/templates/controller.cs.tmpl | 2 +- .../typescript/client/templates/api.ts.tmpl | 4 +- .../core/templates/_helpers.ts.tmpl | 6 +- .../typescript/core/templates/query.ts.tmpl | 4 +- .../typescript/core/templates/types.ts.tmpl | 2 +- .../typescript/react/templates/auth.ts.tmpl | 2 +- cmd/domaincraft/commands.go | 6 +- cmd/wasm-validator/main.go | 2 +- internal/bridge/clone.go | 6 +- internal/bridge/embed.go | 2 +- internal/bridge/resolve_ext.go | 8 +- internal/contract/golden_test.go | 4 +- .../contract/testdata/csharp-core.golden.txt | 2 +- internal/contract/testdata/ts-core.golden.txt | 2 +- internal/ir/build_entities.go | 54 +++---- internal/ir/build_entities_test.go | 14 +- internal/ir/build_relations.go | 16 +- internal/ir/contract_test.go | 72 ++++----- internal/ir/dto.go | 24 +-- internal/ir/dto_test.go | 76 ++++----- internal/ir/endpoints.go | 30 ++-- internal/ir/enums.go | 10 +- internal/ir/enums_test.go | 6 +- internal/ir/field_methods.go | 4 +- internal/ir/indexes.go | 10 +- internal/ir/models.go | 150 +++++++++--------- internal/ir/models_test.go | 40 ++--- internal/ir/permissions.go | 14 +- internal/ir/query.go | 32 ++-- internal/ir/query_test.go | 22 +-- internal/ir/toposort.go | 8 +- internal/ir/typekind.go | 40 ++--- internal/ir/typekind_test.go | 42 ++--- internal/ir/validations.go | 12 +- internal/renderer/hardening_test.go | 6 +- internal/renderer/models.go | 32 ++-- internal/renderer/render.go | 8 +- internal/renderer/render_test.go | 42 ++--- internal/seed/seed.go | 22 +-- internal/seed/seed_test.go | 106 ++++++------- internal/snapshot/hardening_test.go | 2 +- internal/snapshot/migration.go | 12 +- internal/snapshot/migration_test.go | 28 ++-- internal/snapshot/snapshot.go | 10 +- internal/snapshot/snapshot_test.go | 66 ++++---- internal/specmeta/specmeta_json.go | 4 +- spec/errors.md | 6 +- spec/query.md | 12 +- 56 files changed, 563 insertions(+), 580 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 06e269a..4008208 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -27,20 +27,3 @@ linters: # file-permission and path-taint rules target production code. - path: '(.+)_test\.go$' linters: [gosec] - # The IR* prefix is the documented template contract. Renaming these - # exported types would break every shipped bridge and the WASM GUI. - - path: 'internal/ir/.*\.go' - linters: [revive] - text: 'stutters' - # specmeta names mirror domain.yaml keys one-to-one. - - path: 'internal/specmeta/.*\.go' - linters: [revive] - text: 'stutters' - # SnapshotPath is part of the snapshot file layout contract. - - path: 'internal/snapshot/snapshot\.go' - linters: [revive] - text: 'stutters' - # Bridge service names are referenced by CLI help and registry docs. - - path: 'internal/bridge/.*\.go' - linters: [revive] - text: 'stutters' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cc9584e..6f717ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,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/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 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/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/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/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/templates/_helpers.ts.tmpl b/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/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/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index d0f93f0..b52bad3 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -250,7 +250,7 @@ func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { applyAddons(opts, irProject) // --- Schema snapshot / migration diff --- - snapPath := snapshot.SnapshotPath(opts.outputDir) + snapPath := snapshot.Path(opts.outputDir) oldSnapshot, err := snapshot.Load(snapPath) if err != nil { return fmt.Errorf("load schema snapshot: %w", err) @@ -823,7 +823,7 @@ func bridgeUpdateNotice(entryID string, _ *bridge.Update) string { // generateAdminPanel renders the optional admin panel bridge into the output // directory and returns the extra file manifest entries. -func generateAdminPanel(opts *cliOptions, irProject *ir.IRProject, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { +func generateAdminPanel(opts *cliOptions, irProject *ir.Project, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { resolver := bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(opts, log)) adminID := opts.adminBridge @@ -1111,7 +1111,7 @@ func customMark(f snapshot.FileRef) string { // 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(opts *cliOptions, project *ir.IRProject) { +func applyAddons(opts *cliOptions, project *ir.Project) { if strings.TrimSpace(opts.addons) == "" { return } diff --git a/cmd/wasm-validator/main.go b/cmd/wasm-validator/main.go index a42f822..84a908d 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -41,7 +41,7 @@ func versionFunc(_ js.Value, _ []js.Value) any { } func specmetaFunc(_ js.Value, _ []js.Value) any { - return marshal(specmeta.SpecmetaJSON()) + return marshal(specmeta.JSON()) } func validate(_ js.Value, args []js.Value) any { diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index 329e2d3..51677e3 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -11,9 +11,9 @@ import ( "github.com/DomainCraft/DomainCraft/internal/appdir" ) -// BridgeCacheDir returns ~/.domaincraft/bridges/. +// CacheDir returns ~/.domaincraft/bridges/. // Falls back to .domaincraft/bridges in the current directory if the home directory is unavailable. -func BridgeCacheDir() string { +func CacheDir() string { dir, err := appdir.UnionDir("bridges") if err != nil { return filepath.Join(".domaincraft", "bridges") @@ -23,7 +23,7 @@ func BridgeCacheDir() string { // CachePath returns the local cache directory for a bridge entry. func CachePath(entry RegistryEntry) string { - return filepath.Join(BridgeCacheDir(), entry.ID) + return filepath.Join(CacheDir(), entry.ID) } // validateCacheID rejects bridge IDs that could resolve outside the cache diff --git a/internal/bridge/embed.go b/internal/bridge/embed.go index 4b679fe..3cd8763 100644 --- a/internal/bridge/embed.go +++ b/internal/bridge/embed.go @@ -31,7 +31,7 @@ func TryMaterializeEmbedded(entry RegistryEntry, opts *EnsureOptions) (bool, err dst := CachePath(entry) // The cache may be attacker-controlled (a planted symlink would redirect // writes outside it), so check the whole path before creating anything. - if err := refuseSymlinks(BridgeCacheDir(), dst); err != nil { + if err := refuseSymlinks(CacheDir(), dst); 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 diff --git a/internal/bridge/resolve_ext.go b/internal/bridge/resolve_ext.go index 6d8c888..e34a23e 100644 --- a/internal/bridge/resolve_ext.go +++ b/internal/bridge/resolve_ext.go @@ -134,9 +134,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. @@ -155,8 +155,8 @@ 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 { s.Embedded = true diff --git a/internal/contract/golden_test.go b/internal/contract/golden_test.go index 8cac6dd..6f370c9 100644 --- a/internal/contract/golden_test.go +++ b/internal/contract/golden_test.go @@ -31,7 +31,7 @@ var updateGolden = flag.Bool("update", false, "regenerate golden files") // a follow-up once that resolution moves into an importable package. var leafBridges = []string{"csharp-core", "ts-core", "admin-alpine", "appwrite"} -func loadGoldenProject(t *testing.T) *ir.IRProject { +func loadGoldenProject(t *testing.T) *ir.Project { t.Helper() data, err := os.ReadFile(filepath.Join("testdata", "domain.yaml")) if err != nil { @@ -97,7 +97,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) 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/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/ir/build_entities.go b/internal/ir/build_entities.go index bb04a3c..332315e 100644 --- a/internal/ir/build_entities.go +++ b/internal/ir/build_entities.go @@ -20,13 +20,13 @@ func oldDatabaseColumnName(field *parser.ParsedField) string { return textutil.ToDatabaseColumnName(field.OldName) } -// Build converts ParsedSchema into IRProject. -func Build(schema *parser.ParsedSchema) (*IRProject, error) { +// 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,11 +35,11 @@ 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{ + irProject.Cache = &CacheConfig{ Enabled: schema.Project.Cache.Enabled, Provider: schema.Project.Cache.Provider, ConnectionString: schema.Project.Cache.ConnectionString, @@ -47,25 +47,25 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { } } if schema.Project.CORS != nil { - irProject.CORS = &IRCORSConfig{ + irProject.CORS = &CORSConfig{ Enabled: schema.Project.CORS.Enabled, Origins: append([]string(nil), schema.Project.CORS.Origins...), } } if schema.Project.Deploy != nil { - irProject.Deploy = &IRDeployConfig{ + irProject.Deploy = &DeployConfig{ Domain: schema.Project.Deploy.Domain, Port: schema.Project.Deploy.Port, } } if schema.Project.Versioning != nil { - irProject.Versioning = &IRVersioningConfig{ + irProject.Versioning = &VersioningConfig{ Enabled: schema.Project.Versioning.Enabled, DefaultVersion: schema.Project.Versioning.DefaultVersion, } } if schema.Project.RateLimit != nil { - irProject.RateLimit = &IRRateLimitConfig{ + irProject.RateLimit = &RateLimitConfig{ Enabled: schema.Project.RateLimit.Enabled, Policy: schema.Project.RateLimit.Policy, PermitLimit: schema.Project.RateLimit.PermitLimit, @@ -73,13 +73,13 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { } } if schema.Project.Pagination != nil { - irProject.Pagination = &IRPaginationConfig{ + irProject.Pagination = &PaginationConfig{ DefaultPageSize: schema.Project.Pagination.DefaultPageSize, MaxPageSize: schema.Project.Pagination.MaxPageSize, } } if schema.Project.Infrastructure != nil { - irProject.Infrastructure = &IRInfrastructure{ + irProject.Infrastructure = &Infrastructure{ Queue: schema.Project.Infrastructure.Queue, Cache: schema.Project.Infrastructure.Cache, Secrets: schema.Project.Infrastructure.Secrets, @@ -88,22 +88,22 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { } // 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)), + Fields: make([]Field, 0, len(sourceEntity.FieldOrder)), + RelationsOut: make([]Relation, 0), + RelationsIn: make([]Relation, 0), + Indexes: make([]Index, 0, len(sourceEntity.Indexes)), Seed: sourceEntity.Seed, Permissions: convertPermissions(sourceEntity.Permissions), } @@ -119,7 +119,7 @@ func Build(schema *parser.ParsedSchema) (*IRProject, error) { 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 +141,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, @@ -174,22 +174,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...), @@ -254,7 +254,7 @@ func resolveArrayType(targetType string) string { return "array(string)" } -func convertAuth(source *parser.AuthConfig, schema *parser.ParsedSchema) *IRAuthConfig { +func convertAuth(source *parser.AuthConfig, schema *parser.ParsedSchema) *AuthConfig { if source == nil || source.Type == "" || source.Type == "none" { return nil } @@ -274,11 +274,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, diff --git a/internal/ir/build_entities_test.go b/internal/ir/build_entities_test.go index b6f5a59..7f2ba7f 100644 --- a/internal/ir/build_entities_test.go +++ b/internal/ir/build_entities_test.go @@ -615,7 +615,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] } @@ -665,14 +665,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 } @@ -811,7 +811,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] @@ -838,7 +838,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] @@ -907,7 +907,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] @@ -985,7 +985,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] diff --git a/internal/ir/build_relations.go b/internal/ir/build_relations.go index 3d0335c..0df060a 100644 --- a/internal/ir/build_relations.go +++ b/internal/ir/build_relations.go @@ -11,7 +11,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 +30,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(), @@ -51,7 +51,7 @@ func buildForwardRelations(entities []IREntity, schema *parser.ParsedSchema, ent // 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) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -75,7 +75,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) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -96,7 +96,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) { usedInverse := make(map[string]map[string]bool) // target entity -> defined inverse nav names for i := range entities { entity := &entities[i] @@ -130,7 +130,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, @@ -145,7 +145,7 @@ 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 { +func findSingleBack(target *Entity, sourceName string) *Relation { if target == nil { return nil } @@ -161,7 +161,7 @@ func findSingleBack(target *IREntity, sourceName string) *IRRelation { // 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 { +func hasForwardManyTo(target *Entity, entityName string) bool { if target == nil { return false } diff --git a/internal/ir/contract_test.go b/internal/ir/contract_test.go index 47fb5f7..a732305 100644 --- a/internal/ir/contract_test.go +++ b/internal/ir/contract_test.go @@ -4,10 +4,10 @@ import "testing" func TestValidationRules(t *testing.T) { t.Parallel() - f := IRField{ + f := Field{ Name: "email", DatabaseType: "string", - Validations: []IRValidation{ + Validations: []Validation{ {Name: "email", Value: "true"}, {Name: "min", Value: "3"}, {Name: "max", Value: "50"}, @@ -35,10 +35,10 @@ func TestValidationRules(t *testing.T) { func TestValidationRulesNumericBounds(t *testing.T) { t.Parallel() - f := IRField{ + f := Field{ Name: "qty", DatabaseType: "int", - Validations: []IRValidation{ + Validations: []Validation{ {Name: "gte", Value: "10"}, {Name: "lte", Value: "20"}, }, @@ -56,16 +56,16 @@ 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 { t.Run(c.name, func(t *testing.T) { @@ -89,7 +89,7 @@ func TestValidationRulesCodesAndMessages(t *testing.T) { func TestValidationRulesNullableNotRequired(t *testing.T) { t.Parallel() - f := IRField{Name: "nick", DatabaseType: "string", IsNullable: true} + 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") @@ -99,15 +99,15 @@ func TestValidationRulesNullableNotRequired(t *testing.T) { func TestAllIndexesMergesUniqueFields(t *testing.T) { t.Parallel() - e := IREntity{ + 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}, }, } @@ -134,11 +134,11 @@ func TestAllIndexesMergesUniqueFields(t *testing.T) { func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { t.Parallel() - e := IREntity{ + 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 { @@ -151,7 +151,7 @@ func TestAllIndexesDedupesDeclaredUnique(t *testing.T) { func TestPermissionPlan(t *testing.T) { t.Parallel() - p := &IRPermissions{ + p := &Permissions{ Read: []string{"*"}, Create: []string{"Admin", "@Owner"}, Update: []string{}, @@ -180,7 +180,7 @@ func TestPermissionPlan(t *testing.T) { func TestPermissionPlanNil(t *testing.T) { t.Parallel() - var p *IRPermissions + var p *Permissions if p.Plan("read") != nil { t.Error("nil permissions should yield nil plan") } @@ -188,13 +188,13 @@ func TestPermissionPlanNil(t *testing.T) { func TestEndpointsContract(t *testing.T) { t.Parallel() - e := IREntity{Name: "Order", NamePlural: "Orders", Features: map[string]bool{"optimistic_lock": true}} + 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 } @@ -222,19 +222,19 @@ func TestEndpointsContract(t *testing.T) { func TestIREntity_PrimaryKey(t *testing.T) { t.Parallel() - e := IREntity{Fields: []IRField{{Name: "name"}, {Name: "id", IsPrimary: true}}} + 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) { t.Parallel() - e := IREntity{Fields: []IRField{{Name: "firstName"}, {Name: "ID"}}} + 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) } @@ -246,16 +246,16 @@ func TestIREntity_FieldByName(t *testing.T) { } } -func TestIRProject_AuthEntity(t *testing.T) { +func TestProject_AuthEntity(t *testing.T) { t.Parallel() - p := &IRProject{ - Auth: &IRAuthConfig{Type: "jwt", Entity: "User"}, - Entities: []IREntity{{Name: "Order"}, {Name: "User"}}, + 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. @@ -267,13 +267,13 @@ func TestIRProject_AuthEntity(t *testing.T) { func TestIRPermissions_HasOwnerToken(t *testing.T) { t.Parallel() - if (&IRPermissions{Read: []string{"Admin"}, Create: []string{"*"}}).HasOwnerToken() { + 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") } @@ -281,10 +281,10 @@ func TestIRPermissions_HasOwnerToken(t *testing.T) { func TestAuthEndpoints(t *testing.T) { t.Parallel() - p := &IRProject{Auth: &IRAuthConfig{ + p := &Project{Auth: &AuthConfig{ Type: "jwt", Entity: "User", - Endpoints: IRAuthEndpoints{ + Endpoints: AuthEndpoints{ HasLogin: true, HasRegister: true, HasMe: true, HasSetup: true, }, }} @@ -300,7 +300,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..17ab2e5 100644 --- a/internal/ir/dto.go +++ b/internal/ir/dto.go @@ -10,7 +10,7 @@ import ( // 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 +18,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,7 +27,7 @@ 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" } @@ -36,9 +36,9 @@ func (f IRField) IsConcurrencyToken() bool { // 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 +func (e Entity) ReadFields() []Field { + out := make([]Field, 0, len(e.Fields)) + var feature []Field for _, f := range e.Fields { if f.IsHidden || f.IsSensitive() { continue @@ -55,8 +55,8 @@ func (e IREntity) ReadFields() []IRField { // 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)) +func (e Entity) CreateFields() []Field { + out := make([]Field, 0, len(e.Fields)) for _, f := range e.Fields { if f.IsPrimary || f.IsReadonly || f.IsFeatureField() || f.IsSensitive() { continue @@ -69,8 +69,8 @@ func (e IREntity) CreateFields() []IRField { // 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)) +func (e Entity) UpdateFields() []Field { + out := make([]Field, 0, len(e.Fields)) for _, f := range e.Fields { if f.IsPrimary || f.IsReadonly || f.IsSensitive() { continue @@ -89,8 +89,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)) +func (e Entity) PatchFields() []Field { + out := make([]Field, 0, len(e.Fields)) for _, f := range e.Fields { if f.IsPatchable() || f.IsConcurrencyToken() { out = append(out, f) diff --git a/internal/ir/dto_test.go b/internal/ir/dto_test.go index d8276c7..7a3bb83 100644 --- a/internal/ir/dto_test.go +++ b/internal/ir/dto_test.go @@ -2,8 +2,8 @@ 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) { @@ -21,7 +21,7 @@ func TestIRField_IsSensitive(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() - f := IRField{Name: tc.name} + f := Field{Name: tc.name} if got := f.IsSensitive(); got != tc.want { t.Errorf("IsSensitive(%q) = %v, want %v", tc.name, got, tc.want) } @@ -31,23 +31,23 @@ func TestIRField_IsSensitive(t *testing.T) { func TestIRField_IsFeatureField(t *testing.T) { t.Parallel() - if !(IRField{Name: "createdAt"}).IsFeatureField() { + 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) { t.Parallel() - if !(IRField{Name: "version"}).IsConcurrencyToken() { + 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") } } @@ -55,12 +55,12 @@ func TestIRField_IsConcurrencyToken(t *testing.T) { 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 { @@ -76,12 +76,12 @@ 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 { @@ -97,10 +97,10 @@ 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 { @@ -123,16 +123,16 @@ 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"} @@ -149,9 +149,9 @@ 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" { @@ -159,7 +159,7 @@ func TestIREntity_PatchFieldsNoVersionWithoutLock(t *testing.T) { } } -func names(fields []IRField) []string { +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 e201821..b06f7fb 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,7 +22,7 @@ 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). @@ -32,7 +32,7 @@ type IREndpoint struct { // 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" @@ -47,13 +47,13 @@ func (e IREndpoint) AuthPolicy() string { } // HasStatus reports whether status is among the endpoint's possible statuses. -func (e IREndpoint) HasStatus(status int) bool { +func (e Endpoint) HasStatus(status int) bool { return e.SuccessStatus == status || slices.Contains(e.ErrorStatuses, status) } // 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 @@ -68,7 +68,7 @@ func (e IREntity) Endpoints() []IREndpoint { slices.Sort(updateErrors) } - eps := []IREndpoint{ + eps := []Endpoint{ { Method: "GET", Path: base, Operation: "list", HasBody: false, SuccessStatus: 200, @@ -106,9 +106,9 @@ func (e IREntity) Endpoints() []IREndpoint { return eps } -// IREndpointDecl is a project-level endpoint in the contract (e.g. auth +// EndpointDecl 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 { +type EndpointDecl struct { Method string Path string Operation string @@ -120,37 +120,37 @@ type IREndpointDecl struct { // AuthEndpoints returns the project-level auth endpoint contract (login / // register / me / setup) when authentication is enabled. -func (p *IRProject) AuthEndpoints() []IREndpointDecl { +func (p *Project) AuthEndpoints() []EndpointDecl { if !p.HasAuth() || p.Auth == nil { return nil } entity := p.Auth.Entity base := "api/" + entity - var decls []IREndpointDecl + var decls []EndpointDecl if p.Auth.Endpoints.HasLogin { - decls = append(decls, IREndpointDecl{ + decls = append(decls, EndpointDecl{ 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{ + decls = append(decls, EndpointDecl{ 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{ + decls = append(decls, EndpointDecl{ Method: "GET", Path: base + "/me", Operation: "me", HasBody: false, SuccessStatus: 200, ErrorStatuses: []int{401, 404, 429}, }) } if p.Auth.Endpoints.HasSetup { - decls = append(decls, IREndpointDecl{ + decls = append(decls, EndpointDecl{ Method: "POST", Path: base + "/setup", Operation: "setup", HasBody: true, SuccessStatus: 201, ErrorStatuses: []int{400, 409, 429}, Anonymous: true, 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 86f53b6..c179baf 100644 --- a/internal/ir/enums_test.go +++ b/internal/ir/enums_test.go @@ -4,7 +4,7 @@ import "testing" func TestEnumValuesWireValue(t *testing.T) { t.Parallel() - p := &IRProject{ + p := &Project{ Enums: map[string][]string{ "OrderStatus": {"PENDING", "IN_PROGRESS", "Shipped"}, "Single": {"Draft"}, @@ -50,7 +50,7 @@ func TestEnumValuesWireValue(t *testing.T) { func TestEnumValuesNilProject(t *testing.T) { t.Parallel() - var p *IRProject + var p *Project if got := p.EnumValues("X"); got != nil { t.Errorf("nil project EnumValues = %v, want nil", got) } @@ -68,7 +68,7 @@ func TestIRIndexDatabaseName(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - if got := (IRIndex{Name: c.name}).DatabaseName(); got != c.want { + 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..4c05f0a 100644 --- a/internal/ir/field_methods.go +++ b/internal/ir/field_methods.go @@ -3,7 +3,7 @@ package ir import "strings" // HasValidation reports whether the field has the named validation. -func (f IRField) HasValidation(name string) bool { +func (f Field) HasValidation(name string) bool { for _, validation := range f.Validations { if strings.EqualFold(validation.Name, name) { return true @@ -13,7 +13,7 @@ func (f IRField) HasValidation(name string) bool { } // ValidationValue returns the first validation value for the given name. -func (f IRField) ValidationValue(name string) string { +func (f Field) ValidationValue(name string) string { for _, validation := range f.Validations { if strings.EqualFold(validation.Name, name) { return validation.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 1495661..20a31e6 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -9,28 +9,28 @@ import ( "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. @@ -38,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 @@ -50,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 @@ -74,7 +74,7 @@ type IRAuthEndpoints struct { } // HasAuth returns true if authentication is enabled. -func (p *IRProject) HasAuth() bool { +func (p *Project) HasAuth() bool { return p.Auth != nil && p.Auth.Type != "" && p.Auth.Type != "none" } @@ -82,7 +82,7 @@ func (p *IRProject) HasAuth() bool { // 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 { +func (p *Project) AuthEntity() *Entity { if p == nil || !p.HasAuth() || p.Auth == nil { return nil } @@ -94,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) } -// IRVersioningConfig controls 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 } -// IRRateLimitConfig represents the HTTP request rate limiting policy in IR. -type IRRateLimitConfig struct { +// RateLimitConfig represents the HTTP request rate limiting policy in IR. +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 + Fields []Field + RelationsOut []Relation + RelationsIn []Relation + Indexes []Index Seed []map[string]any - Permissions *IRPermissions + 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 @@ -178,12 +178,12 @@ 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 +func (e Entity) NonRelationFields() []Field { + var result []Field for _, f := range e.Fields { if !f.IsRelation { result = append(result, f) @@ -193,8 +193,8 @@ func (e IREntity) NonRelationFields() []IRField { } // RelationFields returns only relation fields. -func (e IREntity) RelationFields() []IRField { - var result []IRField +func (e Entity) RelationFields() []Field { + var result []Field for _, f := range e.Fields { if f.IsRelation { result = append(result, f) @@ -207,7 +207,7 @@ func (e IREntity) RelationFields() []IRField { // 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 { +func (e Entity) EagerLoadRelations() []Relation { return slices.Clone(e.RelationsOut) } @@ -215,7 +215,7 @@ func (e IREntity) EagerLoadRelations() []IRRelation { // 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 } @@ -226,7 +226,7 @@ func (r IRRelation) EagerLoadNavigation() string { // 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 { +func (e Entity) TableName() string { return textutil.ToDatabaseColumnName(e.NamePlural) } @@ -234,7 +234,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)) } @@ -243,7 +243,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)) } @@ -254,7 +254,7 @@ func (f IRField) ColumnName() string { } // 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] } @@ -262,7 +262,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] @@ -272,9 +272,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] @@ -284,47 +284,47 @@ 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 @@ -346,8 +346,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 @@ -355,8 +355,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 548c8d8..096b112 100644 --- a/internal/ir/models_test.go +++ b/internal/ir/models_test.go @@ -18,7 +18,7 @@ func TestIRField_IsArray(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - f := IRField{DatabaseType: tt.databaseType} + f := Field{DatabaseType: tt.databaseType} if got := f.IsArray(); got != tt.want { t.Errorf("IsArray() = %v, want %v", got, tt.want) } @@ -41,7 +41,7 @@ func TestIRField_ArrayElementType(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - f := IRField{DatabaseType: tt.databaseType} + f := Field{DatabaseType: tt.databaseType} if got := f.ArrayElementType(); got != tt.want { t.Errorf("ArrayElementType() = %q, want %q", got, tt.want) } @@ -66,7 +66,7 @@ func TestIREntity_HasFeature(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - e := IREntity{Features: tt.features} + 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) } @@ -88,7 +88,7 @@ func TestIREntity_HasAudit(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - e := IREntity{Features: tt.features} + e := Entity{Features: tt.features} if got := e.HasAudit(); got != tt.want { t.Errorf("HasAudit() = %v, want %v", got, tt.want) } @@ -98,11 +98,11 @@ func TestIREntity_HasAudit(t *testing.T) { func TestIREntity_HasAuditLog(t *testing.T) { t.Parallel() - e := IREntity{Features: map[string]bool{"audit_log": true}} + 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") } @@ -110,7 +110,7 @@ func TestIREntity_HasAuditLog(t *testing.T) { func TestIREntity_HasSoftDelete(t *testing.T) { t.Parallel() - e := IREntity{Features: map[string]bool{"soft_delete": true}} + e := Entity{Features: map[string]bool{"soft_delete": true}} if !e.HasSoftDelete() { t.Error("HasSoftDelete() = false, want true") } @@ -118,7 +118,7 @@ func TestIREntity_HasSoftDelete(t *testing.T) { func TestIREntity_HasOptimisticLock(t *testing.T) { t.Parallel() - e := IREntity{Features: map[string]bool{"optimistic_lock": true}} + e := Entity{Features: map[string]bool{"optimistic_lock": true}} if !e.HasOptimisticLock() { t.Error("HasOptimisticLock() = false, want true") } @@ -126,8 +126,8 @@ func TestIREntity_HasOptimisticLock(t *testing.T) { func TestIREntity_NonRelationFields(t *testing.T) { t.Parallel() - e := IREntity{ - Fields: []IRField{ + e := Entity{ + Fields: []Field{ {Name: "id", IsRelation: false}, {Name: "categoryId", IsRelation: true}, {Name: "name", IsRelation: false}, @@ -144,8 +144,8 @@ func TestIREntity_NonRelationFields(t *testing.T) { func TestIREntity_RelationFields(t *testing.T) { t.Parallel() - e := IREntity{ - Fields: []IRField{ + e := Entity{ + Fields: []Field{ {Name: "id", IsRelation: false}, {Name: "categoryId", IsRelation: true}, {Name: "name", IsRelation: false}, @@ -165,24 +165,24 @@ func TestIREntity_RelationFields(t *testing.T) { // with the template `snakecase`, which diverges on acronyms. func TestCanonicalNameContract(t *testing.T) { t.Parallel() - e := IREntity{Name: "OrderItem", NamePlural: "OrderItems"} + 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 { t.Run(c.name, func(t *testing.T) { @@ -196,11 +196,11 @@ func TestCanonicalNameContract(t *testing.T) { func TestEagerLoadNavigation(t *testing.T) { t.Parallel() - r := IRRelation{FieldName: "orders", NavigationName: "Order", IsMany: true} + 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) } diff --git a/internal/ir/permissions.go b/internal/ir/permissions.go index 7bae330..ee8a850 100644 --- a/internal/ir/permissions.go +++ b/internal/ir/permissions.go @@ -6,7 +6,7 @@ import ( "github.com/DomainCraft/DomainCraft/internal/specmeta" ) -// IRPermissionPlan is the core-computed authorization plan for one operation +// 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]). @@ -16,7 +16,7 @@ import ( // // 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 @@ -27,7 +27,7 @@ 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 } @@ -42,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 } @@ -50,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 } @@ -68,7 +68,7 @@ func (p *IRPermissions) Plan(operation string) *IRPermissionPlan { return nil } - plan := &IRPermissionPlan{Operation: operation} + plan := &PermissionPlan{Operation: operation} for _, r := range roles { switch { case r == "*": @@ -84,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/query.go b/internal/ir/query.go index 2f2b28b..5ff5d3d 100644 --- a/internal/ir/query.go +++ b/internal/ir/query.go @@ -35,7 +35,7 @@ const ( // 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 { +func (Project) AllFilterOperators() []FilterOp { return []FilterOp{OpEq, OpNe, OpGt, OpGte, OpLt, OpLte, OpIn, OpContains, OpStartsWith, OpEndsWith} } @@ -73,7 +73,7 @@ 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 { switch { case f.IsText(): return []FilterOp{OpEq, OpNe, OpContains, OpStartsWith, OpEndsWith, OpIn} @@ -91,8 +91,8 @@ func (f IRField) FilterOperators() []FilterOp { // 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 }) } @@ -100,8 +100,8 @@ 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 { +func (e Entity) SortableFields() []Field { + return e.queryFields(func(f Field) bool { return f.isFilterableScalar() && !f.IsEnum() }) } @@ -109,12 +109,12 @@ func (e IREntity) SortableFields() []IRField { // 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 +126,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,7 +148,7 @@ 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 { +func (e Entity) FilterablePaths() []FilterPathSpec { var out []FilterPathSpec for _, f := range e.FilterableFields() { @@ -190,8 +190,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 +200,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 +214,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 33b5c99..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,7 +33,7 @@ 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}, }, } @@ -43,7 +43,7 @@ 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) @@ -81,7 +81,7 @@ func TestFilterOperators(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - f := IRField{DatabaseType: c.dbType} + f := Field{DatabaseType: c.dbType} got := f.FilterOperators() if len(got) == 0 && len(c.want) == 0 { return @@ -95,7 +95,7 @@ func TestFilterOperators(t *testing.T) { func TestAllFilterOperators(t *testing.T) { t.Parallel() - got := (IRProject{}).AllFilterOperators() + 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) @@ -170,7 +170,7 @@ func TestCursorField(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - e := IREntity{Fields: []IRField{{Name: "id", DatabaseType: c.pkType, IsPrimary: true}}} + 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) @@ -179,7 +179,7 @@ func TestCursorField(t *testing.T) { } // 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/toposort.go b/internal/ir/toposort.go index 7edf1e8..ee996fe 100644 --- a/internal/ir/toposort.go +++ b/internal/ir/toposort.go @@ -4,10 +4,10 @@ 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 @@ -75,12 +75,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] } diff --git a/internal/ir/typekind.go b/internal/ir/typekind.go index b120e47..fab2e16 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) } @@ -23,43 +23,43 @@ func (f IRField) EnumTypeName() string { // EnumTypeName/ArrayElementType). // IsUUID reports whether the field holds a UUID. -func (f IRField) IsUUID() bool { return f.DatabaseType == "uuid" } +func (f Field) IsUUID() bool { return f.DatabaseType == "uuid" } // IsUuid reports whether the field holds a UUID. // // Deprecated: use IsUUID. Kept as an alias for bridges using the old casing. //nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates -func (f IRField) IsUuid() bool { return f.IsUUID() } +func (f Field) IsUuid() bool { return f.IsUUID() } // IsText reports whether the field holds a string/text value. -func (f IRField) IsText() bool { +func (f Field) IsText() bool { return f.DatabaseType == "string" || f.DatabaseType == "text" } // IsInteger reports whether the field holds an integral number (int or bigint). -func (f IRField) IsInteger() bool { +func (f Field) IsInteger() bool { return f.DatabaseType == "int" || f.DatabaseType == "bigint" } // IsFloat reports whether the field holds a floating-point number (float or decimal). -func (f IRField) IsFloat() bool { +func (f Field) IsFloat() bool { return f.DatabaseType == "float" || f.DatabaseType == "decimal" } // 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 == "boolean" } // 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 == "date" } // 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 == "datetime" } // IsJSON reports whether the field holds a JSON document (json or jsonb). -func (f IRField) IsJSON() bool { +func (f Field) IsJSON() bool { return f.DatabaseType == "json" || f.DatabaseType == "jsonb" } @@ -67,40 +67,40 @@ func (f IRField) IsJSON() bool { // // Deprecated: use IsJSON. //nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates -func (f IRField) IsJson() bool { return f.IsJSON() } +func (f Field) IsJson() bool { return f.IsJSON() } // 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 == "jsonb" } // IsJsonB reports whether the field holds a jsonb document. // // Deprecated: use IsJSONB. //nolint:revive // deprecated bridge alias; renaming breaks existing bridge templates -func (f IRField) IsJsonB() bool { return f.IsJSONB() } +func (f Field) IsJsonB() bool { return f.IsJSONB() } // 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 == "string" } // 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 == "text" } // 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 == "bigint" } // 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 == "decimal" } // 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 3efb1d1..a6807ac 100644 --- a/internal/ir/typekind_test.go +++ b/internal/ir/typekind_test.go @@ -31,7 +31,7 @@ func TestIRFieldTypePredicates(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - f := IRField{DatabaseType: c.dbType} + f := Field{DatabaseType: c.dbType} if got := f.IsUuid(); got != c.isUUID { t.Errorf("%q IsUuid() = %v, want %v", c.dbType, got, c.isUUID) } @@ -89,7 +89,7 @@ func TestIRFieldSpecificTypePredicates(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - f := IRField{DatabaseType: c.dbType} + f := Field{DatabaseType: c.dbType} if got := f.IsString(); got != c.isString { t.Errorf("%q IsString() = %v, want %v", c.dbType, got, c.isString) } @@ -110,19 +110,19 @@ 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 { t.Run(c.name, func(t *testing.T) { @@ -136,27 +136,27 @@ func TestIRFieldIsPatchable(t *testing.T) { func TestIRFieldIsTextOnly(t *testing.T) { t.Parallel() - if !(IRField{DatabaseType: "text"}).IsTextOnly() { + 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) { t.Parallel() - e := IREntity{Name: "IPv4Rule", NamePlural: "IPv4Rules"} + 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) } } @@ -195,7 +195,7 @@ func TestKindOf(t *testing.T) { func TestIRPermissionsIsPublic(t *testing.T) { t.Parallel() - p := &IRPermissions{Read: []string{"*"}, Create: []string{"Admin"}, Update: nil, Delete: []string{}} + p := &Permissions{Read: []string{"*"}, Create: []string{"Admin"}, Update: nil, Delete: []string{}} if !p.IsPublic("read") { t.Error("IsPublic(read) = false, want true") } @@ -208,7 +208,7 @@ 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") } @@ -225,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..0b83c5e 100644 --- a/internal/ir/validations.go +++ b/internal/ir/validations.go @@ -2,13 +2,13 @@ package ir import "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 @@ -68,9 +68,9 @@ func validationRuleMeta(kind, value string, exclusive bool) (code, message strin } // 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} } // ValidationRules returns the field's validations as a normalized, ordered list @@ -85,8 +85,8 @@ 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) +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 diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index a9b152f..6e813bc 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -59,7 +59,7 @@ templates: if err != nil { t.Fatalf("New() error = %v", err) } - if _, _, err := r.Render(&ir.IRProject{Name: "P"}, out); err == nil { + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { t.Fatal("Render accepted a symlink at the final target component") } @@ -101,7 +101,7 @@ templates: if err != nil { t.Fatalf("New() error = %v", err) } - if _, _, err := r.Render(&ir.IRProject{Name: "P"}, out); err == nil { + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { t.Fatal("Render succeeded despite an execute error") } @@ -156,7 +156,7 @@ templates: if err != nil { t.Fatalf("New() error = %v", err) } - if _, _, err := r.Render(&ir.IRProject{Name: "P"}, out); err == nil { + if _, _, err := r.Render(&ir.Project{Name: "P"}, out); err == nil { t.Fatal("Render succeeded despite a parse error in the second template") } diff --git a/internal/renderer/models.go b/internal/renderer/models.go index 280eb0b..f11f9f5 100644 --- a/internal/renderer/models.go +++ b/internal/renderer/models.go @@ -68,8 +68,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 +119,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 +127,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 +135,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 +143,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 } @@ -227,7 +227,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 +235,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 +243,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 +253,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 +261,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 +269,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,8 +277,8 @@ 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 } @@ -327,7 +327,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 +335,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/render.go b/internal/renderer/render.go index 96bdc5f..3484f9c 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -107,7 +107,7 @@ func rollbackWrites(staged, committed []stagedWrite) { // 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.IRProject, outputDir string) ([]string, []RenderedFile, error) { +func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []RenderedFile, error) { if project == nil { return nil, nil, errors.New("IR project is nil") } @@ -327,7 +327,7 @@ func (r *Renderer) Render(project *ir.IRProject, outputDir string) ([]string, [] return written, 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" { @@ -402,7 +402,7 @@ 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 { +func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { framework := "" if project != nil { framework = project.Platform @@ -472,7 +472,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_test.go b/internal/renderer/render_test.go index f725355..be6befd 100644 --- a/internal/renderer/render_test.go +++ b/internal/renderer/render_test.go @@ -42,9 +42,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"}}, } written, _, err := r.Render(project, filepath.Join(tmpDir, "out")) if err != nil { @@ -106,7 +106,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) @@ -199,9 +199,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") @@ -259,7 +259,7 @@ func TestRenderContext_HasFeature(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() ctx := RenderContext{ - Entity: &ir.IREntity{Features: tt.features}, + Entity: &ir.Entity{Features: tt.features}, } if tt.name == "nil entity" { ctx.Entity = nil @@ -274,7 +274,7 @@ func TestRenderContext_HasFeature(t *testing.T) { 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") @@ -289,7 +289,7 @@ 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") @@ -299,7 +299,7 @@ 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") @@ -309,7 +309,7 @@ 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") @@ -323,9 +323,9 @@ func TestRenderContext_Permissions(t *testing.T) { 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") @@ -340,8 +340,8 @@ func TestRenderContext_PrimaryKey(t *testing.T) { } ctx2 := RenderContext{ - Entity: &ir.IREntity{ - Fields: []ir.IRField{ + Entity: &ir.Entity{ + Fields: []ir.Field{ {Name: "id", IsPrimary: true}, {Name: "name"}, }, @@ -388,7 +388,7 @@ templates: if err != nil { t.Fatalf("New() error = %v", err) } - written, _, err := r.Render(&ir.IRProject{Name: "P"}, filepath.Join(tmp, "out")) + written, _, err := r.Render(&ir.Project{Name: "P"}, filepath.Join(tmp, "out")) if err != nil { t.Fatalf("Render() error = %v", err) } @@ -432,7 +432,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") @@ -484,7 +484,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) @@ -536,7 +536,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) @@ -563,21 +563,21 @@ 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) { t.Parallel() - e := &ir.IREntity{Name: "User", Fields: []ir.IRField{ + 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/seed/seed.go b/internal/seed/seed.go index db06c7b..124b064 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -30,7 +30,7 @@ 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{} } @@ -88,7 +88,7 @@ func Generate(project *ir.IRProject, opts Options) *ir.SeedDataset { // 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{} } @@ -124,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] @@ -135,7 +135,7 @@ func primaryKey(entity *ir.IREntity) *ir.IRField { // valueFor produces one field value for generated mock seed, honoring type, // validations, defaults and relations. -func valueFor(field ir.IRField, project *ir.IRProject, generated map[string][]any, counter *int, record int) any { +func valueFor(field ir.Field, project *ir.Project, generated map[string][]any, counter *int, record int) any { // Default value wins when the model declares one (and it's not a function). if field.DefaultValue != "" && !field.DefaultIsFunc { return coerceValue(field.DefaultValue, field.DatabaseType) @@ -154,7 +154,7 @@ func valueFor(field ir.IRField, project *ir.IRProject, generated map[string][]an // 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(field ir.IRField, generated map[string][]any, record int) any { +func relationValue(field ir.Field, generated map[string][]any, record int) any { if field.IsMany { return nil } @@ -169,7 +169,7 @@ func relationValue(field ir.IRField, generated map[string][]any, record int) any } // scalarValue produces a scalar value from the field's type and constraints. -func scalarValue(field ir.IRField, project *ir.IRProject, counter *int, record int) any { +func scalarValue(field ir.Field, project *ir.Project, counter *int, record int) any { dbType := field.DatabaseType if field.IsArray() { @@ -206,8 +206,8 @@ 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) any { - inner := ir.IRField{Name: field.Name, DatabaseType: dbType} +func innerValue(dbType string, field ir.Field, project *ir.Project, counter *int, record int) any { + inner := ir.Field{Name: field.Name, DatabaseType: dbType} if specmeta.IsPrimitive(strings.ToLower(dbType)) { return scalarValue(inner, project, counter, record) } @@ -219,7 +219,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() { @@ -264,7 +264,7 @@ func stringValue(field ir.IRField, record int) string { // 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 { +func intValue(field ir.Field, record int) int64 { v := int64(record + 1) for _, r := range field.ValidationRules() { n, err := strconv.ParseInt(r.Value, 10, 64) @@ -287,7 +287,7 @@ func intValue(field ir.IRField, record int) int64 { // 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 { +func floatValue(field ir.Field, record int) float64 { v := float64(record+1) + 0.5 for _, r := range field.ValidationRules() { n, err := strconv.ParseFloat(r.Value, 64) diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index fe4912a..38ae1d5 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -9,13 +9,13 @@ import ( func TestGenerateBasicTypes(t *testing.T) { t.Parallel() - project := &ir.IRProject{ + 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"}, @@ -67,17 +67,17 @@ func TestGenerateBasicTypes(t *testing.T) { func TestGenerateReferencesParentPK(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}, @@ -109,11 +109,11 @@ func TestGenerateReferencesParentPK(t *testing.T) { func TestNormalizeCoercesTypes(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}, @@ -159,10 +159,10 @@ func TestNormalizeCoercesTypes(t *testing.T) { func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { t.Parallel() - 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]any{{"id": "x"}}}, + 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) @@ -173,11 +173,11 @@ func TestNormalizeSkipsEntitiesWithoutSeed(t *testing.T) { func TestNormalizeIncludesRelationFlags(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}, }, @@ -197,17 +197,17 @@ func TestNormalizeIncludesRelationFlags(t *testing.T) { func TestGenerateHonorsNumericBounds(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}}}, }, }, }, @@ -244,16 +244,16 @@ func TestGenerateHonorsNumericBounds(t *testing.T) { func TestGenerateHonorsStringValidations(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}}}, }, }, }, @@ -280,12 +280,12 @@ func TestGenerateHonorsStringValidations(t *testing.T) { func TestNormalizeCoerceEdgeCases(t *testing.T) { t.Parallel() - project := &ir.IRProject{ + 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: "big", DatabaseType: "bigint"}, @@ -359,13 +359,13 @@ func TestGenerateClampsNonPositiveMaxLength(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Item", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, - {Name: "name", DatabaseType: "string", Validations: []ir.IRValidation{{Name: "max", Value: tt.max}}}, + {Name: "name", DatabaseType: "string", Validations: []ir.Validation{{Name: "max", Value: tt.max}}}, }, }, }, @@ -382,15 +382,15 @@ func TestGenerateClampsNonPositiveMaxLength(t *testing.T) { func TestGenerateRotatesRelationPKs(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + project := &ir.Project{ + Entities: []ir.Entity{ { Name: "Category", - Fields: []ir.IRField{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, + Fields: []ir.Field{{Name: "id", DatabaseType: "uuid", IsPrimary: true}}, }, { Name: "Product", - Fields: []ir.IRField{ + Fields: []ir.Field{ {Name: "id", DatabaseType: "uuid", IsPrimary: true}, {Name: "categoryId", DatabaseType: "uuid", IsRelation: true, IsUnique: true, RelationTarget: "Category"}, }, @@ -419,17 +419,17 @@ func TestRelationValueRotatesParentPKs(t *testing.T) { t.Parallel() tests := []struct { name string - field ir.IRField + field ir.Field pks []any record int want any }{ - {name: "first parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 0, want: "a"}, - {name: "second parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 1, want: "b"}, - {name: "wraps around", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a", "b", "c"}, record: 3, want: "a"}, - {name: "single parent", field: ir.IRField{RelationTarget: "Category"}, pks: []any{"a"}, record: 5, want: "a"}, - {name: "no parents", field: ir.IRField{RelationTarget: "Category"}, pks: nil, record: 2}, - {name: "many relation", field: ir.IRField{RelationTarget: "Category", IsMany: true}, pks: []any{"a", "b"}, record: 0}, + {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 { @@ -444,11 +444,11 @@ func TestRelationValueRotatesParentPKs(t *testing.T) { func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { t.Parallel() - project := &ir.IRProject{ - Entities: []ir.IREntity{ + 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"}, diff --git a/internal/snapshot/hardening_test.go b/internal/snapshot/hardening_test.go index 718d1ad..eb70ed1 100644 --- a/internal/snapshot/hardening_test.go +++ b/internal/snapshot/hardening_test.go @@ -14,7 +14,7 @@ import ( func TestSaveReplacesSnapshotWithoutTempLeftovers(t *testing.T) { t.Parallel() dir := t.TempDir() - path := SnapshotPath(dir) + path := Path(dir) if err := Save(path, New("demo", testProject("Product"), nil)); err != nil { t.Fatalf("initial Save() error = %v", err) diff --git a/internal/snapshot/migration.go b/internal/snapshot/migration.go index 77ab297..d4144c7 100644 --- a/internal/snapshot/migration.go +++ b/internal/snapshot/migration.go @@ -25,15 +25,15 @@ func tableName(entityName string) string { } // 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 + newByOldName := make(map[string]*ir.Entity, len(project.Entities)) // old_name -> new entity + newByName := make(map[string]*ir.Entity, len(project.Entities)) // name -> new entity for i := range project.Entities { e := &project.Entities[i] newByName[e.Name] = e @@ -134,9 +134,9 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.IRProject) *ir.MigrationPla // diffColumns appends AddColumn / DropColumn / RenameColumn / AlterColumn ops // for one surviving entity. -func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.IREntity) { +func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.Entity) { oldFields := oldState.Fields // field name -> IR database type - newFieldByName := make(map[string]*ir.IRField, len(e.Fields)) + newFieldByName := make(map[string]*ir.Field, len(e.Fields)) for i := range e.Fields { f := &e.Fields[i] newFieldByName[f.Name] = f @@ -257,7 +257,7 @@ 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 { +func renameTarget(e *ir.Entity, oldField string) string { for i := range e.Fields { if e.Fields[i].OldName == oldField { return e.Fields[i].Name diff --git a/internal/snapshot/migration_test.go b/internal/snapshot/migration_test.go index 0d36b67..f3a632b 100644 --- a/internal/snapshot/migration_test.go +++ b/internal/snapshot/migration_test.go @@ -15,17 +15,17 @@ 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}}, }, }, } @@ -58,13 +58,13 @@ func TestComputeMigrationPlanRenameTable(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}}, }, }, } @@ -94,12 +94,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", @@ -154,7 +154,7 @@ func TestComputeMigrationPlanNilInputs(t *testing.T) { 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") } } @@ -167,12 +167,12 @@ func TestComputeMigrationPlanRenameWithTypeChange(t *testing.T) { "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/snapshot.go b/internal/snapshot/snapshot.go index 8117fda..f4cc6a8 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -57,8 +57,8 @@ type Snapshot struct { 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) } @@ -98,7 +98,7 @@ func Save(path string, snap *Snapshot) error { } // 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)) @@ -205,13 +205,13 @@ func (d *Diff) HasSchemaChanges() bool { // 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) *Diff { diff := &Diff{} if old == nil || project == nil { return diff } - newEntities := make(map[string]ir.IREntity, len(project.Entities)) + newEntities := make(map[string]ir.Entity, len(project.Entities)) renamedByOld := make(map[string]string) // old name -> new name for _, e := range project.Entities { newEntities[e.Name] = e diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index bdea039..cf5a71a 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -14,7 +14,7 @@ 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}, @@ -107,13 +107,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"}, }, @@ -248,12 +248,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", @@ -306,12 +306,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", @@ -348,7 +348,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 { @@ -446,13 +446,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"}, }, @@ -496,13 +496,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}}, }, }, } @@ -534,12 +534,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", @@ -602,13 +602,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", @@ -623,7 +623,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"}, }, @@ -699,24 +699,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}}, }, }, } @@ -767,10 +767,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}}}, }, } } diff --git a/internal/specmeta/specmeta_json.go b/internal/specmeta/specmeta_json.go index 97f7f8d..dbf690f 100644 --- a/internal/specmeta/specmeta_json.go +++ b/internal/specmeta/specmeta_json.go @@ -1,13 +1,13 @@ package specmeta -// SpecmetaJSON returns every specmeta constant as a JSON-ready map. This is the +// 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 { return map[string]any{ "primitiveFieldTypes": PrimitiveFieldTypes, "stringFieldTypes": StringFieldTypes, 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: From bbb446c66900f551fa8648638961bb1f291f15aa Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:18:05 +0300 Subject: [PATCH 14/83] Refactor: share path containment and JSON write helpers --- cmd/domaincraft/commands.go | 11 +----- cmd/schema-gen/main.go | 11 +----- internal/bridge/embed.go | 35 +---------------- internal/fsutil/fsutil.go | 69 ++++++++++++++++++++++++++++++++++ internal/renderer/render.go | 36 +++++------------- internal/snapshot/migration.go | 6 +-- internal/snapshot/paths.go | 18 +++------ 7 files changed, 91 insertions(+), 95 deletions(-) diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index b52bad3..a1dd408 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -16,7 +16,6 @@ package main import ( "cmp" "context" - "encoding/json" "errors" "fmt" "io" @@ -752,15 +751,7 @@ func writeDomainLock(domainPath string, dirs []string) error { } 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) + return fsutil.WriteJSON(filepath.Join(filepath.Dir(domainPath), "domaincraft.lock.json"), domainLock{Bridges: out}) } // bridgeMetadata reads the identifying fields out of a bridge directory's diff --git a/cmd/schema-gen/main.go b/cmd/schema-gen/main.go index 1249061..625800a 100644 --- a/cmd/schema-gen/main.go +++ b/cmd/schema-gen/main.go @@ -2,12 +2,12 @@ package main import ( - "encoding/json" "flag" "fmt" "os" "path/filepath" + "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/specmeta" ) @@ -15,14 +15,7 @@ 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) - os.Exit(1) - } - - if err := os.WriteFile(*outputPath, append(data, '\n'), 0o600); err != nil { + if err := fsutil.WriteJSONWithNewline(*outputPath, buildSchema(), true); err != nil { fmt.Fprintln(os.Stderr, "write schema:", err) os.Exit(1) } diff --git a/internal/bridge/embed.go b/internal/bridge/embed.go index 3cd8763..f4efddd 100644 --- a/internal/bridge/embed.go +++ b/internal/bridge/embed.go @@ -1,7 +1,6 @@ package bridge import ( - "errors" "fmt" "io/fs" "os" @@ -9,6 +8,7 @@ import ( "strings" domaincraft "github.com/DomainCraft/DomainCraft" + "github.com/DomainCraft/DomainCraft/internal/fsutil" ) // TryMaterializeEmbedded copies the embedded copy of an official bridge into its @@ -95,36 +95,5 @@ func refuseSymlinks(base, target string) error { if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return fmt.Errorf("target %q escapes cache directory", target) } - if err := lstatNoSymlink(baseAbs); err != nil { - return err - } - if rel == "." { - return nil - } - cur := baseAbs - for part := range strings.SplitSeq(rel, string(filepath.Separator)) { - if part == "" || part == "." { - continue - } - cur = filepath.Join(cur, part) - if err := lstatNoSymlink(cur); err != nil { - return err - } - } - return nil -} - -// lstatNoSymlink fails on an existing symlink and ignores missing paths. -func lstatNoSymlink(path string) error { - info, err := os.Lstat(path) - if errors.Is(err, os.ErrNotExist) { - return nil - } - 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) - } - return nil + return fsutil.RefuseSymlinks(baseAbs, targetAbs) } diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index 5115341..33473f8 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -5,10 +5,69 @@ package fsutil import ( "encoding/json" + "errors" + "fmt" "os" "path/filepath" + "strings" ) +// 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) + if absTarget != absBase && !strings.HasPrefix(absTarget, absBase+string(filepath.Separator)) { + return "", "", fmt.Errorf("path %q escapes %q", rel, base) + } + relative, err := filepath.Rel(absBase, absTarget) + if err != nil { + return "", "", fmt.Errorf("resolve path %q: %w", rel, err) + } + return absTarget, relative, 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 { + 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) + } + for _, path := range paths { + 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) + } + } + return nil +} + // 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. @@ -37,10 +96,20 @@ func AtomicWrite(path string, data []byte) error { // 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 } + if newline { + data = append(data, '\n') + } return AtomicWrite(path, data) } diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 3484f9c..39dbf8c 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -19,10 +19,10 @@ import ( // safeBridgeSource resolves a template or helper path declared by bridge.yaml // and rejects paths that escape the bridge directory. func safeBridgeSource(dir, rel string) (string, error) { - if !filepath.IsLocal(rel) { - return "", fmt.Errorf("unsafe bridge source path %q", rel) + path, _, err := fsutil.LocalPathWithin(dir, rel) + if err != nil { + return "", fmt.Errorf("unsafe bridge source path %q: %w", rel, err) } - path := filepath.Join(dir, rel) realDir, err := filepath.EvalSymlinks(dir) if err != nil { return "", fmt.Errorf("resolve bridge dir: %w", err) @@ -41,34 +41,16 @@ func safeBridgeSource(dir, rel string) (string, error) { // 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) { - absOutput, err := filepath.Abs(outputDir) + absTarget, _, err := fsutil.LocalPathWithin(outputDir, renderedTarget) if err != nil { - return "", fmt.Errorf("resolve output directory: %w", err) - } - absTarget := filepath.Join(absOutput, filepath.FromSlash(renderedTarget)) - if absTarget != absOutput && !strings.HasPrefix(absTarget, absOutput+string(filepath.Separator)) { - return "", fmt.Errorf("template target path escapes output directory: %s", renderedTarget) + return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) } - rel, err := filepath.Rel(absOutput, absTarget) + absOutput, err := filepath.Abs(outputDir) if err != nil { - return "", fmt.Errorf("resolve target path: %w", err) + return "", fmt.Errorf("resolve output directory: %w", err) } - cur := absOutput - for comp := range strings.SplitSeq(rel, string(filepath.Separator)) { - if comp == "" || comp == "." { - continue - } - cur = filepath.Join(cur, comp) - info, err := os.Lstat(cur) - if errors.Is(err, os.ErrNotExist) { - continue - } - if err != nil { - return "", fmt.Errorf("inspect output path %q: %w", cur, err) - } - if info.Mode()&os.ModeSymlink != 0 { - return "", fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget) - } + if err := fsutil.RefuseSymlinks(absOutput, absTarget); err != nil { + return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) } return absTarget, nil } diff --git a/internal/snapshot/migration.go b/internal/snapshot/migration.go index d4144c7..8df1f8d 100644 --- a/internal/snapshot/migration.go +++ b/internal/snapshot/migration.go @@ -60,7 +60,7 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.Project) *ir.MigrationPlan 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{ @@ -90,7 +90,7 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.Project) *ir.MigrationPlan Kind: ir.OpRenameTable, Entity: e.Name, OldName: oldName, - Table: tableName(e.Name), + Table: e.TableName(), OldTable: tableName(oldName), }) } @@ -142,7 +142,7 @@ func diffColumns(plan *ir.MigrationPlan, oldState EntityState, e *ir.Entity) { newFieldByName[f.Name] = f } - table := tableName(e.Name) + table := e.TableName() // RenameColumn: new field declares old_name pointing at a field that existed. renamedFields := make([]string, 0) diff --git a/internal/snapshot/paths.go b/internal/snapshot/paths.go index 27bb065..6d4cc94 100644 --- a/internal/snapshot/paths.go +++ b/internal/snapshot/paths.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/DomainCraft/DomainCraft/internal/fsutil" ) // safeRelPath resolves a snapshot file path against outputDir and rejects @@ -18,28 +20,18 @@ import ( // inside the resolved output root. The returned path keeps the lexical form so // callers see paths under outputDir even when that directory is itself a link. func safeRelPath(outputDir, relPath string) (string, error) { - local := filepath.FromSlash(relPath) - if !filepath.IsLocal(local) { - return "", fmt.Errorf("unsafe snapshot path %q: must be local to output dir", relPath) + abs, rel, 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) } - abs := filepath.Join(absOutput, local) - if abs != absOutput && !strings.HasPrefix(abs, absOutput+string(filepath.Separator)) { - return "", fmt.Errorf("unsafe snapshot path %q: outside output dir", relPath) - } - realOutput, err := filepath.EvalSymlinks(absOutput) if err != nil { return "", fmt.Errorf("resolve output dir %q: %w", outputDir, err) } - rel, err := filepath.Rel(absOutput, abs) - if err != nil { - return "", fmt.Errorf("resolve snapshot path %q: %w", relPath, err) - } cur, realCur := absOutput, realOutput for comp := range strings.SplitSeq(rel, string(filepath.Separator)) { if comp == "" || comp == "." { From a4ea10269943c68da77e6fe797e4177331df1e8c Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:05 +0300 Subject: [PATCH 15/83] Refactor: consolidate spec rules and field parsing --- internal/ir/build_entities_test.go | 136 ++++++----- internal/ir/permissions.go | 4 +- internal/ir/permissions_test.go | 48 ++++ internal/ir/typekind.go | 12 +- internal/lexer/lexer.go | 34 +-- internal/lexer/lexer_dry_test.go | 92 ++++++++ internal/parser/parse_field_test.go | 104 +++++++++ internal/parser/parser.go | 11 +- internal/snapshot/rewrite.go | 3 +- internal/specmeta/specmeta.go | 71 +++++- internal/specmeta/specmeta_test.go | 134 +++++++++++ internal/testutil/testutil.go | 20 +- internal/testutil/testutil_test.go | 35 +++ internal/validator/validator.go | 36 ++- internal/validator/validator_test.go | 322 +++++++++++++-------------- 15 files changed, 757 insertions(+), 305 deletions(-) create mode 100644 internal/ir/permissions_test.go create mode 100644 internal/lexer/lexer_dry_test.go create mode 100644 internal/parser/parse_field_test.go create mode 100644 internal/testutil/testutil_test.go diff --git a/internal/ir/build_entities_test.go b/internal/ir/build_entities_test.go index 7f2ba7f..bf3494e 100644 --- a/internal/ir/build_entities_test.go +++ b/internal/ir/build_entities_test.go @@ -21,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": { @@ -30,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]"), }, }, }, @@ -79,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)"), }, }, }, @@ -123,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)"), }, }, }, @@ -168,10 +168,6 @@ 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. @@ -187,7 +183,7 @@ func relationPKCycleSchema(t *testing.T) *parser.ParsedSchema { NamePlural: "Alphas", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "relation(Beta) [primary]"), + "id": testutil.MustParsedField(t, "id", "relation(Beta) [primary]"), }, }, "Beta": { @@ -195,7 +191,7 @@ func relationPKCycleSchema(t *testing.T) *parser.ParsedSchema { NamePlural: "Betas", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "relation(Alpha) [primary]"), + "id": testutil.MustParsedField(t, "id", "relation(Alpha) [primary]"), }, }, }, @@ -228,7 +224,7 @@ func TestResolveDatabaseTypeDetectsCycles(t *testing.T) { name: "self relation primary key", schema: relationPKCycleSchema(t), field: func(_ *testing.T, s *parser.ParsedSchema) *parser.ParsedField { - f := mustParsedField(t, "id", "relation(Alpha) [primary]") + f := testutil.MustParsedField(t, "id", "relation(Alpha) [primary]") s.Entities["Alpha"].Fields["id"] = f return f }, @@ -249,13 +245,13 @@ func TestResolveDatabaseTypeDetectsCycles(t *testing.T) { "Order": { FieldOrder: []string{"userId"}, Fields: map[string]*parser.ParsedField{ - "userId": mustParsedField(t, "userId", "relation(User)"), + "userId": testutil.MustParsedField(t, "userId", "relation(User)"), }, }, "User": { FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -347,7 +343,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]"), }, }, }, @@ -376,7 +372,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]"), }, }, }, @@ -423,8 +419,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": { @@ -432,8 +428,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)"), }, }, }, @@ -462,8 +458,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"), }, }, }, @@ -503,8 +499,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]"), }, }, }, @@ -544,32 +540,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": { @@ -577,25 +573,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": { @@ -603,8 +599,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)"), }, }, }, @@ -699,16 +695,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]"), }, }, }, @@ -781,8 +777,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": { @@ -790,8 +786,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]"), }, }, }, @@ -879,8 +875,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": { @@ -888,8 +884,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]"), }, }, }, @@ -938,9 +934,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": { @@ -948,9 +944,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]"), }, }, }, @@ -1018,7 +1014,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]")}, }, }, } diff --git a/internal/ir/permissions.go b/internal/ir/permissions.go index ee8a850..1854c20 100644 --- a/internal/ir/permissions.go +++ b/internal/ir/permissions.go @@ -71,9 +71,9 @@ func (p *Permissions) Plan(operation string) *PermissionPlan { 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) 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/typekind.go b/internal/ir/typekind.go index fab2e16..9749f3e 100644 --- a/internal/ir/typekind.go +++ b/internal/ir/typekind.go @@ -32,19 +32,13 @@ func (f Field) IsUUID() bool { return f.DatabaseType == "uuid" } func (f Field) IsUuid() bool { return f.IsUUID() } // IsText reports whether the field holds a string/text value. -func (f Field) 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 Field) 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 Field) 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 Field) IsNumeric() bool { return specmeta.IsNumeric(f.DatabaseType) } diff --git a/internal/lexer/lexer.go b/internal/lexer/lexer.go index c6b903e..b16de3d 100644 --- a/internal/lexer/lexer.go +++ b/internal/lexer/lexer.go @@ -103,12 +103,11 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { return nil } - // Check for array(Type) - if strings.HasPrefix(typeStr, "array(") { + // Check for array(Type). The prefix/suffix handling lives in specmeta so + // every consumer extracts the element type the same way. + if specmeta.IsArrayType(typeStr) { fd.Type = "array" - innerType := strings.TrimPrefix(typeStr, "array(") - innerType = strings.TrimSuffix(innerType, ")") - fd.TargetType = strings.TrimSpace(innerType) + fd.TargetType = strings.TrimSpace(specmeta.ParseArrayInner(typeStr)) if fd.TargetType == "" { return fmt.Errorf("array type requires an element type") } @@ -129,7 +128,7 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { // Built-in types if !specmeta.IsFieldType(typeStr) { - return fmt.Errorf("unknown type %q; valid types: string, int, uuid, relation, array, enum, json, text", typeStr) + return fmt.Errorf("unknown type %q; valid types: %s", typeStr, strings.Join(specmeta.FieldTypes, ", ")) } fd.Type = typeStr @@ -168,7 +167,7 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { } case "on_delete": if !specmeta.IsOnDeleteValue(value) { - return fmt.Errorf("unknown on_delete value: %s. valid: cascade, set_null, restrict, no_action", value) + return fmt.Errorf("unknown on_delete value: %s. valid: %s", value, strings.Join(specmeta.OnDeleteValues, ", ")) } fd.OnDelete = value case "old_name": @@ -295,32 +294,13 @@ func (fd *FieldDefinition) Validate() error { } // 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 func ParseFieldString(fieldString string) (*FieldDefinition, error) { lexer := New(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/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 f26cac4..f5f465e 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -197,8 +197,17 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) return entity, nil } -// parseField parses a single field using the lexer +// parseField is kept for callers inside the parser; the shared entry point is +// ParseField so the testutil helper cannot drift from the parser's normalization. func (p *Parser) parseField(name string, fieldDef string) (*ParsedField, error) { + return ParseField(name, fieldDef) +} + +// 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 diff --git a/internal/snapshot/rewrite.go b/internal/snapshot/rewrite.go index 40418b3..a39da73 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -17,6 +17,7 @@ import ( "unicode" "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/textutil" ) @@ -119,7 +120,7 @@ func tokenOK(rs []rune, idx, length int) bool { } func isIdentRune(r rune) bool { - return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' + return specmeta.IsIdentifierRune(r) } // entityCasings builds the casing-variant table for an entity rename. diff --git a/internal/specmeta/specmeta.go b/internal/specmeta/specmeta.go index 074bd3d..e488268 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -1,7 +1,10 @@ // Package specmeta is the single source of truth for specification constants. package specmeta -import "strings" +import ( + "strings" + "unicode" +) // FeatureFieldDef describes a field auto-injected by a feature macro. type FeatureFieldDef struct { @@ -72,8 +75,14 @@ var PrimitiveFieldTypes = []string{ "boolean", "date", "datetime", "uuid", "json", "jsonb", } +// IntegralFieldTypes lists the integral scalar types. +var IntegralFieldTypes = []string{"int", "bigint"} + +// FloatFieldTypes lists the floating-point scalar types. +var FloatFieldTypes = []string{"float", "decimal"} + // NumericFieldTypes lists the numeric scalar types. -var NumericFieldTypes = []string{"int", "bigint", "float", "decimal"} +var NumericFieldTypes = append(append([]string{}, IntegralFieldTypes...), FloatFieldTypes...) // StringFieldTypes lists the string scalar types. var StringFieldTypes = []string{"string", "text"} @@ -114,9 +123,27 @@ var FuncDefaults = map[string][]string{ // DefaultFieldType is the fallback type for unresolvable fields. const DefaultFieldType = "string" +// 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. +const ContractVersion = 1 + +// 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 + integralSet map[string]bool + floatSet map[string]bool stringSet map[string]bool booleanSet map[string]bool fieldTypeSet map[string]bool @@ -143,6 +170,8 @@ var ( func init() { primitiveSet = SliceToSet(PrimitiveFieldTypes) numericSet = SliceToSet(NumericFieldTypes) + integralSet = SliceToSet(IntegralFieldTypes) + floatSet = SliceToSet(FloatFieldTypes) stringSet = SliceToSet(StringFieldTypes) booleanSet = SliceToSet(BooleanFieldTypes) fieldTypeSet = SliceToSet(FieldTypes) @@ -172,6 +201,12 @@ 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] } @@ -307,3 +342,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_test.go b/internal/specmeta/specmeta_test.go index cad4b59..2c663f2 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -484,3 +484,137 @@ func TestBuildEntityFieldsEmptyOrder(t *testing.T) { 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]) + } + } +} + +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: "newer version is preserved for the caller to reject", declared: 2, want: 2}, + } + 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 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) + } + }) + } +} 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..639bac8 --- /dev/null +++ b/internal/testutil/testutil_test.go @@ -0,0 +1,35 @@ +package testutil + +import ( + "testing" + + "github.com/DomainCraft/DomainCraft/internal/parser" +) + +func TestMustParsedFieldMatchesParserNormalization(t *testing.T) { + t.Parallel() + cases := []struct { + name string + input string + }{ + {name: "primary implies required", input: "uuid [primary]"}, + {name: "relation gets relation type", input: "relation(User) [many]"}, + {name: "quoted old name survives", input: `string [required, old_name:"previousTitle"]`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + got := MustParsedField(t, "field", c.input) + want, err := parser.ParseField("field", c.input) + if err != nil { + t.Fatalf("parser.ParseField(%q) error = %v", c.input, err) + } + if got.IsRequired != want.IsRequired || + got.RelationType != want.RelationType || + got.DatabaseColumnName != want.DatabaseColumnName || + got.OldName != want.OldName { + t.Errorf("MustParsedField = %#v, want parser.ParseField result %#v", got, want) + } + }) + } +} diff --git a/internal/validator/validator.go b/internal/validator/validator.go index e426421..297184e 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -62,8 +62,6 @@ 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} @@ -372,7 +370,7 @@ func (v *Validator) validateAuth() []ValidationError { // Roles must be valid identifiers for _, role := range auth.Roles { - if !validIdentifier.MatchString(role) { + if !specmeta.IsValidIdentifier(role) { errs = append(errs, invalidf("", "", "auth.roles: %q is not a valid identifier", role)) } @@ -446,7 +444,7 @@ 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) { + if !specmeta.IsValidIdentifier(name) { errs = append(errs, invalid("", name, "enum name is not a valid identifier")) } @@ -510,7 +508,7 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit var errs []ValidationError // Entity name must be a valid identifier. - if !validIdentifier.MatchString(entityName) { + if !specmeta.IsValidIdentifier(entityName) { errs = append(errs, invalid(entityName, "", "entity name is not a valid identifier")) } @@ -651,7 +649,7 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa var errs []ValidationError // Field name must be a valid identifier. - if !validIdentifier.MatchString(fieldName) { + if !specmeta.IsValidIdentifier(fieldName) { errs = append(errs, invalid(entityName, fieldName, "field name is not a valid identifier")) } @@ -972,7 +970,7 @@ func (v *Validator) validatePermissions(entityName string, perms *parser.ParsedP if specmeta.IsReservedPermissionToken(role) { continue } - if !validIdentifier.MatchString(role) { + if !specmeta.IsValidIdentifier(role) { errs = append(errs, warnf(entityName, "", "permission '%s' role %q is not a valid identifier", operation, role)) } @@ -1039,8 +1037,8 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx var errs []ValidationError ftype := strings.ToLower(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]any); isMap { @@ -1050,7 +1048,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } - case "int", "bigint": + case specmeta.IsIntegralType(ftype): switch n := seedValue.(type) { case int, int32, int64, float32, float64: // numeric OK @@ -1064,7 +1062,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } - case "float", "decimal": + case specmeta.IsFloatType(ftype): switch n := seedValue.(type) { case int, int32, int64, float32, float64: // numeric OK @@ -1077,7 +1075,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } - case "boolean": + case ftype == "boolean": switch v := seedValue.(type) { case bool: // OK @@ -1091,7 +1089,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with boolean type", entryIdx, seedValue)) } - case "date": + case ftype == "date": s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1100,7 +1098,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %q is not a valid date (expected YYYY-MM-DD)", entryIdx, s)) } - case "uuid": + case ftype == "uuid": s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1109,7 +1107,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %q is not a valid UUID (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s)) } - case "datetime": + case ftype == "datetime": s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1119,7 +1117,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx "seed entry %d: value %q is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", entryIdx, s)) } - case "json", "jsonb": + case ftype == "json" || ftype == "jsonb": // JSON values can be any valid JSON — accept any type. // String values are validated as parseable JSON. if s, ok := seedValue.(string); ok { @@ -1128,7 +1126,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx "seed entry %d: value %q is not valid JSON", entryIdx, s)) } } - case "enum": + case ftype == "enum": // The value must be one of the declared enum values. sv, ok := seedValue.(string) if !ok { @@ -1144,7 +1142,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx strings.Join(values, ", "))) } } - case "array": + case ftype == "array": // Accept a YAML list. String values are accepted as JSON arrays. switch v := seedValue.(type) { case []any: @@ -1160,7 +1158,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with array type (expected a list)", entryIdx, seedValue)) } - case "relation": + case ftype == "relation": // 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. diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index aa3593e..39b0edd 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -20,7 +20,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"), }, }, }, @@ -46,8 +46,8 @@ func TestValidateRejectsOldNameEqualToFieldName(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [required, old_name:name]"), }, }, }, @@ -76,9 +76,9 @@ func TestValidateRejectsOldNameCollidingWithExistingField(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "title": testutil.MustParsedField(t, "title", "string"), + "name": testutil.MustParsedField(t, "name", "string [required, old_name:title]"), }, }, }, @@ -107,8 +107,8 @@ func TestValidateAcceptsValidOldName(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [required, old_name:title]"), }, }, }, @@ -132,8 +132,8 @@ func TestValidateDetectsDuplicatePrimaryKey(t *testing.T) { Name: "User", FieldOrder: []string{"id", "code"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "code": mustParsedField(t, "code", "string [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "code": testutil.MustParsedField(t, "code", "string [primary]"), }, }, }, @@ -162,8 +162,8 @@ func TestValidateDetectsBrokenRelation(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "categoryId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid"), - "categoryId": mustParsedField(t, "categoryId", "relation(Category)"), + "id": testutil.MustParsedField(t, "id", "uuid"), + "categoryId": testutil.MustParsedField(t, "categoryId", "relation(Category)"), }, }, }, @@ -190,15 +190,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]"), }, }, }, @@ -226,8 +226,8 @@ func TestValidateDetectsUndefinedEnum(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "status"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(NoSuchEnum)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(NoSuchEnum)"), }, }, }, @@ -257,9 +257,9 @@ func TestValidatePassesValidEnums(t *testing.T) { 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)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(ProductStatus)"), + "tags": testutil.MustParsedField(t, "tags", "array(ProductStatus)"), }, }, }, @@ -282,7 +282,7 @@ func TestValidateDetectsEmptyProjectName(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]"), }, }, }, @@ -313,7 +313,7 @@ func TestValidateDetectsManyOnNonRelation(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]"), }, }, }, @@ -340,7 +340,7 @@ func TestValidateDetectsOnDeleteOnNonRelation(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]"), }, }, }, @@ -366,7 +366,7 @@ func TestValidateDetectsEmptyEnum(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]"), }, }, }, @@ -395,7 +395,7 @@ func TestValidateDetectsEmptyIndexFields(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]"), }, Indexes: []*parser.ParsedIndex{ {Fields: []string{}, Type: "btree"}, @@ -427,8 +427,8 @@ func TestValidateDetectsSortLengthMismatch(t *testing.T) { Name: "User", FieldOrder: []string{"id", "email"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string"), }, Indexes: []*parser.ParsedIndex{ {Fields: []string{"id", "email"}, Sort: []string{"asc"}, Type: "btree"}, @@ -450,10 +450,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 { @@ -475,8 +471,8 @@ func TestValidateAuthEntityMissingEmailPassword(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "name"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string"), }, }, }, @@ -506,9 +502,9 @@ func TestValidateAuthEntityValidEmailPassword(t *testing.T) { 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"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string"), + "password": testutil.MustParsedField(t, "password", "string"), }, }, }, @@ -534,8 +530,8 @@ func TestValidateDefaultNowOnNonDatetime(t *testing.T) { Name: "User", FieldOrder: []string{"id", "count"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "count": mustParsedField(t, "count", "int [default:now()]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "count": testutil.MustParsedField(t, "count", "int [default:now()]"), }, }, }, @@ -564,8 +560,8 @@ func TestValidateDefaultNowOnDatetime(t *testing.T) { Name: "User", FieldOrder: []string{"id", "created"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "created": mustParsedField(t, "created", "datetime [default:now()]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "created": testutil.MustParsedField(t, "created", "datetime [default:now()]"), }, }, }, @@ -591,8 +587,8 @@ func TestValidateDefaultUuidOnNonUuid(t *testing.T) { Name: "User", FieldOrder: []string{"id", "name"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [default:uuid()]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [default:uuid()]"), }, }, }, @@ -639,7 +635,7 @@ func TestValidateDeployPortRange(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]"), }, }, }, @@ -682,7 +678,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]"), }, }, }, @@ -717,7 +713,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]"), }, }, }, @@ -747,8 +743,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"}, @@ -758,7 +754,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]"), }, }, }, @@ -787,8 +783,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"}, @@ -798,7 +794,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]"), }, }, }, @@ -823,8 +819,8 @@ func TestValidateIndexOnPrimitiveField(t *testing.T) { Name: "User", FieldOrder: []string{"id", "email"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string"), }, Indexes: []*parser.ParsedIndex{ {Fields: []string{"email"}, Type: "btree"}, @@ -854,8 +850,8 @@ func TestValidateEnumDefaultMustMatchDeclaredValues(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(ProductStatus) [default:DRAFTT]"), }, }, }, @@ -886,8 +882,8 @@ func TestValidateEnumDefaultValidValue(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(ProductStatus) [default:DRAFT]"), }, }, }, @@ -913,8 +909,8 @@ func TestValidateNumericValidationValueNotNumeric(t *testing.T) { Name: "User", FieldOrder: []string{"id", "age"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int [gte:notanumber]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "age": testutil.MustParsedField(t, "age", "int [gte:notanumber]"), }, }, }, @@ -944,8 +940,8 @@ func TestValidateNumericValidationValueValid(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "age": testutil.MustParsedField(t, "age", "int [gte:0, lt:150]"), }, }, }, @@ -972,7 +968,7 @@ func TestValidateEntityEnumNameCollision(t *testing.T) { Name: "Status", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -1002,9 +998,9 @@ func TestValidatePermissionRolesEmptyAuthRoles(t *testing.T) { 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"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string"), + "password": testutil.MustParsedField(t, "password", "string"), }, Permissions: &parser.ParsedPermissions{ Read: []string{"Admin"}, @@ -1036,8 +1032,8 @@ func TestValidateContradictoryStringMinMax(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [min:10, max:5]"), }, }, }, @@ -1067,8 +1063,8 @@ func TestValidateValidStringMinMax(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [min:2, max:50]"), }, }, }, @@ -1094,8 +1090,8 @@ func TestValidateContradictoryNumericGteLt(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "age": testutil.MustParsedField(t, "age", "int [gte:100, lt:10]"), }, }, }, @@ -1125,8 +1121,8 @@ func TestValidateContradictoryNumericGtLte(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "score": testutil.MustParsedField(t, "score", "int [gt:50, lte:50]"), }, }, }, @@ -1156,8 +1152,8 @@ func TestValidateValidNumericRange(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "age": testutil.MustParsedField(t, "age", "int [gte:0, lt:150]"), }, }, }, @@ -1184,8 +1180,8 @@ func TestValidateUnusedEnumWarning(t *testing.T) { Name: "User", FieldOrder: []string{"id", "role"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "role": mustParsedField(t, "role", "enum(Role)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "role": testutil.MustParsedField(t, "role", "enum(Role)"), }, }, }, @@ -1217,8 +1213,8 @@ func TestValidateUsedEnumNoWarning(t *testing.T) { Name: "User", FieldOrder: []string{"id", "role"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "role": mustParsedField(t, "role", "enum(Role)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "role": testutil.MustParsedField(t, "role", "enum(Role)"), }, }, }, @@ -1247,14 +1243,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]"), }, }, }, @@ -1280,8 +1276,8 @@ func TestValidateSeedValueTypeMismatch(t *testing.T) { Name: "User", FieldOrder: []string{"id", "age"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "age": mustParsedField(t, "age", "int"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "age": testutil.MustParsedField(t, "age", "int"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "age": true}, @@ -1314,8 +1310,8 @@ func TestValidateSeedBooleanTypeMismatch(t *testing.T) { Name: "Config", FieldOrder: []string{"id", "enabled"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "enabled": mustParsedField(t, "enabled", "boolean"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "enabled": testutil.MustParsedField(t, "enabled", "boolean"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "enabled": "notabool"}, @@ -1348,15 +1344,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]"), }, }, }, @@ -1386,15 +1382,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]"), }, }, }, @@ -1420,16 +1416,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)"), }, }, }, @@ -1461,16 +1457,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)"), }, }, }, @@ -1526,15 +1522,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]"), }, }, }, @@ -1558,8 +1554,8 @@ func TestValidateSeedUniqueConstraintViolation(t *testing.T) { Name: "User", FieldOrder: []string{"id", "email"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string [unique]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string [unique]"), }, Seed: []map[string]any{ {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, @@ -1593,8 +1589,8 @@ func TestValidateSeedUniqueConstraintPass(t *testing.T) { Name: "User", FieldOrder: []string{"id", "email"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "email": mustParsedField(t, "email", "string [unique]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "email": testutil.MustParsedField(t, "email", "string [unique]"), }, Seed: []map[string]any{ {"id": "11111111-1111-1111-1111-111111111111", "email": "a@test.com"}, @@ -1624,7 +1620,7 @@ func TestValidateSeedInvalidUUID(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]"), }, Seed: []map[string]any{ {"id": "not-a-uuid"}, @@ -1657,7 +1653,7 @@ func TestValidateSeedValidUUID(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]"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000"}, @@ -1686,8 +1682,8 @@ func TestValidateSeedInvalidDatetime(t *testing.T) { Name: "User", FieldOrder: []string{"id", "createdAt"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "createdAt": mustParsedField(t, "createdAt", "datetime"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "createdAt": testutil.MustParsedField(t, "createdAt", "datetime"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "not-a-date"}, @@ -1720,8 +1716,8 @@ func TestValidateSeedValidDatetime(t *testing.T) { Name: "User", FieldOrder: []string{"id", "createdAt"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "createdAt": mustParsedField(t, "createdAt", "datetime"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "createdAt": testutil.MustParsedField(t, "createdAt", "datetime"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "createdAt": "2024-01-15T10:30:00Z"}, @@ -1750,8 +1746,8 @@ func TestValidateSeedInvalidJSON(t *testing.T) { Name: "User", FieldOrder: []string{"id", "metadata"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "metadata": mustParsedField(t, "metadata", "json"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "metadata": testutil.MustParsedField(t, "metadata", "json"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": "{invalid json}"}, @@ -1784,8 +1780,8 @@ func TestValidateSeedValidJSON(t *testing.T) { Name: "User", FieldOrder: []string{"id", "metadata"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "metadata": mustParsedField(t, "metadata", "json"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "metadata": testutil.MustParsedField(t, "metadata", "json"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "metadata": `{"key":"value"}`}, @@ -1814,7 +1810,7 @@ func TestValidatePermissionRoleIdentifierInvalid(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]"), }, Permissions: &parser.ParsedPermissions{ Read: []string{"valid-role", "123invalid"}, @@ -1846,7 +1842,7 @@ func TestValidatePermissionRoleSpecialTokensAllowed(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]"), }, Permissions: &parser.ParsedPermissions{ Read: []string{"*", "@Owner"}, @@ -1875,8 +1871,8 @@ func TestValidateSeedDateTypeMismatch(t *testing.T) { 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"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "started_on": testutil.MustParsedField(t, "started_on", "date"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "not-a-date"}, @@ -1909,8 +1905,8 @@ func TestValidateSeedDateValid(t *testing.T) { 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"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "started_on": testutil.MustParsedField(t, "started_on", "date"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "started_on": "2024-05-01"}, @@ -1942,8 +1938,8 @@ func TestValidateSeedEnumInvalidValue(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "status"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(Status)"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "BOGUS"}, @@ -1979,8 +1975,8 @@ func TestValidateSeedEnumValidValue(t *testing.T) { Name: "Product", FieldOrder: []string{"id", "status"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(Status)"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "status": "ACTIVE"}, @@ -2009,8 +2005,8 @@ func TestValidateSeedArrayInvalidValue(t *testing.T) { Name: "Item", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "array(string)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "array(string)"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": "not-json"}, @@ -2043,8 +2039,8 @@ func TestValidateSeedArrayValidValue(t *testing.T) { Name: "Item", FieldOrder: []string{"id", "tags"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "tags": mustParsedField(t, "tags", "array(string)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "tags": testutil.MustParsedField(t, "tags", "array(string)"), }, Seed: []map[string]any{ {"id": "550e8400-e29b-41d4-a716-446655440000", "tags": []any{"a", "b"}}, @@ -2073,8 +2069,8 @@ func TestValidateStringMinMaxNonNumeric(t *testing.T) { Name: "User", FieldOrder: []string{"id", "name"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", "string [max:abc]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", "string [max:abc]"), }, }, }, @@ -2103,16 +2099,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)"), }, }, }, @@ -2142,15 +2138,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]"), }, }, }, @@ -2176,8 +2172,8 @@ func TestValidateNoCircularRelationWarningForSelfReference(t *testing.T) { Name: "Category", FieldOrder: []string{"id", "parentId"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "parentId": mustParsedField(t, "parentId", "relation(Category) [optional]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "parentId": testutil.MustParsedField(t, "parentId", "relation(Category) [optional]"), }, }, }, @@ -2202,16 +2198,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)"), }, }, }, @@ -2237,8 +2233,8 @@ func TestValidateDefaultDateInvalid(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "started_on": testutil.MustParsedField(t, "started_on", "date [default:not-a-date]"), }, }, }, @@ -2267,8 +2263,8 @@ func TestValidateDefaultUuidInvalid(t *testing.T) { 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]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "external_id": testutil.MustParsedField(t, "external_id", "uuid [default:not-a-uuid]"), }, }, }, @@ -2301,8 +2297,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]"), }, }, }, @@ -2337,14 +2333,14 @@ func TestValidateRejectsRelationPrimaryKey(t *testing.T) { Name: "Child", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", tt.pkDef), + "id": testutil.MustParsedField(t, "id", tt.pkDef), }, }, "Parent": { Name: "Parent", FieldOrder: []string{"id"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), }, }, }, @@ -2388,8 +2384,8 @@ func TestValidateRejectsNonPositiveStringBounds(t *testing.T) { Name: "Doc", FieldOrder: []string{"id", "name"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "name": mustParsedField(t, "name", tt.def), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "name": testutil.MustParsedField(t, "name", tt.def), }, }, }, @@ -2431,8 +2427,8 @@ func TestValidateRejectsEnumWireValueCollision(t *testing.T) { Name: "Doc", FieldOrder: []string{"id", "status"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(Status)"), }, }, }, @@ -2477,10 +2473,10 @@ func TestValidateRejectsUnparseableNumericSeed(t *testing.T) { Name: "Doc", FieldOrder: []string{"id", "count", "big", "price"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "count": mustParsedField(t, "count", "int"), - "big": mustParsedField(t, "big", "bigint"), - "price": mustParsedField(t, "price", "decimal"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "count": testutil.MustParsedField(t, "count", "int"), + "big": testutil.MustParsedField(t, "big", "bigint"), + "price": testutil.MustParsedField(t, "price", "decimal"), }, Seed: []map[string]any{{"id": "550e8400-e29b-41d4-a716-446655440000", tt.field: tt.value}}, }, @@ -2512,8 +2508,8 @@ func TestValidateSortsErrorsByMessageTiebreaker(t *testing.T) { Name: "Doc", FieldOrder: []string{"id", "status"}, Fields: map[string]*parser.ParsedField{ - "id": mustParsedField(t, "id", "uuid [primary]"), - "status": mustParsedField(t, "status", "enum(Status)"), + "id": testutil.MustParsedField(t, "id", "uuid [primary]"), + "status": testutil.MustParsedField(t, "status", "enum(Status)"), }, }, }, From ec0726f054e75c6c2e96b4114020f672ce40cc38 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:19 +0300 Subject: [PATCH 16/83] Refactor: share bounded HTTP helper and URL redaction --- .../commands_update_security_test.go | 8 +- cmd/domaincraft/update.go | 57 ++---- internal/bridge/update.go | 59 +----- internal/netutil/netutil.go | 89 ++++++++++ internal/netutil/netutil_test.go | 168 ++++++++++++++++++ internal/packages/registry.go | 8 +- 6 files changed, 290 insertions(+), 99 deletions(-) create mode 100644 internal/netutil/netutil.go create mode 100644 internal/netutil/netutil_test.go diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go index caba74f..fde7e01 100644 --- a/cmd/domaincraft/commands_update_security_test.go +++ b/cmd/domaincraft/commands_update_security_test.go @@ -96,14 +96,16 @@ func TestValidateReleaseURL(t *testing.T) { } 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/dc"}, - {"plain", updateAssetURL("dc"), updateAssetURL("dc")}, - {"malformed", "https://[::1", ""}, + {"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) { diff --git a/cmd/domaincraft/update.go b/cmd/domaincraft/update.go index 66a5152..6191d28 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -16,6 +16,7 @@ import ( "github.com/DomainCraft/DomainCraft/internal/appdir" "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/netutil" "github.com/DomainCraft/DomainCraft/internal/packages" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -297,17 +298,10 @@ func parseAllowedURL(raw string) (*url.URL, error) { return u, nil } -// redactURL strips credentials, query and fragment from a URL before it is -// embedded in an error message. +// redactURL reduces a URL to scheme and host before it is embedded in an error +// message. Kept as a seam for the update tests; the redaction is shared. func redactURL(raw string) string { - u, err := url.Parse(raw) - if err != nil { - return "" - } - u.User = nil - u.RawQuery = "" - u.Fragment = "" - return u.String() + return netutil.RedactedURL(raw) } // releaseChecksum reads the SHA-256 digest for name from the release's @@ -356,42 +350,27 @@ func verifyFileSHA256(path, want string) error { 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 { + _, err := parseAllowedURL(u.String()) + return err +} + // httpGetBody performs a GET bound to commandCtx and returns the response body, -// capping it at maxResponseBody bytes. An oversized body is an error, not a -// silently truncated success. +// capping it at maxResponseBody bytes. 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) { - req, err := http.NewRequestWithContext(commandCtx, http.MethodGet, rawURL, nil) - if err != nil { - return nil, fmt.Errorf("build request for %s: %w", redactURL(rawURL), err) - } - resp, err := httpClient.Do(req) //nolint:bodyclose // readResponseBody closes the body - if err != nil { - return nil, fmt.Errorf("request %s: %w", redactURL(rawURL), err) - } - return readResponseBody(resp, rawURL) + return netutil.BoundedGet(commandCtx, httpClient, rawURL, maxResponseBody, validateReleaseRedirect) } // readResponseBody reads at most maxResponseBody+1 bytes so an oversized // response is rejected instead of being silently truncated into a valid binary. +// It stays as a test seam for the response-level checks. func readResponseBody(resp *http.Response, rawURL string) ([]byte, error) { - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, redactURL(rawURL)) - } - // A redirect must not move the download off the allowlist either. - if resp.Request != nil && resp.Request.URL != nil { - if _, err := parseAllowedURL(resp.Request.URL.String()); err != nil { - return nil, fmt.Errorf("redirect from %s: %w", redactURL(rawURL), err) - } - } - data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBody+1)) - if err != nil { - return nil, fmt.Errorf("read %s: %w", redactURL(rawURL), err) - } - if int64(len(data)) > maxResponseBody { - return nil, fmt.Errorf("response from %s exceeds %d bytes", redactURL(rawURL), maxResponseBody) - } - return data, nil + return netutil.ReadBoundedBody(resp, rawURL, maxResponseBody, validateReleaseRedirect) } // downloadBinary fetches a release asset into a temp file and returns its path. diff --git a/internal/bridge/update.go b/internal/bridge/update.go index a1321d2..d46fe88 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -2,16 +2,15 @@ package bridge import ( "encoding/json" - "errors" "fmt" - "io" "net/http" - "net/url" "os" "os/exec" "strings" "time" + "github.com/DomainCraft/DomainCraft/internal/netutil" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "gopkg.in/yaml.v3" ) @@ -52,14 +51,10 @@ func parseBridgeContractVersion(data []byte) (int, error) { if err := yaml.Unmarshal(data, &cfg); err != nil { return 0, fmt.Errorf("parse bridge contract version: %w", err) } - switch { - case cfg.ContractVersion == 0: - return 1, nil - case cfg.ContractVersion < 0: + if cfg.ContractVersion < 0 { return 0, fmt.Errorf("invalid contract_version %d", cfg.ContractVersion) - default: - return cfg.ContractVersion, nil } + return specmeta.EffectiveContractVersion(cfg.ContractVersion), nil } // shouldApplyContract verifies that a bridge declaring contractVersion is @@ -279,50 +274,10 @@ func githubAPIHead(entry RegistryEntry) (branch, commit string, err error) { const maxProbeBodyBytes = 1 << 20 // httpGetBody performs a GET bound to the CLI's command context and returns the -// response body. It reads one byte past the limit so an oversized body fails -// instead of being silently truncated into a plausible-looking manifest. +// 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. func httpGetBody(rawURL string) ([]byte, error) { - scope := redactedURLScope(rawURL) - req, err := http.NewRequestWithContext(CommandContext(), http.MethodGet, rawURL, nil) - if err != nil { - return nil, fmt.Errorf("build probe request for %s: %w", scope, redactURLError(err)) - } - resp, err := httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("probe request to %s failed: %w", scope, redactURLError(err)) - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d for %s", resp.StatusCode, scope) - } - body, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeBodyBytes+1)) - if err != nil { - return nil, fmt.Errorf("read response from %s: %w", scope, err) - } - if len(body) > maxProbeBodyBytes { - return nil, fmt.Errorf("response from %s exceeds %d bytes", scope, maxProbeBodyBytes) - } - return body, nil -} - -// redactURLError drops the raw URL carried by *url.Error (userinfo and query -// could be secrets) while keeping the underlying reason for %w wrapping. -func redactURLError(err error) error { - var urlErr *url.Error - if errors.As(err, &urlErr) && urlErr.Err != nil { - return urlErr.Err - } - return err -} - -// redactedURLScope reduces a URL to scheme and host for error messages, so -// credentials and query strings from a bridge's config never reach the log. -func redactedURLScope(raw string) string { - u, err := url.Parse(raw) - if err != nil || u.Scheme == "" || u.Hostname() == "" { - return "" - } - return u.Scheme + "://" + u.Hostname() + return netutil.BoundedGet(CommandContext(), httpClient, rawURL, int64(maxProbeBodyBytes), nil) } // runGit runs a git command in dir and returns its trimmed stdout. diff --git a/internal/netutil/netutil.go b/internal/netutil/netutil.go new file mode 100644 index 0000000..d1af103 --- /dev/null +++ b/internal/netutil/netutil.go @@ -0,0 +1,89 @@ +// 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" +) + +// 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. +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 + +// 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, including the +// target of any redirect the client followed. +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 { + 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: its timeout and redirect policy +// are applied unchanged. +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)) + } + 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/registry.go b/internal/packages/registry.go index 0918828..b34b9eb 100644 --- a/internal/packages/registry.go +++ b/internal/packages/registry.go @@ -15,6 +15,7 @@ import ( "time" "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/netutil" ) // maxRegistryResponseBytes caps a version index read from a registry. @@ -144,12 +145,9 @@ func restrictedRegistryDialer(ctx context.Context, network, addr string) (net.Co // redactedRegistryURL keeps only scheme and host for error messages, so // credentials and query strings from a bridge's config never reach the log. +// The redaction itself is shared with the other network callers. func redactedRegistryURL(raw string) string { - u, err := url.Parse(raw) - if err != nil || u.Scheme == "" || u.Hostname() == "" { - return "" - } - return u.Scheme + "://" + u.Hostname() + return netutil.RedactedURL(raw) } // ResolveVersion queries a package registry (e.g. NuGet) for the latest stable version From e6efc62a7abb2931251f8f994ad090bb1916fd0a Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:33 +0300 Subject: [PATCH 17/83] Renderer: use absolute bridge dir in symlink check --- internal/renderer/render.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 39dbf8c..bd6bc09 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -23,7 +23,11 @@ func safeBridgeSource(dir, rel string) (string, error) { if err != nil { return "", fmt.Errorf("unsafe bridge source path %q: %w", rel, err) } - realDir, err := filepath.EvalSymlinks(dir) + absDir, err := filepath.Abs(dir) + if err != nil { + return "", fmt.Errorf("resolve bridge dir: %w", err) + } + realDir, err := filepath.EvalSymlinks(absDir) if err != nil { return "", fmt.Errorf("resolve bridge dir: %w", err) } From 10431c48584f867e1197de17bc2ac4593027ba2a Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:33 +0300 Subject: [PATCH 18/83] Core: make snapshot.json byte-deterministic --- compliance-suite/regressions.tsv | 1 + internal/snapshot/hardening_test.go | 19 +++++++++++++++++++ internal/snapshot/snapshot.go | 12 +++--------- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 574ed32..62d3d7a 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -74,3 +74,4 @@ cmd/domaincraft/commands_update_security_test.go::TestVerifyFileSHA256 #5 self-u cmd/domaincraft/commands_update_security_test.go::TestRunCoreUpdateFailsClosed #5 failed update path could still replace the executable 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/snapshot/hardening_test.go::TestSnapshotJSONHasNoTimestamp #5 snapshot.json carried a wall-clock timestamp and broke bit-identical output diff --git a/internal/snapshot/hardening_test.go b/internal/snapshot/hardening_test.go index eb70ed1..b3dc9ac 100644 --- a/internal/snapshot/hardening_test.go +++ b/internal/snapshot/hardening_test.go @@ -195,3 +195,22 @@ func TestComputeDiffIgnoresSnapshotPathsThroughSymlinks(t *testing.T) { } }) } + +// 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) + + 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") + } +} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index f4cc6a8..f936545 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -17,7 +17,6 @@ import ( "path/filepath" "slices" "strings" - "time" "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/ir" @@ -51,7 +50,6 @@ 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"` @@ -84,14 +82,11 @@ func Save(path string, snap *Snapshot) error { 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) - } // 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. - if err := fsutil.AtomicWrite(path, append(data, '\n')); err != nil { + // 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 @@ -114,7 +109,6 @@ func New(bridge string, project *ir.Project, files []renderer.RenderedFile) *Sna return &Snapshot{ FormatVersion: FormatVersion, Bridge: bridge, - CreatedAt: time.Now().UTC().Format(time.RFC3339), ProjectNamespace: textutil.PascalCase(project.Name), Files: files, Entities: entities, From cd8900249313b9a1920d35c6ddde16c57bf20951 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:04 +0300 Subject: [PATCH 19/83] Validator: reject fractional seeds and validate rename hints - reject non-integral float seed values for integral fields - validate entity old_name as identifier and reject self-reference - fail on duplicate features instead of collapsing them silently - split validateField into focused rule helpers - register the new regression checks --- compliance-suite/regressions.tsv | 13 +++ internal/parser/parser.go | 6 +- internal/parser/parser_test.go | 37 ++++++++ internal/seed/seed_test.go | 31 +++++++ internal/validator/validator.go | 106 ++++++++++++++++++--- internal/validator/validator_test.go | 134 +++++++++++++++++++++++++++ 6 files changed, 315 insertions(+), 12 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 62d3d7a..2cee3ac 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -75,3 +75,16 @@ cmd/domaincraft/commands_update_security_test.go::TestRunCoreUpdateFailsClosed # 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/snapshot/hardening_test.go::TestSnapshotJSONHasNoTimestamp #5 snapshot.json carried a wall-clock timestamp and broke bit-identical output +internal/validator/validator_test.go::TestValidateRejectsFractionalSeedForIntegralField #5 fractional seed values were silently truncated into integer columns +internal/validator/validator_test.go::TestValidateRejectsInvalidEntityOldName #5 entity old_name bypassed identifier validation and reached migration rewrites +internal/validator/validator_test.go::TestValidateRejectsSelfReferentialEntityOldName #5 self-referential old_name produced a no-op rename migration +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/hardening_test.go::TestRollbackWritesReportsRestoreFailure #5 failed rollback was reported as a clean render +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/packages/registry_test.go::TestResolveVersionRejectsOversizedBody #5 oversized registry response was silently truncated into a version list +internal/fsutil/fsutil_test.go::TestAtomicWritePreservesExistingFileMode #5 atomic rewrite dropped developer-owned files to mode 0600 +internal/snapshot/rewrite_test.go::TestRewriteFilePreservesExistingMode #5 prune rewrite silently changed permissions of custom files +internal/snapshot/hardening_test.go::TestMigrationPlanTableNameMatchesIRForAcronymEntity #5 migration plan and IR derived table names through two different rules +internal/snapshot/hardening_test.go::TestCasingVariants #5 four parallel casing tables could drift during entity renames diff --git a/internal/parser/parser.go b/internal/parser/parser.go index f5f465e..7049533 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -140,12 +140,16 @@ 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 } diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index 3bb8549..b7c5ca8 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -748,3 +748,40 @@ 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) + } + }) + } +} diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index 38ae1d5..18b0630 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -469,3 +469,34 @@ func TestGenerateUsesDeclaredDefaultOverMock(t *testing.T) { t.Errorf("attempts = %#v, want int64(3)", vals["attempts"]) } } + +// TestNormalizeIntegralFloatSeed documents that a float with an integral +// value survives seed coercion; fractional values are rejected upstream by +// the validator before they reach this code. +func TestNormalizeIntegralFloatSeed(t *testing.T) { + t.Parallel() + project := &ir.Project{ + Entities: []ir.Entity{ + { + Name: "Docs", + Fields: []ir.Field{ + {Name: "id", DatabaseType: "uuid", IsPrimary: true}, + {Name: "count", DatabaseType: "int"}, + }, + Seed: []map[string]any{{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "count": float64(1.0), + }}, + }, + }, + } + + ds := Normalize(project) + vals := map[string]any{} + for _, sv := range ds.Entities[0].Records[0].Fields { + vals[sv.Field] = sv.Value + } + if vals["count"] != int64(1) { + t.Errorf("count = %#v, want int64(1)", vals["count"]) + } +} diff --git a/internal/validator/validator.go b/internal/validator/validator.go index 297184e..e482667 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "maps" + "math" "regexp" "slices" "strconv" @@ -513,6 +514,19 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit "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, invalid(entityName, "", @@ -541,16 +555,6 @@ func (v *Validator) validateEntity(entityName string, entity *parser.ParsedEntit } } - // Duplicate feature names. - featureSeen := make(map[string]bool) - for f := range entity.Features { - if featureSeen[f] { - errs = append(errs, warnf(entityName, "", - "duplicate feature %q", f)) - } - featureSeen[f] = true - } - // Track DB column names for collision detection. columnNames := make(map[string]string) // column -> field name @@ -645,8 +649,23 @@ 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 !specmeta.IsValidIdentifier(fieldName) { @@ -664,6 +683,14 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } + 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 { + var errs []ValidationError + // Relation-specific checks. // 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 @@ -710,6 +737,13 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } + 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" { @@ -722,6 +756,13 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } + return errs +} + +// validateEnumField checks that an enum reference is declared. +func (v *Validator) validateEnumField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError + // Enum reference. if field.Type == "enum" && field.TargetType != "" { if _, ok := v.schema.Enums[field.TargetType]; !ok { @@ -730,6 +771,14 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } + return errs +} + +// validateArrayField checks that an array element type is primitive or a +// declared enum. +func (v *Validator) validateArrayField(entityName, fieldName string, field *parser.ParsedField) []ValidationError { + var errs []ValidationError + // Array element type. if field.Type == "array" && field.TargetType != "" { inner := strings.ToLower(field.TargetType) @@ -741,6 +790,14 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa } } + return errs +} + +// 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) @@ -773,6 +830,15 @@ func (v *Validator) validateField(entityName string, fieldName string, field *pa // Check for contradictory range validations. errs = append(errs, validateContradictoryRanges(entityName, fieldName, field, 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) + // Default value type check. if field.DefaultValue != "" && field.DefaultIsFunc { errs = append(errs, validateFuncDefault(entityName, fieldName, ftype, field.DefaultValue)...) @@ -1031,6 +1097,20 @@ func (v *Validator) validateSeedEntry(entityName string, entity *parser.ParsedEn return errs } +// 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 + } +} + // 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 any) []ValidationError { @@ -1051,7 +1131,11 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx case specmeta.IsIntegralType(ftype): switch n := seedValue.(type) { case int, int32, int64, float32, float64: - // numeric OK + // A fractional float would be silently truncated by the seed generator. + if isFractionalFloat(n) { + errs = append(errs, invalidf(entityName, fieldName, + "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) + } case string: // A string must parse; otherwise seed coercion silently yields 0. if _, err := strconv.ParseInt(n, 10, 64); err != nil { diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index 39b0edd..7ccf109 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -2534,3 +2534,137 @@ func TestValidateSortsErrorsByMessageTiebreaker(t *testing.T) { t.Fatalf("first error = %q, want the empty-value error", errs[0].Message) } } + +// 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) + } +} From a720012cc3a6869a7d4fde41806eb4435534b5f9 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:10 +0300 Subject: [PATCH 20/83] Renderer: fail closed on unknown conditions and preserve resolved versions - reject unknown when conditions when loading a bridge manifest - alias the contract version to specmeta and drop bare literals - keep a resolved package version when the cache write fails - deduplicate the version cache pipeline - reject oversized NuGet responses instead of truncating them - report rollback failures instead of swallowing them --- internal/packages/cache.go | 56 +++++++++------------ internal/packages/cache_test.go | 41 ++++++++++++++++ internal/packages/registry.go | 11 +++-- internal/packages/registry_test.go | 18 +++++++ internal/renderer/contract_test.go | 43 ++++++++++++++++ internal/renderer/hardening_test.go | 50 +++++++++++++++++++ internal/renderer/load.go | 60 ++++++++++++++++++++--- internal/renderer/render.go | 76 +++++++++++++++++++---------- internal/renderer/version_test.go | 11 +++++ 9 files changed, 297 insertions(+), 69 deletions(-) diff --git a/internal/packages/cache.go b/internal/packages/cache.go index 104dc74..a4b5147 100644 --- a/internal/packages/cache.go +++ b/internal/packages/cache.go @@ -88,27 +88,25 @@ func persistVersionCache(bridgeID string, entries map[string]versionEntry) error 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() defer cacheMu.Unlock() entries, err := versionStore(bridgeID) if err != nil { // Cache directory unusable — resolve uncached rather than fail. - return resolveVersionFn(registryURL, packageID) + return resolve() } if e, ok := entries[key]; ok && e.Value != "" && time.Since(e.StoredAt) <= DefaultCacheTTL { return e.Value, nil } - version, err := resolveVersionFn(registryURL, packageID) + version, err := resolve() if err != nil { return "", err } @@ -118,38 +116,30 @@ func ResolveVersionCached(bridgeID, registryURL, packageID string) (string, erro entries[key] = versionEntry{Value: version, StoredAt: time.Now()} if err := persistVersionCacheFn(bridgeID, entries); err != nil { - return "", err + // 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 } +// 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) { + return resolveVersionCached(bridgeID, cacheKey(registryURL, packageID), func() (string, error) { + return resolveVersionFn(registryURL, packageID) + }) +} + // 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 - - cacheMu.Lock() - defer cacheMu.Unlock() - - entries, err := versionStore(bridgeID) - if err != nil { + return resolveVersionCached(bridgeID, key, func() (string, error) { return resolveVersionForFrameworkFn(registryURL, packageID, targetFramework) - } - 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()} - if err := persistVersionCacheFn(bridgeID, entries); err != nil { - return "", err - } - return version, nil + }) } diff --git a/internal/packages/cache_test.go b/internal/packages/cache_test.go index 321516d..03e450a 100644 --- a/internal/packages/cache_test.go +++ b/internal/packages/cache_test.go @@ -1,8 +1,10 @@ package packages import ( + "errors" "os" "path/filepath" + "strings" "testing" "time" @@ -256,6 +258,45 @@ func TestResolveVersionCachedIsolation(t *testing.T) { } } +// A failed cache write must not discard a version that was successfully +// resolved from the registry. Both exported resolvers share this guarantee. +func TestPersistFailureKeepsResolvedVersion(t *testing.T) { + persistErr := errors.New("disk full") + oldPersist := persistVersionCacheFn + persistVersionCacheFn = func(_ string, _ map[string]versionEntry) error { return persistErr } + defer func() { persistVersionCacheFn = oldPersist }() + + t.Run("plain", func(t *testing.T) { + resetCacheRoot(t) + old := resolveVersionFn + resolveVersionFn = func(_, _ string) (string, error) { return "2.0.0", nil } + defer func() { resolveVersionFn = old }() + + got, err := ResolveVersionCached("demo", "https://reg.example/{id}", "demo.pkg") + if got != "2.0.0" { + t.Fatalf("version = %q, want 2.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) + } + }) + + t.Run("framework", func(t *testing.T) { + resetCacheRoot(t) + old := resolveVersionForFrameworkFn + resolveVersionForFrameworkFn = func(_, _, _ string) (string, error) { return "10.0.0", nil } + defer func() { resolveVersionForFrameworkFn = old }() + + got, err := ResolveVersionCachedForFramework("demo", "https://reg.example/{id}", "demo.pkg", "net10.0") + 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) { + t.Fatalf("err = %v, want the persist failure", err) + } + }) +} + // TestLoadCacheIgnoresCorruptFile ensures a corrupt cache file degrades // gracefully (fresh empty cache) instead of failing generation. func TestLoadCacheIgnoresCorruptFile(t *testing.T) { diff --git a/internal/packages/registry.go b/internal/packages/registry.go index b34b9eb..380614f 100644 --- a/internal/packages/registry.go +++ b/internal/packages/registry.go @@ -6,7 +6,6 @@ import ( "encoding/json" "errors" "fmt" - "io" "net" "net/http" "net/url" @@ -258,11 +257,17 @@ func fetchVersions(registryURL string, packageID string) ([]string, error) { 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 prevent OOM from malicious/misconfigured registries. - if err := json.NewDecoder(io.LimitReader(resp.Body, maxRegistryResponseBytes)).Decode(&result); err != nil { + if err := json.Unmarshal(body, &result); err != nil { return nil, err } diff --git a/internal/packages/registry_test.go b/internal/packages/registry_test.go index 8aea670..ce4f265 100644 --- a/internal/packages/registry_test.go +++ b/internal/packages/registry_test.go @@ -183,3 +183,21 @@ func TestResolveVersionUnreachableRegistry(t *testing.T) { 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))) + })) + defer srv.Close() + + got, err := ResolveVersion(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/renderer/contract_test.go b/internal/renderer/contract_test.go index 968a915..5700290 100644 --- a/internal/renderer/contract_test.go +++ b/internal/renderer/contract_test.go @@ -74,3 +74,46 @@ 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() + for _, when := range []string{"", "hasSeed", "hasEnums", "hasOwnerTokens", "hasAuth", "hasMigration", "hasMockData", "hasAddon:dapr", "notHasAddon:dapr", "hasAddon", "notHasAddon"} { + 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(writeBridgeConfig(t, yamlContent)); err != nil { + t.Fatalf("loadSource rejected known condition %q: %v", when, err) + } + }) + } +} diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index 6e813bc..a1869e6 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -188,3 +188,53 @@ func assertNoRenderTemps(t *testing.T, dir string) { } } } + +// 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") + + 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, + original: []byte("original"), + existed: true, + mode: 0o644, + }}) + 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 rollbackError(primary, nil) != primary { + t.Error("no-op rollback must return the original error unchanged") + } +} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index 549e8a7..42ba6a1 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -6,9 +6,11 @@ import ( "path/filepath" "regexp" "slices" + "strings" "text/template" "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/logger" "gopkg.in/yaml.v3" @@ -17,8 +19,9 @@ import ( // 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 +// treats an absent declaration as this version (with a deprecation notice). +// It aliases specmeta.ContractVersion so the contract has one definition. +const ContractVersion = specmeta.ContractVersion // sourceConfig is one bridge directory plus its parsed bridge.yaml. A composed // renderer holds several of these, ordered base-first, with the adapter last. @@ -66,6 +69,48 @@ 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" +) + +var ( + simpleWhenConditions = []string{whenSeed, whenEnums, whenOwnerTokens, whenAuth, whenMigration, whenMockData, whenAddon, whenNotAddon} + addonWhenPrefixes = []string{whenAddon, whenNotAddon} +) + +// validateWhenConditions rejects any condition outside the closed vocabulary, +// including unknown colon-prefixed forms such as "hasFeature:audit". Bare +// prefix 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, _, hasColon := strings.Cut(when, ":") + known := false + if hasColon { + known = slices.Contains(addonWhenPrefixes, strings.TrimSpace(prefix)) + } else { + known = slices.Contains(simpleWhenConditions, when) + } + if !known { + return fmt.Errorf("bridge %q template %d: unknown when condition %q (allowed: hasSeed, hasEnums, hasOwnerTokens, hasAuth, hasMigration, hasMockData, hasAddon:, notHasAddon:)", bridgeName, i, when) + } + } + return nil +} + // loadSource loads a single bridge directory (its bridge.yaml). func loadSource(bridgePath string) (sourceConfig, error) { bridgeDir, configPath := resolveBridgePath(bridgePath) @@ -81,14 +126,17 @@ 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. + // Contract version: absent (0) means the core's contract version, with a + // deprecation notice (emitted by the caller); a newer contract is an error. contractDeclared := config.ContractVersion != 0 if config.ContractVersion == 0 { - config.ContractVersion = 1 + config.ContractVersion = ContractVersion } if config.ContractVersion > ContractVersion { return sourceConfig{}, fmt.Errorf( @@ -105,7 +153,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 } diff --git a/internal/renderer/render.go b/internal/renderer/render.go index bd6bc09..6a878f6 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -72,21 +72,42 @@ type stagedWrite struct { } // rollbackWrites undoes committed writes in reverse order and removes every -// staged temp file. It is best-effort: the original error is always returned to -// the caller, and no output file is left in a half-written state. -func rollbackWrites(staged, committed []stagedWrite) { +// 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.existed { - if err := fsutil.AtomicWrite(w.target, w.original); err == nil { - _ = os.Chmod(w.target, w.mode) + if err := fsutil.AtomicWrite(w.target, w.original); err != nil { + failures = append(failures, fmt.Errorf("restore %s: %w", w.target, err)) + continue + } + if err := os.Chmod(w.target, w.mode); err != nil { + failures = append(failures, fmt.Errorf("restore mode of %s: %w", w.target, err)) } continue } - _ = os.Remove(w.target) + if err := os.Remove(w.target); err != nil && !errors.Is(err, os.ErrNotExist) { + failures = append(failures, fmt.Errorf("remove %s: %w", w.target, err)) + } } for _, w := range staged { - _ = os.Remove(w.temp) + 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...) +} + +// 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)) } // Render renders the IR through every bridge in the chain and returns the @@ -138,12 +159,13 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } staged := make([]stagedWrite, 0) + // committed is empty during staging; phase 2 appends to it as files land. + committed := make([]stagedWrite, 0) manifest := make([]RenderedFile, 0) - // fail drops every staged temp file. No output file has been touched during - // staging, so there is nothing to restore yet. + // fail drops every staged temp file (and restores committed files once + // phase 2 starts), attaching any rollback failure to the primary error. fail := func(err error) ([]string, []RenderedFile, error) { - rollbackWrites(staged, nil) - return nil, nil, err + return nil, nil, rollbackError(err, rollbackWrites(staged, committed)) } // Phase 1: parse templates and render each target into a temp file. Nothing @@ -290,18 +312,14 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re // Phase 2: commit staged files. A failed rename rolls back every file that // was already replaced, so callers never observe a partially updated tree. - committed := make([]stagedWrite, 0, len(staged)) for _, w := range staged { if info, err := os.Lstat(w.target); err == nil && info.Mode()&os.ModeSymlink != 0 { - rollbackWrites(staged, committed) - return nil, nil, fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path) + return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) } else if err != nil && !errors.Is(err, os.ErrNotExist) { - rollbackWrites(staged, committed) - return nil, nil, fmt.Errorf("inspect output file %s: %w", w.record.Path, err) + return fail(fmt.Errorf("inspect output file %s: %w", w.record.Path, err)) } if err := os.Rename(w.temp, w.target); err != nil { - rollbackWrites(staged, committed) - return nil, nil, fmt.Errorf("commit output file %s: %w", w.record.Path, err) + return fail(fmt.Errorf("commit output file %s: %w", w.record.Path, err)) } committed = append(committed, w) } @@ -332,7 +350,7 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) // true. if cond, name, ok := strings.Cut(spec.When, ":"); ok { switch strings.TrimSpace(cond) { - case "hasAddon": + case whenAddon: if context.Project != nil { if name == "" { return len(context.Project.Addons) > 0 @@ -340,7 +358,7 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) return context.Project.HasAddon(strings.TrimSpace(name)) } return false - case "notHasAddon": + case whenNotAddon: if context.Project != nil { if name == "" { return len(context.Project.Addons) == 0 @@ -351,16 +369,16 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) } } switch spec.When { - case "hasSeed": + case whenSeed: // Only render seed templates if there's actual seed data. return context.HasSeedData() - case "hasEnums": + case whenEnums: // Only render enum templates if there are enums defined if context.Project != nil && len(context.Project.Enums) > 0 { return true } return false - case "hasOwnerTokens": + case whenOwnerTokens: // Only render owner resolver if any entity uses @Owner tokens if context.Project != nil { for _, e := range context.Project.Entities { @@ -370,15 +388,18 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) } } return false - case "hasAuth": + case whenAuth: return context.Project != nil && context.Project.HasAuth() - case "hasMigration": + case whenMigration: // True when the core computed a non-empty schema migration plan. return context.HasMigration() - case "hasMockData": + case whenMockData: // True when the context carries generated mock data. return context.HasMockData() default: + // Defensive only: loaded manifests are validated against the closed + // vocabulary in validateWhenConditions, so this is unreachable for + // bridge.yaml-driven templates. return true } } @@ -427,8 +448,9 @@ func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { 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 diff --git a/internal/renderer/version_test.go b/internal/renderer/version_test.go index 2ddc792..ff1719a 100644 --- a/internal/renderer/version_test.go +++ b/internal/renderer/version_test.go @@ -3,8 +3,19 @@ package renderer import ( "strings" "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" ) +// TestContractVersionAliasesSpecmeta pins the single source of truth: the +// renderer's public constant must be the specmeta contract, never a copy. +func TestContractVersionAliasesSpecmeta(t *testing.T) { + t.Parallel() + if ContractVersion != specmeta.ContractVersion { + t.Fatalf("renderer.ContractVersion = %d, specmeta.ContractVersion = %d", ContractVersion, 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 From c0bbda43afe3f2c60249e218c20c701bb876e40e Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:25 +0300 Subject: [PATCH 21/83] Snapshot: preserve file modes and single-source rename rules - keep existing permissions when AtomicWrite rewrites a file - export ir.TableNameFor and reuse it in the migration plan - unify casing variants for content and path rewrites - deduplicate the existing-file filter - assert byte-identical snapshot output --- internal/fsutil/fsutil.go | 18 +++++- internal/fsutil/fsutil_test.go | 34 +++++++++++ internal/ir/models.go | 25 ++++++-- internal/snapshot/hardening_test.go | 14 +++++ internal/snapshot/migration.go | 10 +-- internal/snapshot/migration_test.go | 50 +++++++++++++++ internal/snapshot/rewrite.go | 45 +++++++------- internal/snapshot/rewrite_test.go | 95 +++++++++++++++++++++++++++++ internal/snapshot/snapshot.go | 49 ++++++++------- 9 files changed, 279 insertions(+), 61 deletions(-) diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index 33473f8..c3f8ef4 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -70,13 +70,23 @@ func RefuseSymlinks(base, target string) error { // 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. +// 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 { dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0o755); err != nil { //nolint:gosec // generated project and cache dirs must stay world-readable return err } + mode := os.FileMode(0o600) // CreateTemp's default for new files + if info, err := os.Lstat(path); err == nil { + if info.Mode()&os.ModeSymlink == 0 { + mode = info.Mode().Perm() + } + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") if err != nil { return err @@ -84,6 +94,12 @@ func AtomicWrite(path string, data []byte) error { tmpName := tmp.Name() defer func() { _ = os.Remove(tmpName) }() // no-op once the rename succeeds + // CreateTemp uses 0600; apply the target's mode before committing the + // rename, the same way the renderer stages generated files. + if err := tmp.Chmod(mode); err != nil { + _ = tmp.Close() + return err + } if _, err := tmp.Write(data); err != nil { _ = tmp.Close() return err diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go index b570933..ef78e74 100644 --- a/internal/fsutil/fsutil_test.go +++ b/internal/fsutil/fsutil_test.go @@ -23,6 +23,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") diff --git a/internal/ir/models.go b/internal/ir/models.go index 20a31e6..de5ef78 100644 --- a/internal/ir/models.go +++ b/internal/ir/models.go @@ -222,12 +222,27 @@ func (r Relation) EagerLoadNavigation() string { 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`). +// 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 toTableName(textutil.Pluralize(name)) +} + +// toTableName applies the canonical snake_case conversion to an already-plural +// name. The parser stores the plural in Entity.NamePlural, so the two entry +// points share this one conversion instead of each re-deriving it. +func toTableName(plural string) string { + return textutil.ToDatabaseColumnName(plural) +} + +// 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) + return toTableName(e.NamePlural) } // ForeignKeyColumnName returns the snake_case DB column name of this relation's diff --git a/internal/snapshot/hardening_test.go b/internal/snapshot/hardening_test.go index b3dc9ac..30389b1 100644 --- a/internal/snapshot/hardening_test.go +++ b/internal/snapshot/hardening_test.go @@ -1,6 +1,7 @@ package snapshot import ( + "bytes" "os" "path/filepath" "strings" @@ -202,6 +203,7 @@ 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) @@ -213,4 +215,16 @@ func TestSnapshotJSONHasNoTimestamp(t *testing.T) { 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) + } } diff --git a/internal/snapshot/migration.go b/internal/snapshot/migration.go index 8df1f8d..385466d 100644 --- a/internal/snapshot/migration.go +++ b/internal/snapshot/migration.go @@ -18,12 +18,6 @@ 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.Project) *ir.MigrationPlan { plan := &ir.MigrationPlan{} @@ -91,7 +85,7 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.Project) *ir.MigrationPlan Entity: e.Name, OldName: oldName, Table: e.TableName(), - OldTable: tableName(oldName), + OldTable: ir.TableNameFor(oldName), }) } @@ -107,7 +101,7 @@ func ComputeMigrationPlan(old *Snapshot, project *ir.Project) *ir.MigrationPlan plan.Operations = append(plan.Operations, ir.MigrationOp{ Kind: ir.OpDropTable, Entity: name, - Table: tableName(name), + Table: ir.TableNameFor(name), }) } diff --git a/internal/snapshot/migration_test.go b/internal/snapshot/migration_test.go index f3a632b..cb9abf7 100644 --- a/internal/snapshot/migration_test.go +++ b/internal/snapshot/migration_test.go @@ -149,6 +149,56 @@ func TestComputeMigrationPlanColumnOps(t *testing.T) { } } +// 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() { diff --git a/internal/snapshot/rewrite.go b/internal/snapshot/rewrite.go index a39da73..576ebc5 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -123,38 +123,39 @@ func isIdentRune(r rune) bool { return specmeta.IsIdentifierRune(r) } +// 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(old, new string, withPlural bool) map[string]string { + variants := map[string]string{ + old: new, // Product -> Item + textutil.CamelCase(old): textutil.CamelCase(new), // product -> item + strings.ToUpper(old): strings.ToUpper(new), // PRODUCT -> ITEM + } + if withPlural { + oldPlural := textutil.Pluralize(old) + newPlural := textutil.Pluralize(new) + 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 +} + // 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 - } + return casingVariants(textutil.PascalCase(oldName), textutil.PascalCase(newName), true) } // 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 - } + return casingVariants(textutil.PascalCase(oldField), textutil.PascalCase(newField), false) } // 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), - } + return casingVariants(oldNs, newNs, false) } // RewriteEntityContent rewrites identifier references to an old entity name back diff --git a/internal/snapshot/rewrite_test.go b/internal/snapshot/rewrite_test.go index e563ba1..b73dd85 100644 --- a/internal/snapshot/rewrite_test.go +++ b/internal/snapshot/rewrite_test.go @@ -1,6 +1,7 @@ package snapshot import ( + "maps" "os" "path/filepath" "testing" @@ -95,6 +96,100 @@ 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() diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index f936545..a0e2249 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -416,51 +416,50 @@ func customEntityFiles(files []renderer.RenderedFile, entityName string) []strin return paths } -// 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 { - abs, err := safeRelPath(outputDir, 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) []T { + var result []T + for _, item := range items { + abs, err := safeRelPath(outputDir, relPath(item)) if err != nil { continue } if _, err := os.Stat(abs); err != nil { continue } + result = append(result, item) + } + 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 { + existing := existingItems(outputDir, files, func(f renderer.RenderedFile) string { return f.Path }) + 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 { - abs, err := safeRelPath(outputDir, rel) - if err != nil { - continue - } - if _, err := os.Stat(abs); err == nil { - result = append(result, rel) - } - } - slices.Sort(result) - return result + return existingItems(outputDir, relPaths, func(rel string) string { return rel }) } // 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 { // 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 := map[string]string{ - textutil.Pluralize(oldName): textutil.Pluralize(newName), - oldName: newName, - } + variants := casingVariants(oldName, newName, true) return string(replaceLongest([]byte(relPath), variants, tokenOK)) } From 5dad21b679307d72735ae396953b2724c80e0524 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:54:23 +0300 Subject: [PATCH 22/83] CI: align local lint with CI and gate WASM and TypeScript TCK - make lint runs the pinned golangci-lint; vet stays separate - make build no longer rewrites go.mod/go.sum - CI cross-compiles the js/wasm validator and shuffles tests - bridges CI runs the hermetic TypeScript TCK halves - document consent flags, real bridge chains and C#-only rename artifacts --- .github/workflows/bridges.yml | 69 ++++++++++++++++++- .github/workflows/ci.yml | 11 ++- Makefile | 16 +++-- README.md | 35 +++++----- .../csharp/persistence/dapper-stub/README.md | 16 ++--- 5 files changed, 114 insertions(+), 33 deletions(-) diff --git a/.github/workflows/bridges.yml b/.github/workflows/bridges.yml index 8d4ca39..659c6b5 100644 --- a/.github/workflows/bridges.yml +++ b/.github/workflows/bridges.yml @@ -5,8 +5,9 @@ name: bridges # 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). +# are native GitHub `paths:` triggers — no custom scope binary is needed. +# The TypeScript job adds Node; Go, npm cache and local bridge paths keep it +# hermetic (no bridge clones). on: # PR checks cover feature branches; push runs once after a merge to main. @@ -15,10 +16,14 @@ on: paths: - 'bridges/**' - 'internal/**' + - 'cmd/**' + - 'compliance-suite/**' pull_request: paths: - 'bridges/**' - 'internal/**' + - 'cmd/**' + - 'compliance-suite/**' permissions: contents: read @@ -59,3 +64,63 @@ jobs: exit 1 fi go test ./internal/renderer/ -run TestBundledBridgesLoad -v + + typescript-tck: + name: TypeScript TCK (hermetic halves) + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version: '1.27.4' + cache: true + cache-dependency-path: go.sum + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: | + bridges/typescript/core/tck/package-lock.json + bridges/typescript/client/tck/package-lock.json + + - name: Generate kitchen-sink artifacts from local bridges + # Explicit local paths (and the bundled `ts-core` extends target) — + # no registry clones or network bridge lookups. npm ci below only + # installs the TCK's pinned dev dependencies. + run: | + go run ./cmd/domaincraft generate \ + --domain compliance-suite/kitchen-sink.yaml \ + --bridge bridges/typescript/core \ + --output bridges/typescript/core/tck/generated \ + --non-interactive + go run ./cmd/domaincraft generate \ + --domain compliance-suite/kitchen-sink.yaml \ + --bridge bridges/typescript/client \ + --output bridges/typescript/client/tck/generated \ + --non-interactive + + - name: Install ts-core TCK dependencies + working-directory: bridges/typescript/core/tck + run: npm ci + + - name: Certify ts-core (tsc --noEmit + vitest) + working-directory: bridges/typescript/core/tck + # API_URL stays unset: the live-backend interop test is skipped. + run: npm run certify + + - name: Install ts-client TCK dependencies + working-directory: bridges/typescript/client/tck + run: npm ci + + - name: Certify ts-client (tsc --noEmit + vitest) + working-directory: bridges/typescript/client/tck + run: npm run certify + +# k6/Docker and dotnet TCKs stay manual: they need a running backend or SDK +# and are too slow/flaky for PR gates. See the bridge TCK READMEs. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c159bca..69c40dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,8 +59,17 @@ jobs: - name: Build run: go build ./cmd/domaincraft + - 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 -race -count=1 ./... + # Shuffles order because suites mutate package-global seams. + run: go test -race -count=1 -shuffle=on ./... - name: Integration tests run: go test -tags=integration ./internal/bridge diff --git a/Makefile b/Makefile index ed96d9e..6bf29f9 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ endif export GOCACHE := $(GO_CACHE_DIR) export GOTMPDIR := $(GO_TMP_DIR) -.PHONY: help build install run test test-verbose test-coverage lint fmt clean install-deps check-tidy 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-verbose test-coverage lint vet fmt clean install-deps check-tidy 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" @@ -47,16 +47,16 @@ help: @echo " make test - Run all tests" @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 v2.15.0 via go run (same gate as CI)" + @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" install-deps: - @echo "Installing dependencies..." + @echo "Downloading dependencies..." @go mod download - @go mod tidy # Check only: go mod tidy must not mutate go.mod/go.sum in CI. check-tidy: @@ -145,7 +145,11 @@ test-coverage: @echo "Coverage report generated: coverage.html" lint: - @echo "Running linter..." + @echo "Running golangci-lint v2.15.0..." + @go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./... + +vet: + @echo "Running go vet..." @go vet ./... fmt: diff --git a/README.md b/README.md index a707cb3..891951b 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. k6/Docker and dotnet TCKs stay manual — they need a running backend or SDK. See [Certification](https://fellmonkey.github.io/domaincraft-site/docs/guides/certification/). --- 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. From 32ff53c3071f821c9ee51bdd9bd13568910ac220 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:56:01 +0300 Subject: [PATCH 23/83] Bridges: validate fetch branches and preserve update failures - alias CoreContractVersion to specmeta and dedupe embedded path helpers - reject unsafe branch names from cache metadata before git fetch - join fetch, reset, cleanup and re-clone errors - share the monorepo upward walk between resolvers --- compliance-suite/regressions.tsv | 7 ++ internal/bridge/clone.go | 18 +++- internal/bridge/embed.go | 8 +- internal/bridge/embed_test.go | 10 ++ internal/bridge/hardening_test.go | 135 ++++++++++++++++++++++++ internal/bridge/resolve_ext.go | 54 ++++++---- internal/bridge/resolver_test.go | 45 ++++++++ internal/bridge/update.go | 45 ++++++-- internal/bridge/update_contract_test.go | 16 +++ 9 files changed, 303 insertions(+), 35 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 2cee3ac..957a977 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -88,3 +88,10 @@ internal/fsutil/fsutil_test.go::TestAtomicWritePreservesExistingFileMode #5 atom internal/snapshot/rewrite_test.go::TestRewriteFilePreservesExistingMode #5 prune rewrite silently changed permissions of custom files internal/snapshot/hardening_test.go::TestMigrationPlanTableNameMatchesIRForAcronymEntity #5 migration plan and IR derived table names through two different rules internal/snapshot/hardening_test.go::TestCasingVariants #5 four parallel casing tables could drift during entity renames +cmd/domaincraft/commands_prune_test.go::TestPruneCLICleanupFailureKeepsSnapshot #5 prune reported success and advanced the snapshot after a failed cleanup +cmd/domaincraft/commands_hardening_test.go::TestSanitizeCommandLine #5 bridge command lines were displayed with terminal control bytes intact +cmd/domaincraft/commands_update_security_test.go::TestDownloadBinaryChmodFailure #5 self-update ignored a failed chmod on the downloaded binary +cmd/domaincraft/commands_update_security_test.go::TestReplaceExecutableJoinsRenameFailures #5 self-update lost both rename errors and the restore result +internal/bridge/hardening_test.go::TestValidateFetchBranch #5 cache-supplied branch could become a git option during fetch +internal/bridge/hardening_test.go::TestApplyUpdateJoinsFastPathFailureWithCloneFailure #5 update fallback reported only the re-clone failure +internal/bridge/update_contract_test.go::TestCoreContractVersionMatchesSpecmeta #5 bridge contract version had an independent definition diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index 51677e3..b23b3e7 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -1,6 +1,7 @@ package bridge import ( + "errors" "fmt" "os" "os/exec" @@ -95,10 +96,14 @@ func EnsureBridge(entry RegistryEntry, opts *EnsureOptions) (string, error) { 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 { @@ -214,8 +219,11 @@ func CloneBridge(entry RegistryEntry) error { cmd := exec.CommandContext(commandCtx, "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/embed.go b/internal/bridge/embed.go index f4efddd..537ffb6 100644 --- a/internal/bridge/embed.go +++ b/internal/bridge/embed.go @@ -11,6 +11,12 @@ import ( "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 @@ -23,7 +29,7 @@ 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 } diff --git a/internal/bridge/embed_test.go b/internal/bridge/embed_test.go index 817f1b5..42da808 100644 --- a/internal/bridge/embed_test.go +++ b/internal/bridge/embed_test.go @@ -37,6 +37,16 @@ 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) + } +} + func TestEmbeddedContainsRegistryBridges(t *testing.T) { reg := Default() for _, e := range reg.All() { diff --git a/internal/bridge/hardening_test.go b/internal/bridge/hardening_test.go index c690b0f..4f27390 100644 --- a/internal/bridge/hardening_test.go +++ b/internal/bridge/hardening_test.go @@ -312,3 +312,138 @@ func TestHTTPProbeUsesCommandContext(t *testing.T) { 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) { + err := validateFetchBranch(tt.branch) + if (err != nil) != tt.wantErr { + t.Fatalf("validateFetchBranch(%q) = %v, wantErr %v", tt.branch, err, tt.wantErr) + } + if tt.wantErr && !strings.Contains(err.Error(), "invalid fetch branch") { + t.Errorf("error = %q, want it to name the invalid fetch branch", 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{Entry: entry, 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 := filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", "main", "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") + + src := filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, "main") + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", "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) + } +} diff --git a/internal/bridge/resolve_ext.go b/internal/bridge/resolve_ext.go index e34a23e..d4045fc 100644 --- a/internal/bridge/resolve_ext.go +++ b/internal/bridge/resolve_ext.go @@ -38,6 +38,23 @@ func ResolveExtendsRef(ref, fromDir string, resolver *Resolver) (string, error) 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,41 +64,38 @@ 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 - } - parent := filepath.Dir(cur) - if parent == cur { - return "" + found = candidate + return true } - cur = parent - } + 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 { - cur, err := filepath.Abs(dir) + abs, err := filepath.Abs(dir) if err != nil { return "" } - for { + 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") { - return cur + found = cur + return true } } - parent := filepath.Dir(cur) - if parent == cur { - return "" - } - cur = parent - } + return false + }) + return found } // samePath compares two absolute paths using the filesystem's case rules. @@ -105,7 +119,7 @@ func MonorepoRelPath(dir, entryPath string) string { if entryPath == "" || !filepath.IsLocal(filepath.FromSlash(entryPath)) { return "" } - embedded := "bridges/" + filepath.ToSlash(entryPath) + embedded := embeddedBridgeRel(entryPath) if _, err := domaincraft.Bridges.ReadDir(embedded); err != nil { return "" // not a bundled bridge in this binary } @@ -158,7 +172,7 @@ type Status struct { 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 } } diff --git a/internal/bridge/resolver_test.go b/internal/bridge/resolver_test.go index 26c83fe..c20f069 100644 --- a/internal/bridge/resolver_test.go +++ b/internal/bridge/resolver_test.go @@ -94,3 +94,48 @@ func TestLooksLikePath(t *testing.T) { } } } + +// 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/update.go b/internal/bridge/update.go index d46fe88..794af65 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -2,6 +2,7 @@ package bridge import ( "encoding/json" + "errors" "fmt" "net/http" "os" @@ -28,9 +29,10 @@ 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. Any other unreadable value is an error: @@ -142,6 +144,17 @@ func CheckForUpdate(entry RegistryEntry, interval time.Duration) (*Update, error }, nil } +// validateFetchBranch applies the strict git-ref grammar used for pinned refs +// to the branch name passed to `git fetch`. The branch can come from cache +// metadata, so an attacker-controlled value must never become a git option or a +// revision expression. +func validateFetchBranch(branch string) error { + if err := validatePinRef(branch); err != nil { + return fmt.Errorf("invalid fetch branch %q: %w", branch, err) + } + return nil +} + // ApplyUpdate brings a cached bridge up to the upstream default branch, // 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. @@ -164,9 +177,17 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { } else if meta, err := ReadMeta(entry); err == nil && meta != nil && meta.Branch != "" { branch = meta.Branch } + if err := validateFetchBranch(branch); err != nil { + return "", 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. // The manifest must be readable — fail closed when it is not. out, serr := runGit(cacheDir, "show", "FETCH_HEAD:bridge.yaml") @@ -180,18 +201,24 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { if cerr := shouldApplyContract(contract); cerr != nil { return "", cerr } - if _, err := runGit(cacheDir, "reset", "--hard", "FETCH_HEAD"); err == nil { + 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 finishUpdate(entry, branch, pin) } diff --git a/internal/bridge/update_contract_test.go b/internal/bridge/update_contract_test.go index 0adb8f4..9e9355f 100644 --- a/internal/bridge/update_contract_test.go +++ b/internal/bridge/update_contract_test.go @@ -4,8 +4,24 @@ 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 := shouldApplyContract(specmeta.ContractVersion); err != nil { + t.Errorf("contract equal to specmeta version must be accepted: %v", err) + } + if err := shouldApplyContract(specmeta.ContractVersion + 1); err == nil { + t.Error("contract newer than specmeta version must be rejected") + } +} + func TestParseBridgeContractVersion(t *testing.T) { cases := []struct { name string From 9799a7653d4aff163bb264bb3c505a7cb4901c1e Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:56:08 +0300 Subject: [PATCH 24/83] CLI: fail closed on prune errors and harden self-update - --prune returns cleanup failures instead of advancing the snapshot - check chmod and report rename/restore errors during self-update - route progress and warnings through the logger - strip terminal controls from displayed bridge commands - bundle migration context and add prune orchestration tests --- cmd/domaincraft/commands.go | 225 ++++++++--- cmd/domaincraft/commands_hardening_test.go | 90 ++++- cmd/domaincraft/commands_prune_test.go | 374 +++++++++++++++++- .../commands_update_security_test.go | 232 +++++++++++ cmd/domaincraft/update.go | 45 ++- 5 files changed, 886 insertions(+), 80 deletions(-) diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index a1dd408..d613d0d 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -27,6 +27,7 @@ import ( "runtime/debug" "slices" "strings" + "unicode/utf8" "github.com/DomainCraft/DomainCraft/internal/bridge" "github.com/DomainCraft/DomainCraft/internal/fsutil" @@ -380,22 +381,21 @@ func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { } } - // --- 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) - } - - // --- 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 --- + // The warning goes to stderr; the multi-line report is command data and + // stays on stdout so it can be piped. Order is fixed for deterministic runs. + 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.OutOrStdout(), report) + } } // --- Persist the new snapshot --- @@ -770,7 +770,7 @@ func bridgeMetadata(dir string) (id, version string, contractVersion int, err er return "", "", 0, err } if cfg.ContractVersion == 0 { - cfg.ContractVersion = 1 + cfg.ContractVersion = specmeta.ContractVersion } return cfg.Name, cfg.Version, cfg.ContractVersion, nil } @@ -861,13 +861,15 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co } 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). + // 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, command) + _, _ = fmt.Fprintf(out, " %d) %s\n", i+1, sanitizeCommandLine(command)) } for i, command := range cfg.Commands { - log.Info("Migration %d/%d: %s", i+1, len(cfg.Commands), command) + log.Info("Migration %d/%d: %s", i+1, len(cfg.Commands), sanitizeCommandLine(command)) var argv []string var shell string if runtime.GOOS == "windows" { @@ -889,6 +891,63 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co 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\\)?|[@-_])`) + +// sanitizeCommandLine removes terminal control characters from a bridge-declared +// command before it is displayed or logged. Tab and newline are kept; C0 (other +// than those two), C1, CSI/OSC sequences, bare ESC and invalid UTF-8 bytes are +// dropped. 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 { + if (c < 0x20 && c != '\t' && c != '\n') || 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 + } + 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 +} + +// 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 @@ -900,11 +959,16 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co // (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 } - out := cmd.OutOrStdout() + mc := migrationContext{opts: opts, fresh: fresh, log: log, out: cmd.OutOrStdout()} + var failures []error // In --prune mode the tool owns the whole cleanup, so it also rewrites // identifier references in developer-owned files: the project's root @@ -914,31 +978,33 @@ func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[stri if opts.prune { if diff.NamespaceRename != nil { for _, rel := range diff.NamespaceRename.Files { - if fresh[rel] { + if mc.fresh[rel] { continue } rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.NamespaceTransform(diff.NamespaceRename)) if err != nil { - log.Warn("could not rewrite namespace in %s: %v", rel, err) + mc.log.Warn("could not rewrite namespace in %s: %v", rel, err) + failures = append(failures, fmt.Errorf("rewrite namespace in %s: %w", rel, err)) continue } if rewrote { - _, _ = fmt.Fprintf(out, " ▸ updated namespace %s -> %s in %s\n", diff.NamespaceRename.OldNamespace, diff.NamespaceRename.NewNamespace, rel) + 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 fresh[rel] { + if mc.fresh[rel] { continue } rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.FieldTransform(fr)) if err != nil { - log.Warn("could not rewrite field references in %s: %v", rel, err) + mc.log.Warn("could not rewrite field references in %s: %v", rel, err) + failures = append(failures, fmt.Errorf("rewrite field references in %s: %w", rel, err)) continue } if rewrote { - _, _ = fmt.Fprintf(out, " ▸ updated field %s -> %s in %s\n", fr.OldField, fr.NewField, rel) + mc.log.Info("updated field %s -> %s in %s", fr.OldField, fr.NewField, rel) } } } @@ -949,9 +1015,14 @@ func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[stri if len(del.Files) == 0 { continue } - done, err := handleDeletedEntity(opts, del, fresh, log, out) + done, err := handleDeletedEntity(mc, del) if err != nil { - return false, err + if !opts.prune { + return false, err + } + failures = append(failures, err) + applied = false + continue } applied = applied && done } @@ -960,12 +1031,20 @@ func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[stri if len(ren.Files) == 0 { continue } - done, err := handleRename(opts, ren, diff, fresh, log, out) + done, err := handleRename(mc, ren, diff) if err != nil { - return false, err + if !opts.prune { + return false, err + } + failures = append(failures, err) + applied = false + continue } applied = applied && done } + if err := errors.Join(failures...); err != nil { + return false, err + } return applied, nil } @@ -996,31 +1075,39 @@ func chooseMigrationFiles(opts *cliOptions, files []snapshot.FileRef, prompt fun // 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(opts *cliOptions, del snapshot.DeletedEntity, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { - if !opts.prune && (opts.nonInteractive || !isTerminal()) { - log.Warn("Entity %q was removed from domain.yaml — orphaned files kept (re-run with --prune to delete):", del.Name) +// deferred (non-interactive without --prune). Under --prune, delete failures are +// returned so the snapshot is not advanced past an unrecoverable cleanup. +func handleDeletedEntity(mc migrationContext, del snapshot.DeletedEntity) (bool, error) { + if cleanupDeferred(mc.opts) { + mc.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)) + _, _ = fmt.Fprintf(mc.out, " - %s%s\n", f.Path, customMark(f)) } return false, nil } - selected, err := chooseMigrationFiles(opts, del.Files, func(choices []interactive.FileChoice) ([]string, error) { + selected, err := chooseMigrationFiles(mc.opts, del.Files, func(choices []interactive.FileChoice) ([]string, error) { return interactive.PromptDeleteFiles(del.Name, choices) }) if err != nil { return false, err } + var failures []error for _, f := range del.Files { - if !selected[f.Path] || fresh[f.Path] { + if !selected[f.Path] || mc.fresh[f.Path] { continue } - if err := snapshot.DeleteFile(opts.outputDir, f.Path); err != nil { - log.Warn("could not delete %s: %v", f.Path, err) + if err := snapshot.DeleteFile(mc.opts.outputDir, f.Path); err != nil { + mc.log.Warn("could not delete %s: %v", f.Path, err) + if mc.opts.prune { + failures = append(failures, fmt.Errorf("delete %s: %w", f.Path, err)) + } continue } - _, _ = fmt.Fprintf(out, " ▸ deleted %s\n", f.Path) + mc.log.Info("deleted %s", f.Path) + } + if err := errors.Join(failures...); err != nil { + return false, err } return true, nil } @@ -1030,58 +1117,74 @@ func handleDeletedEntity(opts *cliOptions, del snapshot.DeletedEntity, fresh map // 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(opts *cliOptions, ren snapshot.Rename, d *snapshot.Diff, fresh map[string]bool, log *logger.Logger, out io.Writer) (bool, error) { - if !opts.prune && (opts.nonInteractive || !isTerminal()) { - log.Warn("Entity %q was renamed to %q — files kept (re-run with --prune to rename):", ren.OldName, ren.NewName) +func handleRename(mc migrationContext, ren snapshot.Rename, d *snapshot.Diff) (bool, error) { + if cleanupDeferred(mc.opts) { + mc.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)) + _, _ = fmt.Fprintf(mc.out, " - %s -> %s\n", f.Path, snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName)) } return false, nil } - selected, err := chooseMigrationFiles(opts, ren.Files, func(choices []interactive.FileChoice) ([]string, error) { + selected, err := chooseMigrationFiles(mc.opts, ren.Files, func(choices []interactive.FileChoice) ([]string, error) { return interactive.PromptRenameFiles(ren.OldName, ren.NewName, choices) }) if err != nil { return false, err } + var failures []error for _, f := range ren.Files { - if !selected[f.Path] || fresh[f.Path] { + if !selected[f.Path] || mc.fresh[f.Path] { continue } if f.Custom { newRel := snapshot.RenameRelPath(f.Path, ren.OldName, ren.NewName) - if fresh[newRel] { + 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. - if err := os.Remove(filepath.Join(opts.outputDir, filepath.FromSlash(newRel))); err != nil { - log.Warn("could not replace scaffolded %s: %v", newRel, err) + if err := os.Remove(filepath.Join(mc.opts.outputDir, filepath.FromSlash(newRel))); err != nil { + mc.log.Warn("could not replace scaffolded %s: %v", newRel, err) + if mc.opts.prune { + failures = append(failures, fmt.Errorf("replace scaffolded %s: %w", newRel, err)) + } continue } } - newRel, renamed, err := snapshot.RenameEntityFile(opts.outputDir, f.Path, ren.OldName, ren.NewName) + newRel, renamed, err := snapshot.RenameEntityFile(mc.opts.outputDir, f.Path, ren.OldName, ren.NewName) if err != nil { - log.Warn("could not rename %s: %v", f.Path, err) + mc.log.Warn("could not rename %s: %v", f.Path, err) + if mc.opts.prune { + failures = append(failures, fmt.Errorf("rename %s: %w", f.Path, err)) + } continue } if renamed { - if rewrote, rerr := snapshot.RewriteFile(opts.outputDir, newRel, snapshot.RenameTransforms(ren.OldName, ren.NewName, d)...); rerr != nil { - log.Warn("could not rewrite content of %s: %v", newRel, rerr) + if rewrote, rerr := snapshot.RewriteFile(mc.opts.outputDir, newRel, snapshot.RenameTransforms(ren.OldName, ren.NewName, d)...); rerr != nil { + mc.log.Warn("could not rewrite content of %s: %v", newRel, rerr) + if mc.opts.prune { + failures = append(failures, fmt.Errorf("rewrite content of %s: %w", newRel, rerr)) + } } else if rewrote { - _, _ = fmt.Fprintf(out, " ▸ renamed %s -> %s (content updated)\n", f.Path, newRel) + mc.log.Info("renamed %s -> %s (content updated)", f.Path, newRel) continue } - _, _ = fmt.Fprintf(out, " ▸ renamed %s -> %s\n", f.Path, newRel) + mc.log.Info("renamed %s -> %s", f.Path, newRel) } continue } // Generated files have been regenerated under the new name — remove the stale copy. - if err := snapshot.DeleteFile(opts.outputDir, f.Path); err != nil { - log.Warn("could not delete stale generated file %s: %v", f.Path, err) + if err := snapshot.DeleteFile(mc.opts.outputDir, f.Path); err != nil { + mc.log.Warn("could not delete stale generated file %s: %v", f.Path, err) + if mc.opts.prune { + failures = append(failures, fmt.Errorf("delete stale generated file %s: %w", f.Path, err)) + } continue } - _, _ = fmt.Fprintf(out, " ▸ removed stale generated file %s\n", f.Path) + mc.log.Info("removed stale generated file %s", f.Path) + } + if err := errors.Join(failures...); err != nil { + return false, err } return true, nil } @@ -1133,11 +1236,11 @@ func loadAndValidate(opts *cliOptions, cmd *cobra.Command) (*parser.ParsedSchema return nil, err } - errOut := cmd.ErrOrStderr() + log := commandLogger(cmd) hardErrors := make([]error, 0) for _, e := range validator.New(schema).Validate() { if e.Warning { - _, _ = fmt.Fprintf(errOut, "⚠ %s\n", e.Error()) + log.Warn("%s", e.Error()) continue } hardErrors = append(hardErrors, e) diff --git a/cmd/domaincraft/commands_hardening_test.go b/cmd/domaincraft/commands_hardening_test.go index 1a83038..cf7ed18 100644 --- a/cmd/domaincraft/commands_hardening_test.go +++ b/cmd/domaincraft/commands_hardening_test.go @@ -7,10 +7,12 @@ import ( "io" "os" "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" @@ -93,7 +95,8 @@ func TestMigrationCleanupDeferredOnTTYWhenNonInteractive(t *testing.T) { log.SetWriter(&logOut) var fileOut bytes.Buffer - applied, err := handleDeletedEntity(opts, snapshotDeleted(rel), map[string]bool{}, log, &fileOut) + mc := migrationContext{opts: opts, fresh: map[string]bool{}, log: log, out: &fileOut} + applied, err := handleDeletedEntity(mc, snapshotDeleted(rel)) if err != nil || applied { t.Fatalf("handleDeletedEntity = %v, %v; want false, nil", applied, err) } @@ -120,7 +123,8 @@ func TestMigrationCleanupDeferredOnTTYWhenNonInteractive(t *testing.T) { log.SetWriter(&logOut) var fileOut bytes.Buffer - applied, err := handleRename(opts, snapshotRename(rel), nil, map[string]bool{}, log, &fileOut) + 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) } @@ -133,6 +137,88 @@ func TestMigrationCleanupDeferredOnTTYWhenNonInteractive(t *testing.T) { }) } +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") + } +} + +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 Привет"}, + } + 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 !strings.Contains(stdout.String(), "echo SAFE") || !strings.Contains(stderr.String(), "echo SAFE") { + t.Fatalf("command was not displayed: stdout=%q stderr=%q", stdout.String(), stderr.String()) + } + if strings.Contains(stdout.String(), "\x1b") { + t.Errorf("raw escape byte reached stdout: %q", stdout.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 TestLoadAndValidateSendsDiagnosticsToStderr(t *testing.T) { cases := []struct { name string diff --git a/cmd/domaincraft/commands_prune_test.go b/cmd/domaincraft/commands_prune_test.go index 98a0c06..46186ae 100644 --- a/cmd/domaincraft/commands_prune_test.go +++ b/cmd/domaincraft/commands_prune_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "encoding/json" "os" "path/filepath" "strings" @@ -10,12 +11,14 @@ import ( "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. The CLI orchestration was -// previously untested, so a dropped field rename could leave stale names. +// 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} @@ -36,10 +39,13 @@ func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { }}} cmd := &cobra.Command{} - var out bytes.Buffer - cmd.SetOut(&out) + 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{}, nil, cmd) + applied, err := applyMigrationActions(opts, diff, map[string]bool{}, log, cmd) if err != nil || !applied { t.Fatalf("applyMigrationActions = %v, %v; want true, nil", applied, err) } @@ -50,8 +56,11 @@ func TestApplyMigrationActionsRewritesFieldRenames(t *testing.T) { if string(data) != "class ItemService { public string Name; var name = 1; }" { t.Fatalf("custom file not rewritten: %q", data) } - if !strings.Contains(out.String(), "updated field title -> name") { - t.Fatalf("missing report line: %q", out.String()) + 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()) } } @@ -105,3 +114,354 @@ func TestChooseMigrationFiles(t *testing.T) { } }) } + +// --- 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: "could not rewrite field references", + }, + { + 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: "could not delete", + }, + } + + 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) + } + if !strings.Contains(stderr, tt.wantDiag) { + t.Errorf("stderr = %q, want %q", stderr, tt.wantDiag) + } + 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) + } + requireAbsent(t, marker(output)) + }) +} + +// TestPruneCLIReportStreams asserts F18: diagnostics (warnings, progress) go to +// stderr through the logger; the multi-line refactoring reports go to stdout. +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"} { + if !strings.Contains(stdout, want) { + t.Errorf("report missing from stdout: %q; stdout = %q", want, stdout) + } + } + if !strings.Contains(stderr, "ACTION REQUIRED") || !strings.Contains(stderr, "updated field title -> name") { + t.Errorf("warnings/progress missing from stderr: %q", stderr) + } + if strings.Contains(stdout, "updated field title -> name") { + t.Errorf("progress leaked to stdout: %q", stdout) + } +} diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go index fde7e01..f396c43 100644 --- a/cmd/domaincraft/commands_update_security_test.go +++ b/cmd/domaincraft/commands_update_security_test.go @@ -10,6 +10,7 @@ import ( "net/url" "os" "path/filepath" + "runtime" "strings" "testing" @@ -401,3 +402,234 @@ func TestRunCoreUpdateFailsClosed(t *testing.T) { }) } } + +// --- F03: failed installs must be reported, never presented as success --- + +func stubFileOps(t *testing.T) { + t.Helper() + oldChmod, oldRename, oldRemove := chmodFn, renameFn, removeFn + t.Cleanup(func() { chmodFn, renameFn, removeFn = oldChmod, oldRename, oldRemove }) +} + +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") + } + stubFileOps(t) + oldHTTP := httpGetBodyFn + httpGetBodyFn = func(string) ([]byte, error) { return []byte("binary"), nil } + t.Cleanup(func() { httpGetBodyFn = oldHTTP }) + + chmodErr := errors.New("chmod denied") + chmodFn = func(string, os.FileMode) error { return chmodErr } + path, err := downloadBinary("https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64") + 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) + } +} + +func TestReplaceExecutableJoinsRenameFailures(t *testing.T) { + 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 + renameFn = 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 := replaceExecutable(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) { + 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 + renameFn = func(src, dst string) error { + calls++ + if calls == 1 || calls == 3 { + return errors.New("rename failed") + } + return os.Rename(src, dst) + } + err := replaceExecutable(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) { + 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) + } + + removeFn = func(path string) error { + if path == exe+".old" { + return errors.New("backup is locked") + } + return os.Remove(path) + } + renameFn = func(src, dst string) error { + if src == tmp { + return errors.New("locked") + } + t.Error("no rename should happen when the backup cannot be removed") + return nil + } + err := replaceExecutable(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) { + 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 + renameFn = func(src, dst string) error { + renames++ + if renames == 1 { + return errors.New("locked") + } + return os.Rename(src, dst) + } + removals := 0 + removeFn = func(path string) error { + removals++ + if removals == 2 { + return errors.New("backup cleanup failed") + } + return os.Remove(path) + } + err := replaceExecutable(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) { + stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", assets, bodies)) + replaceErr := errors.New("disk full") + calls := 0 + replaceExecutableFn = func(string, string) error { + calls++ + return replaceErr + } + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + err := runCoreUpdate(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 := stubUpdateRun(t, "v1.0.0", fakeUpdateServer("v1.2.0", assets, bodies)) + var logOut bytes.Buffer + log := logger.New() + log.SetWriter(&logOut) + err := runCoreUpdate(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.go b/cmd/domaincraft/update.go index 6191d28..78bb29c 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -4,6 +4,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -57,6 +58,9 @@ var httpGetBodyFn = httpGetBody var ( executableFn = os.Executable replaceExecutableFn = replaceExecutable + chmodFn = os.Chmod + renameFn = os.Rename + removeFn = os.Remove ) // githubRelease is the subset of the GitHub releases/latest payload we need. @@ -206,7 +210,8 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { if err := replaceExecutableFn(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 } @@ -395,7 +400,11 @@ func downloadBinary(rawURL string) (string, error) { return "", err } if runtime.GOOS != "windows" { - _ = os.Chmod(tmp.Name(), 0o755) //nolint:gosec // the downloaded binary must be executable + // A non-executable download must never reach the install step. + if err := chmodFn(tmp.Name(), 0o755); err != nil { //nolint:gosec // the downloaded binary must be executable + _ = os.Remove(tmp.Name()) + return "", fmt.Errorf("make downloaded update executable: %w", err) + } } return tmp.Name(), nil } @@ -404,18 +413,34 @@ func downloadBinary(rawURL string) (string, error) { // 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 { + // 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 := renameFn(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; replace %s manually or run go install: %w", exe, err) + if err := removeFn(old); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove previous backup %s: %w", old, err) + } + if err := renameFn(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 := renameFn(tmp, exe); err != nil { + restoreErr := renameFn(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 := removeFn(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 } From 813fc9f156b8f6fb509ff254bbffbb6ea364d363 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:01:51 +0300 Subject: [PATCH 25/83] Parser: keep explicit numeric zeros in domain.yaml - record key presence for numeric config blocks instead of testing value == 0 - apply defaults only to omitted keys - accept explicit zeros in validator while still rejecting negatives - cover YAML merges and strict unknown-key behavior --- compliance-suite/regressions.tsv | 2 + internal/parser/models.go | 156 +++++++++++++++++++++- internal/parser/parser_test.go | 190 +++++++++++++++++++++++++++ internal/validator/validator.go | 21 +-- internal/validator/validator_test.go | 91 +++++++++++++ 5 files changed, 447 insertions(+), 13 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 957a977..23028ab 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -95,3 +95,5 @@ cmd/domaincraft/commands_update_security_test.go::TestReplaceExecutableJoinsRena internal/bridge/hardening_test.go::TestValidateFetchBranch #5 cache-supplied branch could become a git option during fetch internal/bridge/hardening_test.go::TestApplyUpdateJoinsFastPathFailureWithCloneFailure #5 update fallback reported only the re-clone failure internal/bridge/update_contract_test.go::TestCoreContractVersionMatchesSpecmeta #5 bridge contract version had an independent definition +internal/parser/parser_test.go::TestParseRawSchemaExplicitZerosPreserved #5 explicit zero numeric settings were replaced by defaults +internal/validator/validator_test.go::TestValidateAcceptsExplicitZeroProjectNumericValues #5 explicit zero rate-limit and pagination values were rejected diff --git a/internal/parser/models.go b/internal/parser/models.go index 968a2ad..44fe8c9 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -84,6 +84,72 @@ 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 +} + +// yamlMergeKeyNames returns the key names contributed by a YAML merge value +// ("<<"), which is either an alias to a mapping or a sequence of such aliases. +// The alias decode below 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 + var collect func(*yaml.Node) + collect = func(node *yaml.Node) { + switch node.Kind { + case yaml.AliasNode: + if node.Alias != nil { + collect(node.Alias) + } + case yaml.SequenceNode: + for _, item := range node.Content { + collect(item) + } + case yaml.MappingNode: + for i := 0; i < len(node.Content)-1; i += 2 { + names = append(names, node.Content[i].Value) + } + } + } + collect(value) + return names +} + +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 { + if value.Kind != yaml.MappingNode { + return value.Decode((*deployConfigAlias)(d)) + } + for i := 0; i < len(value.Content)-1; i += 2 { + key := value.Content[i] + switch key.Value { + case "port": + d.portSet = true + case "domain": + // no presence flag needed: the empty string default is unambiguous + case "<<": + if key.Tag != "!!str" { + for _, name := range yamlMergeKeyNames(value.Content[i+1]) { + if name == "port" { + d.portSet = true + } + } + continue + } + // A quoted "<<" is a regular key, not a merge, and falls through. + fallthrough + default: + // 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 this block. + return fmt.Errorf("line %d: field %s not found in type parser.DeployConfig", key.Line, key.Value) + } + } + return value.Decode((*deployConfigAlias)(d)) } // CacheConfig represents cache configuration (agnostic — no language/platform specifics). @@ -112,12 +178,92 @@ 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 { + if value.Kind != yaml.MappingNode { + return value.Decode((*rateLimitConfigAlias)(r)) + } + for i := 0; i < len(value.Content)-1; i += 2 { + key := value.Content[i] + switch key.Value { + case "permit_limit": + r.permitLimitSet = true + case "window_seconds": + r.windowSecondsSet = true + case "enabled", "policy": + // no presence flags needed: these defaults are unambiguous + case "<<": + if key.Tag != "!!str" { + for _, name := range yamlMergeKeyNames(value.Content[i+1]) { + switch name { + case "permit_limit": + r.permitLimitSet = true + case "window_seconds": + r.windowSecondsSet = true + } + } + continue + } + fallthrough + default: + return fmt.Errorf("line %d: field %s not found in type parser.RateLimitConfig", key.Line, key.Value) + } + } + return value.Decode((*rateLimitConfigAlias)(r)) } // 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 { + if value.Kind != yaml.MappingNode { + return value.Decode((*paginationConfigAlias)(p)) + } + for i := 0; i < len(value.Content)-1; i += 2 { + key := value.Content[i] + switch key.Value { + case "default_page_size": + p.defaultPageSizeSet = true + case "max_page_size": + p.maxPageSizeSet = true + case "<<": + if key.Tag != "!!str" { + for _, name := range yamlMergeKeyNames(value.Content[i+1]) { + switch name { + case "default_page_size": + p.defaultPageSizeSet = true + case "max_page_size": + p.maxPageSizeSet = true + } + } + continue + } + fallthrough + default: + return fmt.Errorf("line %d: field %s not found in type parser.PaginationConfig", key.Line, key.Value) + } + } + return value.Decode((*paginationConfigAlias)(p)) } // MultiTenancyConfig holds multi-tenancy settings @@ -273,7 +419,7 @@ func ParseRawSchema(data []byte) (*RawSchema, error) { 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 +441,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 +452,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/parser_test.go b/internal/parser/parser_test.go index b7c5ca8..acf1852 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -72,6 +72,36 @@ 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) { @@ -785,3 +815,163 @@ entities: }) } } + +// 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) + } +} diff --git a/internal/validator/validator.go b/internal/validator/validator.go index e482667..b374065 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -203,23 +203,28 @@ func (v *Validator) validateProject() []ValidationError { errs = append(errs, warn("", "", "rate_limit.permit_limit must be non-negative")) } - if p.RateLimit.WindowSeconds < 1 { + // 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" + // by the time the validator sees it. + if p.RateLimit.WindowSeconds < 0 { errs = append(errs, warn("", "", - "rate_limit.window_seconds must be at least 1")) + "rate_limit.window_seconds must be non-negative")) } } - // Pagination + // Pagination. An explicit 0 is a meaningful value (no default / no cap); + // only negatives are invalid. Omitted keys are defaulted by the parser. if p.Pagination != nil { - if p.Pagination.DefaultPageSize < 1 { + if p.Pagination.DefaultPageSize < 0 { errs = append(errs, warn("", "", - "pagination.default_page_size must be at least 1")) + "pagination.default_page_size must be non-negative")) } - if p.Pagination.MaxPageSize < 1 { + if p.Pagination.MaxPageSize < 0 { errs = append(errs, warn("", "", - "pagination.max_page_size must be at least 1")) + "pagination.max_page_size must be non-negative")) } - if p.Pagination.DefaultPageSize > p.Pagination.MaxPageSize { + if p.Pagination.DefaultPageSize > 0 && p.Pagination.MaxPageSize > 0 && + p.Pagination.DefaultPageSize > p.Pagination.MaxPageSize { errs = append(errs, warnf("", "", "pagination.default_page_size (%d) must not exceed max_page_size (%d)", p.Pagination.DefaultPageSize, p.Pagination.MaxPageSize)) diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index 7ccf109..17d8d6c 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -2668,3 +2668,94 @@ func TestValidateAcceptsValidEntityOldName(t *testing.T) { 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) + } + }) + } +} From e92166698704f5649b206e1bef2db700af2f94f4 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:12:45 +0300 Subject: [PATCH 26/83] Core: remove quadratic scans and add pipeline benchmarks - index inverse dependencies in the entity topological sort - index outbound relations for hub-heavy models - derive custom file paths once in the snapshot diff - back up existing outputs by rename instead of reading them - add benchmarks for sort, diff and warm render - cover relative-dir symlink rejection and rollback edge case --- compliance-suite/regressions.tsv | 3 + internal/ir/build_relations.go | 87 +++++++----- internal/ir/build_relations_bench_test.go | 166 ++++++++++++++++++++++ internal/ir/toposort.go | 36 +++-- internal/renderer/hardening_test.go | 130 +++++++++++++++++ internal/renderer/render.go | 83 ++++++++--- internal/renderer/render_bench_test.go | 60 ++++++++ internal/snapshot/snapshot.go | 29 ++-- internal/snapshot/snapshot_bench_test.go | 91 ++++++++++++ 9 files changed, 601 insertions(+), 84 deletions(-) create mode 100644 internal/ir/build_relations_bench_test.go create mode 100644 internal/renderer/render_bench_test.go create mode 100644 internal/snapshot/snapshot_bench_test.go diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 23028ab..50e8e34 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -97,3 +97,6 @@ internal/bridge/hardening_test.go::TestApplyUpdateJoinsFastPathFailureWithCloneF internal/bridge/update_contract_test.go::TestCoreContractVersionMatchesSpecmeta #5 bridge contract version had an independent definition internal/parser/parser_test.go::TestParseRawSchemaExplicitZerosPreserved #5 explicit zero numeric settings were replaced by defaults internal/validator/validator_test.go::TestValidateAcceptsExplicitZeroProjectNumericValues #5 explicit zero rate-limit and pagination values were rejected +internal/renderer/hardening_test.go::TestRenderRejectsSymlinkWithRelativeBridgeDir #5 relative bridge directory bypassed the symlink containment check +internal/renderer/hardening_test.go::TestRenderRollbackRemovesTargetDeletedBeforeCommit #5 rollback wrote empty bytes when a target disappeared between staging and commit +internal/ir/build_relations_bench_test.go::TestBuildHubRelationsPreservesFirstMatch #5 relation indexing changed first-match semantics on hub entities diff --git a/internal/ir/build_relations.go b/internal/ir/build_relations.go index 0df060a..a56126f 100644 --- a/internal/ir/build_relations.go +++ b/internal/ir/build_relations.go @@ -45,6 +45,45 @@ func buildForwardRelations(entities []Entity, schema *parser.ParsedSchema, entit 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 @@ -52,6 +91,7 @@ func buildForwardRelations(entities []Entity, schema *parser.ParsedSchema, entit // collection navigation. Without this reconciliation a bridge would generate a // spurious join table in addition to the FK. func reconcileOneToMany(entities []Entity) { + index := indexRelationsOut(entities) for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -59,7 +99,10 @@ func reconcileOneToMany(entities []Entity) { 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] + } if pair == nil { continue } @@ -76,6 +119,7 @@ func reconcileOneToMany(entities []Entity) { // 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 []Entity) { + index := indexRelationsOut(entities) for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -83,10 +127,9 @@ func resolveInverseNavs(entities []Entity) { 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) } } } @@ -97,6 +140,7 @@ func resolveInverseNavs(entities []Entity) { // incoming relation is a collection navigation on the target that points back // to the owning entity. func buildIncomingRelations(entities []Entity) { + index := indexRelationsOut(entities) usedInverse := make(map[string]map[string]bool) // target entity -> defined inverse nav names for i := range entities { entity := &entities[i] @@ -113,7 +157,7 @@ func buildIncomingRelations(entities []Entity) { } // 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 @@ -142,34 +186,3 @@ func buildIncomingRelations(entities []Entity) { } } } - -// 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 *Entity, sourceName string) *Relation { - 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 *Entity, 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 -} diff --git a/internal/ir/build_relations_bench_test.go b/internal/ir/build_relations_bench_test.go new file mode 100644 index 0000000..b34f076 --- /dev/null +++ b/internal/ir/build_relations_bench_test.go @@ -0,0 +1,166 @@ +package ir + +import ( + "fmt" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/lexer" + "github.com/DomainCraft/DomainCraft/internal/parser" +) + +// benchmarkChainEntities builds a dependency chain: entity i depends on i-1. +// Every pop scans every entity today, so this is the worst case for sortEntities. +func benchmarkChainEntities(n int) []Entity { + entities := make([]Entity, n) + for i := range entities { + entities[i] = Entity{Name: fmt.Sprintf("E%04d", i)} + } + for i := 1; i < n; i++ { + entities[i].RelationsOut = []Relation{{ + FieldName: "parent", + TargetEntity: &entities[i-1], + 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 := benchmarkChainEntities(size) + for b.Loop() { + _ = sortEntities(entities) + } + }) + // Fan-out: one pop makes every other entity ready at once, so each + // insertion re-sorts a growing ready queue. + b.Run(fmt.Sprintf("fanout/%d", size), func(b *testing.B) { + entities := make([]Entity, size) + for i := range entities { + entities[i] = Entity{Name: fmt.Sprintf("E%04d", i)} + } + for i := 1; i < size; i++ { + entities[i].RelationsOut = []Relation{{ + FieldName: "root", + TargetEntity: &entities[0], + IsMany: false, + }} + } + for b.Loop() { + _ = sortEntities(entities) + } + }) + } +} + +// 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 := 0; i < n; i++ { + 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) + } + } + }) + } +} + +// 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/toposort.go b/internal/ir/toposort.go index ee996fe..729430d 100644 --- a/internal/ir/toposort.go +++ b/internal/ir/toposort.go @@ -1,6 +1,9 @@ package ir -import "slices" +import ( + "slices" + "sort" +) // sortEntities reorders the slice by FK dependencies using Kahn's algorithm. // The order is deterministic: ties are broken by entity name. @@ -14,16 +17,21 @@ func sortEntities(entities []Entity) []Entity { } // 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) } @@ -36,6 +44,10 @@ func sortEntities(entities []Entity) []Entity { } // Deterministic ordering: process ready entities in name order. slices.Sort(ready) + insertReady := func(name string) { + at := sort.Search(len(ready), func(i int) bool { return ready[i] >= name }) + ready = slices.Insert(ready, at, name) + } order := make([]string, 0, len(entities)) for len(ready) > 0 { @@ -43,15 +55,13 @@ func sortEntities(entities []Entity) []Entity { 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. + // The binary insert keeps the queue sorted, so the emitted order is + // unchanged from sorting the whole queue after every insertion. + for _, i := range dependents[name] { + inDegree[i]-- + if inDegree[i] == 0 { + insertReady(entities[i].Name) } } } diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index a1869e6..e722b1d 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -73,6 +73,73 @@ templates: } } +// 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() + 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 := writeHardeningBridge(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) { @@ -176,6 +243,69 @@ templates: } } +// F24: a target that existed at staging but was deleted before commit must be +// rolled back as a new file (removed). Otherwise the nil original bytes are +// written back and an empty file survives the failed render. +func TestRenderRollbackRemovesTargetDeletedBeforeCommit(t *testing.T) { + base := t.TempDir() + bridge := writeHardeningBridge(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) + } + beforeCommitHook = 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() { beforeCommitHook = 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) +} + func assertNoRenderTemps(t *testing.T, dir string) { t.Helper() entries, err := os.ReadDir(dir) diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 6a878f6..c3373de 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -59,12 +59,20 @@ func safeOutputPath(outputDir, renderedTarget string) (string, error) { return absTarget, nil } +// beforeCommitHook is a test seam called once between staging and commit. It is +// nil in production; tests set it to mutate the filesystem at that exact point. +// Tests using it must not run in parallel. +var beforeCommitHook func() + // stagedWrite is a fully rendered file held in a temp file next to its target. -// original holds the target's bytes from before this run so a later failure can -// restore them; existed=false means the target was created by this run. +// backup is the rename-aside path of the previous target, created only at +// commit time; existed=false means the target was created by this run. +// original is retained for callers that invoke rollbackWrites directly with +// in-memory bytes; Render itself no longer reads existing targets up front. type stagedWrite struct { temp string target string + backup string original []byte existed bool mode os.FileMode @@ -78,6 +86,14 @@ type stagedWrite struct { 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. + if err := os.Rename(w.backup, w.target); err != nil { + failures = append(failures, fmt.Errorf("restore %s: %w", w.target, err)) + } + continue + } if w.existed { if err := fsutil.AtomicWrite(w.target, w.original); err != nil { failures = append(failures, fmt.Errorf("restore %s: %w", w.target, err)) @@ -258,17 +274,14 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re existed := false mode := os.FileMode(0o644) // os.Create's default under the usual umask - var original []byte if info, statErr := os.Lstat(absTarget); statErr == nil { if info.Mode()&os.ModeSymlink != 0 { return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget)) } existed = true mode = info.Mode().Perm() - original, err = os.ReadFile(absTarget) //nolint:gosec // absTarget passed safeOutputPath validation - if err != nil { - return fail(fmt.Errorf("read existing output %s: %w", renderedTarget, err)) - } + // The previous bytes are not read here: phase 2 moves the + // whole file aside and moves it back on rollback. } else if !errors.Is(statErr, os.ErrNotExist) { return fail(fmt.Errorf("inspect output file %s: %w", renderedTarget, statErr)) } @@ -297,12 +310,11 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re return fail(fmt.Errorf("close temp output %s: %w", tmpPath, err)) } staged = append(staged, stagedWrite{ - temp: tmpPath, - target: absTarget, - original: original, - existed: existed, - mode: mode, - record: record, + temp: tmpPath, + target: absTarget, + existed: existed, + mode: mode, + record: record, }) manifest = append(manifest, record) } @@ -310,18 +322,51 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } } - // Phase 2: commit staged files. A failed rename rolls back every file that - // was already replaced, so callers never observe a partially updated tree. + // Phase 2: commit staged files. An existing target is renamed aside into a + // sibling backup before the rendered temp file takes its place. Rollback + // renames the backup back, so no prior content is ever read into memory. + if beforeCommitHook != nil { + beforeCommitHook() + } for _, w := range staged { - if info, err := os.Lstat(w.target); err == nil && info.Mode()&os.ModeSymlink != 0 { - return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) - } else if err != nil && !errors.Is(err, os.ErrNotExist) { + if info, err := os.Lstat(w.target); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) + } + // The staged temp name is already unique in this directory. + backup := w.temp + ".bak" + if err := os.Rename(w.target, backup); err != nil { + return fail(fmt.Errorf("back up output file %s: %w", w.record.Path, err)) + } + w.backup = backup + w.existed = true + w.mode = info.Mode().Perm() + } else if errors.Is(err, os.ErrNotExist) { + // The target vanished after staging. Restore the pre-commit state: + // this is now a new file, so rollback must remove it, not write nil + // bytes through the staging-time `existed` flag. + w.existed = false + w.backup = "" + } else { return 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. + committed = append(committed, w) if err := os.Rename(w.temp, w.target); err != nil { return fail(fmt.Errorf("commit output file %s: %w", w.record.Path, err)) } - committed = append(committed, w) + } + + // Backups are only needed until every file has landed. Keep the render + // successful even if a leftover backup cannot be removed; the generated + // files are already correct and rollback must not consume the backups now. + for _, w := range committed { + if w.backup != "" { + if err := os.Remove(w.backup); err != nil && !errors.Is(err, os.ErrNotExist) && r.log != nil { + r.log.Warn("remove backup %s: %v", w.backup, err) + } + } } written := make([]string, 0, len(committed)) diff --git a/internal/renderer/render_bench_test.go b/internal/renderer/render_bench_test.go new file mode 100644 index 0000000..9c35c24 --- /dev/null +++ b/internal/renderer/render_bench_test.go @@ -0,0 +1,60 @@ +package renderer + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +// 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) { + dir := b.TempDir() + bridgeDir := filepath.Join(dir, "bridge") + if err := os.MkdirAll(filepath.Join(bridgeDir, "templates"), 0o755); err != nil { + b.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 { + b.Fatal(err) + } + if err := os.WriteFile(filepath.Join(bridgeDir, "templates", "entity.tmpl"), []byte("generated {{ .Entity.Name }}\n"), 0o644); err != nil { + b.Fatal(err) + } + out := filepath.Join(dir, "out") + project := &ir.Project{Name: "Bench"} + for i := 0; i < size; i++ { + 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 { + b.Fatal(err) + } + if err := os.WriteFile(target, []byte("previous\n"), 0o644); err != nil { + b.Fatal(err) + } + } + r, err := New(bridgeDir, nil) + if err != nil { + b.Fatal(err) + } + for b.Loop() { + if _, _, err := r.Render(project, out); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index a0e2249..3e1d6f3 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -214,13 +214,24 @@ func ComputeDiff(old *Snapshot, project *ir.Project, outputDir string) *Diff { } } - // 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) } } + customPathsByEntity := make(map[string][]string, len(filesByEntity)) + for entityName, files := range filesByEntity { + paths := make([]string, 0, len(files)) + for _, f := range files { + if f.Custom { + paths = append(paths, f.Path) + } + } + customPathsByEntity[entityName] = paths + } // Renamed entities (declared via old_name). for oldName, newName := range renamedByOld { @@ -259,7 +270,7 @@ func ComputeDiff(old *Snapshot, project *ir.Project, outputDir string) *Diff { for _, f := range newEntity.Fields { newFields[f.Name] = f.DatabaseType } - customFiles := existingFilePaths(outputDir, customEntityFiles(old.Files, oldName)) + customFiles := existingFilePaths(outputDir, customPathsByEntity[oldName]) for fieldName, oldType := range oldState.Fields { newType, ok := newFields[fieldName] if !ok || oldType == newType { @@ -294,7 +305,7 @@ func ComputeDiff(old *Snapshot, project *ir.Project, outputDir string) *Diff { if !ok { continue } - customFiles := existingFilePaths(outputDir, customEntityFiles(old.Files, oldName)) + customFiles := existingFilePaths(outputDir, customPathsByEntity[oldName]) for _, f := range newEntity.Fields { if f.OldName == "" { continue @@ -404,18 +415,6 @@ 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) - } - } - return paths -} - // 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 diff --git a/internal/snapshot/snapshot_bench_test.go b/internal/snapshot/snapshot_bench_test.go new file mode 100644 index 0000000..e5310d3 --- /dev/null +++ b/internal/snapshot/snapshot_bench_test.go @@ -0,0 +1,91 @@ +package snapshot + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/renderer" +) + +// 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(b *testing.B, entities int, onDisk, custom bool) (string, *Snapshot, *ir.Project) { + b.Helper() + dir := b.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 := 0; i < entities; i++ { + name := fmt.Sprintf("E%04d", i) + for j := 0; j < 5; j++ { + 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 { + b.Fatal(err) + } + if err := os.WriteFile(abs, []byte("generated\n"), 0o644); err != nil { + b.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 +} + +func BenchmarkComputeDiff(b *testing.B) { + for _, mode := range []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}, + } { + 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)) + } + } + }) + } + }) + } +} From f0a1d1b8cc2bfcb7b7527bec17b72ba1f59f84c4 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:14:21 +0300 Subject: [PATCH 27/83] CI: fix regression references and lint findings - point regression rows at the files that define their checks - use errors.Is in the rollback no-op assertion - modernize benchmark loops and drop a stale nolint directive - avoid built-in and unused parameter names --- cmd/domaincraft/commands_update_security_test.go | 2 +- cmd/domaincraft/update.go | 2 +- compliance-suite/regressions.tsv | 4 ++-- internal/ir/build_relations_bench_test.go | 2 +- internal/renderer/hardening_test.go | 2 +- internal/renderer/render_bench_test.go | 2 +- internal/snapshot/rewrite.go | 12 ++++++------ internal/snapshot/snapshot_bench_test.go | 4 ++-- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go index f396c43..d5206ee 100644 --- a/cmd/domaincraft/commands_update_security_test.go +++ b/cmd/domaincraft/commands_update_security_test.go @@ -532,7 +532,7 @@ func TestReplaceExecutableRemoveOldFailure(t *testing.T) { } return os.Remove(path) } - renameFn = func(src, dst string) error { + renameFn = func(src, _ string) error { if src == tmp { return errors.New("locked") } diff --git a/cmd/domaincraft/update.go b/cmd/domaincraft/update.go index 78bb29c..82ce1a0 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -401,7 +401,7 @@ func downloadBinary(rawURL string) (string, error) { } if runtime.GOOS != "windows" { // A non-executable download must never reach the install step. - if err := chmodFn(tmp.Name(), 0o755); err != nil { //nolint:gosec // the downloaded binary must be executable + if err := chmodFn(tmp.Name(), 0o755); err != nil { _ = os.Remove(tmp.Name()) return "", fmt.Errorf("make downloaded update executable: %w", err) } diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 50e8e34..0afd92b 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -86,8 +86,8 @@ internal/packages/cache_test.go::TestPersistFailureKeepsResolvedVersion #5 cache internal/packages/registry_test.go::TestResolveVersionRejectsOversizedBody #5 oversized registry response was silently truncated into a version list internal/fsutil/fsutil_test.go::TestAtomicWritePreservesExistingFileMode #5 atomic rewrite dropped developer-owned files to mode 0600 internal/snapshot/rewrite_test.go::TestRewriteFilePreservesExistingMode #5 prune rewrite silently changed permissions of custom files -internal/snapshot/hardening_test.go::TestMigrationPlanTableNameMatchesIRForAcronymEntity #5 migration plan and IR derived table names through two different rules -internal/snapshot/hardening_test.go::TestCasingVariants #5 four parallel casing tables could drift during entity renames +internal/snapshot/migration_test.go::TestMigrationPlanTableNameMatchesIRForAcronymEntity #5 migration plan and IR derived table names through two different rules +internal/snapshot/rewrite_test.go::TestCasingVariants #5 four parallel casing tables could drift during entity renames cmd/domaincraft/commands_prune_test.go::TestPruneCLICleanupFailureKeepsSnapshot #5 prune reported success and advanced the snapshot after a failed cleanup cmd/domaincraft/commands_hardening_test.go::TestSanitizeCommandLine #5 bridge command lines were displayed with terminal control bytes intact cmd/domaincraft/commands_update_security_test.go::TestDownloadBinaryChmodFailure #5 self-update ignored a failed chmod on the downloaded binary diff --git a/internal/ir/build_relations_bench_test.go b/internal/ir/build_relations_bench_test.go index b34f076..bda59bc 100644 --- a/internal/ir/build_relations_bench_test.go +++ b/internal/ir/build_relations_bench_test.go @@ -71,7 +71,7 @@ func benchmarkHubSchema(n int) *parser.ParsedSchema { } hub.Fields["id"] = &parser.ParsedField{FieldDefinition: &lexer.FieldDefinition{Name: "id", Type: "uuid", IsPrimary: true}} hub.FieldOrder = append(hub.FieldOrder, "id") - for i := 0; i < n; i++ { + 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, diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index e722b1d..76143f4 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -364,7 +364,7 @@ func TestRollbackErrorKeepsOriginalPrimary(t *testing.T) { if !strings.HasPrefix(got.Error(), primary.Error()) { t.Errorf("primary error is not first: %q", got.Error()) } - if rollbackError(primary, nil) != primary { + if !errors.Is(rollbackError(primary, nil), primary) { t.Error("no-op rollback must return the original error unchanged") } } diff --git a/internal/renderer/render_bench_test.go b/internal/renderer/render_bench_test.go index 9c35c24..c73ed82 100644 --- a/internal/renderer/render_bench_test.go +++ b/internal/renderer/render_bench_test.go @@ -35,7 +35,7 @@ templates: } out := filepath.Join(dir, "out") project := &ir.Project{Name: "Bench"} - for i := 0; i < size; i++ { + 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") diff --git a/internal/snapshot/rewrite.go b/internal/snapshot/rewrite.go index 576ebc5..a89c48e 100644 --- a/internal/snapshot/rewrite.go +++ b/internal/snapshot/rewrite.go @@ -127,15 +127,15 @@ func isIdentRune(r rune) bool { // 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(old, new string, withPlural bool) map[string]string { +func casingVariants(oldName, newName string, withPlural bool) map[string]string { variants := map[string]string{ - old: new, // Product -> Item - textutil.CamelCase(old): textutil.CamelCase(new), // product -> item - strings.ToUpper(old): strings.ToUpper(new), // PRODUCT -> ITEM + 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(old) - newPlural := textutil.Pluralize(new) + 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 diff --git a/internal/snapshot/snapshot_bench_test.go b/internal/snapshot/snapshot_bench_test.go index e5310d3..8acdd3c 100644 --- a/internal/snapshot/snapshot_bench_test.go +++ b/internal/snapshot/snapshot_bench_test.go @@ -32,9 +32,9 @@ func benchmarkDiffData(b *testing.B, entities int, onDisk, custom bool) (string, Name: "NewProject", Entities: make([]ir.Entity, 0, entities), } - for i := 0; i < entities; i++ { + for i := range entities { name := fmt.Sprintf("E%04d", i) - for j := 0; j < 5; j++ { + for j := range 5 { rel := fmt.Sprintf("src/%s/f%d.g.cs", name, j) if onDisk { abs := filepath.Join(dir, filepath.FromSlash(rel)) From f8bf5d2488f0dbae3be030744a66fe089a00ba2c Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:22:06 +0300 Subject: [PATCH 28/83] Bridges: share local path normalization across resolver and renderer - add LocalBridgePaths as the single dir/config normalization - keep the resolver's missing-config hard error and path-like fallback - make the renderer fail closed on the same rules - cover directories, files and missing paths in both layers --- compliance-suite/regressions.tsv | 1 + internal/bridge/local_paths_test.go | 119 ++++++++++++++++++++++++++++ internal/bridge/resolver.go | 47 ++++++++--- internal/renderer/load.go | 22 +++-- internal/renderer/load_test.go | 72 +++++++++++++++++ 5 files changed, 240 insertions(+), 21 deletions(-) create mode 100644 internal/bridge/local_paths_test.go create mode 100644 internal/renderer/load_test.go diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 0afd92b..da31d24 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -100,3 +100,4 @@ internal/validator/validator_test.go::TestValidateAcceptsExplicitZeroProjectNume internal/renderer/hardening_test.go::TestRenderRejectsSymlinkWithRelativeBridgeDir #5 relative bridge directory bypassed the symlink containment check internal/renderer/hardening_test.go::TestRenderRollbackRemovesTargetDeletedBeforeCommit #5 rollback wrote empty bytes when a target disappeared between staging and commit 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 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/resolver.go b/internal/bridge/resolver.go index d438695..135ffbb 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -1,6 +1,7 @@ package bridge import ( + "errors" "fmt" "os" "path/filepath" @@ -39,15 +40,14 @@ func (r *Resolver) Resolve(input string) (string, error) { } // 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 + dir, _, err := LocalBridgePaths(input) + if err == nil { + return dir, 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 "", err } // Path-like inputs ("../x", "./x", "/x", "~/x", "C:\\x") that do not @@ -102,6 +102,35 @@ func (r *Resolver) Resolve(input string) (string, error) { return "", fmt.Errorf("bridge %q not found: not a local path, registry ID, or owner/repo", input) } +// 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 } + +func (e *missingBridgeConfigError) Error() string { + return fmt.Sprintf("directory %q does not contain bridge.yaml", e.dir) +} + +// 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) { diff --git a/internal/renderer/load.go b/internal/renderer/load.go index 42ba6a1..4c06e7c 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -3,12 +3,12 @@ package renderer import ( "fmt" "os" - "path/filepath" "regexp" "slices" "strings" "text/template" + "github.com/DomainCraft/DomainCraft/internal/bridge" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -113,7 +113,10 @@ func validateWhenConditions(bridgeName string, templates []TemplateSpec) error { // loadSource loads a single bridge directory (its bridge.yaml). func loadSource(bridgePath string) (sourceConfig, error) { - bridgeDir, configPath := resolveBridgePath(bridgePath) + bridgeDir, configPath, err := resolveBridgePath(bridgePath) + if err != nil { + return sourceConfig{}, err + } data, err := os.ReadFile(configPath) //nolint:gosec // resolved from validated bridge refs by resolveBridgePath if err != nil { return sourceConfig{}, fmt.Errorf("read bridge config: %w", err) @@ -231,14 +234,9 @@ 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 +// resolveBridgePath normalizes a local bridge reference through the shared +// bridge-package helper. It is fail-closed: a missing path or a directory +// without bridge.yaml is an error, never a guessed config path to read. +func resolveBridgePath(bridgePath string) (string, string, error) { + return bridge.LocalBridgePaths(bridgePath) } diff --git a/internal/renderer/load_test.go b/internal/renderer/load_test.go new file mode 100644 index 0000000..a812491 --- /dev/null +++ b/internal/renderer/load_test.go @@ -0,0 +1,72 @@ +package renderer + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// 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 := resolveBridgePath(tc.input) + if tc.wantErrPart != "" { + if err == nil { + t.Fatalf("resolveBridgePath(%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("resolveBridgePath(%q): %v", tc.input, err) + } + if dir != tc.wantDir || config != tc.wantConfig { + t.Errorf("resolveBridgePath(%q) = (%q, %q), want (%q, %q)", tc.input, dir, config, tc.wantDir, tc.wantConfig) + } + }) + } +} + +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) + } +} From 519c52269d19a6e52aa18e66e33e7b2b744efb91 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:39:01 +0300 Subject: [PATCH 29/83] Tests: make relative bridge symlink test volume-independent - chdir into the test root so filepath.Rel never crosses Windows volumes - verified with TMP/TEMP on D: and checkout on C: --- internal/renderer/hardening_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index 76143f4..1fdcb01 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -79,6 +79,12 @@ templates: 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) From 0db694cc6ec902f32886370ad56db9246aac25a7 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:24:22 +0300 Subject: [PATCH 30/83] Renderer: cache the first symlink containment pass - share one verified-directory cache within a Render call - keep the post-MkdirAll pass fully fresh to preserve TOCTOU protection - never cache the target leaf or missing components - record containment benchmark and A/B numbers --- compliance-suite/regressions.tsv | 2 + internal/fsutil/fsutil.go | 24 ++++- internal/fsutil/fsutil_test.go | 124 +++++++++++++++++++++++++ internal/renderer/render.go | 28 +++++- internal/renderer/render_bench_test.go | 36 +++++++ 5 files changed, 211 insertions(+), 3 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index da31d24..9054179 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -101,3 +101,5 @@ internal/renderer/hardening_test.go::TestRenderRejectsSymlinkWithRelativeBridgeD internal/renderer/hardening_test.go::TestRenderRollbackRemovesTargetDeletedBeforeCommit #5 rollback wrote empty bytes when a target disappeared between staging and commit 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/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRejectsSymlinkAtFinalComponent #5 cached containment check skipped the final symlink component +internal/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRechecksNewlyCreatedComponent #5 newly created directory was served from the containment cache diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index c3f8ef4..f13209e 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -40,6 +40,16 @@ func LocalPathWithin(base, rel string) (string, string, error) { // 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) @@ -53,7 +63,14 @@ func RefuseSymlinks(base, target string) error { cur = filepath.Join(cur, comp) paths = append(paths, cur) } - for _, path := range paths { + 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 @@ -64,6 +81,11 @@ func RefuseSymlinks(base, target string) error { 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 } diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go index ef78e74..d5da562 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" @@ -137,3 +138,126 @@ 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) + } +} diff --git a/internal/renderer/render.go b/internal/renderer/render.go index c3373de..21b0c7c 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -59,6 +59,24 @@ func safeOutputPath(outputDir, renderedTarget string) (string, error) { return absTarget, nil } +// 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) { + absTarget, _, err := fsutil.LocalPathWithin(outputDir, renderedTarget) + if err != nil { + 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 := fsutil.RefuseSymlinksCached(absOutput, absTarget, verified); err != nil { + return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) + } + return absTarget, nil +} + // beforeCommitHook is a test seam called once between staging and commit. It is // nil in production; tests set it to mutate the filesystem at that exact point. // Tests using it must not run in parallel. @@ -174,6 +192,11 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } } + // verified holds directories checked by the pre-MkdirAll containment pass + // in Phase 1. It is local to this Render and never reused across passes: + // the post-MkdirAll pass below stays fully fresh, because MkdirAll itself + // can create components and an attacker can plant a link between calls. + verified := make(map[string]bool) staged := make([]stagedWrite, 0) // committed is empty during staging; phase 2 appends to it as files land. committed := make([]stagedWrite, 0) @@ -240,7 +263,7 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re return fail(fmt.Errorf("render target path: %w", err)) } - absTarget, err := safeOutputPath(outputDir, renderedTarget) + absTarget, err := safeOutputPathCached(outputDir, renderedTarget, verified) if err != nil { return fail(err) } @@ -267,7 +290,8 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re return fail(fmt.Errorf("create output dir: %w", err)) } // MkdirAll may have created the missing components above; re-check - // so a symlink planted in the meantime is still rejected. + // with a fully fresh walk (no cached directories) so a symlink + // planted in the meantime is still rejected. if _, err := safeOutputPath(outputDir, renderedTarget); err != nil { return fail(err) } diff --git a/internal/renderer/render_bench_test.go b/internal/renderer/render_bench_test.go index c73ed82..e5ff397 100644 --- a/internal/renderer/render_bench_test.go +++ b/internal/renderer/render_bench_test.go @@ -58,3 +58,39 @@ templates: }) } } + +// 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%. +// An os.Root rewrite removed the component walks but made warm render 2.9x +// slower there, because every Root operation re-resolves each component through +// directory handles. The first pass is now cached per Render (directories +// only); the second stays fresh. A/B at 2000 entities: 4.32 s -> 4.17 s median +// warm render. 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 := filepath.Join(b.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 { + b.Fatal(err) + } + if err := os.WriteFile(target, []byte("previous\n"), 0o644); err != nil { + b.Fatal(err) + } + targets = append(targets, rel) + } + for b.Loop() { + for _, rel := range targets { + if _, err := safeOutputPath(out, rel); err != nil { + b.Fatal(err) + } + } + } + }) + } +} From e6884afb5f33f2a3c6521bc6cacf6b0d538692b6 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:32:39 +0300 Subject: [PATCH 31/83] Bridges: embed underscore-prefixed helper templates - list the four _helpers templates explicitly in go:embed - compare the embedded tree with the source tree on every test run - correct the stale comment about release-time regeneration --- bridges_embed.go | 16 ++++-- compliance-suite/regressions.tsv | 1 + internal/bridge/embed_test.go | 89 ++++++++++++++++++++++++++++++-- 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/bridges_embed.go b/bridges_embed.go index e6dfad8..42b568e 100644 --- a/bridges_embed.go +++ b/bridges_embed.go @@ -7,9 +7,19 @@ 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. +// +// Go excludes files whose names begin with "_" when embedding a directory. +// Bridge helper templates use that prefix, so each of them is listed explicitly +// below. TestEmbeddedBridgesMatchTree compares this set with the source tree. // //go:embed bridges +//go:embed bridges/csharp/core/templates/_helpers.cs.tmpl +//go:embed bridges/typescript/core/templates/_helpers.ts.tmpl +//go:embed bridges/admin/templates/_helpers.html.tmpl +//go:embed bridges/csharp/persistence/dapper-stub/templates/_helpers.cs.tmpl var Bridges embed.FS diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 9054179..7dc5ef5 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -103,3 +103,4 @@ internal/ir/build_relations_bench_test.go::TestBuildHubRelationsPreservesFirstMa internal/renderer/load_test.go::TestLoadSourceFailsClosedOnMissingBridgeYaml #5 renderer guessed a config path for a directory without bridge.yaml internal/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRejectsSymlinkAtFinalComponent #5 cached containment check skipped the final symlink component internal/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRechecksNewlyCreatedComponent #5 newly created directory was served from the containment cache +internal/bridge/embed_test.go::TestEmbeddedBridgesMatchTree #5 embedded bridge tree omitted underscore-prefixed helper templates diff --git a/internal/bridge/embed_test.go b/internal/bridge/embed_test.go index 42da808..7961b0d 100644 --- a/internal/bridge/embed_test.go +++ b/internal/bridge/embed_test.go @@ -1,18 +1,18 @@ package bridge import ( + "io/fs" + "maps" "os" + "path" "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) { @@ -47,6 +47,10 @@ func TestEmbeddedBridgeRel(t *testing.T) { } } +// 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() { @@ -59,3 +63,80 @@ func TestEmbeddedContainsRegistryBridges(t *testing.T) { } } } + +// TestEmbeddedBridgesMatchTree compares the embedded tree with the source tree. +// Go drops "_"-prefixed files when embedding a directory, and bridge helper +// templates use that prefix. The explicit directives in bridges_embed.go +// must keep the two sets 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() { + switch d.Name() { + case "bin", "obj", "node_modules", ".git": + 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. + switch d.Name() { + case "bin", "obj", "node_modules", ".git": + 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: add an explicit //go:embed directive", 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) + } + } + embeddedHelpers := 0 + for rel := range embedded { + switch path.Base(rel) { + case "_helpers.cs.tmpl", "_helpers.ts.tmpl", "_helpers.html.tmpl": + embeddedHelpers++ + } + } + if embeddedHelpers == 0 { + t.Error("no helper templates in the embedded tree — the offline fallback cannot render") + } +} From e3a195814557cc321e30a8b677fb6770a144a34d Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:10:28 +0300 Subject: [PATCH 32/83] CI: register missing regression checks and require assertions --- compliance-suite/regressions.tsv | 16 +++++ compliance-suite/regressions_test.go | 89 ++++++++++++++++++++++++++-- 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 7dc5ef5..3a77fbf 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -104,3 +104,19 @@ internal/renderer/load_test.go::TestLoadSourceFailsClosedOnMissingBridgeYaml #5 internal/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRejectsSymlinkAtFinalComponent #5 cached containment check skipped the final symlink component internal/fsutil/fsutil_test.go::TestRefuseSymlinksCachedRechecksNewlyCreatedComponent #5 newly created directory was served from the containment cache internal/bridge/embed_test.go::TestEmbeddedBridgesMatchTree #5 embedded bridge tree omitted underscore-prefixed helper templates +internal/ir/build_entities_test.go::TestBuildResolvesTargetEntityAfterTopoSort #5 in-place topological sort overwrote the backing array and corrupted relation TargetEntity pointers +internal/ir/build_entities_test.go::TestBuildPairNavigationNameStripsIdSuffix #5 paired FK with an Id suffix made WithOne reference the field name instead of the navigation property and broke generated C# +internal/ir/build_entities_test.go::TestBuildDisambiguatesInverseNavigationNames #5 two relations from one entity to the same target produced colliding inverse names and duplicate C# navigation properties +internal/ir/build_entities_test.go::TestBuildReconcilesOneToManyDeclaredOnBothSides #5 a [many] relation paired with a target FK was treated as many-to-many and emitted a spurious join table +internal/bridge/resolver_test.go::TestResolver_MissingPathLikeIsErrorNotClone #5 missing path-like bridge input fell through to cloning github.com/../domaincraftcsharp +internal/validator/validator_test.go::TestValidateRejectsInvalidNumericDefault #5 int default accepted an unparseable string and broke generated code +internal/lexer/lexer_test.go::TestLexerRejectsUnclosedTypeDeclaration #5 unclosed relation( and enum( declarations were silently normalized into valid types +internal/lexer/lexer_test.go::TestLexerAcceptsSpecmetaStringModifier #5 lexer hard-coded validation modifiers and ignored the specmeta source of truth +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/parser/parser_test.go::TestUnmarshalYAMLHelpersRejectUnknownKeysForAllConfigs #5 strict config-key decoding could be lost when presence-aware helpers were unified +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/seed/seed_test.go::TestGenerateRespectsExclusiveBounds #5 int and float seed bounds were clamped by two duplicated loops and could drift apart +internal/seed/seed_test.go::TestStringValueMaxLengthClamp #5 oversized max_length clamp was hand-rolled with no direct coverage at zero or above length +internal/snapshot/snapshot_test.go::TestLoadRejectsIncompatibleFormatVersion #5 Load accepted snapshots with any format_version, so stale snapshots could trigger destructive prune diff --git a/compliance-suite/regressions_test.go b/compliance-suite/regressions_test.go index c7b7866..55e352d 100644 --- a/compliance-suite/regressions_test.go +++ b/compliance-suite/regressions_test.go @@ -12,9 +12,10 @@ import ( // 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. A `file::TestX` name must still point at -// an existing test file that defines TestX, so a removed or renamed check -// cannot silently pass. This is the enforcement for the rule -// "every bug fix adds its check here; a removed name is an error". +// 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 "every bug fix adds its check here; a removed name +// is an error". func TestRegressionsTable(t *testing.T) { data, err := os.ReadFile("regressions.tsv") if err != nil { @@ -78,8 +79,88 @@ func TestRegressionsTable(t *testing.T) { if src == "" { continue // Read already reported as an error. } - if !strings.Contains(src, "func "+testName+"(") { + 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 + }{ + {"TestEmptyBody", true, false}, + {"TestNoAssert", true, false}, + {"TestWithAssert", true, true}, + {"TestMissing", false, false}, + } { + 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) } } } From a267c00ff173865479fccd68c06da9f443445af8 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:10:34 +0300 Subject: [PATCH 33/83] Seed: share numeric bound clamping and use min/max for length --- internal/seed/seed.go | 48 +++++++++------------- internal/seed/seed_test.go | 82 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 30 deletions(-) diff --git a/internal/seed/seed.go b/internal/seed/seed.go index 124b064..18bd701 100644 --- a/internal/seed/seed.go +++ b/internal/seed/seed.go @@ -252,22 +252,19 @@ func stringValue(field ir.Field, record int) string { // 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 { - if n < 0 { - n = 0 - } - if n < len(v) { - v = v[:n] - } + 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.Field, record int) int64 { - v := int64(record + 1) - for _, r := range field.ValidationRules() { - n, err := strconv.ParseInt(r.Value, 10, 64) +// 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)) T { + for _, r := range rules { + n, err := parse(r.Value) if err != nil { continue } @@ -285,27 +282,18 @@ func intValue(field ir.Field, 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) +} + // floatValue returns a float honoring the numeric min/max bounds (inclusive or // exclusive) from the normalized ValidationRules contract. func floatValue(field ir.Field, 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 - } - } - return v + parse := func(s string) (float64, error) { return strconv.ParseFloat(s, 64) } + return clampNumericBounds(float64(record+1)+0.5, field.ValidationRules(), parse) } // coerceValue converts a declared seed/default value (from YAML: string, number, diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go index 18b0630..c0df5a3 100644 --- a/internal/seed/seed_test.go +++ b/internal/seed/seed_test.go @@ -242,6 +242,55 @@ 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)}, + } + + 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) { t.Parallel() project := &ir.Project{ @@ -380,6 +429,39 @@ func TestGenerateClampsNonPositiveMaxLength(t *testing.T) { } } +// 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{ From 3de87a15e09dcda04506eb3b7319a2f7c6911f7b Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:10:39 +0300 Subject: [PATCH 34/83] Snapshot: fail closed on incompatible snapshot format versions --- internal/snapshot/snapshot.go | 9 ++++++ internal/snapshot/snapshot_test.go | 50 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 3e1d6f3..13c2104 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -74,6 +74,15 @@ 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 } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index cf5a71a..8178faa 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -58,6 +58,56 @@ 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() From 954ac3c052807b5ef7c81a293044691a8fa0f903 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:12:34 +0300 Subject: [PATCH 35/83] Core: harden field parsing, validation and IR contracts --- compliance-suite/regressions.tsv | 1 + internal/ir/build_entities.go | 9 +- internal/ir/build_entities_test.go | 5 ++ internal/ir/build_relations.go | 14 +-- internal/ir/build_relations_test.go | 95 ++++++++++++++++++++ internal/ir/contract_test.go | 51 +++++++++++ internal/ir/seed.go | 32 +------ internal/ir/seed_kind_test.go | 41 +++++++++ internal/ir/toposort.go | 7 +- internal/ir/toposort_test.go | 56 ++++++++++++ internal/ir/validations.go | 54 +++++++++++- internal/lexer/lexer.go | 59 +++++++------ internal/lexer/lexer_test.go | 63 ++++++++++++++ internal/parser/models.go | 126 ++++++++++----------------- internal/parser/parser.go | 7 +- internal/parser/parser_test.go | 92 +++++++++++++++++++ internal/specmeta/specmeta.go | 123 +++++++++++++++++++++----- internal/specmeta/specmeta_test.go | 84 ++++++++++++++++++ internal/validator/validator.go | 125 +++++++++++++++++--------- internal/validator/validator_test.go | 61 +++++++++++++ 20 files changed, 883 insertions(+), 222 deletions(-) create mode 100644 internal/ir/build_relations_test.go create mode 100644 internal/ir/seed_kind_test.go create mode 100644 internal/ir/toposort_test.go diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 3a77fbf..c4f7b46 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -120,3 +120,4 @@ internal/ir/toposort_test.go::TestTopoSortInsertReadyKeepsNameOrder #5 ready que internal/seed/seed_test.go::TestGenerateRespectsExclusiveBounds #5 int and float seed bounds were clamped by two duplicated loops and could drift apart internal/seed/seed_test.go::TestStringValueMaxLengthClamp #5 oversized max_length clamp was hand-rolled with no direct coverage at zero or above length internal/snapshot/snapshot_test.go::TestLoadRejectsIncompatibleFormatVersion #5 Load accepted snapshots with any format_version, so stale snapshots could trigger destructive prune +internal/parser/parser_test.go::TestNavigationNameStripsIdAndIDSuffixOnly #5 HasIDSuffix treated lowercase id as an FK suffix and renamed fluid to Flu, squid to Squ and avoid to Avo diff --git a/internal/ir/build_entities.go b/internal/ir/build_entities.go index 332315e..72286cf 100644 --- a/internal/ir/build_entities.go +++ b/internal/ir/build_entities.go @@ -159,14 +159,17 @@ func Build(schema *parser.ParsedSchema) (*Project, 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) diff --git a/internal/ir/build_entities_test.go b/internal/ir/build_entities_test.go index bf3494e..1855e15 100644 --- a/internal/ir/build_entities_test.go +++ b/internal/ir/build_entities_test.go @@ -299,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"}}, diff --git a/internal/ir/build_relations.go b/internal/ir/build_relations.go index a56126f..3697722 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" ) @@ -90,8 +91,7 @@ func indexRelationsOut(entities []Entity) map[string]*relationIndex { // 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 []Entity) { - index := indexRelationsOut(entities) +func reconcileOneToMany(entities []Entity, index map[string]*relationIndex) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -103,7 +103,9 @@ func reconcileOneToMany(entities []Entity) { if bySource := index[rel.TargetEntity.Name]; bySource != nil { pair = bySource.singleBack[entity.Name] } - if pair == nil { + // The single-back rule is shared with the validator warning. + if pair == nil || pair.TargetEntity == nil || + !specmeta.IsSingleBackRelationField(true, pair.IsMany, pair.TargetEntity.Name, entity.Name) { continue } rel.RelationType = "one-to-many" @@ -118,8 +120,7 @@ func reconcileOneToMany(entities []Entity) { // 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 []Entity) { - index := indexRelationsOut(entities) +func resolveInverseNavs(entities []Entity, index map[string]*relationIndex) { for i := range entities { entity := &entities[i] for j := range entity.RelationsOut { @@ -139,8 +140,7 @@ func resolveInverseNavs(entities []Entity) { // 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 []Entity) { - index := indexRelationsOut(entities) +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] 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 a732305..9f8a221 100644 --- a/internal/ir/contract_test.go +++ b/internal/ir/contract_test.go @@ -33,6 +33,57 @@ 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) { t.Parallel() f := Field{ diff --git a/internal/ir/seed.go b/internal/ir/seed.go index 8a71564..83a388d 100644 --- a/internal/ir/seed.go +++ b/internal/ir/seed.go @@ -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/toposort.go b/internal/ir/toposort.go index 729430d..371e8e1 100644 --- a/internal/ir/toposort.go +++ b/internal/ir/toposort.go @@ -1,9 +1,6 @@ package ir -import ( - "slices" - "sort" -) +import "slices" // sortEntities reorders the slice by FK dependencies using Kahn's algorithm. // The order is deterministic: ties are broken by entity name. @@ -45,7 +42,7 @@ func sortEntities(entities []Entity) []Entity { // Deterministic ordering: process ready entities in name order. slices.Sort(ready) insertReady := func(name string) { - at := sort.Search(len(ready), func(i int) bool { return ready[i] >= name }) + at, _ := slices.BinarySearch(ready, name) ready = slices.Insert(ready, at, name) } diff --git a/internal/ir/toposort_test.go b/internal/ir/toposort_test.go new file mode 100644 index 0000000..3f38bb0 --- /dev/null +++ b/internal/ir/toposort_test.go @@ -0,0 +1,56 @@ +package ir + +import "testing" + +// TestTopoSortInsertReadyKeepsNameOrder pins the binary insert into the ready +// queue: 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) + } + } + } +} + +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/validations.go b/internal/ir/validations.go index 0b83c5e..8081c76 100644 --- a/internal/ir/validations.go +++ b/internal/ir/validations.go @@ -1,6 +1,10 @@ package ir -import "strings" +import ( + "cmp" + "slices" + "strings" +) // ValidationRule is a normalized, language-agnostic validation rule. The core // derives these from the field's type, nullability and the declared validation @@ -73,9 +77,41 @@ func newRule(kind, value string, exclusive bool) ValidationRule { 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 { + switch kind { + case "required": + return 0 + case "email": + return 1 + case "url": + return 2 + case "ipv4": + return 3 + case "regex": + return 4 + case "min_length": + return 5 + case "max_length": + return 6 + case "min_value": + return 7 + case "max_value": + return 8 + default: + 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,6 +121,8 @@ func newRule(kind, value string, exclusive bool) ValidationRule { // min_value / max_value on numeric types // gte / lte -> inclusive min_value / max_value // gt / lt -> min_value / max_value with Exclusive=true +// 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) @@ -107,6 +145,10 @@ func (f Field) ValidationRules() []ValidationRule { 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 +166,11 @@ func (f Field) ValidationRules() []ValidationRule { } } + // 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 b16de3d..f40ce82 100644 --- a/internal/lexer/lexer.go +++ b/internal/lexer/lexer.go @@ -91,11 +91,14 @@ func (l *Lexer) Parse() (*FieldDefinition, error) { func (l *Lexer) 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, ")") + // Check for relation(EntityName). A missing closing paren is an error, not + // a prefix to be trimmed away. + if strings.HasPrefix(typeStr, specmeta.FieldTypeRelation+"(") { + if !strings.HasSuffix(typeStr, ")") { + return fmt.Errorf("relation type requires a closing parenthesis") + } + fd.Type = specmeta.FieldTypeRelation + targetEntity := strings.TrimSuffix(strings.TrimPrefix(typeStr, specmeta.FieldTypeRelation+"("), ")") fd.TargetEntity = strings.TrimSpace(targetEntity) if fd.TargetEntity == "" { return fmt.Errorf("relation type requires a target entity name") @@ -104,9 +107,13 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { } // Check for array(Type). The prefix/suffix handling lives in specmeta so - // every consumer extracts the element type the same way. + // every consumer extracts the element type the same way and rejects an + // unclosed declaration. + if strings.HasPrefix(typeStr, specmeta.FieldTypeArray+"(") && !strings.HasSuffix(typeStr, ")") { + return fmt.Errorf("array type requires a closing parenthesis") + } if specmeta.IsArrayType(typeStr) { - fd.Type = "array" + fd.Type = specmeta.FieldTypeArray fd.TargetType = strings.TrimSpace(specmeta.ParseArrayInner(typeStr)) if fd.TargetType == "" { return fmt.Errorf("array type requires an element type") @@ -115,10 +122,12 @@ func (l *Lexer) parseType(typeStr string, fd *FieldDefinition) error { } // Check for enum(Name) - if strings.HasPrefix(typeStr, "enum(") { - fd.Type = "enum" - enumName := strings.TrimPrefix(typeStr, "enum(") - enumName = strings.TrimSuffix(enumName, ")") + if strings.HasPrefix(typeStr, specmeta.FieldTypeEnum+"(") { + if !strings.HasSuffix(typeStr, ")") { + return fmt.Errorf("enum type requires a closing parenthesis") + } + fd.Type = specmeta.FieldTypeEnum + enumName := strings.TrimSuffix(strings.TrimPrefix(typeStr, specmeta.FieldTypeEnum+"("), ")") fd.TargetType = strings.TrimSpace(enumName) if fd.TargetType == "" { return fmt.Errorf("enum type requires a name") @@ -154,10 +163,10 @@ 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": + switch { + case specmeta.IsStringValidationModifier(key) || specmeta.IsNumericValidationModifier(key): fd.Validations[key] = value - case "default": + case key == "default": // Check for function-style defaults like now(), uuid() if strings.HasSuffix(value, "()") { fd.DefaultIsFunc = true @@ -165,12 +174,12 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { } else { fd.DefaultValue = value } - case "on_delete": + 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 "old_name": + 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. @@ -184,6 +193,12 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { 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": @@ -200,12 +215,6 @@ func (l *Lexer) parseModifiers(modStr string, fd *FieldDefinition) error { 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) } @@ -272,17 +281,17 @@ 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") } diff --git a/internal/lexer/lexer_test.go b/internal/lexer/lexer_test.go index e85b7b3..71d4b57 100644 --- a/internal/lexer/lexer_test.go +++ b/internal/lexer/lexer_test.go @@ -3,6 +3,8 @@ package lexer import ( "strings" "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" ) func TestParsePrimitiveTypes(t *testing.T) { @@ -422,3 +424,64 @@ 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 TestLexerAcceptsSpecmetaStringModifier(t *testing.T) { + // Not parallel: the spec list is extended for the duration of this test. + original := specmeta.StringValidationModifiers + t.Cleanup(func() { specmeta.StringValidationModifiers = original }) + specmeta.StringValidationModifiers = append(append([]string(nil), original...), "startsWith") + + fd, err := ParseFieldString("string [startsWith:foo]") + if err != nil { + t.Fatalf("ParseFieldString() error = %v", err) + } + if got := fd.Validations["startsWith"]; got != "foo" { + t.Errorf("Validations[startsWith] = %q, want foo", got) + } +} diff --git a/internal/parser/models.go b/internal/parser/models.go index 44fe8c9..3f8d2fc 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -116,40 +116,52 @@ func yamlMergeKeyNames(value *yaml.Node) []string { return names } -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 { +// 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 { if value.Kind != yaml.MappingNode { - return value.Decode((*deployConfigAlias)(d)) + return value.Decode(target) } + allowedKeys := specmeta.SliceToSet(allowed) for i := 0; i < len(value.Content)-1; i += 2 { key := value.Content[i] - switch key.Value { - case "port": - d.portSet = true - case "domain": - // no presence flag needed: the empty string default is unambiguous - case "<<": + if mark, tracked := presence[key.Value]; tracked { + mark() + continue + } + if key.Value == "<<" { if key.Tag != "!!str" { for _, name := range yamlMergeKeyNames(value.Content[i+1]) { - if name == "port" { - d.portSet = true + if mark, merged := presence[name]; merged { + mark() } } continue } - // A quoted "<<" is a regular key, not a merge, and falls through. - fallthrough - default: - // 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 this block. - return fmt.Errorf("line %d: field %s not found in type parser.DeployConfig", key.Line, key.Value) + // A quoted "<<" is a regular key, not a merge — treat as unknown. + } + if !allowedKeys[key.Value] { + return fmt.Errorf("line %d: field %s not found in type parser.%s", key.Line, key.Value, typeName) } } - return value.Decode((*deployConfigAlias)(d)) + return value.Decode(target) +} + +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). @@ -189,36 +201,12 @@ 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 { - if value.Kind != yaml.MappingNode { - return value.Decode((*rateLimitConfigAlias)(r)) - } - for i := 0; i < len(value.Content)-1; i += 2 { - key := value.Content[i] - switch key.Value { - case "permit_limit": - r.permitLimitSet = true - case "window_seconds": - r.windowSecondsSet = true - case "enabled", "policy": - // no presence flags needed: these defaults are unambiguous - case "<<": - if key.Tag != "!!str" { - for _, name := range yamlMergeKeyNames(value.Content[i+1]) { - switch name { - case "permit_limit": - r.permitLimitSet = true - case "window_seconds": - r.windowSecondsSet = true - } - } - continue - } - fallthrough - default: - return fmt.Errorf("line %d: field %s not found in type parser.RateLimitConfig", key.Line, key.Value) - } - } - return value.Decode((*rateLimitConfigAlias)(r)) + 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. @@ -236,34 +224,12 @@ 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 { - if value.Kind != yaml.MappingNode { - return value.Decode((*paginationConfigAlias)(p)) - } - for i := 0; i < len(value.Content)-1; i += 2 { - key := value.Content[i] - switch key.Value { - case "default_page_size": - p.defaultPageSizeSet = true - case "max_page_size": - p.maxPageSizeSet = true - case "<<": - if key.Tag != "!!str" { - for _, name := range yamlMergeKeyNames(value.Content[i+1]) { - switch name { - case "default_page_size": - p.defaultPageSizeSet = true - case "max_page_size": - p.maxPageSizeSet = true - } - } - continue - } - fallthrough - default: - return fmt.Errorf("line %d: field %s not found in type parser.PaginationConfig", key.Line, key.Value) - } - } - return value.Decode((*paginationConfigAlias)(p)) + 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 diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 7049533..a486519 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -64,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 len(name) > 2 && specmeta.HasIDSuffix(name) { name = name[:len(name)-2] } if name == "" { diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index acf1852..39de52c 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" "testing" + + "gopkg.in/yaml.v3" ) func TestParseStrictRejectsUnknownKeys(t *testing.T) { @@ -117,6 +119,51 @@ 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(` @@ -975,3 +1022,48 @@ entities: {} 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/specmeta/specmeta.go b/internal/specmeta/specmeta.go index e488268..3e68858 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -2,10 +2,32 @@ package specmeta 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" + 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" +) + // FeatureFieldDef describes a field auto-injected by a feature macro. type FeatureFieldDef struct { Feature string `json:"feature"` @@ -51,19 +73,19 @@ var InfraSecretStores = []string{"local", "kubernetes", "azure-keyvault", "aws-s var InfraStores = []string{"local", "s3", "azure-blob", "gcs"} // MetaFieldTypes lists the non-primitive field types. -var MetaFieldTypes = []string{"relation", "array", "enum"} +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"}, } // OnDeleteValues lists the valid on_delete modifier values. @@ -71,21 +93,21 @@ var OnDeleteValues = []string{"cascade", "set_null", "restrict", "no_action"} // 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, } // IntegralFieldTypes lists the integral scalar types. -var IntegralFieldTypes = []string{"int", "bigint"} +var IntegralFieldTypes = []string{FieldTypeInt, FieldTypeBigint} // FloatFieldTypes lists the floating-point scalar types. -var FloatFieldTypes = []string{"float", "decimal"} +var FloatFieldTypes = []string{FieldTypeFloat, FieldTypeDecimal} // NumericFieldTypes lists the numeric scalar types. var NumericFieldTypes = append(append([]string{}, IntegralFieldTypes...), FloatFieldTypes...) // StringFieldTypes lists the string scalar types. -var StringFieldTypes = []string{"string", "text"} +var StringFieldTypes = []string{FieldTypeString, FieldTypeText} // NumericValidationModifiers lists numeric validation modifier names. var NumericValidationModifiers = []string{"gte", "gt", "lte", "lt"} @@ -93,6 +115,9 @@ var NumericValidationModifiers = []string{"gte", "gt", "lte", "lt"} // StringValidationModifiers lists string validation modifier names. var StringValidationModifiers = []string{"min", "max", "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"} @@ -112,16 +137,16 @@ var PermissionKeys = []string{"read", "create", "update", "delete"} var SortDirections = []string{"asc", "desc"} // BooleanFieldTypes lists the boolean scalar types. -var BooleanFieldTypes = []string{"boolean"} +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}, } // DefaultFieldType is the fallback type for unresolvable fields. -const DefaultFieldType = "string" +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 @@ -154,7 +179,6 @@ var ( 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 @@ -182,7 +206,6 @@ func init() { multiTenancyModeSet = SliceToSet(MultiTenancyModes) rateLimitPolicySet = SliceToSet(RateLimitPolicies) permissionKeySet = SliceToSet(PermissionKeys) - stringValidationModSet = SliceToSet(StringValidationModifiers) numericValidationModSet = SliceToSet(NumericValidationModifiers) sortDirectionSet = SliceToSet(SortDirections) databaseSet = SliceToSet(Databases) @@ -264,8 +287,14 @@ 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] } +// IsStringValidationModifier reports whether mod applies to string fields. It +// reads the slice directly so extending the spec needs no lexer change. +func IsStringValidationModifier(mod string) bool { return slices.Contains(StringValidationModifiers, mod) } + +// IsStringFlagValidationModifier reports whether mod is a bare string flag. +func IsStringFlagValidationModifier(mod string) bool { + return slices.Contains(StringFlagValidationModifiers, mod) +} // IsNumericValidationModifier reports whether mod applies to numeric fields. func IsNumericValidationModifier(mod string) bool { return numericValidationModSet[mod] } @@ -279,17 +308,63 @@ func SliceToSet(items []string) map[string]bool { return set } -// IsArrayType reports whether dbType is an array declaration. +// 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 an array declaration, or dbType unchanged. +// 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+"("), ")") +} + +// 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")) +} + +// 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 "json" + case !IsPrimitive(dbType): + return "enum" + default: + return "text" + } } // FindAuthEntity returns the first entity with email and password fields. diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index 2c663f2..9e49db9 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -594,6 +594,90 @@ func TestIsValidIdentifier(t *testing.T) { } } +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 { diff --git a/internal/validator/validator.go b/internal/validator/validator.go index b374065..1b6c501 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -440,7 +440,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 } } @@ -489,10 +489,10 @@ 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 } } @@ -751,7 +751,7 @@ func validatePrimaryKeyField(entityName, fieldName string, field *parser.ParsedF // Primary key constraints. if field.IsPrimary { - if field.Type == "array" { + if field.Type == specmeta.FieldTypeArray { errs = append(errs, invalid(entityName, fieldName, "primary key cannot be an array type")) } @@ -769,7 +769,7 @@ func (v *Validator) validateEnumField(entityName, fieldName string, field *parse var errs []ValidationError // Enum reference. - if field.Type == "enum" && field.TargetType != "" { + if field.Type == specmeta.FieldTypeEnum && field.TargetType != "" { if _, ok := v.schema.Enums[field.TargetType]; !ok { errs = append(errs, invalidf(entityName, fieldName, "enum '%s' is not defined in enums section", field.TargetType)) @@ -785,7 +785,7 @@ func (v *Validator) validateArrayField(entityName, fieldName string, field *pars var errs []ValidationError // Array element type. - if field.Type == "array" && field.TargetType != "" { + if field.Type == specmeta.FieldTypeArray && field.TargetType != "" { inner := strings.ToLower(field.TargetType) if !specmeta.IsPrimitive(inner) { if _, ok := v.schema.Enums[field.TargetType]; !ok { @@ -843,16 +843,21 @@ func (v *Validator) validateFieldDefault(entityName, fieldName string, field *pa var errs []ValidationError ftype := strings.ToLower(field.Type) + defaultType := ftype + if ftype == specmeta.FieldTypeArray && field.TargetType != "" { + // The element type drives the default check; specmeta owns extraction. + defaultType = specmeta.FieldTypeArray + "(" + 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, defaultType, 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 := slices.Contains(enumValues, field.DefaultValue) if !found { @@ -866,33 +871,67 @@ func (v *Validator) validateFieldDefault(entityName, fieldName string, field *pa return errs } +// 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. +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 := strings.Split(inner, ",") + for i := range parts { + parts[i] = strings.TrimSpace(parts[i]) + } + return parts +} + +// validateDefaultValue checks one scalar default, or every element of an array +// default, against the field's element type. Numeric defaults must parse as a +// number — the legacy true/false values no longer slip through. func validateDefaultValue(entityName, fieldName, ftype, defaultVal string) []ValidationError { var errs []ValidationError - switch { - case specmeta.IsNumeric(ftype): - if boolValues[defaultVal] { - errs = append(errs, warnf(entityName, fieldName, - "default value '%s' is not valid for numeric type %s", defaultVal, ftype)) - } - case ftype == "boolean": - if !boolValues[defaultVal] { - errs = append(errs, warnf(entityName, fieldName, - "default value '%s' is not valid for boolean (expected true/false)", defaultVal)) - } - case ftype == "date": - if !isValidDate(defaultVal) { - errs = append(errs, warnf(entityName, fieldName, - "default value '%s' is not a valid date (expected YYYY-MM-DD)", defaultVal)) - } - case ftype == "datetime": - if !isValidDatetime(defaultVal) { - errs = append(errs, warnf(entityName, fieldName, - "default value '%s' is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", defaultVal)) - } - case ftype == "uuid": - if !isValidUUID(defaultVal) { - errs = append(errs, warnf(entityName, fieldName, - "default value '%s' is not a valid UUID", defaultVal)) + inner := specmeta.ParseArrayInner(ftype) + values := []string{defaultVal} + if specmeta.IsArrayType(ftype) { + values = splitArrayDefault(defaultVal) + } + + for _, value := range values { + switch { + case specmeta.IsIntegralType(inner): + if _, err := strconv.ParseInt(value, 10, 64); err != nil { + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not valid for numeric type %s", value, inner)) + } + case specmeta.IsFloatType(inner): + if _, err := strconv.ParseFloat(value, 64); err != nil { + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not valid for numeric type %s", value, inner)) + } + case inner == specmeta.FieldTypeBoolean: + if !boolValues[value] { + errs = append(errs, warnf(entityName, fieldName, + "default value '%s' is not valid for boolean (expected true/false)", value)) + } + case inner == specmeta.FieldTypeDate: + if !isValidDate(value) { + errs = append(errs, warnf(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, warnf(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, warnf(entityName, fieldName, + "default value '%s' is not a valid UUID", value)) + } } } return errs @@ -1164,7 +1203,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with type %s", entryIdx, seedValue, ftype)) } - case ftype == "boolean": + case ftype == specmeta.FieldTypeBoolean: switch v := seedValue.(type) { case bool: // OK @@ -1178,7 +1217,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with boolean type", entryIdx, seedValue)) } - case ftype == "date": + case ftype == specmeta.FieldTypeDate: s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1187,7 +1226,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %q is not a valid date (expected YYYY-MM-DD)", entryIdx, s)) } - case ftype == "uuid": + case ftype == specmeta.FieldTypeUUID: s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1196,7 +1235,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %q is not a valid UUID (expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)", entryIdx, s)) } - case ftype == "datetime": + case ftype == specmeta.FieldTypeDatetime: s, ok := seedValue.(string) if !ok { errs = append(errs, invalidf(entityName, fieldName, @@ -1206,7 +1245,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx "seed entry %d: value %q is not a valid datetime (expected ISO 8601 format, e.g. 2024-01-15T10:30:00Z)", entryIdx, s)) } - case ftype == "json" || ftype == "jsonb": + case ftype == specmeta.FieldTypeJSON || ftype == specmeta.FieldTypeJSONB: // JSON values can be any valid JSON — accept any type. // String values are validated as parseable JSON. if s, ok := seedValue.(string); ok { @@ -1215,7 +1254,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx "seed entry %d: value %q is not valid JSON", entryIdx, s)) } } - case ftype == "enum": + case ftype == specmeta.FieldTypeEnum: // The value must be one of the declared enum values. sv, ok := seedValue.(string) if !ok { @@ -1231,7 +1270,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx strings.Join(values, ", "))) } } - case ftype == "array": + case ftype == specmeta.FieldTypeArray: // Accept a YAML list. String values are accepted as JSON arrays. switch v := seedValue.(type) { case []any: @@ -1247,7 +1286,7 @@ func (v *Validator) validateSeedValueType(entityName, fieldName string, entryIdx errs = append(errs, invalidf(entityName, fieldName, "seed entry %d: value %v is not compatible with array type (expected a list)", entryIdx, seedValue)) } - case ftype == "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. @@ -1274,9 +1313,9 @@ func isValidJSONArray(s string) bool { } // 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. +// (ends with "Id" or "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") + return specmeta.HasIDSuffix(name) } 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}$`) diff --git a/internal/validator/validator_test.go b/internal/validator/validator_test.go index 17d8d6c..c581658 100644 --- a/internal/validator/validator_test.go +++ b/internal/validator/validator_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/specmeta" "github.com/DomainCraft/DomainCraft/internal/testutil" ) @@ -2759,3 +2760,63 @@ func TestValidateRejectsNegativeProjectNumericValues(t *testing.T) { }) } } + +func TestValidateRejectsInvalidNumericDefault(t *testing.T) { + t.Parallel() + cases := []struct { + name string + ftype string + defaultVal string + wantWarning bool + }{ + {name: "int rejects text", ftype: specmeta.FieldTypeInt, defaultVal: "abc", wantWarning: true}, + {name: "int accepts integer", ftype: specmeta.FieldTypeInt, defaultVal: "42"}, + {name: "bigint rejects text", ftype: specmeta.FieldTypeBigint, defaultVal: "twelve", wantWarning: true}, + {name: "bigint accepts integer", ftype: specmeta.FieldTypeBigint, defaultVal: "-9000000000"}, + {name: "float rejects text", ftype: specmeta.FieldTypeFloat, defaultVal: "1.2.3", wantWarning: true}, + {name: "float accepts decimal", ftype: specmeta.FieldTypeFloat, defaultVal: "1.25"}, + {name: "decimal rejects text", ftype: specmeta.FieldTypeDecimal, defaultVal: "price", wantWarning: true}, + {name: "decimal accepts decimal", ftype: specmeta.FieldTypeDecimal, defaultVal: "99.95"}, + {name: "legacy true still warns on int", ftype: specmeta.FieldTypeInt, defaultVal: "true", wantWarning: true}, + {name: "legacy false still warns on bigint", ftype: specmeta.FieldTypeBigint, defaultVal: "false", wantWarning: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + errs := validateDefaultValue("Item", "amount", c.ftype, c.defaultVal) + if c.wantWarning { + if len(errs) != 1 || !errs[0].Warning { + t.Fatalf("validateDefaultValue(%q, %q) = %v, want one warning", c.ftype, c.defaultVal, errs) + } + msg := errs[0].Message + if msg != strings.ToLower(msg) || strings.HasSuffix(msg, ".") { + t.Errorf("warning message %q is not lowercase or ends with punctuation", msg) + } + return + } + if len(errs) != 0 { + t.Fatalf("validateDefaultValue(%q, %q) = %v, want no warnings", 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 warnings", c.def, errs, c.want) + } + }) + } +} From 5d7972539ed6cf410e9e0d14f2b4776f29149ca6 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:26:37 +0300 Subject: [PATCH 36/83] Bridges: isolate caches by owner and gate contract and redirects --- compliance-suite/regressions.tsv | 11 +++ internal/bridge/clone.go | 43 +++++++++ internal/bridge/clone_policy_test.go | 138 +++++++++++++++++++++++++++ internal/bridge/hardening_test.go | 32 +++++++ internal/bridge/registry.go | 19 ---- internal/bridge/resolve_ext.go | 11 +++ internal/bridge/resolver.go | 4 +- internal/bridge/resolver_test.go | 41 ++++++++ internal/bridge/update.go | 104 +++++++++++++++++--- internal/netutil/netutil.go | 36 ++++++- internal/renderer/contract_test.go | 15 +++ internal/renderer/load.go | 19 ++-- 12 files changed, 424 insertions(+), 49 deletions(-) diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index c4f7b46..bb375cb 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -121,3 +121,14 @@ internal/seed/seed_test.go::TestGenerateRespectsExclusiveBounds #5 int and float internal/seed/seed_test.go::TestStringValueMaxLengthClamp #5 oversized max_length clamp was hand-rolled with no direct coverage at zero or above length internal/snapshot/snapshot_test.go::TestLoadRejectsIncompatibleFormatVersion #5 Load accepted snapshots with any format_version, so stale snapshots could trigger destructive prune internal/parser/parser_test.go::TestNavigationNameStripsIdAndIDSuffixOnly #5 HasIDSuffix treated lowercase id as an FK suffix and renamed fluid to Flu, squid to Squ and avoid to Avo +internal/bridge/clone_policy_test.go::TestCacheIsolationBetweenOwners #5 alice/utils and bob/utils shared one cache checkout including its migration commands +internal/bridge/clone_policy_test.go::TestApplyUpdateFallbackRejectsUnsupportedContract #5 re-clone fallback skipped the contract gate and cached an unsupported bridge +internal/renderer/contract_test.go::TestLoadSourceRejectsNegativeContractVersion #5 negative contract_version was accepted by the loader but rejected by the update gate +internal/bridge/resolver_test.go::TestResolveExtendsRelativeToAdapterDir #5 relative extends resolved against CWD instead of the adapter directory +internal/bridge/hardening_test.go::TestHTTPProbeRejectsRedirectBeforeFetch #5 update probe fetched a redirected host before checking the target +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 +cmd/domaincraft/commands_hardening_test.go::TestPruneRejectsScaffoldReplaceEscape #5 scaffold replacement under --prune deleted a file outside outputDir via a symlink +cmd/domaincraft/commands_update_security_test.go::TestReplaceExecutableUsesSameVolumeTemp #5 update binary was downloaded to the OS temp dir so rename into the executable directory failed with EXDEV +cmd/domaincraft/commands_hardening_test.go::TestPruneCleanupErrorPrintedOnce #5 failed namespace rewrite under --prune was warned about and then printed again as Error +cmd/domaincraft/commands_hardening_test.go::TestUsageErrorsExitTwo #5 bad flags, bad arguments and missing --bridge exited with code 1 instead of 2 diff --git a/internal/bridge/clone.go b/internal/bridge/clone.go index b23b3e7..a510135 100644 --- a/internal/bridge/clone.go +++ b/internal/bridge/clone.go @@ -27,6 +27,42 @@ func CachePath(entry RegistryEntry) string { return filepath.Join(CacheDir(), 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 { + return false // unreadable metadata is not proof of ownership + } + if meta == nil { + // Legacy cache without metadata: fall back to git's origin. A plain + // embedded materialization has no remote, so it stays usable. + out, gitErr := runGit(CachePath(entry), "remote", "get-url", "origin") + if gitErr != nil { + return true + } + return strings.Contains(out, entry.GitHub) + } + if meta.Source == "" { + return true // old metadata without a source cannot disprove ownership + } + return meta.Source == entry.GitHub +} + // 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 @@ -83,6 +119,13 @@ func EnsureBridge(entry RegistryEntry, opts *EnsureOptions) (string, error) { } 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. ok, err := TryMaterializeEmbedded(entry, opts) diff --git a/internal/bridge/clone_policy_test.go b/internal/bridge/clone_policy_test.go index 2d7f935..5af1a2d 100644 --- a/internal/bridge/clone_policy_test.go +++ b/internal/bridge/clone_policy_test.go @@ -154,6 +154,87 @@ func TestMaybeUpdatePolicies(t *testing.T) { } } +// 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 := filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", "main", "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") + src := filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, "main") + writeBridgeYAML(t, src, "bob-2.0.0") + testGit(t, src, "add", ".") + testGit(t, src, "commit", "-q", "-m", "bob version") + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", "main") + + 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 shouldApplyContract predicate: a bridge // declaring a newer contract must never be fetched into the cache. @@ -218,3 +299,60 @@ func TestApplyUpdateRejectsUnsupportedContract(t *testing.T) { 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 := filepath.Join(root, "remote.git") + testGit(t, root, "init", "--bare", "-b", "main", "remote.git") + testGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/main") + + src := filepath.Join(root, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + makeBridgeRepo(t, src, "main") + testGit(t, src, "remote", "add", "origin", remote) + testGit(t, src, "push", "-q", "-u", "origin", "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{Entry: entry, 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/hardening_test.go b/internal/bridge/hardening_test.go index 4f27390..73834cf 100644 --- a/internal/bridge/hardening_test.go +++ b/internal/bridge/hardening_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "github.com/DomainCraft/DomainCraft/internal/appdir" @@ -293,6 +294,37 @@ func TestHTTPProbeLimitsAndRedaction(t *testing.T) { } } +// 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) { diff --git a/internal/bridge/registry.go b/internal/bridge/registry.go index 1fa7947..351f01d 100644 --- a/internal/bridge/registry.go +++ b/internal/bridge/registry.go @@ -148,22 +148,3 @@ func (r *Registry) ByID(id string) *RegistryEntry { } 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/resolve_ext.go b/internal/bridge/resolve_ext.go index d4045fc..54b803c 100644 --- a/internal/bridge/resolve_ext.go +++ b/internal/bridge/resolve_ext.go @@ -35,6 +35,17 @@ 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) } diff --git a/internal/bridge/resolver.go b/internal/bridge/resolver.go index 135ffbb..8ada49b 100644 --- a/internal/bridge/resolver.go +++ b/internal/bridge/resolver.go @@ -79,7 +79,9 @@ func (r *Resolver) Resolve(input string) (string, error) { } } entry := RegistryEntry{ - ID: parts[1], + // 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) diff --git a/internal/bridge/resolver_test.go b/internal/bridge/resolver_test.go index c20f069..cf409bf 100644 --- a/internal/bridge/resolver_test.go +++ b/internal/bridge/resolver_test.go @@ -95,6 +95,47 @@ 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) { diff --git a/internal/bridge/update.go b/internal/bridge/update.go index 794af65..a10afbe 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" "net/http" + "net/url" "os" "os/exec" + "path/filepath" "strings" "time" @@ -34,41 +36,65 @@ const DefaultUpdateInterval = 24 * time.Hour // be applied. const CoreContractVersion = specmeta.ContractVersion -// parseBridgeContractVersion reads `contract_version` from bridge.yaml bytes. -// An absent field means contract v1. Any other unreadable value is an error: +// 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 parseBridgeContractVersion(data []byte) (int, error) { +func ParseContractVersion(data []byte) (int, bool, error) { // A truncated body may still be valid YAML (e.g. a scalar or a list), so // require the document to be a mapping before reading the version. var probe any if err := yaml.Unmarshal(data, &probe); err != nil { - return 0, fmt.Errorf("parse bridge contract version: %w", err) + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) } if _, ok := probe.(map[string]any); !ok { - return 0, fmt.Errorf("parse bridge contract version: manifest must be a YAML mapping") + 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 0, fmt.Errorf("parse bridge contract version: %w", err) + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) + } + if cfg.ContractVersion == nil { + return CoreContractVersion, false, nil + } + if *cfg.ContractVersion < 0 { + return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) } - if cfg.ContractVersion < 0 { - return 0, fmt.Errorf("invalid contract_version %d", cfg.ContractVersion) + if *cfg.ContractVersion == 0 { + return CoreContractVersion, false, nil } - return specmeta.EffectiveContractVersion(cfg.ContractVersion), nil + return *cfg.ContractVersion, true, nil +} + +// parseBridgeContractVersion keeps the update-side seam used by probes and +// tests; the parsing itself lives in ParseContractVersion. +func parseBridgeContractVersion(data []byte) (int, error) { + version, _, err := ParseContractVersion(data) + return version, err } -// 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 } +func shouldApplyContract(contractVersion int) error { + return CheckContractVersion(contractVersion) +} + // remoteContractVersion fetches a bridge's declared contract version at a ref // without cloning, via the GitHub raw-content endpoint. An unreadable manifest // is an error: callers treat it as "cannot offer update" rather than guessing @@ -220,9 +246,35 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { return "", errors.Join(append(fastPathErrs, fmt.Errorf("re-clone bridge %q into %q: %w", entry.ID, cacheDir, err))...) } + // 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")) //nolint:gosec // path built from a validated cache ID + if err != nil { + return fmt.Errorf("read re-cloned bridge manifest: %w", err) + } + version, _, err := ParseContractVersion(data) + if err != nil { + return err + } + return CheckContractVersion(version) +} + // 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) { @@ -300,11 +352,33 @@ func githubAPIHead(entry RegistryEntry) (branch, commit string, err error) { // maxProbeBodyBytes caps remote probe responses (bridge.yaml, GitHub JSON). const maxProbeBodyBytes = 1 << 20 +// 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) + } + host := strings.ToLower(u.Hostname()) + switch host { + case "github.com", "api.github.com", "raw.githubusercontent.com": + return nil + default: + return fmt.Errorf("host %q is not allowed", host) + } +} + // 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. +// 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), nil) + return netutil.BoundedGet(CommandContext(), httpClient, rawURL, int64(maxProbeBodyBytes), validateProbeRedirect) } // runGit runs a git command in dir and returns its trimmed stdout. diff --git a/internal/netutil/netutil.go b/internal/netutil/netutil.go index d1af103..6167d34 100644 --- a/internal/netutil/netutil.go +++ b/internal/netutil/netutil.go @@ -39,10 +39,28 @@ func redactURLError(err error) error { // 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, including the -// target of any redirect the client followed. +// 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) @@ -50,7 +68,8 @@ func ReadBoundedBody(resp *http.Response, rawURL string, maxBytes int64, validat 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 { + 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)) } @@ -73,14 +92,21 @@ func ReadBoundedBody(resp *http.Response, rawURL string, maxBytes int64, validat // 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: its timeout and redirect policy -// are applied unchanged. +// 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)) diff --git a/internal/renderer/contract_test.go b/internal/renderer/contract_test.go index 5700290..ec2bcf1 100644 --- a/internal/renderer/contract_test.go +++ b/internal/renderer/contract_test.go @@ -46,6 +46,21 @@ func TestLoadSourceDefaultsAbsentContractTo1(t *testing.T) { } } +// 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) { t.Parallel() dir := writeBridgeConfig(t, "name: b\ncontract_version: 1\n") diff --git a/internal/renderer/load.go b/internal/renderer/load.go index 4c06e7c..c372ece 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -135,17 +135,18 @@ func loadSource(bridgePath string) (sourceConfig, error) { if config.OutputDir == "" { config.OutputDir = "generated" } - // Contract version: absent (0) means the core's contract version, with a - // deprecation notice (emitted by the caller); a newer contract is an error. - contractDeclared := config.ContractVersion != 0 - if config.ContractVersion == 0 { - config.ContractVersion = ContractVersion + // 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) } + config.ContractVersion = contractVersion return sourceConfig{dir: bridgeDir, config: config, contractDeclared: contractDeclared}, nil } From 5abb07cd0f9ad210b697c9aef416f5596b84be37 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:26:43 +0300 Subject: [PATCH 37/83] Renderer: keep language syntax in bridge type mappings --- internal/packages/cache.go | 3 +- internal/renderer/bridgefuncs_test.go | 117 +++++++++++++++++-- internal/renderer/render.go | 61 +++++----- internal/renderer/render_test.go | 15 +++ internal/renderer/templates.go | 156 +++++++++++++++----------- 5 files changed, 244 insertions(+), 108 deletions(-) diff --git a/internal/packages/cache.go b/internal/packages/cache.go index a4b5147..417a642 100644 --- a/internal/packages/cache.go +++ b/internal/packages/cache.go @@ -1,6 +1,7 @@ package packages import ( + "errors" "fmt" "os" "path/filepath" @@ -62,7 +63,7 @@ func versionStore(bridgeID string) (map[string]versionEntry, error) { } // 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) { + if err := fsutil.ReadJSON(filepath.Join(dir, CacheFileName), &data); err != nil && !errors.Is(err, os.ErrNotExist) { return nil, err } if data.Entries == nil { diff --git a/internal/renderer/bridgefuncs_test.go b/internal/renderer/bridgefuncs_test.go index a0a0560..6b24b5c 100644 --- a/internal/renderer/bridgefuncs_test.go +++ b/internal/renderer/bridgefuncs_test.go @@ -95,14 +95,60 @@ 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) @@ -137,8 +183,8 @@ func TestBuildBridgeFuncs_LiteralDefault(t *testing.T) { 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 { @@ -171,10 +217,10 @@ 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) } } @@ -221,8 +267,8 @@ 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) } } @@ -262,7 +308,58 @@ 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) + } +} diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 21b0c7c..bc50769 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -38,13 +38,10 @@ func safeBridgeSource(dir, rel string) (string, error) { return path, nil } -// 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) { +// 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 "", fmt.Errorf("template target path %s: %w", renderedTarget, err) @@ -53,28 +50,29 @@ func safeOutputPath(outputDir, renderedTarget string) (string, error) { if err != nil { return "", fmt.Errorf("resolve output directory: %w", err) } - if err := fsutil.RefuseSymlinks(absOutput, absTarget); err != nil { + if err := refuse(absOutput, absTarget); err != nil { return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) } return absTarget, nil } +// 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) { - absTarget, _, err := fsutil.LocalPathWithin(outputDir, renderedTarget) - if err != nil { - 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 := fsutil.RefuseSymlinksCached(absOutput, absTarget, verified); err != nil { - return "", fmt.Errorf("template target path %s: %w", renderedTarget, err) - } - return absTarget, nil + return safeOutputPathChecked(outputDir, renderedTarget, func(base, target string) error { + return fsutil.RefuseSymlinksCached(base, target, verified) + }) } // beforeCommitHook is a test seam called once between staging and commit. It is @@ -162,8 +160,8 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } // 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). + // The project's platform constrains the major version; the core bakes in no + // language-specific framework default. pkgs := r.resolvePackages(project) // Parse shared helper templates from every bridge in the chain (base first, @@ -387,7 +385,7 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re // files are already correct and rollback must not consume the backups now. for _, w := range committed { if w.backup != "" { - if err := os.Remove(w.backup); err != nil && !errors.Is(err, os.ErrNotExist) && r.log != nil { + if err := os.Remove(w.backup); err != nil && !errors.Is(err, os.ErrNotExist) { r.log.Warn("remove backup %s: %v", w.backup, err) } } @@ -478,14 +476,17 @@ 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.Project) map[string]string { - framework := "" - if project != nil { - framework = project.Platform - } - if framework == "" { - framework = "net10.0" // same default as the C# csproj templates +// targetFramework returns the project's declared platform. An absent platform +// leaves package version selection unconstrained — the core has no TFM default. +func targetFramework(project *ir.Project) string { + if project == nil { + return "" } + return project.Platform +} + +func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { + framework := targetFramework(project) // Merge registry_packages from all sources in the chain (base-first, // adapter wins on conflicts — consistent with type_mappings merge). diff --git a/internal/renderer/render_test.go b/internal/renderer/render_test.go index be6befd..6849b66 100644 --- a/internal/renderer/render_test.go +++ b/internal/renderer/render_test.go @@ -353,6 +353,21 @@ func TestRenderContext_PrimaryKey(t *testing.T) { } } +// The core must not bake in a language-specific TFM (net10.0) when a project +// declares no platform: package resolution stays unconstrained. +func TestResolvePackagesHasNoLanguageSpecificFrameworkDefault(t *testing.T) { + t.Parallel() + if got := targetFramework(nil); got != "" { + t.Errorf("targetFramework(nil) = %q, want empty (no core-side default)", got) + } + if got := targetFramework(&ir.Project{}); got != "" { + t.Errorf("targetFramework(empty project) = %q, want empty (no core-side default)", got) + } + if got := targetFramework(&ir.Project{Platform: "net11.0"}); got != "net11.0" { + t.Errorf("targetFramework(net11.0) = %q, want the declared platform", got) + } +} + func TestResolvePackagesNilLoggerDoesNotPanic(t *testing.T) { t.Parallel() // A nil logger is valid (silent mode). A failed registry lookup must not diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index 9a719ac..a3a64fd 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -3,6 +3,7 @@ package renderer import ( "cmp" "encoding/json" + "errors" "fmt" "maps" "os" @@ -88,7 +89,7 @@ func (r *Renderer) loadTypeMappings(dir string) (*typeMappings, error) { } data, err := os.ReadFile(path) //nolint:gosec // path passed safeBridgeSource validation if err != nil { - if os.IsNotExist(err) { + if errors.Is(err, os.ErrNotExist) { return nil, nil } return nil, err @@ -110,25 +111,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)) - maps.Copy(m, dst) - maps.Copy(m, src) - 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), + 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), @@ -141,13 +133,15 @@ func mergeTypeMappings(base, overlay *typeMappings) *typeMappings { 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)) - maps.Copy(m, base) - maps.Copy(m, overlay) + m := make(map[string]V, len(dst)+len(src)) + maps.Copy(m, dst) + maps.Copy(m, src) return m } @@ -166,6 +160,21 @@ func (r *Renderer) getBridgeSpecificFuncs() (map[string]any, 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...) +} + +// 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(log *logger.Logger, kind, key string) { + log.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. @@ -174,38 +183,31 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) 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 - } // wrapNullable applies the bridge-specific nullable format to a type name. wrapNullable := func(typeName string) string { - return typeName + nullableSuffix + return typeName + m.NullableFormat } // Build set of value types for quick lookup - valueTypeSet := make(map[string]bool, len(mapping.ValueTypes)) - for _, vt := range mapping.ValueTypes { + valueTypeSet := make(map[string]bool, len(m.ValueTypes)) + for _, vt := range m.ValueTypes { valueTypeSet[vt] = true } // 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(log, "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) } @@ -220,7 +222,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { if specmeta.IsArrayType(dbType) { return wrapArray(formatted) } - if nullable && mapping.EnumNullable { + if nullable && m.EnumNullable { return wrapNullable(formatted) } return formatted @@ -228,7 +230,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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) @@ -245,7 +247,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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] + spec := m.Literals[dbType] switch kind { case "text": return jsonValue(value) @@ -253,34 +255,47 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { return fmt.Sprintf("%v", value) + spec.Suffix case "uuid", "date", "datetime", "json": if spec.Parse == "" { - return jsonValue(value) + warnMissingSpec(log, "literals.parse", dbType) + return jsonValue(value) // JSON literal is language-neutral, not a target-language expression } - return fmt.Sprintf(spec.Parse, jsonValue(value)) + return formatSpec(spec.Parse, jsonValue(value)) case "enum": - e := mapping.Literals["enum"] + e := m.Literals["enum"] if e.Parse == "" { + warnMissingSpec(log, "literals.enum.parse", dbType) return jsonValue(value) } - return fmt.Sprintf(e.Parse, languageType(dbType, false), jsonValue(textutil.PascalCase(fmt.Sprintf("%v", value)))) + return formatSpec(e.Parse, languageType(dbType, false), jsonValue(textutil.PascalCase(fmt.Sprintf("%v", value)))) } return jsonValue(value) } // literalDefault renders the value-less default expression for a type: - // a scalar default, a zero-valued enum, or an empty array. + // 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. bridgeFuncs["literalDefault"] = func(dbType string) string { - if ir.KindOf(dbType) == "array" { - return fmt.Sprintf(mapping.Array.Empty, languageType(dbType, false)) + kind := ir.KindOf(dbType) + if kind == "array" { + if m.Array.Empty == "" { + warnMissingSpec(log, "array.empty", dbType) + return "" + } + return formatSpec(m.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)) + spec := m.Literals[dbType] + if kind == "enum" { + if spec.Zero == "" { + spec = m.Literals["enum"] // generic enum spec covers user-declared enums } - return fmt.Sprintf("(%s)0", languageType(dbType, false)) + if spec.Zero == "" { + warnMissingSpec(log, "literals.zero", dbType) + return "" + } + return formatSpec(spec.Zero, languageType(dbType, false)) } if spec.Default == "" { - return "default(" + languageType(dbType, false) + ")" + warnMissingSpec(log, "literals.default", dbType) + return "" } return spec.Default } @@ -289,10 +304,12 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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)) + spec := m.Literals["enum"] + if spec.Member == "" { + warnMissingSpec(log, "literals.enum.member", dbType) + return "" } - return languageType(dbType, false) + "." + textutil.PascalCase(value) + return formatSpec(spec.Member, languageType(dbType, false), textutil.PascalCase(value)) } return jsonValue(value) } @@ -300,14 +317,18 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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)) + if m.Array.Open == "" { + warnMissingSpec(log, "array.open", dbType) + return "" + } + return formatSpec(m.Array.Open, languageType(dbType, false)) } bridgeFuncs["arrayLiteralClose"] = func() string { - return mapping.Array.Close + return m.Array.Close } bridgeFuncs["isValueType"] = func(typeName string) bool { - if mapped, ok := mapping.Types[typeName]; ok { + if mapped, ok := m.Types[typeName]; ok { return valueTypeSet[mapped] } return false @@ -315,7 +336,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { bridgeFuncs["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) @@ -327,24 +348,25 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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 { + if len(m.ColumnSizes) > 0 { bridgeFuncs["columnSize"] = func(dbType string) string { - return mapping.ColumnSizes[dbType] + 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 { + // 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 { bridgeFuncs["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(log, "input type", dbType) + return "" } } From 47fb358a1af759e00f80f445c9e82b6f8aad64c2 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:26:48 +0300 Subject: [PATCH 38/83] CLI: harden prune paths, command display and update install --- cmd/domaincraft/commands.go | 121 ++++++++++-- cmd/domaincraft/commands_extends_test.go | 153 +++++++++++++++ cmd/domaincraft/commands_hardening_test.go | 180 +++++++++++++++++- cmd/domaincraft/commands_prune_test.go | 13 +- .../commands_update_security_test.go | 43 ++++- cmd/domaincraft/commands_update_test.go | 2 +- cmd/domaincraft/main.go | 4 + cmd/domaincraft/update.go | 21 +- 8 files changed, 502 insertions(+), 35 deletions(-) diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index d613d0d..bae26aa 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -114,11 +114,54 @@ func init() { } } +// 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 } + +func (u usageError) Error() string { return u.err.Error() } +func (u usageError) Unwrap() error { return u.err } +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} +} + +// 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(err error) { + _, _ = fmt.Fprintln(os.Stderr, "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. +// Errors raised before the command's PersistentPreRun (unknown flag, unknown +// command, failed argument validation) are usage errors by construction. func Execute() error { - if err := newRootCommand().Execute(); err != nil { - _, _ = fmt.Fprintln(os.Stderr, "Error:", err) + root := newRootCommand() + 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(err) + if !reachedRun || errors.Is(err, errUsage) { + return asUsageError(err) + } return err } return nil @@ -272,7 +315,7 @@ func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { // Parse --replace flags (layer|bridgeId=bridgeRef). replacements, err := parseReplaceFlags(opts.replaceFlags) if err != nil { - return err + return asUsageError(err) } // Resolve extends chain with optional node replacements. newBridgePath, basePaths, err := resolveChainWithReplacements(opts, opts.bridgePath, replacements, log) @@ -317,7 +360,7 @@ func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { // argument is rejected by cobra.MaximumNArgs(1) / the check below. if len(args) > 0 { if !cmd.Flags().Changed("admin") || opts.adminBridge != "admin-alpine" { - return fmt.Errorf("unexpected positional argument %q: use --admin ", args[0]) + return asUsageError(fmt.Errorf("unexpected positional argument %q: use --admin ", args[0])) } opts.adminBridge = args[0] } @@ -551,7 +594,7 @@ func resolveBridgeInteractive(opts *cliOptions, log *logger.Logger) (string, str } if opts.nonInteractive || !isTerminal() { - return "", "", fmt.Errorf("--bridge is required in non-interactive mode") + return "", "", asUsageError(fmt.Errorf("--bridge is required in non-interactive mode")) } entry, err := interactive.SelectBridge(bridge.Default()) @@ -895,10 +938,29 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co // 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 +} + // sanitizeCommandLine removes terminal control characters from a bridge-declared -// command before it is displayed or logged. Tab and newline are kept; C0 (other -// than those two), C1, CSI/OSC sequences, bare ESC and invalid UTF-8 bytes are -// dropped. The command itself is never modified — only its presentation. +// 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 @@ -910,11 +972,18 @@ func sanitizeCommandLine(s string) string { continue } if c < utf8.RuneSelf { - if (c < 0x20 && c != '\t' && c != '\n') || c == 0x7f { - i++ - continue + switch c { + case '\t': + b.WriteString(`\t`) + case '\n': + b.WriteString(`\n`) + default: + if (c < 0x20) || c == 0x7f { + i++ + continue + } + b.WriteByte(c) } - b.WriteByte(c) i++ continue } @@ -927,6 +996,11 @@ func sanitizeCommandLine(s string) string { i += size continue } + if isInvisibleFormat(r) { + b.WriteString(fmt.Sprintf("", r)) + i += size + continue + } b.WriteString(s[i : i+size]) i += size } @@ -983,7 +1057,8 @@ func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[stri } rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.NamespaceTransform(diff.NamespaceRename)) if err != nil { - mc.log.Warn("could not rewrite namespace in %s: %v", rel, err) + // Under --prune the error is returned and printed once by + // Execute(); a Warn here would print the same failure twice. failures = append(failures, fmt.Errorf("rewrite namespace in %s: %w", rel, err)) continue } @@ -999,7 +1074,6 @@ func applyMigrationActions(opts *cliOptions, diff *snapshot.Diff, fresh map[stri } rewrote, err := snapshot.RewriteFile(opts.outputDir, rel, snapshot.FieldTransform(fr)) if err != nil { - mc.log.Warn("could not rewrite field references in %s: %v", rel, err) failures = append(failures, fmt.Errorf("rewrite field references in %s: %w", rel, err)) continue } @@ -1098,9 +1172,10 @@ func handleDeletedEntity(mc migrationContext, del snapshot.DeletedEntity) (bool, continue } if err := snapshot.DeleteFile(mc.opts.outputDir, f.Path); err != nil { - mc.log.Warn("could not delete %s: %v", f.Path, err) if mc.opts.prune { failures = append(failures, fmt.Errorf("delete %s: %w", f.Path, err)) + } else { + mc.log.Warn("could not delete %s: %v", f.Path, err) } continue } @@ -1143,27 +1218,32 @@ func handleRename(mc migrationContext, ren snapshot.Rename, d *snapshot.Diff) (b // 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(mc.opts.outputDir, filepath.FromSlash(newRel))); err != nil { - mc.log.Warn("could not replace scaffolded %s: %v", newRel, err) + // Use the validated helper: a poisoned snapshot path must never + // remove a file outside outputDir (including through a symlink). + if err := snapshot.DeleteFile(mc.opts.outputDir, newRel); err != nil { if mc.opts.prune { failures = append(failures, fmt.Errorf("replace scaffolded %s: %w", newRel, err)) + } else { + mc.log.Warn("could not replace scaffolded %s: %v", newRel, err) } continue } } newRel, renamed, err := snapshot.RenameEntityFile(mc.opts.outputDir, f.Path, ren.OldName, ren.NewName) if err != nil { - mc.log.Warn("could not rename %s: %v", f.Path, err) if mc.opts.prune { failures = append(failures, fmt.Errorf("rename %s: %w", f.Path, err)) + } else { + mc.log.Warn("could not rename %s: %v", f.Path, err) } continue } if renamed { if rewrote, rerr := snapshot.RewriteFile(mc.opts.outputDir, newRel, snapshot.RenameTransforms(ren.OldName, ren.NewName, d)...); rerr != nil { - mc.log.Warn("could not rewrite content of %s: %v", newRel, rerr) if mc.opts.prune { failures = append(failures, fmt.Errorf("rewrite content of %s: %w", newRel, rerr)) + } else { + mc.log.Warn("could not rewrite content of %s: %v", newRel, rerr) } } else if rewrote { mc.log.Info("renamed %s -> %s (content updated)", f.Path, newRel) @@ -1175,9 +1255,10 @@ func handleRename(mc migrationContext, ren snapshot.Rename, d *snapshot.Diff) (b } // 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.log.Warn("could not delete stale generated file %s: %v", f.Path, err) if mc.opts.prune { failures = append(failures, fmt.Errorf("delete stale generated file %s: %w", f.Path, err)) + } else { + mc.log.Warn("could not delete stale generated file %s: %v", f.Path, err) } continue } diff --git a/cmd/domaincraft/commands_extends_test.go b/cmd/domaincraft/commands_extends_test.go index 192a7ab..4066449 100644 --- a/cmd/domaincraft/commands_extends_test.go +++ b/cmd/domaincraft/commands_extends_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "os" "path/filepath" "strings" @@ -28,6 +29,158 @@ func writeBridgeDir(t *testing.T, dir, extends string) string { 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() diff --git a/cmd/domaincraft/commands_hardening_test.go b/cmd/domaincraft/commands_hardening_test.go index cf7ed18..1ce2dde 100644 --- a/cmd/domaincraft/commands_hardening_test.go +++ b/cmd/domaincraft/commands_hardening_test.go @@ -163,6 +163,177 @@ func TestCleanupDeferred(t *testing.T) { } } +// 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() + mc := migrationContext{ + opts: &cliOptions{outputDir: output, prune: true}, + fresh: map[string]bool{newRel: true}, // scaffolded destination triggers the replace path + log: logger.New(), + out: &bytes.Buffer{}, + } + ren := snapshot.Rename{ + OldName: "Old", + NewName: "New", + Files: []snapshot.FileRef{{Path: oldRel, Custom: true}}, + } + applied, err := handleRename(mc, ren, &snapshot.Diff{}) + if applied || err == nil { + t.Fatalf("handleRename = %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(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, oldStderr, oldVersion, oldCtx := os.Args, os.Stderr, version, commandCtx + version = "dev" + // run() cancels the context it installs via its deferred stop(); restore + // the package-level context so later tests keep a live one. + t.Cleanup(func() { os.Args, os.Stderr, version, commandCtx = oldArgs, oldStderr, oldVersion, 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) + } + + bridgeDir := pruneBridge(t, "") + cases := []struct { + name string + args []string + want int + }{ + {"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, os.Stderr = tc.args, f + 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 @@ -172,10 +343,17 @@ func TestSanitizeCommandLine(t *testing.T) { {"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"}, + {"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) { diff --git a/cmd/domaincraft/commands_prune_test.go b/cmd/domaincraft/commands_prune_test.go index 46186ae..f67d36a 100644 --- a/cmd/domaincraft/commands_prune_test.go +++ b/cmd/domaincraft/commands_prune_test.go @@ -334,7 +334,7 @@ func TestPruneCLICleanupFailureKeepsSnapshot(t *testing.T) { entity: "Item", fields: map[string]string{"title": "string"}, file: renderer.RenderedFile{Path: "src/LegacyService.txt", Entity: "Item", Custom: true}, - wantDiag: "could not rewrite field references", + wantDiag: "rewrite field references in src/LegacyService.txt", }, { name: "failed orphan delete", @@ -342,7 +342,7 @@ func TestPruneCLICleanupFailureKeepsSnapshot(t *testing.T) { entity: "Old", fields: map[string]string{"id": "uuid"}, file: renderer.RenderedFile{Path: "src/OldService.txt", Entity: "Old", Custom: true}, - wantDiag: "could not delete", + wantDiag: "delete src/OldService.txt", }, } @@ -372,8 +372,13 @@ func TestPruneCLICleanupFailureKeepsSnapshot(t *testing.T) { if err == nil { t.Fatalf("generate --prune should fail; stdout: %s", stdout) } - if !strings.Contains(stderr, tt.wantDiag) { - t.Errorf("stderr = %q, want %q", stderr, tt.wantDiag) + // 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) diff --git a/cmd/domaincraft/commands_update_security_test.go b/cmd/domaincraft/commands_update_security_test.go index d5206ee..e1f566b 100644 --- a/cmd/domaincraft/commands_update_security_test.go +++ b/cmd/domaincraft/commands_update_security_test.go @@ -435,7 +435,7 @@ func TestDownloadBinaryChmodFailure(t *testing.T) { chmodErr := errors.New("chmod denied") chmodFn = func(string, os.FileMode) error { return chmodErr } - path, err := downloadBinary("https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64") + path, err := downloadBinary("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) } @@ -444,6 +444,47 @@ func TestDownloadBinaryChmodFailure(t *testing.T) { } } +// 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, oldHTTP, oldExe, oldReplace, oldCreateTemp := version, httpGetBodyFn, executableFn, replaceExecutableFn, createTempFn + t.Cleanup(func() { + version, httpGetBodyFn, executableFn, replaceExecutableFn, createTempFn = oldVersion, oldHTTP, oldExe, oldReplace, oldCreateTemp + }) + + root := t.TempDir() + exe := filepath.Join(root, "domaincraft") + assets, bodies := updatePayload([]byte("new binary")) + version = "1.0.0" + httpGetBodyFn = fakeUpdateServer("v1.2.0", assets, bodies) + executableFn = func() (string, error) { return exe, nil } + + var tempDir, installedFrom string + createTempFn = func(dir, pattern string) (*os.File, error) { + tempDir = dir + return os.CreateTemp(dir, pattern) + } + replaceExecutableFn = 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 := runCoreUpdate(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) { stubFileOps(t) root := t.TempDir() diff --git a/cmd/domaincraft/commands_update_test.go b/cmd/domaincraft/commands_update_test.go index 45688f9..179f5c5 100644 --- a/cmd/domaincraft/commands_update_test.go +++ b/cmd/domaincraft/commands_update_test.go @@ -140,7 +140,7 @@ func TestDownloadAndReplace(t *testing.T) { } defer func() { httpGetBodyFn = oldHTTP }() - tmp, err := downloadBinary("https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64") + tmp, err := downloadBinary("https://github.com/DomainCraft/DomainCraft/releases/download/v1.2.3/domaincraft-linux-amd64", t.TempDir()) if err != nil { t.Fatalf("downloadBinary: %v", err) } diff --git a/cmd/domaincraft/main.go b/cmd/domaincraft/main.go index ab61081..810a10e 100644 --- a/cmd/domaincraft/main.go +++ b/cmd/domaincraft/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "os" "os/signal" "syscall" @@ -21,6 +22,9 @@ func run() int { commandCtx = ctx bridge.SetCommandContext(ctx) if err := Execute(); err != nil { + if errors.Is(err, errUsage) { + return 2 + } return 1 } return 0 diff --git a/cmd/domaincraft/update.go b/cmd/domaincraft/update.go index 82ce1a0..eb9ae8c 100644 --- a/cmd/domaincraft/update.go +++ b/cmd/domaincraft/update.go @@ -61,6 +61,7 @@ var ( chmodFn = os.Chmod renameFn = os.Rename removeFn = os.Remove + createTempFn = os.CreateTemp ) // githubRelease is the subset of the GitHub releases/latest payload we need. @@ -193,7 +194,13 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { if err != nil { return err } - tmp, err := downloadBinary(assetURL) + // 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 := executableFn() + if err != nil { + return fmt.Errorf("locate current executable: %w", err) + } + tmp, err := downloadBinary(assetURL, filepath.Dir(exe)) if err != nil { return err } @@ -203,10 +210,6 @@ func runCoreUpdate(log *logger.Logger, checkOnly bool) error { return fmt.Errorf("refusing to install update: %w", err) } - exe, err := executableFn() - if err != nil { - return fmt.Errorf("locate current executable: %w", err) - } if err := replaceExecutableFn(tmp, exe); err != nil { return err } @@ -378,8 +381,10 @@ func readResponseBody(resp *http.Response, rawURL string) ([]byte, error) { return netutil.ReadBoundedBody(resp, rawURL, maxResponseBody, validateReleaseRedirect) } -// downloadBinary fetches a release asset into a temp file and returns its path. -func downloadBinary(rawURL string) (string, error) { +// downloadBinary 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 downloadBinary(rawURL, dir string) (string, error) { validURL, err := validateReleaseURL(rawURL) if err != nil { return "", fmt.Errorf("download update: %w", err) @@ -389,7 +394,7 @@ func downloadBinary(rawURL string) (string, error) { return "", fmt.Errorf("download update: %w", err) } - tmp, err := os.CreateTemp("", "domaincraft-update-*") + tmp, err := createTempFn(dir, "domaincraft-update-*") if err != nil { return "", err } From 16e26eab5d2bc48d54732d577295974c5ae91b07 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:33:33 +0300 Subject: [PATCH 39/83] Renderer: split Render phases and bridge function registration --- internal/renderer/bridgefuncs_test.go | 36 +++++ internal/renderer/hardening_test.go | 141 ++++++++++++++++ internal/renderer/load_test.go | 134 ++++++++++++++++ internal/renderer/render.go | 223 ++++++++++++++++---------- internal/renderer/templates.go | 66 +++++--- 5 files changed, 488 insertions(+), 112 deletions(-) diff --git a/internal/renderer/bridgefuncs_test.go b/internal/renderer/bridgefuncs_test.go index 6b24b5c..10fe546 100644 --- a/internal/renderer/bridgefuncs_test.go +++ b/internal/renderer/bridgefuncs_test.go @@ -1,6 +1,8 @@ package renderer import ( + "maps" + "slices" "testing" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -35,6 +37,40 @@ 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()) diff --git a/internal/renderer/hardening_test.go b/internal/renderer/hardening_test.go index 1fdcb01..63197d6 100644 --- a/internal/renderer/hardening_test.go +++ b/internal/renderer/hardening_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "path/filepath" + "reflect" "strings" "testing" @@ -374,3 +375,143 @@ func TestRollbackErrorKeepsOriginalPrimary(t *testing.T) { t.Error("no-op rollback must return the original error unchanged") } } + +// 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 := writeHardeningBridge(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) + } + + beforeCommitHook = func() { + if err := os.Symlink(outside, filepath.Join(out2, "shared.txt")); err != nil { + t.Errorf("plant symlink before commit: %v", err) + } + } + t.Cleanup(func() { beforeCommitHook = 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) + } + } + }) +} diff --git a/internal/renderer/load_test.go b/internal/renderer/load_test.go index a812491..b8db833 100644 --- a/internal/renderer/load_test.go +++ b/internal/renderer/load_test.go @@ -3,6 +3,7 @@ package renderer import ( "os" "path/filepath" + "slices" "strings" "testing" ) @@ -70,3 +71,136 @@ func TestLoadSourceFailsClosedOnMissingBridgeYaml(t *testing.T) { t.Fatalf("loadSource on a directory without bridge.yaml = %v, want a hard error naming bridge.yaml", err) } } + +// 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/render.go b/internal/renderer/render.go index bc50769..df8f58a 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -142,31 +142,10 @@ func rollbackError(err, rollbackErr error) error { return errors.Join(err, fmt.Errorf("rollback writes: %w", rollbackErr)) } -// 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) - - // 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. +// 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 == "" { @@ -174,11 +153,11 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } helperPath, err := safeBridgeSource(src.dir, src.config.Helpers) if err != nil { - return nil, nil, err + return nil, err } helperBytes, err := os.ReadFile(helperPath) //nolint:gosec // helperPath passed safeBridgeSource validation 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)) @@ -186,62 +165,75 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re 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 +} - // verified holds directories checked by the pre-MkdirAll containment pass - // in Phase 1. It is local to this Render and never reused across passes: - // the post-MkdirAll pass below stays fully fresh, because MkdirAll itself - // can create components and an attacker can plant a link between calls. - verified := make(map[string]bool) - staged := make([]stagedWrite, 0) - // committed is empty during staging; phase 2 appends to it as files land. - committed := make([]stagedWrite, 0) - manifest := make([]RenderedFile, 0) - // fail drops every staged temp file (and restores committed files once - // phase 2 starts), attaching any rollback failure to the primary error. - fail := func(err error) ([]string, []RenderedFile, error) { - return nil, nil, rollbackError(err, rollbackWrites(staged, committed)) - } +// 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 + staged []stagedWrite + committed []stagedWrite + manifest []RenderedFile +} + +// 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)) +} - // Phase 1: parse templates and render each target into a temp file. Nothing - // is written to outputDir until every template has executed successfully. +// 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, err := safeBridgeSource(src.dir, spec.Source) if err != nil { - return fail(err) + return s.fail(err) } tplBytes, err := os.ReadFile(sourcePath) //nolint:gosec // sourcePath passed safeBridgeSource validation if err != nil { - return fail(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 fail(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 fail(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 fail(err) + return s.fail(err) } for _, context := range contexts { @@ -256,14 +248,14 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re } for _, targetPattern := range spec.TargetPatterns() { - renderedTarget, err := renderTemplateString(targetPattern, context, funcMap) + renderedTarget, err := renderTemplateString(targetPattern, context, s.funcMap) if err != nil { - return fail(fmt.Errorf("render target path: %w", err)) + return s.fail(fmt.Errorf("render target path: %w", err)) } - absTarget, err := safeOutputPathCached(outputDir, renderedTarget, verified) + absTarget, err := safeOutputPathCached(s.outputDir, renderedTarget, s.verified) if err != nil { - return fail(err) + return s.fail(err) } relPath := filepath.ToSlash(renderedTarget) @@ -279,33 +271,33 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re if spec.IsCustom() { if _, statErr := os.Stat(absTarget); statErr == nil { record.Written = false - manifest = append(manifest, record) + s.manifest = append(s.manifest, record) continue } } if err := os.MkdirAll(filepath.Dir(absTarget), 0o755); err != nil { //nolint:gosec // generated project dirs must stay world-readable - return fail(fmt.Errorf("create output dir: %w", err)) + return s.fail(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(outputDir, renderedTarget); err != nil { - return fail(err) + if _, err := safeOutputPath(s.outputDir, renderedTarget); err != nil { + return s.fail(err) } existed := false mode := os.FileMode(0o644) // os.Create's default under the usual umask if info, statErr := os.Lstat(absTarget); statErr == nil { if info.Mode()&os.ModeSymlink != 0 { - return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget)) + return s.fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", renderedTarget)) } existed = true mode = info.Mode().Perm() - // The previous bytes are not read here: phase 2 moves the - // whole file aside and moves it back on rollback. + // 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 fail(fmt.Errorf("inspect output file %s: %w", renderedTarget, statErr)) + return s.fail(fmt.Errorf("inspect output file %s: %w", renderedTarget, statErr)) } // Render into a temp file in the target's own directory so the @@ -313,52 +305,55 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re // never truncated, even if Execute or Close fails. tmp, err := os.CreateTemp(filepath.Dir(absTarget), ".domaincraft-render-*") if err != nil { - return fail(fmt.Errorf("create temp output file: %w", err)) + return s.fail(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 { _ = tmp.Close() _ = os.Remove(tmpPath) - return fail(fmt.Errorf("set mode on temp output %s: %w", tmpPath, err)) + return s.fail(fmt.Errorf("set mode on temp output %s: %w", tmpPath, err)) } if err := parsedTemplate.Execute(tmp, context); err != nil { _ = tmp.Close() _ = os.Remove(tmpPath) - return fail(fmt.Errorf("execute template: %w", err)) + return s.fail(fmt.Errorf("execute template: %w", err)) } if err := tmp.Close(); err != nil { _ = os.Remove(tmpPath) - return fail(fmt.Errorf("close temp output %s: %w", tmpPath, err)) + return s.fail(fmt.Errorf("close temp output %s: %w", tmpPath, err)) } - staged = append(staged, stagedWrite{ + s.staged = append(s.staged, stagedWrite{ temp: tmpPath, target: absTarget, existed: existed, mode: mode, record: record, }) - manifest = append(manifest, record) + s.manifest = append(s.manifest, record) } } } } + return nil +} - // Phase 2: commit staged files. An existing target is renamed aside into a - // sibling backup before the rendered temp file takes its place. Rollback - // renames the backup back, so no prior content is ever read into memory. +// 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 beforeCommitHook != nil { beforeCommitHook() } - for _, w := range staged { + for _, w := range s.staged { if info, err := os.Lstat(w.target); err == nil { if info.Mode()&os.ModeSymlink != 0 { - return fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) + return s.fail(fmt.Errorf("template target path escapes output directory through a symlink: %s", w.record.Path)) } // The staged temp name is already unique in this directory. backup := w.temp + ".bak" if err := os.Rename(w.target, backup); err != nil { - return fail(fmt.Errorf("back up output file %s: %w", w.record.Path, err)) + return s.fail(fmt.Errorf("back up output file %s: %w", w.record.Path, err)) } w.backup = backup w.existed = true @@ -370,32 +365,84 @@ func (r *Renderer) Render(project *ir.Project, outputDir string) ([]string, []Re w.existed = false w.backup = "" } else { - return fail(fmt.Errorf("inspect output file %s: %w", w.record.Path, err)) + 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. - committed = append(committed, w) + s.committed = append(s.committed, w) if err := os.Rename(w.temp, w.target); err != nil { - return fail(fmt.Errorf("commit output file %s: %w", w.record.Path, err)) + return s.fail(fmt.Errorf("commit output file %s: %w", w.record.Path, err)) } } + return nil +} - // Backups are only needed until every file has landed. Keep the render - // successful even if a leftover backup cannot be removed; the generated - // files are already correct and rollback must not consume the backups now. - for _, w := range committed { +// 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 != "" { if err := os.Remove(w.backup); 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), + staged: make([]stagedWrite, 0), + // committed is empty during staging; commitWrites appends as files land. + committed: make([]stagedWrite, 0), + manifest: make([]RenderedFile, 0), + } + + 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) - written := make([]string, 0, len(committed)) - for _, w := range committed { + written := make([]string, 0, len(session.committed)) + for _, w := range session.committed { written = append(written, w.target) } - return written, manifest, nil + return written, session.manifest, nil } func (r *Renderer) shouldRender(spec TemplateSpec, project *ir.Project, pkgs map[string]string) bool { diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index a3a64fd..17e7efb 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -178,23 +178,28 @@ func warnMissingSpec(log *logger.Logger, kind, key string) { // 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. +// 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 } + languageType := registerTypeFuncs(bridgeFuncs, m, log) + registerLiteralFuncs(bridgeFuncs, m, log, languageType) + registerValueFuncs(bridgeFuncs, m, log) + 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, log *logger.Logger) func(string, bool) string { // wrapNullable applies the bridge-specific nullable format to a type name. wrapNullable := func(typeName string) string { return typeName + m.NullableFormat } - // Build set of value types for quick lookup - valueTypeSet := make(map[string]bool, len(m.ValueTypes)) - for _, vt := range m.ValueTypes { - valueTypeSet[vt] = true - } - // wrapArray wraps a type name in the bridge-specific array format. wrapArray := func(elementType string) string { if m.ArrayFormat == "" { @@ -240,12 +245,29 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { log.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 +} +// 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, log *logger.Logger, languageType func(string, bool) string) { // 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 { + funcs["literalValue"] = func(dbType string, value any) string { kind := ir.KindOf(dbType) spec := m.Literals[dbType] switch kind { @@ -273,7 +295,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // literalDefault renders the value-less default expression for a type: // 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. - bridgeFuncs["literalDefault"] = func(dbType string) string { + funcs["literalDefault"] = func(dbType string) string { kind := ir.KindOf(dbType) if kind == "array" { if m.Array.Empty == "" { @@ -302,7 +324,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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 { + funcs["literalMember"] = func(dbType string, value string) string { if ir.KindOf(dbType) == "enum" { spec := m.Literals["enum"] if spec.Member == "" { @@ -316,25 +338,23 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // arrayLiteralOpen/Close wrap rendered elements in the bridge's array // syntax (e.g. "new List { " ... " }"). - bridgeFuncs["arrayLiteralOpen"] = func(dbType string) string { + funcs["arrayLiteralOpen"] = func(dbType string) string { if m.Array.Open == "" { warnMissingSpec(log, "array.open", dbType) return "" } return formatSpec(m.Array.Open, languageType(dbType, false)) } - bridgeFuncs["arrayLiteralClose"] = func() string { + funcs["arrayLiteralClose"] = func() string { return m.Array.Close } +} - bridgeFuncs["isValueType"] = func(typeName string) bool { - if mapped, ok := m.Types[typeName]; ok { - return valueTypeSet[mapped] - } - return false - } - - 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, log *logger.Logger) { + funcs["deleteBehaviorName"] = func(value string) string { key := strings.ToLower(strings.TrimSpace(value)) if v, ok := m.Behaviors[key]; ok { return v @@ -349,7 +369,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // The input is the IR type name (element type for arrays, the field type // otherwise). if len(m.ColumnSizes) > 0 { - bridgeFuncs["columnSize"] = func(dbType string) string { + funcs["columnSize"] = func(dbType string) string { return m.ColumnSizes[dbType] } } @@ -357,7 +377,7 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { // 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 { - bridgeFuncs["inputType"] = func(dbType string) string { + funcs["inputType"] = func(dbType string) string { inner := specmeta.ParseArrayInner(dbType) if mapped, ok := m.InputTypes[inner]; ok { return mapped @@ -369,8 +389,6 @@ func buildBridgeFuncs(m *typeMappings, log *logger.Logger) map[string]any { return "" } } - - return bridgeFuncs } func renderTemplateString(pattern string, data any, funcMap template.FuncMap) (string, error) { From f4735fd71ca957fe993e6755c3184796aba39568 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:33:38 +0300 Subject: [PATCH 40/83] CLI: split runGenerate and cover migration execution --- cmd/domaincraft/commands.go | 191 +++++++++++++-------- cmd/domaincraft/commands_hardening_test.go | 159 +++++++++++++++++ 2 files changed, 275 insertions(+), 75 deletions(-) diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index bae26aa..2e5d847 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -79,6 +79,11 @@ var ( // 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). version = "dev" @@ -267,30 +272,47 @@ func newGenerateCmd(opts *cliOptions) *cobra.Command { return cmd } -// 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, args []string) error { - log := commandLogger(cmd) - +// loadAndValidateDomain parses and validates domain.yaml, then builds the IR +// and applies addons. resolveBridge is called 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, resolveBridge func() (string, error)) (*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(opts, log) + bridgeName, err := resolveBridge() if err != nil { - return err + return nil, "", err } - opts.bridgePath = resolvedPath log.Info("Building IR") irProject, err := ir.Build(schema) if err != nil { - return err + return nil, "", err } applyAddons(opts, irProject) + 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, args []string) error { + log := commandLogger(cmd) + + irProject, bridgeName, err := loadAndValidateDomain(opts, cmd, log, func() (string, error) { + resolvedPath, name, err := resolveBridgeInteractive(opts, log) + if err != nil { + return "", err + } + opts.bridgePath = resolvedPath + return name, nil + }) + if err != nil { + return err + } // --- Schema snapshot / migration diff --- snapPath := snapshot.Path(opts.outputDir) @@ -353,75 +375,21 @@ func runGenerate(opts *cliOptions, cmd *cobra.Command, args []string) error { 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. Any other positional - // argument is rejected by cobra.MaximumNArgs(1) / the check below. - if len(args) > 0 { - 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] - } - if opts.adminBridge == "" && !cmd.Flags().Changed("admin") && !opts.nonInteractive && isTerminal() { - generate, err := interactive.PromptGenerateAdmin() - if err != nil { - return fmt.Errorf("prompt for admin panel: %w", err) - } - if generate { - opts.adminBridge = "admin-alpine" - } - } - if opts.adminBridge != "" { - adminManifest, err := generateAdminPanel(opts, irProject, seedData, mockDataset, log) - if err != nil { - return err - } - manifest = append(manifest, adminManifest...) + adminManifest, err := generateAdminPanel(opts, cmd, args, irProject, seedData, mockDataset, log) + 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(opts, migrationDiff, fresh, log, cmd) + applied, err := applySchemaMigrations(opts, migrationDiff, manifest, log, cmd) 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 := opts.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 := opts.migrate || autoMigrate - cfg := rendererInstance.MigrationConfig() - if applied && shouldMigrate && cfg != nil && cfg.Enabled { - if !bridgeCommandsAllowed(chainHasCommunity, opts.allowBridgeCommands) { - return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") - } - if err := runDatabaseMigrations(rendererInstance.MigrationConfig(), opts.outputDir, cmd, log); err != nil { - if 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. - 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.") - } + if err := runBridgeDatabaseMigrations(opts, cmd, log, migrationDiff, chainHasCommunity, applied, rendererInstance.MigrationConfig()); err != nil { + return err } // --- Smart refactoring reports --- @@ -855,9 +823,82 @@ func bridgeUpdateNotice(entryID string, _ *bridge.Update) string { return fmt.Sprintf("Updating bridge %s (cached copy is outdated)", entryID) } -// generateAdminPanel renders the optional admin panel bridge into the output -// directory and returns the extra file manifest entries. -func generateAdminPanel(opts *cliOptions, irProject *ir.Project, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { +// 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). +func runBridgeDatabaseMigrations(opts *cliOptions, cmd *cobra.Command, log *logger.Logger, diff *snapshot.Diff, chainHasCommunity, applied bool, cfg *renderer.MigrationConfig) error { + autoMigrate := opts.prune && diff.HasSchemaChanges() + if autoMigrate && chainHasCommunity { + log.Warn("community bridge(s) in the resolved chain — not auto-running database migrations; use --migrate explicitly") + autoMigrate = false + } + shouldMigrate := opts.migrate || autoMigrate + if !applied || !shouldMigrate || cfg == nil || !cfg.Enabled { + return nil + } + if !bridgeCommandsAllowed(chainHasCommunity, opts.allowBridgeCommands) { + return fmt.Errorf("community bridge(s) declared database migrations; re-run with --allow-bridge-commands to execute them") + } + if err := runDatabaseMigrations(cfg, opts.outputDir, cmd, log); err != nil { + if 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. + 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.") + } + 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(opts *cliOptions, diff *snapshot.Diff, manifest []renderer.RenderedFile, log *logger.Logger, cmd *cobra.Command) (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(opts, diff, fresh, log, 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(opts *cliOptions, cmd *cobra.Command, args []string, irProject *ir.Project, seedData, mockDataset *ir.SeedDataset, log *logger.Logger) ([]renderer.RenderedFile, error) { + // 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. Any other positional + // argument is rejected by cobra.MaximumNArgs(1) / the check below. + if len(args) > 0 { + if !cmd.Flags().Changed("admin") || opts.adminBridge != "admin-alpine" { + return nil, asUsageError(fmt.Errorf("unexpected positional argument %q: use --admin ", args[0])) + } + opts.adminBridge = args[0] + } + if opts.adminBridge == "" && !cmd.Flags().Changed("admin") && !opts.nonInteractive && isTerminal() { + generate, err := interactive.PromptGenerateAdmin() + if err != nil { + return nil, fmt.Errorf("prompt for admin panel: %w", err) + } + if generate { + opts.adminBridge = "admin-alpine" + } + } + if opts.adminBridge == "" { + return nil, nil + } + resolver := bridge.NewResolver(bridge.Default()).WithEnsureOptions(bridgeEnsureOptions(opts, log)) adminID := opts.adminBridge @@ -922,7 +963,7 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co shell = "sh" argv = []string{"-c", command} } - c := exec.CommandContext(commandCtx, shell, argv...) //nolint:gosec // shell line is gated by explicit bridge-command consent + c := execCommandFn(commandCtx, shell, argv...) //nolint:gosec // shell line is gated by explicit bridge-command consent c.Dir = outDir c.Stdout = out c.Stderr = out diff --git a/cmd/domaincraft/commands_hardening_test.go b/cmd/domaincraft/commands_hardening_test.go index 1ce2dde..60f7dc3 100644 --- a/cmd/domaincraft/commands_hardening_test.go +++ b/cmd/domaincraft/commands_hardening_test.go @@ -2,10 +2,13 @@ package main import ( "bytes" + "context" "crypto/sha256" "encoding/hex" + "errors" "io" "os" + "os/exec" "path/filepath" "runtime" "strings" @@ -397,6 +400,162 @@ func TestRunDatabaseMigrationsSanitizesDisplayedCommand(t *testing.T) { } } +// 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) + } +} + +// TestRunDatabaseMigrationsRespectsCommandContext checks that the global +// commandCtx 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 := commandCtx + commandCtx = ctx + t.Cleanup(func() { commandCtx = 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 commandCtx", 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 From 306f54a79af1505a66fa65394e2d4221f1faddc5 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:41:30 +0300 Subject: [PATCH 41/83] Contract: resolve bridge chains in a shared package and certify composed bridges --- cmd/domaincraft/commands.go | 30 +-- internal/bridgechain/chain.go | 42 +++ internal/bridgechain/chain_test.go | 85 +++++++ internal/contract/golden_test.go | 239 +++++++++++++++--- .../contract/testdata/csharp-rest.golden.txt | 54 ++++ .../contract/testdata/react-rest.golden.txt | 11 + 6 files changed, 397 insertions(+), 64 deletions(-) create mode 100644 internal/bridgechain/chain.go create mode 100644 internal/bridgechain/chain_test.go create mode 100644 internal/contract/testdata/csharp-rest.golden.txt create mode 100644 internal/contract/testdata/react-rest.golden.txt diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index 2e5d847..a8b2baa 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -30,6 +30,7 @@ import ( "unicode/utf8" "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/internal/ir" @@ -513,33 +514,10 @@ func newBridgeResolver(opts *cliOptions, log *logger.Logger) *bridge.Resolver { } // 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. +// deepest base. The resolution itself lives in the importable bridgechain +// package so the CLI and the contract tests share one chain order. func walkBridgeChain(opts *cliOptions, ref, fromDir string, log *logger.Logger) ([]string, error) { - resolver := newBridgeResolver(opts, 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 + return bridgechain.Walk(ref, fromDir, newBridgeResolver(opts, log), log) } // resolveBridgeInteractive resolves the bridge from the --bridge flag, or diff --git a/internal/bridgechain/chain.go b/internal/bridgechain/chain.go new file mode 100644 index 0000000..2451982 --- /dev/null +++ b/internal/bridgechain/chain.go @@ -0,0 +1,42 @@ +// 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" +) + +// 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) + } + 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 +} diff --git a/internal/bridgechain/chain_test.go b/internal/bridgechain/chain_test.go new file mode 100644 index 0000000..bc92d3a --- /dev/null +++ b/internal/bridgechain/chain_test.go @@ -0,0 +1,85 @@ +package bridgechain + +import ( + "os" + "path/filepath" + "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 testResolver() *bridge.Resolver { + return bridge.NewResolver(bridge.Default()) +} + +func TestWalkResolvesExtendsChainTopFirst(t *testing.T) { + 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, testResolver(), 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) { + 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, testResolver(), nil) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("err = %v, want a cycle error", err) + } +} + +func TestWalkMissingLocalPathIsHardError(t *testing.T) { + root := t.TempDir() + missing := filepath.Join(root, "missing-bridge") + + _, err := Walk(missing, root, testResolver(), 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 6f370c9..5a6aa6f 100644 --- a/internal/contract/golden_test.go +++ b/internal/contract/golden_test.go @@ -6,16 +6,24 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "encoding/json" "flag" "fmt" "os" "path/filepath" + "slices" "sort" "strings" "testing" + "time" + "gopkg.in/yaml.v3" + + "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,12 +32,180 @@ 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", +} + +// 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 goldenBridgeManifest struct { + Name string `yaml:"name"` + RegistryURL string `yaml:"registry_url"` + RegistryPackages map[string]string `yaml:"registry_packages"` +} + +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. +func goldenPlatform() (string, error) { + data, err := os.ReadFile(filepath.Join("testdata", "domain.yaml")) + if err != nil { + return "", err + } + schema, err := parser.ParseYAML(data) + if err != nil { + return "", err + } + proj, err := ir.Build(schema) + if err != nil { + 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() +} + +func readBridgeManifest(dir string) (goldenBridgeManifest, error) { + data, err := os.ReadFile(filepath.Join(dir, "bridge.yaml")) + if err != nil { + return goldenBridgeManifest{}, err + } + var m goldenBridgeManifest + if err := yaml.Unmarshal(data, &m); err != nil { + return goldenBridgeManifest{}, fmt.Errorf("parse %s: %w", dir, err) + } + return m, nil +} + +// 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 := "" + var adapter goldenBridgeManifest + for i, base := range chain { + m, err := readBridgeManifest(base) + if err != nil { + return err + } + if i == 0 { + adapter = m + } + for _, packageID := range m.RegistryPackages { + packageIDs[packageID] = struct{}{} + } + if registryURL == "" && m.RegistryURL != "" { + registryURL = m.RegistryURL + } + } + if len(packageIDs) == 0 { + continue + } + if registryURL == "" { + return fmt.Errorf("bridge %s declares packages but no registry_url", entry.ID) + } + packagesByKey := make(map[string]goldenPackageEntry, len(packageIDs)) + storedAt := time.Now() + for packageID := range packageIDs { + key := registryURL + "\x00" + packageID + "\x00" + framework + packagesByKey[key] = goldenPackageEntry{Value: hermeticPackageVersion, StoredAt: storedAt} + } + cacheDir, err := appdir.CacheDir(cacheNamespace(adapter.Name)) + if err != nil { + return err + } + 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() @@ -63,33 +239,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 } @@ -105,8 +264,12 @@ func renderChain(t *testing.T, chain []string, proj *ir.Project) map[string]stri 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)) @@ -153,16 +316,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) { t.Parallel() - got := strings.Join(manifestLines(renderChain(t, []string{bridgeDir(t, id)}, proj)), "\n") + 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 { 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 From 0ebdffdde6f107b3df29fa339c51beadb0d4d7d7 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:44:05 +0300 Subject: [PATCH 42/83] CI: drop stale nolint directives and use Fprintf for format runs --- cmd/domaincraft/commands.go | 4 ++-- internal/bridge/update.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/domaincraft/commands.go b/cmd/domaincraft/commands.go index a8b2baa..5911a15 100644 --- a/cmd/domaincraft/commands.go +++ b/cmd/domaincraft/commands.go @@ -941,7 +941,7 @@ func runDatabaseMigrations(cfg *renderer.MigrationConfig, outDir string, cmd *co shell = "sh" argv = []string{"-c", command} } - c := execCommandFn(commandCtx, shell, argv...) //nolint:gosec // shell line is gated by explicit bridge-command consent + c := execCommandFn(commandCtx, shell, argv...) c.Dir = outDir c.Stdout = out c.Stderr = out @@ -1016,7 +1016,7 @@ func sanitizeCommandLine(s string) string { continue } if isInvisibleFormat(r) { - b.WriteString(fmt.Sprintf("", r)) + fmt.Fprintf(&b, "", r) i += size continue } diff --git a/internal/bridge/update.go b/internal/bridge/update.go index a10afbe..21538af 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -264,7 +264,7 @@ func ApplyUpdate(entry RegistryEntry, u *Update) (string, error) { // 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")) //nolint:gosec // path built from a validated cache ID + data, err := os.ReadFile(filepath.Join(CachePath(entry), "bridge.yaml")) if err != nil { return fmt.Errorf("read re-cloned bridge manifest: %w", err) } From 20dd422fe4ed923520498fcab346365b705cccd0 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:19:07 +0300 Subject: [PATCH 43/83] Bridges: declare array and framework syntax instead of core fallbacks --- bridges/csharp/core/bridge.yaml | 3 + bridges/typescript/core/type_mappings.yaml | 4 + compliance-suite/regressions.tsv | 3 +- compliance-suite/tck.sh | 228 ++++++++++++++++++ internal/bridge/embed_test.go | 17 +- .../contract/testdata/csharp-rest.golden.txt | 10 +- internal/renderer/enum_array_test.go | 164 +++++++++++++ internal/renderer/models.go | 1 + internal/renderer/render.go | 20 +- internal/renderer/render_test.go | 23 +- 10 files changed, 452 insertions(+), 21 deletions(-) create mode 100755 compliance-suite/tck.sh create mode 100644 internal/renderer/enum_array_test.go diff --git a/bridges/csharp/core/bridge.yaml b/bridges/csharp/core/bridge.yaml index 8ada71e..8637c1e 100644 --- a/bridges/csharp/core/bridge.yaml +++ b/bridges/csharp/core/bridge.yaml @@ -2,6 +2,9 @@ name: csharp-core description: C# language core — enum wire values, entity types, query schema, permission matrix. Certified once per language. version: "1.0.0" layer: core +# 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 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/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index bb375cb..9a60ec4 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -127,8 +127,9 @@ internal/renderer/contract_test.go::TestLoadSourceRejectsNegativeContractVersion internal/bridge/resolver_test.go::TestResolveExtendsRelativeToAdapterDir #5 relative extends resolved against CWD instead of the adapter directory internal/bridge/hardening_test.go::TestHTTPProbeRejectsRedirectBeforeFetch #5 update probe fetched a redirected host before checking the target 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 +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 cmd/domaincraft/commands_hardening_test.go::TestPruneRejectsScaffoldReplaceEscape #5 scaffold replacement under --prune deleted a file outside outputDir via a symlink cmd/domaincraft/commands_update_security_test.go::TestReplaceExecutableUsesSameVolumeTemp #5 update binary was downloaded to the OS temp dir so rename into the executable directory failed with EXDEV cmd/domaincraft/commands_hardening_test.go::TestPruneCleanupErrorPrintedOnce #5 failed namespace rewrite under --prune was warned about and then printed again as Error cmd/domaincraft/commands_hardening_test.go::TestUsageErrorsExitTwo #5 bad flags, bad arguments and missing --bridge exited with code 1 instead of 2 +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 diff --git a/compliance-suite/tck.sh b/compliance-suite/tck.sh new file mode 100755 index 0000000..b0c71cc --- /dev/null +++ b/compliance-suite/tck.sh @@ -0,0 +1,228 @@ +#!/usr/bin/env bash +# TCK entrypoint. The workflow declares jobs; this script owns every step's +# logic. One target row from tck-matrix.json is passed as a JSON argument. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DOMAIN="compliance-suite/kitchen-sink.yaml" +CLIENT_BRIDGE="bridges/typescript/client" + +cd "$ROOT" + +usage() { + cat <<'EOF' +Usage: compliance-suite/tck.sh [target-json] + +Commands: + discover Resolve changed paths into hermetic/glue/k6 outputs + generate Generate the kitchen-sink artifact for a target + certify npm ci + npm run