mirror of
https://github.com/henrygd/beszel.git
synced 2026-09-21 08:57:48 +02:00
Merge commit from fork
* fix: make first-user bootstrap atomic * add tests --------- Co-authored-by: henrygd <hank@henrygd.me>
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
@@ -15,6 +16,8 @@ type UserManager struct {
|
||||
app core.App
|
||||
}
|
||||
|
||||
var errBootstrapUnavailable = errors.New("bootstrap unavailable")
|
||||
|
||||
func NewUserManager(app core.App) *UserManager {
|
||||
return &UserManager{
|
||||
app: app,
|
||||
@@ -59,17 +62,7 @@ func (um *UserManager) InitializeUserSettings(e *core.RecordEvent) error {
|
||||
// Custom API endpoint to create the first user.
|
||||
// Mimics previous default behavior in PocketBase < 0.23.0 allowing user to be created through the Beszel UI.
|
||||
func (um *UserManager) CreateFirstUser(e *core.RequestEvent) error {
|
||||
// check that there are no users
|
||||
totalUsers, err := um.app.CountRecords("users")
|
||||
if err != nil || totalUsers > 0 {
|
||||
return e.JSON(http.StatusForbidden, map[string]string{"err": "Forbidden"})
|
||||
}
|
||||
// check that there is only one superuser and the email matches the email of the superuser we set up in initial-settings.go
|
||||
adminUsers, err := um.app.FindAllRecords(core.CollectionNameSuperusers)
|
||||
if err != nil || len(adminUsers) != 1 || adminUsers[0].GetString("email") != migrations.TempAdminEmail {
|
||||
return e.JSON(http.StatusForbidden, map[string]string{"err": "Forbidden"})
|
||||
}
|
||||
// create first user using supplied email and password in request body
|
||||
// Consume the complete body before evaluating the one-time bootstrap state.
|
||||
data := struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
@@ -81,26 +74,55 @@ func (um *UserManager) CreateFirstUser(e *core.RequestEvent) error {
|
||||
return e.JSON(http.StatusBadRequest, map[string]string{"err": "Bad request"})
|
||||
}
|
||||
|
||||
collection, _ := um.app.FindCollectionByNameOrId("users")
|
||||
user := core.NewRecord(collection)
|
||||
user.SetEmail(data.Email)
|
||||
user.SetPassword(data.Password)
|
||||
user.Set("role", "admin")
|
||||
user.Set("verified", true)
|
||||
if err := um.app.Save(user); err != nil {
|
||||
return e.JSON(http.StatusInternalServerError, map[string]string{"err": err.Error()})
|
||||
}
|
||||
// create superuser using the email of the first user
|
||||
collection, _ = um.app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
|
||||
adminUser := core.NewRecord(collection)
|
||||
adminUser.SetEmail(data.Email)
|
||||
adminUser.SetPassword(data.Password)
|
||||
if err := um.app.Save(adminUser); err != nil {
|
||||
return e.JSON(http.StatusInternalServerError, map[string]string{"err": err.Error()})
|
||||
}
|
||||
// delete the intial superuser
|
||||
if err := um.app.Delete(adminUsers[0]); err != nil {
|
||||
err := um.app.RunInTransaction(func(txApp core.App) error {
|
||||
totalUsers, err := txApp.CountRecords("users")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if totalUsers > 0 {
|
||||
return errBootstrapUnavailable
|
||||
}
|
||||
|
||||
adminUsers, err := txApp.FindAllRecords(core.CollectionNameSuperusers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(adminUsers) != 1 || adminUsers[0].GetString("email") != migrations.TempAdminEmail {
|
||||
return errBootstrapUnavailable
|
||||
}
|
||||
|
||||
collection, err := txApp.FindCollectionByNameOrId("users")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user := core.NewRecord(collection)
|
||||
user.SetEmail(data.Email)
|
||||
user.SetPassword(data.Password)
|
||||
user.Set("role", "admin")
|
||||
user.Set("verified", true)
|
||||
if err := txApp.Save(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection, err = txApp.FindCollectionByNameOrId(core.CollectionNameSuperusers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
adminUser := core.NewRecord(collection)
|
||||
adminUser.SetEmail(data.Email)
|
||||
adminUser.SetPassword(data.Password)
|
||||
if err := txApp.Save(adminUser); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return txApp.Delete(adminUsers[0])
|
||||
})
|
||||
if errors.Is(err, errBootstrapUnavailable) {
|
||||
return e.JSON(http.StatusForbidden, map[string]string{"err": "Forbidden"})
|
||||
}
|
||||
if err != nil {
|
||||
return e.JSON(http.StatusInternalServerError, map[string]string{"err": err.Error()})
|
||||
}
|
||||
|
||||
return e.JSON(http.StatusOK, map[string]string{"msg": "User created"})
|
||||
}
|
||||
|
||||
117
internal/users/users_test.go
Normal file
117
internal/users/users_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
//go:build testing
|
||||
|
||||
package users_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/henrygd/beszel/internal/migrations"
|
||||
beszelTests "github.com/henrygd/beszel/internal/tests"
|
||||
"github.com/henrygd/beszel/internal/users"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type blockedBody struct {
|
||||
io.Reader
|
||||
entered chan struct{}
|
||||
resume chan struct{}
|
||||
}
|
||||
|
||||
func (b *blockedBody) Read(p []byte) (int, error) {
|
||||
if b.entered != nil {
|
||||
close(b.entered)
|
||||
b.entered = nil
|
||||
<-b.resume
|
||||
}
|
||||
return b.Reader.Read(p)
|
||||
}
|
||||
|
||||
func TestCreateFirstUserAtomic(t *testing.T) {
|
||||
for _, scenario := range []string{"parked body", "concurrent requests", "rollback"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
h, err := beszelTests.NewTestHub(t.TempDir())
|
||||
require.NoError(t, err)
|
||||
defer h.Cleanup()
|
||||
h.StartHub()
|
||||
um := users.NewUserManager(h.App)
|
||||
invoke := func(body io.Reader) int {
|
||||
req := httptest.NewRequest("POST", "/api/beszel/create-user", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
if err := um.CreateFirstUser(&core.RequestEvent{App: h.App, Event: router.Event{Request: req, Response: res}}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
return res.Code
|
||||
}
|
||||
body := func(email string) io.Reader {
|
||||
return strings.NewReader(`{"email":"` + email + `","password":"password12345"}`)
|
||||
}
|
||||
await := func(results <-chan int) int {
|
||||
select {
|
||||
case status := <-results:
|
||||
return status
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("request did not finish")
|
||||
return 0
|
||||
}
|
||||
}
|
||||
switch scenario {
|
||||
case "parked body":
|
||||
entered, resume := make(chan struct{}), make(chan struct{})
|
||||
defer func() {
|
||||
select {
|
||||
case <-resume:
|
||||
default:
|
||||
close(resume)
|
||||
}
|
||||
}()
|
||||
result := make(chan int, 1)
|
||||
go func() { result <- invoke(&blockedBody{body("attacker@example.com"), entered, resume}) }()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("request did not reach body parsing")
|
||||
}
|
||||
require.Equal(t, 200, invoke(body("operator@example.com")))
|
||||
close(resume)
|
||||
require.Equal(t, 403, await(result))
|
||||
case "concurrent requests":
|
||||
start := make(chan struct{})
|
||||
results := make(chan int, 2)
|
||||
for _, email := range []string{"one@example.com", "two@example.com"} {
|
||||
go func() { <-start; results <- invoke(body(email)) }()
|
||||
}
|
||||
close(start)
|
||||
require.ElementsMatch(t, []int{200, 403}, []int{await(results), await(results)})
|
||||
case "rollback":
|
||||
hook := h.OnRecordCreate(core.CollectionNameSuperusers).BindFunc(func(e *core.RecordEvent) error {
|
||||
return errors.New("injected superuser creation failure")
|
||||
})
|
||||
require.Equal(t, 500, invoke(body("operator@example.com")))
|
||||
count, err := h.CountRecords("users")
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, count)
|
||||
admins, err := h.FindAllRecords(core.CollectionNameSuperusers)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, admins, 1)
|
||||
require.Equal(t, migrations.TempAdminEmail, admins[0].Email())
|
||||
h.OnRecordCreate(core.CollectionNameSuperusers).Unbind(hook)
|
||||
require.Equal(t, 200, invoke(body("operator@example.com")))
|
||||
}
|
||||
count, err := h.CountRecords("users")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, count)
|
||||
admins, err := h.FindAllRecords(core.CollectionNameSuperusers)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, admins, 1)
|
||||
require.NotEqual(t, migrations.TempAdminEmail, admins[0].Email())
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user