From 2414a96bd3226543e6babfe4be579c80672d1a77 Mon Sep 17 00:00:00 2001 From: kranthi Date: Tue, 1 Dec 2026 18:50:44 -0700 Subject: [PATCH] Add runtime: to .uigraph.yaml, with `runtime detect` and `runtime check` The runtime profile (how to set up, build and test a service, its sidecars and the names of its secrets) is a runtime: section of .uigraph.yaml. The CLI owns the schema (pkg/runtime, plus schema/runtime.schema.json and shared fixtures); uigraph-sandbox carries the same three files and the same parity test, so drift in either repo fails its CI. Unlike the rest of .uigraph.yaml, unknown keys in runtime are errors. Sync uploads the section with the service (the gateway ignores it until it stores it). `uigraph-cli runtime detect [dir]` proposes the section from, in order of trust: CI workflow commands, Makefile targets, package.json scripts and lockfile, go.mod, Dockerfile (HEALTHCHECK, NODE_OPTIONS), compose files and .env.example. Secrets are names only: a private registry the CI logs in to becomes a secret plus an .npmrc line that refers to ${NAME}; secrets whose egress host cannot be read are listed in notes, not guessed. A Makefile test target that CI does not run is noted, not added: uigraph-api's test-integration is not in CI and fails on a fresh database, which would have made the service un-Ready forever. --write appends to .uigraph.yaml, --force replaces an existing section. `runtime check` validates the profile and the repo (make targets, package scripts, compose file exist). With --run it runs setup, build, lint and tests in the sandbox base image with local Docker: the repo is copied in without .git and node_modules, postgres and redis sidecars share the container's network namespace, the network is cut after setup unless egress hosts are declared, and secrets come from same-named env vars passed by name (never on the docker command line); steps whose secrets are unset report needs_secrets instead of running. --report sends the result (status, reasons, commit, checked profile, steps) to Autopilot with the engineer's own UIGRAPH_USER_TOKEN; it needs --run and a clean tree. Verified on copies of uigraph-api (ready, no secrets) and uigraph-ui (setup passes with the registry secret; needs_secrets without it). Co-Authored-By: Claude Sonnet 5.5 --- cmd/runtime.go | 386 +++++++++++ cmd/runtime_test.go | 40 ++ cmd/sync.go | 1 + pkg/autopilot/client.go | 74 +++ pkg/autopilot/client_test.go | 39 ++ pkg/config/config.go | 26 + pkg/config/runtime_test.go | 46 ++ pkg/gateway/client.go | 7 +- pkg/runtime/check.go | 240 +++++++ pkg/runtime/detect.go | 609 ++++++++++++++++++ pkg/runtime/detect_test.go | 183 ++++++ pkg/runtime/run.go | 318 +++++++++ pkg/runtime/runtime.go | 279 ++++++++ pkg/runtime/schema/runtime.schema.json | 66 ++ pkg/runtime/schema_parity_test.go | 151 +++++ pkg/runtime/testdata/repos/goapi/.env.example | 4 + .../repos/goapi/.github/workflows/ci.yml | 15 + pkg/runtime/testdata/repos/goapi/Makefile | 15 + .../testdata/repos/goapi/cmd/api/main.go | 3 + pkg/runtime/testdata/repos/goapi/go.mod | 3 + .../nodeweb/.github/workflows/release.yml | 17 + pkg/runtime/testdata/repos/nodeweb/Dockerfile | 3 + .../testdata/repos/nodeweb/package.json | 12 + .../testdata/repos/nodeweb/pnpm-lock.yaml | 1 + .../testdata/schema/invalid/bad-env-name.yaml | 3 + .../testdata/schema/invalid/bad-host.yaml | 3 + .../testdata/schema/invalid/bad-image.yaml | 3 + .../testdata/schema/invalid/empty-setup.yaml | 3 + .../schema/invalid/multiline-env.yaml | 3 + .../testdata/schema/invalid/no-runtime.yaml | 1 + .../testdata/schema/invalid/no-service.yaml | 2 + .../schema/invalid/secret-in-env.yaml | 4 + .../schema/invalid/secret-lowercase.yaml | 3 + .../schema/invalid/secret-no-egress.yaml | 3 + .../testdata/schema/invalid/secret-twice.yaml | 3 + .../testdata/schema/invalid/unknown-key.yaml | 3 + .../schema/invalid/unknown-nested-key.yaml | 4 + .../testdata/schema/valid/design-example.yaml | 29 + .../schema/valid/sandbox-sample-service.yaml | 17 + .../testdata/schema/valid/service-object.yaml | 18 + 40 files changed, 2638 insertions(+), 2 deletions(-) create mode 100644 cmd/runtime.go create mode 100644 cmd/runtime_test.go create mode 100644 pkg/autopilot/client.go create mode 100644 pkg/autopilot/client_test.go create mode 100644 pkg/config/runtime_test.go create mode 100644 pkg/runtime/check.go create mode 100644 pkg/runtime/detect.go create mode 100644 pkg/runtime/detect_test.go create mode 100644 pkg/runtime/run.go create mode 100644 pkg/runtime/runtime.go create mode 100644 pkg/runtime/schema/runtime.schema.json create mode 100644 pkg/runtime/schema_parity_test.go create mode 100644 pkg/runtime/testdata/repos/goapi/.env.example create mode 100644 pkg/runtime/testdata/repos/goapi/.github/workflows/ci.yml create mode 100644 pkg/runtime/testdata/repos/goapi/Makefile create mode 100644 pkg/runtime/testdata/repos/goapi/cmd/api/main.go create mode 100644 pkg/runtime/testdata/repos/goapi/go.mod create mode 100644 pkg/runtime/testdata/repos/nodeweb/.github/workflows/release.yml create mode 100644 pkg/runtime/testdata/repos/nodeweb/Dockerfile create mode 100644 pkg/runtime/testdata/repos/nodeweb/package.json create mode 100644 pkg/runtime/testdata/repos/nodeweb/pnpm-lock.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/bad-env-name.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/bad-host.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/bad-image.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/empty-setup.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/multiline-env.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/no-runtime.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/no-service.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/secret-in-env.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/secret-lowercase.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/secret-no-egress.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/secret-twice.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/unknown-key.yaml create mode 100644 pkg/runtime/testdata/schema/invalid/unknown-nested-key.yaml create mode 100644 pkg/runtime/testdata/schema/valid/design-example.yaml create mode 100644 pkg/runtime/testdata/schema/valid/sandbox-sample-service.yaml create mode 100644 pkg/runtime/testdata/schema/valid/service-object.yaml diff --git a/cmd/runtime.go b/cmd/runtime.go new file mode 100644 index 0000000..97670ae --- /dev/null +++ b/cmd/runtime.go @@ -0,0 +1,386 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + + "github.com/uigraph-oss/uigraph-cli/pkg/autopilot" + "github.com/uigraph-oss/uigraph-cli/pkg/runtime" +) + +var runtimeCmd = &cobra.Command{ + Use: "runtime", + Short: "Detect and check a service's runtime profile (the runtime: section of .uigraph.yaml)", + Long: `The runtime: section of .uigraph.yaml says how to set up, build and test a service, +what it depends on, and which secrets (names only) its tests need. Autopilot drafts code +only for services whose profile has passed a check.`, +} + +var ( + rtConfig string + rtDetectConfig string + rtWrite bool + rtForce bool + rtRun bool + rtImage string + rtTimeout time.Duration + rtLogPath string + rtReport bool + rtAutopilotURL string + rtOrg string + rtJSON bool +) + +var runtimeDetectCmd = &cobra.Command{ + Use: "detect [dir]", + Short: "Propose a runtime: section from the repo's CI, Makefile, package.json, Dockerfile and compose files", + Long: `Inspects dir (default .) and prints a proposed runtime: section. Review it like any other +artifact. With --write it is added to the directory's .uigraph.yaml (--force replaces an existing one). +Secrets are listed by name only; set their values with uigraph secrets set, never in this file.`, + Args: cobra.MaximumNArgs(1), + RunE: runRuntimeDetect, +} + +var runtimeCheckCmd = &cobra.Command{ + Use: "check", + Short: "Validate the runtime: section, and with --run prove it in the sandbox base image", + Long: `Validates the runtime: section of .uigraph.yaml against the schema and the repo (make targets, +package scripts, compose files). With --run it runs setup, build, lint and tests in the sandbox base +image with local Docker, with sidecars for postgres and redis; secrets come from same-named environment +variables, and steps whose secrets are unset are reported as needing them rather than run. + +--report sends the result to Autopilot as the service's readiness, with the commit it was checked at. +It needs --run, a clean working tree, and your own user token (UIGRAPH_USER_TOKEN); only the +service's owning team and org admins can report.`, + Args: cobra.NoArgs, + RunE: runRuntimeCheck, +} + +func init() { + runtimeDetectCmd.Flags().StringVar(&rtDetectConfig, "config", "", "Config to write with --write (default /.uigraph.yaml)") + runtimeDetectCmd.Flags().BoolVar(&rtWrite, "write", false, "Add the proposal to .uigraph.yaml") + runtimeDetectCmd.Flags().BoolVar(&rtForce, "force", false, "With --write, replace an existing runtime: section") + + f := runtimeCheckCmd.Flags() + f.StringVar(&rtConfig, "config", ".uigraph.yaml", "Path to config file") + f.BoolVar(&rtRun, "run", false, "Run the profile in the sandbox base image with local Docker") + f.StringVar(&rtImage, "image", "", "Base image for --run (default runtime.image, else "+runtime.DefaultBaseImage+")") + f.DurationVar(&rtTimeout, "timeout", 20*time.Minute, "Per-step timeout for --run") + f.StringVar(&rtLogPath, "log", "", "Write every step's output to this file (default: a temp file)") + f.BoolVar(&rtReport, "report", false, "Report the --run result to Autopilot as the service's readiness") + f.StringVar(&rtAutopilotURL, "autopilot-url", "", "UIGraph URL serving /api/v1/autopilot (default UIGRAPH_AUTOPILOT_URL)") + f.StringVar(&rtOrg, "org", "", "Org id (default UIGRAPH_ORG_ID)") + f.BoolVar(&rtJSON, "json", false, "Print the result as JSON") + + runtimeCmd.AddCommand(runtimeDetectCmd, runtimeCheckCmd) + rootCmd.AddCommand(runtimeCmd) +} + +const proposalHeader = "# Proposed by `uigraph runtime detect`; review before committing.\n" + + "# Secrets are names only: set values with `uigraph secrets set`, never here.\n" + +func runRuntimeDetect(cmd *cobra.Command, args []string) error { + dir := "." + if len(args) == 1 { + dir = args[0] + } + det, err := runtime.Detect(dir) + if err != nil { + return err + } + out, err := det.Runtime.Marshal() + if err != nil { + return err + } + for _, n := range det.Notes { + _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "note: "+n) + } + if !rtWrite { + _, _ = fmt.Fprint(cmd.OutOrStdout(), proposalHeader+string(out)) + return nil + } + path := rtDetectConfig + if path == "" { + path = filepath.Join(dir, ".uigraph.yaml") + } + if err := writeRuntime(path, det.Runtime, rtForce); err != nil { + return err + } + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ runtime: section written to %s; run `uigraph-cli runtime check --config %s`\n", path, path) + return nil +} + +// writeRuntime adds rt to the .uigraph.yaml at path. A file without a +// runtime: section gets it appended, leaving the rest byte for byte; an +// existing section is replaced only with force. +func writeRuntime(path string, rt *runtime.Runtime, force bool) error { + section, err := rt.Marshal() + if err != nil { + return err + } + cur, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return os.WriteFile(path, append([]byte(proposalHeader), section...), 0o644) + } + if err != nil { + return err + } + var doc yaml.Node + if err := yaml.Unmarshal(cur, &doc); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + var top *yaml.Node + if len(doc.Content) == 1 && doc.Content[0].Kind == yaml.MappingNode { + top = doc.Content[0] + } + if top == nil && len(bytes.TrimSpace(cur)) > 0 { + return fmt.Errorf("%s: not a YAML mapping", path) + } + idx := -1 + if top != nil { + for i := 0; i+1 < len(top.Content); i += 2 { + if top.Content[i].Value == "runtime" { + idx = i + 1 + } + } + } + if idx < 0 { + if len(cur) > 0 && !bytes.HasSuffix(cur, []byte("\n")) { + cur = append(cur, '\n') + } + return os.WriteFile(path, append(append(cur, '\n'), append([]byte(proposalHeader), section...)...), 0o644) + } + if !force { + return fmt.Errorf("%s already has a runtime: section; pass --force to replace it", path) + } + var fresh yaml.Node + if err := yaml.Unmarshal(section, &fresh); err != nil { + return err + } + top.Content[idx] = fresh.Content[0].Content[1] + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(&doc); err != nil { + return err + } + _ = enc.Close() + return os.WriteFile(path, buf.Bytes(), 0o644) +} + +type checkResult struct { + Config string `json:"config"` + Service string `json:"service"` + Valid bool `json:"valid"` + Problems []string `json:"problems,omitempty"` + Warnings []string `json:"warnings,omitempty"` + Ran bool `json:"ran"` + Steps []runtime.Step `json:"steps,omitempty"` + Readiness string `json:"readiness,omitempty"` + Reasons []runtime.Reason `json:"reasons,omitempty"` + Commit string `json:"commit,omitempty"` + Reported *autopilot.Readiness `json:"reported,omitempty"` +} + +// Exit codes: 1 the profile is invalid, 3 a step failed. Steps that only +// need secret values do not fail the check. +func runRuntimeCheck(cmd *cobra.Command, _ []string) error { + cmd.SilenceUsage = true + ctx := cmd.Context() + out := cmd.OutOrStdout() + if rtJSON { + out = io.Discard + } + res := checkResult{Config: rtConfig} + raw, err := os.ReadFile(rtConfig) + if err != nil { + return err + } + f, err := runtime.Parse(raw) + if f != nil { + res.Service = f.Service + } + if err != nil { + res.Problems = splitErr(err) + return finishCheck(cmd, res, 1) + } + dir, err := filepath.Abs(filepath.Dir(rtConfig)) + if err != nil { + return err + } + res.Problems, res.Warnings = runtime.Lint(f.Runtime, dir) + res.Valid = len(res.Problems) == 0 + _, _ = fmt.Fprintf(out, "Runtime profile for %s (%s)\n", f.Service, rtConfig) + for _, w := range res.Warnings { + _, _ = fmt.Fprintln(out, " ! "+w) + } + if !res.Valid { + return finishCheck(cmd, res, 1) + } + _, _ = fmt.Fprintln(out, " ✓ valid") + if rtReport && !rtRun { + return errors.New("--report needs --run: readiness is what a run proves, not what the file says") + } + if !rtRun { + return finishCheck(cmd, res, 0) + } + + root, commit, dirty := gitState(dir) + res.Commit = commit + var reportCfg *reportTarget + if rtReport { + // Check everything a report needs before spending minutes on a run. + if reportCfg, err = newReportTarget(commit, dirty); err != nil { + return err + } + } + serviceDir, err := filepath.Rel(root, dir) + if err != nil { + return err + } + logW, logName, err := openLog() + if err != nil { + return err + } + defer func() { _ = logW.Close() }() + _, _ = fmt.Fprintf(out, "Running in Docker (full log: %s)\n", logName) + steps, err := runtime.Run(ctx, f.Runtime, runtime.RunOptions{ + RepoRoot: root, ServiceDir: serviceDir, Image: rtImage, StepTimeout: rtTimeout, + Log: logW, Progress: out, + }) + if err != nil { + return err + } + res.Ran, res.Steps = true, steps + res.Readiness, res.Reasons = runtime.Outcome(f.Runtime, steps) + _, _ = fmt.Fprintf(out, "Readiness: %s\n", res.Readiness) + for _, r := range res.Reasons { + _, _ = fmt.Fprintf(out, " - %s: %s\n", r.Code, r.Detail) + } + code := 0 + for _, s := range steps { + if s.Status == runtime.StepFailed { + code = 3 + } + } + if reportCfg != nil { + section, err := f.Runtime.Marshal() + if err != nil { + return err + } + rep := runtime.Report{Status: res.Readiness, Reasons: res.Reasons, Commit: commit, Runtime: string(section), Steps: steps} + if rep.Reasons == nil { + rep.Reasons = []runtime.Reason{} + } + stored, err := reportCfg.client.ReportReadiness(ctx, reportCfg.org, f.Service, rep) + if err != nil { + return fmt.Errorf("report readiness: %w", err) + } + res.Reported = stored + _, _ = fmt.Fprintf(out, "✓ Reported to Autopilot: %s is %s at %.12s\n", stored.ServiceName, stored.Status, stored.Commit) + } + return finishCheck(cmd, res, code) +} + +func finishCheck(cmd *cobra.Command, res checkResult, code int) error { + if rtJSON { + b, err := json.MarshalIndent(res, "", " ") + if err != nil { + return err + } + _, _ = fmt.Fprintln(cmd.OutOrStdout(), string(b)) + } else { + for _, p := range res.Problems { + _, _ = fmt.Fprintln(cmd.ErrOrStderr(), " ✗ "+p) + } + } + if code != 0 { + os.Exit(code) + } + return nil +} + +type reportTarget struct { + client *autopilot.Client + org string +} + +func newReportTarget(commit string, dirty bool) (*reportTarget, error) { + switch { + case commit == "": + return nil, errors.New("--report: not a git checkout, so there is no commit to report the check at") + case dirty: + return nil, errors.New("--report: the working tree has uncommitted changes; commit or stash them so the result matches a commit") + } + base := firstNonEmpty(rtAutopilotURL, os.Getenv("UIGRAPH_AUTOPILOT_URL")) + org := firstNonEmpty(rtOrg, os.Getenv("UIGRAPH_ORG_ID")) + token := os.Getenv("UIGRAPH_USER_TOKEN") + switch { + case base == "": + return nil, errors.New("--report: set --autopilot-url or UIGRAPH_AUTOPILOT_URL") + case org == "": + return nil, errors.New("--report: set --org or UIGRAPH_ORG_ID") + case token == "": + return nil, errors.New("--report: set UIGRAPH_USER_TOKEN to your own UIGraph token (not the CI sync token)") + } + return &reportTarget{client: &autopilot.Client{BaseURL: base, Token: token}, org: org}, nil +} + +// gitState is the repo root (or dir outside git), HEAD and whether the +// tree is dirty. +func gitState(dir string) (root, commit string, dirty bool) { + git := func(args ...string) (string, error) { + b, err := exec.Command("git", append([]string{"-C", dir}, args...)...).Output() + return strings.TrimSpace(string(b)), err + } + root, err := git("rev-parse", "--show-toplevel") + if err != nil { + abs, _ := filepath.Abs(dir) + return abs, "", false + } + commit, _ = git("rev-parse", "HEAD") + st, _ := git("status", "--porcelain") + return root, commit, st != "" +} + +func openLog() (*os.File, string, error) { + if rtLogPath != "" { + f, err := os.Create(rtLogPath) + return f, rtLogPath, err + } + f, err := os.CreateTemp("", "uigraph-runtime-check-*.log") + if err != nil { + return nil, "", err + } + return f, f.Name(), nil +} + +func splitErr(err error) []string { + var out []string + for _, l := range strings.Split(err.Error(), "\n") { + if l = strings.TrimSpace(l); l != "" { + out = append(out, l) + } + } + return out +} + +func firstNonEmpty(v ...string) string { + for _, s := range v { + if s != "" { + return s + } + } + return "" +} diff --git a/cmd/runtime_test.go b/cmd/runtime_test.go new file mode 100644 index 0000000..8958d69 --- /dev/null +++ b/cmd/runtime_test.go @@ -0,0 +1,40 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/uigraph-oss/uigraph-cli/pkg/runtime" +) + +func TestWriteRuntimeAppendsAndReplaces(t *testing.T) { + path := filepath.Join(t.TempDir(), ".uigraph.yaml") + orig := "version: 1\n# keep this comment\nservice:\n name: svc\n" + if err := os.WriteFile(path, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + rt := &runtime.Runtime{Setup: []string{"go mod download"}, Verify: runtime.Verify{Build: "go build ./..."}} + if err := writeRuntime(path, rt, false); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + if !strings.HasPrefix(string(b), orig) { + t.Fatalf("existing content changed:\n%s", b) + } + f, err := runtime.Load(path) + if err != nil || f.Service != "svc" || f.Runtime.Verify.Build != "go build ./..." { + t.Fatalf("reload: %+v %v", f, err) + } + rt.Verify.Build = "make build" + if err := writeRuntime(path, rt, false); err == nil { + t.Fatal("replaced an existing runtime: without --force") + } + if err := writeRuntime(path, rt, true); err != nil { + t.Fatal(err) + } + if f, err := runtime.Load(path); err != nil || f.Runtime.Verify.Build != "make build" || f.Service != "svc" { + t.Fatalf("after force: %+v %v", f, err) + } +} diff --git a/cmd/sync.go b/cmd/sync.go index bcd1b83..888518a 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -167,6 +167,7 @@ func runSync(cmd *cobra.Command, args []string) error { syncReq := gateway.ServiceSyncRequest{ Service: cfg.Service, + Runtime: cfg.Runtime, Git: gitMeta, Source: gateway.Source{ Type: "ci", diff --git a/pkg/autopilot/client.go b/pkg/autopilot/client.go new file mode 100644 index 0000000..cdde933 --- /dev/null +++ b/pkg/autopilot/client.go @@ -0,0 +1,74 @@ +// Package autopilot calls UIGraph Autopilot's public API as the engineer, with +// their own user token (not the CI service-account token sync uses): what is +// allowed depends on who they are. +package autopilot + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +type Client struct { + BaseURL string // e.g. https://app.example.com (Autopilot routes live under /api/v1/autopilot) + Token string + HTTP *http.Client +} + +// Readiness is what Autopilot stored. +type Readiness struct { + ServiceID string `json:"serviceId"` + ServiceName string `json:"serviceName"` + Status string `json:"status"` + Commit string `json:"commit"` + CheckedAt time.Time `json:"checkedAt"` +} + +// ReportReadiness stores a check result for service (its name or id). Only +// the service's owning team and org admins may. +func (c *Client) ReportReadiness(ctx context.Context, orgID, service string, report any) (*Readiness, error) { + body, err := json.Marshal(report) + if err != nil { + return nil, err + } + u := strings.TrimRight(c.BaseURL, "/") + "/api/v1/autopilot/orgs/" + url.PathEscape(orgID) + + "/services/" + url.PathEscape(service) + "/readiness" + req, err := http.NewRequestWithContext(ctx, http.MethodPut, u, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+c.Token) + hc := c.HTTP + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + resp, err := hc.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + switch resp.StatusCode { + case http.StatusOK: + case http.StatusUnauthorized: + return nil, fmt.Errorf("autopilot refused the token (401): check UIGRAPH_USER_TOKEN and the org id") + case http.StatusForbidden: + return nil, fmt.Errorf("only the service's owning team or an org admin can report its readiness (403)") + case http.StatusNotFound: + return nil, fmt.Errorf("service %q not found in the catalog (404); sync it first", service) + default: + return nil, fmt.Errorf("autopilot answered %d: %s", resp.StatusCode, strings.TrimSpace(string(b))) + } + var out Readiness + if err := json.Unmarshal(b, &out); err != nil { + return nil, fmt.Errorf("autopilot response: %w", err) + } + return &out, nil +} diff --git a/pkg/autopilot/client_test.go b/pkg/autopilot/client_test.go new file mode 100644 index 0000000..540ccc9 --- /dev/null +++ b/pkg/autopilot/client_test.go @@ -0,0 +1,39 @@ +package autopilot + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestReportReadiness(t *testing.T) { + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPut || r.URL.EscapedPath() != "/api/v1/autopilot/orgs/o1/services/UIGraph%20API/readiness" || + r.Header.Get("Authorization") != "Bearer user-tok" { + t.Errorf("request: %s %s %q", r.Method, r.URL.EscapedPath(), r.Header.Get("Authorization")) + } + _ = json.NewDecoder(r.Body).Decode(&got) + _, _ = w.Write([]byte(`{"serviceId":"s1","serviceName":"UIGraph API","status":"ready","commit":"abc1234"}`)) + })) + defer srv.Close() + c := &Client{BaseURL: srv.URL + "/", Token: "user-tok"} + out, err := c.ReportReadiness(context.Background(), "o1", "UIGraph API", map[string]string{"status": "ready"}) + if err != nil || out.ServiceID != "s1" || got["status"] != "ready" { + t.Fatalf("%+v %v %v", out, err, got) + } +} + +func TestReportReadinessRefusals(t *testing.T) { + for code, want := range map[int]string{401: "UIGRAPH_USER_TOKEN", 403: "owning team", 404: "sync it first", 500: "500"} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(code) })) + _, err := (&Client{BaseURL: srv.URL, Token: "t"}).ReportReadiness(context.Background(), "o", "s", nil) + srv.Close() + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%d: %v", code, err) + } + } +} diff --git a/pkg/config/config.go b/pkg/config/config.go index be372f3..4b9a1f1 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -9,6 +9,8 @@ import ( "strings" "gopkg.in/yaml.v3" + + "github.com/uigraph-oss/uigraph-cli/pkg/runtime" ) var validScreenshotExt = map[string]bool{ @@ -36,6 +38,9 @@ type Config struct { ML []MLProjectRef `yaml:"ml,omitempty"` CostTags []CostTag `yaml:"costTags,omitempty"` Timeline *TimelineRef `yaml:"timeline,omitempty"` + // Runtime is how to set up, build and test the service (Autopilot's + // runtime profile). Load decodes it strictly: an unknown key is an error. + Runtime *runtime.Runtime `yaml:"runtime,omitempty"` } type CostTag struct { @@ -397,6 +402,19 @@ func Load(path string) (*Config, error) { if err := readYAML(path, "config file", &cfg); err != nil { return nil, err } + if cfg.Runtime != nil { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + // The lenient decode above ignores unknown keys; the runtime section + // must not, or a typo silently drops a step. + f, err := runtime.Parse(raw) + if f == nil || f.Runtime == nil { + return nil, fmt.Errorf("%s: %v", path, err) + } + cfg.Runtime = f.Runtime + } for i := range cfg.TestPacks { if cfg.TestPacks[i].TestCasesPath == "" { @@ -501,6 +519,14 @@ func (c *Config) Validate() error { if c.Timeline != nil { problems = append(problems, "service is required to sync timeline; configs without a service may only sync maps and frames") } + if c.Runtime != nil { + problems = append(problems, "service is required to sync runtime; configs without a service may only sync maps and frames") + } + } + if c.Runtime != nil { + for _, err := range c.Runtime.Problems() { + problems = append(problems, err.Error()) + } } validAPITypes := map[string]bool{"openapi": true, "graphql": true, "grpc": true} diff --git a/pkg/config/runtime_test.go b/pkg/config/runtime_test.go new file mode 100644 index 0000000..183ea54 --- /dev/null +++ b/pkg/config/runtime_test.go @@ -0,0 +1,46 @@ +package config + +import ( + "encoding/json" + "strings" + "testing" +) + +const fullService = " category: Backend\n description: d\n repository: {provider: github, url: https://github.com/acme/x}\n ownership: {team: t}\n" + +func TestRuntimeSectionLoadsAndValidates(t *testing.T) { + cfg, err := Load(videoRepo(t, fullService+"runtime:\n setup: [go mod download]\n verify:\n test: {unit: go test ./...}\n", nil)) + if err != nil { + t.Fatal(err) + } + if cfg.Runtime == nil || cfg.Runtime.Verify.Test["unit"] != "go test ./..." { + t.Fatalf("runtime: %+v", cfg.Runtime) + } + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + // Sync uploads it with the service, with the schema's own key names. + b, _ := json.Marshal(map[string]any{"runtime": cfg.Runtime}) + if !strings.Contains(string(b), `"verify":{"test":{"unit":"go test ./..."}}`) { + t.Errorf("json: %s", b) + } +} + +// Unlike the rest of .uigraph.yaml, an unknown runtime key is an error: a +// typo would otherwise silently drop a step. +func TestRuntimeSectionIsStrict(t *testing.T) { + _, err := Load(videoRepo(t, fullService+"runtime:\n verfiy: {build: make}\n", nil)) + if err == nil || !strings.Contains(err.Error(), "verfiy") { + t.Fatalf("typo accepted: %v", err) + } +} + +func TestRuntimeSectionProblemsReported(t *testing.T) { + cfg, err := Load(videoRepo(t, fullService+"runtime:\n secrets: [{name: K}]\n", nil)) + if err != nil { + t.Fatal(err) + } + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "egress hosts required") { + t.Fatalf("validate: %v", err) + } +} diff --git a/pkg/gateway/client.go b/pkg/gateway/client.go index b2b734c..0889421 100644 --- a/pkg/gateway/client.go +++ b/pkg/gateway/client.go @@ -10,6 +10,7 @@ import ( "github.com/uigraph-oss/uigraph-cli/pkg/config" "github.com/uigraph-oss/uigraph-cli/pkg/git" + "github.com/uigraph-oss/uigraph-cli/pkg/runtime" "github.com/uigraph-oss/uigraph-cli/pkg/timeline" ) @@ -35,8 +36,10 @@ type Source struct { type ServiceSyncRequest struct { Service config.Service `json:"service"` - Git git.Metadata `json:"git"` - Source Source `json:"source"` + // Runtime is the service's runtime profile, uploaded with it. + Runtime *runtime.Runtime `json:"runtime,omitempty"` + Git git.Metadata `json:"git"` + Source Source `json:"source"` } type ServiceSyncResponse struct { diff --git a/pkg/runtime/check.go b/pkg/runtime/check.go new file mode 100644 index 0000000..96b5cf3 --- /dev/null +++ b/pkg/runtime/check.go @@ -0,0 +1,240 @@ +package runtime + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" +) + +// Step statuses. +const ( + StepPassed = "passed" + StepFailed = "failed" + StepSkipped = "skipped" // blocked by an earlier failure + // StepNeedsSecrets: a secret the step needs has no value here. + StepNeedsSecrets = "needs_secrets" +) + +// Readiness, as Autopilot stores it. +const ( + Ready = "ready" + NotReady = "not_ready" +) + +// Reason codes for not_ready, matching the design's readiness states. +const ( + ReasonNeedsSecrets = "needs_secrets" + ReasonPrivateNetwork = "needs_private_network" + ReasonCantBuild = "cant_build" + ReasonTestsFailing = "tests_failing" + ReasonNothingToVerify = "nothing_to_verify" +) + +// Step is one command of a check run. +type Step struct { + Name string `json:"name"` // setup[0], build, lint, test:unit + Command string `json:"command"` + Status string `json:"status"` + Detail string `json:"detail,omitempty"` + Seconds float64 `json:"seconds,omitempty"` +} + +type Reason struct { + Code string `json:"code"` + Detail string `json:"detail"` +} + +// Steps lists a runtime's steps in run order: setup, build, lint, tests. +func (rt *Runtime) Steps() []Step { + var out []Step + for i, c := range rt.Setup { + out = append(out, Step{Name: fmt.Sprintf("setup[%d]", i), Command: c}) + } + if rt.Verify.Build != "" { + out = append(out, Step{Name: "build", Command: rt.Verify.Build}) + } + if rt.Verify.Lint != "" { + out = append(out, Step{Name: "lint", Command: rt.Verify.Lint}) + } + for _, k := range sortedKeys(rt.Verify.Test) { + if c := rt.Verify.Test[k]; c != "" { + out = append(out, Step{Name: "test:" + k, Command: c}) + } + } + return out +} + +// SecretsFor are the secrets step needs: those naming it (setup[N] matches +// "setup") plus those with no needed_for, which every step may need. +func (rt *Runtime) SecretsFor(step string) []string { + kind, _, _ := strings.Cut(step, "[") + var out []string + for _, s := range rt.Secrets { + if len(s.NeededFor) == 0 || slices.Contains(s.NeededFor, kind) || slices.Contains(s.NeededFor, step) { + out = append(out, s.Name) + } + } + return out +} + +// Lint checks a parsed runtime against the repo in dir: the make targets, +// package scripts and compose file it names exist, and needed_for names real +// steps. It returns problems (the profile cannot work) and warnings. +func Lint(rt *Runtime, dir string) (problems, warnings []string) { + r, err := readRepo(dir) + if err != nil { + return []string{err.Error()}, nil + } + for _, st := range append(rt.Steps(), Step{Name: "run", Command: rt.Run}) { + if st.Command == "" { + continue + } + for _, p := range r.commandProblems(st.Command) { + problems = append(problems, st.Name+": "+p) + } + } + if c := rt.Dependencies.Compose; c != "" { + if _, err := os.Stat(filepath.Join(dir, c)); err != nil { + problems = append(problems, fmt.Sprintf("dependencies.compose: %s not found", c)) + } + } + for _, s := range rt.Dependencies.Services { + if _, ok := sidecars[s]; !ok { + warnings = append(warnings, fmt.Sprintf("dependencies.services: %s has no local sidecar image; `check --run` will not start it", s)) + } + } + names := map[string]bool{"setup": true, "build": true, "lint": true, "run": true} + for k := range rt.Verify.Test { + names["test:"+k] = true + } + for _, s := range rt.Secrets { + for _, n := range s.NeededFor { + if !names[n] { + warnings = append(warnings, fmt.Sprintf("secrets.%s.needed_for: no step %q", s.Name, n)) + } + } + } + if rt.Verify.Build == "" && len(rt.Verify.Test) == 0 { + problems = append(problems, "verify: no build and no tests, so a change could never be verified") + } + return problems, warnings +} + +var ( + cmdSplit = regexp.MustCompile(`\s*(?:&&|\|\||;)\s*`) + pnpmOwn = map[string]bool{"install": true, "i": true, "add": true, "exec": true, "dlx": true, "run": true, "x": true, "rebuild": true, "audit": true, "why": true} +) + +// commandProblems understands just enough shell to check `cd`, `make` and +// package-manager script calls; anything else is taken on trust. +func (r *repo) commandProblems(cmd string) []string { + var out []string + cur := r + for _, seg := range cmdSplit.Split(cmd, -1) { + f := strings.Fields(seg) + for len(f) > 0 && strings.Contains(f[0], "=") && !strings.HasPrefix(f[0], "-") { + f = f[1:] // VAR=value prefixes + } + if len(f) == 0 { + continue + } + switch f[0] { + case "cd": + if len(f) < 2 || strings.ContainsAny(f[1], "$~") { + return out + } + next, err := readRepo(filepath.Join(cur.dir, f[1])) + if err != nil { + return append(out, fmt.Sprintf("cd %s: no such directory", f[1])) + } + cur = next + case "make": + for _, a := range f[1:] { + if strings.HasPrefix(a, "-") { + break // -C and friends: don't guess + } + if !strings.Contains(a, "=") && !cur.targets[a] { + out = append(out, fmt.Sprintf("make target %q not in the Makefile", a)) + } + } + case "pnpm", "npm", "yarn": + script := "" + switch { + case len(f) >= 3 && f[1] == "run": + script = f[2] + case len(f) >= 2 && (f[1] == "test" || f[1] == "start"): + script = f[1] + case len(f) >= 2 && f[0] != "npm" && !pnpmOwn[f[1]] && !strings.HasPrefix(f[1], "-"): + script = f[1] + } + if script == "" { + continue + } + if !cur.files["package.json"] { + out = append(out, fmt.Sprintf("%s %s: no package.json", f[0], script)) + } else if _, ok := cur.scripts[script]; !ok { + out = append(out, fmt.Sprintf("package.json has no %q script", script)) + } + } + } + return out +} + +// Outcome turns step results into a readiness and its reasons. A run that +// never happened (no steps run) is not evidence of anything. +func Outcome(rt *Runtime, steps []Step) (string, []Reason) { + var reasons []Reason + var missing, failedSetup, failedTests []string + for _, s := range steps { + switch s.Status { + case StepNeedsSecrets: + for _, n := range strings.Split(s.Detail, ", ") { + if n != "" && !slices.Contains(missing, n) { + missing = append(missing, n) + } + } + case StepFailed: + if strings.HasPrefix(s.Name, "test:") { + failedTests = append(failedTests, s.Name) + } else { + failedSetup = append(failedSetup, s.Name) + } + } + } + if len(failedSetup) > 0 { + reasons = append(reasons, Reason{ReasonCantBuild, "failed: " + strings.Join(failedSetup, ", ")}) + } + if len(failedTests) > 0 { + reasons = append(reasons, Reason{ReasonTestsFailing, "failed: " + strings.Join(failedTests, ", ")}) + } + if len(missing) > 0 { + reasons = append(reasons, Reason{ReasonNeedsSecrets, "no value for " + strings.Join(missing, ", ")}) + } + if len(rt.Network.Internal) > 0 { + reasons = append(reasons, Reason{ReasonPrivateNetwork, "tests need " + strings.Join(rt.Network.Internal, ", ")}) + } + if rt.Verify.Build == "" && len(rt.Verify.Test) == 0 { + reasons = append(reasons, Reason{ReasonNothingToVerify, "verify has no build and no tests"}) + } + if len(reasons) > 0 { + return NotReady, reasons + } + return Ready, nil +} + +// Report is what `uigraph runtime check --report` sends to Autopilot. +type Report struct { + Status string `json:"status"` + Reasons []Reason `json:"reasons"` + Commit string `json:"commit"` + // Runtime is the checked section as YAML, so Autopilot keeps the + // profile the result belongs to. + Runtime string `json:"runtime"` + Steps []Step `json:"steps"` +} + +func (r Report) JSON() ([]byte, error) { return json.MarshalIndent(r, "", " ") } diff --git a/pkg/runtime/detect.go b/pkg/runtime/detect.go new file mode 100644 index 0000000..af1b328 --- /dev/null +++ b/pkg/runtime/detect.go @@ -0,0 +1,609 @@ +package runtime + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + + "gopkg.in/yaml.v3" +) + +// Detection is a proposed runtime section and what the engineer should +// review in it. Nothing in it is a secret value: secrets are names only. +type Detection struct { + Runtime *Runtime + // Notes explain choices and list what detect could not decide. + Notes []string +} + +// repo is what detect reads from a checkout. +type repo struct { + dir string + files map[string]bool + makeVars map[string]string // NAME ?= value / NAME = value + targets map[string]bool + scripts map[string]string // package.json scripts + pm string // pnpm, npm, yarn + ciRuns []ciStep + ciImages []string // CI job service images + ciEnv map[string]string + dockerTxt string +} + +type ciStep struct { + run string // the step's run script, or "" for a uses: step + env map[string]string +} + +// Detect inspects dir (a service's directory, usually a repo root) and +// proposes a runtime section. The CI workflow is the most reliable record of +// how tests really run, so its commands win over Makefile targets, which win +// over language defaults. +func Detect(dir string) (*Detection, error) { + r, err := readRepo(dir) + if err != nil { + return nil, err + } + d := &Detection{Runtime: &Runtime{}} + rt := d.Runtime + hasGo, hasNode := r.files["go.mod"], r.files["package.json"] + var build, unit, lint []string + + if hasGo { + rt.Stack = append(rt.Stack, "go") + rt.Setup = append(rt.Setup, "go mod download") + build = append(build, r.pick("build", "go build", "go build ./...")) + unit = append(unit, r.goUnit()) + lint = append(lint, r.pickMake("lint", "go vet ./...")) + } + if hasNode { + rt.Stack = append(rt.Stack, "node") + rt.Setup = append(rt.Setup, r.registrySetup(d)...) + rt.Setup = append(rt.Setup, r.install()) + if _, ok := r.scripts["build"]; ok { + build = append(build, r.pm+" run build") + } + if _, ok := r.scripts["test"]; ok { + unit = append(unit, r.pm+" test") + } + var l []string + for _, s := range []string{"lint", "typecheck"} { + if _, ok := r.scripts[s]; ok { + l = append(l, r.pm+" run "+s) + } + } + if len(l) > 0 { + lint = append(lint, strings.Join(l, " && ")) + } + for _, s := range []string{"e2e", "test:e2e"} { + if _, ok := r.scripts[s]; ok { + d.note("package.json has an %q script (browser tests); not added to verify, since the sandbox base has no browsers", s) + } + } + } + if !hasGo && !hasNode { + d.note("no go.mod or package.json: fill in setup and verify by hand") + } + if r.dockerTxt != "" { + rt.Stack = append(rt.Stack, "docker") + if h := healthURL(r.dockerTxt); h != "" { + rt.Health = h + } + } + if len(build) > 0 { + rt.Verify.Build = strings.Join(build, " && ") + } + if len(lint) > 0 { + rt.Verify.Lint = strings.Join(lint, " && ") + } + if len(unit) > 0 { + rt.Verify.Test = map[string]string{"unit": strings.Join(unit, " && ")} + } else if s, ok := r.testScript(); ok { + rt.Verify.Test = map[string]string{"unit": s} + } + // Without CI, a Makefile's integration target is the best record there + // is. With CI, only what CI runs is proposed: a suite nobody runs is + // likely broken, and would keep the service from ever being Ready. + integration := r.targets["test-integration"] && !r.ciRunsTests() + if integration { + if rt.Verify.Test == nil { + rt.Verify.Test = map[string]string{} + } + rt.Verify.Test["integration"] = "make test-integration" + } else if r.targets["test-integration"] { + d.note("the Makefile has test-integration, which CI does not run; not added. Add it under verify.test once it passes") + } + if v := dockerEnv(r.dockerTxt, "NODE_OPTIONS"); v != "" && hasNode { + // The image build needs it (typically a bigger heap for the bundler). + rt.Env = map[string]string{"NODE_OPTIONS": v} + } + r.dependencies(d, integration) + r.secrets(d) + rt.Run = r.runCommand(hasGo, hasNode) + if rt.Run == "" { + d.note("could not tell how to run the service; set run (and health) if previews need it") + } + return d, nil +} + +func (d *Detection) note(format string, args ...any) { + d.Notes = append(d.Notes, fmt.Sprintf(format, args...)) +} + +func readRepo(dir string) (*repo, error) { + st, err := os.Stat(dir) + if err != nil { + return nil, err + } + if !st.IsDir() { + return nil, fmt.Errorf("%s is not a directory", dir) + } + r := &repo{dir: dir, files: map[string]bool{}, makeVars: map[string]string{}, targets: map[string]bool{}, + scripts: map[string]string{}, ciEnv: map[string]string{}} + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + for _, e := range entries { + r.files[e.Name()] = true + } + for _, mf := range []string{"GNUmakefile", "makefile", "Makefile"} { + if r.files[mf] { + r.readMakefile(filepath.Join(dir, mf)) + } + } + if r.files["package.json"] { + var pkg struct { + Scripts map[string]string `json:"scripts"` + PackageManager string `json:"packageManager"` + } + b, err := os.ReadFile(filepath.Join(dir, "package.json")) + if err != nil { + return nil, err + } + if err := json.Unmarshal(b, &pkg); err != nil { + return nil, fmt.Errorf("package.json: %w", err) + } + if pkg.Scripts != nil { + r.scripts = pkg.Scripts + } + r.pm = packageManager(r.files, pkg.PackageManager) + } + if r.files["Dockerfile"] { + b, _ := os.ReadFile(filepath.Join(dir, "Dockerfile")) + r.dockerTxt = string(b) + } + r.readWorkflows() + return r, nil +} + +func packageManager(files map[string]bool, declared string) string { + switch { + case strings.HasPrefix(declared, "pnpm@"), files["pnpm-lock.yaml"]: + return "pnpm" + case strings.HasPrefix(declared, "yarn@"), files["yarn.lock"]: + return "yarn" + } + return "npm" +} + +var ( + makeTarget = regexp.MustCompile(`^([A-Za-z0-9_.-]+(?:\s+[A-Za-z0-9_.-]+)*)\s*:([^=]|$)`) + makeVar = regexp.MustCompile(`^([A-Za-z_][A-Za-z0-9_]*)\s*(?:\?|:|\+)?=\s*(.*)$`) +) + +func (r *repo) readMakefile(path string) { + f, err := os.Open(path) + if err != nil { + return + } + defer func() { _ = f.Close() }() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := sc.Text() + if strings.HasPrefix(line, "\t") || strings.HasPrefix(strings.TrimSpace(line), "#") { + continue + } + if m := makeVar.FindStringSubmatch(line); m != nil { + r.makeVars[m[1]] = strings.TrimSpace(m[2]) + continue + } + if m := makeTarget.FindStringSubmatch(line); m != nil { + for _, t := range strings.Fields(m[1]) { + if !strings.HasPrefix(t, ".") { + r.targets[t] = true + } + } + } + } +} + +type workflow struct { + Env map[string]string `yaml:"env"` + Jobs map[string]struct { + Env map[string]string `yaml:"env"` + Services map[string]struct { + Image string `yaml:"image"` + } `yaml:"services"` + Steps []struct { + Uses string `yaml:"uses"` + Run string `yaml:"run"` + Env map[string]string `yaml:"env"` + } `yaml:"steps"` + } `yaml:"jobs"` +} + +func (r *repo) readWorkflows() { + files, _ := filepath.Glob(filepath.Join(r.dir, ".github", "workflows", "*.y*ml")) + sort.Strings(files) + for _, path := range files { + b, err := os.ReadFile(path) + if err != nil { + continue + } + var w workflow + if yaml.Unmarshal(b, &w) != nil { + continue + } + jobs := sortedKeys(w.Jobs) + for _, name := range jobs { + job := w.Jobs[name] + for k, v := range job.Env { + r.ciEnv[k] = v + } + for _, s := range sortedKeys(job.Services) { + r.ciImages = append(r.ciImages, job.Services[s].Image) + } + for _, st := range job.Steps { + r.ciRuns = append(r.ciRuns, ciStep{run: st.Run, env: st.Env}) + } + } + } +} + +// ciLines are the CI's shell commands, one per line, continuations joined. +func (r *repo) ciLines() []string { + var out []string + for _, s := range r.ciRuns { + joined := strings.ReplaceAll(s.run, "\\\n", " ") + for _, l := range strings.Split(joined, "\n") { + l = strings.TrimSpace(l) + if l != "" && !strings.HasPrefix(l, "#") { + out = append(out, strings.Join(strings.Fields(l), " ")) + } + } + } + return out +} + +// pick prefers a CI line starting with prefix, then make , then def. +func (r *repo) pick(target, prefix, def string) string { + for _, l := range r.ciLines() { + if strings.HasPrefix(l, prefix+" ") && !strings.Contains(l, "${{") { + return l + } + } + return r.pickMake(target, def) +} + +func (r *repo) pickMake(target, def string) string { + if r.targets[target] { + return "make " + target + } + return def +} + +func (r *repo) goUnit() string { + for _, l := range r.ciLines() { + if strings.HasPrefix(l, "go test ") && !strings.Contains(l, "${{") { + return l + } + } + for _, t := range []string{"test-unit", "unit", "test"} { + if r.targets[t] { + return "make " + t + } + } + return "go test ./..." +} + +func (r *repo) testScript() (string, bool) { + for _, p := range []string{"scripts/test.sh", "test.sh", "bin/test"} { + if st, err := os.Stat(filepath.Join(r.dir, p)); err == nil && !st.IsDir() { + return "./" + p, true + } + } + return "", false +} + +func (r *repo) install() string { + switch r.pm { + case "pnpm": + return "pnpm install --frozen-lockfile" + case "yarn": + return "yarn install --frozen-lockfile" + } + if r.files["package-lock.json"] { + return "npm ci" + } + return "npm install" +} + +var ( + secretRef = regexp.MustCompile(`secrets\.([A-Za-z_][A-Za-z0-9_]*)`) + scopedReg = regexp.MustCompile(`(@[a-z0-9][a-z0-9._-]*):registry=https://([a-z0-9.-]+)`) + hostInText = regexp.MustCompile(`(?:https?:)?//([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+)`) + httpURLText = regexp.MustCompile(`https?://[^\s'"]+`) + buildStep = regexp.MustCompile(`\b(go (test|build|mod|run)|pnpm|npm|npx|yarn|make|pytest|cargo|mvn|gradle)\b`) +) + +// registrySetup finds a private npm registry the CI authenticates to and +// writes the same .npmrc in setup, referring to the secret by name: npm and +// pnpm expand ${NAME} in .npmrc, so the value never appears in the profile. +func (r *repo) registrySetup(d *Detection) []string { + for _, s := range r.ciRuns { + m := scopedReg.FindStringSubmatch(s.run) + ref := secretRef.FindStringSubmatch(s.run + envText(s.env)) + if m == nil || ref == nil { + continue + } + scope, host, name := m[1], m[2], strings.ToUpper(ref[1]) + d.Runtime.Secrets = append(d.Runtime.Secrets, Secret{ + Name: name, Purpose: "install " + scope + " packages from " + host, + Egress: []string{host}, NeededFor: []string{"setup"}, + }) + d.note("CI installs %s packages from %s with secret %s; set its value with `uigraph secrets set`", scope, host, name) + return []string{fmt.Sprintf(`printf '%%s\n' '%s:registry=https://%s' '//%s/:_authToken=${%s}' >> "$HOME/.npmrc"`, + scope, host, host, name)} + } + return nil +} + +func envText(env map[string]string) string { + var b strings.Builder + for _, k := range sortedKeys(env) { + b.WriteString("\n" + env[k]) + } + return b.String() +} + +// secrets adds the other secrets CI's shell steps use, when the hosts they +// go to can be read from the same step; the rest are listed in notes. A +// secret only handed to an action (`with:`) is a deploy credential, not a +// test one, and is skipped. +func (r *repo) secrets(d *Detection) { + have := map[string]bool{} + for _, s := range d.Runtime.Secrets { + have[s.Name] = true + } + var unplaced []string + for _, s := range r.ciRuns { + if s.run == "" { + continue + } + text := s.run + envText(s.env) + for _, m := range secretRef.FindAllStringSubmatch(text, -1) { + name := strings.ToUpper(m[1]) + if have[name] || name == "GITHUB_TOKEN" || !secretNameRE.MatchString(name) { + continue + } + have[name] = true + var hosts []string + for _, h := range hostInText.FindAllStringSubmatch(text, -1) { + if !slices.Contains(hosts, h[1]) && hostRE.MatchString(h[1]) { + hosts = append(hosts, h[1]) + } + } + // Only a step that builds or tests is evidence the tests need it; + // a notification or deploy step's token is not a test secret. + if len(hosts) == 0 || !buildStep.MatchString(s.run) { + unplaced = append(unplaced, name) + continue + } + d.Runtime.Secrets = append(d.Runtime.Secrets, Secret{Name: name, Purpose: "used by CI", Egress: hosts}) + } + } + for _, f := range []string{".env.example", ".env.sample", ".env.template", ".env.test.example"} { + if r.files[f] { + unplaced = append(unplaced, r.envExampleSecrets(d, filepath.Join(r.dir, f), have)...) + } + } + if len(unplaced) > 0 { + d.note("left out secrets not clearly used by tests, or with no known egress host: %s. If tests need one, add it under secrets with the hosts it is sent to", strings.Join(unplaced, ", ")) + } +} + +// knownEgress maps well-known secret name prefixes to their API hosts. +var knownEgress = map[string]string{ + "STRIPE": "api.stripe.com", "OPENAI": "api.openai.com", "ANTHROPIC": "api.anthropic.com", + "GITHUB": "api.github.com", "SLACK": "slack.com", "SENDGRID": "api.sendgrid.com", + "TWILIO": "api.twilio.com", "LINEAR": "api.linear.app", "FIGMA": "api.figma.com", +} + +var secretish = regexp.MustCompile(`(?i)(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)$`) + +func (r *repo) envExampleSecrets(d *Detection, path string, have map[string]bool) []string { + f, err := os.Open(path) + if err != nil { + return nil + } + defer func() { _ = f.Close() }() + var unplaced []string + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(sc.Text()), "export ")) + name, _, ok := strings.Cut(line, "=") + name = strings.TrimSpace(name) + if !ok || strings.HasPrefix(line, "#") || !secretish.MatchString(name) || !secretNameRE.MatchString(name) || have[name] { + continue + } + have[name] = true + prefix, _, _ := strings.Cut(name, "_") + if host, ok := knownEgress[prefix]; ok { + d.Runtime.Secrets = append(d.Runtime.Secrets, Secret{Name: name, Purpose: "from " + filepath.Base(path), Egress: []string{host}}) + continue + } + unplaced = append(unplaced, name) + } + return unplaced +} + +var knownServices = []string{"postgres", "redis", "mysql", "mongo", "minio"} + +// dependencies finds sidecar services from CI job services, compose files +// and database URLs in the Makefile and CI env, and keeps local URLs (test +// fixtures, not secrets) as env so tests find their sidecars. +func (r *repo) dependencies(d *Detection, withMake bool) { + set := map[string]bool{} + for _, img := range r.ciImages { + if s := serviceOf(img); s != "" { + set[s] = true + } + } + for _, name := range []string{"docker-compose.test.yml", "docker-compose.test.yaml", "compose.test.yml", "compose.test.yaml"} { + if r.files[name] { + d.Runtime.Dependencies.Compose = name + } + } + // CI's job env is set for every step, so it is kept as env. A Makefile's + // URL is only a sidecar hint: make supplies its own default, and + // exporting it would point every other test at the database too. + urls := map[string]string{} + if withMake { + for k, v := range r.makeVars { + urls[k] = v + } + } + for k, v := range r.ciEnv { + urls[k] = v + } + for _, k := range sortedKeys(urls) { + v := strings.Trim(urls[k], `"'`) + scheme, rest, ok := strings.Cut(v, "://") + if !ok || !envKeyRE.MatchString(k) || strings.Contains(v, "$") { + continue + } + svc := map[string]string{"postgres": "postgres", "postgresql": "postgres", "redis": "redis", "mysql": "mysql", "mongodb": "mongo"}[scheme] + host := rest + if i := strings.LastIndex(host, "@"); i >= 0 { + host = host[i+1:] + } + if svc == "" || (!strings.HasPrefix(host, "localhost") && !strings.HasPrefix(host, "127.0.0.1")) { + continue + } + set[svc] = true + if _, fromCI := r.ciEnv[k]; !fromCI { + continue + } + if d.Runtime.Env == nil { + d.Runtime.Env = map[string]string{} + } + d.Runtime.Env[k] = v + } + if d.Runtime.Dependencies.Compose == "" { + for _, name := range []string{"docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"} { + if r.files[name] { + b, _ := os.ReadFile(filepath.Join(r.dir, name)) + var c struct { + Services map[string]struct { + Image string `yaml:"image"` + } `yaml:"services"` + } + if yaml.Unmarshal(b, &c) == nil { + for _, s := range sortedKeys(c.Services) { + if svc := serviceOf(c.Services[s].Image); svc != "" { + set[svc] = true + } + } + } + } + } + } + for _, s := range knownServices { + if set[s] { + d.Runtime.Dependencies.Services = append(d.Runtime.Dependencies.Services, s) + } + } +} + +func serviceOf(image string) string { + base := image + if i := strings.LastIndex(base, "/"); i >= 0 { + base = base[i+1:] + } + base, _, _ = strings.Cut(base, ":") + for _, s := range knownServices { + if base == s || base == s+"ql" || (s == "mongo" && base == "mongodb") { + return s + } + } + return "" +} + +func (r *repo) runCommand(hasGo, hasNode bool) string { + if r.targets["run"] { + return "make run" + } + if hasGo { + if r.files["main.go"] { + return "go run ." + } + mains, _ := filepath.Glob(filepath.Join(r.dir, "cmd", "*", "main.go")) + if len(mains) == 1 { + return "go run ./cmd/" + filepath.Base(filepath.Dir(mains[0])) + } + } + if hasNode { + for _, s := range []string{"start", "dev"} { + if _, ok := r.scripts[s]; ok { + return r.pm + " run " + s + } + } + } + return "" +} + +// ciRunsTests reports whether CI runs any test command. +func (r *repo) ciRunsTests() bool { + for _, l := range r.ciLines() { + if testLine.MatchString(l) { + return true + } + } + return false +} + +var testLine = regexp.MustCompile(`^(go test|(pnpm|npm|yarn)( run)? test|make test|pytest|cargo test)\b`) + +// dockerEnv reads `ENV NAME=value` from a Dockerfile. +func dockerEnv(dockerfile, name string) string { + for _, l := range strings.Split(dockerfile, "\n") { + f := strings.Fields(l) + if len(f) >= 2 && strings.EqualFold(f[0], "ENV") { + for _, kv := range f[1:] { + if k, v, ok := strings.Cut(kv, "="); ok && k == name { + return strings.Trim(v, `"'`) + } + } + } + } + return "" +} + +// healthURL reads a Dockerfile HEALTHCHECK's URL. +func healthURL(dockerfile string) string { + for _, l := range strings.Split(dockerfile, "\n") { + if strings.HasPrefix(strings.ToUpper(strings.TrimSpace(l)), "HEALTHCHECK") { + if u := httpURLText.FindString(l); u != "" { + return u + } + } + } + return "" +} diff --git a/pkg/runtime/detect_test.go b/pkg/runtime/detect_test.go new file mode 100644 index 0000000..ea31846 --- /dev/null +++ b/pkg/runtime/detect_test.go @@ -0,0 +1,183 @@ +package runtime + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// detectAndParse runs detect on a fixture repo and parses the proposal back +// the way `check` does, as a .uigraph.yaml. +func detectAndParse(t *testing.T, dir string) (*Detection, *Runtime) { + t.Helper() + d, err := Detect(dir) + if err != nil { + t.Fatal(err) + } + section, err := d.Runtime.Marshal() + if err != nil { + t.Fatal(err) + } + f, err := Parse(append([]byte("service:\n name: fixture\n"), section...)) + if err != nil { + t.Fatalf("detect output does not parse: %v\n%s", err, section) + } + if problems, _ := Lint(f.Runtime, dir); len(problems) > 0 { + t.Fatalf("detect output fails check: %v\n%s", problems, section) + } + return d, f.Runtime +} + +func TestDetectGoService(t *testing.T) { + d, rt := detectAndParse(t, "testdata/repos/goapi") + if !slices.Equal(rt.Stack, []string{"go"}) || !slices.Equal(rt.Setup, []string{"go mod download"}) { + t.Errorf("stack/setup: %v %v", rt.Stack, rt.Setup) + } + // CI's command wins over the Makefile's, which wins over a default. + if c, _ := rt.TestCommand("unit"); c != "go test ./... -race -cover" { + t.Errorf("unit = %q", c) + } + // CI runs tests, so the Makefile-only integration suite is only noted, + // and the Makefile's database URL is not exported to every test. + if _, ok := rt.TestCommand("integration"); ok || len(rt.Dependencies.Services) > 0 || len(rt.Env) > 0 { + t.Errorf("integration %v deps %v env %v", rt.Verify.Test, rt.Dependencies.Services, rt.Env) + } + if !strings.Contains(strings.Join(d.Notes, "\n"), "test-integration") { + t.Errorf("integration not noted: %v", d.Notes) + } + if rt.Verify.Build != "make build" || rt.Verify.Lint != "make lint" || rt.Run != "go run ./cmd/api" { + t.Errorf("build %q lint %q run %q", rt.Verify.Build, rt.Verify.Lint, rt.Run) + } + // STRIPE_* has a known host; the rest are left for the engineer, and the + // notify step's token is not a test secret. + if len(rt.Secrets) != 1 || rt.Secrets[0].Name != "STRIPE_SECRET_KEY" || rt.Secrets[0].Egress[0] != "api.stripe.com" { + t.Errorf("secrets: %+v", rt.Secrets) + } + notes := strings.Join(d.Notes, "\n") + for _, want := range []string{"NOTIFY_TOKEN", "THING_KEY", "SOMETHING_TOKEN"} { + if !strings.Contains(notes, want) { + t.Errorf("notes miss %s:\n%s", want, notes) + } + } +} + +// Without CI, the Makefile is the record: its integration target is used, +// with a postgres sidecar, but its URL stays in the Makefile. +func TestDetectMakefileIntegrationWithoutCI(t *testing.T) { + dir := t.TempDir() + mk := "TEST_DB ?= postgres://app:pw@localhost:5432/app\nbuild:\n\tgo build ./...\ntest-integration:\n\tgo test ./it/...\n" + for name, body := range map[string]string{"go.mod": "module x\n", "Makefile": mk} { + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + _, rt := detectAndParse(t, dir) + if c, _ := rt.TestCommand("integration"); c != "make test-integration" || !slices.Equal(rt.Dependencies.Services, []string{"postgres"}) || len(rt.Env) > 0 { + t.Fatalf("test %v deps %v env %v", rt.Verify.Test, rt.Dependencies.Services, rt.Env) + } + // The local run's postgres sidecar takes the Makefile's credentials. + got := sidecars["postgres"].env(localURLs(rt, dir)) + if !slices.Equal(got, []string{"POSTGRES_USER=app", "POSTGRES_PASSWORD=pw", "POSTGRES_DB=app"}) { + t.Fatalf("sidecar env %v", got) + } +} + +func TestDetectNodeServiceWithPrivateRegistry(t *testing.T) { + d, rt := detectAndParse(t, "testdata/repos/nodeweb") + if len(rt.Setup) != 2 || rt.Setup[1] != "pnpm install --frozen-lockfile" { + t.Fatalf("setup: %q", rt.Setup) + } + // The registry token is referenced by name in .npmrc, never by value. + want := `printf '%s\n' '@acme-private:registry=https://npm.pkg.github.com' '//npm.pkg.github.com/:_authToken=${PACKAGES_READ_TOKEN}' >> "$HOME/.npmrc"` + if rt.Setup[0] != want { + t.Errorf("npmrc setup:\n got %s\nwant %s", rt.Setup[0], want) + } + if len(rt.Secrets) != 1 || rt.Secrets[0].Name != "PACKAGES_READ_TOKEN" || + !slices.Equal(rt.Secrets[0].Egress, []string{"npm.pkg.github.com"}) || !slices.Equal(rt.Secrets[0].NeededFor, []string{"setup"}) { + t.Errorf("secrets: %+v (docker login secrets must not appear)", rt.Secrets) + } + if rt.Verify.Build != "pnpm run build" || rt.Verify.Lint != "pnpm run lint && pnpm run typecheck" || rt.Verify.Test["unit"] != "pnpm test" { + t.Errorf("verify: %+v", rt.Verify) + } + if rt.Env["NODE_OPTIONS"] != "--max-old-space-size=4096" { + t.Errorf("env %v", rt.Env) + } + if rt.Health != "http://localhost:80/healthz" || rt.Run != "pnpm run start" || !slices.Contains(rt.Stack, "docker") { + t.Errorf("health %q run %q stack %v", rt.Health, rt.Run, rt.Stack) + } + if !strings.Contains(strings.Join(d.Notes, "\n"), `"e2e"`) { + t.Errorf("e2e not noted: %v", d.Notes) + } +} + +func TestLintFindsBrokenCommands(t *testing.T) { + rt := &Runtime{ + Setup: []string{"pnpm install"}, + Dependencies: Dependencies{Compose: "nope.yml", Services: []string{"postgres", "kafka"}}, + Secrets: []Secret{{Name: "K", Egress: []string{"a.com"}, NeededFor: []string{"test:e2e"}}}, + Verify: Verify{ + Build: "make build && make missing-target", + Test: map[string]string{"unit": "cd web && pnpm run nope", "other": "cd nowhere && make x"}, + }, + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "Makefile"), []byte("build:\n\tgo build ./...\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(dir, "web"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "web", "package.json"), []byte(`{"scripts":{"test":"vitest"}}`), 0o644); err != nil { + t.Fatal(err) + } + problems, warnings := Lint(rt, dir) + got := strings.Join(problems, "\n") + for _, want := range []string{`make target "missing-target"`, `no "nope" script`, "cd nowhere", "nope.yml not found"} { + if !strings.Contains(got, want) { + t.Errorf("problems miss %q:\n%s", want, got) + } + } + if strings.Contains(got, `"build"`) { + t.Errorf("existing target flagged:\n%s", got) + } + w := strings.Join(warnings, "\n") + if !strings.Contains(w, "kafka") || !strings.Contains(w, `no step "test:e2e"`) { + t.Errorf("warnings: %s", w) + } +} + +func TestOutcome(t *testing.T) { + rt := &Runtime{Verify: Verify{Build: "b", Test: map[string]string{"unit": "u"}}} + if s, r := Outcome(rt, []Step{{Name: "build", Status: StepPassed}, {Name: "test:unit", Status: StepPassed}}); s != Ready || r != nil { + t.Errorf("all passed: %s %v", s, r) + } + s, r := Outcome(rt, []Step{{Name: "setup[0]", Status: StepNeedsSecrets, Detail: "A, B"}, {Name: "build", Status: StepSkipped}}) + if s != NotReady || len(r) != 1 || r[0].Code != ReasonNeedsSecrets || r[0].Detail != "no value for A, B" { + t.Errorf("secrets: %s %v", s, r) + } + s, r = Outcome(rt, []Step{{Name: "build", Status: StepFailed}, {Name: "test:unit", Status: StepFailed}}) + if s != NotReady || len(r) != 2 || r[0].Code != ReasonCantBuild || r[1].Code != ReasonTestsFailing { + t.Errorf("failures: %s %v", s, r) + } + rt.Network.Internal = []string{"payments.internal"} + if _, r := Outcome(rt, nil); len(r) != 1 || r[0].Code != ReasonPrivateNetwork { + t.Errorf("private network: %v", r) + } +} + +func TestSecretsFor(t *testing.T) { + rt := &Runtime{Secrets: []Secret{ + {Name: "ALL", Egress: []string{"a.com"}}, + {Name: "SETUP", Egress: []string{"a.com"}, NeededFor: []string{"setup"}}, + {Name: "INT", Egress: []string{"a.com"}, NeededFor: []string{"test:integration"}}, + }} + for step, want := range map[string][]string{ + "setup[1]": {"ALL", "SETUP"}, "build": {"ALL"}, "test:integration": {"ALL", "INT"}, "test:unit": {"ALL"}, + } { + if got := rt.SecretsFor(step); !slices.Equal(got, want) { + t.Errorf("%s: %v, want %v", step, got, want) + } + } +} diff --git a/pkg/runtime/run.go b/pkg/runtime/run.go new file mode 100644 index 0000000..1011f1c --- /dev/null +++ b/pkg/runtime/run.go @@ -0,0 +1,318 @@ +package runtime + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "net/url" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "time" +) + +// RunOptions configure a local check run in Docker. +type RunOptions struct { + // RepoRoot is mounted read-only and copied into the container, without + // .git and node_modules, so setup never writes to the checkout. + RepoRoot string + // ServiceDir is the service's directory relative to RepoRoot; commands + // run there, as in the sandbox image. + ServiceDir string + // Image overrides runtime.image (default DefaultBaseImage). + Image string + // LookupEnv finds secret values; the default is os.LookupEnv. Values are + // passed to docker by name (-e NAME), never on its command line. + LookupEnv func(string) (string, bool) + // StepTimeout bounds each step (default 20 minutes). + StepTimeout time.Duration + // Log receives every step's output; Progress one line per step. + Log io.Writer + Progress io.Writer + // Docker is the docker binary (default "docker"). + Docker string +} + +// srcDir matches the sandbox image's layout (uigraph-sandbox runtime.SrcDir). +const srcDir = "/workspace/src" + +// sidecar is a dependency the local run can start. +type sidecar struct { + image string + env func(urls []string) []string + ready []string // command run in the sidecar until it succeeds +} + +var sidecars = map[string]sidecar{ + "postgres": { + image: "postgres:16-alpine", + env: func(urls []string) []string { + user, pass, db := "postgres", "postgres", "postgres" + // Match the first local postgres URL the tests use, so they + // connect with the credentials they already have. + for _, raw := range urls { + u, err := url.Parse(raw) + if err != nil || !strings.HasPrefix(u.Scheme, "postgres") || u.User == nil { + continue + } + user = u.User.Username() + if p, ok := u.User.Password(); ok { + pass = p + } + if d := strings.TrimPrefix(u.Path, "/"); d != "" { + db = d + } + break + } + return []string{"POSTGRES_USER=" + user, "POSTGRES_PASSWORD=" + pass, "POSTGRES_DB=" + db} + }, + ready: []string{"pg_isready", "-h", "127.0.0.1"}, + }, + "redis": {image: "redis:7-alpine", ready: []string{"redis-cli", "ping"}}, +} + +// Run runs the runtime's setup, build, lint and tests in the sandbox base +// image, with sidecars for its dependencies, and returns each step's result. +// A step whose secrets have no value here is not run (needs_secrets); after a +// setup, build or lint step that did not pass, the rest are skipped. +func Run(ctx context.Context, rt *Runtime, opt RunOptions) ([]Step, error) { + if opt.Docker == "" { + opt.Docker = "docker" + } + if opt.LookupEnv == nil { + opt.LookupEnv = os.LookupEnv + } + if opt.StepTimeout == 0 { + opt.StepTimeout = 20 * time.Minute + } + if opt.Log == nil { + opt.Log = io.Discard + } + if opt.Progress == nil { + opt.Progress = io.Discard + } + image := opt.Image + if image == "" { + image = rt.Image + } + if image == "" { + image = DefaultBaseImage + } + root, err := filepath.Abs(opt.RepoRoot) + if err != nil { + return nil, err + } + d := docker{bin: opt.Docker} + if _, err := d.out(ctx, "image", "inspect", "--format", "{{.Id}}", image); err != nil { + return nil, fmt.Errorf("image %s not found locally: build the sandbox base image (uigraph-sandbox: make base-image) or pass --image", image) + } + + name := "uigraph-check-" + randHex() + args := []string{"run", "-d", "--name", name, "--label", "uigraph.runtime-check=1", "-v", root + ":/src:ro"} + for _, k := range sortedKeys(rt.Env) { + args = append(args, "-e", k+"="+rt.Env[k]) + } + missing := map[string]bool{} + var secretEnv []string + for _, s := range rt.Secrets { + if v, ok := opt.LookupEnv(s.Name); ok && v != "" { + args = append(args, "-e", s.Name) + secretEnv = append(secretEnv, s.Name+"="+v) + } else { + missing[s.Name] = true + } + } + args = append(args, image, "sleep", "infinity") + containers := []string{name} + defer func() { + // The run's own context may be cancelled; clean up regardless. + cctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + _, _ = d.out(cctx, append([]string{"rm", "-f"}, containers...)...) + }() + if _, err := d.outEnv(ctx, secretEnv, args...); err != nil { + return nil, fmt.Errorf("start container: %w", err) + } + if out, err := d.out(ctx, "exec", name, "sh", "-ec", + "mkdir -p "+srcDir+" && tar -C /src --exclude=node_modules --exclude=.git -cf - . | tar -C "+srcDir+" -xf -"); err != nil { + return nil, fmt.Errorf("copy the repo into the container: %w: %s", err, out) + } + for _, svc := range rt.Dependencies.Services { + sc, ok := sidecars[svc] + if !ok { + continue + } + sname := name + "-" + svc + sargs := []string{"run", "-d", "--name", sname, "--label", "uigraph.runtime-check=1", "--network", "container:" + name} + if sc.env != nil { + for _, e := range sc.env(localURLs(rt, filepath.Join(root, opt.ServiceDir))) { + sargs = append(sargs, "-e", e) + } + } + containers = append(containers, sname) + if out, err := d.out(ctx, append(sargs, sc.image)...); err != nil { + return nil, fmt.Errorf("start %s: %w: %s", svc, err, out) + } + if err := d.waitReady(ctx, sname, sc.ready); err != nil { + return nil, fmt.Errorf("%s did not become ready: %w", svc, err) + } + _, _ = fmt.Fprintf(opt.Progress, " ✓ %s sidecar ready\n", svc) + } + if rt.Dependencies.Compose != "" { + _, _ = fmt.Fprintf(opt.Progress, " ! dependencies.compose (%s) is started by the sandbox, not by a local check\n", rt.Dependencies.Compose) + } + + workdir := srcDir + if sd := path.Clean(filepath.ToSlash(opt.ServiceDir)); sd != "." && sd != "" { + workdir = path.Join(srcDir, sd) + } + steps := rt.Steps() + blocked := "" + offline := false + for i := range steps { + st := &steps[i] + if blocked != "" { + st.Status, st.Detail = StepSkipped, "after "+blocked + progress(opt.Progress, st) + continue + } + // Once dependencies are installed, cut the network like the sandbox + // does, unless the profile declares hosts tests must reach (a local + // run cannot allowlist them). + if !offline && !strings.HasPrefix(st.Name, "setup") && len(rt.EgressHosts()) == 0 { + if _, err := d.out(ctx, "network", "disconnect", "bridge", name); err == nil { + offline = true + } + } + var need []string + for _, s := range rt.SecretsFor(st.Name) { + if missing[s] { + need = append(need, s) + } + } + if len(need) > 0 { + st.Status, st.Detail = StepNeedsSecrets, strings.Join(need, ", ") + } else { + d.step(ctx, name, workdir, st, opt) + } + progress(opt.Progress, st) + if st.Status != StepPassed && !strings.HasPrefix(st.Name, "test:") { + blocked = st.Name + } + } + return steps, ctx.Err() +} + +// localURLs are the connection URLs the tests may use: the profile's env, +// then the defaults in the service's Makefile. +func localURLs(rt *Runtime, dir string) []string { + var out []string + for _, k := range sortedKeys(rt.Env) { + out = append(out, rt.Env[k]) + } + if r, err := readRepo(dir); err == nil { + for _, k := range sortedKeys(r.makeVars) { + out = append(out, strings.Trim(r.makeVars[k], `"'`)) + } + } + return out +} + +func progress(w io.Writer, st *Step) { + mark := map[string]string{StepPassed: "✓", StepFailed: "✗", StepNeedsSecrets: "…", StepSkipped: "-"}[st.Status] + _, _ = fmt.Fprintf(w, " %s %-12s %s", mark, st.Name, st.Status) + if st.Seconds > 0 { + _, _ = fmt.Fprintf(w, " (%.0fs)", st.Seconds) + } + if st.Detail != "" { + _, _ = fmt.Fprintf(w, ": %s", st.Detail) + } + _, _ = fmt.Fprintln(w) +} + +// step runs one command and records its result. The last lines of a +// failing step's output go into Detail. +func (d docker) step(ctx context.Context, container, workdir string, st *Step, opt RunOptions) { + sctx, cancel := context.WithTimeout(ctx, opt.StepTimeout) + defer cancel() + _, _ = fmt.Fprintf(opt.Log, "\n=== %s: %s\n", st.Name, st.Command) + var tail tailBuffer + cmd := exec.CommandContext(sctx, d.bin, "exec", "-w", workdir, container, "/bin/sh", "-ec", st.Command) + cmd.Stdout = io.MultiWriter(opt.Log, &tail) + cmd.Stderr = cmd.Stdout + start := time.Now() + err := cmd.Run() + st.Seconds = time.Since(start).Seconds() + switch { + case err == nil: + st.Status = StepPassed + case errors.Is(sctx.Err(), context.DeadlineExceeded): + st.Status, st.Detail = StepFailed, fmt.Sprintf("timed out after %s", opt.StepTimeout) + default: + st.Status, st.Detail = StepFailed, fmt.Sprintf("%v; last output:\n%s", err, tail.String()) + } +} + +type docker struct{ bin string } + +func (d docker) out(ctx context.Context, args ...string) (string, error) { + return d.outEnv(ctx, nil, args...) +} + +// outEnv runs docker with extra environment (secret values, which docker +// reads for -e NAME), so they never appear in its argv. +func (d docker) outEnv(ctx context.Context, env []string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, d.bin, args...) + if len(env) > 0 { + cmd.Env = append(os.Environ(), env...) + } + var b bytes.Buffer + cmd.Stdout, cmd.Stderr = &b, &b + err := cmd.Run() + return strings.TrimSpace(b.String()), err +} + +func (d docker) waitReady(ctx context.Context, container string, probe []string) error { + deadline := time.Now().Add(90 * time.Second) + for { + if len(probe) == 0 { + return nil + } + if _, err := d.out(ctx, append([]string{"exec", container}, probe...)...); err == nil { + return nil + } + if time.Now().After(deadline) { + return errors.New("timed out") + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } +} + +// tailBuffer keeps the last 30 lines written to it. +type tailBuffer struct{ lines []string } + +func (t *tailBuffer) Write(p []byte) (int, error) { + t.lines = append(t.lines, strings.Split(strings.TrimRight(string(p), "\n"), "\n")...) + if n := len(t.lines); n > 30 { + t.lines = t.lines[n-30:] + } + return len(p), nil +} + +func (t *tailBuffer) String() string { return strings.Join(t.lines, "\n") } + +func randHex() string { + b := make([]byte, 4) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} diff --git a/pkg/runtime/runtime.go b/pkg/runtime/runtime.go new file mode 100644 index 0000000..4176fb4 --- /dev/null +++ b/pkg/runtime/runtime.go @@ -0,0 +1,279 @@ +// Package runtime is the `runtime:` section of a service's .uigraph.yaml: how +// to set up, run, build and test the service, what it depends on, and the +// names (never values) of the secrets its tests need. +// +// The CLI owns the canonical schema. uigraph-sandbox parses the same section +// to build a service's sandbox image, and the two must not drift: the schema +// is also written down as schema/runtime.schema.json, and both repos carry a +// copy of it and of testdata/schema, with a test (schema_parity_test.go, the +// same file in both) that checks the Go types and patterns against the JSON +// Schema and every fixture against the parser. Changing a field means +// changing it here, in the JSON Schema and in the fixtures, then copying +// schema/ and testdata/schema/ to uigraph-sandbox's internal/runtime. +package runtime + +import ( + "bytes" + "errors" + "fmt" + "os" + "regexp" + "sort" + "strings" + + "gopkg.in/yaml.v3" +) + +// DefaultBaseImage is the sandbox base image used when a runtime names none. +const DefaultBaseImage = "uigraph-sandbox-base:dev" + +// Runtime is how to set up, run, build and test a service. The JSON names +// match the YAML ones, so a JSON copy validates against the same schema. +type Runtime struct { + // Image is the base to layer on. Empty: DefaultBaseImage. + Image string `yaml:"image,omitempty" json:"image,omitempty"` + // Stack is informational (go, node, docker...); detect fills it. + Stack []string `yaml:"stack,omitempty" json:"stack,omitempty"` + // Setup runs once, with network, in the service directory: installing + // dependencies. In the sandbox it runs at image build time. + Setup []string `yaml:"setup,omitempty" json:"setup,omitempty"` + Dependencies Dependencies `yaml:"dependencies,omitempty" json:"dependencies,omitzero"` + Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"` // non-secret values only + Secrets []Secret `yaml:"secrets,omitempty" json:"secrets,omitempty"` + Network Network `yaml:"network,omitempty" json:"network,omitzero"` + Run string `yaml:"run,omitempty" json:"run,omitempty"` + Health string `yaml:"health,omitempty" json:"health,omitempty"` + Verify Verify `yaml:"verify,omitempty" json:"verify,omitzero"` + KnownFlaky []string `yaml:"known_flaky,omitempty" json:"known_flaky,omitempty"` +} + +// Dependencies are services the tests need, run as sidecars that share the +// service's network namespace, so they answer on localhost. +type Dependencies struct { + Compose string `yaml:"compose,omitempty" json:"compose,omitempty"` + Services []string `yaml:"services,omitempty" json:"services,omitempty"` +} + +// Secret is a declared secret: a name, never a value. +type Secret struct { + Name string `yaml:"name" json:"name"` + Purpose string `yaml:"purpose,omitempty" json:"purpose,omitempty"` + // Egress are the only hosts the real value is sent to; the sandbox's + // proxy swaps it in on requests to them. + Egress []string `yaml:"egress" json:"egress"` + // NeededFor names the steps that need it: setup, build, lint, run, or + // test:. Empty means every step. + NeededFor []string `yaml:"needed_for,omitempty" json:"needed_for,omitempty"` +} + +// Network lists hosts beyond the defaults (package registries, model, MCP). +type Network struct { + Internal []string `yaml:"internal,omitempty" json:"internal,omitempty"` // internal hosts; Cloud cannot reach them + Egress []string `yaml:"egress,omitempty" json:"egress,omitempty"` // extra public hosts tests need +} + +// Verify are the commands that prove a change. +type Verify struct { + Build string `yaml:"build,omitempty" json:"build,omitempty"` + Lint string `yaml:"lint,omitempty" json:"lint,omitempty"` + Test map[string]string `yaml:"test,omitempty" json:"test,omitempty"` // e.g. unit, integration +} + +// The patterns are repeated in schema/runtime.schema.json; the parity test +// fails if they differ. +var ( + envKeyRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + secretNameRE = regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`) + hostRE = regexp.MustCompile(`^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$`) + imageRE = regexp.MustCompile(`^[a-z0-9][a-z0-9._/:@-]*$`) +) + +// File is a .uigraph.yaml as far as the runtime cares. +type File struct { + // Service is the service's name. .uigraph.yaml writes it as + // `service: {name: x}`; the design's examples as `service: x`. Both parse. + Service string + Runtime *Runtime +} + +// ErrNoRuntime is returned by Parse when the file has no runtime: section. +var ErrNoRuntime = errors.New("no runtime: section") + +// Parse reads a .uigraph.yaml's service name and runtime section. Unknown +// keys inside runtime are errors, so a typo fails loudly rather than +// silently doing nothing; other top-level sections are other tools' business. +func Parse(b []byte) (*File, error) { + var top map[string]yaml.Node + if err := yaml.Unmarshal(b, &top); err != nil { + return nil, fmt.Errorf("parse .uigraph.yaml: %w", err) + } + f := &File{} + if n, ok := top["service"]; ok { + name, err := serviceName(&n) + if err != nil { + return nil, err + } + f.Service = name + } + n, ok := top["runtime"] + if !ok { + return nil, ErrNoRuntime + } + rt, err := decodeStrict(&n) + if err != nil { + return nil, err + } + f.Runtime = rt + return f, f.Validate() +} + +// Load reads and parses path. +func Load(path string) (*File, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return Parse(b) +} + +func serviceName(n *yaml.Node) (string, error) { + if n.Kind == yaml.MappingNode { + var s struct { + Name string `yaml:"name"` + } + if err := n.Decode(&s); err != nil { + return "", fmt.Errorf("service: %w", err) + } + return s.Name, nil + } + var s string + if err := n.Decode(&s); err != nil { + return "", fmt.Errorf("service: %w", err) + } + return s, nil +} + +func decodeStrict(n *yaml.Node) (*Runtime, error) { + raw, err := yaml.Marshal(n) + if err != nil { + return nil, err + } + dec := yaml.NewDecoder(bytes.NewReader(raw)) + dec.KnownFields(true) + var rt Runtime + if err := dec.Decode(&rt); err != nil { + return nil, fmt.Errorf("runtime: %w", err) + } + return &rt, nil +} + +// Validate checks the runtime section. +func (f *File) Validate() error { + var errs []error + if f.Service == "" { + errs = append(errs, errors.New("service: required")) + } + if f.Runtime == nil { + return errors.Join(append(errs, errors.New("runtime: required"))...) + } + return errors.Join(append(errs, f.Runtime.Problems()...)...) +} + +// Problems lists everything wrong with the section, in a stable order. +func (rt *Runtime) Problems() []error { + var errs []error + if rt.Image != "" && !imageRE.MatchString(rt.Image) { + errs = append(errs, fmt.Errorf("runtime.image %q: not an image reference", rt.Image)) + } + for _, k := range sortedKeys(rt.Env) { + v := rt.Env[k] + if !envKeyRE.MatchString(k) { + errs = append(errs, fmt.Errorf("runtime.env: bad name %q", k)) + } + if strings.ContainsAny(v, "\n\r") { + errs = append(errs, fmt.Errorf("runtime.env.%s: multi-line values are not supported", k)) + } + } + seen := map[string]bool{} + for _, s := range rt.Secrets { + if !secretNameRE.MatchString(s.Name) { + errs = append(errs, fmt.Errorf("runtime.secrets: bad name %q (UPPER_SNAKE)", s.Name)) + } + if seen[s.Name] { + errs = append(errs, fmt.Errorf("runtime.secrets: %s declared twice", s.Name)) + } + seen[s.Name] = true + if _, clash := rt.Env[s.Name]; clash { + errs = append(errs, fmt.Errorf("runtime: %s is both env and a secret", s.Name)) + } + if len(s.Egress) == 0 { + errs = append(errs, fmt.Errorf("runtime.secrets.%s: egress hosts required (where the proxy may send it)", s.Name)) + } + for _, h := range s.Egress { + if !hostRE.MatchString(h) { + errs = append(errs, fmt.Errorf("runtime.secrets.%s.egress: bad host %q", s.Name, h)) + } + } + } + for _, h := range append(append([]string{}, rt.Network.Egress...), rt.Network.Internal...) { + if !hostRE.MatchString(h) { + errs = append(errs, fmt.Errorf("runtime.network: bad host %q", h)) + } + } + for _, c := range rt.Setup { + if strings.TrimSpace(c) == "" { + errs = append(errs, errors.New("runtime.setup: empty command")) + } + } + return errs +} + +// TestCommand returns verify.test[name]. +func (rt *Runtime) TestCommand(name string) (string, bool) { + c, ok := rt.Verify.Test[name] + return c, ok && c != "" +} + +// EgressHosts is every host the sandbox may reach for this service: network +// egress plus each secret's hosts (secret hosts are where the proxy swaps the +// value in, so they must be reachable). +func (rt *Runtime) EgressHosts() []string { + set := map[string]bool{} + for _, h := range rt.Network.Egress { + set[h] = true + } + for _, s := range rt.Secrets { + for _, h := range s.Egress { + set[h] = true + } + } + out := make([]string, 0, len(set)) + for h := range set { + out = append(out, h) + } + sort.Strings(out) + return out +} + +// Marshal renders the section as YAML, nested under a `runtime:` key. +func (rt *Runtime) Marshal() ([]byte, error) { + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(map[string]*Runtime{"runtime": rt}); err != nil { + return nil, err + } + if err := enc.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/pkg/runtime/schema/runtime.schema.json b/pkg/runtime/schema/runtime.schema.json new file mode 100644 index 0000000..3e1a02c --- /dev/null +++ b/pkg/runtime/schema/runtime.schema.json @@ -0,0 +1,66 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://uigraph.app/schemas/runtime.schema.json", + "title": "UIGraph runtime profile", + "description": "The runtime: section of a service's .uigraph.yaml. Canonical copy in uigraph-cli pkg/runtime/schema; uigraph-sandbox carries the same file, and a parity test in each repo checks its Go types against it.", + "type": "object", + "additionalProperties": false, + "properties": { + "image": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._/:@-]*$" }, + "stack": { "type": "array", "items": { "type": "string" } }, + "setup": { "type": "array", "items": { "type": "string", "minLength": 1 } }, + "dependencies": { + "type": "object", + "additionalProperties": false, + "properties": { + "compose": { "type": "string" }, + "services": { "type": "array", "items": { "type": "string" } } + } + }, + "env": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "type": "string", "pattern": "^[^\\r\\n]*$" } + }, + "secrets": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "egress"], + "properties": { + "name": { "type": "string", "pattern": "^[A-Z][A-Z0-9_]{0,63}$" }, + "purpose": { "type": "string" }, + "egress": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/host" } }, + "needed_for": { "type": "array", "items": { "type": "string" } } + } + } + }, + "network": { + "type": "object", + "additionalProperties": false, + "properties": { + "internal": { "type": "array", "items": { "$ref": "#/$defs/host" } }, + "egress": { "type": "array", "items": { "$ref": "#/$defs/host" } } + } + }, + "run": { "type": "string" }, + "health": { "type": "string" }, + "verify": { + "type": "object", + "additionalProperties": false, + "properties": { + "build": { "type": "string" }, + "lint": { "type": "string" }, + "test": { "type": "object", "additionalProperties": { "type": "string" } } + } + }, + "known_flaky": { "type": "array", "items": { "type": "string" } } + }, + "$defs": { + "host": { + "type": "string", + "pattern": "^(\\*\\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$" + } + } +} diff --git a/pkg/runtime/schema_parity_test.go b/pkg/runtime/schema_parity_test.go new file mode 100644 index 0000000..81e37d2 --- /dev/null +++ b/pkg/runtime/schema_parity_test.go @@ -0,0 +1,151 @@ +package runtime + +// This file is identical in uigraph-cli (pkg/runtime) and uigraph-sandbox +// (internal/runtime), as are schema/runtime.schema.json and testdata/schema/. +// It fails in either repo if its Go types, validation patterns or parser +// drift from the shared JSON Schema and fixtures. Edit the CLI's copy first +// (it owns the schema), then copy all three to the sandbox. + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "slices" + "sort" + "strings" + "testing" +) + +type schemaNode struct { + Type string `json:"type"` + Properties map[string]*schemaNode `json:"properties"` + AdditionalProperties json.RawMessage `json:"additionalProperties"` + Items *schemaNode `json:"items"` + Ref string `json:"$ref"` + Pattern string `json:"pattern"` + PropertyNames *schemaNode `json:"propertyNames"` + Required []string `json:"required"` + Defs map[string]*schemaNode `json:"$defs"` +} + +func loadSchema(t *testing.T) *schemaNode { + t.Helper() + b, err := os.ReadFile("schema/runtime.schema.json") + if err != nil { + t.Fatal(err) + } + var s schemaNode + if err := json.Unmarshal(b, &s); err != nil { + t.Fatal(err) + } + return &s +} + +// yamlFields maps a struct's YAML names to their types. +func yamlFields(t reflect.Type) map[string]reflect.Type { + out := map[string]reflect.Type{} + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + name, _, _ := strings.Cut(f.Tag.Get("yaml"), ",") + if name != "" && name != "-" { + out[name] = f.Type + } + } + return out +} + +func keys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// compareStruct checks that a schema object and a Go struct have the same +// fields, recursively, and that the schema rejects unknown keys as the +// parser does. +func compareStruct(t *testing.T, path string, s *schemaNode, typ reflect.Type) { + t.Helper() + if s.Type != "object" || string(s.AdditionalProperties) != "false" { + t.Errorf("%s: schema must be an object with additionalProperties false", path) + } + fields := yamlFields(typ) + if got, want := keys(s.Properties), keys(fields); !slices.Equal(got, want) { + t.Errorf("%s: schema properties %v, Go fields %v", path, got, want) + return + } + for name, ft := range fields { + p := s.Properties[name] + for ft.Kind() == reflect.Pointer { + ft = ft.Elem() + } + switch { + case ft.Kind() == reflect.Struct: + compareStruct(t, path+"."+name, p, ft) + case ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Struct: + if p.Type != "array" || p.Items == nil { + t.Errorf("%s.%s: want an array schema", path, name) + continue + } + compareStruct(t, path+"."+name+"[]", p.Items, ft.Elem()) + case ft.Kind() == reflect.Slice: + if p.Type != "array" { + t.Errorf("%s.%s: Go list, schema %q", path, name, p.Type) + } + case ft.Kind() == reflect.Map: + if p.Type != "object" { + t.Errorf("%s.%s: Go map, schema %q", path, name, p.Type) + } + case ft.Kind() == reflect.String: + if p.Type != "string" { + t.Errorf("%s.%s: Go string, schema %q", path, name, p.Type) + } + } + } +} + +func TestSchemaMatchesTypes(t *testing.T) { + compareStruct(t, "runtime", loadSchema(t), reflect.TypeOf(Runtime{})) +} + +func TestSchemaPatternsMatchValidation(t *testing.T) { + s := loadSchema(t) + for name, c := range map[string]struct{ schema, goRE string }{ + "image": {s.Properties["image"].Pattern, imageRE.String()}, + "env name": {s.Properties["env"].PropertyNames.Pattern, envKeyRE.String()}, + "secret name": {s.Properties["secrets"].Items.Properties["name"].Pattern, secretNameRE.String()}, + "host": {s.Defs["host"].Pattern, hostRE.String()}, + } { + if c.schema != c.goRE { + t.Errorf("%s: schema %q, Go %q", name, c.schema, c.goRE) + } + } + if got := s.Properties["secrets"].Items.Required; !slices.Equal(got, []string{"name", "egress"}) { + t.Errorf("secret required = %v", got) + } +} + +func fixtures(t *testing.T, kind string) []string { + t.Helper() + files, err := filepath.Glob(filepath.Join("testdata", "schema", kind, "*.yaml")) + if err != nil || len(files) == 0 { + t.Fatalf("no %s fixtures: %v", kind, err) + } + return files +} + +func TestSchemaFixtures(t *testing.T) { + for _, f := range fixtures(t, "valid") { + if _, err := Load(f); err != nil { + t.Errorf("%s rejected: %v", filepath.Base(f), err) + } + } + for _, f := range fixtures(t, "invalid") { + if _, err := Load(f); err == nil { + t.Errorf("%s accepted", filepath.Base(f)) + } + } +} diff --git a/pkg/runtime/testdata/repos/goapi/.env.example b/pkg/runtime/testdata/repos/goapi/.env.example new file mode 100644 index 0000000..b3cd829 --- /dev/null +++ b/pkg/runtime/testdata/repos/goapi/.env.example @@ -0,0 +1,4 @@ +# Copy to .env +PORT=8080 +STRIPE_SECRET_KEY= +SOMETHING_TOKEN= diff --git a/pkg/runtime/testdata/repos/goapi/.github/workflows/ci.yml b/pkg/runtime/testdata/repos/goapi/.github/workflows/ci.yml new file mode 100644 index 0000000..384f149 --- /dev/null +++ b/pkg/runtime/testdata/repos/goapi/.github/workflows/ci.yml @@ -0,0 +1,15 @@ +name: CI +on: [push] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: go test ./... -race -cover + - name: Notify + run: | + curl -fsS -H "Authorization: Bearer ${{ secrets.NOTIFY_TOKEN }}" https://hooks.example.com/ci + - name: Mystery + run: ./scripts/thing.sh + env: + THING_KEY: ${{ secrets.THING_KEY }} diff --git a/pkg/runtime/testdata/repos/goapi/Makefile b/pkg/runtime/testdata/repos/goapi/Makefile new file mode 100644 index 0000000..65e2ebf --- /dev/null +++ b/pkg/runtime/testdata/repos/goapi/Makefile @@ -0,0 +1,15 @@ +TEST_POSTGRES_URL ?= postgres://app:secret@localhost:5432/app?sslmode=disable + +.PHONY: build lint test-unit test-integration + +build: + go build ./... + +lint: + go vet ./... + +test-unit: + go test ./... -count=1 + +test-integration: + TEST_POSTGRES_URL=$(TEST_POSTGRES_URL) go test ./tests/... -count=1 diff --git a/pkg/runtime/testdata/repos/goapi/cmd/api/main.go b/pkg/runtime/testdata/repos/goapi/cmd/api/main.go new file mode 100644 index 0000000..38dd16d --- /dev/null +++ b/pkg/runtime/testdata/repos/goapi/cmd/api/main.go @@ -0,0 +1,3 @@ +package main + +func main() {} diff --git a/pkg/runtime/testdata/repos/goapi/go.mod b/pkg/runtime/testdata/repos/goapi/go.mod new file mode 100644 index 0000000..2e3dfc8 --- /dev/null +++ b/pkg/runtime/testdata/repos/goapi/go.mod @@ -0,0 +1,3 @@ +module example.com/goapi + +go 1.26 diff --git a/pkg/runtime/testdata/repos/nodeweb/.github/workflows/release.yml b/pkg/runtime/testdata/repos/nodeweb/.github/workflows/release.yml new file mode 100644 index 0000000..a3ff3e6 --- /dev/null +++ b/pkg/runtime/testdata/repos/nodeweb/.github/workflows/release.yml @@ -0,0 +1,17 @@ +name: Release +on: {release: {types: [published]}} +jobs: + image: + runs-on: ubuntu-latest + steps: + - name: Write npmrc + run: | + { + printf '@acme-private:registry=https://npm.pkg.github.com\n' + printf '//npm.pkg.github.com/:_authToken=%s\n' \ + "${{ secrets.PACKAGES_READ_TOKEN }}" + } > "$RUNNER_TEMP/npmrc" + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/pkg/runtime/testdata/repos/nodeweb/Dockerfile b/pkg/runtime/testdata/repos/nodeweb/Dockerfile new file mode 100644 index 0000000..1198431 --- /dev/null +++ b/pkg/runtime/testdata/repos/nodeweb/Dockerfile @@ -0,0 +1,3 @@ +FROM nginx:alpine +ENV NODE_OPTIONS=--max-old-space-size=4096 +HEALTHCHECK CMD wget -qO- http://localhost:80/healthz || exit 1 diff --git a/pkg/runtime/testdata/repos/nodeweb/package.json b/pkg/runtime/testdata/repos/nodeweb/package.json new file mode 100644 index 0000000..7ac8ac7 --- /dev/null +++ b/pkg/runtime/testdata/repos/nodeweb/package.json @@ -0,0 +1,12 @@ +{ + "name": "nodeweb", + "packageManager": "pnpm@10.0.0", + "scripts": { + "build": "vite build", + "test": "vitest run", + "lint": "eslint .", + "typecheck": "tsc --noEmit", + "e2e": "playwright test", + "start": "vite preview" + } +} diff --git a/pkg/runtime/testdata/repos/nodeweb/pnpm-lock.yaml b/pkg/runtime/testdata/repos/nodeweb/pnpm-lock.yaml new file mode 100644 index 0000000..b0a073a --- /dev/null +++ b/pkg/runtime/testdata/repos/nodeweb/pnpm-lock.yaml @@ -0,0 +1 @@ +lockfileVersion: '9.0' diff --git a/pkg/runtime/testdata/schema/invalid/bad-env-name.yaml b/pkg/runtime/testdata/schema/invalid/bad-env-name.yaml new file mode 100644 index 0000000..cec94a0 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/bad-env-name.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + env: {1A: v} diff --git a/pkg/runtime/testdata/schema/invalid/bad-host.yaml b/pkg/runtime/testdata/schema/invalid/bad-host.yaml new file mode 100644 index 0000000..b20b803 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/bad-host.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + network: {egress: ['http://a.com/x']} diff --git a/pkg/runtime/testdata/schema/invalid/bad-image.yaml b/pkg/runtime/testdata/schema/invalid/bad-image.yaml new file mode 100644 index 0000000..d7bf80d --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/bad-image.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + image: 'a b' diff --git a/pkg/runtime/testdata/schema/invalid/empty-setup.yaml b/pkg/runtime/testdata/schema/invalid/empty-setup.yaml new file mode 100644 index 0000000..772f676 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/empty-setup.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + setup: [""] diff --git a/pkg/runtime/testdata/schema/invalid/multiline-env.yaml b/pkg/runtime/testdata/schema/invalid/multiline-env.yaml new file mode 100644 index 0000000..7951d45 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/multiline-env.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + env: {A: "x\ny"} diff --git a/pkg/runtime/testdata/schema/invalid/no-runtime.yaml b/pkg/runtime/testdata/schema/invalid/no-runtime.yaml new file mode 100644 index 0000000..919af0b --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/no-runtime.yaml @@ -0,0 +1 @@ +service: x diff --git a/pkg/runtime/testdata/schema/invalid/no-service.yaml b/pkg/runtime/testdata/schema/invalid/no-service.yaml new file mode 100644 index 0000000..c0b8e1f --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/no-service.yaml @@ -0,0 +1,2 @@ +runtime: + setup: [a] diff --git a/pkg/runtime/testdata/schema/invalid/secret-in-env.yaml b/pkg/runtime/testdata/schema/invalid/secret-in-env.yaml new file mode 100644 index 0000000..7aa810e --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/secret-in-env.yaml @@ -0,0 +1,4 @@ +service: x +runtime: + env: {K: v} + secrets: [{name: K, egress: [a.com]}] diff --git a/pkg/runtime/testdata/schema/invalid/secret-lowercase.yaml b/pkg/runtime/testdata/schema/invalid/secret-lowercase.yaml new file mode 100644 index 0000000..c4468da --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/secret-lowercase.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + secrets: [{name: k, egress: [a.com]}] diff --git a/pkg/runtime/testdata/schema/invalid/secret-no-egress.yaml b/pkg/runtime/testdata/schema/invalid/secret-no-egress.yaml new file mode 100644 index 0000000..e30132d --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/secret-no-egress.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + secrets: [{name: K}] diff --git a/pkg/runtime/testdata/schema/invalid/secret-twice.yaml b/pkg/runtime/testdata/schema/invalid/secret-twice.yaml new file mode 100644 index 0000000..31949f5 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/secret-twice.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + secrets: [{name: K, egress: [a.com]}, {name: K, egress: [b.com]}] diff --git a/pkg/runtime/testdata/schema/invalid/unknown-key.yaml b/pkg/runtime/testdata/schema/invalid/unknown-key.yaml new file mode 100644 index 0000000..998e589 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/unknown-key.yaml @@ -0,0 +1,3 @@ +service: x +runtime: + setpu: [a] diff --git a/pkg/runtime/testdata/schema/invalid/unknown-nested-key.yaml b/pkg/runtime/testdata/schema/invalid/unknown-nested-key.yaml new file mode 100644 index 0000000..0a317f6 --- /dev/null +++ b/pkg/runtime/testdata/schema/invalid/unknown-nested-key.yaml @@ -0,0 +1,4 @@ +service: x +runtime: + verify: + tests: {unit: a} diff --git a/pkg/runtime/testdata/schema/valid/design-example.yaml b/pkg/runtime/testdata/schema/valid/design-example.yaml new file mode 100644 index 0000000..84f2c91 --- /dev/null +++ b/pkg/runtime/testdata/schema/valid/design-example.yaml @@ -0,0 +1,29 @@ +# The design's billing example (design.md, "Runtime profiles and secrets"), +# plus image. Other tools' sections are ignored. +service: billing +api: {spec: openapi.yaml} +runtime: + image: uigraph-sandbox-base:dev + stack: [go, docker] + setup: [make deps] + dependencies: + compose: docker-compose.test.yml + services: [postgres, redis] + env: + DATABASE_URL: postgres://test:test@localhost:5432/billing + secrets: + - name: STRIPE_TEST_KEY + purpose: integration tests against Stripe test mode + egress: [api.stripe.com] + needed_for: [test:integration] + network: + internal: [] + run: make run + health: http://localhost:8080/healthz + verify: + build: make build + lint: make lint + test: + unit: go test ./... + integration: make test-integration + known_flaky: [TestWebhookRetry] diff --git a/pkg/runtime/testdata/schema/valid/sandbox-sample-service.yaml b/pkg/runtime/testdata/schema/valid/sandbox-sample-service.yaml new file mode 100644 index 0000000..04383cb --- /dev/null +++ b/pkg/runtime/testdata/schema/valid/sandbox-sample-service.yaml @@ -0,0 +1,17 @@ +# A tiny Go + TypeScript service used to prove a service builds inside its +# sandbox image (S2). Dependencies are installed by setup at image build time; +# build and tests then run with no network. +service: sample +runtime: + stack: [go, node] + setup: + - go build ./... && go test -count=1 -run XXX ./... + - cd web && pnpm install --frozen-lockfile + env: + APP_ENV: test + run: go run . + health: http://localhost:8080/healthz + verify: + build: go build ./... && cd web && pnpm run build + test: + unit: go test -count=1 ./... && cd web && pnpm test diff --git a/pkg/runtime/testdata/schema/valid/service-object.yaml b/pkg/runtime/testdata/schema/valid/service-object.yaml new file mode 100644 index 0000000..e568366 --- /dev/null +++ b/pkg/runtime/testdata/schema/valid/service-object.yaml @@ -0,0 +1,18 @@ +# .uigraph.yaml as the CLI writes it: service is an object with a name. +version: 1 +service: + name: billing + category: Backend + description: Billing + repository: {provider: github, url: https://github.com/acme/billing} + ownership: {team: payments} +runtime: + stack: [node] + setup: [pnpm install --frozen-lockfile] + secrets: + - name: NPM_TOKEN + egress: [npm.pkg.github.com, "*.stripe.com:443"] + network: + egress: [registry.npmjs.org] + verify: + test: {unit: pnpm test}