accounts

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package accounts is etherpad-go's account management: accounts (people, service accounts and the anonymous visitor), roles built from scopes, role assignments limited to pad patterns, and the rules that keep an instance from locking itself out or opening up by mistake.

Code checks scopes, never role names: "may this account do X on this pad?" is Grants.Has(X, padId).

Index

Constants

View Source
const (
	RoleViewer    = "viewer"
	RoleEditor    = "editor"
	RoleModerator = "moderator"
	RoleAIUser    = "ai-user"
	RoleAdmin     = "admin"

	// AnonymousID is the account of visitors who are not logged in; every
	// account gets its roles too.
	AnonymousID = "anonymous"
	// AuthenticatedID is the account of everyone logged in, also people a
	// plugin authenticated who have no account of their own.
	AuthenticatedID = "authenticated"
)

The ids of the built-in roles and of the anonymous account.

View Source
const (
	KindHuman   = "human"
	KindService = "service"
	// KindBuiltin marks the anonymous and authenticated accounts.
	KindBuiltin = "builtin"
)

Account kinds.

View Source
const (
	LevelNone     = ""
	LevelReadOnly = "readOnly"
	LevelModify   = "modify"
	LevelCreate   = "create"
)

The levels of pad access of etherpad-lite's authorization.

View Source
const (
	ScopePadRead       = "pad:read"
	ScopePadWrite      = "pad:write"
	ScopePadCreate     = "pad:create"
	ScopePadDelete     = "pad:delete"
	ScopePadSettings   = "pad:settings"
	ScopeChatWrite     = "chat:write"
	ScopeChatModerate  = "chat:moderate"
	ScopeAIUse         = "ai:use"
	ScopeAIUnlimited   = "ai:unlimited"
	ScopeTokensOwn     = "tokens:own"
	ScopeAdminUsers    = "admin:users"
	ScopeAdminRoles    = "admin:roles"
	ScopeAdminAPIKeys  = "admin:apikeys"
	ScopeAdminSettings = "admin:settings"
	ScopeAdminPlugins  = "admin:plugins"
	ScopeAdminPads     = "admin:pads"
)

The scopes of etherpad-go. Plugins add their own with RegisterScope.

View Source
const AllScopes = "*"

AllScopes in a token's scope list means every scope, also those registered later.

View Source
const CacheTTL = 30 * time.Second

CacheTTL is how long role definitions and resolved grants are cached. A change on another instance of a cluster is seen after at most this long.

View Source
const MaxPatternLength = 255

MaxPatternLength is the longest pad pattern.

View Source
const MaxProfileLength = 200

MaxProfileLength caps the display name and e-mail.

View Source
const MaxUsernameLength = 64

MaxUsernameLength is the longest username.

View Source
const MinPasswordLength = 8

MinPasswordLength is the shortest password accepted for a new password.

Variables

View Source
var (
	ErrInvalidCredentials = errors.New("invalid username or password")
	ErrLocked             = errors.New("too many failed logins, try again later")
	ErrForbidden          = errors.New("not allowed")
	ErrLastAdmin          = errors.New("the last active admin cannot lose admin rights")
	ErrAdminRoleFixed     = errors.New("the admin role cannot be changed or deleted")
	ErrBuiltinRole        = errors.New("built-in roles cannot be deleted")
	ErrAnonymousScope     = errors.New("visitors cannot get admin scopes, tokens:own or ai:unlimited, logged-in people as a whole no admin scopes")
	ErrRoleCycle          = errors.New("a role cannot include itself")
	ErrEscalation         = errors.New("cannot grant scopes you do not have yourself")
	ErrInvalidUsername    = errors.New("invalid username")
	ErrInvalidRole        = errors.New("invalid role")
	ErrNoPassword         = errors.New("service and anonymous accounts have no password")
	ErrAnonymousAccount   = errors.New("the anonymous account cannot be changed this way")
	ErrInvalidProfile     = errors.New("invalid display name or e-mail")
	ErrNotBuiltin         = errors.New("only built-in roles can be reset")
)
View Source
var CLI = Actor{ID: "cli", Grants: Grants{/* contains filtered or unexported fields */}, /* contains filtered or unexported fields */}

