Skip to content

Agent Mesh

console: derive the origin from --external-url when it is set

Antonio Ojea04403eeaa51c
diff --git a/charts/sam-mesh/templates/console-deployment.yaml b/charts/sam-mesh/templates/console-deployment.yaml
index 8d77457b..f39e615d 100644
--- a/charts/sam-mesh/templates/console-deployment.yaml
+++ b/charts/sam-mesh/templates/console-deployment.yaml
@@ -93,4 +93,7 @@ spec:
args:
- "--control-plane=http://{{ include "sam-mesh.fullname" . }}-control-plane:{{ .Values.controlPlane.service.port }}"
- "--bind-addr=:8081"
- - "--static-dir=/app/public"{{- end }}
+ - "--static-dir=/app/public"
+ {{- with .Values.console.externalUrl }}
+ - "--external-url={{ . }}"
+ {{- end }}{{- end }}
diff --git a/charts/sam-mesh/values.yaml b/charts/sam-mesh/values.yaml
index 4ae7afc2..bda5d30e 100644
--- a/charts/sam-mesh/values.yaml
+++ b/charts/sam-mesh/values.yaml
@@ -143,6 +143,11 @@ router:
console:
enabled: true
replicaCount: 1
+ # Origin browsers reach the console on, e.g. https://console.example. Set this
+ # when a proxy terminates TLS: without it the OIDC redirect_uri and the cookie
+ # Secure flag are derived from the Host and X-Forwarded-Proto headers, so a
+ # proxy that drops the header leaves session cookies without Secure.
+ externalUrl: ""
image:
repository: sam-console
# Overrides global.imageTag for this image only.
diff --git a/cmd/sam-console/main.go b/cmd/sam-console/main.go
index d9893d2b..94f06fee 100644
--- a/cmd/sam-console/main.go
+++ b/cmd/sam-console/main.go
@@ -35,6 +35,7 @@ func main() {
bindAddr = flag.String("bind-addr", ":8081", "Address to bind the console server")
staticDir = flag.String("static-dir", "public", "Directory containing static frontend files")
basePath = flag.String("base-path", "", "Base path prefix for the console (e.g. /console)")
+ externalURL = flag.String("external-url", "", "Origin browsers reach this console on, e.g. https://console.example. Sets the OIDC redirect_uri and cookie Secure flag instead of trusting the Host and X-Forwarded-Proto headers")
)
flag.Parse()
@@ -51,6 +52,7 @@ func main() {
AdminToken: adminToken,
StaticDir: *staticDir,
BasePath: console.NormalizeBasePath(*basePath),
+ ExternalURL: *externalURL,
})
if err != nil {
log.Fatalf("Failed to initialize console server: %v", err)
diff --git a/internal/console/origin_test.go b/internal/console/origin_test.go
new file mode 100644
index 00000000..d45c63b0
--- /dev/null
+++ b/internal/console/origin_test.go
@@ -0,0 +1,130 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package console
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func newOriginServer(t *testing.T, externalURL string) *Server {
+ t.Helper()
+ // Empty /info means no OIDC, which the console tolerates; these tests are
+ // about how the origin is derived, not about the provider.
+ controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(controlPlane.Close)
+
+ srv, err := NewServer(Config{
+ ControlPlaneURL: controlPlane.URL,
+ AdminToken: "t",
+ StaticDir: t.TempDir(),
+ BasePath: "/console",
+ ExternalURL: externalURL,
+ })
+ if err != nil {
+ t.Fatalf("NewServer: %v", err)
+ }
+ return srv
+}
+
+// TestExternalURLDecidesOriginAndSecureCookies covers the reason the flag
+// exists. Without it both the redirect_uri and the cookie Secure flag come from
+// the Host and X-Forwarded-Proto headers, which the client sets: a proxy that
+// terminates TLS but drops the header leaves the session cookie without Secure.
+func TestExternalURLDecidesOriginAndSecureCookies(t *testing.T) {
+ req := func(host, forwardedProto string) *http.Request {
+ r := httptest.NewRequest(http.MethodGet, "/console/auth/login", nil)
+ r.Host = host
+ if forwardedProto != "" {
+ r.Header.Set("X-Forwarded-Proto", forwardedProto)
+ }
+ return r
+ }
+
+ t.Run("configured external url wins over the headers", func(t *testing.T) {
+ srv := newOriginServer(t, "https://console.example")
+
+ // An attacker-controlled Host must not reach the redirect_uri.
+ got := srv.redirectURI(req("evil.example", ""))
+ if want := "https://console.example/console/auth/callback"; got != want {
+ t.Errorf("redirectURI = %q, want %q", got, want)
+ }
+ if !srv.secureCookies(req("evil.example", "")) {
+ t.Error("secureCookies = false for an https external url")
+ }
+ })
+
+ t.Run("a proxy that drops the header no longer downgrades the cookie", func(t *testing.T) {
+ srv := newOriginServer(t, "https://console.example")
+ if !srv.secureCookies(req("console.example", "")) {
+ t.Error("secureCookies = false, want true: the external url says https")
+ }
+ })
+
+ t.Run("without the flag the request still decides", func(t *testing.T) {
+ srv := newOriginServer(t, "")
+
+ got := srv.redirectURI(req("console.example", "https"))
+ if want := "https://console.example/console/auth/callback"; got != want {
+ t.Errorf("redirectURI = %q, want %q", got, want)
+ }
+ if srv.secureCookies(req("console.example", "")) {
+ t.Error("secureCookies = true for a plain http request")
+ }
+ })
+
+ t.Run("an http external url does not mark cookies secure", func(t *testing.T) {
+ srv := newOriginServer(t, "http://localhost:8081")
+ if srv.secureCookies(req("localhost:8081", "https")) {
+ t.Error("secureCookies = true, want false: the external url says http")
+ }
+ })
+}
+
+// A redirect_uri must match the provider's registered value byte for byte, so a
+// malformed flag has to fail at startup rather than on every login.
+func TestNewServerRejectsAMalformedExternalURL(t *testing.T) {
+ tests := []struct {
+ name string
+ url string
+ }{
+ {"no scheme", "console.example"},
+ {"unsupported scheme", "ftp://console.example"},
+ {"no host", "https://"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := NewServer(Config{
+ ControlPlaneURL: "http://cp.invalid",
+ AdminToken: "t",
+ StaticDir: t.TempDir(),
+ ExternalURL: tt.url,
+ })
+ if err == nil {
+ t.Fatalf("NewServer accepted ExternalURL %q", tt.url)
+ }
+ // Checked before the control plane is contacted, so cp.invalid
+ // never has to resolve.
+ if !strings.Contains(err.Error(), "ExternalURL") {
+ t.Errorf("error %q does not name the offending setting", err)
+ }
+ })
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index ad8a3b5d..e601938f 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -42,6 +42,12 @@ type Config struct {
AdminToken string
StaticDir string
BasePath string
+
+ // ExternalURL is the origin browsers reach this console on, e.g.
+ // "https://console.example". When set it decides the OIDC redirect_uri and
+ // whether session cookies are marked Secure, instead of the Host and
+ // X-Forwarded-Proto headers, which a client controls and a proxy may drop.
+ ExternalURL string
}
// NormalizeBasePath makes a base-path flag value safe to concatenate: no trailing
@@ -57,11 +63,43 @@ func NormalizeBasePath(p string) string {
return p
}
+// origin returns the scheme and host to build absolute URLs with.
+//
+// A configured ExternalURL wins. Falling back to the request means trusting
+// Host and X-Forwarded-Proto, which the client sets: a proxy that terminates
+// TLS but drops the header leaves session cookies without Secure, and the
+// redirect_uri is only kept honest by the provider's own exact-match list.
+func (s *Server) origin(r *http.Request) (scheme, host string) {
+ if s.external != nil {
+ return s.external.Scheme, s.external.Host
+ }
+ scheme = "http"
+ if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
+ scheme = "https"
+ }
+ return scheme, r.Host
+}
+
+// redirectURI is the OIDC callback this console is reachable at. It must match
+// byte for byte between the authorization request and the token exchange.
+func (s *Server) redirectURI(r *http.Request) string {
+ scheme, host := s.origin(r)
+ return fmt.Sprintf("%s://%s%s/auth/callback", scheme, host, s.cfg.BasePath)
+}
+
+// secureCookies reports whether session cookies may carry the Secure attribute.
+func (s *Server) secureCookies(r *http.Request) bool {
+ scheme, _ := s.origin(r)
+ return scheme == "https"
+}
+
type Server struct {
cfg Config
mux *http.ServeMux
provider *oidc.Provider
clientID string
+ // external is the parsed Config.ExternalURL, nil when unset.
+ external *url.URL
}
func NewServer(cfg Config) (*Server, error) {
@@ -74,6 +112,23 @@ func NewServer(cfg Config) (*Server, error) {
return nil, fmt.Errorf("invalid ControlPlaneURL: %w", err)
}
+ var external *url.URL
+ if cfg.ExternalURL != "" {
+ // Fail at startup: a redirect_uri built from a malformed value would be
+ // rejected by the provider on every login instead.
+ u, err := url.Parse(cfg.ExternalURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid ExternalURL: %w", err)
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return nil, fmt.Errorf("invalid ExternalURL %q: scheme must be http or https", cfg.ExternalURL)
+ }
+ if u.Host == "" {
+ return nil, fmt.Errorf("invalid ExternalURL %q: missing host", cfg.ExternalURL)
+ }
+ external = u
+ }
+
var provider *oidc.Provider
var clientID string
@@ -115,6 +170,7 @@ func NewServer(cfg Config) (*Server, error) {
mux: http.NewServeMux(),
provider: provider,
clientID: clientID,
+ external: external,
}
// Create reverse proxy to the control plane
proxy := &httputil.ReverseProxy{
@@ -221,11 +277,7 @@ func (s *Server) HandleLogout(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request) {
- scheme := "http"
- if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
- scheme = "https"
- }
- redirectURI := fmt.Sprintf("%s://%s%s/auth/callback", scheme, r.Host, s.cfg.BasePath)
+ redirectURI := s.redirectURI(r)
verifier, challenge, err := generatePKCE()
if err != nil {
@@ -246,7 +298,7 @@ func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request) {
Path: s.cfg.BasePath + "/",
MaxAge: 300,
HttpOnly: true,
- Secure: scheme == "https",
+ Secure: s.secureCookies(r),
SameSite: http.SameSiteLaxMode,
})
@@ -256,7 +308,7 @@ func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request) {
Path: s.cfg.BasePath + "/",
MaxAge: 300,
HttpOnly: true,
- Secure: scheme == "https",
+ Secure: s.secureCookies(r),
SameSite: http.SameSiteLaxMode,
})
@@ -297,11 +349,8 @@ func (s *Server) HandleCallback(w http.ResponseWriter, r *http.Request) {
return
}
- scheme := "http"
- if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
- scheme = "https"
- }
- redirectURI := fmt.Sprintf("%s://%s%s/auth/callback", scheme, r.Host, s.cfg.BasePath)
+ // Must match the value sent in HandleLogin byte for byte.
+ redirectURI := s.redirectURI(r)
oauth2Config := &oauth2.Config{
ClientID: s.clientID,
@@ -332,7 +381,7 @@ func (s *Server) HandleCallback(w http.ResponseWriter, r *http.Request) {
Path: s.cfg.BasePath + "/",
MaxAge: 24 * 3600,
HttpOnly: true,
- Secure: scheme == "https",
+ Secure: s.secureCookies(r),
SameSite: http.SameSiteLaxMode,
})
@@ -414,18 +463,13 @@ func (s *Server) HandleTokenLogin(w http.ResponseWriter, r *http.Request) {
return
}
- scheme := "http"
- if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
- scheme = "https"
- }
-
http.SetCookie(w, &http.Cookie{
Name: "sam_session",
Value: token,
Path: s.cfg.BasePath + "/",
MaxAge: 24 * 3600,
HttpOnly: true,
- Secure: scheme == "https",
+ Secure: s.secureCookies(r),
SameSite: http.SameSiteLaxMode,
})
w.WriteHeader(http.StatusNoContent)