user

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 14 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 user manages Linux user accounts and groups through an injected exec.Runner.

Build a Manager for an explicit backend (shadow-utils is the only one today) and a Runner, then call its methods. The Manager owns OS mechanism and OS convention — the default-shell policy, the useradd -m/-M "home already exists" dance — while product policy (temporary-password records, SSH authorized_keys, hiding accounts) stays with the caller.

r, _ := exec.NewRunner(exec.Direct) // the agent runs as root; elsewhere: Sudo/Doas
um, _ := user.New(user.ShadowUtils, r)

// Create an interactive account with a home directory:
_ = um.Create(ctx, "deploy", user.CreateOptions{CreateHome: true})

// Set a generated password (carried as a redacted Secret):
pw, _ := user.GeneratePassword(16, user.ComplexityAlphanumeric)
_ = um.SetPassword(ctx, "deploy", pw)
_ = um.ExpirePassword(ctx, "deploy") // force change on first login

Every mutating method validates the account/group name (IsValidName), so a name can never become a useradd/usermod flag or inject an extra chpasswd record. Passwords are exec.Secret values that render as "[REDACTED]" and only the chpasswd sink reveals their bytes.

In tests, pass exectest.FakeRunner instead of a real Runner to assert the exact commands a Manager builds — no host, no sudo, no container.

Index

Constants

View Source
const (
	// MinPasswordLength is the minimum allowed generated-password length.
	MinPasswordLength = 8
	// MaxPasswordLength is the maximum allowed generated-password length.
	MaxPasswordLength = 128
)

Variables

View Source
var ErrUnknownBackend = fmt.Errorf("user: unknown backend")

ErrUnknownBackend is returned by New for the zero value or any Backend the SDK does not implement (fail-closed).

Functions

func DefaultShell

func DefaultShell(system bool) string

DefaultShell returns the SDK's default login shell: an interactive shell for normal accounts, nologin for system accounts. (Product concepts like "disabled" are the consumer's policy — pass Shell explicitly for those.)

func GeneratePassword

func GeneratePassword(length int, c Complexity) (exec.Secret, error)

GeneratePassword returns a cryptographically secure random password as a Secret. length must be in [MinPasswordLength, MaxPasswordLength]. crypto/rand gives a uniform distribution (no modulo bias).

func IsValidName

func IsValidName(name string) bool

IsValidName reports whether name is a valid, safe POSIX account name: starts with a lowercase letter, contains only [a-z0-9_-], max 32 chars. The leading- letter rule means a name can never become a useradd/usermod flag, and the charset rejects the newline/colon that would inject an extra chpasswd record.

func MembersMatch

func MembersMatch(a, b []string) bool

MembersMatch reports whether two member lists contain the same set of names, ignoring order and duplicates. A pure helper for group-membership reconciliation (compare desired vs. GroupMembers); the caller decides what to do about a mismatch.

Types

type Backend

type Backend int

Backend selects the user/group implementation. It is passed explicitly even though shadow-utils is the only value today; the zero value is invalid (New → ErrUnknownBackend) and a real second backend (adduser/homed/busybox) is appended when actually written.

const ShadowUtils Backend = iota + 1

ShadowUtils is the useradd/usermod/userdel/chpasswd/chage implementation.

type Complexity

type Complexity int

Complexity selects the character set GeneratePassword draws from.

const (
	// ComplexityAlphanumeric uses letters and digits only (the zero value).
	ComplexityAlphanumeric Complexity = iota
	// ComplexityComplex adds special characters.
	ComplexityComplex
)

type CreateOptions

type CreateOptions struct {
	UID          int      // 0 = auto-assign
	PrimaryGroup string   // group name or numeric GID; "" = useradd matching-group default
	Groups       []string // supplementary groups
	Shell        string   // "" = DefaultShell(System)
	HomeDir      string   // "" = /home/<name>
	Comment      string   // GECOS
	System       bool     // -r system account; also flips DefaultShell to nologin
	CreateHome   bool     // -m; Create handles the "home already exists" -M/chown dance
}

CreateOptions configures Create. The zero value creates a normal interactive account with a login shell and the backend's matching primary group, and NO home directory.