CLI acts for the command line (etherpad-go admin): it may do everything; the audit log names it.

View Source
var ErrAuditFailed = errors.New("the change was saved, but the audit log could not be written")

ErrAuditFailed is returned when a change was saved but its audit entry could not be written.

View Source
var ErrBusy = errors.New("the accounts are being changed elsewhere, try again")

ErrBusy is returned when another instance holds the write lock too long.

View Source
var ErrInvalidPattern = errors.New("invalid pad pattern")

ErrInvalidPattern is returned for a pad pattern that cannot be used.

View Source
var ErrPasswordTooShort = errors.New("the password is too short")

ErrPasswordTooShort is returned for a new password under MinPasswordLength characters.

View Source
var System = Actor{ID: "system", Grants: Grants{/* contains filtered or unexported fields */}, /* contains filtered or unexported fields */}

System acts for the server: it may do everything.

Functions

func BuiltinRoles

func BuiltinRoles() []db.Role

BuiltinRoles are the roles every instance starts with. Admins change them (except admin) and add their own.

func CheckPassword

func CheckPassword(hash, password string) bool

CheckPassword reports whether password matches the PHC string hash.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns the PHC string of password.

func IsAdminScope

func IsAdminScope(name string) bool

IsAdminScope reports whether name is one of the admin:* scopes.

func KnownScope

func KnownScope(name string) bool

KnownScope reports whether name is a registered scope.

func MatchPattern

func MatchPattern(p, padId string) bool

MatchPattern reports whether pad pattern p matches padId.

func RandomPassword

func RandomPassword() string

RandomPassword returns a password for a one-time login.

func RegisterScope

func RegisterScope(s Scope)

RegisterScope adds a scope, e.g. one of a plugin. Registering a known name again replaces its description.

func ValidatePattern

func ValidatePattern(p string) error

ValidatePattern checks a pad pattern.

Types

type Actor

type Actor struct {
	ID     string
	Grants Grants
	// contains filtered or unexported fields
}

Actor is who makes a change: an account id and its grants. System is the server itself (seeding, migration).

func (Actor) IsServer

func (a Actor) IsServer() bool

IsServer reports whether the actor is the server itself (System or the CLI), not an account.

type Grants

type Grants struct {

	// Limits are the most generous value of each limit over the roles.
	Limits map[string]int64
	// contains filtered or unexported fields
}

Grants are the resolved rights of an account: scopes per pad pattern. The zero value grants nothing.

func (Grants) Empty

func (g Grants) Empty() bool

Empty reports whether the grants allow nothing at all.

func (Grants) GlobalScopes

func (g Grants) GlobalScopes() []string

GlobalScopes returns the scopes granted for all pads, by name.

func (Grants) Has

func (g Grants) Has(scope, padId string) bool

Has reports whether the grants allow scope on padId. Scopes that are not pad scoped only count from assignments for all pads.

func (Grants) HasAnywhere

func (g Grants) HasAnywhere(scope string) bool

HasAnywhere reports whether the grants allow scope on at least some pads.

func (Grants) HasGlobal

func (g Grants) HasGlobal(scope string) bool

HasGlobal reports whether the grants allow scope on every pad (or, for scopes that are not pad scoped, at all).

func (Grants) IsAdmin

func (g Grants) IsAdmin() bool

IsAdmin reports whether the grants include the admin role's rights: the admin UI needs admin:settings.

func (Grants) Level

func (g Grants) Level(padId string) string

Level is the etherpad-lite authorization level the grants give on padId: create needs pad:create and pad:write, modify pad:write, readOnly pad:read.

func (Grants) MayGive

func (g Grants) MayGive(scope, pattern string) bool

MayGive reports whether grants may pass scope on for pads matching pattern ("" or "*": all pads): nobody gives what they do not have. "*" (all scopes) needs every right.

func (Grants) MayGiveLimits

func (g Grants) MayGiveLimits(limits map[string]int64) bool

MayGiveLimits reports whether grants may give these limits: none above their own, unless they have every right.

func (Grants) Restrict

