mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
fix(dashboard): refresh the token proxy session cookie
securecookie encodes sessions with gob, so the issued and expires times come back as int64. The refresh looked for a float64, found none and never fired, so --cookie-refresh=1h, which the chart sets, did nothing. The times are now read in either form. A refreshed cookie keeps the token's expiry: it gets a new issued time and a fresh securecookie timestamp, never a longer life than the token inside it. Encoding a session fails when it outgrows securecookie's maximum length, which a large token can reach. Sign-in set an empty cookie in that case, and the refresh, now that it runs, would have replaced a working cookie with an empty one. Sign-in now shows an error instead, and a refresh that cannot encode leaves the current cookie in place. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
2 files changed
+242
-56
No files matched your search
@@ -429,6 +429,75 @@ func encodeSession(sc *securecookie.SecureCookie, token string, exp, issued int6
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// decodeSession reads the token and session out of a cookie value. Without a
|
||||
// cookie secret the value is the bare token.
|
||||
func decodeSession(sc *securecookie.SecureCookie, value string, now time.Time) (string, map[string]any, error) {
|
||||
if sc == nil {
|
||||
return value, map[string]any{
|
||||
"expires": now.Add(24 * time.Hour).Unix(),
|
||||
"issued": now.Unix(),
|
||||
}, nil
|
||||
}
|
||||
var sess map[string]any
|
||||
if err := sc.Decode(cookieName, value, &sess); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
token, _ := sess["access_token"].(string)
|
||||
return token, sess, nil
|
||||
}
|
||||
|
||||
// sessionCookie builds the cookie that carries a session until the token
|
||||
// expires.
|
||||
func sessionCookie(sc *securecookie.SecureCookie, token string, exp, issued int64) (*http.Cookie, error) {
|
||||
enc, err := encodeSession(sc, token, exp, issued)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: enc,
|
||||
Path: "/",
|
||||
Expires: time.Unix(exp, 0),
|
||||
Secure: cookieSecure,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// refreshedCookie re-issues the session cookie once it is older than refresh,
|
||||
// keeping the token's expiry. It returns nil when no refresh is due.
|
||||
func refreshedCookie(sc *securecookie.SecureCookie, token string, sess map[string]any, refresh time.Duration, now time.Time) *http.Cookie {
|
||||
if refresh <= 0 {
|
||||
return nil
|
||||
}
|
||||
issued, ok := unixSeconds(sess["issued"])
|
||||
if !ok || now.Sub(time.Unix(issued, 0)) <= refresh {
|
||||
return nil
|
||||
}
|
||||
expires, ok := unixSeconds(sess["expires"])
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
c, err := sessionCookie(sc, token, expires, now.Unix())
|
||||
if err != nil {
|
||||
log.Printf("session refresh skipped: %v", err)
|
||||
return nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// unixSeconds reads a session time. The default gob encoding of securecookie
|
||||
// returns the int64 it was given; its JSON encoder would return a float64.
|
||||
func unixSeconds(v any) (int64, bool) {
|
||||
switch n := v.(type) {
|
||||
case int64:
|
||||
return n, true
|
||||
case float64:
|
||||
return int64(n), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
/* ----------------------------- main ------------------------------------- */
|
||||
|
||||
func main() {
|
||||
@@ -498,16 +567,13 @@ func main() {
|
||||
if expTime, ok := verifiedToken.Expiration(); ok && !expTime.IsZero() {
|
||||
exp = expTime.Unix()
|
||||
}
|
||||
session, _ := encodeSession(sc, token, exp, time.Now().Unix())
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: session,
|
||||
Path: "/",
|
||||
Expires: time.Unix(exp, 0),
|
||||
Secure: cookieSecure,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
c, err := sessionCookie(sc, token, exp, time.Now().Unix())
|
||||
if err != nil {
|
||||
log.Printf("session cookie: %v", err)
|
||||
_ = loginTmpl.Execute(w, newLoginData(signIn, "Could not store the session", brandingConfigPath))
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
})
|
||||
@@ -534,20 +600,10 @@ func main() {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var token string
|
||||
var sess map[string]any
|
||||
if sc != nil {
|
||||
if err := sc.Decode(cookieName, c.Value, &sess); err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
token, _ = sess["access_token"].(string)
|
||||
} else {
|
||||
token = c.Value
|
||||
sess = map[string]any{
|
||||
"expires": time.Now().Add(24 * time.Hour).Unix(),
|
||||
"issued": time.Now().Unix(),
|
||||
}
|
||||
token, sess, err := decodeSession(sc, c.Value, time.Now())
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Re-verify the token to ensure it's still valid
|
||||
@@ -608,42 +664,14 @@ func main() {
|
||||
http.Redirect(w, r, signIn, http.StatusFound)
|
||||
return
|
||||
}
|
||||
var token string
|
||||
var sess map[string]any
|
||||
if sc != nil {
|
||||
if err := sc.Decode(cookieName, c.Value, &sess); err != nil {
|
||||
http.Redirect(w, r, signIn, http.StatusFound)
|
||||
return
|
||||
}
|
||||
token, _ = sess["access_token"].(string)
|
||||
} else {
|
||||
token = c.Value
|
||||
sess = map[string]any{
|
||||
"expires": time.Now().Add(24 * time.Hour).Unix(),
|
||||
"issued": time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
if token == "" {
|
||||
token, sess, err := decodeSession(sc, c.Value, time.Now())
|
||||
if err != nil || token == "" {
|
||||
http.Redirect(w, r, signIn, http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
// cookie refresh
|
||||
if cookieRefresh > 0 {
|
||||
if issued, ok := sess["issued"].(float64); ok {
|
||||
if time.Since(time.Unix(int64(issued), 0)) > cookieRefresh {
|
||||
enc, _ := encodeSession(sc, token, int64(sess["expires"].(float64)), time.Now().Unix())
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: enc,
|
||||
Path: "/",
|
||||
Expires: time.Unix(int64(sess["expires"].(float64)), 0),
|
||||
Secure: cookieSecure,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
}
|
||||
if rc := refreshedCookie(sc, token, sess, cookieRefresh, time.Now()); rc != nil {
|
||||
http.SetCookie(w, rc)
|
||||
}
|
||||
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/securecookie"
|
||||
)
|
||||
|
||||
func testCodec() *securecookie.SecureCookie {
|
||||
return securecookie.New([]byte("0123456789abcdef0123456789abcdef"), nil)
|
||||
}
|
||||
|
||||
// The handlers read the session back with sc.Decode; the field types they
|
||||
// get decide whether their type assertions hold.
|
||||
func TestEncodeSessionRoundTrip(t *testing.T) {
|
||||
sc := testCodec()
|
||||
enc, err := encodeSession(sc, "tok", 2000, 1000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var sess map[string]any
|
||||
if err := sc.Decode(cookieName, enc, &sess); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if sess["access_token"] != "tok" {
|
||||
t.Errorf("access_token = %v", sess["access_token"])
|
||||
}
|
||||
if sess["expires"] != int64(2000) || sess["issued"] != int64(1000) {
|
||||
t.Errorf("expires, issued = %#v, %#v; want int64 2000, 1000", sess["expires"], sess["issued"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeSessionWithoutSecretIsTheBareToken(t *testing.T) {
|
||||
enc, err := encodeSession(nil, "tok", 2000, 1000)
|
||||
if err != nil || enc != "tok" {
|
||||
t.Fatalf("encodeSession(nil) = %q, %v; want the token", enc, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieRejectsTampering(t *testing.T) {
|
||||
sc := testCodec()
|
||||
enc, err := encodeSession(sc, "tok", 2000, 1000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := []byte(enc)
|
||||
b[len(b)/2] ^= 1
|
||||
var sess map[string]any
|
||||
if err := sc.Decode(cookieName, string(b), &sess); err == nil {
|
||||
t.Fatalf("tampered cookie decoded: %v", sess)
|
||||
}
|
||||
other := securecookie.New([]byte("fedcba9876543210fedcba9876543210"), nil)
|
||||
if err := other.Decode(cookieName, enc, &sess); err == nil {
|
||||
t.Fatal("cookie signed with another secret decoded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieRejectsExpiredTimestamp(t *testing.T) {
|
||||
enc, err := encodeSession(testCodec(), "tok", 2000, 1000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A negative max age makes every timestamp too old.
|
||||
var sess map[string]any
|
||||
if err := testCodec().MaxAge(-1).Decode(cookieName, enc, &sess); err == nil {
|
||||
t.Fatal("expired cookie decoded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeSessionWithoutSecretTakesTheBareToken(t *testing.T) {
|
||||
now := time.Unix(5000, 0)
|
||||
token, sess, err := decodeSession(nil, "tok", now)
|
||||
if err != nil || token != "tok" {
|
||||
t.Fatalf("decodeSession(nil) = %q, %v", token, err)
|
||||
}
|
||||
if sess["issued"] != now.Unix() || sess["expires"] != now.Add(24*time.Hour).Unix() {
|
||||
t.Errorf("session = %v", sess)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeSessionRejectsForgedCookie(t *testing.T) {
|
||||
if _, _, err := decodeSession(testCodec(), "tok", time.Now()); err == nil {
|
||||
t.Fatal("a bare token decoded as a signed session")
|
||||
}
|
||||
}
|
||||
|
||||
func signedSession(t *testing.T, sc *securecookie.SecureCookie, expires, issued time.Time) (string, map[string]any) {
|
||||
t.Helper()
|
||||
enc, err := encodeSession(sc, "tok", expires.Unix(), issued.Unix())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, sess, err := decodeSession(sc, enc, issued)
|
||||
if err != nil || token != "tok" {
|
||||
t.Fatalf("decodeSession = %q, %v", token, err)
|
||||
}
|
||||
return token, sess
|
||||
}
|
||||
|
||||
// A refreshed cookie gets a new issued time and keeps the token's expiry, so
|
||||
// refreshing never lets the cookie outlive the token.
|
||||
func TestRefreshedCookieReissuesASignedSessionUntilTokenExpiry(t *testing.T) {
|
||||
sc := testCodec()
|
||||
now := time.Now()
|
||||
expires := now.Add(time.Hour)
|
||||
token, sess := signedSession(t, sc, expires, now.Add(-2*time.Hour))
|
||||
|
||||
c := refreshedCookie(sc, token, sess, time.Hour, now)
|
||||
if c == nil {
|
||||
t.Fatal("refreshedCookie = nil for a session older than the refresh interval")
|
||||
}
|
||||
if c.Expires.Unix() != expires.Unix() {
|
||||
t.Errorf("cookie Expires = %v, want the token expiry %v", c.Expires, expires)
|
||||
}
|
||||
if c.Name != cookieName || c.Path != "/" || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode {
|
||||
t.Errorf("cookie = %+v, want %s on / HttpOnly SameSite=Lax", c, cookieName)
|
||||
}
|
||||
_, got, err := decodeSession(sc, c.Value, now)
|
||||
if err != nil {
|
||||
t.Fatalf("decode refreshed cookie: %v", err)
|
||||
}
|
||||
if got["issued"] != now.Unix() || got["expires"] != expires.Unix() {
|
||||
t.Errorf("refreshed session = %v, want issued %d and expires %d", got, now.Unix(), expires.Unix())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshedCookieWaitsForTheInterval(t *testing.T) {
|
||||
sc := testCodec()
|
||||
now := time.Now()
|
||||
token, sess := signedSession(t, sc, now.Add(time.Hour), now.Add(-30*time.Minute))
|
||||
if c := refreshedCookie(sc, token, sess, time.Hour, now); c != nil {
|
||||
t.Errorf("refreshed a session younger than the interval: %+v", c)
|
||||
}
|
||||
token, sess = signedSession(t, sc, now.Add(time.Hour), now.Add(-2*time.Hour))
|
||||
if c := refreshedCookie(sc, token, sess, 0, now); c != nil {
|
||||
t.Errorf("refreshed with refresh disabled: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
// securecookie refuses a value longer than its MaxLength, which a large token
|
||||
// reaches; no half-written cookie may come out of that.
|
||||
func TestSessionCookieReportsAnEncodingFailure(t *testing.T) {
|
||||
sc := testCodec().MaxLength(64)
|
||||
if c, err := sessionCookie(sc, strings.Repeat("t", 512), time.Now().Add(time.Hour).Unix(), time.Now().Unix()); err == nil {
|
||||
t.Fatalf("sessionCookie = %+v, want an error", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshedCookieSkipsASessionItCannotEncode(t *testing.T) {
|
||||
now := time.Now()
|
||||
token, sess := signedSession(t, testCodec(), now.Add(time.Hour), now.Add(-2*time.Hour))
|
||||
if c := refreshedCookie(testCodec().MaxLength(64), token, sess, time.Hour, now); c != nil {
|
||||
t.Fatalf("refreshedCookie = %+v, want nil when the session cannot be encoded", c)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user