feat: a password for each app or device

A person can make a password for each app that connects to their server, in
Settings, Apps and devices. The secret is shown once, can be taken back, and
is for the music API of other apps only: it cannot sign in or change the
account. Secrets are kept sealed (AES-256-GCM, key derived from the jwt secret)
because token login needs them in clear, and a hash finds a device by its key.

- migration 0034 device_passwords (sqlite, postgres)
- internal/devices service, storage repo
- GET/POST /me/devices, DELETE /me/devices/{id}, in the OpenAPI spec
- Settings section with copy and remove
This commit is contained in:
tgiachi 2026-11-16 09:15:25 +01:00
commit 010f2e5057
11 changed files with 1368 additions and 11 deletions

View file

@ -19,6 +19,7 @@ import (
"git.kmalloc.org/squid/sonda/internal/affinity"
"git.kmalloc.org/squid/sonda/internal/auth"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/devices"
"git.kmalloc.org/squid/sonda/internal/discover"
"git.kmalloc.org/squid/sonda/internal/discovery"
"git.kmalloc.org/squid/sonda/internal/duplicates"
@ -115,6 +116,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
Settings: usersettings.NewService(storage.NewUserSettingsRepo(db)),
Streams: streaming.NewService(noFiles{}),
Federation: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()),
Devices: devices.NewService(storage.NewDevicesRepo(db), []byte(strings.Repeat("k", 32))),
Mastodon: mastodon.NewService(storage.NewMastodonRepo(db), &fakeMastodon{handle: "@test@mastodon.social"}, zap.NewNop()),
}
libRepo := storage.NewLibraryRepo(db)

View file

