Files
Yggdrasil/cmd/server/main.go
T
Klagarge fc1b45058c feat: shiroa book, ACL parser, and OIDC-gated Go server
- docs/: shiroa book with three example categories (thermo, security,
  homelab); pages declare access via '#let access-groups = (...)'
- cmd/parser: scans docs/ and generates acl.json (public by default,
  skips book.typ/template.typ/partials)
- internal/acl: loads acl.json, normalizes URLs to page keys so a page's
  renderer data (*.multi.sir.in) inherits its protection; fail closed on
  malformed input
- internal/oidc: authorization-code flow client, verified ID tokens,
  groups claim from Authentik
- internal/middleware: in-memory sessions, login/logout/callback handlers,
  CSRF states, access gate + security headers
- cmd/server + embed.go: single binary embedding dist/ and acl.json;
  /searchindex.json blocked; graceful shutdown
- Justfile (build/run/parse/check/clean/preview-docs), Gitea Actions
  workflow (shiroa v0.4.0-rc2), rootless Dockerfile, README
- legacy docs moved to legacy_docs/; .idea untracked
2026-10-10 18:42:40 +02:00

121 lines
3.3 KiB
Go

// Command server is the Yggdrasil web server: a single static binary that
// embeds the compiled documentation (dist/) and its access control list
// (acl.json), serves public pages directly, and gates protected pages
// behind OIDC authentication (Authentik).
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Klagarge/yggdrasil"
"github.com/Klagarge/yggdrasil/internal/acl"
"github.com/Klagarge/yggdrasil/internal/middleware"
"github.com/Klagarge/yggdrasil/internal/oidc"
)
func main() {
listenAddr := envOr("LISTEN_ADDR", ":8080")
sessionTTL := envDuration("SESSION_TTL", 12*time.Hour)
cookieSecure := envOr("COOKIE_SECURE", "true") == "true"
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
list, err := acl.Load(yggdrasil.ACLData())
if err != nil {
log.Fatalf("refusing to start: %v", err) // fail closed
}
sessions := middleware.NewSessionStore(sessionTTL)
go sessions.StartJanitor(ctx, 10*time.Minute)
auth := setupOIDC(ctx)
dist, err := yggdrasil.DistFS()
if err != nil {
log.Fatalf("embedded dist: %v", err)
}
gate := middleware.NewAccessControl(list, sessions, auth, cookieSecure)
mux := http.NewServeMux()
mux.HandleFunc("GET /login", gate.Login)
mux.HandleFunc("GET /callback", gate.Callback)
mux.HandleFunc("GET /logout", gate.Logout)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
// The search index contains the text of protected pages: never serve it.
mux.HandleFunc("/searchindex.json", http.NotFound)
mux.Handle("/", gate.Wrap(http.FileServerFS(dist)))
srv := &http.Server{
Addr: listenAddr,
Handler: gate.SecurityHeaders(mux),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 2 * time.Minute,
}
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
log.Printf("listening on %s (%d protected pages)", listenAddr, len(list))
select {
case err := <-errCh:
if !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("shutdown: %v", err)
}
}
// setupOIDC builds the OIDC client from the environment. Without OIDC
// configuration the server still serves public pages; protected pages
// answer 503 instead of being exposed.
func setupOIDC(ctx context.Context) *oidc.Authenticator {
cfg, err := oidc.LoadConfigFromEnv()
if err != nil {
log.Printf("OIDC disabled (%v) - protected pages will answer 503", err)
return nil
}
auth, err := oidc.NewAuthenticator(ctx, cfg)
if err != nil {
log.Fatalf("OIDC setup: %v", err)
}
log.Printf("OIDC enabled (issuer: %s)", cfg.IssuerURL)
return auth
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func envDuration(key string, def time.Duration) time.Duration {
if v := os.Getenv(key); v != "" {
if d, err := time.ParseDuration(v); err == nil {
return d
}
log.Printf("invalid %s %q, using %s", key, v, def)
}
return def
}