func (g Grants) Restrict(scopes []string, pattern string, limits map[string]int64) Grants

Restrict cuts the grants down to scopes, a pad pattern ("" or "*": all pads) and limits: what a token of the account may do. A token never gets more than its account: every check needs both. A limit is the smaller of the account's and the token's; scopes that are not pad scoped need a token for all pads, as they need an assignment for all pads.

func (Grants) Summary

func (g Grants) Summary() []PatternScopes

Summary lists the scopes per pattern, for showing what an account may do.

func (Grants) Union

func (g Grants) Union(o Grants) Grants

Union returns the grants of g and o together.

type LegacyUser

type LegacyUser struct {
	Password  string
	IsAdmin   bool
	ReadOnly  bool
	CanCreate *bool
}

LegacyUser is an entry of settings.users, taken over once.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager reads and changes accounts, roles and assignments and enforces the rules on them.

func For

func For(store db.AccountMethods) *Manager

For returns the manager of store: one per store and process, so every part of the server sees the same cache.

func NewManager

func NewManager(store db.AccountMethods) *Manager

NewManager returns a Manager on store.

func (*Manager) Account

func (m *Manager) Account(id string) (*db.Account, error)

Account returns the account, or nil.

func (*Manager) AccountByUsername

func (m *Manager) AccountByUsername(username string) (*db.Account, error)

AccountByUsername returns the account, or nil.

func (*Manager) Accounts

func (m *Manager) Accounts() ([]db.Account, error)

Accounts returns all accounts, oldest first.

func (*Manager) AdminIDs

func (m *Manager) AdminIDs() (map[string]bool, error)

AdminIDs returns the accounts that hold the admin role for all pads, as IsAdmin decides it, loading the state once.

func (*Manager) AnonymousGrants

func (m *Manager) AnonymousGrants() (Grants, error)

AnonymousGrants returns what visitors who are not logged in may do.

func (*Manager) ApplyTemplate

func (m *Manager) ApplyTemplate(actor Actor, t Template) error

ApplyTemplate replaces the roles of the anonymous and authenticated accounts with those of a template: open lets visitors edit, read lets them read, closed lets only logged-in people in (and lets them edit).

func (*Manager) Assign

func (m *Manager) Assign(actor Actor, accountID, roleID, padPattern string) error

Assign gives an account a role for the pads matching padPattern ("" or "*": all pads).

func (*Manager) Assignments

func (m *Manager) Assignments() ([]db.RoleAssignment, error)

Assignments returns all role assignments.

func (*Manager) Audit

func (m *Manager) Audit(limit int) ([]db.AuditEntry, error)

Audit returns the newest audit entries first.

func (*Manager) Authenticate

func (m *Manager) Authenticate(username, password string) (*db.Account, error)

Authenticate checks a username and password. Disabled accounts, service accounts and the built-in accounts cannot log in. After repeated failures the username is locked for a while (ErrLocked); attempts running at the same time count against the limit before they are checked.

func (*Manager) AuthenticatedGrants

func (m *Manager) AuthenticatedGrants() (Grants, error)

AuthenticatedGrants returns what a logged-in person without an account of its own (authenticated by a plugin) may do.

func (*Manager) AuthorOf

func (m *Manager) AuthorOf(accountID string, create func(name string) (string, error)) (string, error)

AuthorOf returns the pad author of a person, creating and linking one on first use with create (which gets the display name). The link is made under the write lock, so two instances do not give one account two authors.

func (*Manager) Changed

func (m *Manager) Changed()

Changed tells this and the other instances that something the rights depend on changed outside the manager (e.g. a token was revoked).

func (*Manager) CreateAccount

func (m *Manager) CreateAccount(actor Actor, n NewAccount) (*db.Account, error)

CreateAccount creates a person's or a service account.

func (*Manager) CurrentActor

func (m *Manager) CurrentActor(accountID string) (Actor, error)

CurrentActor returns the actor of an account with its rights as they are now; ErrForbidden for an unknown, disabled or built-in account.

func (*Manager) DeleteAccount

func (m *Manager) DeleteAccount(actor Actor, accountID string) error

DeleteAccount removes an account and its assignments.

