chore: publish IntegraCI build modules 732ec6c83925
This commit is contained in:
1 parent
7a84930dea
commit
5f8a24d014
133 files changed
+18990
-2
No files matched your search
@@ -0,0 +1,44 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// Liquibase prints one UPDATE SUMMARY per changelog it ran; "Run:" is the
|
||||
// number of changesets that summary applied.
|
||||
liquibaseRun = regexp.MustCompile(`(?m)^Run:\s+(\d+)\s*$`)
|
||||
// Flyway prints one line for the whole run.
|
||||
flywayApplied = regexp.MustCompile(`Successfully applied (\d+) migrations?`)
|
||||
)
|
||||
|
||||
// AppliedCount reads how many migrations an apply ran from the tool's own
|
||||
// summary. Each tool reports it differently, and a marker that fits one tool
|
||||
// counts nothing (or the wrong thing) in another: until 2026-09-27 this module
|
||||
// reported 0 for every Liquibase run and 1 for every Flyway run of any size.
|
||||
// An output without the tool's summary counts 0.
|
||||
func AppliedCount(tool, out string) int {
|
||||
count := 0
|
||||
switch tool {
|
||||
case "liquibase":
|
||||
for _, m := range liquibaseRun.FindAllStringSubmatch(out, -1) {
|
||||
n, _ := strconv.Atoi(m[1])
|
||||
count += n
|
||||
}
|
||||
case "flyway":
|
||||
for _, m := range flywayApplied.FindAllStringSubmatch(out, -1) {
|
||||
n, _ := strconv.Atoi(m[1])
|
||||
count += n
|
||||
}
|
||||
case "atlas":
|
||||
// One "-- migrating version <v>" line per file it applied.
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), "-- migrating version ") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
// The outputs below are what the pinned images printed on 2026-09-27
|
||||
// (liquibase 4.31.1-alpine, flyway 10.22.0-alpine, atlas 1.3.3-community-alpine),
|
||||
// trimmed to the lines that matter.
|
||||
|
||||
const liquibaseTwoChangelogs = `Liquibase Open Source 4.31.1 by Liquibase
|
||||
UPDATE SUMMARY
|
||||
Run: 2
|
||||
Previously run: 0
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 2
|
||||
Liquibase: Update has been successful. Rows affected: 4
|
||||
Liquibase Open Source 4.31.1 by Liquibase
|
||||
UPDATE SUMMARY
|
||||
Run: 1
|
||||
Previously run: 0
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 1
|
||||
`
|
||||
|
||||
// A changelog two of whose three changesets had already run.
|
||||
const liquibasePartlyRun = `UPDATE SUMMARY
|
||||
Run: 1
|
||||
Previously run: 2
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 3
|
||||
`
|
||||
|
||||
const flywayTwo = `Successfully validated 2 migrations (execution time 00:00.020s)
|
||||
Migrating schema "main" to version "1 - a"
|
||||
Migrating schema "main" to version "2 - b"
|
||||
Successfully applied 2 migrations to schema "main", now at version v2 (execution time 00:00.006s)
|
||||
`
|
||||
|
||||
const flywayNothing = `Successfully validated 2 migrations (execution time 00:00.041s)
|
||||
Current version of schema "main": 2
|
||||
Schema "main" is up to date. No migration necessary.
|
||||
`
|
||||
|
||||
const atlasTwo = `Migrating to version 20260927000002 (2 migrations in total):
|
||||
|
||||
-- migrating version 20260927000001
|
||||
-> CREATE TABLE t (id int);
|
||||
-- ok (1.2ms)
|
||||
|
||||
-- migrating version 20260927000002
|
||||
-> DROP TABLE t;
|
||||
-- ok (3.4ms)
|
||||
|
||||
-------------------------
|
||||
-- 11.18681ms
|
||||
-- 2 migrations
|
||||
-- 2 sql statements
|
||||
`
|
||||
|
||||
func TestAppliedCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
tool, out string
|
||||
want int
|
||||
}{
|
||||
{"liquibase", liquibaseTwoChangelogs, 3},
|
||||
// "Previously run" and "Total change sets" are not what ran.
|
||||
{"liquibase", liquibasePartlyRun, 1},
|
||||
{"liquibase", "UPDATE SUMMARY\nRun: 0\nPreviously run: 5\n", 0},
|
||||
{"flyway", flywayTwo, 2},
|
||||
{"flyway", flywayNothing, 0},
|
||||
{"flyway", "Successfully applied 1 migration to schema \"main\"", 1},
|
||||
{"atlas", atlasTwo, 2},
|
||||
// One tool's markers count nothing for another.
|
||||
{"liquibase", flywayTwo, 0},
|
||||
{"flyway", atlasTwo, 0},
|
||||
{"atlas", liquibaseTwoChangelogs, 0},
|
||||
{"none", liquibaseTwoChangelogs, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := AppliedCount(c.tool, c.out); got != c.want {
|
||||
t.Errorf("AppliedCount(%q) = %d, want %d", c.tool, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// liquibaseRunsUnjudged matches a formatted-SQL directive line that makes
|
||||
// Liquibase run, or skip, text the engine read as a comment:
|
||||
//
|
||||
// - precondition(s)/precondition-sql-check: runs the query in the comment
|
||||
// (measured 2026-09-27 on 4.31.1: `--precondition-sql-check expectedResult:0
|
||||
// WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*) FROM d` is
|
||||
// judged "additive" — the engine sees a comment — and Liquibase executes it);
|
||||
// - include/includeAll: pull in files nobody sent to the engine;
|
||||
// - property: defines a ${…} value substituted after judging;
|
||||
// - validCheckSum: accepts an edited changeset without re-running the check;
|
||||
// - ignoreLines: skips judged lines, so what runs is not what was judged.
|
||||
//
|
||||
// The platform refuses the same set, and more, for changesets it renders itself
|
||||
// (apps/api/app/platform/services/db_apply_service.py, _LIQUIBASE_DIRECTIVE_LINE).
|
||||
// A tenant's own file keeps the lines a formatted-SQL changelog needs:
|
||||
// `--liquibase formatted sql`, `--changeset author:id [attributes]`,
|
||||
// `--rollback`, `--comment`.
|
||||
var liquibaseRunsUnjudged = regexp.MustCompile(
|
||||
`(?i)^\s*--\s*(?:preconditions?|precondition-[a-z-]+|include|includeall|property|validchecksum|ignorelines)\b`)
|
||||
|
||||
// lineEnds are line ends as Liquibase's reader sees them (Java readLine): a
|
||||
// lone \r ends a line too, so "SELECT 1;\r--precondition-sql-check …" is two
|
||||
// lines to Liquibase and must be two lines here.
|
||||
var lineEnds = regexp.MustCompile(`\r\n|\r|\n`)
|
||||
|
||||
// LiquibaseJudgeable refuses a formatted-SQL file holding a directive through
|
||||
// which Liquibase would run (or skip) text the engine did not judge.
|
||||
func LiquibaseJudgeable(file, sql string) error {
|
||||
for i, line := range lineEnds.Split(sql, -1) {
|
||||
if liquibaseRunsUnjudged.MatchString(line) {
|
||||
return fmt.Errorf("%s line %d is a Liquibase directive (%q) that runs or skips SQL the engine read as a comment; "+
|
||||
"the engine cannot judge it, so it is refused — write the check as its own changeset", file, i+1, line)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLiquibaseJudgeable(t *testing.T) {
|
||||
refused := []string{
|
||||
"--liquibase formatted sql\n--changeset a:1\n--precondition-sql-check expectedResult:0 WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*) FROM d\nCREATE TABLE t (id int);",
|
||||
"--preconditions onFail:MARK_RAN\nCREATE TABLE t (id int);",
|
||||
"--precondition-table-exists table:t",
|
||||
"--include file:other.sql",
|
||||
"--includeAll path:more/",
|
||||
"--property name:x value:y",
|
||||
"--validCheckSum: ANY",
|
||||
"--ignoreLines:start\nDROP TABLE t;\n--ignoreLines:end",
|
||||
" -- PRECONDITION-SQL-CHECK expectedResult:0 SELECT 1",
|
||||
// A lone \r ends a line for Liquibase.
|
||||
"SELECT 1;\r--precondition-sql-check expectedResult:0 SELECT 1",
|
||||
}
|
||||
for _, sql := range refused {
|
||||
if LiquibaseJudgeable("V1.sql", sql) == nil {
|
||||
t.Errorf("accepted %q", sql)
|
||||
}
|
||||
}
|
||||
// What a tenant's own formatted-SQL changelog legitimately holds.
|
||||
allowed := []string{
|
||||
"--liquibase formatted sql\n--changeset alice:1\nCREATE TABLE t (id int);\n--rollback DROP TABLE t;",
|
||||
"--changeset alice:2 splitStatements:false\nCREATE FUNCTION f() RETURNS int AS $$ SELECT 1 $$ LANGUAGE sql;",
|
||||
"--comment: adds the orders table\nCREATE TABLE orders (id int);",
|
||||
"-- a plain comment about preconditions in prose\nCREATE TABLE t (id int);",
|
||||
"CREATE TABLE includes (id int); -- not a directive",
|
||||
"",
|
||||
}
|
||||
for _, sql := range allowed {
|
||||
if err := LiquibaseJudgeable("V1.sql", sql); err != nil {
|
||||
t.Errorf("refused %q: %v", sql, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Grant is a single-use permission to run one batch (plan §P5): the batch
|
||||
// digest, the changelog's SHA-256, the stage and ruleset it was judged under,
|
||||
// an id and an expiry, all signed by Token.
|
||||
// apps/api/app/platform/services/db_execution.py mints it.
|
||||
type Grant struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Stage string `json:"stage"`
|
||||
Ruleset string `json:"ruleset"`
|
||||
JTI string `json:"jti"`
|
||||
Exp int64 `json:"exp"`
|
||||
// Kind is "apply", or "rollback:<n>" to undo the last n changesets.
|
||||
Kind string `json:"kind"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// Granted is the changelog the platform hands out for a grant.
|
||||
type Granted struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Changelog string `json:"changelog"`
|
||||
Changesets []string `json:"changesets"`
|
||||
// ChangelogName is the file name (without .sql) the platform applies this
|
||||
// schema's changelog under. Liquibase records a changeset by id, author AND
|
||||
// file name, so running it under any other name would run it again.
|
||||
ChangelogName string `json:"changelog_name"`
|
||||
}
|
||||
|
||||
var safeChangelogName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
// FileName is the changelog's file name, or an error when the platform named
|
||||
// something that is not a single safe path segment.
|
||||
func (g *Granted) FileName() (string, error) {
|
||||
if !safeChangelogName.MatchString(g.ChangelogName) || strings.Contains(g.ChangelogName, "..") {
|
||||
return "", fmt.Errorf("the granted changelog name %q is not a safe file name", g.ChangelogName)
|
||||
}
|
||||
return g.ChangelogName + ".sql", nil
|
||||
}
|
||||
|
||||
// ExecutionResult is the report of a delegated run.
|
||||
type ExecutionResult struct {
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Stage string `json:"stage"`
|
||||
Ruleset string `json:"ruleset"`
|
||||
JTI string `json:"jti"`
|
||||
Exp int64 `json:"exp"`
|
||||
Kind string `json:"kind"`
|
||||
Outcome string `json:"outcome"`
|
||||
ExecutionRef string `json:"execution_ref"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// The platform endpoints this client calls, as route templates. Kept in one
|
||||
// place because apps/api/tests/test_dagger_db_migration_paths_exist.py reads
|
||||
// them and checks each is a route the API serves: a fake server in these Go
|
||||
// tests would answer a path the API never had.
|
||||
const (
|
||||
GrantPath = "/api/v1/db-instances/{instance_id}/execution-grant"
|
||||
ChangelogPath = "/api/v1/db-executions/{instance_id}/changelog"
|
||||
ResultPath = "/api/v1/db-executions/{instance_id}/result"
|
||||
DriftReportPath = "/api/v1/db-instances/{instance_id}/drift-report"
|
||||
SnapshotPath = "/api/v1/db-executions/{instance_id}/snapshot"
|
||||
)
|
||||
|
||||
// endpoint fills a route template with the instance id.
|
||||
func endpoint(apiURL, template, instanceID string) string {
|
||||
return strings.TrimRight(apiURL, "/") + strings.Replace(template, "{instance_id}", url.PathEscape(instanceID), 1)
|
||||
}
|
||||
|
||||
// RequestGrant asks the platform for a single-use grant to run the batch with
|
||||
// this digest. The platform re-runs the gate first: a blocked batch, or one
|
||||
// needing an approval nobody recorded for this digest, gets no grant.
|
||||
func RequestGrant(ctx context.Context, client *http.Client, apiURL, apiToken, instanceID, digest string, rollbackCount int) (*Grant, error) {
|
||||
req0 := map[string]any{"digest": digest}
|
||||
if rollbackCount > 0 {
|
||||
req0["kind"] = "rollback"
|
||||
req0["count"] = rollbackCount
|
||||
}
|
||||
body, err := json.Marshal(req0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := endpoint(apiURL, GrantPath, instanceID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("requesting a grant: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("requesting a grant: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var g Grant
|
||||
if err := json.Unmarshal(raw, &g); err != nil {
|
||||
return nil, fmt.Errorf("the grant is not readable: %w", err)
|
||||
}
|
||||
wantKind := "apply"
|
||||
if rollbackCount > 0 {
|
||||
wantKind = fmt.Sprintf("rollback:%d", rollbackCount)
|
||||
}
|
||||
if g.Token == "" || g.JTI == "" || len(g.ChangelogSHA256) != 64 || g.Digest != digest || g.Kind != wantKind {
|
||||
return nil, fmt.Errorf("the platform answered with something that is not a grant for %s", digest)
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// RequestObservationGrant asks for a single-use grant to observe the instance:
|
||||
// kind "drift" or "snapshot". The platform binds it to the instance's applied
|
||||
// state; for drift that state, as a changelog, is the reference to diff against.
|
||||
func RequestObservationGrant(ctx context.Context, client *http.Client, apiURL, apiToken, instanceID, kind string) (*Grant, error) {
|
||||
if kind != "drift" && kind != "snapshot" {
|
||||
return nil, fmt.Errorf("%q is not an observation grant", kind)
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"kind": kind})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, GrantPath, instanceID), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("requesting a %s grant: %w", kind, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("requesting a %s grant: HTTP %d", kind, resp.StatusCode)
|
||||
}
|
||||
var g Grant
|
||||
if err := json.Unmarshal(raw, &g); err != nil {
|
||||
return nil, fmt.Errorf("the grant is not readable: %w", err)
|
||||
}
|
||||
if g.Token == "" || g.JTI == "" || len(g.Digest) != 64 || len(g.ChangelogSHA256) != 64 || g.Kind != kind {
|
||||
return nil, fmt.Errorf("the platform answered with something that is not a %s grant", kind)
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// FetchGranted gets the granted changelog and REFUSES it unless its SHA-256 is
|
||||
// the one the grant names: what runs must be what the platform judged.
|
||||
func FetchGranted(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant) (*Granted, error) {
|
||||
q := url.Values{}
|
||||
q.Set("digest", g.Digest)
|
||||
q.Set("changelog_sha256", g.ChangelogSHA256)
|
||||
q.Set("stage", g.Stage)
|
||||
q.Set("ruleset", g.Ruleset)
|
||||
q.Set("jti", g.JTI)
|
||||
q.Set("kind", g.Kind)
|
||||
q.Set("exp", strconv.FormatInt(g.Exp, 10))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint(apiURL, ChangelogPath, g.InstanceID)+"?"+q.Encode(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching the granted changelog: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("fetching the granted changelog: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var out Granted
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("the granted changelog is not readable: %w", err)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(out.Changelog))
|
||||
if got := hex.EncodeToString(sum[:]); got != g.ChangelogSHA256 {
|
||||
return nil, fmt.Errorf("the changelog's SHA-256 is %s, the grant names %s: refusing to run it", got, g.ChangelogSHA256)
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// Report tells the platform what the run did.
|
||||
func Report(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, outcome, ref, message string) error {
|
||||
if len(message) > 1000 {
|
||||
message = message[:1000]
|
||||
}
|
||||
body, err := json.Marshal(ExecutionResult{
|
||||
Digest: g.Digest, ChangelogSHA256: g.ChangelogSHA256, Stage: g.Stage, Ruleset: g.Ruleset, JTI: g.JTI, Exp: g.Exp, Kind: g.Kind,
|
||||
Outcome: outcome, ExecutionRef: ref, Message: message,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, ResultPath, g.InstanceID), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reporting the outcome: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("reporting the outcome: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DriftReport is a drift check the executor ran against its own database,
|
||||
// under a drift grant: its database against the grant's reference.
|
||||
type DriftReport struct {
|
||||
Drifted bool `json:"drifted"`
|
||||
Diff string `json:"diff"`
|
||||
ExecutionRef string `json:"execution_ref"`
|
||||
}
|
||||
|
||||
// Drifted reads Liquibase's diff output the way the platform's connector does:
|
||||
// a Missing, Unexpected or Changed section with an entry is drift.
|
||||
func Drifted(diff string) bool {
|
||||
for _, marker := range []string{"Missing ", "Unexpected ", "Changed "} {
|
||||
for _, line := range strings.Split(diff, "\n") {
|
||||
l := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(l, marker) && !strings.HasSuffix(l, ": NONE") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// grantFields are the signed fields a report repeats, with the token that signs them.
|
||||
func grantFields(g Grant) map[string]any {
|
||||
return map[string]any{
|
||||
"digest": g.Digest, "changelog_sha256": g.ChangelogSHA256, "stage": g.Stage,
|
||||
"ruleset": g.Ruleset, "jti": g.JTI, "exp": g.Exp, "kind": g.Kind,
|
||||
}
|
||||
}
|
||||
|
||||
// postGranted sends a report made under grant g, once.
|
||||
func postGranted(ctx context.Context, client *http.Client, apiURL, apiToken, template string, g Grant, fields map[string]any) error {
|
||||
body := grantFields(g)
|
||||
for k, v := range fields {
|
||||
body[k] = v
|
||||
}
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, template, g.InstanceID), bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reporting the %s: %w", g.Kind, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("reporting the %s: HTTP %d", g.Kind, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReportDrift records the check on the platform under its drift grant.
|
||||
func ReportDrift(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, r DriftReport) error {
|
||||
if len(r.Diff) > 8000 {
|
||||
r.Diff = r.Diff[:8000]
|
||||
}
|
||||
return postGranted(ctx, client, apiURL, apiToken, DriftReportPath, g, map[string]any{
|
||||
"drifted": r.Drifted, "diff": r.Diff, "execution_ref": r.ExecutionRef,
|
||||
})
|
||||
}
|
||||
|
||||
// ReportSnapshot records a snapshot under its snapshot grant: its SHA-256 and
|
||||
// size. The JSON stays with the executor.
|
||||
func ReportSnapshot(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, outcome, snapshot, ref, message string) error {
|
||||
if len(message) > 1000 {
|
||||
message = message[:1000]
|
||||
}
|
||||
fields := map[string]any{"outcome": outcome, "execution_ref": ref, "snapshot_bytes": len(snapshot), "snapshot_sha256": ""}
|
||||
if snapshot != "" {
|
||||
sum := sha256.Sum256([]byte(snapshot))
|
||||
fields["snapshot_sha256"] = hex.EncodeToString(sum[:])
|
||||
}
|
||||
if message != "" {
|
||||
fields["message"] = message
|
||||
}
|
||||
return postGranted(ctx, client, apiURL, apiToken, SnapshotPath, g, fields)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sum(s string) string {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func client() *http.Client { return &http.Client{Timeout: 5 * time.Second} }
|
||||
|
||||
func TestRequestGrantRefusesAnythingButAGrantForTheDigest(t *testing.T) {
|
||||
digest := strings.Repeat("d", 64)
|
||||
good := Grant{InstanceID: "i", Digest: digest, ChangelogSHA256: strings.Repeat("c", 64), Stage: "dev", Ruleset: "r", JTI: "abcdef012345", Exp: 1, Kind: "apply", Token: "t"}
|
||||
cases := map[string]Grant{
|
||||
"another digest": func() Grant { g := good; g.Digest = strings.Repeat("e", 64); return g }(),
|
||||
"no token": func() Grant { g := good; g.Token = ""; return g }(),
|
||||
"no id": func() Grant { g := good; g.JTI = ""; return g }(),
|
||||
"a rollback": func() Grant { g := good; g.Kind = "rollback:1"; return g }(),
|
||||
}
|
||||
for name, answer := range cases {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(answer)
|
||||
}))
|
||||
_, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 0)
|
||||
srv.Close()
|
||||
if err == nil {
|
||||
t.Fatalf("%s: accepted as a grant", name)
|
||||
}
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/db-instances/i/execution-grant" || r.Header.Get("Authorization") != "Bearer api" {
|
||||
t.Errorf("unexpected request %s %s", r.URL.Path, r.Header.Get("Authorization"))
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(good)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchGrantedRefusesAChangelogWithAnotherHash(t *testing.T) {
|
||||
changelog := "--liquibase formatted sql\nCREATE TABLE t (id int);\n"
|
||||
for name, served := range map[string]string{"same": changelog, "tampered": changelog + "DROP TABLE t;\n"} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-Execution-Token") != "tok" || r.URL.Query().Get("jti") != "j1" {
|
||||
t.Errorf("the grant was not presented: %v", r.URL.Query())
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Granted{Changelog: served})
|
||||
}))
|
||||
_, err := FetchGranted(context.Background(), client(), srv.URL, "api",
|
||||
Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: sum(changelog), JTI: "j1", Token: "tok"})
|
||||
srv.Close()
|
||||
if (err == nil) != (name == "same") {
|
||||
t.Fatalf("%s: err=%v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportSendsEverySignedField(t *testing.T) {
|
||||
var got ExecutionResult
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: "c", Stage: "prod", Ruleset: "r", JTI: "j", Exp: 9, Kind: "rollback:2", Token: "t"}
|
||||
if err := Report(context.Background(), client(), srv.URL, "api", g, "applied", "ref", "ok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Stage != "prod" || got.Ruleset != "r" || got.JTI != "j" || got.Exp != 9 || got.Outcome != "applied" || got.Kind != "rollback:2" {
|
||||
t.Fatalf("report = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A rollback asks for a rollback grant of exactly that many changesets, and
|
||||
// refuses an apply grant (or a rollback of another count) handed back instead:
|
||||
// the executor must not run a batch it was not told to run.
|
||||
func TestRequestGrantForARollbackNamesTheKindAndCount(t *testing.T) {
|
||||
digest := strings.Repeat("d", 64)
|
||||
for _, answered := range []string{"rollback:2", "rollback:3", "apply"} {
|
||||
var asked map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewDecoder(r.Body).Decode(&asked)
|
||||
_ = json.NewEncoder(w).Encode(Grant{InstanceID: "i", Digest: digest, ChangelogSHA256: strings.Repeat("c", 64), JTI: "j", Kind: answered, Token: "t"})
|
||||
}))
|
||||
_, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 2)
|
||||
srv.Close()
|
||||
if asked["kind"] != "rollback" || asked["count"] != float64(2) {
|
||||
t.Fatalf("request = %v", asked)
|
||||
}
|
||||
if (err == nil) != (answered == "rollback:2") {
|
||||
t.Fatalf("answered %s: err=%v", answered, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchGrantedPresentsTheKind(t *testing.T) {
|
||||
changelog := "--liquibase formatted sql\n"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("kind") != "rollback:1" {
|
||||
t.Errorf("kind not presented: %v", r.URL.Query())
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Granted{Changelog: changelog})
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := FetchGranted(context.Background(), client(), srv.URL, "api",
|
||||
Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: sum(changelog), JTI: "j", Kind: "rollback:1", Token: "t"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The file name is the one the platform applies the schema under (Liquibase
|
||||
// keys a changeset on it), and never a path.
|
||||
func TestGrantedFileNameIsOneSafeSegment(t *testing.T) {
|
||||
for name, ok := range map[string]bool{
|
||||
"schema-0b7c2f9e-3a1d-4c55-9d7e-2f1a6b8c9d0e": true,
|
||||
"": false,
|
||||
"../etc/passwd": false,
|
||||
"a/b": false,
|
||||
"schema..x": false,
|
||||
"-flag": false,
|
||||
"name with space": false,
|
||||
} {
|
||||
file, err := (&Granted{ChangelogName: name}).FileName()
|
||||
if (err == nil) != ok {
|
||||
t.Fatalf("%q: err=%v", name, err)
|
||||
}
|
||||
if ok && file != name+".sql" {
|
||||
t.Fatalf("%q -> %q", name, file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriftedReadsTheDiffSections(t *testing.T) {
|
||||
clean := "Diff Results:\nMissing Column(s): NONE\nUnexpected Table(s): NONE\nChanged Index(s): NONE\n"
|
||||
if Drifted(clean) {
|
||||
t.Fatal("a diff with nothing in any section is not drift")
|
||||
}
|
||||
if !Drifted("Diff Results:\nMissing Column(s): \n public.users.email\nUnexpected Table(s): NONE\n") {
|
||||
t.Fatal("a missing column is drift")
|
||||
}
|
||||
if !Drifted("Unexpected Table(s): scratch") {
|
||||
t.Fatal("an unexpected table is drift")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportDriftPostsUnderItsGrant(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/db-instances/i/drift-report" || r.Header.Get("Authorization") != "Bearer api" {
|
||||
t.Errorf("unexpected request %s", r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("X-Execution-Token") != "tok" {
|
||||
t.Errorf("the drift report was sent without its grant's token")
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Digest: strings.Repeat("a", 64), ChangelogSHA256: strings.Repeat("b", 64), Stage: "prod", Ruleset: "r", JTI: "abc123def456", Exp: 9, Kind: "drift", Token: "tok"}
|
||||
if err := ReportDrift(context.Background(), client(), srv.URL, "api", g, DriftReport{Drifted: true, Diff: strings.Repeat("x", 9000), ExecutionRef: "ci-1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["drifted"] != true || got["execution_ref"] != "ci-1" || len(got["diff"].(string)) != 8000 {
|
||||
t.Fatalf("report = %+v", got)
|
||||
}
|
||||
if got["jti"] != "abc123def456" || got["kind"] != "drift" || got["digest"] != g.Digest {
|
||||
t.Fatalf("the report does not repeat its grant's signed fields: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnObservationGrantIsDriftOrSnapshotAndIsChecked(t *testing.T) {
|
||||
if _, err := RequestObservationGrant(context.Background(), client(), "http://x", "api", "i", "apply"); err == nil {
|
||||
t.Fatal("an apply grant was asked for as an observation")
|
||||
}
|
||||
answer := `{"instance_id":"i","digest":"` + strings.Repeat("a", 64) + `","changelog_sha256":"` + strings.Repeat("b", 64) + `","stage":"prod","ruleset":"r","jti":"j1","exp":9,"kind":"%s","token":"t"}`
|
||||
for _, tc := range []struct {
|
||||
kind, answered string
|
||||
ok bool
|
||||
}{{"drift", "drift", true}, {"drift", "snapshot", false}, {"snapshot", "snapshot", true}} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["kind"] != tc.kind || body["digest"] != nil {
|
||||
t.Errorf("request = %+v", body)
|
||||
}
|
||||
_, _ = w.Write([]byte(strings.Replace(answer, "%s", tc.answered, 1)))
|
||||
}))
|
||||
_, err := RequestObservationGrant(context.Background(), client(), srv.URL, "api", "i", tc.kind)
|
||||
srv.Close()
|
||||
if (err == nil) != tc.ok {
|
||||
t.Errorf("%s answered as %s: err = %v", tc.kind, tc.answered, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestASnapshotIsReportedAsItsHashUnderItsGrant(t *testing.T) {
|
||||
var path, token string
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path, token = r.URL.Path, r.Header.Get("X-Execution-Token")
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Kind: "snapshot", Token: "tok"}
|
||||
big := strings.Repeat("x", 3_000_000)
|
||||
if err := ReportSnapshot(context.Background(), client(), srv.URL, "api", g, "taken", big, "ci", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != "/api/v1/db-executions/i/snapshot" || token != "tok" {
|
||||
t.Fatalf("path %q token %q", path, token)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(big))
|
||||
if got["snapshot_sha256"] != hex.EncodeToString(sum[:]) || got["snapshot_bytes"] != float64(len(big)) {
|
||||
t.Fatalf("report = %v", got["snapshot_bytes"])
|
||||
}
|
||||
if _, sent := got["snapshot"]; sent {
|
||||
t.Fatal("the snapshot JSON itself was sent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAReleaseIsAServiceAndAVersionTogether(t *testing.T) {
|
||||
if _, _, err := Release("svc", ""); err == nil {
|
||||
t.Error("a service without a version was accepted")
|
||||
}
|
||||
if _, _, err := Release("", "abc123"); err == nil {
|
||||
t.Error("a version without a service was accepted")
|
||||
}
|
||||
s, v, err := Release("", "")
|
||||
if err != nil || s != nil || v != nil {
|
||||
t.Errorf("no release: got %v %v %v", s, v, err)
|
||||
}
|
||||
s, v, err = Release("svc", "abc123")
|
||||
if err != nil || *s != "svc" || *v != "abc123" {
|
||||
t.Errorf("a release: got %v %v %v", s, v, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The request names the release only when there is one, so a lint that names
|
||||
// none sends exactly what it sent before.
|
||||
func TestTheRequestCarriesTheReleaseOnlyWhenNamed(t *testing.T) {
|
||||
var seen []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var got map[string]any
|
||||
_ = json.Unmarshal(body, &got)
|
||||
seen = append(seen, got)
|
||||
_, _ = w.Write([]byte(`{"decision":"allow","reasons":[],"violations":[]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
service, version, file := "svc", "abc123", "V1.sql"
|
||||
for _, req := range []Request{
|
||||
{SQL: "SELECT 1", Dialect: "postgres"},
|
||||
{SQL: "SELECT 1", Dialect: "postgres", ServiceID: &service, Version: &version, File: &file},
|
||||
} {
|
||||
if _, err := Analyze(context.Background(), client, srv.URL, "t", req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"service_id", "version", "file"} {
|
||||
if _, ok := seen[0][key]; ok {
|
||||
t.Errorf("a lint naming no release sent %q", key)
|
||||
}
|
||||
}
|
||||
if seen[1]["service_id"] != "svc" || seen[1]["version"] != "abc123" || seen[1]["file"] != "V1.sql" {
|
||||
t.Errorf("the release was not sent: %v", seen[1])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MigrationTools are the values --tool takes. The CI presets offer the same
|
||||
// set (ci_presets.DB_MIGRATION_TOOLS; a test in apps/api compares the two).
|
||||
var MigrationTools = map[string]bool{"liquibase": true, "flyway": true, "atlas": true, "none": true}
|
||||
|
||||
// CheckTool refuses a tool the module does not run, before anything runs.
|
||||
// Until 2026-09-27 any other value — a typo such as "liquibse" — fell through
|
||||
// to atlas and applied the directory with a tool nobody chose.
|
||||
//
|
||||
// It also refuses atlas for anything but PostgreSQL and MySQL: the module runs
|
||||
// the Atlas Community Edition, which migrates those two
|
||||
// (https://atlasgo.io/community-edition); SQL Server and Oracle keep their own
|
||||
// message, as they are the ones asked for most.
|
||||
func CheckTool(tool, dialect string) error {
|
||||
if !MigrationTools[tool] {
|
||||
return fmt.Errorf("--tool=%q is not one of liquibase, flyway, atlas, none", tool)
|
||||
}
|
||||
if tool == "atlas" && (dialect == "tsql" || dialect == "oracle") {
|
||||
return fmt.Errorf("atlas community edition does not support dialect %q (SQL Server and Oracle are in its proprietary build only); use liquibase", dialect)
|
||||
}
|
||||
if tool == "atlas" && !atlasDialects[dialect] {
|
||||
return fmt.Errorf("atlas community edition does not support %q; use liquibase or flyway", dialect)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// atlasDialects are what the Atlas Community Edition migrates.
|
||||
var atlasDialects = map[string]bool{"postgres": true, "mysql": true}
|
||||
|
||||
// DefaultDialect is what a local tool (atlas's dev database) runs when
|
||||
// neither --engine nor --dialect names one. --dialect itself has no default:
|
||||
// unset, it is not sent, and the platform judges the SQL in the engines of the
|
||||
// service's own databases (with --service-id) — a default "postgres" sent on
|
||||
// every call made that impossible.
|
||||
const DefaultDialect = "postgres"
|
||||
|
||||
// Target is what the platform is asked to judge the SQL as: the database
|
||||
// ENGINE when one is named — the platform then judges it in that engine's own
|
||||
// dialect, and one it has no rules for (MongoDB, Snowflake, ...) comes back
|
||||
// unjudged, needing an approver (GET /db-engines) — otherwise the SQL
|
||||
// dialect. Never both: the endpoint refuses a request naming both.
|
||||
type Target struct {
|
||||
Engine string
|
||||
Dialect string
|
||||
}
|
||||
|
||||
// ResolveTarget reads --engine and --dialect. Naming both is refused rather
|
||||
// than one of the two silently ignored.
|
||||
func ResolveTarget(engine, dialect string) (Target, error) {
|
||||
engine = strings.ToLower(strings.TrimSpace(engine))
|
||||
dialect = strings.TrimSpace(dialect)
|
||||
if engine == "" {
|
||||
return Target{Dialect: dialect}, nil
|
||||
}
|
||||
if dialect != "" {
|
||||
return Target{}, fmt.Errorf("give --engine or --dialect, not both (--engine=%q, --dialect=%q)", engine, dialect)
|
||||
}
|
||||
return Target{Engine: engine}, nil
|
||||
}
|
||||
|
||||
// ToolDialect is the dialect a migration TOOL works in on this runner (atlas
|
||||
// replays the files on a dev database of it). Only atlas reads it, and atlas
|
||||
// knows PostgreSQL and MySQL; any other engine is returned as it is, which
|
||||
// CheckTool refuses for atlas.
|
||||
func (t Target) ToolDialect() string {
|
||||
switch t.Engine {
|
||||
case "":
|
||||
if t.Dialect == "" {
|
||||
return DefaultDialect
|
||||
}
|
||||
return t.Dialect
|
||||
case "postgres", "postgresql":
|
||||
return "postgres"
|
||||
case "mysql", "mariadb":
|
||||
return "mysql"
|
||||
}
|
||||
return t.Engine
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCheckTool(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
tool, dialect string
|
||||
ok bool
|
||||
}{
|
||||
{"liquibase", "postgres", true},
|
||||
{"liquibase", "tsql", true},
|
||||
{"liquibase", "oracle", true},
|
||||
{"flyway", "mysql", true},
|
||||
{"atlas", "postgres", true},
|
||||
{"atlas", "mysql", true},
|
||||
{"none", "tsql", true},
|
||||
// A typo must fail, not fall through to some other tool.
|
||||
{"liquibse", "postgres", false},
|
||||
{"", "postgres", false},
|
||||
{"sqitch", "postgres", false},
|
||||
{"Liquibase", "postgres", false},
|
||||
// Atlas Community has no SQL Server or Oracle driver.
|
||||
{"atlas", "tsql", false},
|
||||
{"atlas", "oracle", false},
|
||||
} {
|
||||
err := CheckTool(c.tool, c.dialect)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("CheckTool(%q, %q) = %v, want ok=%v", c.tool, c.dialect, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --engine names what the platform judges the SQL as; with it, --dialect keeps
|
||||
// its default and is not sent (the endpoint refuses a request naming both).
|
||||
func TestResolveTarget(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
engine, dialect string
|
||||
want Target
|
||||
ok bool
|
||||
}{
|
||||
{"", "mysql", Target{Dialect: "mysql"}, true},
|
||||
{"", "", Target{}, true}, // neither: nothing sent, the platform decides
|
||||
{" SnowFlake ", "", Target{Engine: "snowflake"}, true},
|
||||
{"postgres", "postgres", Target{}, false},
|
||||
{"mongodb", "", Target{Engine: "mongodb"}, true},
|
||||
{"oracle", "tsql", Target{}, false},
|
||||
} {
|
||||
got, err := ResolveTarget(tc.engine, tc.dialect)
|
||||
if (err == nil) != tc.ok || got != tc.want {
|
||||
t.Errorf("ResolveTarget(%q, %q) = %+v, %v", tc.engine, tc.dialect, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAtlasRunsOnlyWhatItsCommunityEditionMigrates(t *testing.T) {
|
||||
for engine, ok := range map[string]bool{
|
||||
"postgres": true, "postgresql": true, "mysql": true, "mariadb": true,
|
||||
"snowflake": false, "mongodb": false, "sqlserver": false, "oracle": false,
|
||||
} {
|
||||
target, err := ResolveTarget(engine, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := CheckTool("atlas", target.ToolDialect()); (err == nil) != ok {
|
||||
t.Errorf("atlas on %s: err = %v", engine, err)
|
||||
}
|
||||
// The other tools bring the driver the tenant gives them.
|
||||
if err := CheckTool("liquibase", target.ToolDialect()); err != nil {
|
||||
t.Errorf("liquibase on %s: %v", engine, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Neither named: atlas's local dev database is PostgreSQL, as before.
|
||||
func TestToolDialectDefaultsToPostgres(t *testing.T) {
|
||||
if got := (Target{}).ToolDialect(); got != DefaultDialect {
|
||||
t.Fatalf("ToolDialect() = %q", got)
|
||||
}
|
||||
if err := CheckTool("atlas", (Target{}).ToolDialect()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAnalyzeSQLPostsTheScriptToTheEngineEndpoint(t *testing.T) {
|
||||
var got Request
|
||||
var path, auth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path, auth = r.URL.Path, r.Header.Get("Authorization")
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(body, &got)
|
||||
_, _ = w.Write([]byte(`{"decision":"blocked","reasons":["1 destructive statement(s) → block"],` +
|
||||
`"destructive_count":1,"security_count":0,"ruleset_version":"2026.09.1",` +
|
||||
`"violations":[{"rule_id":"DBV-011","severity":"block","message":"UPDATE without WHERE"},` +
|
||||
`{"rule_id":"DBV-035","severity":"info","message":"no lock_timeout"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
env := "env-1"
|
||||
resp, err := Analyze(context.Background(), srv.Client(), srv.URL+"/", "tok",
|
||||
Request{SQL: "UPDATE users SET admin = true;", Dialect: "postgres", EnvironmentID: &env})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != AnalyzePath || auth != "Bearer tok" {
|
||||
t.Fatalf("path=%q auth=%q", path, auth)
|
||||
}
|
||||
if got.SQL != "UPDATE users SET admin = true;" || got.Dialect != "postgres" || got.EnvironmentID == nil || *got.EnvironmentID != "env-1" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
v := Of("V1__x.sql", resp)
|
||||
if v.Decision != "blocked" || strings.Join(v.Rules, ",") != "DBV-011" {
|
||||
t.Fatalf("verdict = %+v (info findings are not rules that failed it)", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnythingButAVerdictIsAnError(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"forbidden": {http.StatusForbidden, `{"detail":"nope"}`},
|
||||
"server": {http.StatusBadGateway, `<html>bad gateway</html>`},
|
||||
"not json": {http.StatusOK, `<html>proxy login</html>`},
|
||||
"no decision": {http.StatusOK, `{"reasons":[]}`},
|
||||
// A verdict-shaped body on an error status (an intermediary replaying a
|
||||
// cached answer, say) is still not this request's verdict.
|
||||
"error status": {http.StatusServiceUnavailable, `{"decision":"allow"}`},
|
||||
}
|
||||
for name, c := range cases {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
_, _ = w.Write([]byte(c.body))
|
||||
}))
|
||||
_, err := Analyze(context.Background(), &http.Client{Timeout: 5 * time.Second}, srv.URL, "t", Request{SQL: "SELECT 1"})
|
||||
srv.Close()
|
||||
if err == nil {
|
||||
t.Fatalf("%s: an answer that is not a verdict must not pass", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhichDecisionsFailTheLint(t *testing.T) {
|
||||
cases := []struct {
|
||||
decision string
|
||||
block bool
|
||||
want bool
|
||||
}{
|
||||
{"allow", true, false},
|
||||
{"warn", true, false},
|
||||
{"requires_approval", true, true},
|
||||
{"requires_approval", false, false},
|
||||
{"blocked", true, true},
|
||||
{"blocked", false, true},
|
||||
{"something-new", true, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Fails(c.decision, c.block); got != c.want {
|
||||
t.Fatalf("Fails(%q, %v) = %v, want %v", c.decision, c.block, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangelogsTheEngineCannotReadAreNotSkippedQuietly(t *testing.T) {
|
||||
sqlFiles, unanalysable := SplitMigrations([]string{
|
||||
"V2__b.sql", "V1__a.SQL", "sub/", "sub/V3__c.sql", "db.changelog-master.xml",
|
||||
"changes.yaml", "README.md", "notes.txt", "atlas.sum", ".gitkeep",
|
||||
// A tool may run these (a flyway suffix set in the repo's config, a
|
||||
// Java migration); the engine cannot read them.
|
||||
"V4__drop.pgsql", "V5__Seed.java", "V6__x.sql.xml",
|
||||
})
|
||||
if strings.Join(sqlFiles, ",") != "V1__a.SQL,V2__b.sql,sub/V3__c.sql" {
|
||||
t.Fatalf("sql files = %v", sqlFiles)
|
||||
}
|
||||
if strings.Join(unanalysable, ",") != "V4__drop.pgsql,V5__Seed.java,V6__x.sql.xml,changes.yaml,db.changelog-master.xml" {
|
||||
t.Fatalf("unanalysable = %v", unanalysable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusedFollowsTheDecisionsAndRefusesAnEmptyJudgement(t *testing.T) {
|
||||
vs := []FileVerdict{
|
||||
{File: "V1.sql", Decision: "allow"},
|
||||
{File: "V2.sql", Decision: "requires_approval", Rules: []string{"DBV-030"}},
|
||||
{File: "V3.sql", Decision: "blocked", Rules: []string{"DBV-010"}},
|
||||
}
|
||||
got, err := Refused(vs, true)
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatalf("block=true: %v %v", got, err)
|
||||
}
|
||||
// Turning blocking off only lets requires_approval through: `blocked` is
|
||||
// the tenant's policy, not the pipeline's to waive.
|
||||
got, err = Refused(vs, false)
|
||||
if err != nil || len(got) != 1 || !strings.HasPrefix(got[0], "V3.sql: blocked") {
|
||||
t.Fatalf("block=false: %v %v", got, err)
|
||||
}
|
||||
if _, err := Refused(nil, true); err == nil {
|
||||
t.Fatal("a lint that judged nothing must not pass")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheClientFollowsNoRedirect(t *testing.T) {
|
||||
hops := 0
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hops++
|
||||
_, _ = w.Write([]byte(`{"decision":"allow"}`))
|
||||
}))
|
||||
defer target.Close()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, target.URL+AnalyzePath, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := Analyze(context.Background(), NewClient(), srv.URL, "t", Request{SQL: "SELECT 1"}); err == nil {
|
||||
t.Fatal("a redirect is not a verdict")
|
||||
}
|
||||
if hops != 0 {
|
||||
t.Fatal("the token followed a redirect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlaceholderMakesAScriptUnjudgeable(t *testing.T) {
|
||||
if !HasPlaceholder("SELECT ('${flyway:filename}');") {
|
||||
t.Fatal("flyway placeholder not seen")
|
||||
}
|
||||
if !HasPlaceholder("CREATE TABLE ${schema}.t (id int);") {
|
||||
t.Fatal("liquibase property not seen")
|
||||
}
|
||||
if HasPlaceholder("SELECT '$1', $$body$$;") {
|
||||
t.Fatal("dollar quoting is not a placeholder")
|
||||
}
|
||||
if Judgeable("V9.sql", "SELECT ('${flyway:filename}');") == nil {
|
||||
t.Fatal("a script with a placeholder was judgeable")
|
||||
}
|
||||
if Judgeable("V1.sql", strings.Repeat("x", MaxSQLBytes+1)) == nil {
|
||||
t.Fatal("an oversized script was judgeable")
|
||||
}
|
||||
if err := Judgeable("V1.sql", "CREATE TABLE t (id int);"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationsAreOrderedByTheirNumbers(t *testing.T) {
|
||||
sqlFiles, _ := SplitMigrations([]string{"V10__c.sql", "V2__b.sql", "V1__a.sql", "V010__d.sql"})
|
||||
if got := strings.Join(sqlFiles, ","); got != "V1__a.sql,V2__b.sql,V10__c.sql,V010__d.sql" {
|
||||
t.Fatalf("order = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARequestNamesTheEngineOrTheDialectNeverBoth(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
target Target
|
||||
want string
|
||||
}{
|
||||
{Target{Engine: "snowflake"}, `{"sql":"x","engine":"snowflake"}`},
|
||||
{Target{Dialect: "mysql"}, `{"sql":"x","dialect":"mysql"}`},
|
||||
// Neither: the platform picks (the service's engines, or PostgreSQL).
|
||||
{Target{}, `{"sql":"x"}`},
|
||||
} {
|
||||
body, err := json.Marshal(Request{SQL: "x", Dialect: tc.target.Dialect, Engine: tc.target.Engine})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != tc.want {
|
||||
t.Errorf("%+v -> %s", tc.target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A platform without engine support answers --engine with a 422; the step
|
||||
// says why instead of only relaying the body.
|
||||
func TestAn422ForAnEngineSaysThePlatformIsOlder(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"detail":"extra fields not permitted"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
for engine, hinted := range map[string]bool{"snowflake": true, "": false} {
|
||||
_, err := Analyze(context.Background(), NewClient(), srv.URL, "t", Request{SQL: "x", Engine: engine, Dialect: "postgres"})
|
||||
if err == nil || strings.Contains(err.Error(), "older than engine support") != hinted {
|
||||
t.Errorf("engine %q: err = %v", engine, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user