package forge import ( "bytes" "context" "encoding/json" "errors" "io" "net" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" ) type descriptionRoundTrip func(*http.Request) (*http.Response, error) func (f descriptionRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func descriptionServer(t *testing.T, h http.HandlerFunc) *http.Client { t.Helper() s := httptest.NewUnstartedServer(h) listener, err := net.Listen("tcp", "127.0.0.1:0") must(t, err) must(t, s.Listener.Close()) s.Listener = listener s.Start() t.Cleanup(s.Close) target, err := url.Parse(s.URL) must(t, err) transport := &http.Transport{Proxy: nil} t.Cleanup(transport.CloseIdleConnections) return &http.Client{Transport: descriptionRoundTrip(func(r *http.Request) (*http.Response, error) { deadline, ok := r.Context().Deadline() if !ok || time.Until(deadline) > 15*time.Second { t.Error("missing bounded GET deadline") } if r.URL.Scheme != "https" || r.URL.Host != "amadan.net" { t.Error("wrong production origin") } local := r.Clone(r.Context()) u := *r.URL u.Scheme, u.Host = target.Scheme, target.Host local.URL = &u return transport.RoundTrip(local) })} } func descriptionResponse(body, agent string) map[string]any { c := DescriptionChannels{Description: body, Human: "Paul", Summary: "Fixed\nchecked", Notes: "✓"} return map[string]any{"description": c.Description, "human": c.Human, "summary": c.Summary, "notes": c.Notes, "by": agent, "at": 123, "agent": map[string]any{"name": "equipo", "operator": "owner@example.com"}, "empty": false, "content_hash": DescriptionContentHash(c)} } func TestAmadanDescriptionLengthHash(t *testing.T) { for _, tc := range []struct { name string c DescriptionChannels want string }{ {"empty", DescriptionChannels{}, "sha256:66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"}, {"utf8", DescriptionChannels{"Equipo café\n", "Paul", "Fixed\nchecked", "✓"}, "sha256:ac030712c32422e57053ff69f80ec87d1efdff87a000e9a08dd3e711d0995a88"}, } { t.Run(tc.name, func(t *testing.T) { if got := DescriptionContentHash(tc.c); got != tc.want { t.Fatalf("hash = %s, want %s", got, tc.want) } }) } if DescriptionContentHash(DescriptionChannels{Description: "ab", Human: "c"}) == DescriptionContentHash(DescriptionChannels{Description: "a", Human: "bc"}) { t.Fatal("channel boundaries lost") } } func TestAmadanDescriptionReadback(t *testing.T) { cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} body := " Equipo café\n unconfined; approved beyond profile\n" for _, name := range []string{"valid", "optional_agent", "reordered", "tamper", "wrong_hash", "wrong_agent", "bad_metadata", "empty", "invalid_utf8", "malformed", "malformed_at", "trailing", "oversized", "redirect", "auth", "timeout"} { t.Run(name, func(t *testing.T) { requests := 0 client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { requests++ if r.URL.Path == "/redirected" { t.Error("followed redirect with credentials") w.WriteHeader(500) return } if r.Header.Get("Cookie") != "" { t.Error("forwarded unrelated client credentials") } if r.Method != "GET" || r.URL.EscapedPath() != "/api/v1/repos/oficina/equipo/branches/review%2Ftrial/description" || r.Header.Get("Authorization") != "Bearer fake-only" { t.Errorf("wrong request: %s %s", r.Method, r.URL.EscapedPath()) } response := descriptionResponse(body, cred.Agent) switch name { case "optional_agent": delete(response, "agent") case "tamper": response["description"] = body + "changed" case "wrong_hash": response["content_hash"] = "sha256:" + strings.Repeat("0", 64) case "wrong_agent": response["by"] = "other~owner@example.com" case "bad_metadata": response["agent"] = "not structured" case "empty": response["empty"] = true case "invalid_utf8": response["description"] = "�" response["content_hash"] = DescriptionContentHash(DescriptionChannels{"�", "Paul", "Fixed\nchecked", "✓"}) raw, _ := json.Marshal(response) _, _ = w.Write(bytes.Replace(raw, []byte("�"), []byte{0xff}, 1)) return case "malformed_at": response["at"] = "invalid" case "malformed": _, _ = io.WriteString(w, "{") return case "trailing": _, _ = io.WriteString(w, "{}{}") return case "oversized": response["padding"] = strings.Repeat("x", 1<<20) case "redirect": http.Redirect(w, r, "/redirected", http.StatusFound) return case "auth": w.WriteHeader(401) return case "timeout": <-r.Context().Done() return } if name == "reordered" { raw, _ := json.Marshal(response) // Whitespace and field order are not part of the content hash. _, _ = io.WriteString(w, "{\"extra\":true, "+string(raw[1:])) return } _ = json.NewEncoder(w).Encode(response) }) jar, err := cookiejar.New(nil) must(t, err) origin, _ := url.Parse("https://amadan.net") jar.SetCookies(origin, []*http.Cookie{{Name: "person", Value: "fake-cookie"}}) client.Jar = jar callCtx := context.Background() if name == "timeout" { var cancel context.CancelFunc callCtx, cancel = context.WithTimeout(callCtx, 30*time.Millisecond) defer cancel() } got, err := ReadBranchDescription(callCtx, client, cred, "amadan.net/oficina/equipo", "review/trial") if name != "valid" && name != "optional_agent" && name != "reordered" { if err == nil { t.Fatalf("accepted %s", name) } return } must(t, err) if got.Body != body || got.Digest != team.ContentDigest([]byte(body)) || got.Agent != cred.Agent || got.Ref != "review/trial" || got.At != 123 || got.Channels.Notes != "✓" || got.ContentHash != DescriptionContentHash(got.Channels) { t.Fatalf("lost verbatim content or metadata: %+v", got) } if name != "optional_agent" && !strings.Contains(string(got.AgentMetadata), "operator") { t.Fatal("lost structured agent metadata") } if requests != 1 { t.Fatal("unexpected request count", requests) } }) } invalidClient := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { t.Error("invalid target reached HTTP") w.WriteHeader(http.StatusBadRequest) }) for _, ref := range []string{"refs/heads/review/trial", "refs/tags/x", "../x", "review//trial", "-flag"} { if _, err := ReadBranchDescription(context.Background(), invalidClient, cred, "amadan.net/oficina/equipo", ref); err == nil { t.Fatal("accepted invalid ref", ref) } } } func TestAmadanDescriptionCommand(t *testing.T) { t.Setenv("PERSON_SECRET", "person-canary") t.Setenv("AMADAN_HOME", "/must-not-use-person-login") root := t.TempDir() command := filepath.Join(root, "describe") script := `#!/usr/bin/python3 import json,os,sys,stat assert sys.argv[1:] == ['branch','describe','oficina/equipo','review/trial','-hub','https://amadan.net','-body','-'] assert 'PERSON_SECRET' not in os.environ assert os.environ['HOME'] == '/nonexistent' home = os.environ['AMADAN_HOME'] assert home != '/must-not-use-person-login' assert stat.S_IMODE(os.stat(home).st_mode) == 0o700 path = home+'/credentials' assert stat.S_IMODE(os.stat(path).st_mode) == 0o600 assert json.load(open(path)) == {'https://amadan.net':'fake-only'} assert sys.stdin.read() == ' Equipo café\n unconfined; approved beyond profile\n' ` must(t, os.WriteFile(command, []byte(script), 0700)) cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: " Equipo café\n unconfined; approved beyond profile\n"} desc.Digest = Digest([]byte(desc.Body)) scratch := filepath.Join(root, "scratch") must(t, os.Mkdir(scratch, 0700)) writer := NewCommandDescriptionWriter(command, scratch) must(t, writer.Set(context.Background(), cred, desc)) if err := NewCommandDescriptionWriter(command, "relative").Set(context.Background(), cred, desc); !errors.Is(err, team.ErrInvalid) { t.Fatal("relative scratch accepted", err) } if err := NewDescriptionTransport(nil, nil).Set(context.Background(), cred, desc); err != team.ErrNotDispatched { t.Fatal("missing writer accepted", err) } entries, err := os.ReadDir(scratch) must(t, err) if len(entries) != 0 { t.Fatal("credential scratch was retained") } for _, name := range []string{"person", "foreign_remote", "missing_token", "repository", "header", "ref", "digest", "agent", "empty", "invalid_utf8", "oversized"} { t.Run(name, func(t *testing.T) { c, d := cred, desc switch name { case "person": c.Agent = "owner@example.com" d.Agent = c.Agent case "foreign_remote": c.Remote = "https://evil.example/oficina/equipo" case "missing_token": c.Bearer = "" case "repository": d.Repository = "amadan.net/../equipo" c.Remote = "https://" + d.Repository case "header": c.Bearer = "fake\r\nInjected: x" case "ref": d.Ref = "refs/heads/review/trial" case "digest": d.Digest = strings.Repeat("0", 64) case "agent": d.Agent = "other~owner@example.com" case "invalid_utf8": d.Body = string([]byte{0xff}) d.Digest = Digest([]byte(d.Body)) case "oversized": d.Body = strings.Repeat("x", (1<<20)+1) d.Digest = Digest([]byte(d.Body)) case "empty": d.Body = "" d.Digest = Digest(nil) } if err := writer.Set(context.Background(), c, d); !errors.Is(err, team.ErrInvalid) { t.Fatal("invalid write reached command", err) } }) } must(t, os.WriteFile(command, []byte("#!/usr/bin/python3\nimport sys\nprint('fake-only',file=sys.stderr)\nprint('fake-only')\nsys.exit(1)\n"), 0700)) readLog, writeLog, err := os.Pipe() must(t, err) previousOut, previousErr := os.Stdout, os.Stderr os.Stdout, os.Stderr = writeLog, writeLog commandErr := writer.Set(context.Background(), cred, desc) os.Stdout, os.Stderr = previousOut, previousErr must(t, writeLog.Close()) captured, err := io.ReadAll(readLog) must(t, readLog.Close()) must(t, err) if commandErr != team.ErrUncertain || len(captured) != 0 { t.Fatal("command output escaped error boundary") } must(t, os.WriteFile(command, []byte("#!/usr/bin/python3\nimport time\ntime.sleep(2)\n"), 0700)) bounded, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() started := time.Now() if err := writer.Set(bounded, cred, desc); err != team.ErrUncertain || time.Since(started) > time.Second { t.Fatal("command did not respect timeout", err) } entries, err = os.ReadDir(scratch) must(t, err) if len(entries) != 0 { t.Fatal("failed command retained credentials") } } func TestAmadanDescriptionNotDispatched(t *testing.T) { root := t.TempDir() command := filepath.Join(root, "command") must(t, os.WriteFile(command, []byte("#!/bin/sh\nexit 1\n"), 0700)) cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: "body"} desc.Digest = Digest([]byte(desc.Body)) for _, mode := range []string{"validation", "relative_path", "unclean_path", "missing_command", "not_executable", "scratch", "cancelled", "started", "missing_writer"} { t.Run(mode, func(t *testing.T) { path, scratch, d := command, root, desc ctx, cancel := context.WithCancel(context.Background()) defer cancel() switch mode { case "validation": d.Digest = "invalid" case "relative_path": path = "sh" case "unclean_path": path = root + "/./command" case "missing_command": path = filepath.Join(root, "missing") case "not_executable": path = filepath.Join(root, "not-executable") must(t, os.WriteFile(path, []byte("exit 1"), 0600)) case "scratch": scratch = filepath.Join(root, "missing-scratch") case "cancelled": cancel() } var writer DescriptionWriter = NewCommandDescriptionWriter(path, scratch) if mode == "missing_writer" { writer = NewDescriptionTransport(nil, nil) } err := writer.Set(ctx, cred, d) if mode == "started" { if !errors.Is(err, team.ErrUncertain) || errors.Is(err, team.ErrNotDispatched) { t.Fatalf("started command declared safe to retry: %v", err) } } else if !errors.Is(err, team.ErrNotDispatched) { t.Fatalf("pre-start failure must allow retry: %v", err) } }) } } func TestDescriptionIgnoresDefaultProxyClient(t *testing.T) { old := http.DefaultClient defer func() { http.DefaultClient = old }() called := false http.DefaultClient = &http.Client{Transport: descriptionRoundTrip(func(*http.Request) (*http.Response, error) { called = true return nil, errors.New("default proxy reached") })} ctx, cancel := context.WithCancel(context.Background()) cancel() _, _ = ReadBranchDescription(ctx, nil, Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"}, "amadan.net/oficina/equipo", "heads/fix") if called { t.Fatal("description used ambient proxy client") } }