diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index d17ea86..d403adc 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -27,6 +27,8 @@ jobs: run: | go mod verify go list -m -json all > dependency-inventory.json + - name: Run Go vulnerability scan + run: go tool -modfile=tools.mod govulncheck ./... - uses: actions/upload-artifact@v7 with: name: dependency-inventory diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 6838304..a4d429b 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -37,7 +37,22 @@ jobs: with: go-version-file: go.mod cache: true - - run: go run ./cmd/xtask validate + - name: Cache golangci-lint binary + id: cache-golangci + uses: actions/cache@v6 + with: + path: ~/go/bin/golangci-lint + key: golangci-lint-${{ runner.os }}-${{ runner.arch }}-v2.15.0 + - name: Install pinned golangci-lint + if: steps.cache-golangci.outputs.cache-hit != 'true' + run: | + mkdir -p "$HOME/go/bin" + curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b "$HOME/go/bin" v2.15.0 + "$HOME/go/bin/golangci-lint" --version + - name: Run native Go validation suite + run: | + export PATH="$HOME/go/bin:$PATH" + go run ./cmd/xtask validate release: name: Tag & Release diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..2cec9de --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,105 @@ +version: "2" +run: + timeout: 5m + modules-download-mode: readonly +formatters: + enable: [] +linters: + default: none + enable: + - bodyclose + - contextcheck + - errcheck + - errorlint + - exhaustive + - forbidigo + - gocritic + - gosec + - govet + - nilerr + - prealloc + - revive + - staticcheck + - unconvert + - wrapcheck + settings: + errcheck: + check-type-assertions: true + check-blank: true + errorlint: + errorf: true + asserts: true + comparison: true + exhaustive: + default-signifies-exhaustive: true + govet: + enable-all: true + disable: + - fieldalignment + staticcheck: + checks: + - "all" + forbidigo: + forbid: + - pattern: '^fmt\.Print.*$' + msg: "use structured logging instead of fmt.Print*" + - pattern: '^time\.Sleep$' + msg: "avoid unconditional time.Sleep; use context-aware timers" + - pattern: '^context\.(Background|TODO)$' + msg: "propagate caller context instead of creating root context in domain code" + revive: + rules: + - name: exported + - name: context-as-argument + - name: context-keys-type + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: increment-decrement + - name: var-declaration + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unreachable-code + - name: redefines-builtin-id + gocritic: + enabled-tags: + - diagnostic + - performance + - style + disabled-checks: + - hugeParam + wrapcheck: + ignore-sigs: + - .Errorf( + - errors.New( + - errors.Unwrap( + - errors.Join( + exclusions: + generated: strict + rules: + # cmd/xtask is the native automation runner and may print gate output. + - path: ^cmd/xtask/ + linters: + - forbidigo + - wrapcheck + # Local dev/CI CLI only: repo files, pinned subprocesses and generated artifacts are trusted. + - path: ^cmd/xtask/ + text: "G(122|204|301|304|306|702|703):" + linters: + - gosec + # Standard Go tests may use context roots and unexported test helpers. + - path: _test\.go$ + linters: + - forbidigo + - gosec + - wrapcheck +issues: + max-issues-per-linter: 0 + max-same-issues: 0 diff --git a/AGENTS.md b/AGENTS.md index 30e18d8..13db51a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,14 +9,16 @@ Technical operating rules for this Go repository template. ## 2. Toolchain & Validation +- Compiler & static safety: preserve every AST rule in `cmd/xtask/lint.go` and `-race` test execution in `cmd/xtask/main.go` (forbid `"unsafe"`, dot imports, `init()`, `panic`, `fmt.Print*`, `os.Exit`, `log.Fatal*`, `time.Sleep`, `context.Background`/`TODO`, `interface{}`, pointer-to-interface, embedded `sync.Mutex`, unchecked type assertions, mutable package globals, files over 500 lines, boolean parameters in exported functions, and bare `//nolint`). +- Semantic analysis: `golangci-lint v2.15.0` runs 15 type-checked linters from the immutable `.golangci.yml` with `formatters: enable: []`; it is installed at a pinned version in CI and must not be replaced with `@latest`. `govulncheck v1.10.0` runs from the isolated `tools.mod` in `security.yml` only. - Enable hooks locally with `git config core.hooksPath .githooks` and run `go run ./cmd/xtask validate` (`TOTAL PASS=8 FAIL=0`) before opening or updating any pull request. -- Do not run `gofmt` or automated code formatters in hooks, CI, or pre-commit steps. +- Do not run `gofmt`, `goimports`, `gofumpt`, or any automated code formatter in hooks, CI, or pre-commit steps. ## 3. Code Layout & Architecture - Organize domain logic under `internal/modules//` as a six-file layered modular layout (`entity.go`, `dto.go`, `repository.go`, `service.go`, `controller.go`, `module.go`). - Enforce unidirectional imports: `Controller` calls `Service` and `dto` (never `Repository`); `entity` and `dto` must not reference `service`, `repository`, or `controller`. -- Keep every source and documentation file at or below **500 lines**. +- Document all exported declarations in `internal/` with Go doc comments and keep every source and documentation file at or below **500 lines**. ## 4. Commit, Dependency & License Policy diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 011f381..06e5941 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -40,6 +40,11 @@ The included `internal/modules/math/` module demonstrates this pattern with an a 3. Add unit, integration, and layer boundary tests in `internal/core/core_test.go`. 4. Run `go run ./cmd/xtask validate` to verify all eight gates pass. +## Strict AST Policy & Tripwires + +- **AST Guardrails**: `cmd/xtask/lint.go` enforces `go vet ./...` plus native `go/ast` checks across `internal/` forbidding `"unsafe"`, dot imports, `init()`, `panic()`, `fmt.Print*`, `os.Exit`, `log.Fatal*`, `time.Sleep`, `context.Background`/`TODO`, `interface{}`, mutable package vars, boolean flag parameters, and unjustified `//nolint`, while requiring doc comments on exported symbols. +- **Race & Policy Lock**: `cmd/xtask/main.go` runs tests with `-race`, and `internal/core/core_test.go` fails if any AST rule, `-race` flag, or 3-day cooldown setting is removed. + ## Monorepo Variant Architecture When scaling into multiple Go services and shared libraries, adopt the `go.work` multi-module workspace layout: diff --git a/README.md b/README.md index 65a17c0..00cf8be 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ Production-ready pure-Go repository template featuring a native `cmd/xtask` vali ## Key Features - **100% Native Go Tooling**: Powered by `go run ./cmd/xtask` and standard library checks with zero Node.js or external script dependencies. +- **Strict AST & Concurrency Safety Lock**: Runs `go vet ./...`, pure-Go `go/ast` guardrails (forbidding `"unsafe"`, `init()`, `panic()`, `fmt.Print*`, `os.Exit`, `log.Fatal*`, `interface{}`, mutable globals, and boolean flag parameters), and `-race` tests; `internal/core/core_test.go` locks all policy rules against weakening. - **Layered Modular Architecture**: Reference domain module (`internal/modules/math/`) separating `entity`, `dto`, `repository`, `service`, `controller`, and `module` layers with automated boundary tests. - **Eight Standardized Validation Gates**: `lint`, `typecheck`, `unit tests`, `integration and architecture tests`, `cooldown`, `hygiene`, `notices`, and `release`. - **Supply-Chain Hardening**: 3-day dependency cooldown policy (`.github/dependabot.yml` `default-days: 3`, no `replace` or `@latest` directives), CodeQL static analysis, and automated SBOM/dependency inventory artifacts. @@ -51,10 +52,10 @@ go run ./cmd/xtask release --check # Verify VERSION matches CHANGELOG.md | Gate | Implementation | Purpose | | :--- | :--- | :--- | -| `lint` | `go vet ./...` + AST checks | Static lints and forbidden calls | +| `lint` | `go vet ./...` + AST checks | Static `go/ast` safety rules, doc comments, `"unsafe"` ban | | `typecheck` | `go build ./...` | Full package compilation check | -| `unit tests` | `go test -run TestUnit ./internal/...` | Fast unit test execution | -| `integration and architecture tests` | `go test -run 'TestIntegration\|TestArchitecture' ./internal/...` | HTTP endpoints and layer boundaries | +| `unit tests` | `go test -race -run TestUnit ./internal/...` | Race-checked unit test execution | +| `integration and architecture tests` | `go test -race -run 'TestIntegration\|TestArchitecture' ./internal/...` | Endpoints, layer boundaries, policy lock | | `cooldown` | `cmd/xtask/main.go` + `.github/dependabot.yml` | 3-day dependency cooldown enforcement | | `hygiene` | `cmd/xtask/hygiene.go` | Anti-leak, required docs, path checks | | `notices` | `cmd/xtask/notices.go` | License inventory parity | diff --git a/VERSION b/VERSION index 77d6f4c..6e8bf73 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +0.1.0 diff --git a/cmd/xtask/commit.go b/cmd/xtask/commit.go index c0abd3a..43ee043 100644 --- a/cmd/xtask/commit.go +++ b/cmd/xtask/commit.go @@ -14,8 +14,13 @@ var ( ) func runCommitCheck(root string, args []string) error { + mode := "" + if len(args) >= 2 { + mode = args[0] + } var msg string - if len(args) >= 2 && args[0] == "--file" { + switch mode { + case "--file": if err := checkGitIdentity(root); err != nil { return err } @@ -24,7 +29,7 @@ func runCommitCheck(root string, args []string) error { return err } msg = string(raw) - } else if len(args) >= 2 && args[0] == "--range" { + case "--range": cmd := exec.Command("git", "log", "--format=%B%x00", args[1]) cmd.Dir = root out, err := cmd.Output() @@ -41,10 +46,10 @@ func runCommitCheck(root string, args []string) error { } } return nil - } else { + default: raw, err := os.ReadFile(".git/COMMIT_EDITMSG") if err != nil { - return fmt.Errorf("missing --file or --range: %v", err) + return fmt.Errorf("missing --file or --range: %w", err) } msg = string(raw) } @@ -91,7 +96,7 @@ func validateCommitText(raw string) error { return fmt.Errorf("blank lines between bullets are forbidden") } if strings.Contains(strings.ToLower(line), "co-authored-by:") { - return fmt.Errorf("Co-authored-by trailers are forbidden") + return fmt.Errorf("co-authored-by trailers are forbidden") } bm := bulletRe.FindStringSubmatch(line) if bm == nil { @@ -117,7 +122,7 @@ func checkGitIdentity(root string) error { nameCmd.Dir = root nameOut, err := nameCmd.Output() if err != nil { - return fmt.Errorf("git user.name not configured: %v", err) + return fmt.Errorf("git user.name not configured: %w", err) } if strings.TrimSpace(string(nameOut)) == "" { return fmt.Errorf("git user.name must be configured") @@ -126,7 +131,7 @@ func checkGitIdentity(root string) error { emailCmd.Dir = root emailOut, err := emailCmd.Output() if err != nil { - return fmt.Errorf("git user.email not configured: %v", err) + return fmt.Errorf("git user.email not configured: %w", err) } if !strings.HasSuffix(strings.TrimSpace(string(emailOut)), noreplySuffix) { return fmt.Errorf("git user.email must end with %q", noreplySuffix) diff --git a/cmd/xtask/lint.go b/cmd/xtask/lint.go index 3abfcec..85ff74a 100644 --- a/cmd/xtask/lint.go +++ b/cmd/xtask/lint.go @@ -6,44 +6,269 @@ import ( "go/parser" "go/token" "io/fs" + "os" + "os/exec" "path/filepath" + "regexp" "strings" ) +var ( + nolintJustifiedRe = regexp.MustCompile(`^//nolint(?::[A-Za-z0-9_,-]+)?\s+//\s+\S.{4,}$`) + todoCommentRe = regexp.MustCompile(`\b(?:TODO|FIXME)\b`) +) + +const golangciVersion = "v2.15.0" + func runLint(root string) error { if err := runExec(root, "go", "vet", "./..."); err != nil { return err } + if err := runGolangciLint(root); err != nil { + return err + } + if err := checkGoLineLimits(root); err != nil { + return err + } fset := token.NewFileSet() return filepath.WalkDir(filepath.Join(root, "internal"), func(path string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { return err } - file, parseErr := parser.ParseFile(fset, path, nil, 0) + file, parseErr := parser.ParseFile(fset, path, nil, parser.ParseComments) if parseErr != nil { return parseErr } - var lintErr error - ast.Inspect(file, func(n ast.Node) bool { - call, ok := n.(*ast.CallExpr) - if !ok { - return true + return inspectGoFile(fset, path, file) + }) +} + +func runGolangciLint(root string) error { + bin, err := exec.LookPath("golangci-lint") + if err != nil { + bin = goBinDir("golangci-lint") + if _, statErr := os.Stat(bin); statErr != nil { + return fmt.Errorf("golangci-lint %s not found; install the pinned binary:\n curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b \"$(go env GOPATH)/bin\" %s", golangciVersion, golangciVersion) + } + } + return runExec(root, bin, "run", "--config", ".golangci.yml", "./...") +} + +func goBinDir(name string) string { + out, err := exec.Command("go", "env", "GOBIN").Output() + if err == nil && strings.TrimSpace(string(out)) != "" { + return filepath.Join(strings.TrimSpace(string(out)), name) + } + out, err = exec.Command("go", "env", "GOPATH").Output() + if err != nil { + return name + } + return filepath.Join(strings.TrimSpace(string(out)), "bin", name) +} + +func checkGoLineLimits(root string) error { + return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if d.Name() == ".git" { + return filepath.SkipDir } - if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" { - lintErr = fmt.Errorf("forbidden panic() in %s", path) + return nil + } + if !strings.HasSuffix(path, ".go") { + return nil + } + raw, readErr := os.ReadFile(path) + if readErr != nil { + return readErr + } + if count := len(strings.Split(string(raw), "\n")); count > 500 { + return fmt.Errorf("file %s exceeds 500 lines (%d)", path, count) + } + return nil + }) +} + +func inspectGoFile(fset *token.FileSet, path string, file *ast.File) error { + for _, imp := range file.Imports { + if imp.Path != nil && imp.Path.Value == `"unsafe"` { + return fmt.Errorf("forbidden unsafe package import in %s", path) + } + if imp.Name != nil && imp.Name.Name == "." { + return fmt.Errorf("forbidden dot import in %s", path) + } + } + + for _, cg := range file.Comments { + for _, c := range cg.List { + text := strings.TrimSpace(c.Text) + if strings.HasPrefix(text, "//nolint") && !nolintJustifiedRe.MatchString(text) { + pos := fset.Position(c.Pos()) + return fmt.Errorf("bare //nolint without rule and '// reason' at %s:%d", path, pos.Line) + } + if todoCommentRe.MatchString(text) { + pos := fset.Position(c.Pos()) + return fmt.Errorf("unresolved TODO or FIXME comment at %s:%d", path, pos.Line) + } + } + } + + for _, decl := range file.Decls { + if err := inspectTopDecl(fset, path, decl); err != nil { + return err + } + } + + var lintErr error + ast.Inspect(file, func(n ast.Node) bool { + if lintErr != nil { + return false + } + if iface, ok := n.(*ast.InterfaceType); ok { + if iface.Methods == nil || len(iface.Methods.List) == 0 { + pos := fset.Position(iface.Pos()) + lintErr = fmt.Errorf("use 'any' instead of empty interface{} at %s:%d", path, pos.Line) return false } - if sel, ok := call.Fun.(*ast.SelectorExpr); ok { - if pkg, ok := sel.X.(*ast.Ident); ok { - if (pkg.Name == "fmt" && strings.HasPrefix(sel.Sel.Name, "Print")) || - (pkg.Name == "os" && sel.Sel.Name == "Exit") { - lintErr = fmt.Errorf("forbidden %s.%s in %s", pkg.Name, sel.Sel.Name, path) - return false - } + } + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" { + lintErr = fmt.Errorf("forbidden panic() in %s", path) + return false + } + if sel, ok := call.Fun.(*ast.SelectorExpr); ok { + if pkg, ok := sel.X.(*ast.Ident); ok { + name := sel.Sel.Name + if (pkg.Name == "fmt" && strings.HasPrefix(name, "Print")) || + (pkg.Name == "os" && name == "Exit") || + (pkg.Name == "log" && (strings.HasPrefix(name, "Fatal") || strings.HasPrefix(name, "Panic"))) || + (pkg.Name == "time" && name == "Sleep") || + (pkg.Name == "context" && (name == "Background" || name == "TODO")) { + pos := fset.Position(call.Pos()) + lintErr = fmt.Errorf("forbidden %s.%s at %s:%d", pkg.Name, name, path, pos.Line) + return false } } - return true - }) - return lintErr + } + return true + }) + + skipAssert := map[ast.Node]bool{} + ast.Inspect(file, func(n ast.Node) bool { + if lintErr != nil { + return false + } + switch v := n.(type) { + case *ast.TypeSwitchStmt: + if v.Assign != nil { + skipAssert[v.Assign] = true + } + case *ast.AssignStmt: + if len(v.Lhs) >= 2 { + for _, rhs := range v.Rhs { + skipAssert[rhs] = true + } + } + case *ast.StarExpr: + if _, ok := v.X.(*ast.InterfaceType); ok { + pos := fset.Position(v.Pos()) + lintErr = fmt.Errorf("pointer-to-interface is forbidden at %s:%d", path, pos.Line) + return false + } + case *ast.StructType: + for _, field := range v.Fields.List { + if len(field.Names) != 0 { + continue + } + sel, ok := field.Type.(*ast.SelectorExpr) + if !ok { + continue + } + pkg, ok := sel.X.(*ast.Ident) + if ok && pkg.Name == "sync" && (sel.Sel.Name == "Mutex" || sel.Sel.Name == "RWMutex") { + pos := fset.Position(field.Pos()) + lintErr = fmt.Errorf("embedded sync.%s is forbidden at %s:%d", sel.Sel.Name, path, pos.Line) + return false + } + } + case *ast.TypeAssertExpr: + if skipAssert[v] || v.Type == nil { + return true + } + pos := fset.Position(v.Pos()) + lintErr = fmt.Errorf("unchecked type assertion requires comma-ok at %s:%d", path, pos.Line) + return false + } + return true }) + return lintErr +} + +func inspectTopDecl(fset *token.FileSet, path string, decl ast.Decl) error { + switch d := decl.(type) { + case *ast.FuncDecl: + if d.Recv == nil && d.Name.Name == "init" { + return fmt.Errorf("forbidden init() function in %s", path) + } + if ast.IsExported(d.Name.Name) { + if d.Doc == nil { + pos := fset.Position(d.Pos()) + return fmt.Errorf("exported func %s missing doc comment at %s:%d", d.Name.Name, path, pos.Line) + } + if d.Type.Params != nil { + for _, field := range d.Type.Params.List { + if ident, ok := field.Type.(*ast.Ident); ok && ident.Name == "bool" { + pos := fset.Position(field.Pos()) + return fmt.Errorf("boolean parameter forbidden in exported func %s at %s:%d", d.Name.Name, path, pos.Line) + } + } + } + } + case *ast.GenDecl: + if d.Tok == token.VAR { + for _, spec := range d.Specs { + vs, ok := spec.(*ast.ValueSpec) + if !ok { + continue + } + for _, name := range vs.Names { + if name.Name == "_" && vs.Type != nil && len(vs.Values) == 1 { + continue + } + if !strings.HasPrefix(name.Name, "Err") { + pos := fset.Position(name.Pos()) + return fmt.Errorf("mutable package var %q forbidden (only Err* sentinels allowed) at %s:%d", name.Name, path, pos.Line) + } + if ast.IsExported(name.Name) && d.Doc == nil && vs.Doc == nil { + pos := fset.Position(name.Pos()) + return fmt.Errorf("exported sentinel %s missing doc comment at %s:%d", name.Name, path, pos.Line) + } + } + } + } + if d.Tok == token.TYPE || d.Tok == token.CONST { + for _, spec := range d.Specs { + switch s := spec.(type) { + case *ast.TypeSpec: + if ast.IsExported(s.Name.Name) && d.Doc == nil && s.Doc == nil { + pos := fset.Position(s.Pos()) + return fmt.Errorf("exported type %s missing doc comment at %s:%d", s.Name.Name, path, pos.Line) + } + case *ast.ValueSpec: + for _, name := range s.Names { + if ast.IsExported(name.Name) && d.Doc == nil && s.Doc == nil { + pos := fset.Position(name.Pos()) + return fmt.Errorf("exported const %s missing doc comment at %s:%d", name.Name, path, pos.Line) + } + } + } + } + } + } + return nil } diff --git a/cmd/xtask/main.go b/cmd/xtask/main.go index 3cf6889..c41138b 100644 --- a/cmd/xtask/main.go +++ b/cmd/xtask/main.go @@ -109,11 +109,11 @@ func runTypecheck(root string) error { } func runUnitTests(root string) error { - return runExec(root, "go", "test", "-run", "TestUnit", "./internal/...") + return runExec(root, "go", "test", "-race", "-run", "TestUnit", "./internal/...") } func runIntegrationTests(root string) error { - return runExec(root, "go", "test", "-run", "TestIntegration|TestArchitecture", "./internal/...") + return runExec(root, "go", "test", "-race", "-run", "TestIntegration|TestArchitecture", "./internal/...") } func runCooldown(root string) error { @@ -135,15 +135,22 @@ func runCooldown(root string) error { if !strings.Contains(string(dependabot), "default-days: 3") { return fmt.Errorf("dependabot.yml must enforce 3-day cooldown") } + toolsRaw, err := os.ReadFile(filepath.Join(root, "tools.mod")) + if err == nil { + tools := string(toolsRaw) + if strings.Contains(tools, "replace ") || strings.Contains(tools, "@latest") { + return fmt.Errorf("tools.mod must pin exact versions without replace or @latest") + } + } return nil } -func runExec(root string, name string, args ...string) error { +func runExec(root, name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Dir = root out, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("%v: %s", err, strings.TrimSpace(string(out))) + return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) } return nil } diff --git a/cmd/xtask/release.go b/cmd/xtask/release.go index 4851d56..a81bd12 100644 --- a/cmd/xtask/release.go +++ b/cmd/xtask/release.go @@ -26,8 +26,9 @@ func runRelease(root string, args []string) error { } re := regexp.MustCompile(`const Version = "[^"]+"`) updatedCore := re.ReplaceAllString(string(coreRaw), fmt.Sprintf(`const Version = %q`, nextVer)) - if err := os.WriteFile(corePath, []byte(updatedCore), 0o644); err != nil { - return err + writeErr := os.WriteFile(corePath, []byte(updatedCore), 0o644) + if writeErr != nil { + return writeErr } changelogPath := filepath.Join(root, "CHANGELOG.md") changelogRaw, err := os.ReadFile(changelogPath) @@ -53,12 +54,38 @@ func runRelease(root string, args []string) error { if !semverRe.MatchString(ver) { return fmt.Errorf("invalid VERSION %q", ver) } - changelog, err := os.ReadFile(filepath.Join(root, "CHANGELOG.md")) + changelogBytes, err := os.ReadFile(filepath.Join(root, "CHANGELOG.md")) if err != nil { return err } - if !strings.Contains(string(changelog), fmt.Sprintf("## %s", ver)) { + changelog := string(changelogBytes) + heading := fmt.Sprintf("## %s", ver) + if !strings.Contains(changelog, heading) { return fmt.Errorf("CHANGELOG.md missing section for %s", ver) } + + if len(args) >= 2 && args[0] == "--notes" { + notes := extractChangelogSection(changelog, heading) + outPath := args[1] + if !filepath.IsAbs(outPath) { + outPath = filepath.Join(root, outPath) + } + if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { + return err + } + return os.WriteFile(outPath, []byte(notes+"\n"), 0o644) + } return nil } + +func extractChangelogSection(changelog, heading string) string { + idx := strings.Index(changelog, heading) + if idx < 0 { + return heading + } + rest := changelog[idx:] + if nextIdx := strings.Index(rest[len(heading):], "\n## "); nextIdx >= 0 { + return strings.TrimSpace(rest[:len(heading)+nextIdx]) + } + return strings.TrimSpace(rest) +} diff --git a/internal/core/core.go b/internal/core/core.go index df1914a..329925e 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -1,3 +1,4 @@ +// Package core exposes the health, greeting, and modular math HTTP surface. package core import ( @@ -10,7 +11,7 @@ import ( ) // Version defines the baseline service version. -const Version = "0.1.2" +const Version = "0.1.0" // Greet returns a normalized greeting for the given name. func Greet(name string) string { @@ -52,6 +53,13 @@ func NewMux() *http.ServeMux { func writeJSON(w http.ResponseWriter, status int, payload any) { w.Header().Set("Content-Type", "application/json") + body, err := json.Marshal(payload) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(payload) + if _, err := w.Write(body); err != nil { + return + } } diff --git a/internal/core/core_test.go b/internal/core/core_test.go index a460298..f5ea718 100644 --- a/internal/core/core_test.go +++ b/internal/core/core_test.go @@ -39,7 +39,7 @@ func TestUnitMathModule(t *testing.T) { } func TestIntegrationHealthEndpoint(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/health", nil) + req := httptest.NewRequest(http.MethodGet, "/health", http.NoBody) rec := httptest.NewRecorder() NewMux().ServeHTTP(rec, req) @@ -56,7 +56,7 @@ func TestIntegrationHealthEndpoint(t *testing.T) { } func TestIntegrationMathAddEndpoint(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/math/add?a=15&b=27", nil) + req := httptest.NewRequest(http.MethodGet, "/math/add?a=15&b=27", http.NoBody) rec := httptest.NewRecorder() NewMux().ServeHTTP(rec, req) @@ -122,3 +122,109 @@ func TestArchitectureModularLayerBoundaries(t *testing.T) { t.Fatal("controller leaked repository") } } + +func TestArchitectureLocksImmutableLintPolicy(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "cmd", "xtask", "lint.go")) + if err != nil { + t.Fatalf("failed reading lint.go: %v", err) + } + lintSrc := string(raw) + requiredRules := []string{ + `"unsafe"`, + `panic`, + `fmt`, + `os`, + `log`, + `"init"`, + `InterfaceType`, + `"bool"`, + `context`, + `Sleep`, + `IsExported`, + `//nolint`, + `mutable package var`, + `golangci-lint`, + `.golangci.yml`, + `TypeAssertExpr`, + `Mutex`, + `500`, + } + for _, token := range requiredRules { + if !strings.Contains(lintSrc, token) { + t.Fatalf("cmd/xtask/lint.go missing immutable policy rule: %s", token) + } + } +} + +func TestArchitectureRaceDetectorAndCooldownPolicy(t *testing.T) { + mainRaw, err := os.ReadFile(filepath.Join("..", "..", "cmd", "xtask", "main.go")) + if err != nil { + t.Fatalf("failed reading main.go: %v", err) + } + if !strings.Contains(string(mainRaw), `"-race"`) { + t.Fatal("cmd/xtask/main.go must run tests with -race enabled") + } + + depRaw, err := os.ReadFile(filepath.Join("..", "..", ".github", "dependabot.yml")) + if err != nil { + t.Fatalf("failed reading dependabot.yml: %v", err) + } + if !strings.Contains(string(depRaw), "default-days: 3") { + t.Fatal("dependabot.yml must enforce default-days: 3") + } + + for _, forbidden := range []string{".prettierrc", "package.json"} { + if _, statErr := os.Stat(filepath.Join("..", "..", forbidden)); statErr == nil { + t.Fatalf("forbidden formatter or js artifact present: %s", forbidden) + } + } +} + +func TestArchitectureLocksGolangciPolicy(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", ".golangci.yml")) + if err != nil { + t.Fatalf("failed reading .golangci.yml: %v", err) + } + cfg := string(raw) + for _, token := range []string{`version: "2"`, `default: none`, `enable: []`, `formatters:`} { + if !strings.Contains(cfg, token) { + t.Fatalf(".golangci.yml missing immutable policy token: %s", token) + } + } + for _, formatter := range []string{"gofmt", "goimports", "gofumpt", "gci", "golines", "swaggo"} { + if strings.Contains(cfg, formatter) { + t.Fatalf(".golangci.yml must never enable formatter %s", formatter) + } + } + for _, linter := range []string{"bodyclose", "contextcheck", "errcheck", "errorlint", "exhaustive", "forbidigo", "gocritic", "gosec", "govet", "nilerr", "prealloc", "revive", "staticcheck", "unconvert", "wrapcheck"} { + if !strings.Contains(cfg, linter) { + t.Fatalf(".golangci.yml missing semantic linter %s", linter) + } + } + for _, option := range []string{"check-type-assertions: true", "check-blank: true", "default-signifies-exhaustive: true", "enable-all: true"} { + if !strings.Contains(cfg, option) { + t.Fatalf(".golangci.yml missing locked option: %s", option) + } + } +} + +func TestArchitectureForbidsFormattersInHooksAndCI(t *testing.T) { + for _, rel := range []string{".githooks/pre-commit", ".githooks/pre-push", ".github/workflows/validate.yml"} { + raw, err := os.ReadFile(filepath.Join("..", "..", rel)) + if err != nil { + t.Fatalf("failed reading %s: %v", rel, err) + } + for _, forbidden := range []string{"gofmt", "goimports", "gofumpt", "golangci-lint fmt", "latest"} { + if strings.Contains(string(raw), forbidden) { + t.Fatalf("%s must never invoke %s", rel, forbidden) + } + } + } + validateRaw, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "validate.yml")) + if err != nil { + t.Fatalf("failed reading validate.yml: %v", err) + } + if !strings.Contains(string(validateRaw), "v2.15.0") { + t.Fatal("validate.yml must pin golangci-lint v2.15.0") + } +} diff --git a/internal/modules/math/controller.go b/internal/modules/math/controller.go index 6542fe2..234b003 100644 --- a/internal/modules/math/controller.go +++ b/internal/modules/math/controller.go @@ -11,6 +11,6 @@ func NewController(service *Service) *Controller { } // HandleAdd executes an addition request through Service. -func (c *Controller) HandleAdd(a int64, b int64) (AddResponse, error) { +func (c *Controller) HandleAdd(a, b int64) (AddResponse, error) { return c.service.Add(AddRequest{A: a, B: b}) } diff --git a/internal/modules/math/dto.go b/internal/modules/math/dto.go index b4831f4..77e20a7 100644 --- a/internal/modules/math/dto.go +++ b/internal/modules/math/dto.go @@ -4,6 +4,9 @@ import "errors" const maxOperandAbs int64 = 1_000_000_000 +// ErrOperandOutOfBounds reports an operand outside the safe template bounds. +var ErrOperandOutOfBounds = errors.New("operand exceeds safe template bounds") + // AddRequest defines the validated addition payload. type AddRequest struct { A int64 `json:"a"` @@ -19,7 +22,7 @@ type AddResponse struct { // ValidateAddRequest enforces safe operand bounds. func ValidateAddRequest(req AddRequest) error { if req.A > maxOperandAbs || req.A < -maxOperandAbs || req.B > maxOperandAbs || req.B < -maxOperandAbs { - return errors.New("operand exceeds safe template bounds") + return ErrOperandOutOfBounds } return nil } diff --git a/internal/modules/math/module.go b/internal/modules/math/module.go index 52024fe..43994e7 100644 --- a/internal/modules/math/module.go +++ b/internal/modules/math/module.go @@ -1,3 +1,4 @@ +// Package math provides the layered reference domain module. package math // Module wires the math domain layers together. diff --git a/internal/modules/math/repository.go b/internal/modules/math/repository.go index ac9f71f..49b0f89 100644 --- a/internal/modules/math/repository.go +++ b/internal/modules/math/repository.go @@ -9,6 +9,8 @@ type Repository interface { List() []CalculationEntry } +var _ Repository = (*InMemoryRepository)(nil) + // InMemoryRepository stores calculation entries in memory. type InMemoryRepository struct { mu sync.Mutex diff --git a/tools.mod b/tools.mod new file mode 100644 index 0000000..474a485 --- /dev/null +++ b/tools.mod @@ -0,0 +1,15 @@ +// CHANGE ME: update example.com/change-me with your module path. +module example.com/change-me/tools + +go 1.27 + +tool golang.org/x/vuln/cmd/govulncheck + +require ( + golang.org/x/mod v0.43.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb // indirect + golang.org/x/tools v0.53.0 // indirect + golang.org/x/vuln v1.10.0 // indirect +) diff --git a/tools.sum b/tools.sum new file mode 100644 index 0000000..b8d2a16 --- /dev/null +++ b/tools.sum @@ -0,0 +1,12 @@ +golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= +golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb h1:juaHO1dWannznOvpnfdTIjkqPDBsG9OcdkOBTBlcUCA= +golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb/go.mod h1:frnW8knEsfI9dILitAKHe8/iQ1ycXgpvIjQ/xz9QFYk= +golang.org/x/tools v0.53.0 h1:T3bIVp3zjHG9/aEiFk6BXxFh5/Vcbk7JA5hRq1cG8IU= +golang.org/x/tools v0.53.0/go.mod h1:vg+Vrb7y5mTTtxZLTdbTK8G745wcaLcsCtgCWgQONCI= +golang.org/x/vuln v1.10.0 h1:W/Im35AGknunDiqBysVe9VoMfaeTJE7lptrD+1s//aE= +golang.org/x/vuln v1.10.0/go.mod h1:kNpckBWtSQiR+USd0ZgdhJCCWf/ZXOl1+n3Wybcj8eE=