@ -888,6 +888,22 @@ func TestResponsesMatchTheSpec(t *testing.T) {
c.expect(c.call("DELETE", "/me/mastodon", token, nil), 204, "disconnect Mastodon")
c.expect(c.call("GET", "/me/mastodon", "", nil), 401, "Mastodon without a token", "unauthorized")
// The passwords of other apps: the secret is shown once, and a device is taken back by its owner only.
if got := c.expect(c.call("GET", "/me/devices", token, nil), 200, "no devices yet"); len(got["devices"].([]any)) != 0 {
c.t.Errorf("devices = %v", got)
}
made := c.expect(c.call("POST", "/me/devices", token, map[string]any{"name": "Phone"}), 201, "make a device")
if len(made["secret"].(string)) != 48 {
c.t.Errorf("secret = %v", made["secret"])
}
c.expect(c.call("POST", "/me/devices", token, map[string]any{"name": " "}), 400, "a device with no name", "invalid_name")
if got := c.expect(c.call("GET", "/me/devices", token, nil), 200, "the devices"); len(got["devices"].([]any)) != 1 {
c.t.Errorf("devices = %v", got)
}
c.expect(c.call("DELETE", "/me/devices/"+idOf(made), token, nil), 204, "take back a device")
c.expect(c.call("DELETE", "/me/devices/"+idOf(made), token, nil), 404, "take back a device twice", "device_not_found")
c.expect(c.call("GET", "/me/devices", "", nil), 401, "devices without a token", "unauthorized")
// Bringing a Spotify export in: what it did, and what is refused.
export := `[{"ts":"2023-05-01T10:00:00Z","ms_played":200000,"master_metadata_track_name":"Nowhere","master_metadata_album_artist_name":"Nobody"}]`
imported := c.expect(c.upload("/me/import/spotify", token, export, `{"playlists":[{"name":"P","items":[{"track":{"trackName":"Nowhere","artistName":"Nobody"}}]}]}`), 200, "import a Spotify export")

View file

@ -0,0 +1,102 @@
package httpapi
import (
"net/http"
"strings"
"testing"
)
func TestDevicesNeedASignedInUser(t *testing.T) {
h := newTestAPI(t)
for _, c := range [][2]string{{"GET", "/api/v1/me/devices"}, {"POST", "/api/v1/me/devices"}, {"DELETE", "/api/v1/me/devices/1"}} {
if r := do(t, h, c[0], c[1], "", map[string]any{}); r.Code != http.StatusUnauthorized {
t.Errorf("%s %s without a token: %d", c[0], c[1], r.Code)
}
}
}
func TestADeviceIsMadeShownOnceAndTakenBack(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/me/devices", alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
if list, ok := r.Body["devices"].([]any); !ok || len(list) != 0 {
t.Fatalf("devices at the start: %v", r.Body)
}
r = do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Phone"})
if r.Code != http.StatusCreated {
t.Fatalf("create: %d %v", r.Code, r.Body)
}
sameKeys(t, "created device", r.Body, "id", "name", "created_at", "secret")
secret, _ := r.Body["secret"].(string)
if len(secret) != 48 || r.Body["name"] != "Phone" {
t.Fatalf("created = %v", r.Body)
}
r = do(t, h, "GET", "/api/v1/me/devices", alice, nil)
list, _ := r.Body["devices"].([]any)
if len(list) != 1 {
t.Fatalf("list = %v", r.Body)
}
one := list[0].(map[string]any)
sameKeys(t, "listed device", one, "id", "name", "created_at")
if strings.Contains(r.Body["devices"].([]any)[0].(map[string]any)["name"].(string), secret) {
t.Fatal("the secret is in the list")
}
id := int64(one["id"].(float64))
path := "/api/v1/me/devices/" + itoa(id)
if r := do(t, h, "DELETE", path, alice, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete: %d %v", r.Code, r.Body)
}
if r := do(t, h, "DELETE", path, alice, nil); r.Code != http.StatusNotFound || errCode(r) != "device_not_found" {
t.Fatalf("delete twice: %d %v", r.Code, r.Body)
}
}
func TestADeviceNeedsAName(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
for _, body := range []any{map[string]any{"name": " "}, map[string]any{}, map[string]any{"name": strings.Repeat("a", 61)}} {
if r := do(t, h, "POST", "/api/v1/me/devices", alice, body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_name" {
t.Errorf("%v: %d %v", body, r.Code, r.Body)
}
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, "{not json"); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("bad json: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "ok", "extra": 1}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("unknown name: %d %v", r.Code, r.Body)
}
}
func TestADeviceOfSomeoneElseIsNotFound(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Phone"})
id := int64(r.Body["id"].(float64))
_, bob := addUser(t, h, alice, "bob", false)
if r := do(t, h, "DELETE", "/api/v1/me/devices/"+itoa(id), bob, nil); r.Code != http.StatusNotFound {
t.Fatalf("bob deleted alice's device: %d", r.Code)
}
if r := do(t, h, "GET", "/api/v1/me/devices", bob, nil); len(r.Body["devices"].([]any)) != 0 {
t.Fatalf("bob sees %v", r.Body)
}
}
func TestTooManyDevices(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
for i := 0; i < 20; i++ {
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "d"}); r.Code != http.StatusCreated {
t.Fatalf("%d: %d", i, r.Code)
}
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "d"}); r.Code != http.StatusConflict || errCode(r) != "too_many_devices" {
t.Fatalf("over the limit: %d %v", r.Code, r.Body)
}
}

View file