type DeleteOptions

type DeleteOptions struct {
	RemoveHome bool // userdel -r
}

DeleteOptions configures Delete.

type EnsureHomeOptions

type EnsureHomeOptions struct {
	// Group owns the home tree (recursively). "" resolves to the user's actual
	// primary group.
	Group string
	// Skel is the skeleton directory copied into a FRESHLY-created home. ""
	// uses /etc/skel. Ignored when the home already exists — existing content is
	// never clobbered.
	Skel string
	// Mode is the home directory's mode. Zero means 0700.
	Mode os.FileMode
}

EnsureHomeOptions configures EnsureHome.

type GroupCreateOptions

type GroupCreateOptions struct {
	GID    int  // 0 = auto-assign
	System bool // -r system group
}

GroupCreateOptions configures GroupCreate.

type Info

type Info struct {
	UID     int
	GID     int
	Comment string
	HomeDir string
	Shell   string
	Groups  []string // supplementary groups (excluding the primary)
	// GroupsKnown reports whether Groups is authoritative. If the `id -Gn`
	// supplementary-group lookup failed, Groups is left empty and GroupsKnown is
	// false — so a caller can tell "no supplementary groups" (empty, GroupsKnown=
	// true) apart from "could not determine" (empty, GroupsKnown=false) instead of
	// silently treating a failed lookup as "no groups".
	GroupsKnown bool
	Locked      bool
	// LockedKnown reports whether Locked is authoritative. The locked state lives
	// in the root-only shadow file; if reading it failed or escalation was not
	// authorized, Locked is left false and LockedKnown is false — so a caller can
	// tell "not locked" (Locked=false, LockedKnown=true) apart from "unknown"
	// (Locked=false, LockedKnown=false) and not treat unknown as unlocked.
	LockedKnown bool
}

Info holds the current state of a user account.

type Manager

type Manager interface {
	// Accounts
	Get(ctx context.Context, name string) (Info, error)
	Exists(ctx context.Context, name string) (bool, error)
	Create(ctx context.Context, name string, opts CreateOptions) error
	EnsureHome(ctx context.Context, name string, opts EnsureHomeOptions) error
	Modify(ctx context.Context, name string, opts ModifyOptions) error
	Delete(ctx context.Context, name string, opts DeleteOptions) error
	Lock(ctx context.Context, name string) error
	Unlock(ctx context.Context, name string) error
	SetPassword(ctx context.Context, name string, password exec.Secret) error
	ExpirePassword(ctx context.Context, name string) error
	PrimaryGroup(ctx context.Context, name string) (string, error)
	SupplementaryGroups(ctx context.Context, name string) ([]string, error)
	KillSessions(ctx context.Context, name string) error
	LastLogin(ctx context.Context, name string) (time.Time, error)
	SetHiddenOnLoginScreen(ctx context.Context, name string, hidden bool) error
	// Groups
	GroupExists(ctx context.Context, name string) (bool, error)
	GroupMembers(ctx context.Context, name string) ([]string, error)
	GroupCreate(ctx context.Context, name string, opts GroupCreateOptions) error
	GroupDelete(ctx context.Context, name string) error
	GroupEnsure(ctx context.Context, name string) error
	AddToGroup(ctx context.Context, name, group string) error
	RemoveFromGroup(ctx context.Context, name, group string) error
}

Manager is the user/group contract. Today shadow-utils is the only implementation; the interface leaves room for adduser/systemd-homed/busybox.

func New

func New(b Backend, runner exec.Runner, _ ...Option) (Manager, error)

New returns a Manager for the named backend, driven by runner. It is pure: it validates the backend is known and does not probe the host. The zero value and any unimplemented backend are rejected with ErrUnknownBackend.

type ModifyOptions

type ModifyOptions struct {
	Shell        string
	HomeDir      string
	Comment      string
	PrimaryGroup string
}

ModifyOptions configures Modify. An empty string leaves that attribute unchanged; if every field is empty Modify is a no-op (no usermod run).

type Option

type Option func(*shadowUtils)

Option is the functional-option type for backend-specific knobs. None are defined today; it reserves the constructor shape.

Jump to

Keyboard shortcuts

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