Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(auth): do not trust identity headers from forwarded clients (#136)
Robert06229bd41cab0155
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee29dbf1..08f1f451 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,12 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`, mirNo migrations are required.+## Unreleased++- With `AGENTFLOW_TRUST_IDENTITY_HEADERS=true`, identity headers such as `Staffname` are ignored on requests that carry `X-Forwarded-For`, `Forwarded` or `X-Real-IP`, unless the gateway also sends `X-AgentFlow-Gateway-Secret` matching the new `AGENTFLOW_IDENTITY_HEADER_SECRET`. A client behind a pass-through reverse proxy could otherwise sign in as any account. Deployments with the option off are unaffected.++Before upgrading a deployment that signs users in by header behind a proxy adding forwarding headers, set `AGENTFLOW_IDENTITY_HEADER_SECRET` and have the gateway send it in `X-AgentFlow-Gateway-Secret`; otherwise header sign-in falls back to guest after the upgrade. See `docs/deployment.md`.+## 0.3.6 — a default sandbox on an uninitialized catalog- A database without sandbox catalog rows, for example after a plain `docker compose --profile platform up` without the installer, now offers the built-in 默认运行沙箱 (`local`). Creating a blank SOP no longer fails with `sandbox profile not found`. The default is not written to the database, a saved `local` profile takes priority, and it cannot be deleted. Compose still runs it in a separate Docker container.diff --git a/docs/deployment.md b/docs/deployment.mdindex f87edec6..3623d937 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -47,6 +47,11 @@ During initial setup, restrict the cloud security group or firewall to the operaThe platform listens on `LOOPFORGE_BIND`, `0.0.0.0` by default, without prompting for an access URL. The installer prints the public, LAN and local addresses; on Tencent Cloud, Alibaba Cloud, AWS, GCP and Azure it reads the public IP from the provider's link-local metadata service, and elsewhere behind NAT you open the public IP yourself. `LOOPFORGE_PUBLIC_URL` is optional and only changes the printed address. Allow the HTTP port in the cloud security group/firewall, or use an HTTPS reverse proxy. Existing `.env` files are preserved; older installations without a bind setting now also listen on `0.0.0.0`. Local-only installations can set `LOOPFORGE_BIND=127.0.0.1`. Proxy WebSocket and streaming requests. Set `AGENTFLOW_SECURE_COOKIES=true` when HTTPS terminates at the proxy. Keep `AGENTFLOW_SESSION_SECRET` stable across API instances and restarts.+Enterprise authentication gateways can sign users in by header with `AGENTFLOW_TRUST_IDENTITY_HEADERS=true`. This option is off by default. The API then accepts `Staffname` / `x-staff-name` only from a loopback peer, and only when it can tell the request came from the gateway:++- Set `AGENTFLOW_IDENTITY_HEADER_SECRET` to a random value, and have the gateway send it in `X-AgentFlow-Gateway-Secret`. The gateway must overwrite, never pass through, the client's `Staffname`, `Staffid`, `x-staff-name` and `X-AgentFlow-Gateway-Secret` headers.+- Without a secret, any request carrying `X-Forwarded-For`, `Forwarded` or `X-Real-IP` is treated as a forwarded client, and its identity headers are ignored. This only protects proxies that add one of those headers: a same-host proxy that passes client headers through without adding them (for example nginx `proxy_pass` without `proxy_set_header X-Forwarded-For`), and any other process on the host, can still sign in as any user. Set the secret whenever header sign-in is on; the platform logs a warning at startup when it is missing.+### Docker sandboxesThe platform exposes a built-in default sandbox (`local`) even when the catalog SQL has not been installed. It is an in-memory fallback and does not insert database rows. An existing saved `local` profile takes priority, including its configured driver and environment. The default cannot be deleted; edit its configuration or create another profile to change how tasks run. The full installer still imports starter SOPs and the welcome project.diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.goindex 7585a913..a19f7c3e 100644--- a/internal/httpapi/auth.go+++ b/internal/httpapi/auth.go@@ -1,6 +1,7 @@package httpapiimport (+ "crypto/subtle""errors""fmt""log"@@ -40,10 +41,26 @@ func trustGatewayIdentityHeaders() bool {return err == nil && enabled}+// gatewayIdentitySecretHeader carries AGENTFLOW_IDENTITY_HEADER_SECRET from+// the authenticating gateway.+const gatewayIdentitySecretHeader = "X-AgentFlow-Gateway-Secret"++// gatewayLoginName trusts identity headers only from the authenticating+// gateway. Loopback alone does not prove that: a reverse proxy on the same+// host also connects from loopback and may pass client headers through. With+// a configured secret the gateway must present it; without one, any forwarded+// request is refused, as authLocal does.func gatewayLoginName(r *http.Request) string {if !trustGatewayIdentityHeaders() || !isLoopbackAddr(r.RemoteAddr) {return ""}+ if secret := strings.TrimSpace(os.Getenv("AGENTFLOW_IDENTITY_HEADER_SECRET")); secret != "" {+ if subtle.ConstantTimeCompare([]byte(strings.TrimSpace(r.Header.Get(gatewayIdentitySecretHeader))), []byte(secret)) != 1 {+ return ""+ }+ } else if r.Header.Get("X-Forwarded-For") != "" || r.Header.Get("Forwarded") != "" || r.Header.Get("X-Real-IP") != "" {+ return ""+ }login := strings.TrimSpace(getHeaderCaseInsensitive(r, "Staffname"))if login == "" {login = strings.TrimSpace(getHeaderCaseInsensitive(r, "x-staff-name"))diff --git a/internal/httpapi/auth_gateway_trust_test.go b/internal/httpapi/auth_gateway_trust_test.gonew file mode 100644index 00000000..6087c71e--- /dev/null+++ b/internal/httpapi/auth_gateway_trust_test.go@@ -0,0 +1,87 @@+package httpapi++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "agentflow/internal/auth"+)++// gatewayCurrent asks /api/auth/current as a caller behind a loopback proxy.+func gatewayCurrent(t *testing.T, handler http.Handler, headers map[string]string) (auth.User, string) {+ t.Helper()+ req := httptest.NewRequest(http.MethodGet, "/api/auth/current", nil)+ req.RemoteAddr = "127.0.0.1:40000"+ for key, value := range headers {+ req.Header.Set(key, value)+ }+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("auth/current status %d: %s", rec.Code, rec.Body.String())+ }+ var body struct {+ User auth.User `json:"user"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ return body.User, rec.Header().Get("Set-Cookie")+}++func TestGatewayIdentityIgnoresForwardedClientHeaders(t *testing.T) {+ t.Setenv("AGENTFLOW_TRUST_IDENTITY_HEADERS", "true")+ t.Setenv("AGENTFLOW_IDENTITY_HEADER_SECRET", "")+ handler, st := newTestAuthServer(t, auth.NewClient(auth.Config{SessionSecret: "test-secret-123"}))+ for name, forwarded := range map[string]map[string]string{+ "x-forwarded-for": {"X-Forwarded-For": "198.51.100.10"},+ "forwarded": {"Forwarded": "for=198.51.100.10"},+ "x-real-ip": {"X-Real-IP": "198.51.100.10"},+ } {+ t.Run(name, func(t *testing.T) {+ headers := map[string]string{"Staffname": "real-admin", "x-staff-name": "real-admin"}+ for key, value := range forwarded {+ headers[key] = value+ }+ user, cookie := gatewayCurrent(t, handler, headers)+ if !user.IsGuest || user.LoginName == "real-admin" || strings.Contains(cookie, authCookieName+"=") {+ t.Fatalf("forwarded client minted a gateway session: user=%+v cookie=%q", user, cookie)+ }+ })+ }+ if _, ok := st.UserByLoginName("real-admin"); ok {+ t.Fatal("forged gateway identity was provisioned")+ }+ // A gateway that connects directly without forwarding headers still works.+ if user, cookie := gatewayCurrent(t, handler, map[string]string{"Staffname": "direct-gateway"}); user.IsGuest || user.LoginName != "direct-gateway" || !strings.Contains(cookie, authCookieName+"=") {+ t.Fatalf("direct loopback gateway rejected: user=%+v", user)+ }+}++func TestGatewayIdentityRequiresConfiguredSecret(t *testing.T) {+ t.Setenv("AGENTFLOW_TRUST_IDENTITY_HEADERS", "true")+ t.Setenv("AGENTFLOW_IDENTITY_HEADER_SECRET", "gateway-shared-secret")+ handler, _ := newTestAuthServer(t, auth.NewClient(auth.Config{SessionSecret: "test-secret-123"}))+ for name, secret := range map[string]string{"missing": "", "wrong": "gateway-shared-secreT", "prefix": "gateway-shared"} {+ t.Run(name, func(t *testing.T) {+ headers := map[string]string{"Staffname": "real-admin"}+ if secret != "" {+ headers[gatewayIdentitySecretHeader] = secret+ }+ if user, cookie := gatewayCurrent(t, handler, headers); !user.IsGuest || strings.Contains(cookie, authCookieName+"=") {+ t.Fatalf("gateway identity accepted without the secret: %+v", user)+ }+ })+ }+ // The authenticating gateway sits behind other proxies and forwards the+ // client address; the secret, not the absence of forwarding, proves it.+ user, cookie := gatewayCurrent(t, handler, map[string]string{+ "Staffname": "real-admin", gatewayIdentitySecretHeader: "gateway-shared-secret", "X-Forwarded-For": "198.51.100.10",+ })+ if user.IsGuest || user.LoginName != "real-admin" || !strings.Contains(cookie, authCookieName+"=") {+ t.Fatalf("gateway with the secret rejected: %+v", user)+ }+}diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex dfb2d882..c777dcba 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -123,6 +123,9 @@ func NewWithNotificationsAndBackground(ctx context.Context, s *repo.Store, e *enfunc newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Service, basicUser, basicPass string, notifications *notification.Service, bg *Background, startBackground func(*assistantHandlers, *runsHandlers)) *gin.Engine {d := &deps{repo: s, engine: e, sync: syncSvc, authClient: auth.NewClientFromEnv(), passwordAttempts: newPasswordLimiter()}+ if trustGatewayIdentityHeaders() && strings.TrimSpace(os.Getenv("AGENTFLOW_IDENTITY_HEADER_SECRET")) == "" {+ log.Printf("warning: AGENTFLOW_TRUST_IDENTITY_HEADERS is on without AGENTFLOW_IDENTITY_HEADER_SECRET; any loopback caller without forwarding headers, including a proxy that passes client headers through, can sign in as any user")+ }if err := ensureDefaultMCPsForAllProjects(s); err != nil {log.Printf("ensure default project MCPs: %v", err)} else {