func (*Manager) DeleteRole

func (m *Manager) DeleteRole(actor Actor, id string) error

DeleteRole removes a role that is not built in.

func (*Manager) Ensure

func (m *Manager) Ensure(cfg *settings.Settings, logger *zap.SugaredLogger) error

Ensure runs EnsureDefaults once per manager with the settings of the first caller; later calls only wait for it. The server calls it at startup; code paths that can run first (tests, tools) call it too.

func (*Manager) EnsureDefaults

func (m *Manager) EnsureDefaults(cfg SeedConfig, logger *zap.SugaredLogger) error

EnsureDefaults prepares the account management of an instance; it is safe to run on every start and from several instances at once:

  • the built-in roles that are missing are created;
  • the anonymous and authenticated accounts are created, and on creation get the roles of the template;
  • settings.users is taken over exactly once (the first start records that it did, even without users); an interrupted take-over is completed on the next start;
  • without an admin who can log in, the bootstrap admin is created.

func (*Manager) Generation

func (m *Manager) Generation() uint64

Generation counts the times the caches were forgotten (every change, and every notice of another instance): what is cached with an older one is stale.

func (*Manager) GrantsFor

func (m *Manager) GrantsFor(accountID string) (Grants, error)

GrantsFor returns what the account may do: its own assignments, those of the authenticated account for people (not for service accounts, which never log in) and those of the anonymous account (nobody has less than a visitor).

func (*Manager) GrantsFromRefs

func (m *Manager) GrantsFromRefs(refs []RoleRef) (Grants, error)

GrantsFromRefs resolves the assignments a verified token of a person carries, with those of the authenticated and anonymous accounts added.

func (*Manager) Holder

func (m *Manager) Holder(accountID string) (*db.Account, error)

Holder returns the account a token may act for: a person or a service account, existing and not disabled; else nil. Cached like Person.

func (*Manager) HolderAuthorOf

func (m *Manager) HolderAuthorOf(accountID string, create func(name string) (string, error)) (string, error)

HolderAuthorOf is AuthorOf for the holder of a token: a person or a service account. A service account writes under its own name, so text it adds stays apart from any person's.

func (*Manager) Invalidate

func (m *Manager) Invalidate()

Invalidate forgets the cached roles and grants, e.g. after another instance changed them.

func (*Manager) IsAdmin

func (m *Manager) IsAdmin(accountID string) (bool, error)

IsAdmin reports whether the account holds the admin role for all pads.

func (*Manager) Locked

func (m *Manager) Locked(fn func() error) error

Locked runs fn under the write lock of the accounts: the process's and, where the store has one, the database's, so the changes of all instances of a cluster happen one after the other. fn must not change accounts or roles through the manager (that takes the lock again).

func (*Manager) MayManage

func (m *Manager) MayManage(actor Actor, accountID string) (bool, error)

MayManage reports whether actor may act on the account: itself, or an account whose rights the actor all has (no take-over of more rights).

func (*Manager) OnChange

func (m *Manager) OnChange(fn func())

OnChange sets what runs after every change, e.g. telling the other instances of a cluster to forget their caches (Invalidate).

func (*Manager) PasswordMatches

func (m *Manager) PasswordMatches(a *db.Account, password string) bool

PasswordMatches reports whether password is the account's current one, without counting as a login attempt.

func (*Manager) Person

func (m *Manager) Person(accountID string) (*db.Account, error)

