diff --git a/internal/api/handler/node_mail_tls_insecure_test.go b/internal/api/handler/node_mail_tls_insecure_test.go new file mode 100644 index 000000000..4e3c15101 --- /dev/null +++ b/internal/api/handler/node_mail_tls_insecure_test.go @@ -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) + } + }) + } +} diff --git a/internal/api/middleware/fresh_auth_test.go b/internal/api/middleware/fresh_auth_test.go new file mode 100644 index 000000000..959c044d9 --- /dev/null +++ b/internal/api/middleware/fresh_auth_test.go @@ -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) + } + }) + } +} diff --git a/internal/api/middleware/recovery_body_test.go b/internal/api/middleware/recovery_body_test.go new file mode 100644 index 000000000..c9376f223 --- /dev/null +++ b/internal/api/middleware/recovery_body_test.go @@ -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) + } +} diff --git a/internal/app/auth/change_password_order_test.go b/internal/app/auth/change_password_order_test.go new file mode 100644 index 000000000..f9359722f --- /dev/null +++ b/internal/app/auth/change_password_order_test.go @@ -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) + } +} diff --git a/internal/app/auth/emailed_code_budget_test.go b/internal/app/auth/emailed_code_budget_test.go new file mode 100644 index 000000000..861d0be38 --- /dev/null +++ b/internal/app/auth/emailed_code_budget_test.go @@ -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") + } +} diff --git a/internal/app/fleetnode/join_token_rotation_test.go b/internal/app/fleetnode/join_token_rotation_test.go new file mode 100644 index 000000000..ae74ce837 --- /dev/null +++ b/internal/app/fleetnode/join_token_rotation_test.go @@ -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) + } +} diff --git a/internal/app/template/service.go b/internal/app/template/service.go index e1a5d9ae1..5d7611428 100644 --- a/internal/app/template/service.go +++ b/internal/app/template/service.go @@ -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() } diff --git a/internal/app/template/service_test.go b/internal/app/template/service_test.go index 13d348b0a..76c2f9bcf 100644 --- a/internal/app/template/service_test.go +++ b/internal/app/template/service_test.go @@ -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": ``, "a": "{{.b}}", "b": "SECOND"} + if got := RenderHTMLString(`

{{.name}}

`, vars); got != `

<img src=x onerror=alert(1)>

` { + 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) + } + } +} diff --git a/internal/app/token/cache.go b/internal/app/token/cache.go index c549c95d4..0719c5ed2 100644 --- a/internal/app/token/cache.go +++ b/internal/app/token/cache.go @@ -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 { diff --git a/internal/app/token/config.go b/internal/app/token/config.go index 24a24b39d..9ea754a59 100644 --- a/internal/app/token/config.go +++ b/internal/app/token/config.go @@ -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 diff --git a/internal/app/token/revocation_cache_test.go b/internal/app/token/revocation_cache_test.go new file mode 100644 index 000000000..8c482c716 --- /dev/null +++ b/internal/app/token/revocation_cache_test.go @@ -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") + } +} diff --git a/internal/app/token/session_deadline_test.go b/internal/app/token/session_deadline_test.go new file mode 100644 index 000000000..75c84f530 --- /dev/null +++ b/internal/app/token/session_deadline_test.go @@ -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) + } +} diff --git a/internal/app/token/sessions.go b/internal/app/token/sessions.go index a8eb8119a..5b82357b4 100644 --- a/internal/app/token/sessions.go +++ b/internal/app/token/sessions.go @@ -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) } diff --git a/internal/app/token/verify.go b/internal/app/token/verify.go index 79c09ca8e..ffe3f1b11 100644 --- a/internal/app/token/verify.go +++ b/internal/app/token/verify.go @@ -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 } diff --git a/internal/config/config_auth_test.go b/internal/config/config_auth_test.go new file mode 100644 index 000000000..539625d12 --- /dev/null +++ b/internal/config/config_auth_test.go @@ -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) + } +} diff --git a/internal/config/ginmode_test.go b/internal/config/ginmode_test.go new file mode 100644 index 000000000..34d46c406 --- /dev/null +++ b/internal/config/ginmode_test.go @@ -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) + } + } +} diff --git a/internal/tasks/campaign_render_once_test.go b/internal/tasks/campaign_render_once_test.go new file mode 100644 index 000000000..67caeab62 --- /dev/null +++ b/internal/tasks/campaign_render_once_test.go @@ -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: "

Hi {{.FirstName}}

", 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}}", "

Hi {{.FirstName}}

", "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) + } + } + }) + } +} diff --git a/internal/tasks/campaign_task.go b/internal/tasks/campaign_task.go index defc5b1f8..066aafb71 100644 --- a/internal/tasks/campaign_task.go +++ b/internal/tasks/campaign_task.go @@ -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 +} diff --git a/internal/tasks/template_injection_test.go b/internal/tasks/template_injection_test.go new file mode 100644 index 000000000..4e75d1131 --- /dev/null +++ b/internal/tasks/template_injection_test.go @@ -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: ``, + 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", `

{{.FirstName}}

x

{{.note}}

`}, + {"fallback", `{{if .Company}}

{{.FirstName}}

x

{{.note}}

`}, + } { + t.Run(tc.name, func(t *testing.T) { + out := RenderHTMLTemplateWith(tc.tmpl, contact, TemplateContext{}) + for _, bad := range []string{"