chore: publish IntegraCI build modules 732ec6c83925

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

No files matched your search

+233
View File
@@ -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")
}
}