feat: RBAC with Authelia groups + filtered launcher + admin panel

This commit is contained in:
Claus Lohmar 2026-07-08 13:46:02 +01:00
parent 7927addcf7
commit 594683dbf8
5 changed files with 329 additions and 92 deletions

View file

@ -21,8 +21,78 @@ totp:
access_control: access_control:
default_policy: deny default_policy: deny
rules: rules:
# Auth and public pages — no auth required
- domain: "auth.{DOMAIN}" - domain: "auth.{DOMAIN}"
policy: bypass policy: bypass
- domain: "www.{DOMAIN}"
policy: bypass
# Admin panel — admins only
- domain: "app.{DOMAIN}"
resources:
- "^/config(/.*)?$"
subject:
- "group:admins"
policy: one_factor
# App paths — group-restricted
- domain: "app.{DOMAIN}"
resources:
- "^/drive(/.*)?$"
subject:
- "group:admins"
- "group:drive"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/office(/.*)?$"
subject:
- "group:admins"
- "group:office"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/enterprise(/.*)?$"
subject:
- "group:admins"
- "group:erp"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/chat(/.*)?$"
subject:
- "group:admins"
- "group:chat"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/meet(/.*)?$"
subject:
- "group:admins"
- "group:meet"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/connect(/.*)?$"
subject:
- "group:admins"
- "group:mail"
policy: one_factor
- domain: "app.{DOMAIN}"
resources:
- "^/aida(/.*)?$"
subject:
- "group:admins"
- "group:ai"
policy: one_factor
# Home/launcher — any authenticated user
- domain: "app.{DOMAIN}" - domain: "app.{DOMAIN}"
policy: one_factor policy: one_factor

View file

@ -6,3 +6,11 @@ users:
email: "{TLS_EMAIL}" email: "{TLS_EMAIL}"
groups: groups:
- admins - admins
- users
- drive
- office
- erp
- chat
- meet
- mail
- ai

View file

@ -138,6 +138,12 @@ if [ "$GREENFIELD" = true ]; then
# Copy apps.yaml template # Copy apps.yaml template
cp "$SCRIPT_DIR/config/nextworkspace/apps.yaml" "$TARGET_DIR/config/nextworkspace/apps.yaml" 2>/dev/null || true cp "$SCRIPT_DIR/config/nextworkspace/apps.yaml" "$TARGET_DIR/config/nextworkspace/apps.yaml" 2>/dev/null || true
# Extract Authelia secret for binary
AUTHELIA_SECRET=$(grep -oP 'session_secret: \K.*' "$TARGET_DIR/config/authelia/configuration.yml" 2>/dev/null || echo "")
if [ -n "$AUTHELIA_SECRET" ]; then
echo "AUTHELIA_SECRET=$AUTHELIA_SECRET" >> "$BACKUP_DIR/.env"
fi
# Write systemd service # Write systemd service
cat > /etc/systemd/system/$SERVICE_NAME.service <<UNIT cat > /etc/systemd/system/$SERVICE_NAME.service <<UNIT
[Unit] [Unit]

295
main.go
View file

