Skip to content

Commit add2ad0

Browse files
authored
Allow selective cookie exclusion in application proxies (#88)
Add `ExcludedCookies` to remove named cookies from application proxy requests while preserving application cookies and other headers. Controlcenter can use this to exclude `CF_Authorization` when Node handles public proxy traffic directly. Validation: full orchestrator race tests and the real-binary offchain integration test pass. Proxy coverage includes all URL modes, duplicate Cookie headers, and SSE/WebSocket requests; CLI/configuration checks and help golden are updated.
1 parent 2364436 commit add2ad0

7 files changed

Lines changed: 95 additions & 10 deletions

File tree

‎cmd/livepeer/testdata/cli/orchestrator-help.golden‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Flags:
2525
-r, --runner-service-url string Runner-facing base URL for callbacks and trickle; defaults to service-url (env: LIVEPEER_ORCHESTRATOR_RUNNER_SERVICE_URL)
2626
--proxy-url-template string Generated proxy URL with {proxy} in a hostname label or final path segment (env: LIVEPEER_ORCHESTRATOR_PROXY_URL_TEMPLATE)
2727
--excluded-headers strings Headers to remove from app requests; a trailing * matches a prefix (env: LIVEPEER_ORCHESTRATOR_EXCLUDED_HEADERS)
28+
--excluded-cookies strings Cookie names to remove from app requests; matching is case-sensitive (env: LIVEPEER_ORCHESTRATOR_EXCLUDED_COOKIES)
2829
--bootstrap-secret-file string File containing runner bootstrap credential (env: LIVEPEER_ORCHESTRATOR_BOOTSTRAP_SECRET_FILE)
2930
--runner-config string Static runner TOML path (env: LIVEPEER_ORCHESTRATOR_RUNNER_CONFIG)
3031
--redeemer-url string Remote winning-ticket redeemer base URL (env: LIVEPEER_ORCHESTRATOR_REDEEMER_URL)

‎configs/orchestrator/config.example.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ SessionProxyGrants = []
1717
HealthGrants = []
1818
# ProxyURLTemplate = "https://{proxy}.apps.example" # Default: ServiceURL/run/{proxy}.
1919
# ExcludedHeaders = ["CF-Access-*", "Cookie"] # Remove matching headers and all cookies from app requests.
20+
# To retain other cookies, omit "Cookie" from ExcludedHeaders.
21+
# ExcludedCookies = ["CF_Authorization"] # Remove only the named cookies from app requests.
2022

2123
# Paid operation requires an on-chain network, account password, RPC, face
2224
# value, winning probability, and one conversion source.

‎docs/orchestrator.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,10 @@ Client API requests use the Host from `APIOriginURL`, which defaults to
108108
HTTP(S) URL with the Host it sends, without a path.
109109

110110
To remove headers from app requests, set `ExcludedHeaders`, for example:
111-
`["CF-Access-*", "Cookie"]`. Matching is case-insensitive.
111+
`["CF-Access-*"]`. Matching is case-insensitive. To remove selected cookies while
112+
preserving other cookies, set `ExcludedCookies`, for example
113+
`["CF_Authorization"]`. Cookie names match exactly and are case-sensitive.
114+
Excluding the entire `Cookie` header still removes all cookies.
112115

113116
## Enable payments
114117

‎orchestrator/app.go‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ type Params struct {
4545
RunnerServiceURL boa.Text[*url.URL] `optional:"true" descr:"Runner-facing base URL for callbacks and trickle; defaults to service-url"`
4646
ProxyURLTemplate string `optional:"true" descr:"Generated proxy URL with {proxy} in a hostname label or final path segment"`
4747
ExcludedHeaders []string `optional:"true" descr:"Headers to remove from app requests; a trailing * matches a prefix"`
48+
ExcludedCookies []string `optional:"true" descr:"Cookie names to remove from app requests; matching is case-sensitive"`
4849
BootstrapSecret string `secret:"true" optional:"true" descr:"Dynamic runner bootstrap credential"`
4950
BootstrapSecretFile string `basepath:"source" secretfor:"BootstrapSecret" descr:"File containing runner bootstrap credential"`
5051
RunnerConfig string `basepath:"source" optional:"true" file:"true" descr:"Static runner TOML path"`
@@ -154,6 +155,9 @@ func (p Params) Validate() error {
154155
if err := validateExcludedHeaders(p.ExcludedHeaders); err != nil {
155156
return err
156157
}
158+
if err := validateExcludedCookies(p.ExcludedCookies); err != nil {
159+
return err
160+
}
157161
if !p.Listen.IsValid() || !p.MetricsListen.IsValid() {
158162
return errors.New("--listen and --metrics-listen require IP:port addresses")
159163
}
@@ -190,6 +194,15 @@ func (p Params) Validate() error {
190194
return nil
191195
}
192196

197+
func validateExcludedCookies(names []string) error {
198+
for _, name := range names {
199+
if err := (&http.Cookie{Name: name}).Valid(); err != nil {
200+
return fmt.Errorf("invalid --excluded-cookies entry %q: %w", name, err)
201+
}
202+
}
203+
return nil
204+
}
205+
193206
func validateExcludedHeaders(patterns []string) error {
194207
for _, pattern := range patterns {
195208
name := strings.TrimSuffix(pattern, "*")
@@ -268,8 +281,8 @@ func printConfig(ctx *boa.HookContext, p *Params, out io.Writer) error {
268281
values := map[string]any{
269282
"Network": &p.Network, "Account": &p.Account, "OrchestratorAddress": &p.OrchestratorAddress,
270283
"Listen": &p.Listen, "MetricsListen": &p.MetricsListen,
271-
"ExcludedHeaders": &p.ExcludedHeaders,
272-
"RunnerGrants": &p.RunnerGrants, "SessionProxyGrants": &p.SessionProxyGrants, "HealthGrants": &p.HealthGrants,
284+
"ExcludedHeaders": &p.ExcludedHeaders, "ExcludedCookies": &p.ExcludedCookies,
285+
"RunnerGrants": &p.RunnerGrants, "SessionProxyGrants": &p.SessionProxyGrants, "HealthGrants": &p.HealthGrants,
273286
"HeartbeatInterval": &p.HeartbeatInterval, "HeartbeatTTL": &p.HeartbeatTTL,
274287
"DrainTimeout": &p.DrainTimeout,
275288
"RedeemerTxTimeout": &p.RedeemerTxTimeout, "RedeemerMaxTxReplacements": &p.RedeemerMaxTxReplacements,
@@ -416,6 +429,7 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) {
416429
app.apiOrigin = p.APIOriginURL.Value
417430
}
418431
app.setExcludedHeaders(p.ExcludedHeaders)
432+
app.excludedCookies = p.ExcludedCookies
419433
logger = app.logger
420434
if engine != nil {
421435
registry.metrics.PaymentObserver(observedChain.Observer, logger)

‎orchestrator/app_test.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,25 @@ func TestExcludedHeadersEnvironmentAndFlag(t *testing.T) {
307307
}
308308
}
309309

310+
func TestExcludedCookiesEnvironmentAndFlag(t *testing.T) {
311+
t.Setenv("LIVEPEER_ORCHESTRATOR_EXCLUDED_COOKIES", "CF_Authorization")
312+
for _, args := range [][]string{nil, {"--excluded-cookies", "ingress_session"}} {
313+
output, err := execute(t, append([]string{"--config", "", "--print-config"}, args...)...)
314+
require.NoError(t, err)
315+
var printed Params
316+
require.NoError(t, toml.Unmarshal([]byte(output), &printed))
317+
want := []string{"CF_Authorization"}
318+
if len(args) > 0 {
319+
want = []string{"ingress_session"}
320+
}
321+
require.Equal(t, want, printed.ExcludedCookies)
322+
}
323+
require.NoError(t, validateExcludedCookies([]string{"CF_Authorization", "session-v1"}))
324+
for _, name := range []string{"", "bad name", "name=value", "name;other", "name\r\n", "é"} {
325+
require.ErrorContains(t, validateExcludedCookies([]string{name}), "--excluded-cookies")
326+
}
327+
}
328+
310329
func TestExcludedHeadersValidation(t *testing.T) {
311330
require.NoError(t, validateExcludedHeaders(nil))
312331
require.NoError(t, validateExcludedHeaders([]string{"CF-Access-*", "Cookie", "X-Exact", "X_Valid!#$%&'+-.^`|~"}))

‎orchestrator/http.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"net/http"
1313
"net/http/httputil"
1414
"net/url"
15+
"slices"
1516
"strings"
1617
"sync"
1718
"time"
@@ -35,6 +36,7 @@ type Server struct {
3536
runnerTransport *http.Transport
3637
proxyTransport *http.Transport
3738
excludedHeaders []string
39+
excludedCookies []string
3840
logger *slog.Logger
3941
payment *PaymentEngine
4042
mux *http.ServeMux
@@ -190,6 +192,37 @@ func (s *Server) setExcludedHeaders(patterns []string) {
190192
s.proxyTransport.DisableCompression = disableCompression
191193
}
192194

195+
// Preserve application cookie bytes instead of parsing and reserializing values.
196+
func excludeCookies(header http.Header, names []string) {
197+
if len(names) == 0 {
198+
return
199+
}
200+
for field, values := range header {
201+
if !strings.EqualFold(field, "Cookie") {
202+
continue
203+
}
204+
filtered := make([]string, 0, len(values))
205+
for _, value := range values {
206+
parts := strings.Split(value, ";")
207+
kept := parts[:0]
208+
for _, part := range parts {
209+
name, _, _ := strings.Cut(part, "=")
210+
if strings.TrimSpace(part) != "" && !slices.Contains(names, strings.TrimSpace(name)) {
211+
kept = append(kept, part)
212+
}
213+
}
214+
if value := strings.TrimSpace(strings.Join(kept, ";")); value != "" {
215+
filtered = append(filtered, value)
216+
}
217+
}
218+
if len(filtered) == 0 {
219+
delete(header, field)
220+
} else {
221+
header[field] = filtered
222+
}
223+
}
224+
}
225+
193226
func headerExcluded(name string, patterns []string) bool {
194227
for _, pattern := range patterns {
195228
if prefix, ok := strings.CutSuffix(pattern, "*"); ok {
@@ -540,6 +573,7 @@ func (s *Server) proxy(w http.ResponseWriter, r *http.Request, transport http.Ro
540573
req.Out.Header.Set("Livepeer-Session-Id", sid)
541574
req.Out.Header.Set("Livepeer-Session-Token", token)
542575
req.Out.Header.Set("Livepeer-Session-Control", control)
576+
excludeCookies(req.Out.Header, s.excludedCookies)
543577
for name := range req.Out.Header {
544578
if headerExcluded(name, s.excludedHeaders) {
545579
delete(req.Out.Header, name)

‎orchestrator/http_test.go‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -171,12 +171,14 @@ func TestProxyExcludedHeaders(t *testing.T) {
171171
policy, err := destination.New("runner", []string{strings.TrimPrefix(upstream.URL, "http://")})
172172
require.NoError(t, err)
173173
for _, template := range []string{"", "https://{proxy}.apps.example", "https://orch.example/custom/{proxy}"} {
174-
for _, patterns := range [][]string{
175-
nil,
176-
{"cF-aCCess-*", "x-ingress-token", "cOOkie", "accept-encoding", "user-agent"},
177-
{"CF-Access-*", "X-Ingress-Token", "Cookie", "Accept-*", "User-*"},
174+
for _, excluded := range []struct{ headers, cookies []string }{
175+
{},
176+
{headers: []string{"cF-aCCess-*", "x-ingress-token", "cOOkie", "accept-encoding", "user-agent"}},
177+
{headers: []string{"CF-Access-*", "X-Ingress-Token", "Cookie", "Accept-*", "User-*"}},
178+
{cookies: []string{"CF_Authorization"}},
178179
} {
179-
t.Run(fmt.Sprintf("template=%s/excluded=%v", template, patterns), func(t *testing.T) {
180+
patterns := excluded.headers
181+
t.Run(fmt.Sprintf("template=%s/headers=%v/cookies=%v", template, patterns, excluded.cookies), func(t *testing.T) {
180182
registry := NewRegistry("secret", "https://orch.example", time.Second, time.Minute)
181183
registry.proxyTemplate = template
182184
for _, mode := range []string{"persistent", "single-shot"} {
@@ -185,6 +187,7 @@ func TestProxyExcludedHeaders(t *testing.T) {
185187
server := NewServer(registry, policy, policy, slog.New(slog.NewTextHandler(io.Discard, nil)))
186188
defer server.Close()
187189
server.setExcludedHeaders(patterns)
190+
server.excludedCookies = excluded.cookies
188191
sid, runnerProxy, _, _, err := registry.Reserve("persistent")
189192
require.NoError(t, err)
190193
target, token, _, err := registry.sessionTarget("persistent", sid)
@@ -221,7 +224,15 @@ func TestProxyExcludedHeaders(t *testing.T) {
221224
var received http.Header
222225
require.NoError(t, json.Unmarshal(record.Body.Bytes(), &received))
223226
for _, name := range []string{"Cf-Access-Jwt-Assertion", "Cf-Access-Client-Id", "X-Ingress-Token", "Cookie", "Accept-Encoding", "User-Agent"} {
224-
if len(patterns) > 0 {
227+
if name == "Cookie" && len(excluded.cookies) > 0 {
228+
var cookies []string
229+
for _, value := range received.Values("Cookie") {
230+
for _, cookie := range strings.Split(value, ";") {
231+
cookies = append(cookies, strings.TrimSpace(cookie))
232+
}
233+
}
234+
require.ElementsMatch(t, []string{"app=one", "app=two", "cf_authorization=another", "other=three"}, cookies)
235+
} else if len(patterns) > 0 {
225236
require.Empty(t, received.Values(name), path+": "+name)
226237
} else {
227238
require.NotEmpty(t, received.Values(name), path+": "+name)
@@ -277,7 +288,8 @@ func TestSessionProxyStreamsSSEAndWebSocket(t *testing.T) {
277288
_, _, err = registry.Heartbeat(registration, registered.HeartbeatSecret)
278289
require.NoError(t, err)
279290
app := NewServer(registry, policy, policy, slog.New(slog.NewTextHandler(io.Discard, nil)))
280-
app.setExcludedHeaders([]string{"CF-Access-*", "Cookie"})
291+
app.setExcludedHeaders([]string{"CF-Access-*"})
292+
app.excludedCookies = []string{"CF_Authorization"}
281293
defer app.Close()
282294
server := httptest.NewServer(app)
283295
app.apiOrigin = mustURL(t, server.URL)

0 commit comments

Comments
 (0)