feat: render campaign copy once after the A/B variant pick, escape reply template HTML previews in one pass, keep revoked session tombstones for the session cache lifetime and fill the cache with SetNX, refuse realtime socket tickets whose single use cannot be recorded, clear workspace-derived dashboard storage on logout, and add tests for session deadlines, password change revoke order, fresh auth, emailed code budgets, join token rotation, gin release mode, panic bodies and the auth secret floor

This commit is contained in:
Matthew Meszaros
2026-10-26 06:13:59 +01:00
parent 297d43085d
commit e44ec03cde
23 changed files with 805 additions and 76 deletions
@@ -0,0 +1,32 @@
package handler
import (
"testing"
"github.com/google/uuid"
"github.com/warmbly/warmbly/internal/models"
)
// A node is handed the MAIL_TLS_INSECURE decision the control plane made, so a hosted node never skips certificate checks.
func TestRenderNodeEnvResolvesMailTLSInsecurePolicy(t *testing.T) {
setInstanceEnv(t)
for _, tc := range []struct {
name, mode, appEnv, flag, want string
}{
{"hosted production ignores it", "cloud", "prod", "true", "false"},
{"hosted production default", "cloud", "prod", "", "false"},
{"self-host honours it", "self_hosted", "prod", "true", "true"},
{"self-host default", "self_hosted", "prod", "", "false"},
{"development honours it", "cloud", "dev", "true", "true"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DEPLOYMENT_MODE", tc.mode)
t.Setenv("APP_ENV", tc.appEnv)
t.Setenv("MAIL_TLS_INSECURE", tc.flag)
env := envLines(t, renderNodeEnv(uuid.New(), models.NodeRoleWorker, ""))
if env["MAIL_TLS_INSECURE"] != tc.want {
t.Errorf("MAIL_TLS_INSECURE = %q, want %q", env["MAIL_TLS_INSECURE"], tc.want)
}
})
}
}
@@ -0,0 +1,49 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/warmbly/warmbly/internal/app/token"
"github.com/warmbly/warmbly/internal/models"
)
// A session caller reaches a fresh-auth route only within the reauth window; a
// credential that has no session passes to the route's own permission gate.
func TestRequireFreshAuth(t *testing.T) {
gin.SetMode(gin.TestMode)
recent := time.Now().Add(-time.Minute)
stale := time.Now().Add(-token.ReauthWindow - time.Second)
cases := []struct {
name string
authType string
session *models.Session
want int
}{
{"session confirmed a minute ago", AuthTypeJWT, &models.Session{ReauthAt: &recent}, http.StatusNoContent},
{"session confirmed past the window", AuthTypeJWT, &models.Session{ReauthAt: &stale}, http.StatusForbidden},
{"session that never confirmed", AuthTypeJWT, &models.Session{}, http.StatusForbidden},
{"no session at all", AuthTypeJWT, nil, http.StatusUnauthorized},
{"api key", AuthTypeAPIKey, nil, http.StatusNoContent},
{"oauth token", AuthTypeOAuth, nil, http.StatusNoContent},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := gin.New()
r.POST("/x", func(c *gin.Context) {
c.Set(AuthTypeKey, tc.authType)
if tc.session != nil {
c.Set(SessionKey, tc.session)
}
}, RequireFreshAuth(), func(c *gin.Context) { c.Status(http.StatusNoContent) })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil))
if w.Code != tc.want {
t.Fatalf("status %d, want %d: %s", w.Code, tc.want, w.Body)
}
})
}
}
@@ -0,0 +1,28 @@
package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// A panic answers 500 with no body: the value and the stack go to the report only.
func TestRecoveryAnswersWithoutTheStack(t *testing.T) {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(Recovery())
r.GET("/boom", func(*gin.Context) { panic("internal-detail-marker") })
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/boom", nil))
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", rec.Code)
}
if b := rec.Body.String(); strings.Contains(b, "internal-detail-marker") || strings.Contains(b, "goroutine") || strings.Contains(b, ".go:") {
t.Fatalf("panic detail reached the client: %q", b)
}
}
@@ -0,0 +1,99 @@
package auth
import (
"context"
"testing"
"github.com/google/uuid"
tokenpkg "github.com/warmbly/warmbly/internal/app/token"
"github.com/warmbly/warmbly/internal/config"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/models"
"github.com/warmbly/warmbly/internal/pkg/argon2"
"github.com/warmbly/warmbly/internal/repository"
)
type orderLog []string
type pwRepo struct {
repository.AuthRepository
hash string
log *orderLog
}
func (r *pwRepo) GetPasswordHash(context.Context, uuid.UUID) (string, *errx.Error) {
return r.hash, nil
}
func (r *pwRepo) ResetPassword(context.Context, uuid.UUID, string) *errx.Error {
*r.log = append(*r.log, "store")
return nil
}
type pwTokens struct {
tokenpkg.TokenService
revokeErr *errx.Error
log *orderLog
}
func (t *pwTokens) RevokeOtherSessions(context.Context, uuid.UUID, uuid.UUID) *errx.Error {
*t.log = append(*t.log, "revoke")
return t.revokeErr
}
func (t *pwTokens) ReissueSession(context.Context, uuid.UUID, *models.Session, string, string) (*models.Token, *errx.Error) {
return &models.Token{}, nil
}
// A signed-in password change ends every other session before the new password
// is stored, and stores nothing when that revocation or the optional credential
// revocation fails.
func TestChangePasswordRevokesBeforeStoring(t *testing.T) {
const current, next = "old-Passphrase-4471", "a-much-longer-new-passphrase-9083"
hash, err := argon2.Hash(current)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
change := func(revokeErr *errx.Error, revokeCreds bool, revokers ...UserCredentialRevoker) (orderLog, *errx.Error) {
var log orderLog
s := trustedSvc(t, config.LoginCodeNewDevice)
s.authRepository = &pwRepo{hash: hash, log: &log}
s.tokenService = &pwTokens{revokeErr: revokeErr, log: &log}
s.WireCredentialRevokers(revokers...)
uid := uuid.New()
t.Cleanup(func() { s.ClearReauthFailures(ctx, uid) })
_, xerr := s.ChangePassword(ctx, uid, &models.Session{ID: uuid.New(), UserID: uid}, "[IP]", "test",
&ChangePassword{CurrentPassword: current, NewPassword: next, RevokeAPICredentials: revokeCreds})
return log, xerr
}
log, xerr := change(nil, false)
if xerr != nil || len(log) != 2 || log[0] != "revoke" || log[1] != "store" {
t.Fatalf("order = %v, err = %v; want [revoke store]", log, xerr)
}
log, xerr = change(errx.InternalError(), false)
if xerr == nil || xerr.Identifier != ErrSessionsNotEnded.Identifier {
t.Fatalf("a failed revocation answered %v, want sessions_not_ended", xerr)
}
for _, step := range log {
if step == "store" {
t.Fatal("the password was stored although other sessions could not be ended")
}
}
log, xerr = change(nil, true, &fakeRevoker{err: context.DeadlineExceeded})
if xerr == nil {
t.Fatal("a failed app and API key revocation must refuse the change")
}
for _, step := range log {
if step == "store" {
t.Fatal("the password was stored although apps and API keys could not be signed out")
}
}
grants, keys := &fakeRevoker{}, &fakeRevoker{}
if _, xerr = change(nil, true, grants, keys); xerr != nil || grants.calls != 1 || keys.calls != 1 {
t.Fatalf("revoke_api_credentials: err %v, grants %d, keys %d", xerr, grants.calls, keys.calls)
}
}
@@ -0,0 +1,75 @@
package auth
import (
"context"
"regexp"
"testing"
"time"
"github.com/google/uuid"
"github.com/warmbly/warmbly/internal/config"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/pkg/crypt"
)
// An emailed code is six random digits.
func TestVerificationCodeIsSixDigits(t *testing.T) {
six := regexp.MustCompile(`^[0-9]{6}$`)
seen := map[string]bool{}
for range 2000 {
code, err := crypt.VerificationCode()
if err != nil || !six.MatchString(code) {
t.Fatalf("code %q, err %v", code, err)
}
seen[code] = true
}
if len(seen) < 1990 {
t.Fatalf("%d distinct codes in 2000 draws", len(seen))
}
}
// One emailed-code session admits AuthAttempts comparisons, and one success.
func TestEmailedCodeSessionAdmitsThreeTriesAndOneUse(t *testing.T) {
ctx := context.Background()
s := trustedSvc(t, config.LoginCodeAlways)
key := getLoginSessionKey(uuid.New())
if err := s.cache.Set(ctx, key, "{}", time.Minute).Err(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.cache.Del(ctx, key, key+":tries").Err() })
for i := range AuthAttempts {
if ok, xerr := s.reserveCodeAttempt(ctx, key, time.Minute); !ok || xerr != nil {
t.Fatalf("try %d refused: %v", i+1, xerr)
}
}
if ok, xerr := s.reserveCodeAttempt(ctx, key, time.Minute); ok || xerr != nil {
t.Fatalf("try %d admitted (err %v), want refused", AuthAttempts+1, xerr)
}
if !s.consumeCodeSession(ctx, key) {
t.Fatal("the first consume did not win")
}
if s.consumeCodeSession(ctx, key) {
t.Fatal("a consumed code session was consumed again")
}
}
// The send budget refuses the sixth code in the window and refuses on a cache error.
func TestEmailedCodeSendBudget(t *testing.T) {
ctx := context.Background()
s := trustedSvc(t, config.LoginCodeAlways)
addr := uuid.NewString() + "@example.test"
t.Cleanup(func() { _ = s.cache.Del(ctx, getEmailVerificationKey(emailFlowLogin, addr)).Err() })
for i := range AuthEmailLimit {
if xerr := s.canSendEmail(ctx, emailFlowLogin, addr); xerr != nil {
t.Fatalf("send %d refused: %v", i+1, xerr)
}
}
if xerr := s.canSendEmail(ctx, emailFlowLogin, addr); xerr != errx.ErrAuthLimit {
t.Fatalf("send %d: %v, want ErrAuthLimit", AuthEmailLimit+1, xerr)
}
s.cache = unreachableCache(t)
if xerr := s.canSendEmail(ctx, emailFlowLogin, addr); xerr == nil {
t.Fatal("a code was sent with no readable send budget")
}
}
@@ -0,0 +1,28 @@
package fleetnode
import (
"context"
"errors"
"testing"
"time"
)
// Issuing a token revokes the one before it; nodes it enrolled are untouched.
func TestIssuingAJoinTokenRevokesThePreviousOne(t *testing.T) {
ctx := context.Background()
s := &Service{settings: &memoryJoinToken{}}
old, _, err := s.IssueJoinToken(ctx, time.Hour)
if err != nil {
t.Fatal(err)
}
fresh, _, err := s.IssueJoinToken(ctx, time.Hour)
if err != nil {
t.Fatal(err)
}
if err := s.VerifyJoinToken(ctx, old); !errors.Is(err, ErrBadToken) {
t.Fatalf("replaced token: %v, want ErrBadToken", err)
}
if err := s.VerifyJoinToken(ctx, fresh); err != nil {
t.Fatalf("current token: %v", err)
}
}
+19 -21
View File
@@ -2,6 +2,7 @@ package template
import (
"context"
"html"
"strings"
"github.com/google/uuid"
@@ -145,7 +146,7 @@ func (s *templateService) Render(ctx context.Context, orgID, templateID uuid.UUI
return &models.RenderedReplyTemplate{
Subject: RenderString(t.Subject, vars),
BodyHTML: RenderString(t.BodyHTML, vars),
BodyHTML: RenderHTMLString(t.BodyHTML, vars),
BodyPlain: RenderString(t.BodyPlain, vars),
}, nil
}
@@ -153,34 +154,31 @@ func (s *templateService) Render(ctx context.Context, orgID, templateID uuid.UUI
// RenderString replaces {{.Key}} placeholders in s with values from vars.
// Unknown keys are dropped (rendered as empty string) so previews don't
// leak the placeholder syntax to recipients.
func RenderString(s string, vars map[string]string) string {
if s == "" {
return s
}
func RenderString(s string, vars map[string]string) string { return renderVars(s, vars, false) }
out := s
for k, v := range vars {
out = strings.ReplaceAll(out, "{{."+k+"}}", v)
}
// RenderHTMLString is RenderString for an HTML body: every value is HTML-escaped.
func RenderHTMLString(s string, vars map[string]string) string { return renderVars(s, vars, true) }
// Drop any remaining {{.X}} placeholders so users never see raw syntax.
out = stripPlaceholders(out)
return out
}
// stripPlaceholders removes any leftover {{.Anything}} tokens. It is
// intentionally permissive — anything between {{. and the next }} (no
// nested braces) is treated as a placeholder.
func stripPlaceholders(s string) string {
// renderVars replaces each {{.Key}} once, left to right; an inserted value is never rescanned.
func renderVars(s string, vars map[string]string, escape bool) string {
var b strings.Builder
for {
start := strings.Index(s, "{{.")
if start < 0 {
return s
break
}
end := strings.Index(s[start:], "}}")
if end < 0 {
return s
break
}
s = s[:start] + s[start+end+2:]
v := vars[s[start+3:start+end]]
if escape {
v = html.EscapeString(v)
}
b.WriteString(s[:start])
b.WriteString(v)
s = s[start+end+2:]
}
b.WriteString(s)
return b.String()
}
+12
View File
@@ -314,3 +314,15 @@ func TestService_Render_NotFound(t *testing.T) {
t.Fatalf("expected NotFound, got %v", xerr)
}
}
func TestRenderHTMLStringEscapesValuesAndNeverRescansThem(t *testing.T) {
vars := map[string]string{"name": `<img src=x onerror=alert(1)>`, "a": "{{.b}}", "b": "SECOND"}
if got := RenderHTMLString(`<p title="{{.name}}">{{.name}}</p>`, vars); got != `<p title="&lt;img src=x onerror=alert(1)&gt;">&lt;img src=x onerror=alert(1)&gt;</p>` {
t.Fatalf("html: %q", got)
}
for i := 0; i < 20; i++ {
if got := RenderString(`{{.a}}`, vars); got != "{{.b}}" {
t.Fatalf("a value was rescanned: %q", got)
}
}
}
+10
View File
@@ -31,6 +31,16 @@ func (s *tokenService) saveSession(ctx context.Context, session *models.Session,
return nil
}
// fillSession caches a row read from the database only when nothing is cached,
// so it can never overwrite a revoked tombstone written while the row was read.
func (s *tokenService) fillSession(ctx context.Context, session *models.Session) {
data, err := json.Marshal(session)
if err != nil {
return
}
_ = s.cache.SetNX(ctx, getSessionKey(session.ID), data, SessionTTL).Err()
}
func (s *tokenService) getSession(ctx context.Context, sessionID uuid.UUID) (*models.Session, *errx.Error) {
data, err := s.cache.Get(ctx, getSessionKey(sessionID)).Bytes()
if err != nil {
+2 -3
View File
@@ -4,9 +4,8 @@ import "time"
const (
SessionTTL = 12 * time.Hour
// revokedTombstoneTTL bounds how long a revoked marker written in place of
// a failed cache eviction lives before reads fall back to the row.
revokedTombstoneTTL = 5 * time.Minute
// revokedTombstoneTTL outlives any cached copy, so no fill can resurrect a revoked session.
revokedTombstoneTTL = SessionTTL
RefreshTokenTTL = 12 * time.Hour
AccessTokenLifeTime = 12 * time.Hour
RefreshTokenLifeTime = 180 * 24 * time.Hour
+127
View File
@@ -0,0 +1,127 @@
package token
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/infrastructure/cache"
"github.com/warmbly/warmbly/internal/models"
"github.com/warmbly/warmbly/internal/repository"
)
// failDel refuses every DEL while every other command reaches Redis.
type failDel struct{}
func (failDel) DialHook(next redis.DialHook) redis.DialHook { return next }
func (failDel) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if cmd.Name() == "del" {
return errors.New("injected: DEL refused")
}
return next(ctx, cmd)
}
}
func (failDel) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return next
}
func revocationCache(t *testing.T, refuseDel bool) *cache.Cache {
t.Helper()
url := os.Getenv("WARMBLY_TEST_REDIS")
if url == "" {
t.Skip("WARMBLY_TEST_REDIS not set")
}
c, err := cache.New(url)
if err != nil {
t.Fatalf("connect: %v", err)
}
if refuseDel {
c.AddHook(failDel{})
}
t.Cleanup(func() { _ = c.Close() })
return c
}
// revocableRepo is the sessions table for one row. read, when set, blocks the
// row read until the test releases it, so a revocation can land in between.
type revocableRepo struct {
repository.TokenRepository
sess models.Session
read chan struct{}
started chan struct{}
}
func (r *revocableRepo) GetSession(context.Context, uuid.UUID) (*models.Session, *errx.Error) {
row := r.sess
if r.read != nil {
close(r.started)
<-r.read
r.read = nil
}
return &row, nil
}
func (r *revocableRepo) RevokeSessionByID(_ context.Context, _, _ uuid.UUID, at time.Time) (bool, *errx.Error) {
r.sess.RevokedAt = &at
return true, nil
}
func liveRow(userID uuid.UUID) models.Session {
exp := time.Now().Add(time.Hour)
return models.Session{ID: uuid.New(), UserID: userID, ExpiresAt: &exp}
}
// A revoked session is refused even when the cache refuses the eviction.
func TestRevokedSessionIsRefusedWhenTheCacheEvictionFails(t *testing.T) {
ctx := context.Background()
user := uuid.New()
repo := &revocableRepo{sess: liveRow(user)}
s := &tokenService{cache: revocationCache(t, true), tokenRepository: repo}
t.Cleanup(func() { _ = revocationCache(t, false).Del(ctx, getSessionKey(repo.sess.ID)).Err() })
if got, _ := s.GetSession(ctx, repo.sess.ID); !got.Live(time.Now()) {
t.Fatal("fixture: the session should start live and cached")
}
_ = s.RevokeSessionByID(ctx, user, repo.sess.ID, uuid.New())
got, xerr := s.GetSession(ctx, repo.sess.ID)
if xerr != nil {
t.Fatalf("read after revoke: %v", xerr)
}
if got.Live(time.Now()) {
t.Fatal("a revoked session is still served live from the cache")
}
}
// A row read before a revocation commits is never cached after it.
func TestRevokedSessionIsNotRecachedByARacingRead(t *testing.T) {
ctx := context.Background()
user := uuid.New()
repo := &revocableRepo{sess: liveRow(user), read: make(chan struct{}), started: make(chan struct{})}
s := &tokenService{cache: revocationCache(t, false), tokenRepository: repo}
t.Cleanup(func() { _ = s.cache.Del(ctx, getSessionKey(repo.sess.ID)).Err() })
done := make(chan struct{})
go func() { defer close(done); _, _ = s.GetSession(ctx, repo.sess.ID) }()
<-repo.started // the racing request has read the live row
if xerr := s.RevokeSessionByID(ctx, user, repo.sess.ID, uuid.New()); xerr != nil {
t.Fatalf("revoke: %v", xerr)
}
close(repo.read) // and only now writes it to the cache
<-done
got, xerr := s.GetSession(ctx, repo.sess.ID)
if xerr != nil {
t.Fatalf("read after revoke: %v", xerr)
}
if got.Live(time.Now()) {
t.Fatal("a racing read re-cached the live row after the revocation")
}
}
@@ -0,0 +1,47 @@
package token
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/infrastructure/cache"
"github.com/warmbly/warmbly/internal/models"
)
// Past its expires_at a session answers no request and mints no token, even
// with an access and a refresh token whose own exp is still ahead.
func TestExpiredSessionNeitherAuthenticatesNorRefreshes(t *testing.T) {
down := &cache.Cache{Client: redis.NewClient(&redis.Options{Addr: "[IP]:1", DialTimeout: 200 * time.Millisecond})}
issued := time.Now().Add(-time.Hour).Truncate(time.Second)
ended := time.Now().Add(-time.Minute)
id, uid := uuid.New(), uuid.New()
repo := &sessionRepo{session: &models.Session{ID: id, UserID: uid, ExpiresAt: &ended,
AccessNonce: "access-nonce", RefreshNonce: "refresh-nonce", LastRefreshedAt: issued}}
s := &tokenService{cache: down, tokenRepository: repo, AuthSecret: "test-only-signing-key-of-32-bytes-min"}
ctx := context.Background()
access, err := s.GenerateTokenFor(PurposeAccess, uid, id, "", "access-nonce", issued, time.Now().Add(time.Hour))
if err != nil {
t.Fatal(err)
}
if _, xerr := s.ValidateAccessToken(ctx, access); xerr != errx.ErrSessionEnded {
t.Fatalf("access token on an expired session: %v, want ErrSessionEnded", xerr)
}
refresh, err := s.GenerateTokenFor(PurposeRefresh, uid, id, "", "refresh-nonce", issued, time.Now().Add(time.Hour))
if err != nil {
t.Fatal(err)
}
if tok, xerr := s.RefreshToken(ctx, refresh); xerr != errx.ErrSessionEnded || tok != nil {
t.Fatalf("refresh on an expired session: %v, %v; want ErrSessionEnded and no token", tok, xerr)
}
live := time.Now().Add(time.Hour)
repo.session.ExpiresAt = &live
if _, xerr := s.ValidateAccessToken(ctx, access); xerr != nil {
t.Fatalf("the same token on a live session: %v", xerr)
}
}
+6 -13
View File
@@ -84,9 +84,7 @@ func (s *tokenService) RevokeSessionByID(ctx context.Context, userID, sessionID,
return errx.ErrSessionNotFound
}
// Bust the cache so ValidateAccessToken re-reads the now-revoked row and the
// session stops working immediately rather than after the cache TTL.
if err := s.deleteSession(ctx, sessionID); err != nil {
if err := s.evictRevoked(ctx, sessionID, userID, time.Now()); err != nil {
return err
}
s.notifyRevoked(ctx, userID)
@@ -133,17 +131,12 @@ func (s *tokenService) revokeOthers(ctx context.Context, userID, currentSessionI
return first
}
// evictRevoked drops a revoked session from the cache. When the delete is
// refused it stores a revoked tombstone instead: a reader that would have
// served the stale copy for the rest of SessionTTL sees revoked_at set, and a
// short TTL sends the next read to the row.
// evictRevoked overwrites a revoked session's cache entry with a tombstone that
// outlives any cached copy; only when that write is refused does it delete.
func (s *tokenService) evictRevoked(ctx context.Context, id, userID uuid.UUID, revokedAt time.Time) *errx.Error {
if err := s.deleteSession(ctx, id); err == nil {
tomb := &models.Session{ID: id, UserID: userID, RevokedAt: &revokedAt}
if err := s.saveSession(ctx, tomb, revokedTombstoneTTL); err == nil {
return nil
}
tomb := &models.Session{ID: id, UserID: userID, RevokedAt: &revokedAt}
if err := s.saveSession(ctx, tomb, revokedTombstoneTTL); err != nil {
return err
}
return nil
return s.deleteSession(ctx, id)
}
+1 -1
View File
@@ -28,7 +28,7 @@ func (s *tokenService) GetSession(ctx context.Context, sessionID uuid.UUID) (*mo
// only costs the next request a database read. Returning the error here
// meant a Redis write that was refused, on quota or anything else, failed
// every authenticated request with a 500.
_ = s.saveSession(ctx, sess, SessionTTL)
s.fillSession(ctx, sess)
return sess, nil
}
+21
View File
@@ -0,0 +1,21 @@
package config
import (
"strings"
"testing"
)
// The backend refuses to boot with an AUTH_SECRET shorter than the HS256 floor.
func TestLoadAuthConfigRefusesAShortAuthSecret(t *testing.T) {
t.Setenv("AWS_CONFIG_ENABLED", "")
for _, n := range []int{1, 16, MinAuthSecretLength - 1} {
t.Setenv("AUTH_SECRET", strings.Repeat("a", n))
if _, err := (&Config{}).LoadAuthConfig(t.Context()); err == nil {
t.Fatalf("AUTH_SECRET of %d bytes was accepted", n)
}
}
t.Setenv("AUTH_SECRET", strings.Repeat("a", MinAuthSecretLength))
if _, err := (&Config{}).LoadAuthConfig(t.Context()); err != nil && strings.Contains(err.Error(), "AUTH_SECRET must be") {
t.Fatalf("a %d-byte AUTH_SECRET was refused: %v", MinAuthSecretLength, err)
}
}
+23
View File
@@ -0,0 +1,23 @@
package config
import (
"context"
"testing"
"github.com/gin-gonic/gin"
)
// Production must run gin in release mode without anyone remembering GIN_MODE.
func TestGinModeFollowsAppEnv(t *testing.T) {
t.Setenv("WEBSOCKET_URL", "wss://realtime.example.com/socket")
t.Setenv("GIN_MODE", "")
for env, want := range map[string]string{"prod": gin.ReleaseMode, "dev": gin.DebugMode} {
api, err := (&Config{Env: env}).LoadApiConfig(context.Background())
if err != nil {
t.Fatal(err)
}
if api.GinMode != want {
t.Errorf("APP_ENV=%s: GinMode = %q, want %q", env, api.GinMode, want)
}
}
}
@@ -0,0 +1,43 @@
package tasks
import (
"context"
"strings"
"testing"
"github.com/google/uuid"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/models"
)
// passThrough is the control arm: it hands back whatever copy it was given.
type passThrough struct{ variant *models.VariantSelection }
func (p passThrough) SelectVariant(_ context.Context, _, _, _, _ uuid.UUID, subject, bodyHTML, bodyPlain string) (*models.VariantSelection, *errx.Error) {
if p.variant != nil {
return p.variant, nil
}
return &models.VariantSelection{Subject: subject, BodyHTML: bodyHTML, BodyPlain: bodyPlain}, nil
}
// A template action a contact typed into a field is sent as text, on the control arm and on a variant.
func TestSendRendersContactDataOnce(t *testing.T) {
contact := models.Contact{ID: uuid.New(), Email: "ann@example.com",
FirstName: `{{.Email}}{{range $k, $v := .}}{{$k}}={{$v}};{{end}}`,
CustomFields: map[string]string{"internal_note": "never shown"}}
variant := &models.VariantSelection{Subject: "Hi {{.FirstName}}", BodyHTML: "<p>Hi {{.FirstName}}</p>", BodyPlain: "Hi {{.FirstName}}"}
for name, picker := range map[string]variantSelector{"no A/B": nil, "control arm": passThrough{}, "variant": passThrough{variant: variant}} {
t.Run(name, func(t *testing.T) {
subject, html, plain, xerr := selectAndRender(context.Background(), picker, uuid.New(), uuid.New(), uuid.New(), contact, TemplateContext{}, "",
"Hi {{.FirstName}}", "<p>Hi {{.FirstName}}</p>", "Hi {{.FirstName}}")
if xerr != nil {
t.Fatal(xerr)
}
for _, out := range []string{subject, html, plain} {
if strings.Contains(out, "ann@example.com") || strings.Contains(out, "never shown") || !strings.Contains(out, "{{.Email}}") {
t.Fatalf("contact data was rendered as a template: %q", out)
}
}
})
}
}
+44 -36
View File
@@ -626,47 +626,18 @@ func (s *tasksService) HandleCampaignTask(task *proto.ProcessTask) (result *errx
}
extra := templateContext(account, unsubscribeURL)
// STEP 10: Render email template with contact variables, then expand any
// {a|b|c} spintax per-recipient (only real |-groups; literal braces/CSS are
// left intact) so each send varies for deliverability.
subject := expandSpintax(RenderTemplateWith(rawSubject, *contact, extra))
bodyHTML := expandSpintax(RenderHTMLTemplateWith(rawBodyHTML, *contact, extra))
bodyPlain := expandSpintax(RenderTemplateWith(rawBodyPlain, *contact, extra))
// STEP 10: Pick the copy, then render it with contact variables exactly
// once and expand any {a|b|c} spintax per-recipient. Rendering happens after
// the variant pick so a contact value is never parsed as template text.
subject, bodyHTML, bodyPlain, sxerr := s.selectAndRender(ctx, orgID, campaign.ID, sequence.ID, *contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain)
if sxerr != nil {
return sxerr
}
// A recorded conversation subject is already rendered: reuse it verbatim.
if threadParent != nil && threadParent.SubjectSent && threadSubject != "" {
subject = threadSubject
}
// If no plain text provided, extract from HTML
if bodyPlain == "" && bodyHTML != "" {
bodyPlain = ExtractPlainTextFromHTML(bodyHTML)
}
if s.advanced != nil {
selection, sxerr := s.advanced.SelectVariant(ctx, orgID, campaign.ID, contact.ID, sequence.ID, subject, bodyHTML, bodyPlain)
if sxerr != nil {
return sxerr
}
if selection != nil {
// A chosen variant is stored template text, so it goes through the
// same render as the step's own copy; the control arm comes back
// already rendered, for which this pass is a no-op.
//
// A threading step is the exception: its subject belongs to the
// conversation, not to the arm, so variants on a follow-up vary
// the body only.
if threadSubject == "" {
subject = expandSpintax(RenderTemplateWith(selection.Subject, *contact, extra))
}
bodyHTML = expandSpintax(RenderHTMLTemplateWith(selection.BodyHTML, *contact, extra))
bodyPlain = expandSpintax(RenderTemplateWith(selection.BodyPlain, *contact, extra))
// A variant may carry HTML only; keep the plain-text alternative.
if bodyPlain == "" && bodyHTML != "" {
bodyPlain = ExtractPlainTextFromHTML(bodyHTML)
}
}
}
// STEP 10.5: Resolve per-recipient AI variables (AI blocks in the body that
// generate unique copy for THIS contact). Runs before tracking/signature so
// the generated copy gets open/click tracking like any other body text. A
@@ -1885,3 +1856,40 @@ func (s *tasksService) keepChainAfterFailure(rawTaskID string, handedOff bool) {
log.Warn().Err(err).Str("campaign_id", campaignID.String()).Msg("could not schedule the campaign's next pass after a failed one")
}
}
// variantSelector is the slice of advanced.Service the send path uses to pick copy.
type variantSelector interface {
SelectVariant(ctx context.Context, organizationID, campaignID, contactID, sequenceID uuid.UUID, subject, bodyHTML, bodyPlain string) (*models.VariantSelection, *errx.Error)
}
// selectAndRender picks the step's copy or an A/B variant from template text, then renders it once.
func (s *tasksService) selectAndRender(ctx context.Context, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string) (string, string, string, *errx.Error) {
var picker variantSelector
if s.advanced != nil {
picker = s.advanced
}
return selectAndRender(ctx, picker, orgID, campaignID, sequenceID, contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain)
}
func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string) (string, string, string, *errx.Error) {
if picker != nil {
selection, xerr := picker.SelectVariant(ctx, orgID, campaignID, contact.ID, sequenceID, rawSubject, rawBodyHTML, rawBodyPlain)
if xerr != nil {
return "", "", "", xerr
}
if selection != nil {
// A threading step's subject belongs to the conversation, so variants vary the body only.
if threadSubject == "" {
rawSubject = selection.Subject
}
rawBodyHTML, rawBodyPlain = selection.BodyHTML, selection.BodyPlain
}
}
subject := expandSpintax(RenderTemplateWith(rawSubject, contact, extra))
bodyHTML := expandSpintax(RenderHTMLTemplateWith(rawBodyHTML, contact, extra))
bodyPlain := expandSpintax(RenderTemplateWith(rawBodyPlain, contact, extra))
if bodyPlain == "" && bodyHTML != "" {
bodyPlain = ExtractPlainTextFromHTML(bodyHTML)
}
return subject, bodyHTML, bodyPlain, nil
}
+39
View File
@@ -0,0 +1,39 @@
package tasks
import (
"strings"
"testing"
"github.com/warmbly/warmbly/internal/models"
)
// Contact data is data: markup is escaped and a template action inside a value is never evaluated.
func TestContactValuesCannotInjectMarkupOrTemplateActions(t *testing.T) {
contact := models.Contact{
FirstName: `<script>alert(1)</script>`,
Email: "ann@example.com",
Company: `" onmouseover="alert(1)`,
CustomFields: map[string]string{
"note": `{{.Email}}{{printf "%s" .Email}}{{range .}}x{{end}}`,
},
}
for _, tc := range []struct{ name, tmpl string }{
{"compiled", `<p>{{.FirstName}}</p><a title="{{.Company}}">x</a><p>{{.note}}</p>`},
{"fallback", `{{if .Company}}<p>{{.FirstName}}</p><a title="{{.Company}}">x</a><p>{{.note}}</p>`},
} {
t.Run(tc.name, func(t *testing.T) {
out := RenderHTMLTemplateWith(tc.tmpl, contact, TemplateContext{})
for _, bad := range []string{"<script>", `" onmouseover="`, "ann@example.com"} {
if strings.Contains(out, bad) {
t.Fatalf("value escaped its context (%q): %s", bad, out)
}
}
if !strings.Contains(out, "&lt;script&gt;") || !strings.Contains(out, "{{.Email}}") {
t.Fatalf("value was not kept as escaped text: %s", out)
}
})
}
if out := RenderTemplateWith(`Hi {{.note}}`, contact, TemplateContext{}); strings.Contains(out, "ann@example.com") {
t.Fatalf("plain part evaluated an action inside a value: %s", out)
}
}
+2 -2
View File
@@ -160,8 +160,8 @@ defmodule Realtime.Auth do
{:error, :ticket_used}
{:error, reason} ->
Logger.warning("Socket ticket claim unavailable, accepting: #{inspect(reason)}")
:ok
Logger.warning("Socket ticket claim unavailable, refusing: #{inspect(reason)}")
{:error, :verification_error}
end
end
@@ -0,0 +1,37 @@
defmodule Realtime.WsTicketClaimOutageTest do
@moduledoc """
A ticket that cannot be marked used opens no socket.
"""
use ExUnit.Case, async: false
alias Realtime.Auth
alias Realtime.Test.AuthRepo
alias Realtime.Test.Counter
setup do
Counter.reset()
start_supervised!(AuthRepo)
on_exit(fn -> Counter.simulate_outage(false) end)
:ok
end
test "a ticket is refused while its single use cannot be recorded" do
AuthRepo.respond_with(fn _sql, _params -> {:ok, %{rows: [[true]]}} end)
ticket =
JOSE.JWT.sign(JOSE.JWK.from_oct("test_jwt_secret"), %{"alg" => "HS256"}, %{
"sub" => "0b7d5c1e-6a1f-4c1e-9d5a-2f0c8e4b7a10",
"sid" => UUID.uuid4(),
"nonce" => "nonce",
"purpose" => "ws",
"session_id" => "1c8e6d2f-7b2a-4d2f-8e6b-3a1d9f5c8b21",
"exp" => System.system_time(:second) + 600
})
|> JOSE.JWS.compact()
|> elem(1)
Counter.simulate_outage(true)
assert {:error, :verification_error} = Auth.verify_jwt(ticket)
end
end
+6
View File
@@ -65,10 +65,16 @@ export const saveTokens = (data: Record<string, unknown>) => {
// banners are deliberately not here; they are not the user's data.
const SESSION_SCOPED_KEY_PREFIXES = [
"warmbly-reply-draft:",
"remie.tips.",
"warmbly:view:",
"warmbly:signin-migration-later:",
];
const SESSION_SCOPED_KEYS = [
"sso_binding",
"warmbly.sendingDomains.redirectRescue",
"warmbly.sendingDomains.setupNudge",
"warmbly.compose.seedPick",
];
// clearTokens ends the client's half of the session: the tokens, and the
+55
View File
@@ -0,0 +1,55 @@
import { beforeEach, describe, expect, it } from "vitest";
import { clearClientSession } from "./session";
// setupTests.ts replaces localStorage with no-op stubs; back them with a map here.
function backLocalStorage(): Map<string, string> {
const data = new Map<string, string>();
const ls = window.localStorage as unknown as Record<string, unknown>;
ls.getItem = (k: string) => data.get(k) ?? null;
ls.setItem = (k: string, v: string) => { data.set(k, String(v)); };
ls.removeItem = (k: string) => { data.delete(k); };
ls.clear = () => data.clear();
ls.key = (i: number) => [...data.keys()][i] ?? null;
Object.defineProperty(ls, "length", { configurable: true, get: () => data.size });
return data;
}
// Everything a signed-in person leaves in this browser is gone after sign-out,
// except the remembered-device marker and preferences that describe no workspace.
const SIGNED_IN: Record<string, string> = {
access_token: "a", access_token_expires_at: "2099-01-01T00:00:00Z",
refresh_token: "r", refresh_token_expires_at: "2099-01-01T00:00:00Z",
auth_token: "{}",
sso_binding: "b",
"warmbly-storage": JSON.stringify({ state: { currentOrganization: { id: "org" } }, version: 1 }),
'warmbly-reply-draft:["u","o","t","m","reply"]': "{}",
"warmbly.sendingDomains.redirectRescue": "acme.com,acme.io",
"warmbly.sendingDomains.setupNudge": "acme.com",
"warmbly.compose.seedPick": '["seed-1"]',
"remie.tips.u.o": "{}",
"warmbly:view:u:o:contacts": "{}",
"warmbly:signin-migration-later:o": "1",
};
const KEPT: Record<string, string> = {
"warmbly-trusted-devices": '{"person@example.com":"device"}',
theme: "dark",
"warmbly:passkey-nudge-dismissed": "1",
};
describe("clearClientSession", () => {
let local: Map<string, string>;
beforeEach(() => {
local = backLocalStorage();
sessionStorage.clear();
for (const [k, v] of Object.entries({ ...SIGNED_IN, ...KEPT })) localStorage.setItem(k, v);
sessionStorage.setItem("sso_binding", "b");
sessionStorage.setItem("warmbly:browse:v1:x", "{}");
sessionStorage.setItem("warmbly:mailbox-tag:x", "t");
});
it("leaves only the remembered-device marker and workspace-free preferences", () => {
clearClientSession();
expect([...local.keys()].sort()).toEqual(Object.keys(KEPT).sort());
expect(Object.keys(sessionStorage)).toEqual([]);
});
});