sonda/internal/mastodon/client_test.go
tgiachi 0dc7782028 feat: post what I listen to on Mastodon, if I connect an account
In Settings a person connects their Mastodon account: the address of their instance and an access token that can only write posts. Nothing is connected by default, and disconnecting forgets the token.

- When a track of this server counts as a listen, it is posted as an unlisted status: title, artists, album and #NowPlaying, with no link. Music of a friend is never reported as a listen, so it is never posted. At most one post a minute for each person, in the background, with a bounded queue.
- PUT, GET and DELETE /me/mastodon. The token is never sent back.
- The address of the instance is typed by a person, so it must be a domain name on https, and the client never connects to a private, loopback or link-local address (checked on the address it really dials, so a name that points inside is no way in), never follows a redirect, ignores proxy settings and reads at most a megabyte.
- New table mastodon_accounts (SQLite and PostgreSQL) that goes with the account.
- README: the feature, and the credit for butterchurn and its presets.
2026-11-13 21:59:03 +01:00

149 lines
5.8 KiB
Go

package mastodon
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
// testRemote reaches the test server on the loopback, which the real one never does.
func testRemote(srv *httptest.Server) *HTTPRemote {
client := *srv.Client()
client.CheckRedirect = refuseRedirect // the one the real client has
return &HTTPRemote{client: &client, userAgent: "Sonda-test"}
}
func TestVerifyAsksWhoTheTokenBelongsToAndAnswersWithTheHandle(t *testing.T) {
var gotAuth, gotAgent, gotPath string
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth, gotAgent, gotPath = r.Header.Get("Authorization"), r.Header.Get("User-Agent"), r.URL.Path
_, _ = io.WriteString(w, `{"acct":"squid","username":"squid"}`)
}))
defer srv.Close()
handle, err := testRemote(srv).Verify(context.Background(), srv.URL, "tok")
if err != nil {
t.Fatal(err)
}
host := strings.TrimPrefix(srv.URL, "https://")
if handle != "@squid@"+hostOnly(host) {
t.Errorf("handle = %q", handle)
}
if gotAuth != "Bearer tok" || gotAgent != "Sonda-test" || gotPath != "/api/v1/accounts/verify_credentials" {
t.Errorf("request: %q %q %q", gotAuth, gotAgent, gotPath)
}
}
func hostOnly(h string) string {
if host, _, err := net.SplitHostPort(h); err == nil {
return host
}
return h
}
func TestVerifyKeepsTheDomainOfAFederatedHandle(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"acct":"squid@other.example"}`)
}))
defer srv.Close()
handle, err := testRemote(srv).Verify(context.Background(), srv.URL, "tok")
if err != nil || handle != "@squid@other.example" {
t.Errorf("handle = %q, %v", handle, err)
}
}
func TestAnInstanceThatRefusesTheTokenIsRefusedAndOneThatIsBrokenIsUnreachable(t *testing.T) {
for status, want := range map[int]error{401: ErrRefused, 403: ErrRefused, 500: ErrUnreachable, 503: ErrUnreachable, 404: ErrUnreachable, 429: ErrUnreachable} {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) }))
if _, err := testRemote(srv).Verify(context.Background(), srv.URL, "tok"); !errors.Is(err, want) {
t.Errorf("verify %d: %v, want %v", status, err, want)
}
if err := testRemote(srv).Post(context.Background(), srv.URL, "tok", "hi", "k"); !errors.Is(err, want) {
t.Errorf("post %d: %v, want %v", status, err, want)
}
srv.Close()
}
}
func TestAnAnswerThatIsNotAnAccountIsNotTrusted(t *testing.T) {
for _, body := range []string{"", "not json", `{}`, `{"acct":""}`, `{"acct":"a b"}`, `{"acct":"` + strings.Repeat("a", 400) + `"}`} {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, body) }))
if handle, err := testRemote(srv).Verify(context.Background(), srv.URL, "tok"); !errors.Is(err, ErrUnreachable) {
t.Errorf("body %.20q: handle %q, err %v", body, handle, err)
}
srv.Close()
}
}
func TestPostSendsAnUnlistedStatusWithAnIdempotencyKey(t *testing.T) {
var form url.Values
var method, auth, key, contentType string
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
method, auth, key, contentType = r.Method, r.Header.Get("Authorization"), r.Header.Get("Idempotency-Key"), r.Header.Get("Content-Type")
_ = r.ParseForm()
form = r.PostForm
_, _ = io.WriteString(w, `{"id":"1"}`)
}))
defer srv.Close()
if err := testRemote(srv).Post(context.Background(), srv.URL, "tok", "🎵 Sonar #NowPlaying", "abc123"); err != nil {
t.Fatal(err)
}
if method != "POST" || auth != "Bearer tok" || key != "abc123" || !strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
t.Errorf("request: %s %q %q %q", method, auth, key, contentType)
}
if form.Get("status") != "🎵 Sonar #NowPlaying" || form.Get("visibility") != "unlisted" {
t.Errorf("form = %v", form)
}
}
func TestARedirectIsNeverFollowed(t *testing.T) {
hit := false
other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hit = true }))
defer other.Close()
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL, http.StatusFound)
}))
defer srv.Close()
if _, err := testRemote(srv).Verify(context.Background(), srv.URL, "tok"); !errors.Is(err, ErrUnreachable) {
t.Errorf("err = %v", err)
}
if hit {
t.Error("the redirect was followed, and the token went with it")
}
}
func TestTheRealClientNeverReachesAPrivateNetwork(t *testing.T) {
hit := false
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hit = true }))
defer srv.Close()
real := NewRemote("Sonda-test")
for _, base := range []string{srv.URL, "https://127.0.0.1:1", "https://[::1]:1", "https://10.1.2.3", "https://192.168.1.10", "https://169.254.169.254", "https://localhost:1"} {
if _, err := real.Verify(context.Background(), base, "tok"); !errors.Is(err, ErrUnreachable) {
t.Errorf("%s: err = %v", base, err)
}
if err := real.Post(context.Background(), base, "tok", "x", "k"); !errors.Is(err, ErrUnreachable) {
t.Errorf("%s: post err = %v", base, err)
}
}
if hit {
t.Error("the server on the loopback was reached")
}
}
func TestPublicAddressesAreTheOnlyOnesAllowed(t *testing.T) {
for ip, want := range map[string]bool{
"8.8.8.8": true, "93.184.216.34": true, "2606:4700:4700::1111": true,
"127.0.0.1": false, "::1": false, "10.0.0.1": false, "172.16.5.5": false, "192.168.0.1": false, "169.254.1.1": false,
"100.64.0.1": false, "0.0.0.0": false, "::": false, "fe80::1": false, "fc00::1": false, "224.0.0.1": false, "255.255.255.255": false,
"::ffff:127.0.0.1": false, "::ffff:10.0.0.1": false,
} {
if got := publicIP(net.ParseIP(ip)); got != want {
t.Errorf("publicIP(%s) = %v, want %v", ip, got, want)
}
}
}