feat: Authentik OIDC SSO, allow/deny RBAC, admin console & Gitea CI
All checks were successful
build-and-push / build (push) Successful in 15m15s

Authentication & RBAC
- Add confidential OIDC client (Authentik) with /auth/oidc/login +
  /auth/oidc/callback: discovery, code exchange, id_token verify (go-oidc),
  groups claim → role (Archivum-admin → admin, else user). Sessions carry groups.
- Rework ACL into an allow/deny model (new `effect` column + migration).
  db.EffectiveAccess resolves user + all groups over the path and its ancestors:
  default deny, explicit deny always beats allow.
- Enforce ACL for ALL non-admin users (not just guest) across list/read/save/
  delete/move/create/history/diff/images/upload. Admins bypass.
- Seed built-in Archivum-admin / Archivum-reader groups; login allow-list on
  users & groups; public (guest) user access is ACL-configurable.

Admin API & UI
- New GraphQL ops: oidcConfig/updateOidcConfig, group CRUD, membership,
  setUserRole/setUserLogin/setGroupLogin, userGroups, loginOptions.
- Rebuilt AdminView: SSO config, user/group management + membership, login
  toggles, and an allow/deny access-control matrix per path.
- LoginView: "Sign in with Authentik" + public-user option; OIDC callback route.

Rendering/editor
- Fix bug where inline marks (bold/italic/code/strike/link) were dropped on
  TipTap→AsciiDoc save. Add RENDERING_IMPROVEMENTS.md with proposals.

CI / build
- .gitea/workflows/build.yaml: build on the Pi5 runner, push
  localhost:5000/archivum:{latest,<sha>}. Add .dockerignore; bump Go image to 1.25.
- Docs: ARCHITECTURE.md, README.md, docs/AUTHENTIK_SETUP.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-05 21:58:50 +02:00
parent d808b0289f
commit cd588197b9
22 changed files with 2458 additions and 735 deletions

View File

@@ -1,10 +1,12 @@
module github.com/brasse-b/archivum
go 1.22
go 1.25.0
require (
github.com/coreos/go-oidc/v3 v3.19.0
github.com/go-ldap/ldap/v3 v3.4.8
golang.org/x/crypto v0.21.0
golang.org/x/oauth2 v0.36.0
modernc.org/sqlite v1.30.0
)
@@ -12,6 +14,7 @@ require (
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect

View File

@@ -2,6 +2,8 @@ github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I=
github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -9,6 +11,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
@@ -71,6 +75,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=

View File

@@ -19,6 +19,7 @@ type Session struct {
Username string
Token string
Role string
Groups []string // group names (from OIDC claim or local membership)
ExpiresAt time.Time
}
@@ -59,9 +60,10 @@ func CheckPassword(hashedPassword, password string) error {
// Returns the session token, the user's role, and any error.
// password is a SHA-256 hash (for local accounts); ldapPassword is plaintext (for LDAP bind).
func (m *Manager) Login(database *db.DB, username, password, ldapPassword string) (token, role string, err error) {
// Guest login — no password required.
// Guest / public login — no password required.
if username == "guest" {
tok, err := m.createSession("guest", "guest")
groups, _ := database.GetUserGroupNames("guest")
tok, err := m.createSession("guest", "guest", groups)
return tok, "guest", err
}
@@ -74,7 +76,8 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
if bcrypt.CompareHashAndPassword([]byte(user.PassHash), []byte(password)) != nil {
return "", "", errors.New("invalid credentials")
}
tok, err := m.createSession(username, user.Role)
groups, _ := database.GetUserGroupNames(username)
tok, err := m.createSession(username, user.Role, groups)
return tok, user.Role, err
}
// No local password — must be an LDAP-only account.
@@ -92,7 +95,8 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
if err := ldapUserBind(cfg, username, ldapPwd); err != nil {
return "", "", errors.New("invalid credentials")
}
tok, err := m.createSession(username, user.Role)
groups, _ := database.GetUserGroupNames(username)
tok, err := m.createSession(username, user.Role, groups)
return tok, user.Role, err
}
// In DB but no password and not LDAP — refuse.
@@ -116,10 +120,60 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
return "", "", err
}
tok, err := m.createSession(username, "user")
tok, err := m.createSession(username, "user", nil)
return tok, "user", err
}
// LoginOIDC establishes a session from a verified OIDC identity. It maps the
// group claim to a role (admin group → admin, otherwise user), mirrors the
// user and groups into the local DB (for the admin UI and ACL targeting), and
// enforces the login allow-list. Returns an error if the account is not
// permitted to sign in.
func (m *Manager) LoginOIDC(database *db.DB, u *OIDCUser) (token, role string, err error) {
m.mu.RLock()
cfg := m.cfg
m.mu.RUnlock()
adminGroup, readerGroup := "Archivum-admin", "Archivum-reader"
if cfg != nil {
oc := cfg.OIDC
oc.Normalize()
adminGroup, readerGroup = oc.AdminGroup, oc.ReaderGroup
}
_ = readerGroup // reader currently maps to the ACL-gated "user" role
// Mirror the token's groups locally so ACLs can target them and the admin
// UI can list them.
for _, g := range u.Groups {
_ = database.CreateOrUpdateGroup(g, true)
}
allowed := database.LoginAllowed(u.Username, u.Groups)
role = "user"
for _, g := range u.Groups {
if g == adminGroup {
role = "admin"
break
}
}
// Provision / refresh the user record and its group mirror. allow_login is
// seeded from the gate result on first insert and preserved afterwards.
_ = database.CreateOrUpdateExternalUser(u.Username, role, allowed)
if role == "admin" {
_ = database.SetUserRole(u.Username, "admin")
}
_ = database.SyncUserGroups(u.Username, u.Groups)
if !allowed {
return "", "", errors.New("this account is not permitted to sign in to Archivum")
}
tok, err := m.createSession(u.Username, role, u.Groups)
return tok, role, err
}
// UserAuthType returns "guest", "ldap", or "local" for the given username.
// A user with a non-empty pass_hash is always "local", regardless of is_ldap,
// so that the frontend hashes the password before sending it.
@@ -246,7 +300,7 @@ func BrowseLDAP(url, baseDN, adminUser, adminPassword string) ([]string, []strin
return users, groups, nil
}
func (m *Manager) createSession(username, role string) (string, error) {
func (m *Manager) createSession(username, role string, groups []string) (string, error) {
token, err := generateToken()
if err != nil {
return "", err
@@ -256,6 +310,7 @@ func (m *Manager) createSession(username, role string) (string, error) {
Username: username,
Token: token,
Role: role,
Groups: groups,
ExpiresAt: time.Now().Add(24 * time.Hour),
}
m.mu.Unlock()

View File

@@ -0,0 +1,231 @@
package auth
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"strings"
"sync"
"time"
"github.com/brasse-b/archivum/internal/config"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
// OIDCUser is the identity extracted from a verified id_token / userinfo.
type OIDCUser struct {
Username string
Email string
Groups []string
}
var ErrOIDCNotConfigured = errors.New("OIDC not configured")
type oidcState struct {
expiresAt time.Time
}
// OIDCProvider wraps an OpenID Connect provider and OAuth2 client and manages
// the short-lived CSRF state values used during the auth-code flow. It can be
// reconfigured at runtime (after an admin changes the OIDC settings).
type OIDCProvider struct {
mu sync.Mutex
cfg config.OIDCConfig
redirect string
oauth *oauth2.Config
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
ready bool
states map[string]oidcState
}
func NewOIDCProvider() *OIDCProvider {
return &OIDCProvider{states: make(map[string]oidcState)}
}
// Configure (re)initialises the provider from config. It performs OIDC
// discovery against the issuer, which requires network access to the IdP.
// Returns an error if discovery fails; the provider is then left disabled.
func (p *OIDCProvider) Configure(ctx context.Context, cfg config.OIDCConfig, redirectURL string) error {
cfg.Normalize()
p.mu.Lock()
p.cfg = cfg
p.redirect = redirectURL
p.ready = false
p.provider = nil
p.verifier = nil
p.oauth = nil
p.mu.Unlock()
if !cfg.Enabled || cfg.Issuer == "" || cfg.ClientID == "" || redirectURL == "" {
return nil
}
provider, err := oidc.NewProvider(ctx, strings.TrimRight(cfg.Issuer, "/"))
if err != nil {
return err
}
oauthCfg := &oauth2.Config{
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
Endpoint: provider.Endpoint(),
RedirectURL: redirectURL,
Scopes: []string{oidc.ScopeOpenID, "profile", "email", cfg.GroupsClaim},
}
verifier := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID})
p.mu.Lock()
p.provider = provider
p.oauth = oauthCfg
p.verifier = verifier
p.ready = true
p.mu.Unlock()
return nil
}
// Enabled reports whether the provider is configured and ready.
func (p *OIDCProvider) Enabled() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.ready
}
// AuthURL creates a fresh state value and returns the authorization URL to
// redirect the browser to.
func (p *OIDCProvider) AuthURL() (string, error) {
p.mu.Lock()
defer p.mu.Unlock()
if !p.ready {
return "", ErrOIDCNotConfigured
}
state := randToken()
p.states[state] = oidcState{expiresAt: time.Now().Add(10 * time.Minute)}
p.gcStatesLocked()
return p.oauth.AuthCodeURL(state), nil
}
// Exchange validates the state, swaps the code for tokens, verifies the
// id_token and returns the resulting identity (with groups). If the id_token
// carries no groups claim it falls back to the userinfo endpoint.
func (p *OIDCProvider) Exchange(ctx context.Context, state, code string) (*OIDCUser, error) {
p.mu.Lock()
if !p.ready {
p.mu.Unlock()
return nil, ErrOIDCNotConfigured
}
st, ok := p.states[state]
if ok {
delete(p.states, state)
}
oauthCfg := p.oauth
verifier := p.verifier
provider := p.provider
cfg := p.cfg
p.mu.Unlock()
if !ok || time.Now().After(st.expiresAt) {
return nil, errors.New("invalid or expired state")
}
tok, err := oauthCfg.Exchange(ctx, code)
if err != nil {
return nil, err
}
rawID, ok := tok.Extra("id_token").(string)
if !ok {
return nil, errors.New("no id_token in token response")
}
idTok, err := verifier.Verify(ctx, rawID)
if err != nil {
return nil, err
}
var claims map[string]interface{}
if err := idTok.Claims(&claims); err != nil {
return nil, err
}
user := &OIDCUser{
Username: claimString(claims, cfg.UsernameClaim),
Email: claimString(claims, "email"),
Groups: claimStrings(claims, cfg.GroupsClaim),
}
// Some providers only expose groups via userinfo — fall back to it.
if len(user.Groups) == 0 && provider != nil {
if ui, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(tok)); err == nil {
var uiClaims map[string]interface{}
if err := ui.Claims(&uiClaims); err == nil {
user.Groups = claimStrings(uiClaims, cfg.GroupsClaim)
if user.Username == "" {
user.Username = claimString(uiClaims, cfg.UsernameClaim)
}
if user.Email == "" {
user.Email = claimString(uiClaims, "email")
}
}
}
}
if user.Username == "" {
user.Username = user.Email
}
if user.Username == "" {
user.Username = idTok.Subject
}
if user.Username == "" {
return nil, errors.New("could not determine username from OIDC claims")
}
return user, nil
}
func (p *OIDCProvider) gcStatesLocked() {
now := time.Now()
for k, v := range p.states {
if now.After(v.expiresAt) {
delete(p.states, k)
}
}
}
func claimString(claims map[string]interface{}, key string) string {
if v, ok := claims[key].(string); ok {
return v
}
return ""
}
func claimStrings(claims map[string]interface{}, key string) []string {
raw, ok := claims[key]
if !ok {
return nil
}
switch v := raw.(type) {
case []interface{}:
out := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok && s != "" {
out = append(out, s)
}
}
return out
case []string:
return v
case string:
if v == "" {
return nil
}
return []string{v}
}
return nil
}
func randToken() string {
b := make([]byte, 32)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"os"
"strings"
)
// Config holds all backend runtime configuration.
@@ -11,8 +12,13 @@ type Config struct {
StoragePath string `json:"storage_path"`
DBPath string `json:"db_path"`
LDAP LDAPConfig `json:"ldap"`
OIDC OIDCConfig `json:"oidc"`
JWTSecret string `json:"jwt_secret"`
ListenAddr string `json:"listen_addr"`
// PublicURL is the externally reachable base URL of Archivum
// (e.g. https://archivum.brasse-pc.eu). Used to build the OIDC
// redirect URL when one is not set explicitly.
PublicURL string `json:"public_url"`
}
type LDAPConfig struct {
@@ -22,6 +28,50 @@ type LDAPConfig struct {
AdminPass string `json:"admin_pass"`
}
// OIDCConfig configures Single-Sign-On via an OpenID Connect provider
// (Authentik in this deployment). The provider authenticates the user and
// returns their group membership in the groups claim.
type OIDCConfig struct {
Enabled bool `json:"enabled"`
Issuer string `json:"issuer"` // e.g. https://authentik.brasse-pc.eu/application/o/archivum/
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url"` // optional; derived from PublicURL when empty
// Claim/group mapping. Sensible defaults are applied in Normalize().
GroupsClaim string `json:"groups_claim"` // default "groups"
UsernameClaim string `json:"username_claim"` // default "preferred_username"
AdminGroup string `json:"admin_group"` // default "Archivum-admin"
ReaderGroup string `json:"reader_group"` // default "Archivum-reader"
}
// Normalize fills in defaults for optional OIDC fields.
func (o *OIDCConfig) Normalize() {
if o.GroupsClaim == "" {
o.GroupsClaim = "groups"
}
if o.UsernameClaim == "" {
o.UsernameClaim = "preferred_username"
}
if o.AdminGroup == "" {
o.AdminGroup = "Archivum-admin"
}
if o.ReaderGroup == "" {
o.ReaderGroup = "Archivum-reader"
}
}
// ResolvedRedirectURL returns the OIDC callback URL, deriving it from
// PublicURL when RedirectURL is not set.
func (c *Config) ResolvedRedirectURL() string {
if c.OIDC.RedirectURL != "" {
return c.OIDC.RedirectURL
}
if c.PublicURL != "" {
return strings.TrimRight(c.PublicURL, "/") + "/auth/oidc/callback"
}
return ""
}
// ErrRequireSetup is returned when config is missing or empty,
// signalling that the frontend should start the Setup Wizard.
var ErrRequireSetup = errors.New("REQUIRE_SETUP")
@@ -54,6 +104,8 @@ func Load(path string) (*Config, error) {
cfg.DBPath = "/data/db/archivum.db"
}
cfg.OIDC.Normalize()
return &cfg, nil
}

