фронт и secure browser session

This commit is contained in:
2026-10-23 14:48:57 +03:00
parent bd28f1ae26
commit 34618bd423
43 changed files with 5374 additions and 28 deletions
+29 -9
View File
@@ -16,9 +16,10 @@ type Config struct {
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
CursorSigningKey string
SessionTTL time.Duration
IdempotencyTTL time.Duration
SessionCookieSecure bool
CursorSigningKey string
DatabaseURL string
DatabaseMaxConns int32
@@ -60,6 +61,10 @@ func Load() (Config, error) {
return Config{}, err
}
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
@@ -181,12 +186,13 @@ func Load() (Config, error) {
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
CursorSigningKey: cursorSigningKey,
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
SessionCookieSecure: sessionCookieSecure,
CursorSigningKey: cursorSigningKey,
DatabaseURL: databaseURL,
DatabaseMaxConns: databaseMaxConns,
@@ -345,6 +351,20 @@ func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
return int32(value), nil
}
func boolFromEnv(name string, fallback bool) (bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("%s must be true or false: %w", name, err)
}
return value, nil
}
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
+29
View File
@@ -0,0 +1,29 @@
package config
import "testing"
func TestBoolFromEnv(t *testing.T) {
t.Run("fallback", func(t *testing.T) {
t.Setenv("TEST_BOOL", "")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || !value {
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
}
})
t.Run("explicit false", func(t *testing.T) {
t.Setenv("TEST_BOOL", "false")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || value {
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
}
})
t.Run("invalid", func(t *testing.T) {
t.Setenv("TEST_BOOL", "sometimes")
_, err := boolFromEnv("TEST_BOOL", false)
if err == nil {
t.Fatal("boolFromEnv() error = nil, want validation error")
}
})
}
@@ -15,5 +15,6 @@ func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) {
"service is temporarily unavailable", requestID)
return
}
h.clearSessionCookie(w)
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
}
+10 -3
View File
@@ -30,9 +30,10 @@ type ReadinessChecker interface {
type Option func(*Handler)
type Handler struct {
service *application.Service
readinessChecker ReadinessChecker
readinessTimeout time.Duration
service *application.Service
readinessChecker ReadinessChecker
readinessTimeout time.Duration
sessionCookieSecure bool
}
func NewHandler(
@@ -61,6 +62,12 @@ func WithReadiness(
}
}
func WithSessionCookieSecure(secure bool) Option {
return func(handler *Handler) {
handler.sessionCookieSecure = secure
}
}
func decodeJSON(r *http.Request, destination any) error {
mediaType, parameters, err := mime.ParseMediaType(
r.Header.Get("Content-Type"),
@@ -0,0 +1,39 @@
package handlers
import (
"net/http"
"time"
)
const sessionCookieName = "mtusi_session"
func (h *Handler) setSessionCookie(
w http.ResponseWriter,
token string,
expiresAt time.Time,
) {
maxAge := int(time.Until(expiresAt).Seconds())
if maxAge < 1 {
maxAge = 1
}
h.writeSessionCookie(w, token, expiresAt, maxAge)
}
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
}
func (h *Handler) writeSessionCookie(
w http.ResponseWriter,
value string,
expiresAt time.Time,
maxAge int,
) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName, Value: value, Path: "/",
Expires: expiresAt, MaxAge: maxAge,
HttpOnly: true, Secure: h.sessionCookieSecure,
SameSite: http.SameSiteStrictMode,
})
}
@@ -0,0 +1,61 @@
package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestSessionCookieIsHardened(t *testing.T) {
handler := &Handler{sessionCookieSecure: true}
recorder := httptest.NewRecorder()
handler.setSessionCookie(
recorder,
"secret-token",
time.Now().Add(time.Hour),
)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
t.Fatalf("unexpected cookie: %#v", cookie)
}
if cookie.Path != "/" || cookie.Domain != "" {
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
}
if !cookie.HttpOnly || !cookie.Secure {
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
}
if cookie.SameSite != http.SameSiteStrictMode {
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
}
if cookie.MaxAge < 1 {
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
}
}
func TestClearSessionCookieExpiresIt(t *testing.T) {
handler := &Handler{}
recorder := httptest.NewRecorder()
handler.clearSessionCookie(recorder)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Value != "" || cookie.MaxAge != -1 {
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
}
if !cookie.Expires.Before(time.Now()) {
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
}
}
@@ -55,6 +55,8 @@ func (h *Handler) CreateSession(
return
}
h.setSessionCookie(w, session.Token, session.ExpiresAt)
response.WriteJSON(
w,
http.StatusCreated,