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:" 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) }