package httpapi import ( "context" "net/http" "strings" "sync" "testing" "time" "github.com/uptrace/bun" "go.uber.org/zap" "git.kmalloc.org/squid/sonda/internal/mastodon" "git.kmalloc.org/squid/sonda/internal/storage" ) // fakeMastodon stands in for the instance: it answers like the one a test sets up and tells what was posted. type fakeMastodon struct { mu sync.Mutex handle string verify error postErr error posted chan [2]string // token, status } func (f *fakeMastodon) Verify(_ context.Context, _, _ string) (string, error) { f.mu.Lock() defer f.mu.Unlock() return f.handle, f.verify } func (f *fakeMastodon) Post(_ context.Context, _, token, status, _ string) error { if f.posted != nil { f.posted <- [2]string{token, status} } return f.postErr } // mastodonEnv is the API with the Mastodon service on the given instance. The worker that posts runs for the length of the test. func mastodonEnv(t *testing.T, remote mastodon.Remote) http.Handler { t.Helper() h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) { svc := mastodon.NewService(storage.NewMastodonRepo(db), remote, zap.NewNop()) ctx, stop := context.WithCancel(context.Background()) t.Cleanup(stop) go svc.Run(ctx) d.Mastodon = svc }) return h } func TestMastodonNeedsASignedInUser(t *testing.T) { h := newTestAPI(t) for _, m := range []string{"GET", "PUT", "DELETE"} { if r := do(t, h, m, "/api/v1/me/mastodon", "", map[string]any{}); r.Code != http.StatusUnauthorized { t.Errorf("%s without a token: %d", m, r.Code) } } } func TestMastodonStartsDisconnected(t *testing.T) { h := newTestAPI(t) alice := registerAndLogin(t, h) r := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil) if r.Code != http.StatusOK { t.Fatalf("%d %v", r.Code, r.Body) } sameKeys(t, "status", r.Body, "connected") if r.Body["connected"] != false { t.Errorf("status = %v", r.Body) } } func TestConnectingAnAccountKeepsItAndNeverShowsTheToken(t *testing.T) { h := mastodonEnv(t, &fakeMastodon{handle: "@squid@mastodon.social"}) alice := registerAndLogin(t, h) r := do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "Mastodon.Social/", "token": "secret-token-value"}) if r.Code != http.StatusOK { t.Fatalf("%d %v", r.Code, r.Body) } sameKeys(t, "connected", r.Body, "connected", "instance", "handle") if r.Body["connected"] != true || r.Body["instance"] != "https://mastodon.social" || r.Body["handle"] != "@squid@mastodon.social" { t.Errorf("body = %v", r.Body) } g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil) sameKeys(t, "status", g.Body, "connected", "instance", "handle") for _, resp := range []map[string]any{r.Body, g.Body} { for k, v := range resp { if s, ok := v.(string); ok && strings.Contains(s, "secret-token") { t.Errorf("the token came back in %q: %v", k, resp) } } } } func TestAnAccountThatCannotBeConnectedIsNotKept(t *testing.T) { for _, c := range []struct { name string verify error instance string token string status int code string }{ {"a refused token", mastodon.ErrRefused, "mastodon.social", "tok", http.StatusUnprocessableEntity, "mastodon_refused"}, {"an instance that is not there", mastodon.ErrUnreachable, "mastodon.social", "tok", http.StatusBadGateway, "mastodon_unreachable"}, {"a plain http address", nil, "http://mastodon.social", "tok", http.StatusBadRequest, "invalid_instance"}, {"a name with no dot", nil, "localhost", "tok", http.StatusBadRequest, "invalid_instance"}, {"an empty token", nil, "mastodon.social", " ", http.StatusBadRequest, "invalid_token"}, } { h := mastodonEnv(t, &fakeMastodon{handle: "@a@b", verify: c.verify}) alice := registerAndLogin(t, h) r := do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": c.instance, "token": c.token}) if r.Code != c.status || errCode(r) != c.code { t.Errorf("%s: %d %v, want %d %s", c.name, r.Code, r.Body, c.status, c.code) } if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["connected"] != false { t.Errorf("%s: something was kept: %v", c.name, g.Body) } } } func TestAMastodonBodyThatIsNotWhatWasAskedForIsRefused(t *testing.T) { h := newTestAPI(t) alice := registerAndLogin(t, h) for name, body := range map[string]any{ "a list": []any{"mastodon.social"}, "a number": map[string]any{"instance": 5, "token": "t"}, "no instance": map[string]any{"token": "t"}, "no token": map[string]any{"instance": "mastodon.social"}, "an unknown name": map[string]any{"instance": "mastodon.social", "token": "t", "visibility": "public"}, } { if r := do(t, h, "PUT", "/api/v1/me/mastodon", alice, body); r.Code != http.StatusBadRequest { t.Errorf("%s: %d %v, want 400", name, r.Code, r.Body) } } } func TestDisconnectingForgetsTheAccountAndCanBeRepeated(t *testing.T) { h := mastodonEnv(t, &fakeMastodon{handle: "@a@b"}) alice := registerAndLogin(t, h) do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "tok"}) for i := 0; i < 2; i++ { if r := do(t, h, "DELETE", "/api/v1/me/mastodon", alice, nil); r.Code != http.StatusNoContent { t.Fatalf("delete %d: %d %v", i, r.Code, r.Body) } } if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["connected"] != false { t.Errorf("still connected: %v", g.Body) } } func TestEachPersonHasTheirOwnMastodonAccount(t *testing.T) { h := mastodonEnv(t, &fakeMastodon{handle: "@a@b"}) alice := registerAndLogin(t, h) do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "tok"}) cred := map[string]any{"email": "bob@example.org", "password": "longenough"} if c := do(t, h, "POST", "/api/v1/users", alice, cred); c.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", c.Code, c.Body) } bob, _ := do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string) if g := do(t, h, "GET", "/api/v1/me/mastodon", bob, nil); g.Body["connected"] != false { t.Errorf("bob sees alice's account: %v", g.Body) } } func TestOnlyAListenThatCountsIsPostedAndOnlyForWhoConnected(t *testing.T) { remote := &fakeMastodon{handle: "@squid@mastodon.social", posted: make(chan [2]string, 4)} h := mastodonEnv(t, remote) alice := registerAndLogin(t, h) cred := map[string]any{"email": "bob@example.org", "password": "longenough"} do(t, h, "POST", "/api/v1/users", alice, cred) bob, _ := do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string) do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "tok"}) listen := func(token, key, kind string, ms int) { t.Helper() r := do(t, h, "POST", "/api/v1/listens", token, map[string]any{"track_id": 1, "event_type": kind, "duration_played_ms": ms, "idempotency_key": key}) if r.Code != http.StatusCreated { t.Fatalf("listen %s: %d %v", key, r.Code, r.Body) } } listen(bob, "b1", "complete", 30000) // counts, but bob connected nothing listen(alice, "a1", "skip", 5000) // alice connected, but it does not count listen(alice, "a2", "complete", 30000) // this one is posted select { case p := <-remote.posted: if p[0] != "tok" || !strings.Contains(p[1], "song") || !strings.HasSuffix(p[1], "#NowPlaying") { t.Errorf("post = %v", p) } case <-time.After(3 * time.Second): t.Fatal("nothing was posted for a listen that counts") } select { case p := <-remote.posted: t.Errorf("a second post: %v", p) case <-time.After(200 * time.Millisecond): } } func TestARefusedTokenShowsAsAProblemUntilTheAccountIsConnectedAgain(t *testing.T) { remote := &fakeMastodon{handle: "@squid@mastodon.social", postErr: mastodon.ErrRefused, posted: make(chan [2]string, 4)} h := mastodonEnv(t, remote) alice := registerAndLogin(t, h) do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "tok"}) if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["problem"] != nil { t.Fatalf("a fresh account has no problem: %v", g.Body) } r := do(t, h, "POST", "/api/v1/listens", alice, map[string]any{"track_id": 1, "event_type": "complete", "duration_played_ms": 30000, "idempotency_key": "a1"}) if r.Code != http.StatusCreated { t.Fatalf("listen: %d %v", r.Code, r.Body) } <-remote.posted deadline := time.Now().Add(3 * time.Second) for { g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil) if g.Body["problem"] == "token_refused" { sameKeys(t, "with a problem", g.Body, "connected", "instance", "handle", "problem") break } if time.Now().After(deadline) { t.Fatalf("the problem never showed: %v", g.Body) } time.Sleep(20 * time.Millisecond) } // A new token clears it. remote.postErr = nil do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "new"}) if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["problem"] != nil { t.Errorf("connecting again left the problem: %v", g.Body) } }