Skip to content

Commit

Permalink
reverseproxy: add Max-Age option to sticky cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonYuan869 committed Jun 14, 2024
1 parent aca4002 commit 568f304
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions modules/caddyhttp/reverseproxy/selectionpolicies.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"strconv"
"strings"
"sync/atomic"
"time"

"github.com/cespare/xxhash/v2"

Expand Down Expand Up @@ -613,6 +614,8 @@ type CookieHashSelection struct {
Name string `json:"name,omitempty"`
// Secret to hash (Hmac256) chosen upstream in cookie
Secret string `json:"secret,omitempty"`
// The cookie's Max-Age before it expires. Default is no expiry.
MaxAge caddy.Duration `json:"max_age,omitempty"`

// The fallback policy to use if the cookie is not present. Defaults to `random`.
FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
Expand Down Expand Up @@ -671,6 +674,9 @@ func (s CookieHashSelection) Select(pool UpstreamPool, req *http.Request, w http
cookie.Secure = true
cookie.SameSite = http.SameSiteNoneMode
}
if s.MaxAge > 0 {
cookie.MaxAge = int(time.Duration(s.MaxAge).Seconds())
}
http.SetCookie(w, cookie)
return upstream
}
Expand Down Expand Up @@ -699,8 +705,10 @@ func (s CookieHashSelection) Select(pool UpstreamPool, req *http.Request, w http
//
// lb_policy cookie [<name> [<secret>]] {
// fallback <policy>
// [max_age <duration>]
// }
//
// `max_age` is a positive (non-zero) `caddy.Duration`
// By default name is `lb`
func (s *CookieHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
args := d.RemainingArgs()
Expand Down Expand Up @@ -728,6 +736,24 @@ func (s *CookieHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
return err
}
s.FallbackRaw = mod
case "max_age":
if !d.NextArg() {
return d.ArgErr()
}
if s.MaxAge != 0 {
return d.Err("cookie max_age already specified")
}
maxAge, err := caddy.ParseDuration(d.Val())
if err != nil {
return d.Errf("invalid duration: %s", d.Val())
}
if maxAge <= 0 {
return d.Errf("invalid duration: %s, max_age should be non-zero and positive", d.Val())
}
if d.NextArg() {
return d.ArgErr()
}
s.MaxAge = caddy.Duration(maxAge)
default:
return d.Errf("unrecognized option '%s'", d.Val())
}
Expand Down

0 comments on commit 568f304

Please sign in to comment.