package plan3test import ( "crypto/aes" "crypto/cipher" "crypto/ed25519" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/equipo/setup" ) func TestPersonAPIDeviceTrustedProxySource(t *testing.T) { for _, proxied := range []bool{false, true} { t.Run(fmt.Sprint(proxied), func(t *testing.T) { f := newFixture(t) control := "" if proxied { control = "fixture-socket" } t.Setenv("CARLOS_CONTROL_SOCKET", control) pub, _, err := ed25519.GenerateKey(rand.Reader) must(t, err) request := func(xff string) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", "/api/v1/auth/devices", strings.NewReader(fmt.Sprintf(`{"public_key":%q,"label":"phone"}`, base64.RawURLEncoding.EncodeToString(pub)))) r.RemoteAddr = "127.0.0.1:1234" r.Header.Set("X-Forwarded-For", xff) r.Header.Set("Content-Type", "application/json") r.Header.Set("Idempotency-Key", rand.Text()) w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } for i := 0; i < 10; i++ { expectHTTP(t, request(fmt.Sprintf("198.51.100.%d, 192.0.2.1", i)), 200) } expectHTTP(t, request("198.51.100.99, 192.0.2.1"), 429) want := 429 if proxied { want = 200 } expectHTTP(t, request("198.51.100.99, 192.0.2.2"), want) }) } } func TestPersonAPILegacyCursorFailsClosed(t *testing.T) { f := newFixture(t) key := sha256.Sum256([]byte("equipo.person-api.cursor.v1\x00plan3-fixture")) block, err := aes.NewCipher(key[:]) must(t, err) g, err := cipher.NewGCM(block) must(t, err) raw, err := json.Marshal(struct { Position any ExpiresAt time.Time }{map[string]any{"ID": "", "Sequence": 0}, time.Now().Add(time.Hour)}) must(t, err) nonce := make([]byte, g.NonceSize()) _, err = rand.Read(nonce) must(t, err) token := base64.RawURLEncoding.EncodeToString(g.Seal(nonce, nonce, raw, []byte(owner.Address+"\x00people"))) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+token, "", "", ""), 410) } func TestPersonAPIRunnerInstanceProjection(t *testing.T) { f := newFixture(t) for _, instance := range []string{f.TeamID, "foreign"} { must(t, f.DB.G.Create(&setup.RunnerRecord{Runner: setup.Runner{ID: instance, Person: owner.Address, Label: instance, Revision: 1}, InstanceID: instance}).Error) } w := apiRequest(t, f, owner, "GET", "/api/v1/runners", "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[map[string]any]](t, w) if len(page.Items) != 1 || page.Items[0]["id"] != f.TeamID { t.Fatal("runner list crossed instance boundary") } for _, key := range []string{"created_at", "last_seen"} { if _, ok := page.Items[0][key]; ok { t.Fatal("unavailable runner time should be omitted", key) } } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/runners/foreign", "", "", ""), 404) }