sonda/internal/opensubsonic/handler_test.go
tgiachi 1ae8e77d81 feat: OpenSubsonic core, login with a device password
/rest speaks the OpenSubsonic API (Subsonic 1.16.1) so that other apps can browse
the music of a server. A call logs in with the password of a device: an apiKey,
Subsonic's token (u, t, s) or the password itself (u, p). The account password is
never accepted there.

- devices: ByKey, ByToken, ByPassword and the note of last use
- opensubsonic package: JSON and XML answers, ping, getLicense,
  getOpenSubsonicExtensions, tokenInfo, getMusicFolders, getArtists, getArtist,
  getAlbum, getSong, getGenres
- storage.SubsonicRepo: year, genres, size, bitrate, suffix and added date
2026-11-16 09:32:11 +01:00

487 lines
18 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package opensubsonic
import (
"context"
"encoding/json"
"encoding/xml"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/devices"
"git.kmalloc.org/squid/sonda/internal/library"
)
const secret = "0123456789abcdef0123456789abcdef0123456789abcdef"
type fakeLogin struct{}
func (fakeLogin) ByKey(_ context.Context, key string) (devices.Principal, error) {
if key == secret {
return devices.Principal{UserID: 1, DeviceID: 5, Email: "tom@example.org"}, nil
}
return devices.Principal{}, devices.ErrBadCredentials
}
func (fakeLogin) ByToken(_ context.Context, email, token, salt string) (devices.Principal, error) {
if email == "tom@example.org" && token == "tok-"+salt {
return devices.Principal{UserID: 1, DeviceID: 5, Email: email}, nil
}
return devices.Principal{}, devices.ErrBadCredentials
}
func (fakeLogin) ByPassword(_ context.Context, email, password string) (devices.Principal, error) {
if email == "tom@example.org" && password == secret {
return devices.Principal{UserID: 1, DeviceID: 5, Email: email}, nil
}
return devices.Principal{}, devices.ErrBadCredentials
}
type fakeLibraries struct{}
func (fakeLibraries) List(context.Context) ([]library.Library, error) {
return []library.Library{{ID: 1, Name: "Rock"}, {ID: 2, Name: "Jazz"}}, nil
}
// The catalogue of the tests: Radiohead (OK Computer, 2 songs), Björk (nothing to play but a name), 3 Doors Down.
type fakeCatalog struct{ libs []int64 }
var (
artists = []catalog.Artist{
{ID: 3, Name: "3 Doors Down", AlbumCount: 0, TrackCount: 1},
{ID: 2, Name: "Björk", AlbumCount: 0, TrackCount: 1},
{ID: 1, Name: "Radiohead", AlbumCount: 1, TrackCount: 2},
{ID: 4, Name: "Radio Dept", AlbumCount: 0, TrackCount: 1},
}
okComputer = catalog.Album{ID: 7, Title: "OK Computer", Artist: &catalog.ArtistRef{ID: 1, Name: "Radiohead"}, TrackCount: 2, DurationMs: 600_400}
airbag = catalog.Track{ID: 70, Title: "Airbag", DurationMs: 284_000, TrackNo: 1, DiscNo: 1, Album: &catalog.AlbumRef{ID: 7, Title: "OK Computer"},
Artists: []catalog.ArtistRef{{ID: 1, Name: "Radiohead"}}, Format: "flac",
ReplayGain: &catalog.ReplayGain{TrackGain: ptr(-6.5)}}
karma = catalog.Track{ID: 71, Title: "Karma Police", DurationMs: 264_400, TrackNo: 2, DiscNo: 1, Album: &catalog.AlbumRef{ID: 7, Title: "OK Computer"},
Artists: []catalog.ArtistRef{{ID: 1, Name: "Radiohead"}, {ID: 9, Name: "Guest"}}, Format: "mp3"}
)
func ptr(f float64) *float64 { return &f }
func (c *fakeCatalog) Artists(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error) {
if f.LibraryID != 0 {
c.libs = append(c.libs, f.LibraryID)
}
return catalog.Page[catalog.Artist]{Items: page(artists, f), Total: len(artists), Limit: f.Limit, Offset: f.Offset}, nil
}
func (c *fakeCatalog) Albums(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error) {
var all []catalog.Album
if f.ArtistID == 0 || f.ArtistID == 1 {
all = []catalog.Album{okComputer}
}
return catalog.Page[catalog.Album]{Items: page(all, f), Total: len(all), Limit: f.Limit, Offset: f.Offset}, nil
}
func (c *fakeCatalog) Tracks(_ context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error) {
var all []catalog.Track
if f.AlbumID == 7 {
all = []catalog.Track{airbag, karma}
}
return catalog.Page[catalog.Track]{Items: page(all, f), Total: len(all), Limit: f.Limit, Offset: f.Offset}, nil
}
func (c *fakeCatalog) Artist(_ context.Context, id int64) (catalog.Artist, error) {
for _, a := range artists {
if a.ID == id {
return a, nil
}
}
return catalog.Artist{}, catalog.ErrNotFound
}
func (c *fakeCatalog) Album(_ context.Context, id int64) (catalog.Album, error) {
if id == 7 {
return okComputer, nil
}
return catalog.Album{}, catalog.ErrNotFound
}
func (c *fakeCatalog) Track(_ context.Context, id int64) (catalog.Track, error) {
switch id {
case 70:
return airbag, nil
case 71:
return karma, nil
}
return catalog.Track{}, catalog.ErrNotFound
}
func page[T any](all []T, f catalog.Filter) []T {
if f.Offset >= len(all) {
return []T{}
}
end := len(all)
if f.Limit > 0 && f.Offset+f.Limit < end {
end = f.Offset + f.Limit
}
return all[f.Offset:end]
}
type fakeExtras struct{}
func (fakeExtras) Tracks(_ context.Context, ids []int64) (map[int64]TrackExtra, error) {
out := map[int64]TrackExtra{}
for _, id := range ids {
switch id {
case 70:
out[id] = TrackExtra{Year: 1997, Genres: []string{"alternative rock", "art rock"}, Size: 29_000_000, BitrateKbps: 900, Suffix: "flac", AddedAt: time.Unix(1_700_000_000, 0)}
case 71:
out[id] = TrackExtra{Size: 6_000_000, BitrateKbps: 320, Suffix: "mp3", AddedAt: time.Unix(1_700_000_100, 0)}
}
}
return out, nil
}
func (fakeExtras) Albums(_ context.Context, ids []int64) (map[int64]AlbumExtra, error) {
out := map[int64]AlbumExtra{}
for _, id := range ids {
if id == 7 {
out[id] = AlbumExtra{Year: 1997, Genres: []string{"alternative rock", "art rock"}, AddedAt: time.Unix(1_700_000_000, 0)}
}
}
return out, nil
}
func (fakeExtras) Genres(context.Context) ([]Genre, error) {
return []Genre{{Name: "alternative rock", Songs: 1, Albums: 1}, {Name: "art rock", Songs: 1, Albums: 1}}, nil
}
func newTestServer() (http.Handler, *fakeCatalog) {
gin.SetMode(gin.TestMode)
cat := &fakeCatalog{}
r := gin.New()
Register(r, Deps{Login: fakeLogin{}, Catalog: cat, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9"})
return r, cat
}
// get makes a request to /rest and returns the recorder.
func get(t *testing.T, h http.Handler, method, path string, q url.Values) *httptest.ResponseRecorder {
t.Helper()
var req *http.Request
if method == http.MethodPost {
req = httptest.NewRequest(method, path, strings.NewReader(q.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req = httptest.NewRequest(method, path+"?"+q.Encode(), nil)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// ok is the parameters of a call that is logged in with the API key and answers in JSON.
func ok(extra ...string) url.Values {
q := url.Values{"apiKey": {secret}, "f": {"json"}, "v": {"1.16.1"}, "c": {"test"}}
for i := 0; i+1 < len(extra); i += 2 {
q.Set(extra[i], extra[i+1])
}
return q
}
// body decodes the JSON answer and returns the content of subsonic-response.
func body(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out struct {
R map[string]any `json:"subsonic-response"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.R == nil {
t.Fatalf("not an answer: %v: %s", err, rec.Body.String())
}
return out.R
}
func good(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("HTTP %d: %s", rec.Code, rec.Body.String())
}
r := body(t, rec)
if r["status"] != "ok" {
t.Fatalf("status %v: %s", r["status"], rec.Body.String())
}
return r
}
func failed(t *testing.T, rec *httptest.ResponseRecorder, code int) {
t.Helper()
r := body(t, rec)
e, _ := r["error"].(map[string]any)
if r["status"] != "failed" || e == nil || int(e["code"].(float64)) != code {
t.Fatalf("want error %d, got %s", code, rec.Body.String())
}
}
func TestTheAnswerSaysWhoIsAnswering(t *testing.T) {
h, _ := newTestServer()
rec := get(t, h, "GET", "/rest/ping", ok())
r := good(t, rec)
if r["version"] != APIVersion || r["type"] != "sonda" || r["serverVersion"] != "9.9" || r["openSubsonic"] != true {
t.Fatalf("envelope %v", r)
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("content type %q", ct)
}
if rec.Header().Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("a web app on another address cannot read the answer")
}
}
func TestTheDefaultAnswerIsXML(t *testing.T) {
h, _ := newTestServer()
q := ok()
q.Del("f")
rec := get(t, h, "GET", "/rest/ping.view", q)
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/xml") {
t.Fatalf("content type %q", ct)
}
var r struct {
XMLName xml.Name `xml:"subsonic-response"`
Xmlns string `xml:"xmlns,attr"`
Status string `xml:"status,attr"`
Version string `xml:"version,attr"`
}
if err := xml.Unmarshal(rec.Body.Bytes(), &r); err != nil || r.Status != "ok" || r.Version != APIVersion || r.Xmlns != "http://subsonic.org/restapi" {
t.Fatalf("%v %+v: %s", err, r, rec.Body.String())
}
}
func TestACallCanBeAFormPost(t *testing.T) {
h, _ := newTestServer()
good(t, get(t, h, "POST", "/rest/ping", ok()))
}
func TestTheLoginIsChecked(t *testing.T) {
h, _ := newTestServer()
// The API key, a token with its salt, and the password, each for a person.
good(t, get(t, h, "GET", "/rest/ping", ok()))
good(t, get(t, h, "GET", "/rest/ping", url.Values{"u": {"tom@example.org"}, "t": {"tok-abc123"}, "s": {"abc123"}, "f": {"json"}}))
good(t, get(t, h, "GET", "/rest/ping", url.Values{"u": {"tom@example.org"}, "p": {secret}, "f": {"json"}}))
for name, q := range map[string]struct {
q url.Values
code int
}{
"nothing": {url.Values{"f": {"json"}}, ErrMissingParam},
"no password": {url.Values{"u": {"tom@example.org"}, "f": {"json"}}, ErrMissingParam},
"a token with no salt": {url.Values{"u": {"tom@example.org"}, "t": {"x"}, "f": {"json"}}, ErrMissingParam},
"a wrong password": {url.Values{"u": {"tom@example.org"}, "p": {"nope"}, "f": {"json"}}, ErrWrongLogin},
"a wrong token": {url.Values{"u": {"tom@example.org"}, "t": {"bad"}, "s": {"abc"}, "f": {"json"}}, ErrWrongLogin},
"a wrong key": {url.Values{"apiKey": {"nope"}, "f": {"json"}}, ErrBadAPIKey},
"a key and a user": {url.Values{"apiKey": {secret}, "u": {"tom@example.org"}, "f": {"json"}}, ErrAuthConflict},
"a key and a token": {url.Values{"apiKey": {secret}, "t": {"x"}, "s": {"y"}, "f": {"json"}}, ErrAuthConflict},
"a key and a password": {url.Values{"apiKey": {secret}, "p": {secret}, "f": {"json"}}, ErrAuthConflict},
"a token and a password": {url.Values{"u": {"tom@example.org"}, "t": {"tok-a"}, "s": {"a"}, "p": {secret}, "f": {"json"}}, ErrAuthConflict},
} {
rec := get(t, h, "GET", "/rest/ping", q.q)
if rec.Code != http.StatusOK {
t.Errorf("%s: HTTP %d, a failed call is still a 200", name, rec.Code)
}
failed(t, rec, q.code)
}
}
func TestAFailedLoginIsAnswerdInTheFormatAskedFor(t *testing.T) {
h, _ := newTestServer()
rec := get(t, h, "GET", "/rest/ping.view", url.Values{"u": {"x"}, "p": {"y"}})
if !strings.Contains(rec.Body.String(), `<error code="40"`) {
t.Fatal(rec.Body.String())
}
}
func TestAnUnknownCallIsAnError(t *testing.T) {
h, _ := newTestServer()
failed(t, get(t, h, "GET", "/rest/doesNotExist", ok()), ErrGeneric)
}
func TestTheServerSpeaksTheExtensionsItHas(t *testing.T) {
h, _ := newTestServer()
r := good(t, get(t, h, "GET", "/rest/getOpenSubsonicExtensions", ok()))
names := map[string]bool{}
for _, e := range r["openSubsonicExtensions"].([]any) {
m := e.(map[string]any)
names[m["name"].(string)] = true
if len(m["versions"].([]any)) == 0 {
t.Errorf("%v has no version", m)
}
}
if !names["apiKeyAuthentication"] || !names["formPost"] {
t.Fatalf("extensions %v", names)
}
}
func TestExtensionsAreAnsweredWithoutALogin(t *testing.T) {
// An app asks what the server speaks before it has the person's password.
h, _ := newTestServer()
good(t, get(t, h, "GET", "/rest/getOpenSubsonicExtensions", url.Values{"f": {"json"}}))
}
func TestLicenseAndTokenInfo(t *testing.T) {
h, _ := newTestServer()
if l := good(t, get(t, h, "GET", "/rest/getLicense", ok()))["license"].(map[string]any); l["valid"] != true {
t.Fatalf("license %v", l)
}
if ti := good(t, get(t, h, "GET", "/rest/tokenInfo", ok()))["tokenInfo"].(map[string]any); ti["username"] != "tom@example.org" {
t.Fatalf("token info %v", ti)
}
}
func TestMusicFoldersAreTheLibraries(t *testing.T) {
h, _ := newTestServer()
f := good(t, get(t, h, "GET", "/rest/getMusicFolders", ok()))["musicFolders"].(map[string]any)["musicFolder"].([]any)
if len(f) != 2 || f[0].(map[string]any)["name"] != "Rock" || f[1].(map[string]any)["id"].(float64) != 2 {
t.Fatalf("folders %v", f)
}
}
func TestArtistsAreGroupedByTheirFirstLetter(t *testing.T) {
h, cat := newTestServer()
a := good(t, get(t, h, "GET", "/rest/getArtists", ok("musicFolderId", "2")))["artists"].(map[string]any)
if a["ignoredArticles"] != "" {
t.Fatalf("articles %v", a["ignoredArticles"])
}
var names []string
got := map[string][]string{}
for _, i := range a["index"].([]any) {
m := i.(map[string]any)
names = append(names, m["name"].(string))
for _, ar := range m["artist"].([]any) {
got[m["name"].(string)] = append(got[m["name"].(string)], ar.(map[string]any)["name"].(string))
}
}
if strings.Join(names, ",") != "#,B,R" {
t.Fatalf("groups %v", names)
}
if strings.Join(got["R"], ",") != "Radiohead,Radio Dept" || got["#"][0] != "3 Doors Down" {
t.Fatalf("artists %v", got)
}
first := a["index"].([]any)[2].(map[string]any)["artist"].([]any)[0].(map[string]any)
if first["id"] != "ar-1" || first["albumCount"].(float64) != 1 {
t.Fatalf("artist %v", first)
}
if len(cat.libs) == 0 || cat.libs[0] != 2 {
t.Fatalf("the folder was not asked for: %v", cat.libs)
}
}
func TestAnArtistHasItsAlbums(t *testing.T) {
h, _ := newTestServer()
a := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-1")))["artist"].(map[string]any)
if a["id"] != "ar-1" || a["name"] != "Radiohead" || a["albumCount"].(float64) != 1 {
t.Fatalf("artist %v", a)
}
al := a["album"].([]any)[0].(map[string]any)
if al["id"] != "al-7" || al["name"] != "OK Computer" || al["artistId"] != "ar-1" || al["artist"] != "Radiohead" ||
al["coverArt"] != "al-7" || al["songCount"].(float64) != 2 || al["duration"].(float64) != 600 ||
al["year"].(float64) != 1997 || al["genre"] != "alternative rock" || al["created"] != "2023-11-14T22:13:20.000Z" {
t.Fatalf("album %v", al)
}
}
func TestAnArtistWithNoAlbumsHasNoAlbumList(t *testing.T) {
h, _ := newTestServer()
a := good(t, get(t, h, "GET", "/rest/getArtist", ok("id", "ar-2")))["artist"].(map[string]any)
if _, has := a["album"]; has {
t.Fatalf("artist %v", a)
}
}
func TestAnAlbumHasItsSongs(t *testing.T) {
h, _ := newTestServer()
al := good(t, get(t, h, "GET", "/rest/getAlbum", ok("id", "al-7")))["album"].(map[string]any)
songs := al["song"].([]any)
if len(songs) != 2 || al["name"] != "OK Computer" {
t.Fatalf("album %v", al)
}
s := songs[0].(map[string]any)
want := map[string]any{
"id": "tr-70", "parent": "al-7", "isDir": false, "title": "Airbag", "album": "OK Computer", "artist": "Radiohead",
"track": 1.0, "discNumber": 1.0, "year": 1997.0, "genre": "alternative rock", "coverArt": "al-7", "size": 29000000.0,
"contentType": "audio/flac", "suffix": "flac", "duration": 284.0, "bitRate": 900.0, "albumId": "al-7", "artistId": "ar-1",
"type": "music", "mediaType": "song", "isVideo": false, "displayArtist": "Radiohead", "path": "Radiohead/OK Computer/01 - Airbag.flac",
}
for k, v := range want {
if s[k] != v {
t.Errorf("%s = %v, want %v", k, s[k], v)
}
}
if g := s["genres"].([]any); len(g) != 2 || g[1].(map[string]any)["name"] != "art rock" {
t.Errorf("genres %v", g)
}
if rg := s["replayGain"].(map[string]any); rg["trackGain"] != -6.5 {
t.Errorf("replay gain %v", rg)
}
k := songs[1].(map[string]any)
if k["contentType"] != "audio/mpeg" || k["artist"] != "Radiohead & Guest" || k["displayArtist"] != "Radiohead & Guest" {
t.Errorf("second song %v", k)
}
if a := k["artists"].([]any); len(a) != 2 || a[1].(map[string]any)["id"] != "ar-9" {
t.Errorf("artists of the second song %v", a)
}
}
func TestASongByItself(t *testing.T) {
h, _ := newTestServer()
s := good(t, get(t, h, "GET", "/rest/getSong", ok("id", "tr-71")))["song"].(map[string]any)
if s["title"] != "Karma Police" || s["id"] != "tr-71" {
t.Fatalf("song %v", s)
}
}
func TestTheIdsOfThingsThatAreNotThereAreNotFound(t *testing.T) {
h, _ := newTestServer()
for _, c := range [][2]string{
{"getArtist", "ar-99"}, {"getAlbum", "al-99"}, {"getSong", "tr-99"},
{"getArtist", "al-7"}, {"getAlbum", "tr-70"}, {"getSong", "12"}, {"getSong", "tr-x"}, {"getSong", "tr--1"},
} {
failed(t, get(t, h, "GET", "/rest/"+c[0], ok("id", c[1])), ErrNotFound)
}
for _, m := range []string{"getArtist", "getAlbum", "getSong"} {
failed(t, get(t, h, "GET", "/rest/"+m, ok()), ErrMissingParam)
}
}
func TestGenresHaveTheirSongsAndAlbums(t *testing.T) {
h, _ := newTestServer()
g := good(t, get(t, h, "GET", "/rest/getGenres", ok()))["genres"].(map[string]any)["genre"].([]any)
if len(g) != 2 || g[0].(map[string]any)["value"] != "alternative rock" || g[0].(map[string]any)["songCount"].(float64) != 1 {
t.Fatalf("genres %v", g)
}
}
func TestXMLHasTheValuesAsAttributesAndTheListsAsElements(t *testing.T) {
h, _ := newTestServer()
q := ok("id", "al-7")
q.Del("f")
got := get(t, h, "GET", "/rest/getAlbum", q).Body.String()
for _, want := range []string{`<album id="al-7" name="OK Computer"`, `<song id="tr-70" parent="al-7" isDir="false" title="Airbag"`, `<artists id="ar-1" name="Radiohead">`} {
if !strings.Contains(got, want) {
t.Errorf("missing %s in %s", want, got)
}
}
q = ok()
q.Del("f")
if g := get(t, h, "GET", "/rest/getGenres", q).Body.String(); !strings.Contains(g, `<genre songCount="1" albumCount="1">alternative rock</genre>`) {
t.Errorf("genres %s", g)
}
}
func TestAccentsAreTakenOffForTheLetterOfAnArtist(t *testing.T) {
for name, want := range map[string]string{"Édith Piaf": "E", "Ünïcode Band": "U", "björk": "B", "3 Doors Down": "#", "": "#", "!!!": "#", "Ζωή": "Ζ"} {
if got := indexLetter(name); got != want {
t.Errorf("%q: %q, want %q", name, got, want)
}
}
}