// Package coreconfig lets any service in this workspace receive AuthGuard's, CarrierNode's, // ComfyUI's, and // ProjectConfigurator's current base URL(s) 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(_N) 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 ( "crypto/subtle" "encoding/json" "errors" "net/http" "net/url" "strings" "sync" "unicode/utf8" ) // MinInternalSecretLength is the shortest SECRET a service accepts for its internal routes. const MinInternalSecretLength = 16 // exampleInternalSecrets are the placeholders shipped in .env.example files, plus the bare variable // name. They are public, so they never gate a route. var exampleInternalSecrets = map[string]bool{ "SECRET": true, "change-me-to-a-long-random-value": true, } // InternalSecretUsable reports whether secret is strong enough to gate an internal route: at least // MinInternalSecretLength characters and not an example placeholder. Length counts characters, as // the Python and Node helpers do, not bytes. func InternalSecretUsable(secret string) bool { return utf8.RuneCountInString(secret) >= MinInternalSecretLength && !exampleInternalSecrets[secret] } // InternalSecretMatches reports whether presented is the configured secret. A secret that is not // usable (see InternalSecretUsable) never matches, and the comparison is constant-time. func InternalSecretMatches(presented, secret string) bool { if !InternalSecretUsable(secret) { return false } return subtle.ConstantTimeCompare([]byte(presented), []byte(secret)) == 1 } // Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by // ProjectConfigurator. type Info struct { AuthGuardURL string `json:"authGuardUrl"` // ComfyUIURL is the configured ComfyUI endpoint for services that use the // generator. It is optional so services that do not use ComfyUI can ignore it. ComfyUIURL string `json:"comfyUiUrl,omitempty"` // ProjectConfiguratorURL is the ProjectConfigurator instance that owns the current workspace // configuration. Consumers with independent databases can use it to read settings such as the // configured mount mappings. ProjectConfiguratorURL string `json:"projectConfiguratorUrl"` // ContentScannerURL and ContentScannerSecret let services with independent databases import // the scanner's successfully discovered media without connecting to its PostgreSQL database. ContentScannerURL string `json:"contentScannerUrl,omitempty"` ContentScannerSecret string `json:"contentScannerSecret,omitempty"` // CarrierNodeURL is the primary CarrierNode instance's URL (CarrierNodeURLs[0], if any) - kept // for the services that only ever talk to one CarrierNode instance via // carriernodeclient.New(secret, store.CarrierNodeURL). CarrierNodeURL string `json:"carrierNodeUrl"` // CarrierNodeURLs is every CarrierNode instance ProjectConfigurator has registered, in // priority order (the first entry is the same as CarrierNodeURL) - services that want to // discover files across every configured storage backend / fail over between replicas wire // this through carriernodeclient.NewMulti(secret, store.CarrierNodeURLs) instead. CarrierNodeURLs []string `json:"carrierNodeUrls"` // CarrierNodeSecret is the credential CarrierNode expects in X-Internal-Auth. // ProjectConfigurator includes it so consumers with independent databases can // authenticate storage requests without falling back to their own SECRET. CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"` // OmniLoggerURL is the OmniLogger instance that receives this service's log entries. Services // that ship logs use it with OmniLoggerIngestToken; both are optional, so a service that does not // ship logs ignores them. OmniLoggerURL string `json:"omniLoggerUrl,omitempty"` // OmniLoggerIngestToken is the ingest token ProjectConfigurator minted for this receiving service. // OmniLogger binds it to the service's name, so it can only write this service's own entries. // It is a per-service credential, not a SECRET, and is never echoed back in the response. OmniLoggerIngestToken string `json:"omniLoggerIngestToken,omitempty"` } // 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) listeners []func(Info) } // NewStore returns a Store seeded with fallback. func NewStore(fallback Info) *Store { return &Store{info: normalizeInfo(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 } // ComfyUIURL is a convenience accessor for Get().ComfyUIURL. func (s *Store) ComfyUIURL() string { return s.Get().ComfyUIURL } // ProjectConfiguratorURL is a convenience accessor for Get().ProjectConfiguratorURL. func (s *Store) ProjectConfiguratorURL() string { return s.Get().ProjectConfiguratorURL } // ContentScannerURL is a convenience accessor for Get().ContentScannerURL. func (s *Store) ContentScannerURL() string { return s.Get().ContentScannerURL } // ContentScannerSecret is the credential the scanner expects on internal sync requests. func (s *Store) ContentScannerSecret() string { return s.Get().ContentScannerSecret } // CarrierNodeURL is a convenience accessor for Get().CarrierNodeURL - the natural closure to wire // as a single-instance carriernodeclient.Client's BaseURL: carriernodeclient.New(secret, func(ctx // context.Context) string { return store.CarrierNodeURL() }). func (s *Store) CarrierNodeURL() string { return s.Get().CarrierNodeURL } // CarrierNodeURLs is a convenience accessor for Get().CarrierNodeURLs - the natural closure to // wire as a multi-instance carriernodeclient.Client's BaseURLs: // carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { return // store.CarrierNodeURLs() }). func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs } // CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret. func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret } // OmniLoggerURL is a convenience accessor for Get().OmniLoggerURL. func (s *Store) OmniLoggerURL() string { return s.Get().OmniLoggerURL } // OmniLoggerIngestToken is a convenience accessor for Get().OmniLoggerIngestToken. func (s *Store) OmniLoggerIngestToken() string { return s.Get().OmniLoggerIngestToken } // 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() } // Subscribe registers fn to be called (synchronously, so keep it fast) with the new Info after every // Set, in addition to OnUpdate's single callback, which it does not replace. Use it when a service // has more than one component that follows the pushed values, such as an authclient.Client and a // log shipper. Subscribers cannot be removed; they live as long as the Store. func (s *Store) Subscribe(fn func(Info)) { s.mu.Lock() s.listeners = append(s.listeners, fn) s.mu.Unlock() } // Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push // (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. func (s *Store) Set(next Info) { next = normalizeInfo(next) s.mu.Lock() if url := strings.TrimSpace(next.AuthGuardURL); url != "" { s.info.AuthGuardURL = url } if url := strings.TrimRight(strings.TrimSpace(next.ComfyUIURL), "/"); url != "" { s.info.ComfyUIURL = url } if url := strings.TrimRight(strings.TrimSpace(next.ProjectConfiguratorURL), "/"); url != "" { s.info.ProjectConfiguratorURL = url } if url := strings.TrimRight(strings.TrimSpace(next.ContentScannerURL), "/"); url != "" { s.info.ContentScannerURL = url } if secret := strings.TrimSpace(next.ContentScannerSecret); secret != "" { s.info.ContentScannerSecret = secret } if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" { s.info.CarrierNodeSecret = secret } if url := strings.TrimRight(strings.TrimSpace(next.OmniLoggerURL), "/"); url != "" { s.info.OmniLoggerURL = url } if token := strings.TrimSpace(next.OmniLoggerIngestToken); token != "" { s.info.OmniLoggerIngestToken = token } if len(next.CarrierNodeURLs) > 0 { s.info.CarrierNodeURLs = next.CarrierNodeURLs s.info.CarrierNodeURL = next.CarrierNodeURLs[0] } current := s.info callback := s.onUpdate listeners := append([]func(Info){}, s.listeners...) s.mu.Unlock() if callback != nil { callback(current) } for _, fn := range listeners { fn(current) } } // normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a // lone legacy CarrierNodeURL (or vice versa), so every caller - old pushes that only ever set // CarrierNodeURL, and new ones that set CarrierNodeURLs - sees both fields populated consistently. func normalizeInfo(info Info) Info { var cleaned []string for _, url := range info.CarrierNodeURLs { if url = strings.TrimSpace(url); url != "" { cleaned = append(cleaned, url) } } if len(cleaned) == 0 { if url := strings.TrimSpace(info.CarrierNodeURL); url != "" { cleaned = []string{url} } } info.CarrierNodeURLs = cleaned if len(cleaned) > 0 { info.CarrierNodeURL = cleaned[0] } else { info.CarrierNodeURL = "" } return info } // 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 // SECRET (the same value ProjectConfigurator and CarrierNode were configured // with - a secret that is not usable (see InternalSecretUsable) 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 !InternalSecretMatches(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 } if err := validateServiceURLs(input); err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } store.Set(input) // Do not echo service credentials to the caller. The push is authenticated, but // these credentials are needed only by the recipient. info := store.Get() info.CarrierNodeSecret = "" info.ContentScannerSecret = "" info.OmniLoggerIngestToken = "" writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info}) } } // validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push // cannot point this service's clients at another scheme or at an empty host. func validateServiceURLs(info Info) error { urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL, info.OmniLoggerURL}, info.CarrierNodeURLs...) for _, raw := range urls { value := strings.TrimSpace(raw) if value == "" { continue } parsed, err := url.Parse(value) if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { return errors.New("core service URL must be an http or https URL with a host") } } return nil } 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}) }