| 1 | package assist |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "os" |
| 11 | "strings" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/rastrillo/rastrillo/budget" |
| 17 | ) |
| 18 | |
| 19 | func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| 20 | |
| 21 | type fake struct { |
| 22 | name string |
| 23 | ops map[string][]Operation |
| 24 | err error |
| 25 | lists atomic.Int32 |
| 26 | got struct { |
| 27 | person, op, key string |
| 28 | input json.RawMessage |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func (f *fake) Name() string { return f.name } |
| 33 | func (f *fake) List(_ context.Context, person string) ([]Operation, error) { |
| 34 | f.lists.Add(1) |
| 35 | if f.err != nil { |
| 36 | return nil, f.err |
| 37 | } |
| 38 | return f.ops[person], nil |
| 39 | } |
| 40 | func (f *fake) Invoke(_ context.Context, person, op string, in json.RawMessage, key string) (json.RawMessage, error) { |
| 41 | f.got.person, f.got.op, f.got.key, f.got.input = person, op, key, in |
| 42 | return json.RawMessage(`{"ok":true}`), nil |
| 43 | } |
| 44 | |
| 45 | func TestLookGroupsByApp(t *testing.T) { |
| 46 | long := strings.Repeat("x", 300) |
| 47 | a := &fake{name: "base", ops: map[string][]Operation{"p": { |
| 48 | {Name: "base_apps", App: "Apps", Description: "List the apps.\nSecond line.", ReadOnly: true}, |
| 49 | {Name: "base_people", App: "Apps", Description: long, ReadOnly: true}, |
| 50 | {Name: "base_settings", App: "Settings", Description: "Change settings"}, |
| 51 | }}} |
| 52 | b := &fake{name: "team", ops: map[string][]Operation{"p": {{Name: "team_request", App: "Team", Description: "Hand over"}}}} |
| 53 | bad := &fake{name: "broken", err: errors.New("down")} |
| 54 | r := NewRegistry(a, bad, b) |
| 55 | out, err := r.Look(context.Background(), "p", "") |
| 56 | if err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | for _, want := range []string{"Apps (base)\n- base_apps: List the apps.\n", "Settings (base)\n", "Team (team)\n- team_request: Hand over"} { |
| 60 | if !strings.Contains(out, want) { |
| 61 | t.Errorf("missing %q in:\n%s", want, out) |
| 62 | } |
| 63 | } |
| 64 | if strings.Contains(out, "Second line") || strings.Contains(out, strings.Repeat("x", 161)) || !strings.Contains(out, "- base_people: "+strings.Repeat("x", 160)+"\n") { |
| 65 | t.Errorf("description not cut to first line and 160 chars:\n%s", out) |
| 66 | } |
| 67 | if strings.Contains(out, "broken") { |
| 68 | t.Errorf("failing provider listed:\n%s", out) |
| 69 | } |
| 70 | out, _ = r.Look(context.Background(), "p", "SETTINGS") |
| 71 | if !strings.Contains(out, "base_settings") || strings.Contains(out, "team_request") { |
| 72 | t.Errorf("query filter wrong:\n%s", out) |
| 73 | } |
| 74 | out, _ = r.Look(context.Background(), "p", "hand OVER") |
| 75 | if !strings.Contains(out, "team_request") || strings.Contains(out, "base_apps") { |
| 76 | t.Errorf("description filter wrong:\n%s", out) |
| 77 | } |
| 78 | many := make([]Operation, 250) |
| 79 | for i := range many { |
| 80 | many[i] = Operation{Name: "op" + string(rune('a'+i/26)) + string(rune('A'+i%26)), App: "Many", ReadOnly: true} |
| 81 | } |
| 82 | r = NewRegistry(&fake{name: "m", ops: map[string][]Operation{"p": many}}) |
| 83 | out, _ = r.Look(context.Background(), "p", "") |
| 84 | if n := strings.Count(out, "\n- "); n != 200 { |
| 85 | t.Errorf("want 200 operations, got %d", n) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func TestRegistryCachesLists(t *testing.T) { |
| 90 | f := &fake{name: "base", ops: map[string][]Operation{ |
| 91 | "ann": {{Name: "only_ann", App: "A", ReadOnly: true}}, |
| 92 | "bob": {{Name: "only_bob", App: "A", ReadOnly: true}}, |
| 93 | }} |
| 94 | r := NewRegistry(f) |
| 95 | ctx := allowAll(context.Background()) |
| 96 | out, _ := r.Look(ctx, "ann", "") |
| 97 | r.Look(ctx, "ann", "") |
| 98 | if f.lists.Load() != 1 { |
| 99 | t.Fatalf("second Look listed again: %d", f.lists.Load()) |
| 100 | } |
| 101 | out2, _ := r.Look(ctx, "bob", "") |
| 102 | if !strings.Contains(out, "only_ann") || strings.Contains(out2, "only_ann") || !strings.Contains(out2, "only_bob") { |
| 103 | t.Fatalf("lists crossed people:\n%s\n%s", out, out2) |
| 104 | } |
| 105 | if f.lists.Load() != 2 { |
| 106 | t.Fatalf("lists = %d", f.lists.Load()) |
| 107 | } |
| 108 | r.Forget("ann") |
| 109 | r.Look(ctx, "ann", "") |
| 110 | if f.lists.Load() != 3 { |
| 111 | t.Fatalf("Forget did not drop ann: %d", f.lists.Load()) |
| 112 | } |
| 113 | r.Look(ctx, "bob", "") |
| 114 | if f.lists.Load() != 3 { |
| 115 | t.Fatalf("Forget(ann) dropped bob: %d", f.lists.Load()) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // A cached list lasts 60 s: just short of it Look answers from the |
| 120 | // cache, at 60 s it lists again, and the new list starts its own 60 s. |
| 121 | func TestRegistryListExpires(t *testing.T) { |
| 122 | f := &fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_apps", App: "Apps", ReadOnly: true}}}} |
| 123 | r := NewRegistry(f) |
| 124 | at := time.Date(2026, 11, 13, 9, 0, 0, 0, time.UTC) |
| 125 | r.now = func() time.Time { return at } |
| 126 | ctx := allowAll(context.Background()) |
| 127 | look := func(want int32) { |
| 128 | t.Helper() |
| 129 | if out, err := r.Look(ctx, "p", ""); err != nil || !strings.Contains(out, "base_apps") { |
| 130 | t.Fatalf("look %q %v", out, err) |
| 131 | } |
| 132 | if got := f.lists.Load(); got != want { |
| 133 | t.Fatalf("at %s: %d lists, want %d", at.Format(time.TimeOnly), got, want) |
| 134 | } |
| 135 | } |
| 136 | look(1) |
| 137 | at = at.Add(time.Minute - time.Nanosecond) |
| 138 | look(1) |
| 139 | at = at.Add(time.Nanosecond) |
| 140 | look(2) |
| 141 | at = at.Add(time.Minute - time.Nanosecond) |
| 142 | look(2) |
| 143 | at = at.Add(time.Nanosecond) |
| 144 | look(3) |
| 145 | } |
| 146 | |
| 147 | func TestDecide(t *testing.T) { |
| 148 | cases := []struct { |
| 149 | name string |
| 150 | op Operation |
| 151 | run bool |
| 152 | code string |
| 153 | }{ |
| 154 | {"read", Operation{Provider: "base", ReadOnly: true}, true, ""}, |
| 155 | {"team", Operation{Provider: "team"}, true, ""}, |
| 156 | {"destructive", Operation{Provider: "base", Destructive: true, KeyField: "k"}, false, "not_yet"}, |
| 157 | {"external", Operation{Provider: "base", External: true, KeyField: "k"}, false, "not_yet"}, |
| 158 | {"team destructive", Operation{Provider: "team", Destructive: true}, false, "not_yet"}, |
| 159 | {"write without key", Operation{Provider: "base"}, false, "write_not_supported"}, |
| 160 | {"write with key", Operation{Provider: "base", KeyField: "client_id"}, true, ""}, |
| 161 | } |
| 162 | for _, c := range cases { |
| 163 | run, code := Decide(c.op) |
| 164 | if run != c.run || code != c.code { |
| 165 | t.Errorf("%s: got %v %q, want %v %q", c.name, run, code, c.run, c.code) |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | func TestRegistryInvoke(t *testing.T) { |
| 171 | f := &fake{name: "cal", ops: map[string][]Operation{"p": { |
| 172 | {Name: "add", App: "C", KeyField: "client_id"}, |
| 173 | {Name: "nokey", App: "C"}, |
| 174 | {Name: "wipe", App: "C", Destructive: true, KeyField: "client_id"}, |
| 175 | {Name: "get", App: "C", ReadOnly: true}, |
| 176 | }}} |
| 177 | r := NewRegistry(f) |
| 178 | ctx := allowAll(context.Background()) |
| 179 | if _, err := r.Invoke(ctx, "p", "add", json.RawMessage(`{"title":"x"}`), "t/1/u"); err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | var in map[string]any |
| 183 | if err := json.Unmarshal(f.got.input, &in); err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | if in["client_id"] != Key("t/1/u") || in["title"] != "x" || f.got.key != Key("t/1/u") || f.got.op != "add" || f.got.person != "p" { |
| 187 | t.Errorf("key not placed at KeyField: %s key=%q", f.got.input, f.got.key) |
| 188 | } |
| 189 | for op, code := range map[string]string{"nokey": "write_not_supported", "wipe": "not_yet", "nope": "unknown_operation"} { |
| 190 | f.got.op = "" |
| 191 | _, err := r.Invoke(ctx, "p", op, nil, "k") |
| 192 | var fl Failure |
| 193 | if !errors.As(err, &fl) || fl.Code != code || f.got.op != "" { |
| 194 | t.Errorf("%s: err=%v called=%q", op, err, f.got.op) |
| 195 | } |
| 196 | } |
| 197 | if _, err := r.Invoke(ctx, "p", "get", nil, "k"); err != nil || f.got.key != "" { |
| 198 | t.Errorf("read got key %q err %v", f.got.key, err) |
| 199 | } |
| 200 | if _, err := r.Describe(ctx, "p", "add"); err != nil { |
| 201 | t.Error(err) |
| 202 | } |
| 203 | if _, err := r.Describe(ctx, "p", "nope"); err == nil { |
| 204 | t.Error("describe of unknown operation succeeded") |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | func TestWriteNeedsLedgerKey(t *testing.T) { |
| 209 | f := &fake{name: "cal", ops: map[string][]Operation{"p": { |
| 210 | {Name: "add", App: "C", KeyField: "client_id"}, |
| 211 | {Name: "get", App: "C", ReadOnly: true}, |
| 212 | }}} |
| 213 | tm := &fake{name: "team", ops: map[string][]Operation{"p": {{Name: "team_request", App: "T"}}}} |
| 214 | r := NewRegistry(f, tm) |
| 215 | ctx := allowAll(context.Background()) |
| 216 | for _, op := range []string{"add", "team_request"} { |
| 217 | f.got.op, tm.got.op = "", "" |
| 218 | _, err := r.Invoke(ctx, "p", op, json.RawMessage(`{"client_id":"mine"}`), "") |
| 219 | var fl Failure |
| 220 | if !errors.As(err, &fl) || fl.Code != "missing_key" || f.got.op != "" || tm.got.op != "" { |
| 221 | t.Errorf("%s: err=%v called=%q%q", op, err, f.got.op, tm.got.op) |
| 222 | } |
| 223 | } |
| 224 | if _, err := r.Invoke(ctx, "p", "get", nil, ""); err != nil { |
| 225 | t.Errorf("read without key: %v", err) |
| 226 | } |
| 227 | if _, err := r.Invoke(ctx, "p", "add", json.RawMessage(`{"client_id":"mine"}`), "t/1/u"); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | var in map[string]any |
| 231 | json.Unmarshal(f.got.input, &in) |
| 232 | if in["client_id"] != Key("t/1/u") { |
| 233 | t.Errorf("caller value kept: %s", f.got.input) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | type slow struct { |
| 238 | fake |
| 239 | started, release chan struct{} |
| 240 | stale bool |
| 241 | } |
| 242 | |
| 243 | func (s *slow) List(_ context.Context, _ string) ([]Operation, error) { |
| 244 | if s.stale { |
| 245 | s.stale = false |
| 246 | close(s.started) |
| 247 | <-s.release |
| 248 | return []Operation{{Name: "old_op", App: "A", ReadOnly: true}}, nil |
| 249 | } |
| 250 | return []Operation{{Name: "new_op", App: "A", ReadOnly: true}}, nil |
| 251 | } |
| 252 | |
| 253 | func TestForgetDuringListDropsStaleResult(t *testing.T) { |
| 254 | s := &slow{fake: fake{name: "base"}, started: make(chan struct{}), release: make(chan struct{}), stale: true} |
| 255 | r := NewRegistry(s) |
| 256 | ctx := allowAll(context.Background()) |
| 257 | done := make(chan string) |
| 258 | go func() { out, _ := r.Look(ctx, "p", ""); done <- out }() |
| 259 | <-s.started |
| 260 | r.Forget("p") |
| 261 | close(s.release) |
| 262 | if own := <-done; !strings.Contains(own, "old_op") { |
| 263 | t.Errorf("in-flight caller lost its result: %s", own) |
| 264 | } |
| 265 | out, _ := r.Look(ctx, "p", "") |
| 266 | if strings.Contains(out, "old_op") || !strings.Contains(out, "new_op") { |
| 267 | t.Errorf("stale list repopulated the cache:\n%s", out) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | type bigFake struct{ *fake } |
| 272 | |
| 273 | func (bigFake) Invoke(context.Context, string, string, json.RawMessage, string) (json.RawMessage, error) { |
| 274 | return json.RawMessage(`"` + strings.Repeat("a", MaxResult) + `"`), nil |
| 275 | } |
| 276 | |
| 277 | func TestRegistryCapsResult(t *testing.T) { |
| 278 | f := &bigFake{&fake{name: "b", ops: map[string][]Operation{"p": {{Name: "get", ReadOnly: true}}}}} |
| 279 | _, err := NewRegistry(f).Invoke(allowAll(context.Background()), "p", "get", nil, "") |
| 280 | var fl Failure |
| 281 | if !errors.As(err, &fl) || fl.Code != "too_large" { |
| 282 | t.Fatalf("err = %v", err) |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | func TestKeyIsUUIDv5(t *testing.T) { |
| 287 | k := Key("a") |
| 288 | if len(k) != 36 || k[14] != '5' || !strings.ContainsRune("89ab", rune(k[19])) || k[8] != '-' || k[13] != '-' { |
| 289 | t.Fatalf("not a v5 uuid: %s", k) |
| 290 | } |
| 291 | if k != Key("a") || k == Key("b") || k == "00000000-0000-0000-0000-000000000000" { |
| 292 | t.Fatalf("unstable or colliding: %s %s", k, Key("b")) |
| 293 | } |
| 294 | // Reference value from Python's uuid.uuid5 in the same namespace. |
| 295 | if want := "9cc669b8-e9f9-5e93-af5a-3b54204bdf25"; k != want { |
| 296 | t.Fatalf("Key(a) = %s, want %s", k, want) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | func hostFor(origin string) func(context.Context, string) (string, string, bool, error) { |
| 301 | return func(context.Context, string) (string, string, bool, error) { return origin, "tok", true, nil } |
| 302 | } |
| 303 | |
| 304 | func TestHTTPProvider(t *testing.T) { |
| 305 | var hits atomic.Int32 |
| 306 | var gotAuth, gotKey, gotBody string |
| 307 | mux := http.NewServeMux() |
| 308 | mux.HandleFunc("GET /api/v1/operations", func(w http.ResponseWriter, r *http.Request) { |
| 309 | hits.Add(1) |
| 310 | gotAuth = r.Header.Get("Authorization") |
| 311 | w.Write([]byte(`{"operations":[{"name":"base_apps","app":"Apps","read_only":true}]}`)) |
| 312 | }) |
| 313 | mux.HandleFunc("POST /api/v1/operations/{name}", func(w http.ResponseWriter, r *http.Request) { |
| 314 | hits.Add(1) |
| 315 | gotAuth, gotKey = r.Header.Get("Authorization"), r.Header.Get("Idempotency-Key") |
| 316 | b, _ := io.ReadAll(r.Body) |
| 317 | gotBody = string(b) |
| 318 | switch r.PathValue("name") { |
| 319 | case "denied": |
| 320 | w.WriteHeader(401) |
| 321 | w.Write([]byte(`{"error":{"code":"nope","message":"no"}}`)) |
| 322 | case "bad": |
| 323 | w.WriteHeader(422) |
| 324 | w.Write([]byte(`{"error":{"code":"invalid","message":"bad input"}}`)) |
| 325 | case "redirect": |
| 326 | http.Redirect(w, r, "/elsewhere", http.StatusFound) |
| 327 | case "huge": |
| 328 | w.Write([]byte(`{"x":"` + strings.Repeat("a", 256<<10) + `"}`)) |
| 329 | case "big": |
| 330 | w.Write([]byte(`{"x":"` + strings.Repeat("a", MaxResult) + `"}`)) |
| 331 | default: |
| 332 | w.Write([]byte(`{"done":1}`)) |
| 333 | } |
| 334 | }) |
| 335 | mux.HandleFunc("GET /elsewhere", func(http.ResponseWriter, *http.Request) { hits.Add(100) }) |
| 336 | srv := httptest.NewServer(mux) |
| 337 | defer srv.Close() |
| 338 | ctx := allowAll(context.Background()) |
| 339 | p := NewHTTPProvider("base", hostFor(srv.URL), srv.Client()) |
| 340 | |
| 341 | ops, err := p.List(ctx, "p") |
| 342 | if err != nil || len(ops) != 1 || ops[0].Name != "base_apps" || ops[0].Provider != "base" || gotAuth != "Bearer tok" { |
| 343 | t.Fatalf("list: %v %+v auth=%q", err, ops, gotAuth) |
| 344 | } |
| 345 | out, err := p.Invoke(ctx, "p", "ok", json.RawMessage(`{"a":1}`), "key-1") |
| 346 | if err != nil || string(out) != `{"done":1}` || gotAuth != "Bearer tok" || gotKey != "key-1" || gotBody != `{"a":1}` { |
| 347 | t.Fatalf("invoke: %v %s auth=%q key=%q body=%q", err, out, gotAuth, gotKey, gotBody) |
| 348 | } |
| 349 | if _, err = p.Invoke(ctx, "p", "ok", nil, ""); err != nil || gotKey != "" { |
| 350 | t.Fatalf("no key: %v %q", err, gotKey) |
| 351 | } |
| 352 | code := func(op string) string { |
| 353 | _, err := p.Invoke(ctx, "p", op, nil, "") |
| 354 | var f Failure |
| 355 | if !errors.As(err, &f) { |
| 356 | return "<" + errString(err) + ">" |
| 357 | } |
| 358 | return f.Code |
| 359 | } |
| 360 | if c := code("denied"); c != "unauthenticated" { |
| 361 | t.Errorf("401 -> %s", c) |
| 362 | } |
| 363 | if c := code("bad"); c != "invalid" { |
| 364 | t.Errorf("422 -> %s", c) |
| 365 | } |
| 366 | before := hits.Load() |
| 367 | if c := code("redirect"); c == "" || strings.HasPrefix(c, "<") { |
| 368 | t.Errorf("redirect -> %s", c) |
| 369 | } |
| 370 | if hits.Load() != before+1 { |
| 371 | t.Errorf("redirect was followed: %d hits", hits.Load()-before) |
| 372 | } |
| 373 | if c := code("huge"); c != "too_large" { |
| 374 | t.Errorf("256KiB+ -> %s", c) |
| 375 | } |
| 376 | if c := code("big"); c != "too_large" { |
| 377 | t.Errorf("over MaxResult -> %s", c) |
| 378 | } |
| 379 | |
| 380 | // a list body over the cap |
| 381 | big := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 382 | w.Write([]byte(`{"operations":[],"pad":"` + strings.Repeat("a", 256<<10) + `"}`)) |
| 383 | })) |
| 384 | defer big.Close() |
| 385 | _, err = NewHTTPProvider("base", hostFor(big.URL), big.Client()).List(ctx, "p") |
| 386 | var f Failure |
| 387 | if !errors.As(err, &f) || f.Code != "too_large" { |
| 388 | t.Errorf("big list: %v", err) |
| 389 | } |
| 390 | |
| 391 | // not connected: no request |
| 392 | hits.Store(0) |
| 393 | nc := NewHTTPProvider("base", func(context.Context, string) (string, string, bool, error) { return srv.URL, "tok", false, nil }, srv.Client()) |
| 394 | if _, err := nc.List(ctx, "p"); !errors.As(err, &f) || f.Code != "not_connected" { |
| 395 | t.Errorf("list not connected: %v", err) |
| 396 | } |
| 397 | if _, err := nc.Invoke(ctx, "p", "ok", nil, "k"); !errors.As(err, &f) || f.Code != "not_connected" { |
| 398 | t.Errorf("invoke not connected: %v", err) |
| 399 | } |
| 400 | if hits.Load() != 0 { |
| 401 | t.Errorf("not_connected made %d requests", hits.Load()) |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | func errString(err error) string { |
| 406 | if err == nil { |
| 407 | return "nil" |
| 408 | } |
| 409 | return err.Error() |
| 410 | } |
| 411 | |