View File

@@ -3,6 +3,7 @@ package db
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
@@ -12,14 +13,31 @@ import (
var ErrUserNotFound = errors.New("user not found")
var ErrUserExists = errors.New("username already exists")
// User represents a local account stored in SQLite.
// Built-in group names that map to application roles. They are seeded on
// startup and are what OIDC group claims are matched against.
const (
GroupAdmin = "Archivum-admin"
GroupReader = "Archivum-reader"
)
// User represents an account stored in SQLite (local or externally
// provisioned via OIDC/LDAP).
type User struct {
ID int64
Username string
PassHash string
Role string
IsLDAP bool
CreatedAt time.Time
ID int64
Username string
PassHash string
Role string
IsLDAP bool
AllowLogin bool
CreatedAt time.Time
}
// Group represents a group stored in SQLite.
type Group struct {
ID int64
Name string
IsLDAP bool
AllowLogin bool
}
// DB wraps the SQLite connection.
@@ -29,7 +47,7 @@ type DB struct {
// New opens (or creates) the SQLite database at path and runs migrations.
func New(path string) (*DB, error) {
sqldb, err := sql.Open("sqlite", path+"?_journal=WAL&_timeout=5000")
sqldb, err := sql.Open("sqlite", path+"?_journal=WAL&_timeout=5000&_pragma=foreign_keys(1)")
if err != nil {
return nil, err
}
@@ -48,18 +66,20 @@ func (d *DB) Close() error {
func (d *DB) init() error {
_, err := d.sql.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
pass_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
is_ldap BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
pass_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
is_ldap BOOLEAN NOT NULL DEFAULT 0,
allow_login BOOLEAN NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
is_ldap BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
is_ldap BOOLEAN NOT NULL DEFAULT 0,
allow_login BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS user_groups (
user_id INTEGER NOT NULL,
@@ -69,34 +89,122 @@ func (d *DB) init() error {
FOREIGN KEY(group_id) REFERENCES groups(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS acl (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL,
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL,
subject_type TEXT NOT NULL CHECK(subject_type IN ('user', 'group')),
subject_id INTEGER NOT NULL,
can_search BOOLEAN NOT NULL DEFAULT 0,
can_view BOOLEAN NOT NULL DEFAULT 0,
can_read BOOLEAN NOT NULL DEFAULT 0,
can_edit BOOLEAN NOT NULL DEFAULT 0,
can_create BOOLEAN NOT NULL DEFAULT 0,
can_delete BOOLEAN NOT NULL DEFAULT 0,
can_move BOOLEAN NOT NULL DEFAULT 0,
UNIQUE(path, subject_type, subject_id)
subject_id INTEGER NOT NULL,
effect TEXT NOT NULL DEFAULT 'allow' CHECK(effect IN ('allow','deny')),
can_search BOOLEAN NOT NULL DEFAULT 0,
can_view BOOLEAN NOT NULL DEFAULT 0,
can_read BOOLEAN NOT NULL DEFAULT 0,
can_edit BOOLEAN NOT NULL DEFAULT 0,
can_create BOOLEAN NOT NULL DEFAULT 0,
can_delete BOOLEAN NOT NULL DEFAULT 0,
can_move BOOLEAN NOT NULL DEFAULT 0,
UNIQUE(path, subject_type, subject_id, effect)
);
`)
return err
if err != nil {
return err
}
return d.migrate()
}
// HasUsers returns true if at least one user account exists.
// migrate brings older databases (created before allow/deny ACLs and the
// allow_login flags) up to the current schema. All steps are idempotent.
func (d *DB) migrate() error {
// users.allow_login
if ok, err := d.columnExists("users", "allow_login"); err != nil {
return err
} else if !ok {
if _, err := d.sql.Exec(`ALTER TABLE users ADD COLUMN allow_login BOOLEAN NOT NULL DEFAULT 1`); err != nil {
return err
}
}
// groups.allow_login
if ok, err := d.columnExists("groups", "allow_login"); err != nil {
return err
} else if !ok {
if _, err := d.sql.Exec(`ALTER TABLE groups ADD COLUMN allow_login BOOLEAN NOT NULL DEFAULT 0`); err != nil {
return err
}
}
// acl.effect — requires a table rebuild because the UNIQUE constraint changes.
if ok, err := d.columnExists("acl", "effect"); err != nil {
return err
} else if !ok {
tx, err := d.sql.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stmts := []string{
`ALTER TABLE acl RENAME TO acl_old`,
`CREATE TABLE acl (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL,
subject_type TEXT NOT NULL CHECK(subject_type IN ('user', 'group')),
subject_id INTEGER NOT NULL,
effect TEXT NOT NULL DEFAULT 'allow' CHECK(effect IN ('allow','deny')),
can_search BOOLEAN NOT NULL DEFAULT 0,
can_view BOOLEAN NOT NULL DEFAULT 0,
can_read BOOLEAN NOT NULL DEFAULT 0,
can_edit BOOLEAN NOT NULL DEFAULT 0,
can_create BOOLEAN NOT NULL DEFAULT 0,
can_delete BOOLEAN NOT NULL DEFAULT 0,
can_move BOOLEAN NOT NULL DEFAULT 0,
UNIQUE(path, subject_type, subject_id, effect)
)`,
`INSERT INTO acl (path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
SELECT path, subject_type, subject_id, 'allow', can_search, can_view, can_read, can_edit, can_create, can_delete, can_move FROM acl_old`,
`DROP TABLE acl_old`,
}
for _, s := range stmts {
if _, err := tx.Exec(s); err != nil {
return fmt.Errorf("acl migration: %w", err)
}
}
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func (d *DB) columnExists(table, column string) (bool, error) {
rows, err := d.sql.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
if err != nil {
return false, err
}
defer rows.Close()
for rows.Next() {
var cid int
var name, ctype string
var notnull, pk int
var dflt sql.NullString
if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err != nil {
return false, err
}
if name == column {
return true, nil
}
}
return false, rows.Err()
}
// HasUsers returns true if at least one non-guest user account exists.
func (d *DB) HasUsers() bool {
var n int
d.sql.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
d.sql.QueryRow(`SELECT COUNT(*) FROM users WHERE username != 'guest'`).Scan(&n)
return n > 0
}
// CreateUser inserts a new user. Returns ErrUserExists if the username is taken.
// ── Users ───────────────────────────────────────────────────────────────────
// CreateUser inserts a new local user. Returns ErrUserExists if taken.
func (d *DB) CreateUser(username, passHash, role string) error {
_, err := d.sql.Exec(
`INSERT INTO users (username, pass_hash, role) VALUES (?, ?, ?)`,
`INSERT INTO users (username, pass_hash, role, allow_login) VALUES (?, ?, ?, 1)`,
username, passHash, role,
)
if err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") {
@@ -108,12 +216,12 @@ func (d *DB) CreateUser(username, passHash, role string) error {
// GetUser fetches a single user by username.
func (d *DB) GetUser(username string) (*User, error) {
row := d.sql.QueryRow(
`SELECT id, username, pass_hash, role, is_ldap, created_at FROM users WHERE username = ?`,
`SELECT id, username, pass_hash, role, is_ldap, allow_login, created_at FROM users WHERE username = ?`,
username,
)
u := &User{}
var createdAt string
err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.IsLDAP, &createdAt)
err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.IsLDAP, &u.AllowLogin, &createdAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserNotFound
}
@@ -127,7 +235,7 @@ func (d *DB) GetUser(username string) (*User, error) {
// ListUsers returns all users ordered by id.
func (d *DB) ListUsers() ([]*User, error) {
rows, err := d.sql.Query(
`SELECT id, username, role, is_ldap, created_at FROM users ORDER BY id`,
`SELECT id, username, role, is_ldap, allow_login, created_at FROM users ORDER BY id`,
)
if err != nil {
return nil, err
@@ -138,7 +246,7 @@ func (d *DB) ListUsers() ([]*User, error) {
for rows.Next() {
u := &User{}
var createdAt string
if err := rows.Scan(&u.ID, &u.Username, &u.Role, &u.IsLDAP, &createdAt); err != nil {
if err := rows.Scan(&u.ID, &u.Username, &u.Role, &u.IsLDAP, &u.AllowLogin, &createdAt); err != nil {
return nil, err
}
u.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
@@ -176,49 +284,253 @@ func (d *DB) UpdatePassword(username, passHash string) error {
return nil
}
// UserCount returns the total number of local accounts.
// SetUserRole updates a user's role (admin/user/guest).
func (d *DB) SetUserRole(username, role string) error {
_, err := d.sql.Exec(`UPDATE users SET role = ? WHERE username = ?`, role, username)
return err
}
// SetUserLogin toggles whether a user is permitted to sign in.
func (d *DB) SetUserLogin(username string, allow bool) error {
_, err := d.sql.Exec(`UPDATE users SET allow_login = ? WHERE username = ?`, boolInt(allow), username)
return err
}
// UserCount returns the total number of accounts.
func (d *DB) UserCount() (int, error) {
var n int
err := d.sql.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
return n, err
}
// --- LDAP & Roles ---
// ── LDAP / OIDC provisioning ─────────────────────────────────────────────────
// CreateOrUpdateLDAPUser inserts or updates an LDAP user (without password, role='user').
// Existing accounts with a non-empty pass_hash are never overwritten so that
// a local admin cannot be accidentally converted to an LDAP-only account.
func (d *DB) CreateOrUpdateLDAPUser(username string) error {
// CreateOrUpdateExternalUser inserts or updates an externally-authenticated
// user (OIDC/LDAP; no local password). On first insert allow_login is set to
// allowLogin; on subsequent logins the stored allow_login is preserved so an
// admin's manual toggle sticks. Existing accounts with a non-empty pass_hash
// (local admins) keep their role — they are never downgraded.
func (d *DB) CreateOrUpdateExternalUser(username, role string, allowLogin bool) error {
if role == "" {
role = "user"
}
_, err := d.sql.Exec(`
INSERT INTO users (username, pass_hash, role, is_ldap)
VALUES (?, '', 'user', 1)
ON CONFLICT(username) DO UPDATE SET is_ldap=1
WHERE excluded.pass_hash = '' AND pass_hash = '';
`, username)
INSERT INTO users (username, pass_hash, role, is_ldap, allow_login)
VALUES (?, '', ?, 1, ?)
ON CONFLICT(username) DO UPDATE SET is_ldap=1, role=excluded.role
WHERE users.pass_hash = '';
`, username, role, boolInt(allowLogin))
return err
}
// CreateOrUpdateGroup inserts or updates a group (local or LDAP).
// CreateOrUpdateGroup inserts or updates a group (local or external).
func (d *DB) CreateOrUpdateGroup(name string, isLdap bool) error {
ldVal := 0
if isLdap {
ldVal = 1
}
_, err := d.sql.Exec(`
INSERT INTO groups (name, is_ldap)
VALUES (?, ?)
ON CONFLICT(name) DO UPDATE SET is_ldap=excluded.is_ldap;
`, name, ldVal)
`, name, boolInt(isLdap))
return err
}
// --- ACL Methods ---
// DeleteGroup removes a group and its memberships/ACLs cascade via FK / manual cleanup.
func (d *DB) DeleteGroup(name string) error {
g, err := d.GetGroup(name)
if err != nil {
return err
}
tx, err := d.sql.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM acl WHERE subject_type='group' AND subject_id=?`, g.ID); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM groups WHERE id=?`, g.ID); err != nil {
return err
}
return tx.Commit()
}
// SetGroupLogin toggles whether members of a group are permitted to sign in.
func (d *DB) SetGroupLogin(name string, allow bool) error {
_, err := d.sql.Exec(`UPDATE groups SET allow_login = ? WHERE name = ?`, boolInt(allow), name)
return err
}
// GetGroup fetches a group by name.
func (d *DB) GetGroup(name string) (*Group, error) {
row := d.sql.QueryRow(`SELECT id, name, is_ldap, allow_login FROM groups WHERE name = ?`, name)
g := &Group{}
if err := row.Scan(&g.ID, &g.Name, &g.IsLDAP, &g.AllowLogin); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserNotFound
}
return nil, err
}
return g, nil
}
// ListGroups returns all groups ordered by name.
func (d *DB) ListGroups() ([]*Group, error) {
rows, err := d.sql.Query(`SELECT id, name, is_ldap, allow_login FROM groups ORDER BY name`)
if err != nil {
return nil, err
}
defer rows.Close()
var groups []*Group
for rows.Next() {
g := &Group{}
if err := rows.Scan(&g.ID, &g.Name, &g.IsLDAP, &g.AllowLogin); err != nil {
return nil, err
}
groups = append(groups, g)
}
return groups, rows.Err()
}
// EnsureBuiltinGroups creates the Archivum-admin / Archivum-reader groups that
// map to application roles. They are marked external (synced from the IdP) and
// login-enabled.
func (d *DB) EnsureBuiltinGroups() error {
for _, name := range []string{GroupAdmin, GroupReader} {
if _, err := d.sql.Exec(`
INSERT INTO groups (name, is_ldap, allow_login) VALUES (?, 1, 1)
ON CONFLICT(name) DO UPDATE SET allow_login=1;
`, name); err != nil {
return err
}
}
return nil
}
// EnsureGuestUser creates the built-in public/guest account if missing.
func (d *DB) EnsureGuestUser() error {
_, err := d.sql.Exec(`
INSERT INTO users (username, pass_hash, role, allow_login) VALUES ('guest', '', 'guest', 1)
ON CONFLICT(username) DO NOTHING;
`)
return err
}
// ── Group membership ──────────────────────────────────────────────────────────
// AddUserToGroup links a user to a group (both by name).
func (d *DB) AddUserToGroup(username, groupName string) error {
u, err := d.GetUser(username)
if err != nil {
return err
}
g, err := d.GetGroup(groupName)
if err != nil {
return err
}
_, err = d.sql.Exec(`INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)`, u.ID, g.ID)
return err
}
// RemoveUserFromGroup unlinks a user from a group.
func (d *DB) RemoveUserFromGroup(username, groupName string) error {
u, err := d.GetUser(username)
if err != nil {
return err
}
g, err := d.GetGroup(groupName)
if err != nil {
return err
}
_, err = d.sql.Exec(`DELETE FROM user_groups WHERE user_id=? AND group_id=?`, u.ID, g.ID)
return err
}
// GetUserGroupNames returns the names of all groups a (local) user belongs to.
func (d *DB) GetUserGroupNames(username string) ([]string, error) {
rows, err := d.sql.Query(`
SELECT g.name FROM groups g
JOIN user_groups ug ON ug.group_id = g.id
JOIN users u ON u.id = ug.user_id
WHERE u.username = ?
ORDER BY g.name
`, username)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
return nil, err
}
out = append(out, n)
}
return out, rows.Err()
}
// SyncUserGroups ensures the given group names exist and that the user is a
// member of exactly those groups that are also present in the DB. Used to keep
// a local mirror of an OIDC user's group membership for the admin UI.
func (d *DB) SyncUserGroups(username string, groupNames []string) error {
u, err := d.GetUser(username)
if err != nil {
return err
}
tx, err := d.sql.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM user_groups WHERE user_id=?`, u.ID); err != nil {
return err
}
for _, name := range groupNames {
var gid int64
if err := tx.QueryRow(`SELECT id FROM groups WHERE name=?`, name).Scan(&gid); err != nil {
if errors.Is(err, sql.ErrNoRows) {
continue
}
return err
}
if _, err := tx.Exec(`INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)`, u.ID, gid); err != nil {
return err
}
}
return tx.Commit()
}
// ── Login gate ────────────────────────────────────────────────────────────────
// LoginAllowed reports whether a subject may sign in: the user must have
// allow_login set, or belong to at least one login-enabled group (by name).
// The built-in role groups always permit login.
func (d *DB) LoginAllowed(username string, groupNames []string) bool {
if u, err := d.GetUser(username); err == nil {
if u.Role == "admin" || u.AllowLogin {
return true
}
}
for _, name := range groupNames {
if name == GroupAdmin || name == GroupReader {
return true
}
var allow int
d.sql.QueryRow(`SELECT allow_login FROM groups WHERE name=?`, name).Scan(&allow)
if allow == 1 {
return true
}
}
return false
}
// ── ACL ────────────────────────────────────────────────────────────────────
type ACLEntry struct {
ID int64
Path string
SubjectType string
SubjectID int64
Effect string // "allow" | "deny"
CanSearch bool
CanView bool
CanRead bool
@@ -228,20 +540,34 @@ type ACLEntry struct {
CanMove bool
}
// SetACL inserts or replaces an ACL entry.
// Perms is the resolved effective permission set for a subject on a path.
type Perms struct {
Search bool
View bool
Read bool
Edit bool
Create bool
Delete bool
Move bool
}
// SetACL inserts or replaces an ACL entry keyed on (path, subject, effect).
func (d *DB) SetACL(entry ACLEntry) error {
if entry.Effect != "deny" {
entry.Effect = "allow"
}
_, err := d.sql.Exec(`
INSERT INTO acl (path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(path, subject_type, subject_id) DO UPDATE SET
INSERT INTO acl (path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(path, subject_type, subject_id, effect) DO UPDATE SET
can_search = excluded.can_search,
can_view = excluded.can_view,
can_read = excluded.can_read,
can_edit = excluded.can_edit,
can_view = excluded.can_view,
can_read = excluded.can_read,
can_edit = excluded.can_edit,
can_create = excluded.can_create,
can_delete = excluded.can_delete,
can_move = excluded.can_move;
`, entry.Path, entry.SubjectType, entry.SubjectID,
can_move = excluded.can_move;
`, entry.Path, entry.SubjectType, entry.SubjectID, entry.Effect,
entry.CanSearch, entry.CanView, entry.CanRead, entry.CanEdit,
entry.CanCreate, entry.CanDelete, entry.CanMove)
return err
@@ -253,23 +579,13 @@ func (d *DB) RemoveACL(id int64) error {
return err
}
// GetACLsForSubject retrieves all ACL entries for a specific subject (user or group).
func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry, error) {
rows, err := d.sql.Query(`
SELECT id, path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move
FROM acl WHERE subject_type = ? AND subject_id = ?
ORDER BY path
`, subjectType, subjectID)
if err != nil {
return nil, err
}
func scanACLRows(rows *sql.Rows) ([]ACLEntry, error) {
defer rows.Close()
var entries []ACLEntry
for rows.Next() {
var e ACLEntry
if err := rows.Scan(
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID,
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID, &e.Effect,
&e.CanSearch, &e.CanView, &e.CanRead, &e.CanEdit,
&e.CanCreate, &e.CanDelete, &e.CanMove,
); err != nil {
@@ -280,106 +596,125 @@ func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry,
return entries, rows.Err()
}
// GetACLsForPath retrieves all ACL definitions for a specific document or folder.
const aclCols = `id, path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move`
// GetACLsForSubject retrieves all ACL entries for a specific subject.
func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry, error) {
rows, err := d.sql.Query(
`SELECT `+aclCols+` FROM acl WHERE subject_type = ? AND subject_id = ? ORDER BY path, effect`,
subjectType, subjectID)
if err != nil {
return nil, err
}
return scanACLRows(rows)
}
// GetACLsForPath retrieves all ACL definitions for a specific path.
func (d *DB) GetACLsForPath(path string) ([]ACLEntry, error) {
rows, err := d.sql.Query(`
SELECT id, path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move
FROM acl WHERE path = ?
`, path)
rows, err := d.sql.Query(`SELECT `+aclCols+` FROM acl WHERE path = ?`, path)
if err != nil {
return nil, err
}
defer rows.Close()
return scanACLRows(rows)
}
var entries []ACLEntry
for rows.Next() {
var e ACLEntry
if err := rows.Scan(
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID,
&e.CanSearch, &e.CanView, &e.CanRead, &e.CanEdit,
&e.CanCreate, &e.CanDelete, &e.CanMove,
); err != nil {
return nil, err
}
entries = append(entries, e)
// EffectiveAccess resolves the permissions a user has on a path by combining
// every ACL entry that applies to the user directly or to any of the given
// groups, across the path and all of its ancestor folders.
//
// Resolution rule (as specified): default deny. An explicit allow grants a
// permission; an explicit deny anywhere in the applicable set always wins over
// an allow. So a permission is granted only if some entry allows it and no
// entry denies it.
func (d *DB) EffectiveAccess(username string, groupNames []string, path string) Perms {
ancestors := pathAncestors(path)
ancestorSet := make(map[string]bool, len(ancestors))
for _, p := range ancestors {
ancestorSet[p] = true
}
return entries, nil
}
// Group represents a group stored in SQLite.
type Group struct {
ID int64
Name string
IsLDAP bool
}
// Build the subject filter: this user + these groups.
var where []string
var args []interface{}
if uid, ok := d.userID(username); ok {
where = append(where, `(subject_type='user' AND subject_id=?)`)
args = append(args, uid)
}
if gids := d.groupIDs(groupNames); len(gids) > 0 {
ph := make([]string, len(gids))
for i, id := range gids {
ph[i] = "?"
args = append(args, id)
}
where = append(where, `(subject_type='group' AND subject_id IN (`+strings.Join(ph, ",")+`))`)
}
if len(where) == 0 {
return Perms{}
}
// ListGroups returns all groups ordered by name.
func (d *DB) ListGroups() ([]*Group, error) {
rows, err := d.sql.Query(`SELECT id, name, is_ldap FROM groups ORDER BY name`)
rows, err := d.sql.Query(
`SELECT `+aclCols+` FROM acl WHERE `+strings.Join(where, " OR "), args...)
if err != nil {
return nil, err
return Perms{}
}
defer rows.Close()
var groups []*Group
for rows.Next() {
g := &Group{}
if err := rows.Scan(&g.ID, &g.Name, &g.IsLDAP); err != nil {
return nil, err
entries, err := scanACLRows(rows)
if err != nil {
return Perms{}
}
var allow, deny Perms
for _, e := range entries {
if !ancestorSet[e.Path] {
continue
}
groups = append(groups, g)
target := &allow
if e.Effect == "deny" {
target = &deny
}
target.Search = target.Search || e.CanSearch
target.View = target.View || e.CanView
target.Read = target.Read || e.CanRead
target.Edit = target.Edit || e.CanEdit
target.Create = target.Create || e.CanCreate
target.Delete = target.Delete || e.CanDelete
target.Move = target.Move || e.CanMove
}
return Perms{
Search: allow.Search && !deny.Search,
View: allow.View && !deny.View,
Read: allow.Read && !deny.Read,
Edit: allow.Edit && !deny.Edit,
Create: allow.Create && !deny.Create,
Delete: allow.Delete && !deny.Delete,
Move: allow.Move && !deny.Move,
}
return groups, rows.Err()
}
// EnsureGuestUser creates the built-in guest account if it does not already exist.
func (d *DB) EnsureGuestUser() error {
_, err := d.sql.Exec(`
INSERT INTO users (username, pass_hash, role) VALUES ('guest', '', 'guest')
ON CONFLICT(username) DO NOTHING;
`)
return err
func (d *DB) userID(username string) (int64, bool) {
var id int64
err := d.sql.QueryRow(`SELECT id FROM users WHERE username=?`, username).Scan(&id)
if err != nil {
return 0, false
}
return id, true
}
// CanUserReadPath returns true if the given username has can_read access on the
// exact path or any of its ancestor folder paths.
func (d *DB) CanUserReadPath(username, path string) bool {
// Build a list of candidate paths: the path itself and each parent segment.
candidates := pathAncestors(path)
for _, p := range candidates {
var n int
d.sql.QueryRow(`
SELECT COUNT(*) FROM acl
JOIN users ON users.id = acl.subject_id AND acl.subject_type = 'user'
WHERE users.username = ? AND acl.path = ? AND acl.can_read = 1
`, username, p).Scan(&n)
if n > 0 {
return true
func (d *DB) groupIDs(names []string) []int64 {
var out []int64
for _, n := range names {
var id int64
if err := d.sql.QueryRow(`SELECT id FROM groups WHERE name=?`, n).Scan(&id); err == nil {
out = append(out, id)
}
}
return false
}
// CanUserViewPath returns true if the given username has can_view access on the
// exact path or any of its ancestor folder paths.
func (d *DB) CanUserViewPath(username, path string) bool {
candidates := pathAncestors(path)
for _, p := range candidates {
var n int
d.sql.QueryRow(`
SELECT COUNT(*) FROM acl
JOIN users ON users.id = acl.subject_id AND acl.subject_type = 'user'
WHERE users.username = ? AND acl.path = ? AND acl.can_view = 1
`, username, p).Scan(&n)
if n > 0 {
return true
}
}
return false
return out
}
// pathAncestors returns the path and all its parent segments.
// e.g. "a/b/c" → ["a/b/c", "a/b", "a"]
func pathAncestors(path string) []string {
path = strings.TrimSuffix(path, "/")
out := []string{path}
for {
idx := strings.LastIndex(path, "/")
@@ -391,3 +726,10 @@ func pathAncestors(path string) []string {
}
return out
}
func boolInt(b bool) int {
if b {
return 1
}
return 0
}

View File

@@ -49,6 +49,18 @@ type Query {
# Returns the role of the currently authenticated user ("admin", "user", "guest").
currentUserRole: String!
# Sign-in methods the login page should offer (public, no auth required).
loginOptions: LoginOptions!
# All local/external users with role & login state (admin only).
users: [UserInfo!]!
# Current OpenID Connect (Authentik) configuration (admin only, no secret).
oidcConfig: OIDCConfigView!
# Names of the groups a user belongs to (admin only).
userGroups(username: String!): [String!]!
}
type Mutation {
@@ -73,9 +85,25 @@ type Mutation {
# Modify LDAP Configuration (admin only).
updateLdapConfig(input: LDAPInput): Boolean!
# Modify OpenID Connect (Authentik) configuration (admin only).
updateOidcConfig(input: OIDCInput!): Boolean!
# Sync users/groups from LDAP
importLdapSubject(type: String!, name: String!): Boolean!
# Group management (admin only).
createGroup(name: String!): Boolean!
deleteGroup(name: String!): Boolean!
addUserToGroup(username: String!, group: String!): Boolean!
removeUserFromGroup(username: String!, group: String!): Boolean!
# Who may sign in (admin only).
setUserLogin(username: String!, allow: Boolean!): Boolean!
setGroupLogin(name: String!, allow: Boolean!): Boolean!
# Change a user's application role: "admin" | "user" (admin only).
setUserRole(username: String!, role: String!): Boolean!
# ACL Mutations
setAcl(input: ACLInput!): Boolean!
removeAcl(id: Int!): Boolean!
@@ -127,6 +155,7 @@ type ACLEntry {
path: String!
subjectType: String!
subjectId: Int!
effect: String! # "allow" | "deny" — deny always wins over allow
canSearch: Boolean!
canView: Boolean!
canRead: Boolean!
@@ -136,6 +165,35 @@ type ACLEntry {
canMove: Boolean!
}
type LoginOptions {
localEnabled: Boolean!
oidcEnabled: Boolean!
oidcButtonLabel: String!
publicEnabled: Boolean!
}
type UserInfo {
username: String!
role: String!
isLdap: Boolean!
allowLogin: Boolean!
createdAt: String!
}
type OIDCConfigView {
enabled: Boolean!
ready: Boolean!
issuer: String!
clientId: String!
clientSecretSet: Boolean!
redirectUrl: String!
publicUrl: String!
groupsClaim: String!
usernameClaim: String!
adminGroup: String!
readerGroup: String!
}
type ServerDirectory {
name: String!
path: String!
@@ -198,9 +256,11 @@ input LDAPInput {
}
type ACLSubject {
id: Int!
name: String!
isLdap: Boolean!
id: Int!
name: String!
isLdap: Boolean!
role: String # only present for users
allowLogin: Boolean!
}
type ACLSubjects {
@@ -212,6 +272,7 @@ input ACLInput {
path: String!
subjectType: String!
subjectId: Int!
effect: String # "allow" (default) | "deny"
canSearch: Boolean!
canView: Boolean!
canRead: Boolean!
@@ -221,6 +282,19 @@ input ACLInput {
canMove: Boolean!
}
input OIDCInput {
enabled: Boolean!
issuer: String!
clientId: String!
clientSecret: String # empty = keep existing
redirectUrl: String
publicUrl: String
groupsClaim: String
usernameClaim: String
adminGroup: String
readerGroup: String
}
input SaveDocumentInput {
slug: String!
content: String!

View File

@@ -2,11 +2,13 @@ package graph
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
@@ -30,10 +32,11 @@ type Server struct {
database *db.DB
authMgr *auth.Manager
gitRepo *git.Repo
oidc *auth.OIDCProvider
}
func NewServer(cfg *config.Config, configPath string) http.Handler {
s := &Server{cfg: cfg, configPath: configPath}
s := &Server{cfg: cfg, configPath: configPath, oidc: auth.NewOIDCProvider()}
if cfg != nil {
s.initRuntime(cfg)
@@ -44,6 +47,8 @@ func NewServer(cfg *config.Config, configPath string) http.Handler {
mux.HandleFunc("/health", s.handleHealth)
mux.HandleFunc("/api/upload", s.handleUpload)
mux.HandleFunc("/media/", s.handleMedia)
mux.HandleFunc("/auth/oidc/login", s.handleOIDCLogin)
mux.HandleFunc("/auth/oidc/callback", s.handleOIDCCallback)
uiDir := os.Getenv("UI_DIR")
if uiDir == "" {
@@ -75,10 +80,13 @@ func (s *Server) initRuntime(cfg *config.Config) {
log.Printf("[db] failed to open at %s: %v", cfg.DBPath, err)
} else {
d = database
// Ensure guest user exists (handles upgrades from older versions).
// Ensure guest user + built-in role groups exist (handles upgrades).
if err := d.EnsureGuestUser(); err != nil {
log.Printf("[db] warning: could not ensure guest user: %v", err)
}
if err := d.EnsureBuiltinGroups(); err != nil {
log.Printf("[db] warning: could not ensure built-in groups: %v", err)
}
log.Printf("[db] opened at %s", cfg.DBPath)
}
@@ -98,7 +106,31 @@ func (s *Server) initRuntime(cfg *config.Config) {
s.database = d
s.authMgr = am
s.gitRepo = gr
if s.oidc == nil {
s.oidc = auth.NewOIDCProvider()
}
s.mu.Unlock()
s.configureOIDC(cfg)
}
// configureOIDC (re)initialises the OIDC provider from config. Discovery
// requires reaching the IdP, so it runs in the background to avoid blocking
// startup if Authentik is momentarily unavailable.
func (s *Server) configureOIDC(cfg *config.Config) {
if cfg == nil || s.oidc == nil {
return
}
oc := cfg.OIDC
redirect := cfg.ResolvedRedirectURL()
provider := s.oidc
go func() {
if err := provider.Configure(context.Background(), oc, redirect); err != nil {
log.Printf("[oidc] provider not ready: %v", err)
} else if oc.Enabled {
log.Printf("[oidc] provider configured (issuer=%s, redirect=%s)", oc.Issuer, redirect)
}
}()
}
// ── GraphQL handler ───────────────────────────────────────────────────────────
@@ -157,6 +189,11 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) {
writeJSON(w, `{"data":{"systemStatus":"OK"}}`)
}
// Public: what sign-in methods the login page should offer. Must be
// matched before the "login" case since it also contains that substring.
case strings.Contains(q, "loginOptions"):
s.handleLoginOptions(w)
case strings.Contains(q, "testLdapConnection"):
s.handleTestLdapConnection(w, req)
@@ -188,6 +225,37 @@ func (s *Server) dispatchAuthenticated(
q := req.Query
switch {
// ── Admin: OIDC / groups / membership / login gate (matched first) ─────────
case strings.Contains(q, "updateOidcConfig"):
s.handleUpdateOidcConfig(w, req, sess)
case strings.Contains(q, "oidcConfig"):
s.handleOidcConfig(w, sess)
case strings.Contains(q, "createGroup"):
s.handleCreateGroup(w, req, sess)
case strings.Contains(q, "deleteGroup"):
s.handleDeleteGroup(w, req, sess)
case strings.Contains(q, "addUserToGroup"):
s.handleAddUserToGroup(w, req, sess)
case strings.Contains(q, "removeUserFromGroup"):
s.handleRemoveUserFromGroup(w, req, sess)
case strings.Contains(q, "setUserLogin"):
s.handleSetUserLogin(w, req, sess)
case strings.Contains(q, "setGroupLogin"):
s.handleSetGroupLogin(w, req, sess)
case strings.Contains(q, "setUserRole"):
s.handleSetUserRole(w, req, sess)
case strings.Contains(q, "userGroups"):
s.handleUserGroups(w, req, sess)
case strings.Contains(q, "saveDocument"):
s.handleSaveDocument(w, req, sess)
@@ -398,6 +466,38 @@ func (s *Server) sessionFromRequest(r *http.Request) *auth.Session {
return sess
}
// allPerms is the permission set granted to administrators (who bypass ACLs).
var allPerms = db.Perms{Search: true, View: true, Read: true, Edit: true, Create: true, Delete: true, Move: true}
// access resolves the effective permissions the session has on a path.
// Administrators always get the full set; everyone else (users, readers,
// guest/public) is resolved through the allow/deny ACL model, which defaults
// to deny. A nil session gets nothing.
func (s *Server) access(sess *auth.Session, path string) db.Perms {
if sess == nil {
return db.Perms{}
}
if sess.Role == "admin" {
return allPerms
}
s.mu.RLock()
database := s.database
s.mu.RUnlock()
if database == nil {
return db.Perms{}
}
return database.EffectiveAccess(sess.Username, sess.Groups, path)
}
// parentDir returns the folder containing a slug, or "" at the root.
func parentDir(slug string) string {
slug = strings.Trim(slug, "/")
if idx := strings.LastIndex(slug, "/"); idx >= 0 {
return slug[:idx]
}
return ""
}
// ── Document handlers ─────────────────────────────────────────────────────────
func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *auth.Session, store *storage.Store) {
@@ -423,15 +523,10 @@ func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *au
log.Printf("[document] user %q is opening document %q", sess.Username, slug)
// Guest users may only read documents they have been given access to.
s.mu.RLock()
database := s.database
s.mu.RUnlock()
if sess.Role == "guest" && database != nil {
if !database.CanUserReadPath(sess.Username, slug) && !database.CanUserViewPath(sess.Username, slug) {
writeGQLError(w, "UNAUTHORIZED")
return
}
// Everyone except admin is gated by the allow/deny ACL model.
if !s.access(sess, slug).Read {
writeGQLError(w, "UNAUTHORIZED")
return
}
content, err := store.Read(slug)
@@ -467,15 +562,12 @@ func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *au
log.Printf("[document] user %q listed documents (found %d documents)", sess.Username, len(slugs))
s.mu.RLock()
database := s.database
s.mu.RUnlock()
docs := make([]map[string]string, 0, len(slugs))
for _, slug := range slugs {
// Guest users may only see documents they have explicit read or view access to.
if sess.Role == "guest" && database != nil {
if !database.CanUserReadPath(sess.Username, slug) && !database.CanUserViewPath(sess.Username, slug) {
// Non-admins only see documents they can view, read or search for.
if sess.Role != "admin" {
p := s.access(sess, slug)
if !(p.Read || p.View || p.Search) {
continue
}
}
@@ -525,6 +617,13 @@ func (s *Server) handleSaveDocument(w http.ResponseWriter, req gqlRequest, sess
commitMsg = "Update " + slug
}
// Saving requires edit (existing docs) or create (new docs) permission.
if p := s.access(sess, slug); !(p.Edit || p.Create) {
log.Printf("[acl] save denied for %q on %q", sess.Username, slug)
writeGQLError(w, "UNAUTHORIZED")
return
}
log.Printf("[document] user %q is attempting to save document %q (commit msg: %q)", sess.Username, slug, commitMsg)
s.mu.RLock()
@@ -584,6 +683,11 @@ func (s *Server) handleDeleteDocument(w http.ResponseWriter, req gqlRequest, ses
return
}
if !s.access(sess, slug).Delete {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
store := s.store
s.mu.RUnlock()
@@ -704,12 +808,14 @@ func (s *Server) handleUsers(w http.ResponseWriter, sess *auth.Session) {
return
}
list := make([]map[string]string, 0, len(users))
list := make([]map[string]interface{}, 0, len(users))
for _, u := range users {
list = append(list, map[string]string{
"username": u.Username,
"role": u.Role,
"createdAt": u.CreatedAt.Format(time.RFC3339),
list = append(list, map[string]interface{}{
"username": u.Username,
"role": u.Role,
"isLdap": u.IsLDAP,
"allowLogin": u.AllowLogin,
"createdAt": u.CreatedAt.Format(time.RFC3339),
})
}
@@ -748,6 +854,7 @@ func (s *Server) handleSubjectAcl(w http.ResponseWriter, req gqlRequest, sess *a
"path": a.Path,
"subjectType": a.SubjectType,
"subjectId": a.SubjectID,
"effect": a.Effect,
"canSearch": a.CanSearch,
"canView": a.CanView,
"canRead": a.CanRead,
@@ -807,17 +914,20 @@ func (s *Server) handleAclSubjects(w http.ResponseWriter, sess *auth.Session) {
userList := make([]map[string]interface{}, 0, len(users))
for _, u := range users {
userList = append(userList, map[string]interface{}{
"id": u.ID,
"name": u.Username,
"isLdap": u.IsLDAP,
"id": u.ID,
"name": u.Username,
"isLdap": u.IsLDAP,
"role": u.Role,
"allowLogin": u.AllowLogin,
})
}
groupList := make([]map[string]interface{}, 0, len(groups))
for _, g := range groups {
groupList = append(groupList, map[string]interface{}{
"id": g.ID,
"name": g.Name,
"isLdap": g.IsLDAP,
"id": g.ID,
"name": g.Name,
"isLdap": g.IsLDAP,
"allowLogin": g.AllowLogin,
})
}
@@ -1238,6 +1348,10 @@ func (s *Server) handleSetup(w http.ResponseWriter, req gqlRequest) {
if err := database.EnsureGuestUser(); err != nil {
log.Printf("[setup] warning: could not create guest user: %v", err)
}
// Ensure the Archivum-admin / Archivum-reader role groups exist.
if err := database.EnsureBuiltinGroups(); err != nil {
log.Printf("[setup] warning: could not create built-in groups: %v", err)
}
log.Printf("[setup] admin user %q created", adminUser)
@@ -1269,8 +1383,13 @@ func (s *Server) handleSetup(w http.ResponseWriter, req gqlRequest) {
s.database = database
s.authMgr = auth.NewManager(cfg)
s.gitRepo = repo
if s.oidc == nil {
s.oidc = auth.NewOIDCProvider()
}
s.mu.Unlock()
s.configureOIDC(cfg)
log.Printf("[setup] complete")
writeJSON(w, `{"data":{"setup":true}}`)
}
@@ -1501,7 +1620,7 @@ func (s *Server) handleImportLdapSubject(w http.ResponseWriter, req gqlRequest,
var err error
if typ == "user" {
err = database.CreateOrUpdateLDAPUser(name)
err = database.CreateOrUpdateExternalUser(name, "user", true)
} else if typ == "group" {
err = database.CreateOrUpdateGroup(name, true)
} else {
@@ -1536,6 +1655,10 @@ func (s *Server) handleSetAcl(w http.ResponseWriter, req gqlRequest, sess *auth.
var entry db.ACLEntry
entry.Path = strVal(input, "path")
entry.SubjectType = strVal(input, "subjectType")
entry.Effect = strVal(input, "effect")
if entry.Effect != "deny" {
entry.Effect = "allow"
}
if idF, ok := input["subjectId"].(float64); ok {
entry.SubjectID = int64(idF)
} else {
@@ -1611,6 +1734,7 @@ func (s *Server) handleAcl(w http.ResponseWriter, req gqlRequest, sess *auth.Ses
"path": a.Path,
"subjectType": a.SubjectType,
"subjectId": a.SubjectID,
"effect": a.Effect,
"canSearch": a.CanSearch,
"canView": a.CanView,
"canRead": a.CanRead,
@@ -1662,6 +1786,11 @@ func (s *Server) handleHistory(w http.ResponseWriter, req gqlRequest, sess *auth
return
}
if !s.access(sess, slug).Read {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
repo := s.gitRepo
s.mu.RUnlock()
@@ -1701,6 +1830,11 @@ func (s *Server) handleDiff(w http.ResponseWriter, req gqlRequest, sess *auth.Se
fromHash, _ := req.Variables["fromHash"].(string)
toHash, _ := req.Variables["toHash"].(string)
if !s.access(sess, slug).Read {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
repo := s.gitRepo
s.mu.RUnlock()
@@ -1727,6 +1861,11 @@ func (s *Server) handleDocumentAtCommit(w http.ResponseWriter, req gqlRequest, s
slug, _ := req.Variables["slug"].(string)
hash, _ := req.Variables["hash"].(string)
if !s.access(sess, slug).Read {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
repo := s.gitRepo
s.mu.RUnlock()
@@ -1757,6 +1896,11 @@ func (s *Server) handleCreateFolder(w http.ResponseWriter, req gqlRequest, sess
return
}
if p := s.access(sess, path); !(p.Create || p.Edit) {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
store := s.store
s.mu.RUnlock()
@@ -1794,6 +1938,16 @@ func (s *Server) handleMoveDocument(w http.ResponseWriter, req gqlRequest, sess
return
}
// Moving requires move permission on the source and write on the destination.
if !s.access(sess, oldSlug).Move {
writeGQLError(w, "UNAUTHORIZED")
return
}
if dst := s.access(sess, newSlug); !(dst.Edit || dst.Create) {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
store := s.store
repo := s.gitRepo
@@ -1864,6 +2018,11 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
return
}
if p := s.access(sess, slug); !(p.Edit || p.Create) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
file, header, err := r.FormFile("image")
if err != nil {
http.Error(w, "Missing image", http.StatusBadRequest)
@@ -1922,7 +2081,6 @@ func (s *Server) handleFolders(w http.ResponseWriter, sess *auth.Session) {
s.mu.RLock()
store := s.store
database := s.database
s.mu.RUnlock()
if store == nil {
@@ -1937,11 +2095,12 @@ func (s *Server) handleFolders(w http.ResponseWriter, sess *auth.Session) {
return
}
// Guest users may only see folders they have been granted view access to.
if sess.Role == "guest" && database != nil {
// Non-admins only see folders they may view/read/search into.
if sess.Role != "admin" {
visible := folders[:0]
for _, f := range folders {
if database.CanUserViewPath(sess.Username, f) {
p := s.access(sess, f)
if p.View || p.Read || p.Search {
visible = append(visible, f)
}
}
@@ -1968,6 +2127,11 @@ func (s *Server) handleImages(w http.ResponseWriter, req gqlRequest, sess *auth.
return
}
if !s.access(sess, slug).Read {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
store := s.store
s.mu.RUnlock()
@@ -2000,6 +2164,11 @@ func (s *Server) handleDeleteImage(w http.ResponseWriter, req gqlRequest, sess *
return
}
if !s.access(sess, slug).Edit {
writeGQLError(w, "UNAUTHORIZED")
return
}
s.mu.RLock()
store := s.store
s.mu.RUnlock()
@@ -2017,3 +2186,359 @@ func (s *Server) handleDeleteImage(w http.ResponseWriter, req gqlRequest, sess *
log.Printf("[storage] deleted image %q from %q by %s", filename, slug, sess.Username)
writeJSON(w, `{"data":{"deleteImage":true}}`)
}
// ── OIDC HTTP endpoints ─────────────────────────────────────────────────────────
func (s *Server) handleOIDCLogin(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
provider := s.oidc
s.mu.RUnlock()
if provider == nil || !provider.Enabled() {
http.Error(w, "OIDC sign-in is not configured", http.StatusServiceUnavailable)
return
}
authURL, err := provider.AuthURL()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
http.Redirect(w, r, authURL, http.StatusFound)
}
func (s *Server) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
provider := s.oidc
database := s.database
mgr := s.authMgr
s.mu.RUnlock()
if provider == nil || database == nil || mgr == nil {
s.redirectLoginError(w, r, "server not ready")
return
}
q := r.URL.Query()
if e := q.Get("error"); e != "" {
desc := q.Get("error_description")
if desc == "" {
desc = e
}
s.redirectLoginError(w, r, desc)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
oidcUser, err := provider.Exchange(ctx, q.Get("state"), q.Get("code"))
if err != nil {
log.Printf("[oidc] token exchange failed: %v", err)
s.redirectLoginError(w, r, "sign-in failed")
return
}
token, role, err := mgr.LoginOIDC(database, oidcUser)
if err != nil {
log.Printf("[oidc] login denied for %q: %v", oidcUser.Username, err)
s.redirectLoginError(w, r, err.Error())
return
}
log.Printf("[oidc] login: %s (%s) groups=%v", oidcUser.Username, role, oidcUser.Groups)
// The SPA reads these from the URL fragment; the fragment is never sent to
// a server, so the token stays on the client (mirrors the localStorage model).
frag := fmt.Sprintf("#token=%s&username=%s&role=%s",
url.QueryEscape(token), url.QueryEscape(oidcUser.Username), url.QueryEscape(role))
http.Redirect(w, r, "/oidc/callback"+frag, http.StatusFound)
}
func (s *Server) redirectLoginError(w http.ResponseWriter, r *http.Request, msg string) {
http.Redirect(w, r, "/oidc/callback#error="+url.QueryEscape(msg), http.StatusFound)
}
// ── Login options (public) ───────────────────────────────────────────────────────
func (s *Server) handleLoginOptions(w http.ResponseWriter) {
s.mu.RLock()
provider := s.oidc
database := s.database
s.mu.RUnlock()
oidcEnabled := provider != nil && provider.Enabled()
label := "Sign in with Authentik"
publicEnabled := false
if database != nil {
if _, err := database.GetUser("guest"); err == nil {
publicEnabled = true
}
}
writeJSONObj(w, map[string]interface{}{
"data": map[string]interface{}{
"loginOptions": map[string]interface{}{
"localEnabled": true,
"oidcEnabled": oidcEnabled,
"oidcButtonLabel": label,
"publicEnabled": publicEnabled,
},
},
})
}
// ── Admin helpers ─────────────────────────────────────────────────────────────
// requireAdmin writes an UNAUTHORIZED error and returns false if the session
// is missing or not an administrator.
func (s *Server) requireAdmin(w http.ResponseWriter, sess *auth.Session) bool {
if sess == nil || sess.Role != "admin" {
writeGQLError(w, "UNAUTHORIZED")
return false
}
return true
}
func (s *Server) db() *db.DB {
s.mu.RLock()
defer s.mu.RUnlock()
return s.database
}
// ── OIDC config (admin) ────────────────────────────────────────────────────────
func (s *Server) handleOidcConfig(w http.ResponseWriter, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
s.mu.RLock()
cfg := s.cfg
provider := s.oidc
s.mu.RUnlock()
if cfg == nil {
writeGQLError(w, "server not initialised")
return
}
oc := cfg.OIDC
oc.Normalize()
writeJSONObj(w, map[string]interface{}{
"data": map[string]interface{}{
"oidcConfig": map[string]interface{}{
"enabled": oc.Enabled,
"ready": provider != nil && provider.Enabled(),
"issuer": oc.Issuer,
"clientId": oc.ClientID,
"clientSecretSet": oc.ClientSecret != "",
"redirectUrl": cfg.ResolvedRedirectURL(),
"publicUrl": cfg.PublicURL,
"groupsClaim": oc.GroupsClaim,
"usernameClaim": oc.UsernameClaim,
"adminGroup": oc.AdminGroup,
"readerGroup": oc.ReaderGroup,
},
},
})
}
func (s *Server) handleUpdateOidcConfig(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
input, ok := req.Variables["input"].(map[string]interface{})
if !ok {
input, _ = req.Variables["i"].(map[string]interface{})
}
if input == nil {
writeGQLError(w, "missing input")
return
}
s.mu.RLock()
cfg := s.cfg
s.mu.RUnlock()
if cfg == nil {
writeGQLError(w, "server not initialised")
return
}
newCfg := *cfg
oc := config.OIDCConfig{
Enabled: boolVal(input, "enabled"),
Issuer: strings.TrimSpace(strVal(input, "issuer")),
ClientID: strings.TrimSpace(strVal(input, "clientId")),
ClientSecret: strVal(input, "clientSecret"),
RedirectURL: strings.TrimSpace(strVal(input, "redirectUrl")),
GroupsClaim: strVal(input, "groupsClaim"),
UsernameClaim: strVal(input, "usernameClaim"),
AdminGroup: strVal(input, "adminGroup"),
ReaderGroup: strVal(input, "readerGroup"),
}
// Empty client secret means "keep existing".
if oc.ClientSecret == "" {
oc.ClientSecret = cfg.OIDC.ClientSecret
}
oc.Normalize()
newCfg.OIDC = oc
if pu := strings.TrimSpace(strVal(input, "publicUrl")); pu != "" {
newCfg.PublicURL = pu
}
if err := config.Save(s.configPath, &newCfg); err != nil {
writeGQLError(w, fmt.Sprintf("failed to save config: %v", err))
return
}
s.mu.Lock()
s.cfg = &newCfg
mgr := s.authMgr
s.mu.Unlock()
if mgr != nil {
mgr.UpdateConfig(&newCfg)
}
s.configureOIDC(&newCfg)
log.Printf("[admin] OIDC config updated by %s (enabled=%v)", sess.Username, oc.Enabled)
writeJSON(w, `{"data":{"updateOidcConfig":true}}`)
}
// ── Group management (admin) ─────────────────────────────────────────────────────
func (s *Server) handleCreateGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
name := strings.TrimSpace(strVal(req.Variables, "name"))
if name == "" {
writeGQLError(w, "group name is required")
return
}
if err := s.db().CreateOrUpdateGroup(name, false); err != nil {
writeGQLError(w, err.Error())
return
}
log.Printf("[admin] group created: %s by %s", name, sess.Username)
writeJSON(w, `{"data":{"createGroup":true}}`)
}
func (s *Server) handleDeleteGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
name := strVal(req.Variables, "name")
if name == db.GroupAdmin || name == db.GroupReader {
writeGQLError(w, "built-in role groups cannot be deleted")
return
}
if err := s.db().DeleteGroup(name); err != nil {
writeGQLError(w, err.Error())
return
}
log.Printf("[admin] group deleted: %s by %s", name, sess.Username)
writeJSON(w, `{"data":{"deleteGroup":true}}`)
}
func (s *Server) handleAddUserToGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
username := strVal(req.Variables, "username")
group := strVal(req.Variables, "group")
if err := s.db().AddUserToGroup(username, group); err != nil {
writeGQLError(w, err.Error())
return
}
writeJSON(w, `{"data":{"addUserToGroup":true}}`)
}
func (s *Server) handleRemoveUserFromGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
username := strVal(req.Variables, "username")
group := strVal(req.Variables, "group")
if err := s.db().RemoveUserFromGroup(username, group); err != nil {
writeGQLError(w, err.Error())
return
}
writeJSON(w, `{"data":{"removeUserFromGroup":true}}`)
}
func (s *Server) handleUserGroups(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
username := strVal(req.Variables, "username")
names, err := s.db().GetUserGroupNames(username)
if err != nil {
writeGQLError(w, err.Error())
return
}
if names == nil {
names = []string{}
}
writeJSONObj(w, map[string]interface{}{
"data": map[string]interface{}{"userGroups": names},
})
}
func (s *Server) handleSetUserLogin(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
username := strVal(req.Variables, "username")
allow := boolVal(req.Variables, "allow")
if err := s.db().SetUserLogin(username, allow); err != nil {
writeGQLError(w, err.Error())
return
}
log.Printf("[admin] user %q login set to %v by %s", username, allow, sess.Username)
writeJSON(w, `{"data":{"setUserLogin":true}}`)
}
func (s *Server) handleSetGroupLogin(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
name := strVal(req.Variables, "name")
allow := boolVal(req.Variables, "allow")
if err := s.db().SetGroupLogin(name, allow); err != nil {
writeGQLError(w, err.Error())
return
}
log.Printf("[admin] group %q login set to %v by %s", name, allow, sess.Username)
writeJSON(w, `{"data":{"setGroupLogin":true}}`)
}
func (s *Server) handleSetUserRole(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
if !s.requireAdmin(w, sess) {
return
}
username := strVal(req.Variables, "username")
role := strVal(req.Variables, "role")
if role != "admin" && role != "user" {
writeGQLError(w, "role must be 'admin' or 'user'")
return
}
if username == "guest" {
writeGQLError(w, "cannot change the public user's role")
return
}
if username == sess.Username && role != "admin" {
writeGQLError(w, "cannot remove your own admin role")
return
}
if err := s.db().SetUserRole(username, role); err != nil {
writeGQLError(w, err.Error())
return
}
log.Printf("[admin] user %q role set to %s by %s", username, role, sess.Username)
writeJSON(w, `{"data":{"setUserRole":true}}`)
}
func boolVal(m map[string]interface{}, key string) bool {
if m == nil {
return false
}
b, _ := m[key].(bool)
return b
}