-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.go
More file actions
368 lines (332 loc) · 9.94 KB
/
builder.go
File metadata and controls
368 lines (332 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package crum
import (
"errors"
"net/http"
"strings"
"time"
"unicode/utf8"
)
// CookieBuilder constructs a validated *http.Cookie with secure defaults.
// Zero values are not useful; always start with New(name, value).
type CookieBuilder struct {
name string
value string
path string
domain string
expires *time.Time
maxAge *int
secure *bool
httpOnly *bool
sameSite *http.SameSite
partition *bool
now func() time.Time
errs []error
}
// NewCookie provides a small builder for constructing and validating *http.Cookie values with secure defaults.
//
// Defaults (unless overridden):
// - Path: "/" (scopes cookie site-wide)
// - Secure: true (HTTPS only)
// - HttpOnly: true (inaccessible to JS, mitigates XSS exfiltration)
// - SameSite: http.SameSiteLaxMode (mitigates CSRF while preserving typical flows)
// - Session cookie: yes (no Expires/MaxAge unless TTL/MaxAge is set)
//
// Notes
// - RFC 6265 validation: we enforce a strict cookie-name token and forbid
// disallowed value bytes (control chars, semicolons, commas, backslashes).
// - SameSite=None requires Secure=true (enforced).
// - MaxAge semantics (Go http.Cookie):
// MaxAge < 0 => instructs deletion immediately
// MaxAge == 0 => not present in Set-Cookie (i.e., session cookie)
// MaxAge > 0 => persistent cookie with that lifetime in seconds
// - Use Delete() to emit a cookie that removes the stored value on clients.
// - The builder is not goroutine-safe; build per request.
// - If you need non-ASCII values, URL-encode or base64-encode them first.
//
// Example (session cookie):
//
// cb := crum.NewCookie("sid", sessionID).
// Domain("example.com").
// SameSiteLax(). // default, can be omitted
// MustBuild()
//
// Example (persistent login cookie, 30 days):
//
// cb := crum.NewCookie("remember", token).
// TTL(30 * 24 * time.Hour).
// SameSiteStrict().
// MustBuild()
//
// Example (cross-site, third-party flow where needed):
//
// cb := crum.NewCookie("cs", v).
// SameSiteNone(). // will also enforce Secure(true)
// TTL(24*time.Hour).
// MustBuild()
func NewCookie(name, value string) *CookieBuilder {
secure := true
httpOnly := true
ss := http.SameSiteLaxMode
return &CookieBuilder{
name: name,
value: value,
path: "/",
secure: &secure,
httpOnly: &httpOnly,
sameSite: &ss,
now: time.Now,
}
}
// FromCookie constructs a new Builder prepopulated from an existing *http.Cookie.
//
// It copies all mutable fields (Name, Value, Path, Domain, Secure, HttpOnly,
// SameSite, Expires, MaxAge, Partitioned if supported). The returned Builder can
// then be modified further (e.g., Delete(), TTL(), Domain(), etc.).
//
// Useful for transforming or revoking cookies already set by your system:
//
// newC := crum.FromCookie(c).Delete().MustBuild()
//
// The original cookie is never mutated.
func FromCookie(c *http.Cookie) *CookieBuilder {
if c == nil {
return NewCookie("", "")
}
b := &CookieBuilder{
name: c.Name,
value: c.Value,
path: c.Path,
domain: c.Domain,
now: time.Now,
}
if !c.Expires.IsZero() {
exp := c.Expires.UTC().Truncate(time.Second)
b.expires = &exp
}
if c.MaxAge != 0 {
m := c.MaxAge
b.maxAge = &m
}
b.secure = &c.Secure
b.httpOnly = &c.HttpOnly
ss := c.SameSite
b.sameSite = &ss
b.partition = &c.Partitioned
return b
}
// UnsafeValue allows setting an already-encoded value (e.g., URL/Base64).
// Values must be ASCII; control chars, semicolons, commas, and backslashes are rejected.
// Prefer encoding sensitive data before calling New/UnsafeValue.
func (b *CookieBuilder) UnsafeValue(v string) *CookieBuilder {
b.value = v
return b
}
// Path sets the cookie path. Empty becomes "/".
func (b *CookieBuilder) Path(p string) *CookieBuilder {
if strings.TrimSpace(p) == "" {
p = "/"
}
b.path = p
return b
}
// Domain sets the cookie domain. The leading dot is normalized away.
func (b *CookieBuilder) Domain(d string) *CookieBuilder {
d = strings.TrimPrefix(strings.TrimSpace(d), ".")
b.domain = d
return b
}
// Expires sets an absolute expiration time (also implies persistence).
// Prefer TTL() for relative lifetimes.
func (b *CookieBuilder) Expires(t time.Time) *CookieBuilder {
tt := t.UTC().Truncate(time.Second)
b.expires = &tt
// If MaxAge isn't already set, infer it from now() to produce consistent MaxAge/Expires.
if b.maxAge == nil {
sec := int(tt.Sub(b.now()).Seconds())
b.maxAge = &sec
}
return b
}
// TTL sets a relative lifetime. Sets both Expires and MaxAge coherently.
// TTL <= 0 results in a deletion cookie (MaxAge=-1, Expires in the past).
func (b *CookieBuilder) TTL(d time.Duration) *CookieBuilder {
if d <= 0 {
return b.Delete()
}
sec := int(d.Seconds())
exp := b.now().Add(d).UTC().Truncate(time.Second)
b.maxAge = &sec
b.expires = &exp
return b
}
// MaxAgeSeconds sets MaxAge directly. Use with care; prefer TTL() for coherence.
// MaxAge < 0 marks a deletion cookie; 0 yields a session cookie.
func (b *CookieBuilder) MaxAgeSeconds(s int) *CookieBuilder {
b.maxAge = &s
// If positive and Expires not set, synthesize Expires for wider client support:
if s > 0 && b.expires == nil {
exp := b.now().Add(time.Duration(s) * time.Second).UTC().Truncate(time.Second)
b.expires = &exp
}
// If zero, leave Expires unset (session cookie). If negative, set past Expires in Delete().
if s < 0 {
past := b.now().Add(-365 * 24 * time.Hour).UTC()
b.expires = &past
}
return b
}
// Session makes the cookie a session cookie (clears persistent attributes).
func (b *CookieBuilder) Session() *CookieBuilder {
b.maxAge = nil
b.expires = nil
return b
}
// Delete configures the cookie to remove itself from clients.
func (b *CookieBuilder) Delete() *CookieBuilder {
m := -1
past := b.now().Add(-365 * 24 * time.Hour).UTC()
b.maxAge = &m
b.expires = &past
// For deletion, also clear value by convention (servers differ; value may be ignored on delete).
b.value = ""
return b
}
// Secure toggles the Secure attribute (default true).
func (b *CookieBuilder) Secure(on bool) *CookieBuilder {
b.secure = &on
return b
}
// HttpOnly toggles the HttpOnly attribute (default true).
func (b *CookieBuilder) HttpOnly(on bool) *CookieBuilder {
b.httpOnly = &on
return b
}
// SameSiteStrict sets SameSite=Strict.
func (b *CookieBuilder) SameSiteStrict() *CookieBuilder {
ss := http.SameSiteStrictMode
b.sameSite = &ss
return b
}
// SameSiteLax sets SameSite=Lax (default).
func (b *CookieBuilder) SameSiteLax() *CookieBuilder {
ss := http.SameSiteLaxMode
b.sameSite = &ss
return b
}
// SameSiteNone sets SameSite=None and enforces Secure=true.
func (b *CookieBuilder) SameSiteNone() *CookieBuilder {
ss := http.SameSiteNoneMode
b.sameSite = &ss
// Enforce Secure per modern browsers; do not silently allow insecure None.
if b.secure == nil || !*b.secure {
on := true
b.secure = &on
}
return b
}
// WithClock injects a custom clock for testing (e.g., a fixed time).
func (b *CookieBuilder) WithClock(now func() time.Time) *CookieBuilder {
if now != nil {
b.now = now
}
return b
}
// Partitioned enables the Partitioned attribute.
func (b *CookieBuilder) Partitioned(on bool) *CookieBuilder {
b.partition = &on
return b
}
// Build returns a validated *http.Cookie or an error.
// It never panics; all constraints are returned as a single error via errors.Join.
func (b *CookieBuilder) Build() (*http.Cookie, error) {
b.errs = b.errs[:0]
if err := validateName(b.name); err != nil {
b.errs = append(b.errs, err)
}
if err := validateValue(b.value); err != nil {
b.errs = append(b.errs, err)
}
if b.domain != "" && !isASCII(b.domain) {
b.errs = append(b.errs, errors.New("cookie domain must be ASCII"))
}
if strings.ContainsAny(b.domain, " \t\r\n") {
b.errs = append(b.errs, errors.New("cookie domain must not contain whitespace"))
}
if b.sameSite != nil && *b.sameSite == http.SameSiteNoneMode {
if b.secure == nil || !*b.secure {
b.errs = append(b.errs, errors.New("SameSite=None requires Secure=true"))
}
}
if b.path == "" {
b.path = "/"
}
c := &http.Cookie{
Name: b.name,
Value: b.value,
Path: b.path,
Domain: b.domain,
Secure: derefOr(b.secure, true),
HttpOnly: derefOr(b.httpOnly, true),
SameSite: derefOr(b.sameSite, http.SameSiteLaxMode),
}
// Apply Expires/MaxAge as configured.
if b.expires != nil {
c.Expires = *b.expires
}
if b.maxAge != nil {
c.MaxAge = *b.maxAge
}
if b.partition != nil {
c.Partitioned = *b.partition
}
if len(b.errs) > 0 {
return nil, errors.Join(b.errs...)
}
return c, nil
}
// MustBuild is like Build but panics if validation fails.
// Useful in init-time configuration or tests where failing fast is desired.
func (b *CookieBuilder) MustBuild() *http.Cookie {
c, err := b.Build()
if err != nil {
panic(err)
}
return c
}
func derefOr[T any](in *T, def T) T {
if in == nil {
return def
}
return *in
}
func validateName(n string) error {
if n == "" {
return errors.New("cookie name must not be empty")
}
// RFC 6265 "token": 1*<any CHAR except CTLs or separators or whitespace or DEL>
// We enforce a conservative set: ASCII alnum and - _ . ~
for i := 0; i < len(n); i++ {
ch := n[i]
if (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '_' || ch == '.' || ch == '~' {
continue
}
return errors.New("cookie name contains invalid characters (allowed: A-Z a-z 0-9 - _ . ~)")
}
return nil
}
func validateValue(v string) error {
// RFC 6265 cookie-octet excludes CTLs, DQUOTE, COMMA, SEMICOLON, BACKSLASH, and non-ASCII.
if !isASCII(v) {
return errors.New("cookie value must be ASCII; encode it (e.g., URL-encode or base64)")
}
if strings.ContainsAny(v, "\";,\\\n\r\t") {
return errors.New("cookie value contains forbidden characters (\") (;) (,) (\\) or control chars")
}
return nil
}
func isASCII(s string) bool {
return utf8.ValidString(s) && !strings.ContainsFunc(s, func(r rune) bool { return r > 0x7F })
}