@ -0,0 +1,105 @@
package httpapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/devices"
)
// deviceService is what the handlers need from devices.Service.
type deviceService interface {
Create(ctx context.Context, userID int64, name string) (devices.Device, string, error)
List(ctx context.Context, userID int64) ([]devices.Device, error)
Revoke(ctx context.Context, userID, id int64) error
}
// deviceHandlers serve the passwords of the signed-in user's apps and devices.
type deviceHandlers struct{ svc deviceService }
// deviceJSON is a device as a person sees it: never with its secret, except in the answer that makes it.
type deviceJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}
type createdDeviceJSON struct {
deviceJSON
Secret string `json:"secret"`
}
func toDeviceJSON(d devices.Device) deviceJSON {
return deviceJSON{ID: d.ID, Name: d.Name, CreatedAt: d.CreatedAt.UTC(), LastUsedAt: d.LastUsedAt}
}
func (h *deviceHandlers) list(c *gin.Context) {
list, err := h.svc.List(c.Request.Context(), currentUserID(c))
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
out := make([]deviceJSON, len(list))
for i, d := range list {
out[i] = toDeviceJSON(d)
}
c.JSON(http.StatusOK, gin.H{"devices": out})
}
func (h *deviceHandlers) create(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
return
}
// One object with the name and nothing else: what comes back is a secret.
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
var req struct {
Name string `json:"name"`
}
if err := dec.Decode(&req); err != nil || dec.More() {
writeError(c, http.StatusBadRequest, "invalid_input", "send the name of the device")
return
}
d, secret, err := h.svc.Create(c.Request.Context(), currentUserID(c), req.Name)
switch {
case errors.Is(err, devices.ErrInvalidName):
writeError(c, http.StatusBadRequest, "invalid_name", err.Error())
case errors.Is(err, devices.ErrTooMany):
writeError(c, http.StatusConflict, "too_many_devices", err.Error())
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusCreated, createdDeviceJSON{deviceJSON: toDeviceJSON(d), Secret: secret})
}
}
func (h *deviceHandlers) revoke(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id < 1 {
writeError(c, http.StatusNotFound, "device_not_found", "device not found")
return
}
switch err := h.svc.Revoke(c.Request.Context(), currentUserID(c), id); {
case errors.Is(err, devices.ErrNotFound):
writeError(c, http.StatusNotFound, "device_not_found", "device not found")
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.Status(http.StatusNoContent)
}
}

View file

