| 1 | package forge |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "net/http/cookiejar" |
| 12 | "net/http/httptest" |
| 13 | "net/url" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 21 | ) |
| 22 | |
| 23 | type descriptionRoundTrip func(*http.Request) (*http.Response, error) |
| 24 | |
| 25 | func (f descriptionRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 26 | |
| 27 | func descriptionServer(t *testing.T, h http.HandlerFunc) *http.Client { |
| 28 | t.Helper() |
| 29 | s := httptest.NewUnstartedServer(h) |
| 30 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 31 | must(t, err) |
| 32 | must(t, s.Listener.Close()) |
| 33 | s.Listener = listener |
| 34 | s.Start() |
| 35 | t.Cleanup(s.Close) |
| 36 | target, err := url.Parse(s.URL) |
| 37 | must(t, err) |
| 38 | transport := &http.Transport{Proxy: nil} |
| 39 | t.Cleanup(transport.CloseIdleConnections) |
| 40 | return &http.Client{Transport: descriptionRoundTrip(func(r *http.Request) (*http.Response, error) { |
| 41 | deadline, ok := r.Context().Deadline() |
| 42 | if !ok || time.Until(deadline) > 15*time.Second { |
| 43 | t.Error("missing bounded GET deadline") |
| 44 | } |
| 45 | if r.URL.Scheme != "https" || r.URL.Host != "amadan.net" { |
| 46 | t.Error("wrong production origin") |
| 47 | } |
| 48 | local := r.Clone(r.Context()) |
| 49 | u := *r.URL |
| 50 | u.Scheme, u.Host = target.Scheme, target.Host |
| 51 | local.URL = &u |
| 52 | return transport.RoundTrip(local) |
| 53 | })} |
| 54 | } |
| 55 | |
| 56 | func descriptionResponse(body, agent string) map[string]any { |
| 57 | c := DescriptionChannels{Description: body, Human: "Paul", Summary: "Fixed\nchecked", Notes: "✓"} |
| 58 | 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)} |
| 59 | } |
| 60 | |
| 61 | func TestAmadanDescriptionLengthHash(t *testing.T) { |
| 62 | for _, tc := range []struct { |
| 63 | name string |
| 64 | c DescriptionChannels |
| 65 | want string |
| 66 | }{ |
| 67 | {"empty", DescriptionChannels{}, "sha256:66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"}, |
| 68 | {"utf8", DescriptionChannels{"Equipo café\n", "Paul", "Fixed\nchecked", "✓"}, "sha256:ac030712c32422e57053ff69f80ec87d1efdff87a000e9a08dd3e711d0995a88"}, |
| 69 | } { |
| 70 | t.Run(tc.name, func(t *testing.T) { |
| 71 | if got := DescriptionContentHash(tc.c); got != tc.want { |
| 72 | t.Fatalf("hash = %s, want %s", got, tc.want) |
| 73 | } |
| 74 | }) |
| 75 | } |
| 76 | if DescriptionContentHash(DescriptionChannels{Description: "ab", Human: "c"}) == DescriptionContentHash(DescriptionChannels{Description: "a", Human: "bc"}) { |
| 77 | t.Fatal("channel boundaries lost") |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | func TestAmadanDescriptionReadback(t *testing.T) { |
| 82 | cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| 83 | body := " Equipo café\n unconfined; approved beyond profile\n" |
| 84 | 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"} { |
| 85 | t.Run(name, func(t *testing.T) { |
| 86 | requests := 0 |
| 87 | client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { |
| 88 | requests++ |
| 89 | if r.URL.Path == "/redirected" { |
| 90 | t.Error("followed redirect with credentials") |
| 91 | w.WriteHeader(500) |
| 92 | return |
| 93 | } |
| 94 | if r.Header.Get("Cookie") != "" { |
| 95 | t.Error("forwarded unrelated client credentials") |
| 96 | } |
| 97 | if r.Method != "GET" || r.URL.EscapedPath() != "/api/v1/repos/oficina/equipo/branches/review%2Ftrial/description" || r.Header.Get("Authorization") != "Bearer fake-only" { |
| 98 | t.Errorf("wrong request: %s %s", r.Method, r.URL.EscapedPath()) |
| 99 | } |
| 100 | response := descriptionResponse(body, cred.Agent) |
| 101 | switch name { |
| 102 | case "optional_agent": |
| 103 | delete(response, "agent") |
| 104 | case "tamper": |
| 105 | response["description"] = body + "changed" |
| 106 | case "wrong_hash": |
| 107 | response["content_hash"] = "sha256:" + strings.Repeat("0", 64) |
| 108 | case "wrong_agent": |
| 109 | response["by"] = "other~owner@example.com" |
| 110 | case "bad_metadata": |
| 111 | response["agent"] = "not structured" |
| 112 | case "empty": |
| 113 | response["empty"] = true |
| 114 | case "invalid_utf8": |
| 115 | response["description"] = "�" |
| 116 | response["content_hash"] = DescriptionContentHash(DescriptionChannels{"�", "Paul", "Fixed\nchecked", "✓"}) |
| 117 | raw, _ := json.Marshal(response) |
| 118 | _, _ = w.Write(bytes.Replace(raw, []byte("�"), []byte{0xff}, 1)) |
| 119 | return |
| 120 | case "malformed_at": |
| 121 | response["at"] = "invalid" |
| 122 | case "malformed": |
| 123 | _, _ = io.WriteString(w, "{") |
| 124 | return |
| 125 | case "trailing": |
| 126 | _, _ = io.WriteString(w, "{}{}") |
| 127 | return |
| 128 | case "oversized": |
| 129 | response["padding"] = strings.Repeat("x", 1<<20) |
| 130 | case "redirect": |
| 131 | http.Redirect(w, r, "/redirected", http.StatusFound) |
| 132 | return |
| 133 | case "auth": |
| 134 | w.WriteHeader(401) |
| 135 | return |
| 136 | case "timeout": |
| 137 | <-r.Context().Done() |
| 138 | return |
| 139 | } |
| 140 | if name == "reordered" { |
| 141 | raw, _ := json.Marshal(response) |
| 142 | // Whitespace and field order are not part of the content hash. |
| 143 | _, _ = io.WriteString(w, "{\"extra\":true, "+string(raw[1:])) |
| 144 | return |
| 145 | } |
| 146 | _ = json.NewEncoder(w).Encode(response) |
| 147 | }) |
| 148 | jar, err := cookiejar.New(nil) |
| 149 | must(t, err) |
| 150 | origin, _ := url.Parse("https://amadan.net") |
| 151 | jar.SetCookies(origin, []*http.Cookie{{Name: "person", Value: "fake-cookie"}}) |
| 152 | client.Jar = jar |
| 153 | callCtx := context.Background() |
| 154 | if name == "timeout" { |
| 155 | var cancel context.CancelFunc |
| 156 | callCtx, cancel = context.WithTimeout(callCtx, 30*time.Millisecond) |
| 157 | defer cancel() |
| 158 | } |
| 159 | got, err := ReadBranchDescription(callCtx, client, cred, "amadan.net/oficina/equipo", "review/trial") |
| 160 | if name != "valid" && name != "optional_agent" && name != "reordered" { |
| 161 | if err == nil { |
| 162 | t.Fatalf("accepted %s", name) |
| 163 | } |
| 164 | return |
| 165 | } |
| 166 | must(t, err) |
| 167 | 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) { |
| 168 | t.Fatalf("lost verbatim content or metadata: %+v", got) |
| 169 | } |
| 170 | if name != "optional_agent" && !strings.Contains(string(got.AgentMetadata), "operator") { |
| 171 | t.Fatal("lost structured agent metadata") |
| 172 | } |
| 173 | if requests != 1 { |
| 174 | t.Fatal("unexpected request count", requests) |
| 175 | } |
| 176 | }) |
| 177 | } |
| 178 | invalidClient := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { |
| 179 | t.Error("invalid target reached HTTP") |
| 180 | w.WriteHeader(http.StatusBadRequest) |
| 181 | }) |
| 182 | for _, ref := range []string{"refs/heads/review/trial", "refs/tags/x", "../x", "review//trial", "-flag"} { |
| 183 | if _, err := ReadBranchDescription(context.Background(), invalidClient, cred, "amadan.net/oficina/equipo", ref); err == nil { |
| 184 | t.Fatal("accepted invalid ref", ref) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func TestAmadanDescriptionCommand(t *testing.T) { |
| 190 | t.Setenv("PERSON_SECRET", "person-canary") |
| 191 | t.Setenv("AMADAN_HOME", "/must-not-use-person-login") |
| 192 | root := t.TempDir() |
| 193 | command := filepath.Join(root, "describe") |
| 194 | script := `#!/usr/bin/python3 |
| 195 | import json,os,sys,stat |
| 196 | assert sys.argv[1:] == ['branch','describe','oficina/equipo','review/trial','-hub','https://amadan.net','-body','-'] |
| 197 | assert 'PERSON_SECRET' not in os.environ |
| 198 | assert os.environ['HOME'] == '/nonexistent' |
| 199 | home = os.environ['AMADAN_HOME'] |
| 200 | assert home != '/must-not-use-person-login' |
| 201 | assert stat.S_IMODE(os.stat(home).st_mode) == 0o700 |
| 202 | path = home+'/credentials' |
| 203 | assert stat.S_IMODE(os.stat(path).st_mode) == 0o600 |
| 204 | assert json.load(open(path)) == {'https://amadan.net':'fake-only'} |
| 205 | assert sys.stdin.read() == ' Equipo café\n unconfined; approved beyond profile\n' |
| 206 | ` |
| 207 | must(t, os.WriteFile(command, []byte(script), 0700)) |
| 208 | cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| 209 | desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: " Equipo café\n unconfined; approved beyond profile\n"} |
| 210 | desc.Digest = Digest([]byte(desc.Body)) |
| 211 | scratch := filepath.Join(root, "scratch") |
| 212 | must(t, os.Mkdir(scratch, 0700)) |
| 213 | writer := NewCommandDescriptionWriter(command, scratch) |
| 214 | must(t, writer.Set(context.Background(), cred, desc)) |
| 215 | if err := NewCommandDescriptionWriter(command, "relative").Set(context.Background(), cred, desc); !errors.Is(err, team.ErrInvalid) { |
| 216 | t.Fatal("relative scratch accepted", err) |
| 217 | } |
| 218 | if err := NewDescriptionTransport(nil, nil).Set(context.Background(), cred, desc); err != team.ErrNotDispatched { |
| 219 | t.Fatal("missing writer accepted", err) |
| 220 | } |
| 221 | entries, err := os.ReadDir(scratch) |
| 222 | must(t, err) |
| 223 | if len(entries) != 0 { |
| 224 | t.Fatal("credential scratch was retained") |
| 225 | } |
| 226 | for _, name := range []string{"person", "foreign_remote", "missing_token", "repository", "header", "ref", "digest", "agent", "empty", "invalid_utf8", "oversized"} { |
| 227 | t.Run(name, func(t *testing.T) { |
| 228 | c, d := cred, desc |
| 229 | switch name { |
| 230 | case "person": |
| 231 | c.Agent = "owner@example.com" |
| 232 | d.Agent = c.Agent |
| 233 | case "foreign_remote": |
| 234 | c.Remote = "https://evil.example/oficina/equipo" |
| 235 | case "missing_token": |
| 236 | c.Bearer = "" |
| 237 | case "repository": |
| 238 | d.Repository = "amadan.net/../equipo" |
| 239 | c.Remote = "https://" + d.Repository |
| 240 | case "header": |
| 241 | c.Bearer = "fake\r\nInjected: x" |
| 242 | case "ref": |
| 243 | d.Ref = "refs/heads/review/trial" |
| 244 | case "digest": |
| 245 | d.Digest = strings.Repeat("0", 64) |
| 246 | case "agent": |
| 247 | d.Agent = "other~owner@example.com" |
| 248 | case "invalid_utf8": |
| 249 | d.Body = string([]byte{0xff}) |
| 250 | d.Digest = Digest([]byte(d.Body)) |
| 251 | case "oversized": |
| 252 | d.Body = strings.Repeat("x", (1<<20)+1) |
| 253 | d.Digest = Digest([]byte(d.Body)) |
| 254 | case "empty": |
| 255 | d.Body = "" |
| 256 | d.Digest = Digest(nil) |
| 257 | } |
| 258 | if err := writer.Set(context.Background(), c, d); !errors.Is(err, team.ErrInvalid) { |
| 259 | t.Fatal("invalid write reached command", err) |
| 260 | } |
| 261 | }) |
| 262 | } |
| 263 | 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)) |
| 264 | readLog, writeLog, err := os.Pipe() |
| 265 | must(t, err) |
| 266 | previousOut, previousErr := os.Stdout, os.Stderr |
| 267 | os.Stdout, os.Stderr = writeLog, writeLog |
| 268 | commandErr := writer.Set(context.Background(), cred, desc) |
| 269 | os.Stdout, os.Stderr = previousOut, previousErr |
| 270 | must(t, writeLog.Close()) |
| 271 | captured, err := io.ReadAll(readLog) |
| 272 | must(t, readLog.Close()) |
| 273 | must(t, err) |
| 274 | if commandErr != team.ErrUncertain || len(captured) != 0 { |
| 275 | t.Fatal("command output escaped error boundary") |
| 276 | } |
| 277 | must(t, os.WriteFile(command, []byte("#!/usr/bin/python3\nimport time\ntime.sleep(2)\n"), 0700)) |
| 278 | bounded, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) |
| 279 | defer cancel() |
| 280 | started := time.Now() |
| 281 | if err := writer.Set(bounded, cred, desc); err != team.ErrUncertain || time.Since(started) > time.Second { |
| 282 | t.Fatal("command did not respect timeout", err) |
| 283 | } |
| 284 | entries, err = os.ReadDir(scratch) |
| 285 | must(t, err) |
| 286 | if len(entries) != 0 { |
| 287 | t.Fatal("failed command retained credentials") |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestAmadanDescriptionNotDispatched(t *testing.T) { |
| 292 | root := t.TempDir() |
| 293 | command := filepath.Join(root, "command") |
| 294 | must(t, os.WriteFile(command, []byte("#!/bin/sh\nexit 1\n"), 0700)) |
| 295 | cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| 296 | desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: "body"} |
| 297 | desc.Digest = Digest([]byte(desc.Body)) |
| 298 | for _, mode := range []string{"validation", "relative_path", "unclean_path", "missing_command", "not_executable", "scratch", "cancelled", "started", "missing_writer"} { |
| 299 | t.Run(mode, func(t *testing.T) { |
| 300 | path, scratch, d := command, root, desc |
| 301 | ctx, cancel := context.WithCancel(context.Background()) |
| 302 | defer cancel() |
| 303 | switch mode { |
| 304 | case "validation": |
| 305 | d.Digest = "invalid" |
| 306 | case "relative_path": |
| 307 | path = "sh" |
| 308 | case "unclean_path": |
| 309 | path = root + "/./command" |
| 310 | case "missing_command": |
| 311 | path = filepath.Join(root, "missing") |
| 312 | case "not_executable": |
| 313 | path = filepath.Join(root, "not-executable") |
| 314 | must(t, os.WriteFile(path, []byte("exit 1"), 0600)) |
| 315 | case "scratch": |
| 316 | scratch = filepath.Join(root, "missing-scratch") |
| 317 | case "cancelled": |
| 318 | cancel() |
| 319 | } |
| 320 | var writer DescriptionWriter = NewCommandDescriptionWriter(path, scratch) |
| 321 | if mode == "missing_writer" { |
| 322 | writer = NewDescriptionTransport(nil, nil) |
| 323 | } |
| 324 | err := writer.Set(ctx, cred, d) |
| 325 | if mode == "started" { |
| 326 | if !errors.Is(err, team.ErrUncertain) || errors.Is(err, team.ErrNotDispatched) { |
| 327 | t.Fatalf("started command declared safe to retry: %v", err) |
| 328 | } |
| 329 | } else if !errors.Is(err, team.ErrNotDispatched) { |
| 330 | t.Fatalf("pre-start failure must allow retry: %v", err) |
| 331 | } |
| 332 | }) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | func TestDescriptionIgnoresDefaultProxyClient(t *testing.T) { |
| 337 | old := http.DefaultClient |
| 338 | defer func() { http.DefaultClient = old }() |
| 339 | called := false |
| 340 | http.DefaultClient = &http.Client{Transport: descriptionRoundTrip(func(*http.Request) (*http.Response, error) { |
| 341 | called = true |
| 342 | return nil, errors.New("default proxy reached") |
| 343 | })} |
| 344 | ctx, cancel := context.WithCancel(context.Background()) |
| 345 | cancel() |
| 346 | _, _ = 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") |
| 347 | if called { |
| 348 | t.Fatal("description used ambient proxy client") |
| 349 | } |
| 350 | } |
| 351 | |