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, `bad gateway`}, "not json": {http.StatusOK, `proxy login`}, "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) } } }