Person returns the account of a logged-in person if it may still be logged in: it exists, is a human and is not disabled; else nil. It is cached like the grants (CacheTTL, forgotten on every change and on the other instances' notices), so a session costs no database read per request.

func (*Manager) Record

func (m *Manager) Record(actor Actor, action, target string, details any) error

Record writes an audit entry for a change made outside the manager.

func (*Manager) Refs

func (m *Manager) Refs(accountID string) ([]RoleRef, error)

Refs returns the assignments of an account as role references.

func (*Manager) ResetPassword

func (m *Manager) ResetPassword(actor Actor, accountID string) (string, error)

ResetPassword gives a person a new one-time password that must be changed at the next login, enables the account and lifts a login lock of this process. It returns the password.

func (*Manager) ResetRole

func (m *Manager) ResetRole(actor Actor, id string) (*db.Role, error)

ResetRole sets a built-in role back to how it was shipped.

func (*Manager) Roles

func (m *Manager) Roles() (map[string]db.Role, error)

Roles returns the role definitions by id.

func (*Manager) SaveRole

func (m *Manager) SaveRole(actor Actor, r db.Role) (*db.Role, error)

SaveRole creates the role (no ID yet, or an unknown one) or changes it.

func (*Manager) SetDisabled

func (m *Manager) SetDisabled(actor Actor, accountID string, disabled bool) error

SetDisabled disables or enables an account.

func (*Manager) SetPassword

func (m *Manager) SetPassword(actor Actor, accountID, password string, mustChange bool) error

SetPassword sets a person's password; actor is the person or someone with all its rights and admin:users.

func (*Manager) Unassign

func (m *Manager) Unassign(actor Actor, accountID, roleID, padPattern string) error

Unassign takes a role assignment away.

func (*Manager) UpdateProfile

func (m *Manager) UpdateProfile(actor Actor, accountID string, p Profile) (*db.Account, error)

UpdateProfile changes an account's username, display name or e-mail. The account's person may change the display name and e-mail; a username and the profile of others need admin:users and all the account's rights.

type NewAccount

type NewAccount struct {
	Username    string
	DisplayName string
	Email       string
	Kind        string
	// Password, only for people; "" leaves the account without one.
	Password string
	// PasswordHash takes over an existing hash instead of Password.
	PasswordHash       string
	MustChangePassword bool
}

NewAccount describes an account to create.

type PatternScopes

type PatternScopes struct {
	Pattern string   `json:"pattern"`
	Scopes  []string `json:"scopes"`
}

PatternScopes is the scope list of one pad pattern ("" = all pads).

type Profile

type Profile struct {
	Username    *string
	DisplayName *string
	Email       *string
}

Profile is what UpdateProfile changes; nil fields stay as they are.

type RoleRef

type RoleRef struct {
	Role string `json:"role"`
	Pads string `json:"pads,omitempty"`
}

RoleRef is an assignment as a token carries it: a role id and the pad pattern ("" = all pads).

type Scope

type Scope struct {
	Name        string
	Description string
	// PadScoped scopes can be limited to a pad pattern; the others only
	// count from assignments for all pads.
	PadScoped bool
}

Scope describes one right.

func LookupScope

func LookupScope(name string) (Scope, bool)

LookupScope returns the scope with this name.

func Scopes

func Scopes() []Scope

Scopes returns all known scopes, by name.

type SeedConfig

type SeedConfig struct {
	// Template applies when the anonymous account is created, i.e. on
	// the first start with account management.
	Template Template
	// LegacyUsers are taken over when there are no accounts of people
	// yet.
	LegacyUsers map[string]LegacyUser
	// BootstrapUser and BootstrapPassword create the first admin when no
	// active admin exists.
	BootstrapUser     string
	BootstrapPassword string
}

SeedConfig is what EnsureDefaults sets up an instance from.

func SeedConfigOf

func SeedConfigOf(cfg *settings.Settings) SeedConfig

SeedConfigOf builds the seed configuration of an instance from its settings: the template from requireAuthentication, settings.users, and the bootstrap admin.

type Template

type Template string

Template is what visitors who are not logged in may do on a new instance.

const (
	// TemplateOpen lets visitors read, write and create pads.
	TemplateOpen Template = "open"
	// TemplateRead lets visitors read pads only.
	TemplateRead Template = "read"
	// TemplateClosed lets visitors do nothing: everyone logs in.
	TemplateClosed Template = "closed"
)

func TemplateOf

func TemplateOf(requireAuthentication bool) Template

TemplateOf returns the template that keeps etherpad-lite's behaviour of requireAuthentication.

Directories

Path Synopsis
Package admincli is "etherpad-go admin": creating admins, resetting passwords and listing accounts from the command line, on the database of the settings.
Package admincli is "etherpad-go admin": creating admins, resetting passwords and listing accounts from the command line, on the database of the settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL