fix(server): address review feedback

- writeDeleteManyResponse uses rest.RespondWithJSON, so the response now
  has Content-Type: application/json. This also removes a marshal error
  branch that could never run.
- createInitialAdminUser returns the CountAll error instead of panicking,
  and wraps its errors. initialSetup now stops the server with log.Fatal
  when setup fails. Before, the error was dropped and the server started
  with a half-done setup.
- Trim comments that described PR history.
This commit is contained in:
Deluan 2026-09-23 10:44:33 -04:00
parent 1fa2b7f393
commit 94aff0871a
8 changed files with 16 additions and 35 deletions

View File

@ -159,7 +159,6 @@ func createAdminUser(ctx context.Context, ds model.DataStore, username, password
}
err := ds.User(ctx).Put(&initialUser)
if err != nil {
// Log the username only: initialUser carries the password in clear text
log.Error(ctx, "Could not create initial user", "user", initialUser.UserName, err)
return fmt.Errorf("creating initial user: %w", err)
}

View File

@ -76,8 +76,6 @@ var _ = Describe("Auth", func() {
})
})
// createAdminUser used to swallow the Put error and return nil, so a failure
// fell through to doLogin and surfaced as a misleading 401.
Describe("createAdmin when the user cannot be stored", func() {
It("responds 500 rather than falling through to login", func() {
failing := dsWithFailingPut(errors.New("db is down"))

View File

@ -16,7 +16,7 @@ import (
func initialSetup(ds model.DataStore) {
ctx := context.TODO()
_ = ds.WithTx(func(tx model.DataStore) error {
err := ds.WithTx(func(tx model.DataStore) error {
if err := tx.Library(ctx).StoreMusicFolder(); err != nil {
return err
}
@ -36,6 +36,9 @@ func initialSetup(ds model.DataStore) {
err = properties.Put(consts.InitialSetupFlagKey, time.Now().String())
return err
}, "initial setup")
if err != nil {
log.Fatal("Error running initial setup", err)
}
}
// If the Dev Admin user is not present, create it
@ -43,7 +46,7 @@ func createInitialAdminUser(ds model.DataStore, initialPassword string) error {
users := ds.User(context.TODO())
c, err := users.CountAll(model.QueryOptions{Filters: squirrel.Eq{"user_name": consts.DevInitialUserName}})
if err != nil {
panic(fmt.Sprintf("Could not access User table: %s", err))
return fmt.Errorf("could not access User table: %w", err)
}
if c == 0 {
newID := id.NewRandom()
@ -57,14 +60,8 @@ func createInitialAdminUser(ds model.DataStore, initialPassword string) error {
NewPassword: initialPassword,
IsAdmin: true,
}
// The Put error used to be assigned to a shadowed err and dropped, so a
// failure was reported as success and initialSetup went on to commit the
// "setup complete" flag — leaving no admin user, and skipping setup on
// every later boot.
if err := users.Put(&initialUser); err != nil {
// Log the username rather than the whole struct, as everywhere else
log.Error("Could not create initial admin user", "user", consts.DevInitialUserName, err)
return err
return fmt.Errorf("could not create initial admin user: %w", err)
}
}
return nil

View File

@ -10,8 +10,6 @@ import (
. "github.com/onsi/gomega"
)
// failingPutUserRepo counts users normally but fails to store them, to exercise the
// error path of the initial user creation.
type failingPutUserRepo struct {
model.UserRepository
err error
@ -47,11 +45,15 @@ var _ = Describe("initial_setup", func() {
Expect(ur.CountAll()).To(Equal(int64(1)))
})
// The error was assigned to a shadowed err and dropped, so the caller saw
// success and went on to commit the "setup complete" flag.
It("returns the error when the user cannot be stored", func() {
boom := errors.New("db is down")
Expect(createInitialAdminUser(dsWithFailingPut(boom), "pass123")).To(MatchError(boom))
})
It("returns the error when the user table cannot be read", func() {
boom := errors.New("db is down")
ds = &tests.MockDataStore{MockedUser: &tests.MockedUserRepo{Error: boom}}
Expect(createInitialAdminUser(ds, "pass123")).To(MatchError(boom))
})
})
})

View File

@ -29,8 +29,6 @@ var _ = Describe("writeDeleteManyResponse", func() {
Expect(write("a", "b")).To(HaveKeyWithValue("ids", ConsistOf("a", "b")))
})
// ids come straight from the query string. html.EscapeString, used previously to
// build the single-id body, does not escape backslashes, so `{"id":"a\"}` went out.
It("stays valid JSON when the id contains a backslash", func() {
Expect(write(`a\`)).To(HaveKeyWithValue("id", `a\`))
})
@ -43,8 +41,9 @@ var _ = Describe("writeDeleteManyResponse", func() {
Expect(write("a&b")).To(HaveKeyWithValue("id", "a&b"))
})
It("responds 200 on success", func() {
It("responds 200 with a JSON content type", func() {
write("abc123")
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Type")).To(Equal("application/json"))
})
})

View File

@ -2,7 +2,6 @@ package nativeapi
import (
"context"
"encoding/json"
"net/http"
"strconv"
"time"
@ -205,9 +204,6 @@ func (api *Router) addMissingFilesRoute(r chi.Router) {
}
func writeDeleteManyResponse(w http.ResponseWriter, r *http.Request, ids []string) {
// Marshal both shapes instead of building the single-id case by hand: ids come
// from the query string, and html.EscapeString leaves backslashes untouched, so
// an id containing one produced a malformed body.
var payload any
if len(ids) == 1 {
payload = struct {
@ -218,13 +214,7 @@ func writeDeleteManyResponse(w http.ResponseWriter, r *http.Request, ids []strin
Ids []string `json:"ids"`
}{Ids: ids}
}
resp, err := json.Marshal(payload)
if err != nil {
log.Error(r.Context(), "Error marshaling response", "ids", ids, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := w.Write(resp); err != nil {
if err := rest.RespondWithJSON(w, http.StatusOK, payload); err != nil {
log.Error(r.Context(), "Error writing response", "ids", ids, err)
}
}

View File

@ -58,7 +58,6 @@ func (pub *Router) handleM3U(w http.ResponseWriter, r *http.Request) {
}
s = pub.mapShareToM3U(r, *s)
// Content-Type must be set before WriteHeader, otherwise it is dropped
w.Header().Set("Content-Type", "audio/x-mpegurl")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(s.ToM3U8())) //nolint:gosec

View File

@ -30,7 +30,6 @@ var _ = Describe("handleM3U", func() {
return w
}
// Content-Type used to be set after WriteHeader, which silently drops it.
It("sets the M3U content type", func() {
share := &model.Share{ID: "abc123", Tracks: model.MediaFiles{{ID: "t1", Title: "Track 1"}}}
shareRepo.ID = share.ID
@ -39,9 +38,7 @@ var _ = Describe("handleM3U", func() {
w := makeRequest("abc123")
Expect(w.Code).To(Equal(http.StatusOK))
// Result() reports the headers as they were when WriteHeader ran, which is
// what the client actually receives. w.Header() would still show a
// Content-Type set too late to be sent.
// Result() has the headers sent at WriteHeader time, unlike w.Header()
Expect(w.Result().Header.Get("Content-Type")).To(Equal("audio/x-mpegurl"))
Expect(w.Body.String()).To(HavePrefix("#EXTM3U"))
})