@ -228,6 +228,7 @@ type Deps struct {
Tokens tokenParser
Listening listenService
Mastodon mastodonService
Devices deviceService
Scan scanService
Libraries libraryService
Catalog catalogService
@ -393,6 +394,10 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/me/mastodon", ma.get)
protected.PUT("/me/mastodon", ma.connect)
protected.DELETE("/me/mastodon", ma.disconnect)
dv := &deviceHandlers{svc: d.Devices}
protected.GET("/me/devices", dv.list)
protected.POST("/me/devices", dv.create)
protected.DELETE("/me/devices/:id", dv.revoke)
lib := &libraryHandlers{scan: d.Scan}
protected.GET("/library/scan", lib.scanStatus)

View file

@ -2271,6 +2271,73 @@ paths:
'204': {description: Disconnected.}
'401': {$ref: '#/components/responses/Unauthorized'}
/me/devices:
get:
tags: [Taste]
operationId: listMyDevices
summary: The passwords of your apps and devices
description: |
The device passwords you made for other apps (OpenSubsonic clients), newest first. The secret is never sent
back: it was shown once, when the password was made.
security: [{bearerAuth: []}]
responses:
'200':
description: Your devices.
content:
application/json:
schema: {$ref: '#/components/schemas/DeviceList'}
'401': {$ref: '#/components/responses/Unauthorized'}
post:
tags: [Taste]
operationId: createMyDevice
summary: Make a password for an app or device
description: |
Makes a password for one app or device and returns it. **The secret is shown only in this answer**: copy it into
the app now. It opens the music API for other apps and nothing else: it cannot sign in to Sonda, change your
account or make more passwords. Make one for each app, so that you can take back one without the others. You can
have up to 20. The body must be one JSON object with the name and nothing else.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/CreateDevice'}
responses:
'201':
description: The device, with its secret.
content:
application/json:
schema: {$ref: '#/components/schemas/CreatedDevice'}
'400':
description: The body is malformed (`invalid_input`) or the name is empty or longer than 60 characters (`invalid_name`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
'401': {$ref: '#/components/responses/Unauthorized'}
'409':
description: You have 20 devices already (`too_many_devices`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/me/devices/{id}:
delete:
tags: [Taste]
operationId: deleteMyDevice
summary: Take back the password of a device
description: "Takes back the password, so the app that had it can no longer connect. Only your own devices."
security: [{bearerAuth: []}]
parameters:
- {name: id, in: path, required: true, schema: {type: integer, format: int64}}
responses:
'204': {description: Taken back.}
'401': {$ref: '#/components/responses/Unauthorized'}
'404':
description: There is no such device of yours (`device_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/me/import/spotify:
get:
tags: [Taste]
@ -6016,6 +6083,42 @@ components:
name: {type: string}
count: {type: integer, description: 'Plays and playlist songs of this artist that were not found.'}
Device:
type: object
additionalProperties: false
required: [id, name, created_at]
properties:
id: {type: integer, format: int64}
name: {type: string, maxLength: 60}
created_at: {type: string, format: date-time}
last_used_at: {type: string, format: date-time, description: "When an app last connected with it. Absent until it does."}
DeviceList:
type: object
additionalProperties: false
required: [devices]
properties:
devices:
type: array
items: {$ref: '#/components/schemas/Device'}
CreateDevice:
type: object
additionalProperties: false
required: [name]
properties:
name: {type: string, maxLength: 60, description: "What this password is for, like `Phone` or `Feishin on the laptop`."}
CreatedDevice:
type: object
additionalProperties: false
required: [id, name, created_at, secret]
properties:
id: {type: integer, format: int64}
name: {type: string, maxLength: 60}
created_at: {type: string, format: date-time}
secret: {type: string, description: "The password, 48 characters. Shown only here: it is never sent again."}
MastodonAccount:
type: object
additionalProperties: false

173
internal/devices/devices.go Normal file
View file

@ -0,0 +1,173 @@
// Package devices keeps the passwords a person makes for the apps and devices that connect to their server.
//
// A device password is a long random secret, shown once, that opens the music API for other apps (the OpenSubsonic
// one) and nothing else: it cannot sign in to Sonda, change the account or make more passwords. A person can have one
// for each phone or app and take it back at any time, so the account password never goes to an app.
//
// Subsonic's token login sends md5(secret + salt), so the server must know the secret itself, not a hash of it. The
// secret is therefore kept sealed (AES-256-GCM, with a key derived from the server's jwt secret): a copy of the
// database alone does not tell it. A hash of the secret is kept too, to find the device of an API key without trying
// every one.
package devices
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sort"
"strings"
"time"
"unicode/utf8"
)
// Errors returned by the service.
var (
ErrNotFound = errors.New("device not found")
ErrInvalidName = errors.New("the name must have 1 to 60 characters")
ErrTooMany = errors.New("there are too many devices: remove one first")
)
const (
// MaxDevices is how many a person can have: far more than anyone uses, and a bound on the work of a login.
MaxDevices = 20
// MaxName is the longest name, in characters.
MaxName = 60
secretSize = 24
)
// Device is what a person sees of a device: never the secret.
type Device struct {
ID int64
Name string
CreatedAt time.Time
LastUsedAt *time.Time // nil until the device is used
}
// Row is a device as it is stored.
type Row struct {
ID int64
UserID int64
Name string
KeyHash string // hex sha256 of the secret, to find it when only the secret is known
Sealed []byte // the secret, sealed
CreatedAt time.Time
LastUsedAt *time.Time
}
// Store keeps the devices.
type Store interface {
// Create stores a device and returns it with its id.
Create(ctx context.Context, r Row) (Row, error)
// List returns the devices of a person.
List(ctx context.Context, userID int64) ([]Row, error)
// Delete removes a device of a person, with ErrNotFound when there is none.
Delete(ctx context.Context, userID, id int64) error
}
// Service makes and takes back device passwords.
type Service struct {
store Store
aead cipher.AEAD
now func() time.Time
}
// NewService builds a Service. secret is the server's jwt secret: the key that seals the passwords comes from it, so
// a server that changes it makes the people make their device passwords again.
func NewService(store Store, secret []byte) *Service {
key, err := hkdf.Key(sha256.New, secret, nil, "sonda device passwords", 32)
if err != nil {
panic(fmt.Sprintf("devices: derive key: %v", err)) // only for a length that is out of range
}
block, err := aes.NewCipher(key)
if err != nil {
panic(fmt.Sprintf("devices: cipher: %v", err)) // a 32-byte key is always valid
}
aead, err := cipher.NewGCM(block)
if err != nil {
panic(fmt.Sprintf("devices: gcm: %v", err))
}
return &Service{store: store, aead: aead, now: time.Now}
}
// Create makes a device for a person and returns it with its secret, which is never given again.
func (s *Service) Create(ctx context.Context, userID int64, name string) (Device, string, error) {
name = strings.TrimSpace(name)
if n := utf8.RuneCountInString(name); n == 0 || n > MaxName {
return Device{}, "", ErrInvalidName
}
rows, err := s.store.List(ctx, userID)
if err != nil {
return Device{}, "", fmt.Errorf("list devices: %w", err)
}
if len(rows) >= MaxDevices {
return Device{}, "", ErrTooMany
}
raw := make([]byte, secretSize)
if _, err := rand.Read(raw); err != nil {
return Device{}, "", fmt.Errorf("generate secret: %w", err)
}
secret := hex.EncodeToString(raw)
row, err := s.store.Create(ctx, Row{
UserID: userID, Name: name, KeyHash: KeyHash(secret), Sealed: s.seal(secret), CreatedAt: s.now(),
})
if err != nil {
return Device{}, "", fmt.Errorf("create device: %w", err)
}
return device(row), secret, nil
}
// List returns the devices of a person, the newest first.
func (s *Service) List(ctx context.Context, userID int64) ([]Device, error) {
rows, err := s.store.List(ctx, userID)
if err != nil {
return nil, fmt.Errorf("list devices: %w", err)
}
sort.Slice(rows, func(i, j int) bool { return rows[i].ID > rows[j].ID })
out := make([]Device, len(rows))
for i, r := range rows {
out[i] = device(r)
}
return out, nil
}
// Revoke takes back the password of a device of a person: the app that had it can no longer connect.
func (s *Service) Revoke(ctx context.Context, userID, id int64) error {
return s.store.Delete(ctx, userID, id)
}
// Reveal opens a sealed secret.
func (s *Service) Reveal(sealed []byte) (string, error) {
n := s.aead.NonceSize()
if len(sealed) < n+s.aead.Overhead() {
return "", errors.New("devices: sealed secret is too short")
}
plain, err := s.aead.Open(nil, sealed[:n], sealed[n:], nil)
if err != nil {
return "", errors.New("devices: cannot open the sealed secret")
}
return string(plain), nil
}
func (s *Service) seal(secret string) []byte {
nonce := make([]byte, s.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
panic(fmt.Sprintf("devices: nonce: %v", err)) // the system source of randomness failed: nothing is safe
}
return s.aead.Seal(nonce, nonce, []byte(secret), nil)
}
// KeyHash is what is kept to find a device by its secret.
func KeyHash(secret string) string {
sum := sha256.Sum256([]byte(secret))
return hex.EncodeToString(sum[:])
}
func device(r Row) Device {
return Device{ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, LastUsedAt: r.LastUsedAt}
}

View file

@ -0,0 +1,148 @@
package devices
import (
"bytes"
"context"
"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
}
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{}
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)
}
}

View file

@ -0,0 +1,72 @@
package storage
import (
"context"
"fmt"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/devices"
)
type deviceRow struct {
bun.BaseModel `bun:"table:device_passwords"`
ID int64 `bun:"id,pk,autoincrement"`
UserID int64 `bun:"user_id,notnull"`
Name string `bun:"name,notnull"`
KeyHash string `bun:"key_hash,notnull"`
Sealed []byte `bun:"sealed,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
LastUsedAt *int64 `bun:"last_used_at"`
}
func (r deviceRow) device() devices.Row {
out := devices.Row{ID: r.ID, UserID: r.UserID, Name: r.Name, KeyHash: r.KeyHash, Sealed: r.Sealed, CreatedAt: time.Unix(r.CreatedAt, 0)}
if r.LastUsedAt != nil {
t := time.Unix(*r.LastUsedAt, 0)
out.LastUsedAt = &t
}
return out
}
// DevicesRepo keeps the passwords of apps and devices. It implements devices.Store.
type DevicesRepo struct{ db *bun.DB }
// NewDevicesRepo builds a DevicesRepo.
func NewDevicesRepo(db *bun.DB) *DevicesRepo { return &DevicesRepo{db: db} }
// Create stores a device and returns it with its id.
func (r *DevicesRepo) Create(ctx context.Context, d devices.Row) (devices.Row, error) {
row := &deviceRow{UserID: d.UserID, Name: d.Name, KeyHash: d.KeyHash, Sealed: d.Sealed, CreatedAt: d.CreatedAt.Unix()}
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
return devices.Row{}, fmt.Errorf("insert device: %w", err)
}
return row.device(), nil
}
// List returns the devices of a person.
func (r *DevicesRepo) List(ctx context.Context, userID int64) ([]devices.Row, error) {
var rows []deviceRow
if err := r.db.NewSelect().Model(&rows).Where("user_id = ?", userID).Order("id DESC").Scan(ctx); err != nil {
return nil, fmt.Errorf("select devices: %w", err)
}
out := make([]devices.Row, len(rows))
for i, row := range rows {
out[i] = row.device()
}
return out, nil
}
// Delete removes a device of a person, with devices.ErrNotFound when there is none.
func (r *DevicesRepo) Delete(ctx context.Context, userID, id int64) error {
res, err := r.db.NewDelete().Model((*deviceRow)(nil)).Where("id = ? AND user_id = ?", id, userID).Exec(ctx)
if err != nil {
return fmt.Errorf("delete device: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return devices.ErrNotFound
}
return nil
}

View file

@ -0,0 +1,82 @@
package storage
import (
"context"
"errors"
"testing"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/devices"
)
func TestDevicesAreKeptListedAndTakenBack(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
alice, bob := seedUser(t, db, "a@example.org"), seedUser(t, db, "b@example.org")
at := time.Unix(1_700_000_000, 0)
first, err := repo.Create(ctx, devices.Row{UserID: alice, Name: "Phone", KeyHash: "h1", Sealed: []byte{1, 2, 3}, CreatedAt: at})
if err != nil || first.ID == 0 {
t.Fatalf("Create = %+v, %v", first, err)
}
if _, err := repo.Create(ctx, devices.Row{UserID: bob, Name: "Tablet", KeyHash: "h2", Sealed: []byte{4}, CreatedAt: at}); err != nil {
t.Fatal(err)
}
got, err := repo.List(ctx, alice)
if err != nil || len(got) != 1 {
t.Fatalf("List = %+v, %v", got, err)
}
if g := got[0]; g.ID != first.ID || g.Name != "Phone" || g.KeyHash != "h1" || string(g.Sealed) != "\x01\x02\x03" || !g.CreatedAt.Equal(at) || g.LastUsedAt != nil {
t.Fatalf("row %+v", g)
}
if err := repo.Delete(ctx, bob, first.ID); !errors.Is(err, devices.ErrNotFound) {
t.Fatalf("someone else's device: %v", err)
}
if err := repo.Delete(ctx, alice, first.ID); err != nil {
t.Fatal(err)
}
if err := repo.Delete(ctx, alice, first.ID); !errors.Is(err, devices.ErrNotFound) {
t.Fatalf("twice: %v", err)
}
if got, _ := repo.List(ctx, alice); len(got) != 0 {
t.Fatalf("after delete: %+v", got)
}
})
}
func TestTwoDevicesCannotShareASecret(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
uid := seedUser(t, db, "a@example.org")
row := devices.Row{UserID: uid, Name: "A", KeyHash: "same", Sealed: []byte{1}, CreatedAt: time.Unix(1, 0)}
if _, err := repo.Create(ctx, row); err != nil {
t.Fatal(err)
}
if _, err := repo.Create(ctx, row); err == nil {
t.Fatal("the same secret was kept twice")
}
})
}
func TestDevicesGoWithTheirPerson(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
uid := seedUser(t, db, "a@example.org")
if _, err := repo.Create(ctx, devices.Row{UserID: uid, Name: "A", KeyHash: "h", Sealed: []byte{1}, CreatedAt: time.Unix(1, 0)}); err != nil {
t.Fatal(err)
}
if _, err := db.ExecContext(ctx, "DELETE FROM users WHERE id = ?", uid); err != nil {
t.Fatal(err)
}
var n int
if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM device_passwords").Scan(&n); err != nil || n != 0 {
t.Fatalf("%d devices left, %v", n, err)
}
})
}

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 33 {
t.Errorf("applied migrations = %d, want 33", applied)
if applied != 34 {
t.Errorf("applied migrations = %d, want 34", applied)
}
})
}