feat(webui): scope cookies to the instance and show non-default instance names

This commit is contained in:
sam committed 2026-10-19 10:17:05 +11:00
1 parent f72a3df413
commit fafa0426be
14 files changed
+89 -53

No files matched your search

+1
View File
@@ -65,6 +65,7 @@ func compose(ctx context.Context, d deps) *webui.Server {
ControlPlane: d.ControlPlane,
Identities: d.Identities,
Issuer: strings.TrimSpace(d.Options.OidcIssuer),
Instance: d.Options.instance,
}
if subjects, ok := d.Identities.(identity.SubjectBinding); ok {
srv.Subjects = subjects
+6
View File
@@ -26,8 +26,12 @@ func Resolve(o Options, log *slog.Logger) (Options, error) {
if found {
o = merge(o, cfg)
tls = cfg.tls
o.instance = cfg.instance
}
}
if o.instance == "" {
o.instance = configuration.InstanceName()
}
o = withDefaults(o)
id, err := rpctls.Load(tls.CAFile, tls.CertDir, presence.UI)
if err != nil {
@@ -66,6 +70,7 @@ type projection struct {
daemon ServiceTarget
tls config.TLS
capture CaptureOptions
instance string
}
func project(cfg config.Config) projection {
@@ -78,6 +83,7 @@ func project(cfg config.Config) projection {
harness: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameHarness).Target},
daemon: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameDaemon).Target},
tls: cfg.TLS,
instance: cfg.Instance,
capture: CaptureOptions{
Retention: cfg.Capture.Retention.Std(),
MaxEvents: cfg.Capture.MaxEvents,
+3
View File
@@ -79,6 +79,9 @@ type Options struct {
// identity is this process's certificate, loaded by Resolve from
// [tls]; nil is plaintext, loopback only.
identity *rpctls.Identity
// instance is the deployment name, from the configuration source or
// ARCHIE_INSTANCE.
instance string
}
// CaptureOptions carries the [capture] settings the capture receiver needs.
+10 -12
View File
@@ -15,8 +15,6 @@ import (
"github.com/samcharles93/archie-core/internal/ratelimit"
)
const accountCookie = "archie_session"
func (s *Server) registerAccountRoutes(public, protected *http.ServeMux) {
if s.Accounts == nil {
return
@@ -38,7 +36,7 @@ func (s *Server) registerAccountRoutes(public, protected *http.ServeMux) {
}
func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
if c, err := r.Cookie(accountCookie); err == nil {
if c, err := r.Cookie(s.cookies().account); err == nil {
value, err := s.Accounts.ResolveAccountSession(r.Context(), c.Value)
if err != nil {
return identity.Identity{}, err
@@ -51,7 +49,7 @@ func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
if s.Authenticate != nil && strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
return s.Authenticate(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
}
if cookie, err := r.Cookie(providerTokenCookie); err == nil {
if cookie, err := r.Cookie(s.cookies().providerToken); err == nil {
return s.authenticateBrowser(r.Context(), cookie.Value)
}
@@ -100,7 +98,7 @@ func (s *Server) handleAccountStatus(w http.ResponseWriter, r *http.Request) {
oidcEnabled = settings.OIDCIssuer != ""
}
}
writeJSON(w, map[string]any{"setup_required": required, "user": user, "oidc": oidcEnabled, "public_url": publicURL})
writeJSON(w, map[string]any{"setup_required": required, "user": user, "oidc": oidcEnabled, "public_url": publicURL, "instance": s.Instance})
}
func decodeAccountRequest(w http.ResponseWriter, r *http.Request, value any) bool {
@@ -157,7 +155,7 @@ func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, pa
func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) {
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: accountCookie, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
w.Header().Set("Cache-Control", "no-store")
}
@@ -165,13 +163,13 @@ func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if c, err := r.Cookie(accountCookie); err == nil {
if c, err := r.Cookie(s.cookies().account); err == nil {
if err = s.Accounts.SignOutAccount(r.Context(), c.Value); err != nil {
s.writeAccountError(w, err)
return
}
}
for _, name := range []string{accountCookie, providerTokenCookie} {
for _, name := range []string{s.cookies().account, s.cookies().providerToken} {
http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode})
}
w.WriteHeader(http.StatusNoContent)
@@ -212,7 +210,7 @@ func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) {
s.writeAccountError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: accountCookie, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
w.WriteHeader(http.StatusNoContent)
}
@@ -301,7 +299,7 @@ func (s *Server) requireFreshAccount(w http.ResponseWriter, r *http.Request) boo
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return false
}
cookie, err := r.Cookie(accountCookie)
cookie, err := r.Cookie(s.cookies().account)
if err == nil {
err = store.RequireFreshAccountSession(r.Context(), cookie.Value)
}
@@ -355,7 +353,7 @@ func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) clearProviderCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: providerTokenCookie, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: s.cookies().providerToken, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool {
@@ -388,7 +386,7 @@ func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.
}
func (s *Server) verifyAccountProvider(r *http.Request, value identity.Identity) error {
cookie, err := r.Cookie(providerTokenCookie)
cookie, err := r.Cookie(s.cookies().providerToken)
if errors.Is(err, http.ErrNoCookie) {
return nil
}
+2 -2
View File
@@ -73,7 +73,7 @@ func TestAccountBoundary(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", tc.csrf)
if tc.cookie != "" {
req.AddCookie(&http.Cookie{Name: accountCookie, Value: tc.cookie})
req.AddCookie(&http.Cookie{Name: "archie_session", Value: tc.cookie})
}
recorder := httptest.NewRecorder()
srv.Handler().ServeHTTP(recorder, req)
@@ -83,7 +83,7 @@ func TestAccountBoundary(t *testing.T) {
if tc.name == "successful login" {
var found bool
for _, cookie := range recorder.Result().Cookies() {
if cookie.Name == accountCookie {
if cookie.Name == "archie_session" {
found = true
if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.Value != "new-session" {
t.Fatalf("unsafe session cookie: %+v", cookie)
+13 -25
View File
@@ -17,20 +17,8 @@ import (
"github.com/samcharles93/archie-core/internal/domain/identity"
)
// tokenCookie carries the dashboard token once it has been exchanged from the
// URL, so the token is not left sitting in browser history or referrers.
const (
tokenCookie = "archie_ui"
// providerTokenCookie holds the provider's own access token after a browser
// sign-in. It is not a session archie issued: the token belongs to the
// provider and is verified on every request exactly as a presented header is,
// so nothing archie stores can outlive the provider's decision.
providerTokenCookie = "archie_provider_token"
// The sign-in flow's state and PKCE verifier live in short-lived cookies for
// the duration of the redirect, scoped to the callback path.
loginStateCookie = "archie_login_state"
loginVerifierCookie = "archie_login_verifier"
loginCookieMaxAge = 600
loginCookieMaxAge = 600
// loginPath is where a browser signs in, and the path a refused browser is
// sent to. loginCallbackPath must match the redirect URI registered at the
// provider: the provider returns the browser to the path it was given.
@@ -98,7 +86,7 @@ func (s *Server) requireToken(h http.Handler) http.Handler {
return
}
http.SetCookie(w, &http.Cookie{
Name: tokenCookie,
Name: s.cookies().token,
Value: tok,
Path: "/",
HttpOnly: true,
@@ -113,7 +101,7 @@ func (s *Server) requireToken(h http.Handler) http.Handler {
return
}
if c, err := r.Cookie(tokenCookie); err == nil && tokenEqual(c.Value, s.Token) {
if c, err := r.Cookie(s.cookies().token); err == nil && tokenEqual(c.Value, s.Token) {
h.ServeHTTP(w, r)
return
}
@@ -137,7 +125,7 @@ func (s *Server) requireToken(h http.Handler) http.Handler {
// identity it resolves to.
func (s *Server) requireIdentity(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
credential, ok := bearerCredential(r)
credential, ok := s.bearerCredential(r)
if !ok {
s.refuseUnidentified(w, r, identity.ErrNoCredential)
return
@@ -152,7 +140,7 @@ func (s *Server) requireIdentity(h http.Handler) http.Handler {
}
// bearerCredential returns the request's bearer token or provider cookie.
func bearerCredential(r *http.Request) (string, bool) {
func (s *Server) bearerCredential(r *http.Request) (string, bool) {
const prefix = "Bearer "
header := r.Header.Get("Authorization")
if len(header) > len(prefix) && strings.EqualFold(header[:len(prefix)], prefix) {
@@ -160,7 +148,7 @@ func bearerCredential(r *http.Request) (string, bool) {
return token, true
}
}
if c, err := r.Cookie(providerTokenCookie); err == nil && strings.TrimSpace(c.Value) != "" {
if c, err := r.Cookie(s.cookies().providerToken); err == nil && strings.TrimSpace(c.Value) != "" {
return c.Value, true
}
return "", false
@@ -184,8 +172,8 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, err)
return
}
setFlowCookie(w, r, loginStateCookie, state)
setFlowCookie(w, r, loginVerifierCookie, verifier)
setFlowCookie(w, r, s.cookies().loginState, state)
setFlowCookie(w, r, s.cookies().loginVerifier, verifier)
http.Redirect(w, r, url, http.StatusSeeOther)
}
@@ -203,12 +191,12 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, fmt.Errorf("%w: provider returned %s", identity.ErrCredentialRejected, providerErr))
return
}
state, stateErr := r.Cookie(loginStateCookie)
state, stateErr := r.Cookie(s.cookies().loginState)
if stateErr != nil || !tokenEqual(state.Value, query.Get("state")) {
s.refuseUnidentified(w, r, fmt.Errorf("%w: sign-in state did not match", identity.ErrCredentialRejected))
return
}
verifier, verifierErr := r.Cookie(loginVerifierCookie)
verifier, verifierErr := r.Cookie(s.cookies().loginVerifier)
if verifierErr != nil || strings.TrimSpace(verifier.Value) == "" {
s.refuseUnidentified(w, r, fmt.Errorf("%w: sign-in verifier is missing", identity.ErrCredentialRejected))
return
@@ -223,8 +211,8 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, err)
return
}
clearFlowCookie(w, r, loginStateCookie)
clearFlowCookie(w, r, loginVerifierCookie)
clearFlowCookie(w, r, s.cookies().loginState)
clearFlowCookie(w, r, s.cookies().loginVerifier)
if security, ok := s.Accounts.(identity.AccountSecurity); ok {
principal, resolveErr := s.Principals.PrincipalFor(r.Context(), value.ID)
if resolveErr != nil {
@@ -239,7 +227,7 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.setAccountCookie(w, r, local)
}
http.SetCookie(w, &http.Cookie{
Name: providerTokenCookie, Value: session.Token, Path: "/",
Name: s.cookies().providerToken, Value: session.Token, Path: "/",
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil,
})
http.Redirect(w, r, "/", http.StatusSeeOther)
@@ -149,7 +149,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
req.Header.Set("X-Archie-CSRF", "1")
want := http.StatusUnauthorized
if signedIn {
req.AddCookie(&http.Cookie{Name: accountCookie, Value: "valid"})
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
want = http.StatusForbidden
}
rec := httptest.NewRecorder()
+28
View File
@@ -0,0 +1,28 @@
package webui
import "strings"
// cookieNames are the dashboard's cookie names. Browsers scope cookies by host
// and ignore the port, so each name carries the instance: two instances on
// one host would otherwise overwrite each other's sessions.
type cookieNames struct {
token, account, providerToken, loginState, loginVerifier, passkeyRegistration, passkeyLogin string
}
func newCookieNames(instance string) cookieNames {
prefix := strings.ReplaceAll(instance, "-", "_")
if prefix == "" {
prefix = "archie"
}
return cookieNames{
token: prefix + "_ui",
account: prefix + "_session",
providerToken: prefix + "_provider_token",
loginState: prefix + "_login_state",
loginVerifier: prefix + "_login_verifier",
passkeyRegistration: prefix + "_passkey_registration",
passkeyLogin: prefix + "_passkey_login",
}
}
func (s *Server) cookies() cookieNames { return newCookieNames(s.Instance) }
+6 -6
View File
@@ -16,11 +16,11 @@ func (s *Server) registerPasskeyRoutes(public, protected *http.ServeMux) {
protected.HandleFunc("DELETE /api/account/passkeys/{id}", s.handlePasskeyDelete)
}
func passkeyCookie(registration bool) string {
func (s *Server) passkeyCookie(registration bool) string {
if registration {
return "archie_passkey_registration"
return s.cookies().passkeyRegistration
}
return "archie_passkey_login"
return s.cookies().passkeyLogin
}
func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, registration bool) {
@@ -41,7 +41,7 @@ func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, regi
return
}
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300})
http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300})
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, json.RawMessage(value.Options))
}
@@ -58,12 +58,12 @@ func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, reg
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
return
}
cookie, err := r.Cookie(passkeyCookie(registration))
cookie, err := r.Cookie(s.passkeyCookie(registration))
if err != nil {
http.Error(w, "passkey request expired", http.StatusUnauthorized)
return
}
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
var request struct {
Credential json.RawMessage `json:"credential"`
Name string `json:"name"`
+5
View File
@@ -152,6 +152,11 @@ type Server struct {
Subjects identity.SubjectBinding
Issuer string
// Instance names this deployment among others on the same host. It
// prefixes the cookie names and is shown in the dashboard when it is not
// the default.
Instance string
// Orgs serves the org pages: the caller's org, its workspaces, members and
// agent assignments. Nil answers the org routes Unavailable.
Orgs org.API