Add users: many at once from a CSV file

Onboarding a group meant registering people one by one. Add users can
now read a CSV (username, optional password, optional admin), generate
missing passwords, save them all owner-only beside it, and create the
accounts in one run through the playbook's matrix_user_creator, which
every homeserver and MAS supports and which leaves existing accounts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vvvomitandClaude Opus 5.5 committed 2026-10-29 05:16:13 +03:30
1 parent 6783a3b148
commit 5560782fe8
7 files changed
+232 -9

No files matched your search

+4 -1
View File
@@ -212,7 +212,10 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0).
ones your enabled services need listed apart from the rest. `m` on
Welcome opens it.
- **Manage an existing server:** update, run the self-check, restart, add
users (Synapse/Dendrite), open or close registration (Conduit,
users (Synapse/Dendrite), or many at once from a CSV file
(`username[,password][,admin]` a line; missing passwords are generated
and all are saved beside it as `…-passwords.csv`, owner-only), open or
close registration (Conduit,
Continuwuity, Tuwunel, and Synapse with MAS, where anyone with the
sign-up token can join without an email address), back up the Postgres database to this computer, and follow any
service's log live. Every action has a one-letter shortcut on Manage
+102
View File
@@ -0,0 +1,102 @@
package deploy
import (
"context"
"encoding/csv"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"interzone/internal/config"
)
var localpartOK = regexp.MustCompile(`^[a-z0-9._=/+-]+$`)
// ReadUsersCSV reads the accounts to make, one a line: a username, then
// optionally a password and "admin". A first line naming the columns is
// skipped. Empty passwords are generated.
func ReadUsersCSV(path string) ([]NewUser, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
r.FieldsPerRecord, r.TrimLeadingSpace, r.Comment = -1, true, '#'
rows, err := r.ReadAll()
if err != nil {
return nil, err
}
var out []NewUser
seen := map[string]bool{}
for i, row := range rows {
name := strings.ToLower(strings.TrimPrefix(strings.SplitN(strings.TrimSpace(row[0]), ":", 2)[0], "@"))
if i == 0 && (name == "username" || name == "user" || name == "name") {
continue
}
if name == "" {
continue
}
if !localpartOK.MatchString(name) {
return nil, fmt.Errorf("line %d: %q isn't a valid username (a–z, 0–9 and ._=-/+)", i+1, name)
}
if seen[name] {
return nil, fmt.Errorf("line %d: %s is listed twice", i+1, name)
}
seen[name] = true
u := NewUser{Name: name}
if len(row) > 1 {
u.Password = strings.TrimSpace(row[1])
}
if u.Password == "" {
u.Password = config.RandomPassword(16)
}
if len(row) > 2 {
v := strings.ToLower(strings.TrimSpace(row[2]))
u.Admin = v == "admin" || v == "yes" || v == "true" || v == "1"
}
out = append(out, u)
}
if len(out) == 0 {
return nil, fmt.Errorf("%s lists nobody", path)
}
return out, nil
}
// WritePasswords saves who gets which password beside the CSV, readable
// by its owner only, and returns where.
func WritePasswords(csvPath, domain string, users []NewUser) (string, error) {
out := strings.TrimSuffix(csvPath, filepath.Ext(csvPath)) + "-passwords.csv"
var b strings.Builder
w := csv.NewWriter(&b)
_ = w.Write([]string{"username", "user ID", "password", "admin"})
for _, u := range users {
_ = w.Write([]string{u.Name, "@" + u.Name + ":" + domain, u.Password, fmt.Sprint(u.Admin)})
}
w.Flush()
return out, os.WriteFile(out, []byte(b.String()), 0o600)
}
// bulkUsers makes Options.Users with the playbook's user creator, which
// every homeserver (and MAS) supports and which leaves existing accounts
// alone. The passwords go in a file, not on the command line.
func (r *Runner) bulkUsers(ctx context.Context) error {
var list []map[string]string
for _, u := range r.opts.Users {
kind := "user"
if u.Admin {
kind = "admin"
}
list = append(list, map[string]string{"username": u.Name, "initial_password": u.Password, "initial_type": kind})
}
vars, _ := json.Marshal(map[string]any{"matrix_user_creator_users_additional": list})
file := filepath.Join(r.cfg.PlaybookDir, "inventory", "interzone-users-vars.json")
if err := os.WriteFile(file, vars, 0o600); err != nil {
return err
}
defer os.Remove(file)
return r.playbookRun(ctx, StepBulkUsers, "--tags=ensure-matrix-users-created", "-e", "@"+file)
}
+39
View File
@@ -0,0 +1,39 @@
package deploy
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestReadUsersCSV(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "people.csv")
_ = os.WriteFile(path, []byte("username,password,admin\n@Alice:example.org, s3cret, admin\n# a comment\nbob\n\ncarol,,no\n"), 0o644)
users, err := ReadUsersCSV(path)
if err != nil || len(users) != 3 {
t.Fatal(users, err)
}
if u := users[0]; u.Name != "alice" || u.Password != "s3cret" || !u.Admin {
t.Errorf("%+v", u)
}
if u := users[2]; u.Name != "carol" || len(u.Password) != 16 || u.Admin {
t.Errorf("%+v", u)
}
out, err := WritePasswords(path, "example.org", users)
if err != nil || out != filepath.Join(dir, "people-passwords.csv") {
t.Fatal(out, err)
}
b, _ := os.ReadFile(out)
if st, _ := os.Stat(out); st.Mode().Perm() != 0o600 || !strings.Contains(string(b), "alice,@alice:example.org,s3cret,true") {
t.Errorf("%v %q", st.Mode(), b)
}
for _, bad := range []string{"al ice\n", "bob\nbob\n", "username\n"} {
_ = os.WriteFile(path, []byte(bad), 0o644)
if _, err := ReadUsersCSV(path); err == nil {
t.Errorf("took %q", bad)
}
}
}
+11 -4
View File
@@ -52,6 +52,7 @@ const (
StepAlerts
StepDryPlaybook
StepDryRun
StepBulkUsers
)
var stepNames = map[Step]string{
@@ -82,6 +83,7 @@ var stepNames = map[Step]string{
StepAlerts: "Set up alerts",
StepDryPlaybook: "Get the newest playbook, beside yours",
StepDryRun: "Run it without changing anything",
StepBulkUsers: "Create the users",
}
func (s Step) String() string { return stepNames[s] }
@@ -110,6 +112,7 @@ const (
ActionDisk // what takes the server's disk space
ActionAlerts // the server's own checks and alerts (Config.Alerts)
ActionDryRun // an update in check mode, in a copy of the playbook
ActionBulkUsers // create Options.Users
)
// Plan lists the steps an action runs, in order.
@@ -151,6 +154,8 @@ func Plan(a Action) []Step {
return []Step{StepAnsible, StepInventory, StepAlerts}
case ActionDryRun:
return []Step{StepAnsible, StepDryPlaybook, StepInventory, StepRoles, StepDryRun}
case ActionBulkUsers:
return []Step{StepAnsible, StepInventory, StepBulkUsers}
case ActionMigrate:
return []Step{StepAnsible, StepPlaybook, StepInventory, StepRoles, StepStopOld, StepCopyData, StepMirrors, StepInstall, StepSelfCheck}
}
@@ -196,10 +201,11 @@ type NewUser struct {
type Options struct {
Action Action
User NewUser // ActionRegister
Service string // ActionLogs: systemd unit, e.g. matrix-synapse
Output string // ActionBundle: archive path
Backup string // ActionRestore: local dump file
User NewUser // ActionRegister
Users []NewUser // ActionBulkUsers; Output is where their passwords were saved
Service string // ActionLogs: systemd unit, e.g. matrix-synapse
Output string // ActionBundle: archive path
Backup string // ActionRestore: local dump file
// ActionMigrate: the server to move to. The run works on a copy of the
// config; the caller switches its own Target when the Moved event comes.
NewTarget config.Target
@@ -332,6 +338,7 @@ func (r *Runner) run(ctx context.Context) error {
StepAlerts: r.alerts,
StepDryPlaybook: r.dryPlaybook,
StepDryRun: r.dryRun,
StepBulkUsers: r.bulkUsers,
}
plan := Plan(r.opts.Action)
r.emit(Event{Plan: plan})
+43
View File
@@ -0,0 +1,43 @@
package ui
import (
"os"
"path/filepath"
"strings"
"testing"
"interzone/internal/deploy"
)
// Add users › from a CSV: a bad file is shown on the form; a good one
// saves the passwords and starts the run.
func TestBulkUsersForm(t *testing.T) {
a := demoApp(t, 120, 36)
a.jump(a.index("Manage"))
s := a.cur().(*manageScreen)
s.choose("user")
s.userForm.get("how").choice = 1
if s.userForm.get("name").visible() || !s.userForm.get("csv").visible() {
t.Fatal("the CSV choice didn't swap the fields")
}
dir := t.TempDir()
path := filepath.Join(dir, "team.csv")
_ = os.WriteFile(path, []byte("al ice\n"), 0o644)
s.userForm.get("csv").input.SetValue(path)
if cmd := s.register(); cmd != nil || !strings.Contains(s.view(100, 30), "valid username") {
t.Fatalf("bad CSV: %q", s.userErr)
}
_ = os.WriteFile(path, []byte("alice\nbob,,admin\n"), 0o644)
cmd := s.register()
if cmd == nil {
t.Fatal(s.userErr)
}
m, ok := cmd().(runActionMsg)
if !ok || m.opts.Action != deploy.ActionBulkUsers || len(m.opts.Users) != 2 || !m.opts.Users[1].Admin ||
m.opts.Output != filepath.Join(dir, "team-passwords.csv") {
t.Fatalf("%+v", m)
}
if _, err := os.Stat(m.opts.Output); err != nil {
t.Error(err)
}
}
+6
View File
@@ -564,6 +564,7 @@ var actionTitles = map[deploy.Action][3]string{ // running, done, failed
deploy.ActionSelfCheck: {"Checking services…", "Self-check finished", "Self-check couldn't run"},
deploy.ActionRestart: {"Restarting services…", "Services restarted", "Restart failed"},
deploy.ActionRegister: {"Registering the user…", "User registered", "Couldn't register the user"},
deploy.ActionBulkUsers: {"Creating the users…", "Users created", "Couldn't create the users"},
deploy.ActionBackup: {"Backing up…", "Backup saved", "Backup failed"},
deploy.ActionLogs: {"Fetching logs…", "Logs", "Couldn't fetch logs"},
deploy.ActionImages: {"Checking container images…", "Image check finished", "Couldn't check the images"},
@@ -948,6 +949,11 @@ func (s *deployScreen) resultView(w int) string {
return panel(cMint,
sGood.Render("✓ Registered ")+sTitle.Render("@"+s.opts.User.Name+":"+c.Domain),
sMuted.Render("Password ")+sTitle.Render(s.opts.User.Password)+sMuted.Render(" (shown once; it isn't saved)"))
case deploy.ActionBulkUsers:
return panel(cMint,
sGood.Render(fmt.Sprintf("✓ %d users created on %s", len(s.opts.Users), c.Domain)),
sMuted.Render("Their passwords are in ")+sTitle.Render(s.opts.Output)+sMuted.Render("; hand them out, then delete it."),
sMuted.Render("Accounts that already existed kept their own passwords."))
case deploy.ActionBackup:
return panel(cMint,
sGood.Render("✓ Database dump saved to ")+sTitle.Render(res.File),
+27 -4
View File
@@ -86,6 +86,7 @@ type manageScreen struct {
mode manageMode
userForm *form
userErr string // what's wrong with the CSV file
loading bool
units []string
@@ -104,7 +105,7 @@ func (s *manageScreen) name() string { return "Manage" }
func (s *manageScreen) title() string {
switch s.mode {
case modeUser:
return "Add a user"
return "Add users"
case modeServices:
return "Which service's logs?"
case modeLogs:
@@ -374,11 +375,17 @@ func (s *manageScreen) choose(id string) tea.Cmd {
case "services", "disk", "vacuum", "pgupgrade", "compress", "tags", "uninstall":
return func() tea.Msg { return maintainMsg(id) }
case "user":
how := choiceField("how", "Add", []string{"one", "csv"}, []string{"One user", "Many, from a CSV file"}, "one", "")
u := textField("name", "Username", "", "alice", "Just the name, not @alice:"+s.cfg.Domain+".")
u.required = true
pw := secretField("pass", "Password", config.RandomPassword(16), "Generated for you. Press ctrl+r to see it; it's shown again when the user is created.")
pw.required = true
s.userForm = newForm(u, pw, toggleField("admin", "Make this user a server administrator", false, ""))
csvf := textField("csv", "CSV file", "", "~/people.csv",
"One user a line: username, then optionally a password and \"admin\". Missing passwords are generated, and all of them are saved beside it as …-passwords.csv. Existing accounts are left as they are.")
u.required, pw.required, csvf.required = true, true, true
s.userForm, s.userErr = newForm(how, u, pw, toggleField("admin", "Make this user a server administrator", false, ""), csvf), ""
one := func() bool { return s.userForm.value("how") == "one" }
many := func() bool { return !one() }
s.userForm.get("name").hidden, s.userForm.get("pass").hidden, s.userForm.get("admin").hidden = many, many, many
s.userForm.get("csv").hidden = one
s.mode = modeUser
return nil
case "logs":
@@ -405,6 +412,19 @@ func (s *manageScreen) choose(id string) tea.Cmd {
func (s *manageScreen) register() tea.Cmd {
f := s.userForm
if f.value("how") == "csv" {
path := config.ExpandHome(f.value("csv"))
users, err := deploy.ReadUsersCSV(path)
if err == nil {
path, err = deploy.WritePasswords(path, s.cfg.Domain, users)
}
if err != nil {
s.userErr = err.Error()
return nil
}
s.mode = modeList
return run(deploy.Options{Action: deploy.ActionBulkUsers, Users: users, Output: path})
}
name := strings.TrimPrefix(strings.SplitN(f.value("name"), ":", 2)[0], "@")
if name == "" || f.value("pass") == "" {
return nil
@@ -418,6 +438,9 @@ func (s *manageScreen) register() tea.Cmd {
func (s *manageScreen) view(w, h int) string {
switch s.mode {
case modeUser:
if s.userErr != "" {
return sBad.Render("✗ "+s.userErr) + "\n\n" + s.userForm.View(w, h-2)
}
return s.userForm.View(w, h)
case modeServices:
return s.servicesView(w, h)