fix(devices): re-approving a known device rotates its token instead of 500

App reinstalls that preserve data (Android Studio installDebug over an
existing install) re-register with the same device_identifier, but the
devices row from the previous install still exists — device_identifier
is UNIQUE, so ApproveDevice's blind INSERT failed with a unique
violation and returned 500 'failed to create device' (reproduced via
curl: second approve with the same identifier = instant 500; the ~98s
in the original report was app-side retry/polling, not server wait).

ApproveDevice is now idempotent: look the device up by identifier
first; a row owned by the approving user gets its auth token rotated
via UpdateDeviceAuthToken (row id unchanged, so synced highlights/
bookmarks/progress anchored to it stay valid; fresh install = fresh
credentials, old token invalidated); a row owned by another user gets
409; unknown identifiers INSERT as before, with the 23505 race falling
through to the rotate path. DB failures are logged (they were silent).

Also guard the in-memory pendingRegistrations map with a mutex —
register/approve/reject/status/list all touch it from HTTP goroutines,
and a racing write is a Go runtime fatal, not an error. The approver's
credential publication and the status poller's approved-branch snapshot
now run under the lock so the token can never be read half-written.

Regression test: TestApproveDeviceReapprovalRotatesToken — register →
approve → re-register same identifier → approve (must be 200) → token
rotated, exactly one devices row, row carries the new token.
This commit is contained in:
John O'Keefe
2026-09-17 23:09:02 -04:00
parent b4c956aed4
commit 1cd8557b58
2 changed files with 204 additions and 20 deletions
+82
View File
@@ -252,6 +252,88 @@ func TestListPendingRegistrations(t *testing.T) {
assert.NotNil(t, pending, "Pending registrations should not be nil")
}
// Regression test for the "approve returns 500 after app reinstall" bug:
// an app reinstall that preserves data (e.g. Android Studio installDebug
// over an existing install) re-registers with the SAME device_identifier,
// and the blind INSERT in ApproveDevice hit the UNIQUE(device_identifier)
// constraint. Re-approval must be idempotent: same row (id unchanged),
// rotated token, old token invalidated.
func TestApproveDeviceReapprovalRotatesToken(t *testing.T) {
setup := setupTestServer(t)
userID := getTestUserID(t, setup.DB)
identifier := fmt.Sprintf("repro-reinstall-%s", uuid.New().String())
registerAndApprove := func() string {
regRequest := map[string]interface{}{
"device_name": "Reinstall Device",
"device_type": "mobile",
"device_identifier": identifier,
}
regBody, _ := json.Marshal(regRequest)
req := httptest.NewRequest("POST", "/api/devices/register", bytes.NewReader(regBody))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusCreated, rec.Code, "Should initiate registration")
var regResponse map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &regResponse)
registrationID, ok := regResponse["registration_id"].(string)
require.True(t, ok, "Should have registration_id")
req = httptest.NewRequest("GET", fmt.Sprintf("/api/devices/approve/%s", registrationID), nil)
req.Header.Set("Authorization", "Bearer "+setup.Token)
rec = httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code,
"Approve must succeed even when the identifier already exists (was the reinstall 500)")
// The status response is single-use and carries the credentials.
statusBody, _ := json.Marshal(map[string]string{"registration_id": registrationID})
req = httptest.NewRequest("POST", "/api/devices/register/status", bytes.NewReader(statusBody))
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var statusResponse map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &statusResponse)
require.Equal(t, "approved", statusResponse["status"])
token, ok := statusResponse["auth_token"].(string)
require.True(t, ok, "Should have auth_token")
require.NotEmpty(t, token)
return token
}
token1 := registerAndApprove()
token2 := registerAndApprove()
assert.NotEqual(t, token1, token2, "Re-approval must rotate the auth token (fresh install = fresh credentials)")
devices, err := setup.DB.ListDevicesByUser(context.Background(),
pgtype.UUID{Bytes: [16]byte(userID), Valid: true})
require.NoError(t, err)
rows := 0
for _, d := range devices {
if d.DeviceIdentifier == identifier {
rows++
}
}
assert.Equal(t, 1, rows, "Re-approval must reuse the existing devices row, not duplicate it")
// The rotated-in token must be the live one.
var live *database.Devices
for i := range devices {
if devices[i].DeviceIdentifier == identifier {
live = &devices[i]
}
}
require.NotNil(t, live)
assert.Equal(t, token2, live.AuthToken, "The devices row must carry the newly rotated token")
}
func TestApproveDeviceRegistration(t *testing.T) {
setup := setupTestServer(t)