sonda/internal/devices/devices_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

272 lines
8.2 KiB
Go

package devices
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"errors"
"strings"
"testing"
"time"
)
// memStore keeps the rows in memory, like the database would, and lets a test look at what was stored.
type memStore struct {
rows []Row
nextID int64
emails map[int64]string // user id -> email
touched map[int64]time.Time
}
func (m *memStore) ByKeyHash(_ context.Context, hash string) (Row, error) {
for _, r := range m.rows {
if r.KeyHash == hash {
r.Email = m.emails[r.UserID]
return r, nil
}
}
return Row{}, ErrNotFound
}
func (m *memStore) ByEmail(_ context.Context, email string) ([]Row, error) {
var out []Row
for _, r := range m.rows {
if m.emails[r.UserID] == email {
r.Email = email
out = append(out, r)
}
}
return out, nil
}
func (m *memStore) Touch(_ context.Context, id int64, at time.Time) error {
if m.touched == nil {
m.touched = map[int64]time.Time{}
}
m.touched[id] = at
for i := range m.rows {
if m.rows[i].ID == id {
m.rows[i].LastUsedAt = &at
}
}
return nil
}
func (m *memStore) Create(_ context.Context, r Row) (Row, error) {
m.nextID++
r.ID = m.nextID
m.rows = append(m.rows, r)
return r, nil
}
func (m *memStore) List(_ context.Context, userID int64) ([]Row, error) {
var out []Row
for _, r := range m.rows {
if r.UserID == userID {
out = append(out, r)
}
}
return out, nil
}
func (m *memStore) Delete(_ context.Context, userID, id int64) error {
for i, r := range m.rows {
if r.ID == id && r.UserID == userID {
m.rows = append(m.rows[:i], m.rows[i+1:]...)
return nil
}
}
return ErrNotFound
}
func newService() (*Service, *memStore) {
st := &memStore{emails: map[int64]string{1: "alice@example.org", 2: "bob@example.org"}}
s := NewService(st, []byte(strings.Repeat("k", 32)))
s.now = func() time.Time { return time.Unix(1_700_000_000, 0) }
return s, st
}
func TestCreateGivesTheSecretOnceAndKeepsItSealed(t *testing.T) {
s, st := newService()
d, secret, err := s.Create(context.Background(), 1, " Phone ")
if err != nil {
t.Fatal(err)
}
if d.Name != "Phone" || d.ID == 0 || !d.CreatedAt.Equal(time.Unix(1_700_000_000, 0)) {
t.Fatalf("device %+v", d)
}
if len(secret) != 48 {
t.Fatalf("secret %q is not 24 bytes in hex", secret)
}
row := st.rows[0]
if bytes.Contains(row.Sealed, []byte(secret)) {
t.Fatal("the secret is stored in clear")
}
if row.KeyHash == "" || strings.Contains(row.KeyHash, secret) {
t.Fatalf("the lookup hash is %q", row.KeyHash)
}
back, err := s.Reveal(row.Sealed)
if err != nil || back != secret {
t.Fatalf("Reveal = %q, %v", back, err)
}
}
func TestTwoDevicesHaveDifferentSecrets(t *testing.T) {
s, st := newService()
_, a, _ := s.Create(context.Background(), 1, "A")
_, b, _ := s.Create(context.Background(), 1, "B")
if a == b || st.rows[0].KeyHash == st.rows[1].KeyHash {
t.Fatal("two devices share a secret")
}
}
func TestAnotherKeyCannotOpenASealedSecret(t *testing.T) {
s, st := newService()
_, _, _ = s.Create(context.Background(), 1, "Phone")
other := NewService(&memStore{}, []byte(strings.Repeat("z", 32)))
if _, err := other.Reveal(st.rows[0].Sealed); err == nil {
t.Fatal("a different key opened the secret")
}
if _, err := s.Reveal([]byte("short")); err == nil {
t.Fatal("a bad value was opened")
}
}
func TestTheNameIsRequiredAndShort(t *testing.T) {
s, _ := newService()
for _, name := range []string{"", " ", strings.Repeat("a", 61)} {
if _, _, err := s.Create(context.Background(), 1, name); !errors.Is(err, ErrInvalidName) {
t.Errorf("name %q: %v", name, err)
}
}
if _, _, err := s.Create(context.Background(), 1, strings.Repeat("à", 60)); err != nil {
t.Errorf("60 letters: %v", err)
}
}
func TestThereIsALimitOfDevicesForEachPerson(t *testing.T) {
s, _ := newService()
for i := 0; i < MaxDevices; i++ {
if _, _, err := s.Create(context.Background(), 1, "d"); err != nil {
t.Fatal(err)
}
}
if _, _, err := s.Create(context.Background(), 1, "one more"); !errors.Is(err, ErrTooMany) {
t.Fatalf("over the limit: %v", err)
}
if _, _, err := s.Create(context.Background(), 2, "someone else"); err != nil {
t.Fatalf("another person: %v", err)
}
}
func TestListShowsOwnDevicesNewestFirstWithoutSecrets(t *testing.T) {
s, _ := newService()
_, _, _ = s.Create(context.Background(), 1, "first")
_, _, _ = s.Create(context.Background(), 2, "not mine")
_, _, _ = s.Create(context.Background(), 1, "second")
got, err := s.List(context.Background(), 1)
if err != nil || len(got) != 2 || got[0].Name != "second" || got[1].Name != "first" {
t.Fatalf("List = %+v, %v", got, err)
}
}
func TestRevokeIsForTheOwnerOnly(t *testing.T) {
s, _ := newService()
d, _, _ := s.Create(context.Background(), 1, "Phone")
if err := s.Revoke(context.Background(), 2, d.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("someone else: %v", err)
}
if err := s.Revoke(context.Background(), 1, d.ID); err != nil {
t.Fatal(err)
}
if err := s.Revoke(context.Background(), 1, d.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("twice: %v", err)
}
}
func md5hex(s string) string {
sum := md5.Sum([]byte(s))
return hex.EncodeToString(sum[:])
}
func TestAnApiKeyFindsItsDevice(t *testing.T) {
s, st := newService()
d, secret, _ := s.Create(context.Background(), 1, "Phone")
p, err := s.ByKey(context.Background(), secret)
if err != nil || p.UserID != 1 || p.DeviceID != d.ID || p.Email != "alice@example.org" {
t.Fatalf("ByKey = %+v, %v", p, err)
}
if _, err := s.ByKey(context.Background(), strings.Repeat("0", 48)); !errors.Is(err, ErrBadCredentials) {
t.Fatalf("a key nobody has: %v", err)
}
if _, err := s.ByKey(context.Background(), ""); !errors.Is(err, ErrBadCredentials) {
t.Fatalf("no key: %v", err)
}
if st.touched[d.ID].IsZero() {
t.Fatal("the use of the device was not noted")
}
}
func TestATokenIsChecked(t *testing.T) {
s, _ := newService()
_, secret, _ := s.Create(context.Background(), 1, "Phone")
_, other, _ := s.Create(context.Background(), 1, "Laptop")
ctx := context.Background()
if p, err := s.ByToken(ctx, "Alice@Example.org ", md5hex(secret+"c19f3a"), "c19f3a"); err != nil || p.UserID != 1 {
t.Fatalf("right token: %+v, %v", p, err)
}
if p, err := s.ByToken(ctx, "alice@example.org", md5hex(other+"salt12"), "salt12"); err != nil || p.UserID != 1 {
t.Fatalf("the other device: %+v, %v", p, err)
}
for name, c := range map[string][3]string{
"wrong secret": {"alice@example.org", md5hex("nope" + "salt12"), "salt12"},
"wrong user": {"bob@example.org", md5hex(secret + "salt12"), "salt12"},
"unknown user": {"zed@example.org", md5hex(secret + "salt12"), "salt12"},
"no salt": {"alice@example.org", md5hex(secret), ""},
"no token": {"alice@example.org", "", "salt12"},
} {
if _, err := s.ByToken(ctx, c[0], c[1], c[2]); !errors.Is(err, ErrBadCredentials) {
t.Errorf("%s: %v", name, err)
}
}
}
func TestAPlainPasswordIsChecked(t *testing.T) {
s, _ := newService()
_, secret, _ := s.Create(context.Background(), 1, "Phone")
ctx := context.Background()
if p, err := s.ByPassword(ctx, "alice@example.org", secret); err != nil || p.UserID != 1 {
t.Fatalf("plain: %+v, %v", p, err)
}
if p, err := s.ByPassword(ctx, "alice@example.org", "enc:"+hex.EncodeToString([]byte(secret))); err != nil || p.UserID != 1 {
t.Fatalf("hex: %+v, %v", p, err)
}
for _, pw := range []string{"", "nope", "enc:zz", "enc:" + hex.EncodeToString([]byte("nope"))} {
if _, err := s.ByPassword(ctx, "alice@example.org", pw); !errors.Is(err, ErrBadCredentials) {
t.Errorf("%q: %v", pw, err)
}
}
if _, err := s.ByPassword(ctx, "bob@example.org", secret); !errors.Is(err, ErrBadCredentials) {
t.Errorf("someone else's: %v", err)
}
}
func TestTheUseOfADeviceIsNotedOncePerTenMinutes(t *testing.T) {
s, st := newService()
d, secret, _ := s.Create(context.Background(), 1, "Phone")
ctx := context.Background()
_, _ = s.ByKey(ctx, secret)
first := st.touched[d.ID]
s.now = func() time.Time { return first.Add(5 * time.Minute) }
_, _ = s.ByKey(ctx, secret)
if !st.touched[d.ID].Equal(first) {
t.Fatal("noted again after five minutes")
}
s.now = func() time.Time { return first.Add(11 * time.Minute) }
_, _ = s.ByKey(ctx, secret)
if !st.touched[d.ID].Equal(first.Add(11 * time.Minute)) {
t.Fatal("not noted after eleven minutes")
}
}