Learn AuthGuard/CarrierNode URLs from ProjectConfigurator's push
Lint / Lint (push) Successful in 39s
Tests / Go backend (push) Successful in 42s
Tests / Dashboard checks (push) Successful in 46s
Docker / Docker Build & Push (push) Successful in 3m37s

Adds the receiving end of ProjectConfigurator's core-services push
(PUT /api/core-services/internal, X-Internal-Auth-gated) via the shared
coreconfig package, so this service's AUTHGUARD_URL/CARRIERNODE_URL env
vars become just the bootstrap/fallback value instead of the permanent
source of truth. authclient.Client gains a concurrency-safe SetBaseURL
so a later push retargets it in place with no restart.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-10 11:56:17 +02:00
1 parent 20e9461d46
commit 7c4a903f59
7 files changed
+320 -8

No files matched your search

+5 -1
View File
@@ -34,12 +34,16 @@ CollabTable's browser dashboard authenticates through AuthGuard, a centralized i
`AUTHGUARD_URL` is optional: leaving it unset does not fall back to any local account store — it disables authentication entirely, treating every request as authenticated with nothing gated. Only run without it for local development or a deployment you are certain does not need access control. Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state. `AUTHGUARD_URL` is optional: leaving it unset does not fall back to any local account store — it disables authentication entirely, treating every request as authenticated with nothing gated. Only run without it for local development or a deployment you are certain does not need access control. Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
`AUTHGUARD_URL` and `CARRIERNODE_URL` are also only the bootstrap fallback: once CollabTable is registered in ProjectConfigurator's Projects workspace, ProjectConfigurator pushes both values here automatically (`PUT /api/core-services/internal`, `X-Internal-Auth`-gated with `INTERNAL_SERVICE_SECRET`) and keeps them current with no restart — see `Core/ProjectConfigurator/README.md`'s "Pushing core service info to other projects". CarrierNode isn't used by any feature here yet, but the client is wired and ready.
The device-sync API token (generated from the dashboard's Settings page, used by the Android app's `Authorization: Bearer` header for `/api/lists`, `/api/fields`, `/api/items`, `/api/sync`, and notification polling) is unrelated to AuthGuard and unaffected by whether it's configured: it's a long-lived per-account credential for a user's own devices, not a browser session, and stays entirely local to CollabTable's own Postgres. The device-sync API token (generated from the dashboard's Settings page, used by the Android app's `Authorization: Bearer` header for `/api/lists`, `/api/fields`, `/api/items`, `/api/sync`, and notification polling) is unrelated to AuthGuard and unaffected by whether it's configured: it's a long-lived per-account credential for a user's own devices, not a browser session, and stays entirely local to CollabTable's own Postgres.
| Variable | Required | Default | Description | | Variable | Required | Default | Description |
|----------|----------|---------|--------------| |----------|----------|---------|--------------|
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) | | `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
| `AUTHGUARD_URL` | No | unset (auth disabled) | Base URL of the AuthGuard identity service. Leaving it unset disables authentication entirely rather than falling back to local auth. | | `AUTHGUARD_URL` | No | unset (auth disabled) | Base URL of the AuthGuard identity service. Leaving it unset disables authentication entirely rather than falling back to local auth. Bootstrap fallback only — see below. |
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
| `INTERNAL_SERVICE_SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. |
| `PORT` | No | `8080` | HTTP listen port | | `PORT` | No | `8080` | HTTP listen port |
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page | | `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` | | `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
+14
View File
@@ -18,6 +18,20 @@ COOKIE_SECURE=false
# Only run without it for local development or a deployment you are certain # Only run without it for local development or a deployment you are certain
# does not need access control. # does not need access control.
# Base URL of a CarrierNode instance, for the generic per-project mount API
# (not used by any feature here yet).
# CARRIERNODE_URL=https://carrier.example.com
# Shared secret CarrierNode and ProjectConfigurator were also configured with,
# sent/checked as X-Internal-Auth. AUTHGUARD_URL and CARRIERNODE_URL above are
# only the bootstrap fallback: once this project is registered in
# ProjectConfigurator's Projects workspace, it pushes both values here
# automatically (PUT /api/core-services/internal) and keeps them current --
# see Core/ProjectConfigurator/README.md's "Pushing core service info to
# other projects". That push is itself authenticated with this secret, so it
# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't.
# INTERNAL_SERVICE_SECRET=
################################################################# #################################################################
# PostgreSQL configuration # PostgreSQL configuration
################################################################# #################################################################
+34 -1
View File
@@ -17,6 +17,8 @@ import (
_ "github.com/joho/godotenv/autoload" _ "github.com/joho/godotenv/autoload"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
) )
// The SvelteKit build is copied here by the Docker builder before go build. // The SvelteKit build is copied here by the Docker builder before go build.
@@ -30,6 +32,9 @@ type Server struct {
db *DB db *DB
auth *AuthService auth *AuthService
startTime time.Time startTime time.Time
internalServiceSecret string
coreConfig *coreconfig.Store
carrierNode *carriernodeclient.Client
} }
func main() { func main() {
@@ -65,8 +70,33 @@ func main() {
fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated") fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated")
} }
// coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project
// is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and
// CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives.
// See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects".
internalServiceSecret := strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET"))
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
if authGuard != nil {
coreConfig.OnUpdate(func(info coreconfig.Info) {
if info.AuthGuardURL != "" {
authGuard.SetBaseURL(info.AuthGuardURL)
}
})
}
carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string {
return coreConfig.CarrierNodeURL()
})
auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true")) auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
server := &Server{db: database, auth: auth, startTime: time.Now()} server := &Server{
db: database,
auth: auth,
startTime: time.Now(),
internalServiceSecret: internalServiceSecret,
coreConfig: coreConfig,
carrierNode: carrierNode,
}
webRoot, err := fs.Sub(webFS, "web") webRoot, err := fs.Sub(webFS, "web")
if err != nil { if err != nil {
@@ -132,6 +162,9 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// Health and auth bootstrap routes are intentionally public. // Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth) mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/info", s.handleInfo) mux.HandleFunc("GET /api/info", s.handleInfo)
// X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus) mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup) mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin) mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
+43 -6
View File
@@ -23,6 +23,7 @@ import (
"net" "net"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -48,8 +49,12 @@ const DefaultCookieName = "auth_session"
// Client calls a centralized AuthServer instance over HTTP. // Client calls a centralized AuthServer instance over HTTP.
type Client struct { type Client struct {
// BaseURL is AuthServer's base URL, e.g. "https://auth.example.com" // baseURLMu guards baseURL so SetBaseURL can be called concurrently with
// (no trailing slash required). // Validate/Middleware/the rest of the API surface - see SetBaseURL.
baseURLMu sync.RWMutex
// baseURL is AuthServer's base URL, e.g. "https://auth.example.com" (no
// trailing slash required). Read/written only through getBaseURL/
// SetBaseURL once construction is done.
baseURL string baseURL string
// HTTPClient is used for every request; defaults to a client with a // HTTPClient is used for every request; defaults to a client with a
// short timeout suitable for a per-request auth check. // short timeout suitable for a per-request auth check.
@@ -95,6 +100,30 @@ func New(baseURL string, opts ...Option) *Client {
return c return c
} }
// SetBaseURL atomically replaces the AuthServer base URL this Client calls,
// normalizing it the same way New does. Safe to call concurrently with
// Validate/Middleware/any other method on this Client - the intended use is
// a service wiring this up as a coreconfig.Store's OnUpdate callback, so a
// fresh authguard_url pushed from ProjectConfigurator takes effect on this
// Client's very next call with no restart. A blank baseURL is ignored
// (leaving the previous value in place) rather than leaving the client
// unable to reach AuthServer at all.
func (c *Client) SetBaseURL(baseURL string) {
normalized := normalizeBaseURL(baseURL)
if normalized == "" {
return
}
c.baseURLMu.Lock()
c.baseURL = normalized
c.baseURLMu.Unlock()
}
func (c *Client) getBaseURL() string {
c.baseURLMu.RLock()
defer c.baseURLMu.RUnlock()
return c.baseURL
}
func normalizeBaseURL(baseURL string) string { func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/") trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" { if trimmed == "" {
@@ -140,7 +169,11 @@ func isPrivateHost(hostport string) bool {
// ErrInvalidSession (wrapped) when AuthServer reports the session as not // ErrInvalidSession (wrapped) when AuthServer reports the session as not
// valid, and a plain error for any transport/decoding failure. // valid, and a plain error for any transport/decoding failure.
func (c *Client) Validate(ctx context.Context, token string) (*User, error) { func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
if c == nil || c.baseURL == "" { if c == nil {
return nil, errors.New("authclient: client has no base URL")
}
baseURL := c.getBaseURL()
if baseURL == "" {
return nil, errors.New("authclient: client has no base URL") return nil, errors.New("authclient: client has no base URL")
} }
token = strings.TrimSpace(token) token = strings.TrimSpace(token)
@@ -148,7 +181,7 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
return nil, ErrInvalidSession return nil, ErrInvalidSession
} }
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("authclient: build request: %w", err) return nil, fmt.Errorf("authclient: build request: %w", err)
} }
@@ -359,7 +392,11 @@ func ForwardCookies(w http.ResponseWriter, cookies []*http.Cookie) {
// on a transport-level failure) is provided so callers can read Cookies(); // on a transport-level failure) is provided so callers can read Cookies();
// its Body is always already fully read and closed. // its Body is always already fully read and closed.
func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) { func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) {
if c == nil || c.baseURL == "" { if c == nil {
return nil, errors.New("authclient: client has no base URL")
}
baseURL := c.getBaseURL()
if baseURL == "" {
return nil, errors.New("authclient: client has no base URL") return nil, errors.New("authclient: client has no base URL")
} }
@@ -371,7 +408,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
} }
reader = bytes.NewReader(data) reader = bytes.NewReader(data)
} }
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader) req, err := http.NewRequestWithContext(ctx, method, baseURL+path, reader)
if err != nil { if err != nil {
return nil, fmt.Errorf("authclient: build request: %w", err) return nil, fmt.Errorf("authclient: build request: %w", err)
} }
+27
View File
@@ -83,3 +83,30 @@ func TestSetupStatusPropagatesTransportError(t *testing.T) {
t.Fatal("SetupStatus() expected an error against an unreachable server, got nil") t.Fatal("SetupStatus() expected an error against an unreachable server, got nil")
} }
} }
func TestSetBaseURLRetargetsSubsequentCalls(t *testing.T) {
client := New("http://127.0.0.1:0")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]bool{"setup_required": true})
}))
defer server.Close()
client.SetBaseURL(server.URL)
got, err := client.SetupStatus(context.Background())
if err != nil {
t.Fatalf("SetupStatus() after SetBaseURL error = %v", err)
}
if !got {
t.Fatalf("SetupStatus() = %v, want true", got)
}
}
func TestSetBaseURLIgnoresBlank(t *testing.T) {
client := New("https://auth.example.com")
client.SetBaseURL(" ")
if got := client.getBaseURL(); got != "https://auth.example.com" {
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
}
}
+114
View File
@@ -0,0 +1,114 @@
// Package coreconfig lets any service in this workspace receive AuthGuard's and CarrierNode's
// current base URLs pushed from ProjectConfigurator, instead of each service hardcoding them in
// its own env vars. ProjectConfigurator's Projects workspace is the operator-facing source of
// truth for both (its authguard_url/carriernode_url settings); it pushes a fresh copy to every
// project it has registered whenever either changes, and again on a periodic tick, so a service
// that restarted (and lost its in-memory copy) converges again within a couple of minutes with no
// manual step. See ProjectConfigurator/README.md's "Pushing core service info to other projects"
// section for the wire contract this package implements both ends of (Store/Handler on the
// receiving side; ProjectConfigurator's own settings.go on the sending side).
package coreconfig
import (
"encoding/json"
"net/http"
"strings"
"sync"
)
// Info is AuthGuard's and CarrierNode's current base URL, as pushed by ProjectConfigurator.
type Info struct {
AuthGuardURL string `json:"authGuardUrl"`
CarrierNodeURL string `json:"carrierNodeUrl"`
}
// Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given
// (typically this service's own AUTHGUARD_URL/CARRIERNODE_URL env vars) until ProjectConfigurator's
// first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator
// instance at all, in which case those env vars keep working exactly as before.
type Store struct {
mu sync.RWMutex
info Info
onUpdate func(Info)
}
// NewStore returns a Store seeded with fallback.
func NewStore(fallback Info) *Store {
return &Store{info: fallback}
}
// Get returns the current Info.
func (s *Store) Get() Info {
s.mu.RLock()
defer s.mu.RUnlock()
return s.info
}
// AuthGuardURL is a convenience accessor for Get().AuthGuardURL - the natural value to feed an
// authclient.Client's SetBaseURL, or (via OnUpdate) to keep one continuously up to date.
func (s *Store) AuthGuardURL() string { return s.Get().AuthGuardURL }
// CarrierNodeURL is a convenience accessor for Get().CarrierNodeURL - the natural closure to wire
// as a carriernodeclient.Client's BaseURL: carriernodeclient.New(secret, func(ctx
// context.Context) string { return store.CarrierNodeURL() }).
func (s *Store) CarrierNodeURL() string { return s.Get().CarrierNodeURL }
// OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after
// every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through
// Store on every call. Only one callback is kept; a second registration replaces the first, which
// is enough for every current caller (one authclient.Client per service).
func (s *Store) OnUpdate(fn func(Info)) {
s.mu.Lock()
s.onUpdate = fn
s.mu.Unlock()
}
// Set replaces the current Info, field by field, ignoring a blank field so a partial push (e.g.
// only carrierNodeUrl changed) never clobbers the other value with an empty string.
func (s *Store) Set(next Info) {
s.mu.Lock()
if url := strings.TrimSpace(next.AuthGuardURL); url != "" {
s.info.AuthGuardURL = url
}
if url := strings.TrimSpace(next.CarrierNodeURL); url != "" {
s.info.CarrierNodeURL = url
}
current := s.info
callback := s.onUpdate
s.mu.Unlock()
if callback != nil {
callback(current)
}
}
// Handler is the X-Internal-Auth-gated PUT /api/core-services/internal endpoint
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see
// ProjectConfigurator/README.md) behind a secret check for this service's own
// INTERNAL_SERVICE_SECRET (the same value ProjectConfigurator and CarrierNode were configured
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's
// own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if secret == "" || r.Header.Get("X-Internal-Auth") != secret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
var input Info
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
store.Set(input)
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": store.Get()})
}
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
@@ -0,0 +1,83 @@
package coreconfig
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestStoreSetIgnoresBlankFields(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com"})
store.Set(Info{CarrierNodeURL: "http://carrier2.example.com"})
got := store.Get()
if got.AuthGuardURL != "http://auth.example.com" {
t.Fatalf("AuthGuardURL = %q, want unchanged", got.AuthGuardURL)
}
if got.CarrierNodeURL != "http://carrier2.example.com" {
t.Fatalf("CarrierNodeURL = %q, want updated", got.CarrierNodeURL)
}
}
func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) {
store := NewStore(Info{})
var got Info
calls := 0
store.OnUpdate(func(info Info) {
calls++
got = info
})
store.Set(Info{AuthGuardURL: "http://auth.example.com"})
if calls != 1 {
t.Fatalf("OnUpdate called %d times, want 1", calls)
}
if got.AuthGuardURL != "http://auth.example.com" {
t.Fatalf("OnUpdate saw AuthGuardURL = %q, want http://auth.example.com", got.AuthGuardURL)
}
}
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
cases := []string{"", "wrong"}
for _, header := range cases {
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
if header != "" {
req.Header.Set("X-Internal-Auth", header)
}
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401 for X-Internal-Auth=%q", rec.Code, header)
}
}
if got := store.Get(); got.AuthGuardURL != "" {
t.Fatalf("store was updated despite auth failure: %+v", got)
}
}
func TestHandlerAppliesPushedInfo(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com"})
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
}
got := store.Get()
if got.AuthGuardURL != "http://auth.example.com" || got.CarrierNodeURL != "http://carrier.example.com" {
t.Fatalf("store = %+v, want pushed values applied", got)
}
}