chore: publish IntegraCI build modules 732ec6c83925

This commit is contained in:
dhimaz0445 committed 2026-10-28 08:09:16 +00:00
1 parent 7a84930dea
commit 5f8a24d014
133 files changed
+18990 -2

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
// Package verdict asks IntegraCI's DB-change engine to judge migration SQL.
//
// Kept out of package main: the Dagger-generated package panics at init without
// a Dagger session, so tests in main cannot run under a plain `go test`.
package verdict
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
"sort"
"strings"
"time"
)
// AnalyzePath is IntegraCI's DB-change policy endpoint: the DBV engine
// (libs/dbv-policy) behind the tenant's own policy. The lint used to grep the
// migration TOOL's output for keywords instead — liquibase/flyway `validate`
// output carries no SQL, so it never found anything, and `|| true` made the
// tool unable to fail the step at all.
//
// apps/api/tests/test_dagger_db_migration_lint_contract.py reads this constant
// and the request field names below and checks the API really serves them.
const AnalyzePath = "/api/v1/db-changes/analyze"
// MaxSQLBytes mirrors the endpoint's `sql` max_length (DbChangeAnalyzeRequest).
const MaxSQLBytes = 200_000
// Request is the body of POST AnalyzePath.
type Request struct {
SQL string `json:"sql"`
// Exactly one of the two (Target): the endpoint refuses both.
Dialect string `json:"dialect,omitempty"`
Engine string `json:"engine,omitempty"`
EnvironmentID *string `json:"environment_id,omitempty"`
// The release this file belongs to. With both set, the platform records
// the verdict IT computed for (service, version), which its deploy gate
// reads (DbChangePolicy.release_verdict).
ServiceID *string `json:"service_id,omitempty"`
Version *string `json:"version,omitempty"`
File *string `json:"file,omitempty"`
}
// Release names the release a lint judges: both or neither.
func Release(serviceID, version string) (*string, *string, error) {
if (serviceID == "") != (version == "") {
return nil, nil, fmt.Errorf("--service-id and --version name a release together: give both or neither")
}
if serviceID == "" {
return nil, nil, nil
}
return &serviceID, &version, nil
}
// Violation is one finding of the engine, as the endpoint reports it.
type Violation struct {
RuleID string `json:"rule_id"`
Severity string `json:"severity"`
Message string `json:"message"`
}
// Response is the part of the endpoint's verdict the lint reads.
type Response struct {
Decision string `json:"decision"`
Reasons []string `json:"reasons"`
DestructiveCount int `json:"destructive_count"`
SecurityCount int `json:"security_count"`
Violations []Violation `json:"violations"`
RulesetVersion string `json:"ruleset_version"`
}
// FileVerdict is the engine's verdict on one migration file.
type FileVerdict struct {
File string `json:"file"`
Decision string `json:"decision"`
Reasons []string `json:"reasons"`
Rules []string `json:"rules"`
RulesetVersion string `json:"ruleset_version"`
}
// NewClient is the HTTP client the lint asks IntegraCI with. It follows no
// redirect: Go keeps the Authorization header on a same-host redirect, even
// one from https to http, and a 3xx is not a verdict anyway.
func NewClient() *http.Client {
return &http.Client{
Timeout: 60 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// Analyze asks IntegraCI to judge one script. Any answer that is not a
// verdict — transport error, non-2xx, unreadable body, empty decision — is an
// error: the lint cannot pass what nobody judged.
func Analyze(ctx context.Context, client *http.Client, apiURL, token string, req Request) (*Response, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
url := strings.TrimRight(apiURL, "/") + AnalyzePath
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("POST %s: %w", AnalyzePath, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("POST %s: reading the answer: %w", AnalyzePath, err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
snippet := string(raw)
if len(snippet) > 300 {
snippet = snippet[:300]
}
hint := ""
if resp.StatusCode == http.StatusUnprocessableEntity && req.Engine != "" {
hint = " (a platform older than engine support refuses --engine; use --dialect until it is upgraded)"
}
return nil, fmt.Errorf("POST %s: HTTP %d: %s%s", AnalyzePath, resp.StatusCode, snippet, hint)
}
var out Response
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("POST %s: not a verdict: %w", AnalyzePath, err)
}
if out.Decision == "" {
return nil, fmt.Errorf("POST %s: the answer carries no decision", AnalyzePath)
}
return &out, nil
}
// Fails reports whether a decision fails the lint. `blocked` always does,
// whatever `block` says; `requires_approval` does too while blocking is on,
// because nobody can approve inside a CI step — the change goes through
// IntegraCI's apply, where the approval is decided.
func Fails(decision string, block bool) bool {
switch decision {
case "allow", "warn":
return false
case "requires_approval":
return block
default: // blocked, and any decision this module does not know
return true
}
}
// HasPlaceholder reports whether a script holds a `${…}` placeholder. Flyway
// (by default, with built-ins such as `${flyway:filename}`) and Liquibase
// substitute these AFTER the engine has judged the text and BEFORE they split
// statements, so the SQL that runs is not the SQL that was judged: a file named
// `V9__x');DROP TABLE users;--.sql` holding `SELECT ('${flyway:filename}');`
// is one harmless literal to the engine and a DROP to flyway. A script with a
// placeholder cannot be judged, so it is refused.
func HasPlaceholder(sql string) bool {
return strings.Contains(sql, "${")
}
// Judgeable refuses a script the engine cannot be trusted to have judged: one
// over the endpoint's size limit, or one with a placeholder the tool would
// substitute afterwards.
func Judgeable(file, sql string) error {
if len(sql) > MaxSQLBytes {
return fmt.Errorf("%s is %d bytes; the DB-change engine takes at most %d — split it", file, len(sql), MaxSQLBytes)
}
if HasPlaceholder(sql) {
return fmt.Errorf("%s holds a ${…} placeholder: the tool substitutes it after the engine has judged the text, "+
"so the SQL that would run is not the SQL judged — write the value out", file)
}
return nil
}
// Refused lists the verdicts that fail the lint. Judging nothing is itself a
// refusal: a directory with no SQL passed a lint that read nothing.
func Refused(verdicts []FileVerdict, block bool) ([]string, error) {
if len(verdicts) == 0 {
return nil, fmt.Errorf("no migration was judged: the directory holds no SQL " +
"(point --dir at the migrations, or use --tool=none to opt out of governance)")
}
refused := []string{}
for _, v := range verdicts {
if Fails(v.Decision, block) {
refused = append(refused, fmt.Sprintf("%s: %s (%s)", v.File, v.Decision, strings.Join(v.Rules, ", ")))
}
}
return refused, nil
}
// notMigrations are the only non-SQL files a migrations directory may hold.
// Anything else is a file some tool may run that the engine cannot read — an
// XML/YAML/JSON changelog, a flyway `.pgsql` suffix set in the repo's config,
// a Java migration — so a lint that skipped it would pass what it never judged.
var (
notMigrationExtensions = map[string]bool{".md": true, ".txt": true, ".rst": true}
notMigrationNames = map[string]bool{".gitkeep": true, ".keep": true, "atlas.sum": true, "readme": true, "license": true}
)
// SplitMigrations sorts a directory listing into the SQL the engine judges
// and the files it cannot, which fail the step.
func SplitMigrations(entries []string) (sqlFiles, unanalysable []string) {
for _, e := range entries {
if strings.HasSuffix(e, "/") {
continue
}
base := strings.ToLower(path.Base(e))
ext := path.Ext(base)
switch {
case ext == ".sql":
sqlFiles = append(sqlFiles, e)
case notMigrationExtensions[ext] || notMigrationNames[base]:
default:
unanalysable = append(unanalysable, e)
}
}
sort.Slice(sqlFiles, func(i, j int) bool { return naturalLess(sqlFiles[i], sqlFiles[j]) })
sort.Strings(unanalysable)
return sqlFiles, unanalysable
}
// naturalLess orders names with their digit runs compared as numbers, so
// `V2.sql` comes before `V10.sql`: Liquibase applies the judged files one by
// one in this order, and a lexical sort would run V10 first.
func naturalLess(a, b string) bool {
for a != "" && b != "" {
da, db := digitPrefix(a), digitPrefix(b)
if da != "" && db != "" {
na, nb := strings.TrimLeft(da, "0"), strings.TrimLeft(db, "0")
if len(na) != len(nb) {
return len(na) < len(nb)
}
if na != nb {
return na < nb
}
a, b = a[len(da):], b[len(db):]
continue
}
if a[0] != b[0] {
return a[0] < b[0]
}
a, b = a[1:], b[1:]
}
return len(a) < len(b)
}
func digitPrefix(s string) string {
i := 0
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
i++
}
return s[:i]
}
// Of condenses one answer for the report.
func Of(file string, resp *Response) FileVerdict {
rules := []string{}
for _, v := range resp.Violations {
if v.Severity != "info" {
rules = append(rules, v.RuleID)
}
}
return FileVerdict{
File: file,
Decision: resp.Decision,
Reasons: resp.Reasons,
Rules: rules,
RulesetVersion: resp.RulesetVersion,
}
}