Create the first superadmin from DOCWELL_ADMIN_EMAIL on start
When DOCWELL_ADMIN_EMAIL and DOCWELL_ADMIN_PASSWORD are set (and optionally DOCWELL_ADMIN_NAME), docwell-server creates that account as superadmin on start while the instance has no accounts. Once any account exists it changes nothing, so restarts never reset the password or a role changed in the admin panel. Without them, the first sign-up still wins. Pass the variables through every compose file, document them in the .env examples and the configuration, access and quick-start guides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b9be8be156
commit
3c7403ddf9
27 files changed
+239
-3
No files matched your search
@@ -86,6 +86,19 @@ func run(log *slog.Logger) error {
|
||||
OAuthRedirects: []string{cfg.WebURL + "/oauth/callback", "docwell://oauth/callback"},
|
||||
})
|
||||
settingsSvc.SetOAuthCallback(cfg.WebURL + "/oauth/callback")
|
||||
if cfg.AdminEmail != "" {
|
||||
adminCtx, cancelAdmin := context.WithTimeout(context.Background(), time.Minute)
|
||||
created, err := authSvc.EnsureSuperadmin(adminCtx, cfg.AdminEmail, cfg.AdminPassword, cfg.AdminName)
|
||||
cancelAdmin()
|
||||
switch {
|
||||
case err != nil:
|
||||
return fmt.Errorf("create superadmin from DOCWELL_ADMIN_EMAIL: %w", err)
|
||||
case created:
|
||||
log.Info("created superadmin from DOCWELL_ADMIN_EMAIL", "email", cfg.AdminEmail)
|
||||
default:
|
||||
log.Info("accounts already exist; DOCWELL_ADMIN_EMAIL left unused")
|
||||
}
|
||||
}
|
||||
auditLog := audit.New(db, log)
|
||||
defer auditLog.Close()
|
||||
hooks := webhooks.New(db, log, webhooks.Options{AllowLocal: cfg.WebhooksAllowLocal})
|
||||
|
||||
@@ -331,6 +331,43 @@ func (s *Service) Signup(ctx context.Context, in SignupInput) (Session, error) {
|
||||
return s.Login(ctx, in.Email, in.Password, "")
|
||||
}
|
||||
|
||||
// EnsureSuperadmin creates the instance's first account as superadmin when the
|
||||
// instance has no accounts yet (DOCWELL_ADMIN_EMAIL, DOCWELL_ADMIN_PASSWORD).
|
||||
// Once anyone exists it changes nothing, so restarts never reset a password
|
||||
// or a role changed in the admin panel. created reports whether it made one.
|
||||
func (s *Service) EnsureSuperadmin(ctx context.Context, email, password, name string) (created bool, err error) {
|
||||
email = strings.TrimSpace(email)
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
name = "Admin"
|
||||
}
|
||||
if len(password) < 8 {
|
||||
return false, &ValidationError{Fields: map[string]string{"password": "Password must be at least 8 characters."}}
|
||||
}
|
||||
existing, err := pocketbase.List[UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 1})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if existing.TotalItems > 0 {
|
||||
return false, nil
|
||||
}
|
||||
_, err = pocketbase.Create[UserRecord](ctx, s.pb, "users", map[string]any{
|
||||
"email": email,
|
||||
"password": password,
|
||||
"passwordConfirm": password,
|
||||
"name": name,
|
||||
"status": "active",
|
||||
"role": access.RoleSuperadmin,
|
||||
"emailVisibility": false,
|
||||
// The operator chose this address; there is no one to confirm it.
|
||||
"verified": true,
|
||||
})
|
||||
if err != nil {
|
||||
return false, mapError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Service) signupRules(ctx context.Context) (bool, []string, error) {
|
||||
if s.opts.Rules != nil {
|
||||
return s.opts.Rules(ctx)
|
||||
|
||||
@@ -171,6 +171,45 @@ func TestFirstSignupBecomesSuperadminThenSignupIsClosed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureSuperadminOnlyOnEmptyInstance(t *testing.T) {
|
||||
f, pb := newFakePB(t)
|
||||
s := NewService(pb, Options{SignupEnabled: false})
|
||||
|
||||
var verr *ValidationError
|
||||
if _, err := s.EnsureSuperadmin(ctx, "root@docwell.test", "short", ""); !errors.As(err, &verr) {
|
||||
t.Errorf("short password err = %v", err)
|
||||
}
|
||||
|
||||
created, err := s.EnsureSuperadmin(ctx, " root@docwell.test ", "password123", "")
|
||||
if err != nil || !created {
|
||||
t.Fatalf("first run = %v, %v", created, err)
|
||||
}
|
||||
if rec := f.users["root@docwell.test"]; rec["role"] != "superadmin" || rec["name"] != "Admin" {
|
||||
t.Errorf("created = %+v", rec)
|
||||
}
|
||||
sess, err := s.Login(ctx, "root@docwell.test", "password123", "")
|
||||
if err != nil || sess.User.Role != "superadmin" {
|
||||
t.Errorf("login = %+v, %v", sess.User, err)
|
||||
}
|
||||
|
||||
// A restart with another password changes nothing.
|
||||
created, err = s.EnsureSuperadmin(ctx, "root@docwell.test", "different123", "Root")
|
||||
if err != nil || created || f.passwords["root@docwell.test"] != "password123" {
|
||||
t.Errorf("second run = %v, %v, password %q", created, err, f.passwords["root@docwell.test"])
|
||||
}
|
||||
// Nor does a different address once someone exists.
|
||||
if created, err := s.EnsureSuperadmin(ctx, "other@docwell.test", "password123", ""); err != nil || created {
|
||||
t.Errorf("other address = %v, %v", created, err)
|
||||
}
|
||||
if _, ok := f.users["other@docwell.test"]; ok {
|
||||
t.Error("created a second superadmin")
|
||||
}
|
||||
// And the next signup is an ordinary one (closed here).
|
||||
if _, err := s.Signup(ctx, SignupInput{Email: "bob@docwell.test", Password: "password123", Name: "Bob"}); !errors.Is(err, ErrSignupDisabled) {
|
||||
t.Errorf("signup after bootstrap err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupDomainsAndValidation(t *testing.T) {
|
||||
_, pb := newFakePB(t)
|
||||
s := NewService(pb, Options{SignupEnabled: true, SignupDomains: []string{"docwell.test"}})
|
||||
|
||||
@@ -26,7 +26,13 @@ type Config struct {
|
||||
// SignupDomains limits signup to these email domains when not empty.
|
||||
SignupDomains []string
|
||||
|
||||
PocketBaseURL string
|
||||
// AdminEmail and AdminPassword create the first account as superadmin when
|
||||
// the instance has none (both set or neither). AdminName is its name.
|
||||
AdminEmail string
|
||||
AdminPassword string
|
||||
AdminName string
|
||||
|
||||
PocketBaseURL string
|
||||
PocketBaseEmail string
|
||||
PocketBasePassword string
|
||||
|
||||
@@ -95,6 +101,9 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
|
||||
PocketBasePassword: get("DOCWELL_PB_PASSWORD", ""),
|
||||
SignupEnabled: get("DOCWELL_SIGNUP_ENABLED", "true") == "true",
|
||||
SignupDomains: splitList(get("DOCWELL_SIGNUP_DOMAINS", "")),
|
||||
AdminEmail: strings.TrimSpace(get("DOCWELL_ADMIN_EMAIL", "")),
|
||||
AdminPassword: get("DOCWELL_ADMIN_PASSWORD", ""),
|
||||
AdminName: get("DOCWELL_ADMIN_NAME", ""),
|
||||
DataDir: get("DOCWELL_DATA_DIR", "./data"),
|
||||
ShutdownTimeout: 15 * time.Second,
|
||||
WebhooksAllowLocal: get("DOCWELL_WEBHOOKS_ALLOW_LOCAL", "false") == "true",
|
||||
@@ -154,6 +163,13 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
|
||||
cfg.MaxUploadMB = n
|
||||
}
|
||||
|
||||
if (cfg.AdminEmail == "") != (cfg.AdminPassword == "") {
|
||||
return Config{}, errors.New("set both DOCWELL_ADMIN_EMAIL and DOCWELL_ADMIN_PASSWORD, or neither")
|
||||
}
|
||||
if cfg.AdminPassword != "" && len(cfg.AdminPassword) < 8 {
|
||||
return Config{}, errors.New("DOCWELL_ADMIN_PASSWORD must be at least 8 characters")
|
||||
}
|
||||
|
||||
if cfg.PocketBaseEmail == "" || cfg.PocketBasePassword == "" {
|
||||
return Config{}, errors.New("DOCWELL_PB_EMAIL and DOCWELL_PB_PASSWORD are required")
|
||||
}
|
||||
|
||||
@@ -63,6 +63,31 @@ func TestOverridesAndTrimming(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAccount(t *testing.T) {
|
||||
base := func(extra map[string]string) map[string]string {
|
||||
env := map[string]string{"DOCWELL_PB_EMAIL": "a@b.c", "DOCWELL_PB_PASSWORD": "x"}
|
||||
for k, v := range extra {
|
||||
env[k] = v
|
||||
}
|
||||
return env
|
||||
}
|
||||
cfg, err := fromLookup(lookup(base(map[string]string{
|
||||
"DOCWELL_ADMIN_EMAIL": " root@docwell.test ", "DOCWELL_ADMIN_PASSWORD": "password123", "DOCWELL_ADMIN_NAME": "Root",
|
||||
})))
|
||||
if err != nil || cfg.AdminEmail != "root@docwell.test" || cfg.AdminPassword != "password123" || cfg.AdminName != "Root" {
|
||||
t.Errorf("admin = %+v, %v", cfg, err)
|
||||
}
|
||||
for name, extra := range map[string]map[string]string{
|
||||
"email only": {"DOCWELL_ADMIN_EMAIL": "root@docwell.test"},
|
||||
"password only": {"DOCWELL_ADMIN_PASSWORD": "password123"},
|
||||
"short password": {"DOCWELL_ADMIN_EMAIL": "root@docwell.test", "DOCWELL_ADMIN_PASSWORD": "short"},
|
||||
} {
|
||||
if _, err := fromLookup(lookup(base(extra))); err == nil {
|
||||
t.Errorf("%s: expected an error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingCredentials(t *testing.T) {
|
||||
if _, err := fromLookup(lookup(nil)); err == nil {
|
||||
t.Fatal("expected error without PocketBase credentials")
|
||||
|
||||
Reference in new issue
Block a user