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,3 @@
|
||||
/dagger.gen.go linguist-generated
|
||||
/internal/dagger/** linguist-generated
|
||||
/internal/telemetry/** linguist-generated
|
||||
@@ -0,0 +1,4 @@
|
||||
/dagger.gen.go
|
||||
/internal/dagger
|
||||
/internal/telemetry
|
||||
/.env
|
||||
@@ -0,0 +1,212 @@
|
||||
# db-migration (Dagger module)
|
||||
|
||||
Judges a service's migration SQL with **IntegraCI's DB-change engine** — the DBV
|
||||
policy engine behind the tenant's own DB-change policy
|
||||
(`POST /api/v1/db-changes/analyze`) — and applies migrations with the
|
||||
tenant's own tool: `liquibase` (default), `flyway` or `atlas`.
|
||||
|
||||
Builds with `dagger functions` on engine v0.21.8 (verified 2026-09-27).
|
||||
|
||||
## Tools, images and databases
|
||||
|
||||
Every image is pinned by tag and digest in `main.go` (checked 2026-09-27).
|
||||
|
||||
| Tool | Image | Licence | Databases |
|
||||
| --- | --- | --- | --- |
|
||||
| `liquibase` | `liquibase/liquibase:4.31.1-alpine` — the version the platform runs | Apache 2.0 | PostgreSQL, SQL Server, Oracle, MariaDB, DB2, Firebird, Snowflake, SQLite, H2, HSQLDB (drivers in the image) |
|
||||
| `flyway` | `flyway/flyway:10.22.0-alpine` | Apache 2.0 (Community) | as Flyway Community supports |
|
||||
| `atlas` | `arigaio/atlas:1.3.3-community-alpine` | Apache 2.0 (Community Edition) | PostgreSQL, MySQL, MariaDB, SQLite |
|
||||
|
||||
- **MySQL with Liquibase:** the image has no MySQL Connector/J (it is GPL and
|
||||
not shipped), so a `jdbc:mysql:` URL finds no driver. Use a `jdbc:mariadb:`
|
||||
URL; the MariaDB driver talks to MySQL.
|
||||
- **Atlas is the Community Edition.** The standard `arigaio/atlas` image is
|
||||
licensed under the proprietary Atlas MSA; this module ran it until
|
||||
2026-09-27. Community migrates PostgreSQL and MySQL only, so `--tool=atlas`
|
||||
on any other dialect or engine is refused before anything runs.
|
||||
- **`--tool` is checked.** Anything but `liquibase`, `flyway`, `atlas` or
|
||||
`none` is refused. Until 2026-09-27 an unknown value (a typo) fell through
|
||||
to atlas and applied the directory with a tool nobody chose.
|
||||
- **What the SQL is judged as.** Name nothing, and the platform decides: in the
|
||||
engines of the service's own databases when `--service-id` is given (its
|
||||
`spec.resources` and the DB schemas registered to it — what the deploy gate
|
||||
judges with too), and as PostgreSQL otherwise. Or name the database
|
||||
**engine** (`--engine`): the platform judges in that engine's dialect, and
|
||||
an engine it has no rules for comes back unjudged (an approver decides, so
|
||||
the step fails under `--block-destructive`; `GET /api/v1/db-engines`). Or
|
||||
name the SQL **dialect** (`--dialect`: postgres, mysql, oracle, tsql) — not
|
||||
both. `--engine` needs a platform with engine support; an older one refuses
|
||||
it with HTTP 422, and the step fails. Before 2026-09-27 `--dialect` defaulted
|
||||
to `postgres` and was sent on every call, so a warehouse or MongoDB
|
||||
directory was judged as PostgreSQL.
|
||||
|
||||
## Engine adapters (ADR-0070 §1)
|
||||
|
||||
DBV judges; the tool that applies a change is an **adapter** in `engine/`. An
|
||||
adapter builds the command (the pinned image and the exact argv) and declares
|
||||
what it drives. It never sees a secret — `main.go` binds `$DATABASE_URL` /
|
||||
`$REFERENCE_URL` as Dagger secrets and mounts only the judged files — and it
|
||||
never picks the files: they are the ones the engine judged.
|
||||
|
||||
```go
|
||||
type Adapter interface {
|
||||
Name() string // the --tool value
|
||||
Capabilities() Capabilities
|
||||
Apply(files []string) (Command, error) // judged files, in order
|
||||
Rollback(file string, n int) (Command, error) // last n changesets of a granted changelog
|
||||
Drift(file string) (Command, error) // build file into $REFERENCE_URL, diff $DATABASE_URL
|
||||
Snapshot() (Command, error) // schema of $DATABASE_URL
|
||||
}
|
||||
```
|
||||
|
||||
An operation an adapter does not drive returns `engine.ErrUnsupported`; it
|
||||
never runs something else. What each adapter drives today:
|
||||
|
||||
| Adapter | Dialects accepted | apply | rollback | drift | snapshot | native lint | checksum |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `liquibase` (default, `engine.DefaultTool`) | postgres, mysql, oracle, tsql | yes | yes | yes | yes | — | changeset |
|
||||
| `flyway` | postgres, mysql, oracle, tsql | yes | — | — | — | — | file |
|
||||
| `atlas` | postgres, mysql | yes | — | — | — | yes (advisory) | directory |
|
||||
|
||||
- **Grants are written for the default adapter.** `execute`, `drift` and
|
||||
`snapshot` run under a platform grant whose changelog is Liquibase
|
||||
formatted SQL, so they use `engine.DefaultTool`. Re-choosing the default
|
||||
(ADR-0070 §2) is that one constant plus its mirror in the API.
|
||||
- **The pins stay in `main.go`.** `tools/ci/check-liquibase-pins.py` and
|
||||
Renovate read them there; `engine.New` receives them.
|
||||
- **The API mirrors the declarations** in
|
||||
`apps/api/app/platform/services/db_engine_adapters.py`. Both sides are
|
||||
tested against `engine/capabilities.json`; neither parses the other's
|
||||
language. `ci_presets.DB_MIGRATION_TOOLS` is derived from it (adapters plus
|
||||
`none`).
|
||||
- **Dialects are accepted, not tested per dialect.** They are what
|
||||
`verdict.CheckTool` lets through; per-dialect adapter tests are ADR-0070
|
||||
phase 2. Not driven by any adapter yet: dry-run SQL, `status`, and online
|
||||
schema change (pgroll, gh-ost).
|
||||
- **Phase 1 (#2135, 2026-10-11) changed no behaviour.** Every argv is
|
||||
byte-identical to the one `main.go` built inline before;
|
||||
`engine/engine_test.go` pins each one.
|
||||
|
||||
## Functions
|
||||
|
||||
### `lint`
|
||||
|
||||
Sends every `.sql` file under `dir` to IntegraCI and fails when the tenant's
|
||||
policy blocks a change — or requires approval for one, which nobody can give
|
||||
inside a CI step (the change then goes through IntegraCI's governed apply).
|
||||
For `atlas` it then runs `atlas migrate lint` — only after the policy has
|
||||
passed every file, because the lint **replays** the files on its dev database
|
||||
— and fails when that reports an error (a destructive change, for example);
|
||||
the lint's output is in the error. It sees the judged directory alone, so an
|
||||
`atlas.hcl` in the repo is not read. Without `--dev-url` (a secret: a DSN
|
||||
carries a password) the lint starts a throwaway PostgreSQL for this run only
|
||||
(`postgres:16.13-alpine`, as a Dagger service); another dialect needs
|
||||
`--dev-url`. The previous default, `docker://postgres/16/dev`, needs a Docker
|
||||
CLI inside the atlas container and never worked, so `--tool=atlas` failed in
|
||||
every generated pipeline (none passes `--dev-url`).
|
||||
|
||||
```sh
|
||||
dagger call lint \
|
||||
--source . \
|
||||
--dir migrations \
|
||||
--api-url "$INTEGRACI_URL" \
|
||||
--token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
| Param | Default | Description |
|
||||
| ------------------- | -------------------------- | -------------------------------------------------------- |
|
||||
| `source` | (required) | Source directory containing migrations |
|
||||
| `dir` | `migrations` | Migrations directory relative to source |
|
||||
| `tool` | `liquibase` | `liquibase` \| `atlas` \| `flyway` \| `none` (skip) |
|
||||
| `api-url` | (required unless `none`) | IntegraCI API URL — the engine that judges the SQL |
|
||||
| `token` | (required unless `none`) | IntegraCI API token |
|
||||
| `dialect` | (unset: the platform picks) | `postgres` \| `mysql` \| `oracle` \| `tsql` |
|
||||
| `engine` | (optional, instead of `dialect`) | Database engine; the platform picks the dialect (`GET /db-engines`) |
|
||||
| `environment-id` | (optional) | Tenant environment whose policy and stage apply |
|
||||
| `block-destructive` | `true` | Also fail on `requires_approval` (`blocked` always fails) |
|
||||
| `dev-url` | (a throwaway PostgreSQL) | Secret: dev DB atlas replays the migrations on (`atlas` only) |
|
||||
|
||||
**It fails closed.** The step fails when nothing has judged the SQL:
|
||||
- no `--api-url`/`--token`;
|
||||
- no `.sql` file in `dir` at all;
|
||||
- a file the engine cannot read: an XML/YAML/JSON changelog, a `.pgsql` or
|
||||
other suffix a tool may be configured to run, a Java migration. Only `.sql`,
|
||||
docs (`.md`, `.txt`, `.rst`, `README`, `LICENSE`), `.gitkeep` and
|
||||
`atlas.sum` may sit in `dir`. Use Liquibase formatted SQL, or `--tool=none`
|
||||
to opt out of governance;
|
||||
- with `--tool=liquibase`, a Liquibase directive that runs or skips text the
|
||||
engine reads as a comment: `--precondition*`/`--preconditions`,
|
||||
`--include`/`--includeAll`, `--property`, `--validCheckSum`,
|
||||
`--ignoreLines`. Measured 2026-09-27: `--precondition-sql-check
|
||||
expectedResult:0 WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*)
|
||||
FROM d` is judged "additive" and Liquibase executes it. `--liquibase
|
||||
formatted sql`, `--changeset` (with attributes), `--rollback` and
|
||||
`--comment` stay allowed;
|
||||
- a file holding a `${…}` placeholder. Flyway and Liquibase substitute it
|
||||
after the engine has judged the text, so what would run is not what was
|
||||
judged (`${flyway:filename}` in a file named `V9__x');DROP TABLE t;--.sql`);
|
||||
- a file over 200 kB;
|
||||
- an answer from IntegraCI that is not a verdict (non-2xx, a redirect, no
|
||||
`decision`).
|
||||
|
||||
Measured 2026-09-26 on engine v0.21.8: hidden files (`.x/V1.sql`, `.V1.sql`)
|
||||
are listed and judged; a symlinked directory is listed as a plain entry, so it
|
||||
is refused, not followed.
|
||||
|
||||
`--block-destructive=false` only lets `requires_approval` through. A change the
|
||||
tenant's policy `blocked` is not the pipeline's to waive.
|
||||
|
||||
A Jenkins build that holds no IntegraCI token (a pull-request build never does)
|
||||
renders the stage as a visible "DB migration lint NOT RUN" instead of failing;
|
||||
the governed apply judges every changeset again.
|
||||
|
||||
### `apply`
|
||||
|
||||
Judges the migrations the same way, refuses what the policy refuses, then runs
|
||||
the tool against `--db-url` (a secret, never on the command line).
|
||||
|
||||
The tool sees **only `dir`**, mounted alone with an empty working directory, so
|
||||
a `liquibase.properties` or flyway config in the repo cannot point it at SQL
|
||||
nobody judged. Liquibase runs each judged `.sql` file as its own formatted-SQL
|
||||
changelog, ordered with numbers compared as numbers (`V2` before `V10`); flyway
|
||||
runs with `-placeholderReplacement=false`.
|
||||
|
||||
**Breaking for anyone who wired `apply` by hand** (no generated pipeline calls
|
||||
it): the repo's `liquibase.properties`, `flyway.conf`/`flyway.toml` and
|
||||
`atlas.hcl` are no longer read. That drops contexts/labels (every changeset
|
||||
runs), a custom history table or schema (the tool sees an empty history and
|
||||
re-runs everything), and a master changelog's order and file paths (Liquibase
|
||||
stores the path relative to `dir`, so changesets recorded under another path
|
||||
run again). Check a database's history table before pointing `apply` at it.
|
||||
|
||||
```sh
|
||||
dagger call apply --source . --dir migrations \
|
||||
--db-url env://DATABASE_URL --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
`applied` is read from each tool's own summary (Liquibase `Run: N` per
|
||||
changelog, Flyway `Successfully applied N migrations`, one atlas
|
||||
`-- migrating version` line per file). Before 2026-09-27 it counted flyway and
|
||||
atlas markers for every tool, so a Liquibase apply reported 0 and a Flyway one 1.
|
||||
|
||||
## Before 2026-09-26
|
||||
|
||||
The lint could not fail for `liquibase` or `flyway`: it ran `validate || true`
|
||||
(which needs a live database anyway), looked for destructive keywords in the
|
||||
tool's output (which carries no SQL), and POSTed a summary to
|
||||
`/api/v1/services/{id}/migrations`, a route the API never served.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
dagger develop # regenerate the gitignored SDK bindings
|
||||
go test ./... # verdict/: HTTP contract, decisions, file split, applied count;
|
||||
# engine/: adapter argv, capabilities, the capabilities.json contract
|
||||
```
|
||||
|
||||
`apps/api/tests/test_dagger_db_migration_lint_contract.py` checks the other
|
||||
side: the route and request fields exist in the API, and every CI template
|
||||
passes an API URL and a token. `test_dagger_db_migration_tools_match_the_presets.py`
|
||||
checks that `--tool` accepts exactly the tools the CI presets offer, and
|
||||
`test_db_engine_adapters_match_the_module.py` that the API's adapter registry
|
||||
matches `engine/capabilities.json` and that `dagger.json` includes `engine/`.
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "db-migration",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./engine/**",
|
||||
"./verdict/**"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"atlas": {
|
||||
"dialects": ["mysql", "postgres"],
|
||||
"rollback": false,
|
||||
"drift": false,
|
||||
"snapshot": false,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": true,
|
||||
"checksum": "directory",
|
||||
"online_change": []
|
||||
},
|
||||
"flyway": {
|
||||
"dialects": ["mysql", "oracle", "postgres", "tsql"],
|
||||
"rollback": false,
|
||||
"drift": false,
|
||||
"snapshot": false,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": false,
|
||||
"checksum": "file",
|
||||
"online_change": []
|
||||
},
|
||||
"liquibase": {
|
||||
"dialects": ["mysql", "oracle", "postgres", "tsql"],
|
||||
"rollback": true,
|
||||
"drift": true,
|
||||
"snapshot": true,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": false,
|
||||
"checksum": "changeset",
|
||||
"online_change": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package engine is the migration-engine adapter interface of the db-migration
|
||||
// module (ADR-0070 §1): DBV judges, an adapter only says how its tool runs.
|
||||
//
|
||||
// An adapter builds COMMANDS — the image and the exact argv to exec in it — and
|
||||
// declares what it can do. It never sees a secret: the database URLs reach the
|
||||
// container as environment variables ($DATABASE_URL, $REFERENCE_URL) that
|
||||
// main.go binds as Dagger secrets, and the scripts read them from there. It does
|
||||
// not decide what runs either: the files it is handed are the judged ones, and
|
||||
// the module mounts them alone at /migrations (or /reference).
|
||||
//
|
||||
// Phase 1 (#2135, 2026-10-11) moved the module's existing tool calls behind
|
||||
// this interface with no behaviour change: every argv is byte-identical to the
|
||||
// one main.go built inline before, and engine_test.go pins each of them. The
|
||||
// API mirrors the capabilities in app/platform/services/db_engine_adapters.py;
|
||||
// both sides are compared against capabilities.json, so neither parses the
|
||||
// other's language.
|
||||
package engine
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// ErrUnsupported is returned for an operation the adapter does not drive.
|
||||
var ErrUnsupported = errors.New("not supported by this migration tool")
|
||||
|
||||
// DefaultTool is the adapter the platform's grants are written for: a granted
|
||||
// batch, a drift reference and a snapshot are Liquibase formatted SQL today.
|
||||
// ADR-0070 §2 makes re-choosing the default a configuration change; this is
|
||||
// that configuration.
|
||||
const DefaultTool = "liquibase"
|
||||
|
||||
// Capabilities are what an adapter DRIVES in this module today — not what its
|
||||
// tool could do in principle. A capability declared here is one a caller can
|
||||
// use without the call failing with ErrUnsupported.
|
||||
type Capabilities struct {
|
||||
// Which of the DBV engine's four dialects (postgres, mysql, oracle, tsql)
|
||||
// the module accepts this tool for (verdict.CheckTool), sorted. Accepted,
|
||||
// not tested per dialect: per-dialect tests are ADR-0070 phase 2.
|
||||
Dialects []string `json:"dialects"`
|
||||
// Rollback of the last n changesets of a granted changelog.
|
||||
Rollback bool `json:"rollback"`
|
||||
// Drift: build the granted changelog into a reference and diff the live
|
||||
// database against it.
|
||||
Drift bool `json:"drift"`
|
||||
// Snapshot of the live schema as JSON.
|
||||
Snapshot bool `json:"snapshot"`
|
||||
// DryRunSQL: render the SQL an apply would run without running it.
|
||||
DryRunSQL bool `json:"dry_run_sql"`
|
||||
// NativeLint: the tool's own lint runs after the DBV verdict, as an
|
||||
// advisory signal (ADR-0070 §3), never as the verdict.
|
||||
NativeLint bool `json:"native_lint"`
|
||||
// Checksum is what the tool's history is keyed and checksummed by:
|
||||
// "changeset" (id+author+file), "file" (versioned script) or "directory"
|
||||
// (a sum file over the whole directory).
|
||||
Checksum string `json:"checksum"`
|
||||
// OnlineChange lists online schema-change tools the adapter drives
|
||||
// (pgroll, gh-ost, ...). None yet (ADR-0070 §5, 6–12 months).
|
||||
OnlineChange []string `json:"online_change"`
|
||||
}
|
||||
|
||||
// Command is one tool invocation: the image to run and the argv to exec in it.
|
||||
type Command struct {
|
||||
Image string
|
||||
Args []string
|
||||
}
|
||||
|
||||
// Adapter runs one migration tool.
|
||||
type Adapter interface {
|
||||
// Name is the --tool value that selects this adapter.
|
||||
Name() string
|
||||
Capabilities() Capabilities
|
||||
// Apply runs the judged files, in this order, against $DATABASE_URL.
|
||||
Apply(files []string) (Command, error)
|
||||
// Rollback undoes the last n changesets of file against $DATABASE_URL.
|
||||
Rollback(file string, n int) (Command, error)
|
||||
// Drift builds file into $REFERENCE_URL and diffs $DATABASE_URL against it.
|
||||
Drift(file string) (Command, error)
|
||||
// Snapshot prints the schema of $DATABASE_URL.
|
||||
Snapshot() (Command, error)
|
||||
}
|
||||
|
||||
// Images are the pinned images the adapters run. They stay declared in
|
||||
// main.go, where tools/ci/check-liquibase-pins.py and Renovate look for them.
|
||||
type Images struct {
|
||||
Liquibase string
|
||||
Flyway string
|
||||
Atlas string
|
||||
}
|
||||
|
||||
// Registry is the set of adapters, keyed by tool name.
|
||||
type Registry map[string]Adapter
|
||||
|
||||
// New returns every adapter the module has, running the given images.
|
||||
func New(images Images) Registry {
|
||||
r := Registry{}
|
||||
for _, a := range []Adapter{
|
||||
Liquibase{Image: images.Liquibase},
|
||||
Flyway{Image: images.Flyway},
|
||||
Atlas{Image: images.Atlas},
|
||||
} {
|
||||
r[a.Name()] = a
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// For returns the adapter for tool. An unknown tool is an error, never another
|
||||
// tool: until 2026-09-27 an unknown --tool fell through to atlas.
|
||||
func (r Registry) For(tool string) (Adapter, error) {
|
||||
a, ok := r[tool]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("--tool=%q is not a migration tool this module runs", tool)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Names lists the registered tools, sorted.
|
||||
func (r Registry) Names() []string {
|
||||
out := make([]string, 0, len(r))
|
||||
for name := range r {
|
||||
out = append(out, name)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func unsupported(tool, op string) error {
|
||||
return fmt.Errorf("%s %s: %w", tool, op, ErrUnsupported)
|
||||
}
|
||||
|
||||
// Liquibase is the default adapter (ADR-0070 §2: pinned below 5.0).
|
||||
type Liquibase struct{ Image string }
|
||||
|
||||
func (Liquibase) Name() string { return "liquibase" }
|
||||
|
||||
func (Liquibase) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "oracle", "postgres", "tsql"},
|
||||
Rollback: true,
|
||||
Drift: true,
|
||||
Snapshot: true,
|
||||
Checksum: "changeset",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
// Apply runs each judged file as its own formatted-SQL changelog, in order:
|
||||
// there is no master changelog to point it at, and that is exactly the set the
|
||||
// engine saw. Files are positional arguments, never spliced into the script.
|
||||
func (l Liquibase) Apply(files []string) (Command, error) {
|
||||
return Command{Image: l.Image, Args: append([]string{"sh", "-c",
|
||||
`for f in "$@"; do liquibase --searchPath=/migrations --changelog-file="$f" --url="$DATABASE_URL" update || exit 1; done`,
|
||||
"sh"}, files...)}, nil
|
||||
}
|
||||
|
||||
// Rollback undoes the last n changesets with Liquibase's rollback-count.
|
||||
func (l Liquibase) Rollback(file string, n int) (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --searchPath=/migrations --changelog-file="$1" --url="$DATABASE_URL" rollback-count --count="$2"`,
|
||||
"sh", file, fmt.Sprintf("%d", n)}}, nil
|
||||
}
|
||||
|
||||
// Drift updates the empty reference database from the granted changelog
|
||||
// (mounted at /reference), then diffs the live database against it.
|
||||
func (l Liquibase) Drift(file string) (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --searchPath=/reference --changelog-file="$1" --url="$REFERENCE_URL" update >/dev/null && ` +
|
||||
`liquibase --url="$DATABASE_URL" --referenceUrl="$REFERENCE_URL" diff`,
|
||||
"sh", file}}, nil
|
||||
}
|
||||
|
||||
func (l Liquibase) Snapshot() (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --url="$DATABASE_URL" snapshot --snapshotFormat=json`}}, nil
|
||||
}
|
||||
|
||||
// Flyway applies a directory of versioned scripts. Placeholder replacement is
|
||||
// off: a ${...} in judged SQL must reach the database as written, not be
|
||||
// rewritten after the verdict.
|
||||
type Flyway struct{ Image string }
|
||||
|
||||
func (Flyway) Name() string { return "flyway" }
|
||||
|
||||
func (Flyway) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "oracle", "postgres", "tsql"},
|
||||
Checksum: "file",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (f Flyway) Apply([]string) (Command, error) {
|
||||
return Command{Image: f.Image, Args: []string{"sh", "-c",
|
||||
`flyway -url="$DATABASE_URL" -locations=filesystem:/migrations -placeholderReplacement=false migrate`}}, nil
|
||||
}
|
||||
|
||||
func (Flyway) Rollback(string, int) (Command, error) {
|
||||
return Command{}, unsupported("flyway", "rollback")
|
||||
}
|
||||
func (Flyway) Drift(string) (Command, error) { return Command{}, unsupported("flyway", "drift") }
|
||||
func (Flyway) Snapshot() (Command, error) { return Command{}, unsupported("flyway", "snapshot") }
|
||||
|
||||
// Atlas is the Community Edition (Apache 2.0): PostgreSQL and MySQL only. Its
|
||||
// own lint (`atlas migrate lint`) runs in main.go after the DBV verdict.
|
||||
type Atlas struct{ Image string }
|
||||
|
||||
func (Atlas) Name() string { return "atlas" }
|
||||
|
||||
func (Atlas) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "postgres"},
|
||||
NativeLint: true,
|
||||
Checksum: "directory",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (a Atlas) Apply([]string) (Command, error) {
|
||||
return Command{Image: a.Image, Args: []string{"sh", "-c",
|
||||
`atlas migrate apply --dir file:///migrations --url "$DATABASE_URL"`}}, nil
|
||||
}
|
||||
|
||||
func (Atlas) Rollback(string, int) (Command, error) {
|
||||
return Command{}, unsupported("atlas", "rollback")
|
||||
}
|
||||
func (Atlas) Drift(string) (Command, error) { return Command{}, unsupported("atlas", "drift") }
|
||||
func (Atlas) Snapshot() (Command, error) { return Command{}, unsupported("atlas", "snapshot") }
|
||||
@@ -0,0 +1,205 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"dagger/db-migration/verdict"
|
||||
)
|
||||
|
||||
var images = Images{Liquibase: "lb-image", Flyway: "fw-image", Atlas: "at-image"}
|
||||
|
||||
// The argv main.go built inline before #2135, copied verbatim from
|
||||
// origin/main 13a3918e2. Phase 1 promised no behaviour change; this is the
|
||||
// proof. Changing a script here is a behaviour change: review it as one.
|
||||
//
|
||||
// MUTATION-CHECK: drop `|| exit 1` from the Liquibase apply loop, or
|
||||
// `-placeholderReplacement=false` from Flyway → FAILS.
|
||||
func TestCommandsAreTheOnesTheModuleRanBefore(t *testing.T) {
|
||||
r := New(images)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
got func() (Command, error)
|
||||
want Command
|
||||
}{
|
||||
{"liquibase apply", func() (Command, error) { return r["liquibase"].Apply([]string{"a.sql", "b c.sql"}) },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`for f in "$@"; do liquibase --searchPath=/migrations --changelog-file="$f" --url="$DATABASE_URL" update || exit 1; done`,
|
||||
"sh", "a.sql", "b c.sql"}}},
|
||||
{"liquibase rollback", func() (Command, error) { return r["liquibase"].Rollback("granted.sql", 3) },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --searchPath=/migrations --changelog-file="$1" --url="$DATABASE_URL" rollback-count --count="$2"`,
|
||||
"sh", "granted.sql", "3"}}},
|
||||
{"liquibase drift", func() (Command, error) { return r["liquibase"].Drift("granted.sql") },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --searchPath=/reference --changelog-file="$1" --url="$REFERENCE_URL" update >/dev/null && ` +
|
||||
`liquibase --url="$DATABASE_URL" --referenceUrl="$REFERENCE_URL" diff`,
|
||||
"sh", "granted.sql"}}},
|
||||
{"liquibase snapshot", func() (Command, error) { return r["liquibase"].Snapshot() },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --url="$DATABASE_URL" snapshot --snapshotFormat=json`}}},
|
||||
{"flyway apply", func() (Command, error) { return r["flyway"].Apply([]string{"V1__x.sql"}) },
|
||||
Command{"fw-image", []string{"sh", "-c",
|
||||
`flyway -url="$DATABASE_URL" -locations=filesystem:/migrations -placeholderReplacement=false migrate`}}},
|
||||
{"atlas apply", func() (Command, error) { return r["atlas"].Apply([]string{"1_x.sql"}) },
|
||||
Command{"at-image", []string{"sh", "-c",
|
||||
`atlas migrate apply --dir file:///migrations --url "$DATABASE_URL"`}}},
|
||||
} {
|
||||
got, err := tc.got()
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", tc.name, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s:\n got %q\nwant %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file name is an argument, never part of the script: a name carrying shell
|
||||
// syntax must not reach `sh -c`'s script string.
|
||||
func TestFileNamesNeverReachTheScript(t *testing.T) {
|
||||
evil := `x.sql"; touch /pwned; echo "`
|
||||
l := New(images)["liquibase"]
|
||||
for name, cmd := range map[string]func() (Command, error){
|
||||
"apply": func() (Command, error) { return l.Apply([]string{evil}) },
|
||||
"rollback": func() (Command, error) { return l.Rollback(evil, 1) },
|
||||
"drift": func() (Command, error) { return l.Drift(evil) },
|
||||
} {
|
||||
c, err := cmd()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if strings.Contains(c.Args[2], "pwned") {
|
||||
t.Errorf("%s: the file name reached the script: %q", name, c.Args[2])
|
||||
}
|
||||
if c.Args[3] != "sh" || c.Args[4] != evil {
|
||||
t.Errorf("%s: the file name is not the first positional argument: %q", name, c.Args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An operation an adapter does not declare fails with ErrUnsupported — it
|
||||
// never runs something else — and one it declares never does.
|
||||
func TestUnsupportedOperationsMatchTheCapabilities(t *testing.T) {
|
||||
for _, a := range New(images) {
|
||||
caps := a.Capabilities()
|
||||
for op, c := range map[string]struct {
|
||||
declared bool
|
||||
call func() (Command, error)
|
||||
}{
|
||||
"rollback": {caps.Rollback, func() (Command, error) { return a.Rollback("f.sql", 1) }},
|
||||
"drift": {caps.Drift, func() (Command, error) { return a.Drift("f.sql") }},
|
||||
"snapshot": {caps.Snapshot, func() (Command, error) { return a.Snapshot() }},
|
||||
} {
|
||||
cmd, err := c.call()
|
||||
if c.declared && err != nil {
|
||||
t.Errorf("%s declares %s but it fails: %v", a.Name(), op, err)
|
||||
}
|
||||
if !c.declared && (!errors.Is(err, ErrUnsupported) || cmd.Image != "" || cmd.Args != nil) {
|
||||
t.Errorf("%s does not declare %s, got %q, %v", a.Name(), op, cmd, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.Apply([]string{"f.sql"}); err != nil {
|
||||
t.Errorf("%s apply: %v", a.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every adapter runs its own pinned image, never another tool's.
|
||||
func TestEachAdapterRunsItsOwnImage(t *testing.T) {
|
||||
want := map[string]string{"liquibase": "lb-image", "flyway": "fw-image", "atlas": "at-image"}
|
||||
for name, a := range New(images) {
|
||||
c, _ := a.Apply([]string{"f.sql"})
|
||||
if c.Image != want[name] {
|
||||
t.Errorf("%s runs %q, want %q", name, c.Image, want[name])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --tool selects exactly one adapter; an unknown or misspelt one is an error,
|
||||
// not another tool (it fell through to atlas until 2026-09-27).
|
||||
func TestForRefusesAnUnknownTool(t *testing.T) {
|
||||
r := New(images)
|
||||
for _, tool := range []string{"liquibase", "flyway", "atlas"} {
|
||||
a, err := r.For(tool)
|
||||
if err != nil || a.Name() != tool {
|
||||
t.Errorf("For(%q) = %v, %v", tool, a, err)
|
||||
}
|
||||
}
|
||||
for _, tool := range []string{"", "none", "Liquibase", "liquibse", "sqitch"} {
|
||||
if a, err := r.For(tool); err == nil {
|
||||
t.Errorf("For(%q) = %v, want an error", tool, a.Name())
|
||||
}
|
||||
}
|
||||
if r["liquibase"] == nil || DefaultTool != "liquibase" {
|
||||
t.Errorf("the default adapter is %q and must be registered", DefaultTool)
|
||||
}
|
||||
}
|
||||
|
||||
// The adapters are exactly the tools --tool takes, minus "none" (which opts
|
||||
// out of governance and runs nothing).
|
||||
func TestAdaptersAreTheModulesTools(t *testing.T) {
|
||||
var tools []string
|
||||
for tool := range verdict.MigrationTools {
|
||||
if tool != "none" {
|
||||
tools = append(tools, tool)
|
||||
}
|
||||
}
|
||||
sort.Strings(tools)
|
||||
if got := New(images).Names(); !reflect.DeepEqual(got, tools) {
|
||||
t.Errorf("adapters %v, but --tool takes %v", got, tools)
|
||||
}
|
||||
}
|
||||
|
||||
// The declared dialects are the ones verdict.CheckTool accepts the tool for —
|
||||
// a declaration that disagreed would advertise a tool the module then refuses,
|
||||
// or hide one it runs.
|
||||
func TestDeclaredDialectsAreTheOnesCheckToolAccepts(t *testing.T) {
|
||||
for _, a := range New(images) {
|
||||
declared := map[string]bool{}
|
||||
for _, d := range a.Capabilities().Dialects {
|
||||
declared[d] = true
|
||||
}
|
||||
for _, d := range []string{"postgres", "mysql", "oracle", "tsql"} {
|
||||
accepted := verdict.CheckTool(a.Name(), d) == nil
|
||||
if accepted != declared[d] {
|
||||
t.Errorf("%s: dialect %s declared=%v, CheckTool accepts=%v", a.Name(), d, declared[d], accepted)
|
||||
}
|
||||
}
|
||||
if !sort.StringsAreSorted(a.Capabilities().Dialects) {
|
||||
t.Errorf("%s: dialects not sorted: %v", a.Name(), a.Capabilities().Dialects)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// capabilities.json is the contract the API's registry
|
||||
// (app/platform/services/db_engine_adapters.py) is tested against too.
|
||||
//
|
||||
// MUTATION-CHECK: flip Liquibase Rollback to false, or add an adapter without
|
||||
// a JSON entry → FAILS here; edit the JSON only → FAILS here and in the API test.
|
||||
func TestCapabilitiesMatchTheContract(t *testing.T) {
|
||||
raw, err := os.ReadFile("capabilities.json")
|
||||
if err != nil {
|
||||
t.Fatalf("capabilities.json is the cross-language contract and must exist: %v", err)
|
||||
}
|
||||
var contract map[string]Capabilities
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&contract); err != nil {
|
||||
t.Fatalf("capabilities.json: %v", err)
|
||||
}
|
||||
got := map[string]Capabilities{}
|
||||
for name, a := range New(images) {
|
||||
got[name] = a.Capabilities()
|
||||
}
|
||||
if !reflect.DeepEqual(got, contract) {
|
||||
t.Errorf("adapters declare\n %+v\nbut capabilities.json says\n %+v", got, contract)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
module dagger/db-migration
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/Khan/genqlient v0.8.1
|
||||
github.com/dagger/otel-go v1.43.0
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59
|
||||
github.com/vektah/gqlparser/v2 v2.5.32
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.89 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/grpc v1.79.3 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/log => go.opentelemetry.io/otel/log v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/sdk/log => go.opentelemetry.io/otel/sdk/log v0.16.0
|
||||
@@ -0,0 +1,97 @@
|
||||
github.com/99designs/gqlgen v0.17.89 h1:KzEcxPiMgQoMw3m/E85atUEHyZyt0PbAflMia5Kw8z8=
|
||||
github.com/99designs/gqlgen v0.17.89/go.mod h1:GFqruTVGB7ZTdrf1uzOagpXbY7DrEt1pIxnTdhIbWvQ=
|
||||
github.com/Khan/genqlient v0.8.1 h1:wtOCc8N9rNynRLXN3k3CnfzheCUNKBcvXmVv5zt6WCs=
|
||||
github.com/Khan/genqlient v0.8.1/go.mod h1:R2G6DzjBvCbhjsEajfRjbWdVglSH/73kSivC9TLWVjU=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/dagger/otel-go v1.43.0 h1:AYCnAamWmxtSxigWPTgC+8EWqiWPcDZEegh8y05gdJ8=
|
||||
github.com/dagger/otel-go v1.43.0/go.mod h1:83CTuXi70zcx1kaym5buqmb7RNzg1E9dEiQSFyLbLdU=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 h1:g6vfdGRyz6fAjfHz5FyYPZgHy8qcQ31fHrBl1iCOzxw=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59/go.mod h1:jsdUJeYzcbyK1j/EqMGPrQgNYxl/Zfg06vvM9C/xXxs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE=
|
||||
github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32 h1:k9QPJd4sEDTL+qB4ncPLflqTJ3MmjB9SrVzJrawpFSc=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0 h1:ZVg+kCXxd9LtAaQNKBxAvJ5NpMf7LpvEr4MIZqb0TMQ=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0/go.mod h1:hh0tMeZ75CCXrHd9OXRYxTlCAdxcXioWHFIpYw2rZu8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0 h1:djrxvDxAe44mJUrKataUbOhCKhR3F8QCyWucO16hTQs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0/go.mod h1:dt3nxpQEiSoKvfTVxp3TUg5fHPLhKtbcnN3Z1I1ePD0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 h1:VO3BL6OZXRQ1yQc8W6EVfJzINeJ35BkiHx4MYfoQf44=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0/go.mod h1:qRDnJ2nv3CQXMK2HUd9K9VtvedsPAce3S+/4LZHjX/s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 h1:MMrOAN8H1FrvDyq9UJ4lu5/+ss49Qgfgb7Zpm0m8ABo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0/go.mod h1:Na+2NNASJtF+uT4NxDe0G+NQb+bUgdPDfwxY/6JmS/c=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 h1:mq/Qcf28TWz719lE3/hMB4KkyDuLJIvgJnFGcd0kEUI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0/go.mod h1:yk5LXEYhsL2htyDNJbEq7fWzNEigeEdV5xBF/Y+kAv0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/log v0.16.0 h1:DeuBPqCi6pQwtCK0pO4fvMB5eBq6sNxEnuTs88pjsN4=
|
||||
go.opentelemetry.io/otel/log v0.16.0/go.mod h1:rWsmqNVTLIA8UnwYVOItjyEZDbKIkMxdQunsIhpUMes=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0 h1:e/b4bdlQwC5fnGtG3dlXUrNOnP7c8YLVSpSfEBIkTnI=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0/go.mod h1:JKfP3T6ycy7QEuv3Hj8oKDy7KItrEkus8XJE6EoSzw4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0 h1:/XVkpZ41rVRTP4DfMgYv1nEtNmf65XPPyAdqV90TMy4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0/go.mod h1:iOOPgQr5MY9oac/F5W86mXdeyWZGleIx3uXO98X2R6Y=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,722 @@
|
||||
// Package main implements the IntegraCI db-migration Dagger module.
|
||||
//
|
||||
// Judges a service's migration SQL with IntegraCI's DB-change engine (the DBV
|
||||
// policy engine behind the tenant's own policy, POST /api/v1/db-changes/analyze)
|
||||
// and applies migrations with the tenant's own tool: liquibase (default — the
|
||||
// engine the platform runs for its own database), flyway, or atlas. Which tool
|
||||
// a tenant uses is the tenant's choice; atlas here is one of those choices, not
|
||||
// the platform's (the platform retired atlas for its own schema in 2026-09).
|
||||
//
|
||||
// Verified 2026-09-26: `dagger functions` builds this module on engine v0.21.8.
|
||||
// Before that date it was marked an unverified scaffold, and its lint could not
|
||||
// fail for liquibase or flyway: `validate || true` swallowed every error, the
|
||||
// destructive check grepped the tool's output (which carries no SQL), and the
|
||||
// summary was POSTed to /services/{id}/migrations, which the API never served.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call lint --source . --dir migrations --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
// dagger call apply --source . --dir migrations --db-url env://DATABASE_URL --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"dagger/db-migration/engine"
|
||||
"dagger/db-migration/internal/dagger"
|
||||
"dagger/db-migration/verdict"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DbMigration is the IntegraCI database migration module.
|
||||
type DbMigration struct{}
|
||||
|
||||
// The images this module runs, pinned by tag AND digest (checked 2026-09-27):
|
||||
// a bare tag is a question to the registry on every run, and an air-gapped
|
||||
// mirror can only serve what it was given.
|
||||
const (
|
||||
// The Liquibase version the platform itself runs (apps/api/Dockerfile).
|
||||
// Its JDBC drivers: postgresql, mssql-jdbc (SQL Server), ojdbc8 (Oracle),
|
||||
// mariadb-java-client (MariaDB, and MySQL through a jdbc:mariadb: URL),
|
||||
// jcc (DB2), jaybird (Firebird), snowflake, sqlite, h2, hsqldb. Not
|
||||
// MySQL Connector/J: a jdbc:mysql: URL finds no driver.
|
||||
liquibaseImage = "liquibase/liquibase:4.31.1-alpine@sha256:d7e17e2d234835fe132c4c46ec1af7d7d490710e882db162abb15593c4948fe8"
|
||||
flywayImage = "flyway/flyway:10.22.0-alpine@sha256:94a81ca7db9a9f24fd8acd7463fa4560cb8f66aae2aa64485c27eb296f5851cf"
|
||||
// Atlas Community Edition (Apache 2.0). The standard arigaio/atlas image
|
||||
// is licensed under the proprietary Atlas MSA, and this module used it until
|
||||
// 2026-09-27. Community supports PostgreSQL, MySQL, MariaDB and SQLite —
|
||||
// not SQL Server or Oracle (https://atlasgo.io/community-edition).
|
||||
atlasImage = "arigaio/atlas:1.3.3-community-alpine@sha256:9d3161bf3bf2b0ce6d0f6b63471d0a341e664e87cccec90a12139ea2cba18575"
|
||||
// The throwaway database `atlas migrate lint` replays migrations on.
|
||||
atlasDevPostgresImage = "postgres:16.13-alpine@sha256:4e6e670bb069649261c9c18031f0aded7bb249a5b6664ddec29c013a89310d50"
|
||||
)
|
||||
|
||||
// engines are the migration-engine adapters (ADR-0070 §1), running the images
|
||||
// pinned above. An adapter builds the command; this file binds the secrets and
|
||||
// mounts only the judged files.
|
||||
var engines = engine.New(engine.Images{Liquibase: liquibaseImage, Flyway: flywayImage, Atlas: atlasImage})
|
||||
|
||||
// defaultAdapter is the adapter the platform's grants are written for, if it
|
||||
// drives the operation op. Asked before a grant is requested, so a default
|
||||
// that cannot drive it fails without spending a grant nobody reports.
|
||||
func defaultAdapter(drives func(engine.Capabilities) bool, op string) (engine.Adapter, error) {
|
||||
adapter, err := engines.For(engine.DefaultTool)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !drives(adapter.Capabilities()) {
|
||||
return nil, fmt.Errorf("%s %s: %w", adapter.Name(), op, engine.ErrUnsupported)
|
||||
}
|
||||
return adapter, nil
|
||||
}
|
||||
|
||||
// LintReport summarises a migration lint run.
|
||||
type LintReport struct {
|
||||
Tool string `json:"tool"`
|
||||
Dir string `json:"dir"`
|
||||
// Destructive and security-sensitive statements across all files.
|
||||
DestructiveFound int `json:"destructive_found"`
|
||||
DestructiveList []string `json:"destructive_list"`
|
||||
// The engine's verdict per migration file.
|
||||
Verdicts []FileVerdict `json:"verdicts"`
|
||||
// Output of the tool's own lint (atlas only; kept when it fails too).
|
||||
Report string `json:"report"`
|
||||
Skipped bool `json:"skipped,omitempty"`
|
||||
Pass bool `json:"pass"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// ApplyResult contains the output of a migration apply run.
|
||||
type ApplyResult struct {
|
||||
Tool string `json:"tool"`
|
||||
Dir string `json:"dir"`
|
||||
Applied int `json:"applied"`
|
||||
Pending int `json:"pending"`
|
||||
Report string `json:"report"`
|
||||
BlockedReason string `json:"blocked_reason,omitempty"`
|
||||
Skipped bool `json:"skipped,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Lint judges every migration file with IntegraCI's DB-change engine and fails
|
||||
// on a change the tenant's policy blocks (or one needing approval, while
|
||||
// blocking is on). For atlas it also runs `atlas migrate lint`, and fails when
|
||||
// that does.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Lint(
|
||||
ctx context.Context,
|
||||
// Source directory containing migrations
|
||||
source *dagger.Directory,
|
||||
// Migrations directory relative to source
|
||||
// +optional
|
||||
// +default="migrations"
|
||||
dir string,
|
||||
// Dev database URL atlas replays the migrations on — a secret, since a
|
||||
// DSN carries a password. Unset: a throwaway PostgreSQL is started for
|
||||
// this run (dialect postgres). The old default, docker://postgres/16/dev,
|
||||
// needs a Docker CLI inside the atlas container and never worked here.
|
||||
// +optional
|
||||
devURL *dagger.Secret,
|
||||
// Migration tool: liquibase | atlas | flyway | none
|
||||
// +optional
|
||||
// +default="liquibase"
|
||||
tool string,
|
||||
// Also fail on a change that needs approval (a blocked change always fails)
|
||||
// +optional
|
||||
// +default=true
|
||||
blockDestructive bool,
|
||||
// IntegraCI API URL — the engine that judges the SQL
|
||||
// +optional
|
||||
apiURL string,
|
||||
// IntegraCI API token
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
||||
// judges in the engines of the service's databases when --service-id is
|
||||
// given, and as PostgreSQL otherwise
|
||||
// +optional
|
||||
dialect string,
|
||||
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
||||
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
||||
// that engine's dialect, and one it has no rules for comes back unjudged,
|
||||
// needing an approver (GET /api/v1/db-engines)
|
||||
// +optional
|
||||
engine string,
|
||||
// Tenant environment id whose DB-change policy (and stage) applies
|
||||
// +optional
|
||||
environmentID string,
|
||||
// The service these migrations belong to. With --version, the platform
|
||||
// records its verdict for that release, which its deploy gate can require
|
||||
// +optional
|
||||
serviceID string,
|
||||
// The version being built: the image tag the deploy will carry
|
||||
// +optional
|
||||
version string,
|
||||
) (*LintReport, error) {
|
||||
report := &LintReport{
|
||||
Tool: tool,
|
||||
Dir: dir,
|
||||
DestructiveList: []string{},
|
||||
Verdicts: []FileVerdict{},
|
||||
Pass: true,
|
||||
}
|
||||
|
||||
target, err := verdict.ResolveTarget(engine, dialect)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// "none" disables DB migration governance — no-op skip.
|
||||
if tool == "none" {
|
||||
report.Skipped = true
|
||||
return report, nil
|
||||
}
|
||||
|
||||
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The policy decides first. atlas lint REPLAYS the files on its dev
|
||||
// database, so a file the policy refuses must never reach it (review,
|
||||
// 2026-09-27: a blocked `COPY … TO PROGRAM` would otherwise run there).
|
||||
refused, err := verdict.Refused(judged(report), blockDestructive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(refused) > 0 {
|
||||
report.Pass = false
|
||||
return report, fmt.Errorf("lint: %d migration file(s) refused by the DB-change policy: %s",
|
||||
len(refused), strings.Join(refused, "; "))
|
||||
}
|
||||
|
||||
if tool == "atlas" {
|
||||
rawOut, failed, err := m.atlasLint(ctx, source.Directory(dir), devURL, target.ToolDialect())
|
||||
report.Report = rawOut
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("atlas lint could not run: %w", err)
|
||||
}
|
||||
if failed {
|
||||
report.Pass = false
|
||||
return report, fmt.Errorf("atlas migrate lint reported errors:\n%s", rawOut)
|
||||
}
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Apply runs the migrations against the target database. It judges them first
|
||||
// and refuses what the DB-change policy refuses: always a blocked change, and
|
||||
// one that needs approval unless blockDestructive is off. The tool sees ONLY
|
||||
// the judged directory — not the repo root, where a liquibase.properties or a
|
||||
// flyway config could point it at SQL nobody judged.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Apply(
|
||||
ctx context.Context,
|
||||
// Source directory containing migrations
|
||||
source *dagger.Directory,
|
||||
// Migrations directory relative to source
|
||||
// +optional
|
||||
// +default="migrations"
|
||||
dir string,
|
||||
// Target database URL (DATABASE_URL) to apply migrations to
|
||||
// +optional
|
||||
dbURL *dagger.Secret,
|
||||
// Migration tool: liquibase | atlas | flyway | none
|
||||
// +optional
|
||||
// +default="liquibase"
|
||||
tool string,
|
||||
// Also refuse a change that needs approval (a blocked change is always refused)
|
||||
// +optional
|
||||
// +default=true
|
||||
blockDestructive bool,
|
||||
// IntegraCI API URL — the engine that judges the SQL
|
||||
// +optional
|
||||
apiURL string,
|
||||
// IntegraCI API token
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
||||
// judges in the engines of the service's databases when --service-id is
|
||||
// given, and as PostgreSQL otherwise
|
||||
// +optional
|
||||
dialect string,
|
||||
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
||||
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
||||
// that engine's dialect, and one it has no rules for comes back unjudged,
|
||||
// needing an approver (GET /api/v1/db-engines)
|
||||
// +optional
|
||||
engine string,
|
||||
// Tenant environment id whose DB-change policy (and stage) applies
|
||||
// +optional
|
||||
environmentID string,
|
||||
// The service these migrations belong to (with --version; see lint)
|
||||
// +optional
|
||||
serviceID string,
|
||||
// The version being built: the image tag the deploy will carry
|
||||
// +optional
|
||||
version string,
|
||||
) (*ApplyResult, error) {
|
||||
result := &ApplyResult{Tool: tool, Dir: dir}
|
||||
target, err := verdict.ResolveTarget(engine, dialect)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// "none" disables DB migration governance — no-op skip.
|
||||
if tool == "none" {
|
||||
result.Skipped = true
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Judge before touching the target DB — always.
|
||||
lint := &LintReport{DestructiveList: []string{}, Verdicts: []FileVerdict{}}
|
||||
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, lint); err != nil {
|
||||
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
||||
}
|
||||
refused, err := verdict.Refused(judged(lint), blockDestructive)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
||||
}
|
||||
if len(refused) > 0 {
|
||||
result.BlockedReason = strings.Join(refused, "; ")
|
||||
return result, fmt.Errorf("apply blocked: %s", result.BlockedReason)
|
||||
}
|
||||
files := make([]string, 0, len(lint.Verdicts))
|
||||
for _, v := range lint.Verdicts {
|
||||
files = append(files, v.File)
|
||||
}
|
||||
|
||||
rawOut, err := m.runApply(ctx, source.Directory(dir), tool, dbURL, files)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s apply failed: %w", tool, err)
|
||||
}
|
||||
result.Report = rawOut
|
||||
result.Applied = verdict.AppliedCount(tool, rawOut)
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Execute runs a batch the platform granted to this executor (plan §P5,
|
||||
// integraci_db_apply_execution = "delegated"). It asks for a single-use grant
|
||||
// for the dispatched batch digest, fetches the granted changelog, refuses it
|
||||
// unless its SHA-256 is the one the grant names, runs it with Liquibase against
|
||||
// --db-url, and reports the outcome once, so the platform's ledger records what
|
||||
// ran. The platform never connects to the database.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Execute(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id the batch was dispatched for
|
||||
instanceID string,
|
||||
// Batch digest (changeset_sha256) from the dispatched apply or rollback
|
||||
digest string,
|
||||
// Target database URL — a secret, never on the command line
|
||||
dbURL *dagger.Secret,
|
||||
// Roll back the last N applied changesets instead of applying (the count
|
||||
// the dispatched rollback named); 0 applies
|
||||
// +optional
|
||||
// +default=0
|
||||
rollbackCount int,
|
||||
) (*ApplyResult, error) {
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestGrant(ctx, client, apiURL, api, instanceID, digest, rollbackCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := granted.FileName()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
migrations := dag.Directory().WithNewFile(file, granted.Changelog)
|
||||
ref := "dagger-" + grant.ChangelogSHA256[:12]
|
||||
var out string
|
||||
var runErr error
|
||||
if rollbackCount > 0 {
|
||||
out, runErr = m.runRollback(ctx, migrations, file, dbURL, rollbackCount)
|
||||
} else {
|
||||
out, runErr = m.runApply(ctx, migrations, engine.DefaultTool, dbURL, []string{file})
|
||||
}
|
||||
outcome, message := "applied", "applied by the tenant's executor"
|
||||
if runErr != nil {
|
||||
outcome, message = "failed", runErr.Error()
|
||||
}
|
||||
if err := verdict.Report(ctx, client, apiURL, api, *grant, outcome, ref, message); err != nil {
|
||||
// The run happened; the ledger does not know. Say both.
|
||||
return nil, fmt.Errorf("%s, and %w", outcome, err)
|
||||
}
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("%s apply failed (reported): %w", engine.DefaultTool, runErr)
|
||||
}
|
||||
return &ApplyResult{Tool: engine.DefaultTool, Dir: "granted", Applied: len(granted.Changesets), Report: out, Success: true}, nil
|
||||
}
|
||||
|
||||
// judge sends every migration file to IntegraCI's DB-change engine and records
|
||||
// the verdicts in report. It fails closed: without an API to ask, with a
|
||||
// changelog format the engine cannot read, or with a file the API will not
|
||||
// take, nothing has judged the directory, so the step cannot pass.
|
||||
func (m *DbMigration) judge(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
dir, tool, apiURL string,
|
||||
token *dagger.Secret,
|
||||
target verdict.Target,
|
||||
environmentID, serviceID, version string,
|
||||
report *LintReport,
|
||||
) error {
|
||||
if apiURL == "" || token == nil {
|
||||
return fmt.Errorf("--api-url and --token are required: the verdict comes from IntegraCI's DB-change engine, and without it nothing judges the SQL")
|
||||
}
|
||||
migrations := source.Directory(dir)
|
||||
entries, err := migrations.Glob(ctx, "**/*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing %s: %w", dir, err)
|
||||
}
|
||||
sqlFiles, unanalysable := verdict.SplitMigrations(entries)
|
||||
if len(unanalysable) > 0 {
|
||||
return fmt.Errorf("the DB-change engine reads SQL files; it cannot judge these (changelogs, other suffixes, symlinks): %s "+
|
||||
"(use Liquibase formatted SQL, or --tool=none to opt out of governance)", strings.Join(unanalysable, ", "))
|
||||
}
|
||||
plain, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading the token: %w", err)
|
||||
}
|
||||
var env *string
|
||||
if environmentID != "" {
|
||||
env = &environmentID
|
||||
}
|
||||
service, release, err := verdict.Release(serviceID, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
for _, file := range sqlFiles {
|
||||
sql, err := migrations.File(file).Contents(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s: %w", file, err)
|
||||
}
|
||||
if err := verdict.Judgeable(file, sql); err != nil {
|
||||
return err
|
||||
}
|
||||
if tool == "liquibase" {
|
||||
if err := verdict.LiquibaseJudgeable(file, sql); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(sql) == "" {
|
||||
continue
|
||||
}
|
||||
name := file
|
||||
resp, err := verdict.Analyze(ctx, client, apiURL, plain, verdict.Request{
|
||||
SQL: sql, Dialect: target.Dialect, Engine: target.Engine, EnvironmentID: env,
|
||||
ServiceID: service, Version: release, File: &name,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("judging %s: %w", file, err)
|
||||
}
|
||||
v := FileVerdict(verdict.Of(file, resp))
|
||||
report.Verdicts = append(report.Verdicts, v)
|
||||
report.DestructiveFound += resp.DestructiveCount + resp.SecurityCount
|
||||
report.DestructiveList = append(report.DestructiveList, v.Rules...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// judged converts the report's verdicts for the verdict package.
|
||||
func judged(report *LintReport) []verdict.FileVerdict {
|
||||
out := make([]verdict.FileVerdict, 0, len(report.Verdicts))
|
||||
for _, v := range report.Verdicts {
|
||||
out = append(out, verdict.FileVerdict(v))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// atlasLint runs atlas' own migration lint against a dev database — the given
|
||||
// one, or, with none given, a throwaway PostgreSQL started for this run. Like
|
||||
// runApply it sees the judged directory alone, with an empty working
|
||||
// directory, so an atlas.hcl in the repo cannot change what it reads. It
|
||||
// returns the lint's output and whether the lint failed; err is for a lint
|
||||
// that could not run at all.
|
||||
func (m *DbMigration) atlasLint(ctx context.Context, migrations *dagger.Directory, devURL *dagger.Secret, dialect string) (string, bool, error) {
|
||||
ctr := dag.Container().
|
||||
From(atlasImage).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work")
|
||||
if devURL != nil {
|
||||
ctr = ctr.WithSecretVariable("DEV_URL", devURL)
|
||||
} else {
|
||||
if dialect != "postgres" {
|
||||
return "", false, fmt.Errorf("--dev-url is required for atlas with dialect %q: only a PostgreSQL dev database is started for you", dialect)
|
||||
}
|
||||
nonce := make([]byte, 8)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
dev := dag.Container().
|
||||
From(atlasDevPostgresImage).
|
||||
// Reachable only through this binding, for this run. Trust auth: no
|
||||
// password to leak. The nonce makes the service this run's own —
|
||||
// two identical definitions could otherwise share one database.
|
||||
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
||||
WithEnvVariable("POSTGRES_DB", "dev").
|
||||
WithEnvVariable("INTEGRACI_LINT_RUN", hex.EncodeToString(nonce)).
|
||||
WithExposedPort(5432).
|
||||
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
||||
ctr = ctr.
|
||||
WithServiceBinding("devdb", dev).
|
||||
WithEnvVariable("DEV_URL", "postgres://postgres@devdb:5432/dev?sslmode=disable")
|
||||
}
|
||||
run := ctr.WithExec([]string{"sh", "-c",
|
||||
`atlas migrate lint --dir file:///migrations --dev-url "$DEV_URL" --latest 1`,
|
||||
}, dagger.ContainerWithExecOpts{Expect: dagger.ReturnTypeAny})
|
||||
code, err := run.ExitCode(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
stdout, err := run.Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
stderr, err := run.Stderr(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return strings.TrimSpace(stdout + "\n" + stderr), code != 0, nil
|
||||
}
|
||||
|
||||
// runApply executes the tool-specific apply and returns its output. The tool
|
||||
// gets the judged directory alone, mounted at /migrations, and an empty
|
||||
// working directory, so no config file from the repo can widen what it runs.
|
||||
// The target database URL is a secret env var, never on the command line.
|
||||
// Liquibase runs each judged file as its own formatted-SQL changelog, in the
|
||||
// order they were judged: there is no master changelog to point it at, and
|
||||
// that is exactly the set the engine saw.
|
||||
func (m *DbMigration) runApply(ctx context.Context, migrations *dagger.Directory, tool string, dbURL *dagger.Secret, files []string) (string, error) {
|
||||
// verdict.CheckTool already refused an unknown tool; For refuses it again
|
||||
// rather than fall through to another tool.
|
||||
adapter, err := engines.For(tool)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Apply(files)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work").
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
}
|
||||
|
||||
// Drift checks the tenant's database for drift under a platform-issued drift
|
||||
// grant, and reports it once. The reference is NOT the executor's choice: the
|
||||
// grant names the instance's applied changelog, which is built into a
|
||||
// throwaway PostgreSQL (or into --reference-url, an EMPTY database of the same
|
||||
// engine, for another dialect) and diffed against the live database. Until
|
||||
// 2026-09-27 the executor passed any reference URL and the report took no
|
||||
// grant, so it proved nothing (plan §7, "self-attested").
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Drift(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id to report drift for
|
||||
instanceID string,
|
||||
// The live database URL (JDBC) — a secret
|
||||
dbURL *dagger.Secret,
|
||||
// A reference to this run (CI job URL or id), kept with the report
|
||||
executionRef string,
|
||||
// An EMPTY database of the live database's engine to build the reference
|
||||
// in (JDBC, a secret). Unset: a throwaway PostgreSQL for this run.
|
||||
// +optional
|
||||
referenceURL *dagger.Secret,
|
||||
) (*DriftResult, error) {
|
||||
// Before the grant: one the adapter cannot use would be spent unreported.
|
||||
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Drift }, "drift")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "drift")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := granted.FileName()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd, err := adapter.Drift(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctr := dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/reference", dag.Directory().WithNewFile(file, granted.Changelog)).
|
||||
WithWorkdir("/work").
|
||||
// This grant's own run: never a cached diff from an earlier one.
|
||||
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI)
|
||||
if referenceURL != nil {
|
||||
ctr = ctr.WithSecretVariable("REFERENCE_URL", referenceURL)
|
||||
} else {
|
||||
ref := dag.Container().
|
||||
From(atlasDevPostgresImage).
|
||||
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
||||
WithEnvVariable("POSTGRES_DB", "reference").
|
||||
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI).
|
||||
WithExposedPort(5432).
|
||||
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
||||
ctr = ctr.
|
||||
WithServiceBinding("refdb", ref).
|
||||
WithEnvVariable("REFERENCE_URL", "jdbc:postgresql://refdb:5432/reference?user=postgres")
|
||||
}
|
||||
out, err := ctr.WithExec(cmd.Args).Stdout(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("building the reference or diffing against it failed: %w", err)
|
||||
}
|
||||
report := verdict.DriftReport{Drifted: verdict.Drifted(out), Diff: out, ExecutionRef: executionRef}
|
||||
if err := verdict.ReportDrift(ctx, client, apiURL, api, *grant, report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &DriftResult{Drifted: report.Drifted, Report: out}, nil
|
||||
}
|
||||
|
||||
// Snapshot takes a schema snapshot of the tenant's database under a snapshot
|
||||
// grant and records it on the platform (its hash and size, as an in-process
|
||||
// snapshot is not stored either). Returns the snapshot JSON.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Snapshot(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id the snapshot is of
|
||||
instanceID string,
|
||||
// The live database URL (JDBC) — a secret
|
||||
dbURL *dagger.Secret,
|
||||
// A reference to this run (CI job URL or id)
|
||||
executionRef string,
|
||||
) (string, error) {
|
||||
// Before the grant: one the adapter cannot use would be spent unreported.
|
||||
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Snapshot }, "snapshot")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "snapshot")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Snapshot()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out, runErr := dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithWorkdir("/work").
|
||||
// This grant's own run: never a cached snapshot from an earlier one.
|
||||
WithEnvVariable("INTEGRACI_SNAPSHOT_GRANT", grant.JTI).
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
outcome, message := "taken", ""
|
||||
if runErr != nil {
|
||||
outcome, message, out = "failed", runErr.Error(), ""
|
||||
}
|
||||
if err := verdict.ReportSnapshot(ctx, client, apiURL, api, *grant, outcome, out, executionRef, message); err != nil {
|
||||
return "", fmt.Errorf("%s, and %w", outcome, err)
|
||||
}
|
||||
if runErr != nil {
|
||||
return "", fmt.Errorf("%s snapshot failed (reported): %w", engine.DefaultTool, runErr)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DriftResult is what Drift found and reported.
|
||||
type DriftResult struct {
|
||||
Drifted bool
|
||||
Report string
|
||||
}
|
||||
|
||||
// runRollback undoes the last n changesets of the granted changelog with the
|
||||
// default adapter, against the judged file alone (see runApply).
|
||||
func (m *DbMigration) runRollback(ctx context.Context, migrations *dagger.Directory, file string, dbURL *dagger.Secret, n int) (string, error) {
|
||||
adapter, err := engines.For(engine.DefaultTool)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Rollback(file, n)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work").
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
}
|
||||
@@ -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