Преглед изворни кода

Restrict /system/auth/register to administrators

Once any user existed, HandleRegister only checked that the caller was
signed in and then created the account in the group named in the POST
body, so any ordinary user could create an administrator account (or
overwrite an existing account's password, since CreateUserAccount
writes over existing keys).

- With users present, only a caller in an admin group may register
  accounts, and the requested group must exist (exact match, as group
  membership lookups are case sensitive).
- First-run setup still works without login, but the first account must
  be in an existing admin group, matching what listgroup offers then.
- Existing usernames are refused instead of being overwritten.
- The checks come from a RegisterAuthorizer wired in by main (auth
  cannot import user/permission); registration fails closed if unset.
- user.html and newUser.html now show {"error": ...} replies instead of
  throwing on data.includes.

The public self-registration flow (/public/register/*) calls the auth
agent directly and is unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Toby Chui пре 3 недеља
родитељ
комит
052f24450d
5 измењених фајлова са 316 додато и 15 уклоњено
  1. 54 11
      src/mod/auth/auth.go
  2. 226 0
      src/mod/auth/register_test.go
  3. 16 0
      src/user.go
  4. 10 2
      src/web/SystemAO/users/newUser.html
  5. 10 2
      src/web/user.html

+ 54 - 11
src/mod/auth/auth.go

@@ -74,6 +74,18 @@ type AuthAgent struct {
 
 	//Logger
 	Logger *authlogger.Logger
+
+	//Account creation policy for /system/auth/register, wired in by main
+	RegisterAuthorizer *RegisterAuthorizer
+}
+
+// RegisterAuthorizer holds the permission checks HandleRegister needs. The auth
+// package cannot import the user or permission packages (both import auth), so
+// main fills these in once the user and permission handlers exist.
+type RegisterAuthorizer struct {
+	CallerIsAdmin func(w http.ResponseWriter, r *http.Request) bool //Signed-in caller belongs to an admin group
+	GroupExists   func(group string) bool                           //Permission group is defined
+	GroupIsAdmin  func(group string) bool                           //Permission group grants admin rights
 }
 
 type AuthEndpoints struct {
@@ -391,9 +403,9 @@ func (a *AuthAgent) CheckLogin(w http.ResponseWriter, r *http.Request) {
 }
 
 // Handle new user register. Require POST username, password, group.
+// With no users in the system this creates the first (admin) account without
+// login, otherwise only an administrator may create accounts.
 func (a *AuthAgent) HandleRegister(w http.ResponseWriter, r *http.Request) {
-	userCount := a.GetUserCounts()
-
 	//Get username from request
 	newusername, err := utils.PostPara(r, "username")
 	if err != nil {
@@ -415,15 +427,16 @@ func (a *AuthAgent) HandleRegister(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	//Check if the number of users in the system is == 0. If yes, there are no need to login before registering new user
-	if userCount > 0 {
-		//Require login to create new user
-		if a.CheckAuth(r) == false {
-			//System have more than one person and this user is not logged in
-			sendErrorResponse(w, "Login is needed to create new user")
-			return
-		}
+	err = a.checkRegisterPermission(w, r, group)
+	if err != nil {
+		sendErrorResponse(w, err.Error())
+		return
+	}
 
+	//Never overwrite an existing account (and its password) from here
+	if a.UserExists(newusername) {
+		sendErrorResponse(w, "Username already taken")
+		return
 	}
 
 	//Ok to proceed create this user
@@ -436,7 +449,37 @@ func (a *AuthAgent) HandleRegister(w http.ResponseWriter, r *http.Request) {
 	//Return to the client with OK
 	sendOK(w)
 	logger.PrintAndLog("Auth", "[System Auth] New user "+newusername+" added to system.", nil)
-	return
+}
+
+// checkRegisterPermission decides whether the request may create an account in
+// the given group. It fails closed when no RegisterAuthorizer is wired in.
+func (a *AuthAgent) checkRegisterPermission(w http.ResponseWriter, r *http.Request, group string) error {
+	authz := a.RegisterAuthorizer
+	if authz == nil || authz.CallerIsAdmin == nil || authz.GroupExists == nil || authz.GroupIsAdmin == nil {
+		return errors.New("Account registration is not available")
+	}
+
+	if a.GetUserCounts() == 0 {
+		//First run setup: no login needed, but the first account must be able to administrate the system
+		if !authz.GroupExists(group) || !authz.GroupIsAdmin(group) {
+			return errors.New("The first account must be created in an administrator group")
+		}
+		return nil
+	}
+
+	//Require login to create new user
+	if !a.CheckAuth(r) {
+		return errors.New("Login is needed to create new user")
+	}
+
+	if !authz.CallerIsAdmin(w, r) {
+		return errors.New("Permission denied")
+	}
+
+	if !authz.GroupExists(group) {
+		return errors.New("Permission group not exists")
+	}
+	return nil
 }
 
 // Check authentication from request header's session value

+ 226 - 0
src/mod/auth/register_test.go

@@ -0,0 +1,226 @@
+package auth
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"path/filepath"
+	"strings"
+	"sync"
+	"testing"
+
+	"github.com/gorilla/sessions"
+
+	db "imuslab.com/arozos/mod/database"
+)
+
+// newTestAuthAgent builds an AuthAgent on a temp database with a fake register
+// policy: "administrator" and "admins" are admin groups, "user" is not, and
+// callers listed in admins are administrators.
+func newTestAuthAgent(t *testing.T, admins map[string]bool) *AuthAgent {
+	t.Helper()
+	sysdb, err := db.NewDatabase(filepath.Join(t.TempDir(), "test.db"), false)
+	if err != nil {
+		t.Fatalf("NewDatabase returned error: %v", err)
+	}
+	t.Cleanup(sysdb.Close)
+	if err := sysdb.NewTable("auth"); err != nil {
+		t.Fatalf("NewTable returned error: %v", err)
+	}
+
+	a := &AuthAgent{
+		SessionName:  "ao_auth",
+		SessionStore: sessions.NewCookieStore([]byte("0123456789abcdef0123456789abcdef")),
+		Database:     sysdb,
+		mutex:        &sync.Mutex{},
+	}
+	groups := map[string]bool{"administrator": true, "admins": true, "user": false}
+	a.RegisterAuthorizer = &RegisterAuthorizer{
+		CallerIsAdmin: func(w http.ResponseWriter, r *http.Request) bool {
+			username, err := a.GetUserName(w, r)
+			return err == nil && admins[username]
+		},
+		GroupExists: func(group string) bool {
+			_, ok := groups[group]
+			return ok
+		},
+		GroupIsAdmin: func(group string) bool {
+			return groups[group]
+		},
+	}
+	return a
+}
+
+// sessionCookies returns the session cookies of a signed-in username.
+func sessionCookies(t *testing.T, a *AuthAgent, username string) []*http.Cookie {
+	t.Helper()
+	rec := httptest.NewRecorder()
+	a.LoginUserByRequest(rec, httptest.NewRequest(http.MethodPost, "/system/auth/login", nil), username, false)
+	cookies := rec.Result().Cookies()
+	if len(cookies) == 0 {
+		t.Fatal("LoginUserByRequest set no session cookie")
+	}
+	return cookies
+}
+
+// postRegister calls HandleRegister and returns the response body.
+func postRegister(a *AuthAgent, cookies []*http.Cookie, username, password, group string) string {
+	form := url.Values{"username": {username}, "password": {password}, "group": {group}}
+	req := httptest.NewRequest(http.MethodPost, "/system/auth/register", strings.NewReader(form.Encode()))
+	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	for _, c := range cookies {
+		req.AddCookie(c)
+	}
+	rec := httptest.NewRecorder()
+	a.HandleRegister(rec, req)
+	return rec.Body.String()
+}
+
+// TestHandleRegisterFirstRun covers creating the initial account with no users and no login.
+func TestHandleRegisterFirstRun(t *testing.T) {
+	tests := []struct {
+		name    string
+		group   string
+		wantOK  bool
+		wantErr string
+	}{
+		{"administrator group", "administrator", true, ""},
+		{"other admin group", "admins", true, ""},
+		{"non admin group", "user", false, "administrator group"},
+		{"unknown group", "nosuchgroup", false, "administrator group"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			a := newTestAuthAgent(t, nil)
+			body := postRegister(a, nil, "first", "secret", tc.group)
+			if tc.wantOK {
+				if body != "\"OK\"" {
+					t.Fatalf("body = %s, want \"OK\"", body)
+				}
+				if !a.UserExists("first") {
+					t.Error("first user was not created")
+				}
+				return
+			}
+			if !strings.Contains(body, tc.wantErr) {
+				t.Errorf("body = %s, want it to contain %q", body, tc.wantErr)
+			}
+			if a.GetUserCounts() != 0 {
+				t.Error("account was created despite the error")
+			}
+		})
+	}
+}
+
+// TestHandleRegisterExistingUsers covers who may create accounts once users exist.
+func TestHandleRegisterExistingUsers(t *testing.T) {
+	tests := []struct {
+		name     string
+		caller   string //empty for an anonymous request
+		username string
+		group    string
+		wantOK   bool
+		wantErr  string
+	}{
+		{"anonymous", "", "eve", "user", false, "Login is needed"},
+		{"non admin creates admin", "alice", "eve", "administrator", false, "Permission denied"},
+		{"non admin creates user", "alice", "eve", "user", false, "Permission denied"},
+		{"admin creates user", "admin", "bob", "user", true, ""},
+		{"admin creates admin", "admin", "bob", "administrator", true, ""},
+		{"admin with unknown group", "admin", "bob", "nosuchgroup", false, "group not exists"},
+		{"admin overwrites existing user", "admin", "alice", "user", false, "already taken"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			a := newTestAuthAgent(t, map[string]bool{"admin": true})
+			if err := a.CreateUserAccount("admin", "adminpass", []string{"administrator"}); err != nil {
+				t.Fatalf("CreateUserAccount returned error: %v", err)
+			}
+			if err := a.CreateUserAccount("alice", "alicepass", []string{"user"}); err != nil {
+				t.Fatalf("CreateUserAccount returned error: %v", err)
+			}
+
+			var cookies []*http.Cookie
+			if tc.caller != "" {
+				cookies = sessionCookies(t, a, tc.caller)
+			}
+			body := postRegister(a, cookies, tc.username, "newpass", tc.group)
+			if tc.wantOK {
+				if body != "\"OK\"" {
+					t.Fatalf("body = %s, want \"OK\"", body)
+				}
+				if !a.UserExists(tc.username) {
+					t.Errorf("user %s was not created", tc.username)
+				}
+				return
+			}
+			if !strings.Contains(body, tc.wantErr) {
+				t.Errorf("body = %s, want it to contain %q", body, tc.wantErr)
+			}
+			if a.GetUserCounts() != 2 {
+				t.Errorf("user count = %d, want 2", a.GetUserCounts())
+			}
+			passhash := ""
+			a.Database.Read("auth", "passhash/alice", &passhash)
+			if passhash != Hash("alicepass") {
+				t.Error("existing user's password was changed")
+			}
+		})
+	}
+}
+
+// TestHandleRegisterNoAuthorizer checks that registration fails closed when main did not wire a policy.
+func TestHandleRegisterNoAuthorizer(t *testing.T) {
+	tests := []struct {
+		name          string
+		existingUsers int
+	}{
+		{"first run", 0},
+		{"with users", 1},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			a := newTestAuthAgent(t, map[string]bool{"admin": true})
+			a.RegisterAuthorizer = nil
+			var cookies []*http.Cookie
+			if tc.existingUsers > 0 {
+				if err := a.CreateUserAccount("admin", "adminpass", []string{"administrator"}); err != nil {
+					t.Fatalf("CreateUserAccount returned error: %v", err)
+				}
+				cookies = sessionCookies(t, a, "admin")
+			}
+			body := postRegister(a, cookies, "bob", "newpass", "administrator")
+			if !strings.Contains(body, "not available") {
+				t.Errorf("body = %s, want registration to be unavailable", body)
+			}
+			if a.UserExists("bob") {
+				t.Error("account was created without a register policy")
+			}
+		})
+	}
+}
+
+// TestHandleRegisterMissingParams checks that each required POST field is enforced.
+func TestHandleRegisterMissingParams(t *testing.T) {
+	tests := []struct {
+		name                      string
+		username, password, group string
+		wantErr                   string
+	}{
+		{"no username", "", "pass", "administrator", "'username'"},
+		{"no password", "bob", "", "administrator", "'password'"},
+		{"no group", "bob", "pass", "", "'group'"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			a := newTestAuthAgent(t, nil)
+			body := postRegister(a, nil, tc.username, tc.password, tc.group)
+			if !strings.Contains(body, tc.wantErr) {
+				t.Errorf("body = %s, want it to contain %q", body, tc.wantErr)
+			}
+			if a.GetUserCounts() != 0 {
+				t.Error("account was created despite the missing parameter")
+			}
+		})
+	}
+}

+ 16 - 0
src/user.go

@@ -35,6 +35,22 @@ func UserSystemInit() {
 	}
 	userHandler = uh
 
+	//Account creation through /system/auth/register needs the user and permission handlers
+	authAgent.RegisterAuthorizer = &auth.RegisterAuthorizer{
+		CallerIsAdmin: func(w http.ResponseWriter, r *http.Request) bool {
+			userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
+			return err == nil && userinfo.IsAdmin()
+		},
+		GroupExists: func(group string) bool {
+			//Exact match, group membership lookups are case sensitive
+			return permissionHandler.GetPermissionGroupByName(group) != nil
+		},
+		GroupIsAdmin: func(group string) bool {
+			pg := permissionHandler.GetPermissionGroupByName(group)
+			return pg != nil && pg.IsAdmin
+		},
+	}
+
 	/*
 		router := prout.NewModuleRouter(prout.RouterOption{
 			ModuleName:  "System Settings",

+ 10 - 2
src/web/SystemAO/users/newUser.html

@@ -176,7 +176,8 @@
         $.post("../../system/auth/register", { username: username, password: password, group: usergroup })
             .done(function(data) {
                 $(btn).removeClass("loading");
-                if (!data.includes("Error")) {
+                var errMsg = nuRegisterErrorMessage(data);
+                if (errMsg === null) {
                     try {
                         if (!(!parent.isDesktopMode)) {
                             ao_module_parentCallback(true);
@@ -186,7 +187,7 @@
                     } catch(e) {}
                     window.location.href = "../../SystemAO/closeTabInsturction.html";
                 } else {
-                    $("#nu-err-msg").text(data);
+                    $("#nu-err-msg").text(errMsg);
                     $("#nu-error").slideDown('fast');
                 }
             })
@@ -197,6 +198,13 @@
             });
     }
 
+    // Register replies with "Error. ..." text or a {"error": "..."} object on failure
+    function nuRegisterErrorMessage(data) {
+        if (data && typeof data === "object" && data.error !== undefined) return String(data.error);
+        if (typeof data === "string" && data.includes("Error")) return data;
+        return null;
+    }
+
     function nuCancel() {
         try {
             if (!(!parent.isDesktopMode)) {

+ 10 - 2
src/web/user.html

@@ -369,7 +369,8 @@ function createUser() {
 
     $.post("system/auth/register", { username: username, password: password, group: usergroup })
         .done(function(data) {
-            if (!data.includes("Error")) {
+            var errMsg = registerErrorMessage(data);
+            if (errMsg === null) {
                 $.get("system/auth/checkLogin", function(loggedIn) {
                     if (loggedIn == true) {
                         try {
@@ -385,11 +386,18 @@ function createUser() {
                     }
                 });
             } else {
-                $("#uu-err").text(data).slideDown('fast');
+                $("#uu-err").text(errMsg).slideDown('fast');
             }
         });
 }
 
+/* Register replies with "Error. ..." text or a {"error": "..."} object on failure */
+function registerErrorMessage(data) {
+    if (data && typeof data === "object" && data.error !== undefined) return String(data.error);
+    if (typeof data === "string" && data.includes("Error")) return data;
+    return null;
+}
+
 function cancel() {
     try {
         if (!(!parent.isDesktopMode)) {