@ -1,8 +1,10 @@
package main package main
import ( import (
"bytes"
"fmt" "fmt"
"html/template" "html/template"
"io"
"log" "log"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
@ -32,11 +34,12 @@ type Config struct {
} }
type AppEntry struct { type AppEntry struct {
Name string `yaml:"name"` Name string `yaml:"name"`
Subtitle string `yaml:"subtitle"` Subtitle string `yaml:"subtitle"`
Path string `yaml:"path"` Path string `yaml:"path"`
Upstream string `yaml:"upstream"` Upstream string `yaml:"upstream"`
Icon string `yaml:"icon"` Icon string `yaml:"icon"`
Groups []string `yaml:"groups"`
} }
type AppsFile struct { type AppsFile struct {
@ -74,6 +77,19 @@ func loadApps(configDir string) ([]AppEntry, error) {
return appsFile.Apps, nil return appsFile.Apps, nil
} }
// --- Helpers ---
func userHasAnyGroup(userGroups []string, requiredGroups []string) bool {
for _, ug := range userGroups {
for _, rg := range requiredGroups {
if strings.TrimSpace(ug) == rg {
return true
}
}
}
return false
}
// --- Auth middleware (trusts Remote-User from Caddy forward auth) --- // --- Auth middleware (trusts Remote-User from Caddy forward auth) ---
func authMiddleware(next http.HandlerFunc) http.HandlerFunc { func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
@ -88,6 +104,17 @@ func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
} }
} }
func adminGroupMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
groups := r.Header.Get("Remote-Groups")
if !strings.Contains(groups, "admins") {
http.Error(w, "Forbidden — admins only", http.StatusForbidden)
return
}
next(w, r)
}
}
// --- Handlers --- // --- Handlers ---
func healthHandler(w http.ResponseWriter, r *http.Request) { func healthHandler(w http.ResponseWriter, r *http.Request) {
@ -100,16 +127,28 @@ func launcherHandler(cfg *Config, apps []AppEntry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("Remote-User") user := r.Header.Get("Remote-User")
groupsHeader := r.Header.Get("Remote-Groups")
userGroups := strings.Split(groupsHeader, ",")
var allowedApps []AppEntry
for _, app := range apps {
if len(app.Groups) == 0 || userHasAnyGroup(userGroups, app.Groups) {
allowedApps = append(allowedApps, app)
}
}
data := struct { data := struct {
AppName string AppName string
Description string Description string
User string User string
IsAdmin bool
Apps []AppEntry Apps []AppEntry
}{ }{
AppName: cfg.App.Name, AppName: cfg.App.Name,
Description: cfg.App.Description, Description: cfg.App.Description,
User: user, User: user,
Apps: apps, IsAdmin: strings.Contains(groupsHeader, "admins"),
Apps: allowedApps,
} }
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, data) tmpl.Execute(w, data)
@ -128,6 +167,58 @@ func proxyToUpstream(upstream string) http.HandlerFunc {
} }
} }
func adminHandler(w http.ResponseWriter, r *http.Request) {
apiBase := "http://127.0.0.1:8080"
apiToken := os.Getenv("AUTHELIA_SECRET")
switch r.Method {
case http.MethodGet:
// List users from authelia-api
req, _ := http.NewRequest("GET", apiBase+"/api/users", nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
tmpl := template.Must(template.New("admin").Parse(adminHTML))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, map[string]interface{}{
"Users": string(body),
"ApiError": resp.StatusCode != 200,
})
case http.MethodPost:
// Create user
body, _ := io.ReadAll(r.Body)
req, _ := http.NewRequest("POST", apiBase+"/api/users/bulk", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
case http.MethodDelete:
username := r.URL.Query().Get("username")
req, _ := http.NewRequest("DELETE", apiBase+"/api/users/"+username, nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
}
// --- Templates --- // --- Templates ---
const landingPageHTML = `<!DOCTYPE html> const landingPageHTML = `<!DOCTYPE html>
@ -135,7 +226,7 @@ const landingPageHTML = `<!DOCTYPE html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NextWorkspace Your Self-Hosted Workspace for Startups</title> <title>NextWorkspace</title>
<style> <style>
* { margin: 0; padding: 0; box-sizing: border-box; } * { margin: 0; padding: 0; box-sizing: border-box; }
body { body {
@ -144,44 +235,19 @@ const landingPageHTML = `<!DOCTYPE html>
color: #1a1a2e; color: #1a1a2e;
min-height: 100vh; min-height: 100vh;
} }
header { header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 3rem 2rem; text-align: center; }
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
color: #fff;
padding: 3rem 2rem;
text-align: center;
}
header h1 { font-size: 2.5rem; margin-bottom: 0.5rem; } header h1 { font-size: 2.5rem; margin-bottom: 0.5rem; }
header p { color: #a0aec0; font-size: 1.2rem; } header p { color: #a0aec0; font-size: 1.2rem; }
.domain { color: #63b3ed; font-size: 0.9rem; margin-top: 0.5rem; } .domain { color: #63b3ed; font-size: 0.9rem; margin-top: 0.5rem; }
.container { max-width: 800px; margin: 0 auto; padding: 2rem; } .container { max-width: 800px; margin: 0 auto; padding: 2rem; }
h2 { font-size: 1.5rem; margin: 2rem 0 1rem; color: #2d3748; } h2 { font-size: 1.5rem; margin: 2rem 0 1rem; color: #2d3748; }
ul { list-style: none; padding: 0; } ul { list-style: none; padding: 0; }
li { li { background: #fff; border-radius: 8px; padding: 1rem 1.25rem; margin-bottom: 0.75rem; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
background: #fff; li a { color: #1a1a2e; text-decoration: none; font-weight: 600; }
border-radius: 8px;
padding: 1rem 1.25rem;
margin-bottom: 0.75rem;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
li a { color: #1a1a2e; text-decoration: none; font-weight: 600; font-size: 1.05rem; }
li a:hover { color: #63b3ed; } li a:hover { color: #63b3ed; }
li span { color: #718096; font-size: 0.9rem; margin-left: 0.5rem; } li span { color: #718096; font-size: 0.9rem; margin-left: 0.5rem; }
.ai-credit { .ai-credit { background: #edf2f7; border-radius: 8px; padding: 1.5rem; margin-top: 2rem; text-align: center; font-size: 0.9rem; color: #4a5568; }
background: #edf2f7; footer { text-align: center; padding: 2rem; color: #a0aec0; font-size: 0.85rem; }
border-radius: 8px;
padding: 1.5rem;
margin-top: 2rem;
text-align: center;
font-size: 0.9rem;
color: #4a5568;
}
.ai-credit strong { color: #1a1a2e; }
footer {
text-align: center;
padding: 2rem;
color: #a0aec0;
font-size: 0.85rem;
}
</style> </style>
</head> </head>
<body> <body>
@ -207,9 +273,7 @@ const landingPageHTML = `<!DOCTYPE html>
<p>NextWorkspace was developed with assistance from AI coding tools, using <strong>DeepSeek</strong> as the provider and <strong>OpenCode</strong> as the development framework.</p> <p>NextWorkspace was developed with assistance from AI coding tools, using <strong>DeepSeek</strong> as the provider and <strong>OpenCode</strong> as the development framework.</p>
</div> </div>
</div> </div>
<footer> <footer>&copy; 2026 NextWorkspace &mdash; nextwks.eu</footer>
&copy; 2026 NextWorkspace &mdash; nextwks.eu
</footer>
</body> </body>
</html>` </html>`
@ -227,57 +291,16 @@ const launcherHTML = `<!DOCTYPE html>
color: #1a1a2e; color: #1a1a2e;
min-height: 100vh; min-height: 100vh;
} }
header { header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 2rem; text-align: center; }
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
color: #fff;
padding: 2rem;
text-align: center;
}
header h1 { font-size: 2rem; margin-bottom: 0.25rem; } header h1 { font-size: 2rem; margin-bottom: 0.25rem; }
header p { color: #a0aec0; font-size: 1rem; } header p { color: #a0aec0; font-size: 1rem; }
.user-banner { .user-banner { background: #2d3748; color: #e2e8f0; padding: 0.75rem 2rem; text-align: center; font-size: 0.9rem; display: flex; justify-content: center; gap: 1rem; }
background: #2d3748; .user-banner a { color: #63b3ed; text-decoration: none; }
color: #e2e8f0;
padding: 0.75rem 2rem;
text-align: center;
font-size: 0.9rem;
}
.user-banner a { color: #63b3ed; text-decoration: none; margin-left: 0.5rem; }
.user-banner a:hover { text-decoration: underline; } .user-banner a:hover { text-decoration: underline; }
.grid { .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 1.5rem; padding: 2rem; max-width: 1200px; margin: 0 auto; }
display: grid; .card { background: #fff; border-radius: 12px; padding: 1.5rem; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.08); transition: transform 0.2s; text-decoration: none; color: inherit; display: block; }
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); .card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
gap: 1.5rem; .icon { width: 48px; height: 48px; margin: 0 auto 1rem; background: #edf2f7; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
.card {
background: #fff;
border-radius: 12px;
padding: 1.5rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
transition: transform 0.2s, box-shadow 0.2s;
text-decoration: none;
color: inherit;
display: block;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
.icon {
width: 48px;
height: 48px;
margin: 0 auto 1rem;
background: #edf2f7;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
}
.card h3 { font-size: 1.1rem; margin-bottom: 0.25rem; } .card h3 { font-size: 1.1rem; margin-bottom: 0.25rem; }
.card p { color: #718096; font-size: 0.85rem; } .card p { color: #718096; font-size: 0.85rem; }
</style> </style>
@ -288,7 +311,9 @@ const launcherHTML = `<!DOCTYPE html>
<p>{{.Description}}</p> <p>{{.Description}}</p>
</header> </header>
<div class="user-banner"> <div class="user-banner">
Welcome, {{.User}} &middot; <a href="https://auth.nextwks.eu/logout">Logout</a> <span>Welcome, {{.User}}</span>
{{if .IsAdmin}}<a href="/config">Admin Panel</a>{{end}}
<a href="https://auth.nextwks.eu/logout">Logout</a>
</div> </div>
<div class="grid"> <div class="grid">
{{range .Apps}} {{range .Apps}}
@ -306,6 +331,88 @@ const launcherHTML = `<!DOCTYPE html>
</body> </body>
</html>` </html>`
const adminHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Panel NextWorkspace</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f0f2f5; color: #1a1a2e; }
header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 1.5rem 2rem; display: flex; justify-content: space-between; align-items: center; }
header h1 { font-size: 1.5rem; }
header a { color: #63b3ed; text-decoration: none; font-size: 0.9rem; }
.container { max-width: 1000px; margin: 0 auto; padding: 2rem; }
.card { background: #fff; border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
h2 { font-size: 1.2rem; margin-bottom: 1rem; color: #2d3748; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 0.6rem 0.5rem; border-bottom: 1px solid #e2e8f0; font-size: 0.9rem; }
th { color: #718096; font-weight: 600; }
.btn { display: inline-block; padding: 0.4rem 0.8rem; border-radius: 4px; text-decoration: none; font-size: 0.85rem; cursor: pointer; border: none; }
.btn-danger { background: #fc8181; color: #fff; }
.btn-primary { background: #1a1a2e; color: #fff; }
.btn-primary:hover { background: #2d3748; }
input, select { padding: 0.4rem 0.6rem; border: 1px solid #e2e8f0; border-radius: 4px; font-size: 0.9rem; margin-right: 0.5rem; }
.form-row { display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap; margin-bottom: 1rem; }
.error { background: #fed7d7; color: #c53030; padding: 0.75rem; border-radius: 6px; margin-bottom: 1rem; }
</style>
</head>
<body>
<header>
<h1>Admin Panel</h1>
<a href="/home/">Back to Launcher</a>
</header>
<div class="container">
{{if .ApiError}}<div class="error">Could not fetch users from authelia-api (is it running on :8080?)</div>{{end}}
<div class="card">
<h2>Create User</h2>
<form id="createForm" onsubmit="createUser(event)">
<div class="form-row">
<input name="username" placeholder="Username" required>
<input name="display_name" placeholder="Display Name" required>
<input name="email" placeholder="Email" type="email" required>
<input name="password" placeholder="Password" type="password" required>
<select name="groups" multiple size="3">
<option value="users">users</option>
<option value="drive">drive</option>
<option value="office">office</option>
<option value="erp">erp</option>
<option value="chat">chat</option>
<option value="meet">meet</option>
<option value="mail">mail</option>
<option value="ai">ai</option>
</select>
<button type="submit" class="btn btn-primary">Create</button>
</div>
</form>
</div>
<div class="card">
<h2>Users</h2>
<pre>{{.Users}}</pre>
</div>
</div>
<script>
async function createUser(e) {
e.preventDefault();
const form = e.target;
const data = Object.fromEntries(new FormData(form));
data.groups = Array.from(form.querySelector('[name=groups]').selectedOptions).map(o => o.value);
const resp = await fetch('/config', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({users: [data]})
});
if (resp.ok) { alert('User created'); location.reload(); }
else { alert('Error: ' + await resp.text()); }
}
</script>
</body>
</html>`
// --- Main --- // --- Main ---
func main() { func main() {
@ -328,23 +435,27 @@ func main() {
mux := http.NewServeMux() mux := http.NewServeMux()
// Public paths // Public
mux.HandleFunc("/health", healthHandler) mux.HandleFunc("/health", healthHandler)
// Protected: launcher // Protected: launcher
mux.Handle("/home/", authMiddleware(launcherHandler(cfg, apps))) mux.Handle("/home/", authMiddleware(launcherHandler(cfg, apps)))
mux.Handle("/home", authMiddleware(launcherHandler(cfg, apps))) mux.Handle("/home", authMiddleware(launcherHandler(cfg, apps)))
// Protected: admin — admins only
mux.Handle("/config", adminGroupMiddleware(authMiddleware(adminHandler)))
mux.Handle("/config/", adminGroupMiddleware(authMiddleware(adminHandler)))
// Protected: upstream app proxies // Protected: upstream app proxies
for _, app := range apps { for _, app := range apps {
if app.Path != "" && app.Upstream != "" { if app.Path != "" && app.Upstream != "" && app.Path != "/config" && app.Path != "/home" {
proxyHandler := authMiddleware(proxyToUpstream(app.Upstream)) proxyHandler := authMiddleware(proxyToUpstream(app.Upstream))
mux.Handle(app.Path+"/", proxyHandler) mux.Handle(app.Path+"/", proxyHandler)
mux.Handle(app.Path, proxyHandler) mux.Handle(app.Path, proxyHandler)
} }
} }
// Default: serve landing page for www, redirect to launcher otherwise // Default: www landing page or redirect to /home/
domain := os.Getenv("DOMAIN") domain := os.Getenv("DOMAIN")
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, "www.") || (domain != "" && r.Host == "www."+domain) { if strings.HasPrefix(r.Host, "www.") || (domain != "" && r.Host == "www."+domain) {

42
tools/manage-users.sh Normal file
View file

@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Manage users via authelia-api
# Usage: ./manage-users.sh list
# ./manage-users.sh create username displayname email groups...
# ./manage-users.sh delete username
API_BASE="http://127.0.0.1:8080"
TOKEN=$(grep -oP 'session_secret: \K.*' /opt/nextworkspace/config/authelia/configuration.yml)
case "${1:-}" in
list)
curl -s -H "Authorization: Bearer $TOKEN" "$API_BASE/api/users" | jq . 2>/dev/null || \
curl -s -H "Authorization: Bearer $TOKEN" "$API_BASE/api/users"
;;
create)
shift
if [ $# -lt 3 ]; then
echo "Usage: $0 create username displayname email [groups...]" >&2
exit 1
fi
USERNAME="$1"; DISPLAY="$2"; EMAIL="$3"; shift 3
GROUPS='["users"'
for g in "$@"; do GROUPS="$GROUPS,\"$g\""; done
GROUPS="$GROUPS]"
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"users\":[{\"username\":\"$USERNAME\",\"display_name\":\"$DISPLAY\",\"email\":\"$EMAIL\",\"groups\":$GROUPS}]}" \
"$API_BASE/api/users/bulk"
;;
delete)
if [ -z "${2:-}" ]; then
echo "Usage: $0 delete username" >&2
exit 1
fi
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
"$API_BASE/api/users/$2"
;;
*)
echo "Usage: $0 {list|create|delete} ..." >&2
exit 1
;;
esac