A Core sign-in, and a posting account's or Search Console's OAuth sign-in, now sets a short-lived cookie whose hash the flow keeps on the server. The callback refuses one without it (constant-time compare), clears the cookie either way, and the flow is used up regardless. This stops login CSRF: a callback URL brought to another browser signs nobody in. The cookie uses the __Host- prefix over https, so its Path is "/". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
60 lines
2.0 KiB
Go
60 lines
2.0 KiB
Go
package web
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// A sign-in that finishes at a callback URL (the Core's, a posting
|
|
// account's) is tied to the browser that started it: a random cookie, of
|
|
// which the flow on the server keeps the hash. A callback brought to
|
|
// another browser (a link, an image) lacks the cookie and is refused, so
|
|
// nobody can be signed in as someone else, or have someone else's account
|
|
// connected, by opening a URL.
|
|
|
|
const (
|
|
coreFlowCookie = "sm_oidc"
|
|
oauthFlowCookie = "sm_oauth"
|
|
)
|
|
|
|
// The cookie's Path is "/": over https it has the __Host- prefix (so no
|
|
// other subdomain can set it), which browsers only take with Path "/".
|
|
// SameSite Lax: it must come back on the provider's top-level redirect.
|
|
|
|
// bindFlow sets the cookie and gives the hash for the flow to keep.
|
|
func (s *Server) bindFlow(w http.ResponseWriter, name string, ttl time.Duration) (string, error) {
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", err
|
|
}
|
|
v := base64.RawURLEncoding.EncodeToString(b)
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: s.cookieName(name), Value: v, Path: "/", MaxAge: int(ttl / time.Second),
|
|
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
|
})
|
|
return flowHash(v), nil
|
|
}
|
|
|
|
// flowFromThisBrowser says whether the request carries the cookie whose
|
|
// hash a flow kept, and clears the cookie either way.
|
|
func (s *Server) flowFromThisBrowser(w http.ResponseWriter, r *http.Request, name, hash string) bool {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: s.cookieName(name), Value: "", Path: "/", MaxAge: -1,
|
|
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
|
})
|
|
c, err := r.Cookie(s.cookieName(name))
|
|
if err != nil || c.Value == "" || hash == "" {
|
|
return false
|
|
}
|
|
return subtle.ConstantTimeCompare([]byte(flowHash(c.Value)), []byte(hash)) == 1
|
|
}
|
|
|
|
func flowHash(v string) string {
|
|
sum := sha256.Sum256([]byte(v))
|
|
return base64.RawURLEncoding.EncodeToString(sum[:])
|
|
}
|