-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsrf.go
More file actions
68 lines (55 loc) · 1.63 KB
/
Copy pathcsrf.go
File metadata and controls
68 lines (55 loc) · 1.63 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
package openlane
import (
"context"
"github.com/theopenlane/httpsling"
)
const (
csrfHeader = "X-CSRF-Token"
csrfCookie = "ol.csrf-token" // this should match the cookie name in the server config
csrfPath = "/livez"
)
// InitCSRF fetches a CSRF token and sets it on the client for subsequent
// requests. It returns an error if the token cannot be obtained.
func (c *Client) InitCSRF(ctx context.Context) (string, error) {
token, err := c.fetchCSRFToken(ctx)
if err != nil {
return "", err
}
return token, nil
}
// fetchCSRFToken performs a safe request to retrieve the CSRF cookie value.
func (c *Client) fetchCSRFToken(ctx context.Context) (string, error) {
if c.HTTPSlingRequester().CookieJar() == nil {
return "", ErrNoCookieJarSet
}
// make a GET request to acquire the CSRF cookie
resp, err := c.HTTPSlingRequester().ReceiveWithContext(ctx, nil, httpsling.Get(csrfPath))
if err != nil {
return "", err
}
if resp != nil {
resp.Body.Close()
}
return c.getCSRFToken()
}
// getCSRFToken retrieves the CSRF token from the cookie jar
// and returns it. If the token is not found or is empty, it returns an error.
// if it doesn't exist, it returns an empty string without an error.
// this is used for cases where CSRF protection is not enabled.
func (c *Client) getCSRFToken() (string, error) {
cookies, err := c.Cookies()
if err != nil {
return "", err
}
for _, ck := range cookies {
if ck.Name == csrfCookie {
if ck.Value == "" {
return "", ErrEmptyCSRFToken
}
return ck.Value, nil
}
}
// do not return an error, if CSRF protection is not enabled
// there may not be a CSRF cookie set
return "", nil
}