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

@@ -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
}