fix: harden login session lifetime

This commit is contained in:
OpenClaw Agent
2026-09-22 04:39:10 +08:00
parent 2c8531d9b9
commit c37161db31
6 changed files with 73 additions and 28 deletions
+16 -8
View File
@@ -197,16 +197,24 @@ type jwtClaims struct {
jwt.StandardClaims
}
func NewToken(username string, _ int) (string, error) {
// CHFS v4 keeps the JWT itself valid for one year. session.timeout is
// retained as a compatibility configuration field, but it does not alter
// the JWT exp claim in the original implementation.
claims := jwtClaims{Acc: username, StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Add(365 * 24 * time.Hour).Unix()}}
func NewToken(username string, timeoutMinutes int, secrets ...string) (string, error) {
if timeoutMinutes <= 0 {
timeoutMinutes = 30
}
secret := jwtSecret
if len(secrets) > 0 && secrets[0] != "" {
secret = secrets[0]
}
claims := jwtClaims{Acc: username, StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Add(time.Duration(timeoutMinutes) * time.Minute).Unix()}}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(jwtSecret))
return token.SignedString([]byte(secret))
}
func GetAccFromToken(raw string) (string, error) {
func GetAccFromToken(raw string, secrets ...string) (string, error) {
secret := jwtSecret
if len(secrets) > 0 && secrets[0] != "" {
secret = secrets[0]
}
if raw == "" {
return "", fmt.Errorf("empty token")
}
@@ -215,7 +223,7 @@ func GetAccFromToken(raw string) (string, error) {
if t.Method != jwt.SigningMethodHS256 {
return nil, fmt.Errorf("unexpected signing method: %s", t.Method.Alg())
}
return []byte(jwtSecret), nil
return []byte(secret), nil
})
if err != nil || token == nil || !token.Valid {
if err == nil {
+28 -1
View File
@@ -1,6 +1,33 @@
package auth
import "testing"
import (
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v4"
)
func TestTokenUsesConfiguredSecretAndTimeout(t *testing.T) {
const secret = "test-secret"
before := time.Now().Add(2 * time.Minute).Unix()
raw, err := NewToken("alice", 2, secret)
if err != nil {
t.Fatal(err)
}
var claims jwtClaims
token, err := jwt.ParseWithClaims(raw, &claims, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil || !token.Valid {
t.Fatalf("token should validate with configured secret: %v", err)
}
if claims.ExpiresAt < before-1 || claims.ExpiresAt > before+1 {
t.Fatalf("unexpected expiration: %v", claims.ExpiresAt)
}
if _, err := GetAccFromToken(raw, "wrong-secret"); err == nil {
t.Fatal("token validated with wrong secret")
}
}
func TestMatchPath(t *testing.T) {
cases := []struct {