Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
improvement: add region prefix to request ID for cloud instances
Scott Wilsondb2ffb1f0f2e
diff --git a/backend-go/internal/libs/requestid/requestid.go b/backend-go/internal/libs/requestid/requestid.goindex f3e03defc9..8d3fb344ca 100644--- a/backend-go/internal/libs/requestid/requestid.go+++ b/backend-go/internal/libs/requestid/requestid.go@@ -27,28 +27,44 @@ func FromContext(ctx context.Context) string {return v}-// Middleware extracts the X-Request-Id header from the incoming request.-// If the header is missing or empty a new ID is generated. The ID is stored-// in the request context (retrievable via FromContext) and echoed back in-// the response X-Request-Id header.-func Middleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- id := r.Header.Get(Header)- if id == "" {- id = generate()- }-- w.Header().Set(Header, id)- ctx := context.WithValue(r.Context(), ctxKey{}, id)- next.ServeHTTP(w, r.WithContext(ctx))- })+// OriginPrefix returns the request ID prefix for this deployment. Infisical+// Cloud IDs carry a region segment (req-us-, req-eu-) so an ID's origin is+// identifiable at a glance; self-hosted and dedicated stay bare req-. Matches+// the Node.js backend convention.+func OriginPrefix(isInfisicalCloud bool, internalRegion string) string {+ if !isInfisicalCloud {+ return "req-"+ }+ if internalRegion == "eu" {+ return "req-eu-"+ }+ return "req-us-"+}++// Middleware returns middleware that extracts the X-Request-Id header from the+// incoming request. If the header is missing or empty a new ID is generated+// with the given prefix. The ID is stored in the request context (retrievable+// via FromContext) and echoed back in the response X-Request-Id header.+func Middleware(prefix string) func(http.Handler) http.Handler {+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ id := r.Header.Get(Header)+ if id == "" {+ id = generate(prefix)+ }++ w.Header().Set(Header, id)+ ctx := context.WithValue(r.Context(), ctxKey{}, id)+ next.ServeHTTP(w, r.WithContext(ctx))+ })+ }}-// generate returns a request ID in the format "req-<14 alphanumeric chars>"+// generate returns a request ID: the prefix followed by 14 alphanumeric chars,// matching the Node.js backend convention.-func generate() string {+func generate(prefix string) string {var buf [9]byte // 9 bytes → 14+ base32 chars (no padding)_, _ = rand.Read(buf[:])encoded := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf[:])- return "req-" + strings.ToLower(encoded[:14])+ return prefix + strings.ToLower(encoded[:14])}diff --git a/backend-go/internal/libs/requestid/requestid_test.go b/backend-go/internal/libs/requestid/requestid_test.gonew file mode 100644index 0000000000..d48e6f0dd9--- /dev/null+++ b/backend-go/internal/libs/requestid/requestid_test.go@@ -0,0 +1,63 @@+package requestid++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestOriginPrefix_Deployments(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ isInfisicalCloud bool+ internalRegion string+ want string+ }{+ {name: "us cloud", isInfisicalCloud: true, internalRegion: "us", want: "req-us-"},+ {name: "eu cloud", isInfisicalCloud: true, internalRegion: "eu", want: "req-eu-"},+ {name: "cloud without region defaults to us", isInfisicalCloud: true, internalRegion: "", want: "req-us-"},+ {name: "self-hosted", isInfisicalCloud: false, internalRegion: "", want: "req-"},+ {name: "self-hosted ignores region", isInfisicalCloud: false, internalRegion: "eu", want: "req-"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ assert.Equal(t, tt.want, OriginPrefix(tt.isInfisicalCloud, tt.internalRegion))+ })+ }+}++func TestMiddleware_GeneratesPrefixedID(t *testing.T) {+ t.Parallel()++ var ctxID string+ handler := Middleware("req-eu-")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {+ ctxID = FromContext(r.Context())+ }))++ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/", http.NoBody))++ headerID := rec.Header().Get(Header)+ assert.Equal(t, ctxID, headerID)+ assert.Regexp(t, "^req-eu-[a-z0-9]{14}$", headerID)+}++func TestMiddleware_HonorsInboundHeader(t *testing.T) {+ t.Parallel()++ handler := Middleware("req-")(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))++ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/", http.NoBody)+ req.Header.Set(Header, "req-us-abc123def45678")+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ assert.Equal(t, "req-us-abc123def45678", rec.Header().Get(Header))+}diff --git a/backend-go/internal/server/middlewares/timeout_test.go b/backend-go/internal/server/middlewares/timeout_test.goindex 8c219e9928..9056b376bd 100644--- a/backend-go/internal/server/middlewares/timeout_test.go+++ b/backend-go/internal/server/middlewares/timeout_test.go@@ -75,7 +75,7 @@ func TestTimeout_IncludesRequestID(t *testing.T) {// Chain requestid middleware before timeout middlewaretimeoutMiddleware := Timeout(10 * time.Millisecond)- wrapped := requestid.Middleware(timeoutMiddleware(handler))+ wrapped := requestid.Middleware("req-")(timeoutMiddleware(handler))req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/test", http.NoBody)req.Header.Set(requestid.Header, "test-request-123")diff --git a/backend-go/internal/server/server.go b/backend-go/internal/server/server.goindex abd2cc6db2..803c811ae8 100644--- a/backend-go/internal/server/server.go+++ b/backend-go/internal/server/server.go@@ -53,7 +53,7 @@ func (s *Server) Listen(ctx context.Context, addr string, wg *sync.WaitGroup, erhandler = middlewares.CORS(s.buildCORSConfig())(handler)handler = middlewares.SecurityHeaders(handler)handler = middlewares.Recoverer(s.logger)(handler)- handler = requestid.Middleware(handler)+ handler = requestid.Middleware(requestid.OriginPrefix(s.config.InfisicalCloud, s.config.InternalRegion))(handler)srv := &http.Server{Addr: addr,diff --git a/backend/src/server/app.ts b/backend/src/server/app.tsindex 0661affe0c..3cc47e4c55 100644--- a/backend/src/server/app.ts+++ b/backend/src/server/app.ts@@ -72,10 +72,17 @@ export const main = async ({}: TMain) => {const appCfg = getConfig();+ // Infisical Cloud request IDs carry a region segment (req-us-, req-eu-) so an ID's+ // origin is identifiable at a glance; self-hosted and dedicated stay bare req-.+ let requestIdOrigin = "";+ if (appCfg.INFISICAL_CLOUD) {+ requestIdOrigin = appCfg.INTERNAL_REGION === "eu" ? "eu-" : "us-";+ }+const server = fastify({// eslint-disable-next-line @typescript-eslint/no-explicit-any...(appCfg.NODE_ENV === "test" ? { logger: false } : { loggerInstance: logger }),- genReqId: () => `req-${alphaNumericNanoId(14)}`,+ genReqId: () => `req-${requestIdOrigin}${alphaNumericNanoId(14)}`,// When TRUSTED_PROXY_CIDRS is configured, only requests from those sources have their// forwarded-IP headers honored. Unset preserves legacy behavior (trust all) for backcompat.trustProxy: appCfg.TRUSTED_PROXY_CIDRS ?? true,