Harden job-application tracker: backend fixes, tests, UI rework
Deploy with Docker Compose / deploy (push) Successful in 1m8s
Deploy with Docker Compose / deploy (push) Successful in 1m8s
Backend (email sync + resolvers): - Sync window anchored on latest received_at with slack + rewind age-out - Skip ctx-cancelled per-email side effects - Soft-deleted applications no longer block pipeline matching - Status normalization shared between pipeline and resolvers, with tests - Reject empty jobTitle/company on create/update - IMAP fallback synthesizes Message-ID from stable message traits - Consistent list ordering with id tie-break Frontend (JobApplications.vue): - Unified status vocabulary with pipeline (lowercase keys) - Emptied optional fields now clear on save; row stays open on failure - URL editable, notes textarea, appliedAt defaults to today - Error banner, delete confirmations, inline status select - Search, sortable columns, status-count filter tiles, stale-row marker - CSV export with UTF-8 BOM + CRLF Tests: stdlib table-driven tests for sync, status, auth, handlers. Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -8,9 +8,11 @@ package graph
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
@@ -23,12 +25,20 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// String! is non-null but not non-empty, and the columns are only
|
||||
// `not null`, so "" stores happily and then never matches the email
|
||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
||||
jobTitle := strings.TrimSpace(input.JobTitle)
|
||||
company := strings.TrimSpace(input.Company)
|
||||
if jobTitle == "" || company == "" {
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
app := models.JobApplication{
|
||||
JobTitle: input.JobTitle,
|
||||
Company: input.Company,
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: input.Status,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
}
|
||||
@@ -44,18 +54,25 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched;
|
||||
// note this also means a nullable column can never be cleared back to
|
||||
// null through this mutation.
|
||||
// is distinguishable from "set to empty". A nil field is left untouched.
|
||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
||||
// empties a wrong URL or stale notes — but the same value on a required
|
||||
// column is rejected rather than blanking a live row.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.JobTitle != nil {
|
||||
app.JobTitle = *input.JobTitle
|
||||
if strings.TrimSpace(*input.JobTitle) == "" {
|
||||
return nil, fmt.Errorf("jobTitle cannot be empty")
|
||||
}
|
||||
app.JobTitle = strings.TrimSpace(*input.JobTitle)
|
||||
}
|
||||
if input.Company != nil {
|
||||
app.Company = *input.Company
|
||||
if strings.TrimSpace(*input.Company) == "" {
|
||||
return nil, fmt.Errorf("company cannot be empty")
|
||||
}
|
||||
app.Company = strings.TrimSpace(*input.Company)
|
||||
}
|
||||
if input.Location != nil {
|
||||
app.Location = input.Location
|
||||
@@ -64,7 +81,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = *input.Status
|
||||
app.Status = services.NormalizeStatus(*input.Status)
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
@@ -100,7 +117,10 @@ func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobAppli
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil {
|
||||
// id is the tie-break: one sync loop inserts several rows inside the same
|
||||
// timestamp, and Postgres gives no stable order for equal sort keys, so
|
||||
// without it the list can reshuffle between two identical page loads.
|
||||
if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return apps, nil
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// What is deliberately NOT covered here, and why:
|
||||
//
|
||||
// - Every handler method (Login, UploadMessageFile, the radio file movers,
|
||||
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
|
||||
// multipart request, the container's /backend/... directories, or a paid
|
||||
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
|
||||
// CI.
|
||||
// - The radio/chat upload filename sanitisation itself. It is written inline
|
||||
// inside the handler bodies rather than in a helper, so testing it would
|
||||
// mean either driving a full multipart upload against the real upload
|
||||
// directories or refactoring production code. Neither was in scope, so the
|
||||
// part that *is* extractable — the extension allow-lists those handlers
|
||||
// gate on — is covered as a table contract below instead.
|
||||
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
|
||||
// reach the database on the refresh path.
|
||||
//
|
||||
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
|
||||
// three shared caches, the admin claim check on the upload trust boundary, and
|
||||
// the upload allow-list tables.
|
||||
|
||||
// --- Spotify OAuth CSRF nonces -------------------------------------------
|
||||
|
||||
func TestSpotifyStateSingleUse(t *testing.T) {
|
||||
s := &Store{}
|
||||
|
||||
state, err := s.NewSpotifyState()
|
||||
if err != nil {
|
||||
t.Fatalf("NewSpotifyState: %v", err)
|
||||
}
|
||||
if !s.ConsumeSpotifyState(state) {
|
||||
t.Fatal("a freshly minted state must be accepted")
|
||||
}
|
||||
// The whole point of the nonce: a replayed callback must not authenticate
|
||||
// a second time.
|
||||
if s.ConsumeSpotifyState(state) {
|
||||
t.Fatal("a consumed state must not be accepted again")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeSpotifyStateRejections(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
// setup returns the state string to present to ConsumeSpotifyState.
|
||||
setup func(s *Store) string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "empty state is rejected before the map is even consulted",
|
||||
setup: func(*Store) string { return "" },
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "a state this process never minted is rejected",
|
||||
setup: func(*Store) string { return "deadbeef" },
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "a state minted within the TTL is accepted",
|
||||
setup: func(s *Store) string {
|
||||
st, _ := s.NewSpotifyState()
|
||||
return st
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "a state older than the TTL is rejected",
|
||||
setup: func(s *Store) string {
|
||||
st, _ := s.NewSpotifyState()
|
||||
// Backdating beats sleeping for ten minutes; the map is in the
|
||||
// same package so the creation stamp is writable here.
|
||||
s.spotifyStates[st] = time.Now().Add(-spotifyStateTTL - time.Second)
|
||||
return st
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := &Store{}
|
||||
state := c.setup(s)
|
||||
if got := s.ConsumeSpotifyState(state); got != c.want {
|
||||
t.Fatalf("ConsumeSpotifyState = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An expired nonce must also be removed, not merely refused: otherwise the map
|
||||
// grows without bound for any flow that is started and abandoned.
|
||||
func TestNewSpotifyStatePrunesExpired(t *testing.T) {
|
||||
s := &Store{}
|
||||
stale, _ := s.NewSpotifyState()
|
||||
s.spotifyStates[stale] = time.Now().Add(-spotifyStateTTL - time.Second)
|
||||
|
||||
if _, err := s.NewSpotifyState(); err != nil {
|
||||
t.Fatalf("NewSpotifyState: %v", err)
|
||||
}
|
||||
if _, ok := s.spotifyStates[stale]; ok {
|
||||
t.Fatal("minting a new state should have pruned the expired one")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Cache TTL rules ------------------------------------------------------
|
||||
|
||||
// Each cache treats "empty" as stale, which is deliberate (an empty listening
|
||||
// history or games list is re-fetched rather than cached). These tables pin
|
||||
// that down so it cannot be "fixed" into caching emptiness by accident.
|
||||
func TestCachedRecentSongsFreshness(t *testing.T) {
|
||||
song := []spotify.RecentlyPlayedItem{{}}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(s *Store)
|
||||
wantOK bool
|
||||
}{
|
||||
{"never fetched", func(*Store) {}, false},
|
||||
{"fetched but empty counts as stale", func(s *Store) {
|
||||
s.SetRecentSongs([]spotify.RecentlyPlayedItem{})
|
||||
}, false},
|
||||
{"just fetched", func(s *Store) { s.SetRecentSongs(song) }, true},
|
||||
{"inside the one-minute TTL", func(s *Store) {
|
||||
s.SetRecentSongs(song)
|
||||
s.RecentSongsFetchedAt = time.Now().Add(-59 * time.Second)
|
||||
}, true},
|
||||
{"past the one-minute TTL", func(s *Store) {
|
||||
s.SetRecentSongs(song)
|
||||
s.RecentSongsFetchedAt = time.Now().Add(-time.Minute - time.Second)
|
||||
}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := &Store{}
|
||||
c.setup(s)
|
||||
if _, ok := s.CachedRecentSongs(); ok != c.wantOK {
|
||||
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedGiteaFeedFreshness(t *testing.T) {
|
||||
feed := &services.GiteaFeedResponse{}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(s *Store)
|
||||
wantOK bool
|
||||
}{
|
||||
{"never fetched", func(*Store) {}, false},
|
||||
{"just fetched", func(s *Store) { s.SetGiteaFeed(feed) }, true},
|
||||
{"past the one-minute TTL", func(s *Store) {
|
||||
s.SetGiteaFeed(feed)
|
||||
s.GiteaFeedFetchedAt = time.Now().Add(-time.Minute - time.Second)
|
||||
}, false},
|
||||
// Unlike the songs cache, a nil feed is the only "empty" here, and a
|
||||
// nil stored feed must never read as fresh.
|
||||
{"explicitly cached nil is never fresh", func(s *Store) { s.SetGiteaFeed(nil) }, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := &Store{}
|
||||
c.setup(s)
|
||||
if _, ok := s.CachedGiteaFeed(); ok != c.wantOK {
|
||||
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedSteamFreshness(t *testing.T) {
|
||||
games := []services.SteamRecentGame{{}}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(s *Store)
|
||||
wantOK bool
|
||||
wantOnline bool
|
||||
}{
|
||||
{"never fetched", func(*Store) {}, false, false},
|
||||
{"just fetched, online flag preserved", func(s *Store) { s.SetSteam(games, true) }, true, true},
|
||||
{"just fetched, offline", func(s *Store) { s.SetSteam(games, false) }, true, false},
|
||||
{"nil games list counts as stale even when online", func(s *Store) { s.SetSteam(nil, true) }, false, false},
|
||||
{"past the five-minute TTL", func(s *Store) {
|
||||
s.SetSteam(games, true)
|
||||
s.SteamFetchedAt = time.Now().Add(-5*time.Minute - time.Second)
|
||||
}, false, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := &Store{}
|
||||
c.setup(s)
|
||||
_, online, ok := s.CachedSteam()
|
||||
if ok != c.wantOK {
|
||||
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
|
||||
}
|
||||
if online != c.wantOnline {
|
||||
t.Fatalf("online = %v, want %v", online, c.wantOnline)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- Upload trust boundary ------------------------------------------------
|
||||
|
||||
// requestIsAdmin gates private (admin-only) attachment uploads, so every way
|
||||
// the claim can be absent or the wrong shape must read as "not admin". No DB
|
||||
// or network is involved: it only inspects the Gin context.
|
||||
func TestRequestIsAdmin(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
claims := func(m jwt.MapClaims) any { return &m }
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
// set is nil when nothing should be put in the context at all.
|
||||
set any
|
||||
want bool
|
||||
}{
|
||||
{"no claims in context at all", nil, false},
|
||||
{"claims of the wrong type are not trusted", "not-claims", false},
|
||||
// A by-value jwt.MapClaims is not what AuthMiddlewear stores; accepting
|
||||
// it would mean the type assertion had been loosened.
|
||||
{"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false},
|
||||
{"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false},
|
||||
{"admin false", claims(jwt.MapClaims{"admin": false}), false},
|
||||
{"admin as a string is not a truthy admin", claims(jwt.MapClaims{"admin": "true"}), false},
|
||||
{"admin true", claims(jwt.MapClaims{"admin": true}), true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
if c.set != nil {
|
||||
ctx.Set("userClaims", c.set)
|
||||
}
|
||||
if got := requestIsAdmin(ctx); got != c.want {
|
||||
t.Fatalf("requestIsAdmin = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The allow-list tables are the upload trust boundary's data. Testing them as
|
||||
// data catches the realistic failure: someone adding an executable or markup
|
||||
// extension, or adding an extension to the MIME map without allowing it (which
|
||||
// would be dead configuration).
|
||||
func TestUploadAllowLists(t *testing.T) {
|
||||
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
|
||||
// Served by nginx from a public directory with no auth, so anything
|
||||
// the browser will execute or render as markup must not be storable.
|
||||
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
|
||||
if allowedExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed chat upload extension", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
|
||||
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
|
||||
// any other shape is unreachable.
|
||||
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
|
||||
for ext := range m {
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("malformed allow-list key %q", ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
|
||||
for ext := range extensionToMIMEPrefix {
|
||||
if !allowedExtensions[ext] {
|
||||
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("audio extensions are content-unverified by design", func(t *testing.T) {
|
||||
// http.DetectContentType is unreliable for these, so a missing entry
|
||||
// means "extension allowed, content not verified". Adding one would
|
||||
// start rejecting legitimate uploads.
|
||||
for _, ext := range []string{".mp3", ".ogg"} {
|
||||
if _, ok := extensionToMIMEPrefix[ext]; ok {
|
||||
t.Errorf("%q should not be MIME-checked", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("radio allow-list is audio only", func(t *testing.T) {
|
||||
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
|
||||
if allowedAudioExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed radio upload extension", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Companion to auth_test.go, covering the two pure things it leaves out: the
|
||||
// expiry the minting code bakes into each token, and the cookie attributes
|
||||
// SetAuthCookies/ClearAuthCookies emit.
|
||||
//
|
||||
// DELIBERATELY NOT COVERED HERE:
|
||||
// - AuthenticateToken past the id claim, and BumpTokenVersion: both need a
|
||||
// live *gorm.DB and the only driver in go.mod is postgres.
|
||||
// - Everything auth_test.go already covers (tokenVersionOf, the claim split,
|
||||
// the VerifyJWT rejection table) — not duplicated.
|
||||
// - Password hashing: there is none in this package; handlers own it.
|
||||
//
|
||||
// Cookie assertions go through a real gin context because gin, not this
|
||||
// package, is what turns the SetCookie arguments into a header — asserting on
|
||||
// the arguments alone would test nothing.
|
||||
|
||||
// cookiesFrom runs fn against a throwaway gin context and returns what it set,
|
||||
// keyed by cookie name.
|
||||
func cookiesFrom(fn func(*gin.Context)) map[string]*http.Cookie {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
gc, _ := gin.CreateTestContext(rec)
|
||||
fn(gc)
|
||||
|
||||
out := map[string]*http.Cookie{}
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
out[c.Name] = c
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// exp must track the configured lifetime, because the cookie max-age is derived
|
||||
// from the same number: if they disagreed the browser would hold a dead cookie
|
||||
// or drop a live one.
|
||||
func TestGenerateJWTExpiryMatchesConfiguredLifetime(t *testing.T) {
|
||||
auth := testAuth()
|
||||
issued := time.Now()
|
||||
|
||||
tokens, err := auth.GenerateJWT(&models.User{ID: 7, Username: "adam", TokenVersion: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateJWT: %v", err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
token string
|
||||
want time.Duration
|
||||
}{
|
||||
{"access token expires after AccessTokenLifetime", tokens.AccessToken, auth.Config.AccessTokenLifetime},
|
||||
{"refresh token expires after RefreshTokenLifetime", tokens.RefreshToken, auth.Config.RefreshTokenLifetime},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
claims, err := auth.VerifyJWT(c.token)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyJWT: %v", err)
|
||||
}
|
||||
exp, ok := (*claims)["exp"].(float64)
|
||||
if !ok {
|
||||
t.Fatal("token carries no numeric exp claim")
|
||||
}
|
||||
// A couple of seconds of slack: exp is whole seconds and the two
|
||||
// tokens are minted a hair apart.
|
||||
got := time.Unix(int64(exp), 0).Sub(issued)
|
||||
if got < c.want-2*time.Second || got > c.want+2*time.Second {
|
||||
t.Fatalf("exp is %v after minting, want ~%v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAuthCookies(t *testing.T) {
|
||||
config := testAuth().Config
|
||||
tokens := &Tokens{AccessToken: "access-value", RefreshToken: "refresh-value"}
|
||||
got := cookiesFrom(func(gc *gin.Context) { SetAuthCookies(gc, config, tokens) })
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cookie string
|
||||
wantValue string
|
||||
wantMaxAge int
|
||||
}{
|
||||
{"access cookie carries the access token and its lifetime", "access_token", "access-value", int(config.AccessTokenLifetime.Seconds())},
|
||||
{"refresh cookie carries the refresh token and its lifetime", "refresh_token", "refresh-value", int(config.RefreshTokenLifetime.Seconds())},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
ck := got[c.cookie]
|
||||
if ck == nil {
|
||||
t.Fatalf("no %s cookie was set", c.cookie)
|
||||
}
|
||||
if ck.Value != c.wantValue {
|
||||
t.Errorf("value = %q, want %q", ck.Value, c.wantValue)
|
||||
}
|
||||
if ck.MaxAge != c.wantMaxAge {
|
||||
t.Errorf("max-age = %d, want %d (the token's own lifetime)", ck.MaxAge, c.wantMaxAge)
|
||||
}
|
||||
// These four are the security contract: unreadable from JS, never
|
||||
// sent in clear, and not attached to cross-site POSTs.
|
||||
if !ck.HttpOnly {
|
||||
t.Error("cookie must be HttpOnly")
|
||||
}
|
||||
if !ck.Secure {
|
||||
t.Error("cookie must be Secure")
|
||||
}
|
||||
if ck.SameSite != http.SameSiteLaxMode {
|
||||
t.Errorf("SameSite = %v, want Lax", ck.SameSite)
|
||||
}
|
||||
if ck.Path != "/" || ck.Domain != config.Domain {
|
||||
t.Errorf("path/domain = %q/%q, want \"/\"/%q", ck.Path, ck.Domain, config.Domain)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A browser only replaces a cookie when path, domain and flags match the
|
||||
// original, so a deletion that differs in any of them silently leaves the user
|
||||
// logged in. Hence asserting the attributes, not just the negative max-age.
|
||||
func TestClearAuthCookiesMatchesTheCookiesItDeletes(t *testing.T) {
|
||||
config := testAuth().Config
|
||||
set := cookiesFrom(func(gc *gin.Context) {
|
||||
SetAuthCookies(gc, config, &Tokens{AccessToken: "a", RefreshToken: "r"})
|
||||
})
|
||||
cleared := cookiesFrom(func(gc *gin.Context) { ClearAuthCookies(gc, config) })
|
||||
|
||||
for _, name := range []string{"access_token", "refresh_token"} {
|
||||
t.Run(name+" is expired with attributes matching the original", func(t *testing.T) {
|
||||
ck, orig := cleared[name], set[name]
|
||||
if ck == nil || orig == nil {
|
||||
t.Fatalf("missing %s cookie", name)
|
||||
}
|
||||
if ck.Value != "" {
|
||||
t.Errorf("value = %q, want empty", ck.Value)
|
||||
}
|
||||
if ck.MaxAge >= 0 {
|
||||
t.Errorf("max-age = %d, want negative so the browser deletes it", ck.MaxAge)
|
||||
}
|
||||
if ck.Path != orig.Path || ck.Domain != orig.Domain ||
|
||||
ck.Secure != orig.Secure || ck.HttpOnly != orig.HttpOnly || ck.SameSite != orig.SameSite {
|
||||
t.Errorf("attributes differ from the cookie being deleted:\n cleared %+v\n set %+v", ck, orig)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -308,8 +310,19 @@ func parseRawEmail(raw string) (graphMessage, error) {
|
||||
// Extract body text
|
||||
bodyContent := extractTextBody(msg.Header, msg.Body)
|
||||
|
||||
// Dedup is keyed on GraphMessageID: a missing Message-ID header would
|
||||
// yield "", which collides every headerless message onto one shared row
|
||||
// (the first one processed, forever). Synthesise an id from stable
|
||||
// message traits instead — hashing because From/Date/Subject/size are not
|
||||
// unique alone but their combination is stable across retries.
|
||||
msgID := header.Get("Message-ID")
|
||||
if msgID == "" {
|
||||
hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent))
|
||||
msgID = "synth-" + hex.EncodeToString(hash[:8])
|
||||
}
|
||||
|
||||
return graphMessage{
|
||||
ID: header.Get("Message-ID"),
|
||||
ID: msgID,
|
||||
Subject: decodeHeader(header.Get("Subject")),
|
||||
ReceivedDateTime: parsedDate.Format(time.RFC3339),
|
||||
From: graphFrom{
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package services
|
||||
|
||||
import "testing"
|
||||
|
||||
// These tests cover the status progression rule only — statusAdvances, the
|
||||
// predicate extracted out of updateJobApplication. The rest of
|
||||
// updateJobApplication (note appending, the DB.Save, the returned counters)
|
||||
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
|
||||
// deliberately not exercised here. Nothing in this file touches Claude or the
|
||||
// Graph API either; email classification is a network call by construction.
|
||||
|
||||
func TestStatusAdvances(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
current string
|
||||
next string
|
||||
want bool
|
||||
}{
|
||||
{"one step forward is the normal case", "applied", "screening", true},
|
||||
{"skipping intermediate stages still advances", "applied", "offer", true},
|
||||
{"adjacent step backwards is refused", "interviewing", "assessment", false},
|
||||
{"a long way backwards is refused", "offer", "applied", false},
|
||||
{"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false},
|
||||
|
||||
// rejected and withdrawn sit at the top of statusOrder: once an
|
||||
// application lands there, no later email may move it.
|
||||
{"rejected cannot fall back to interviewing", "rejected", "interviewing", false},
|
||||
{"rejected cannot fall back to offer", "rejected", "offer", false},
|
||||
{"rejected cannot repeat", "rejected", "rejected", false},
|
||||
{"withdrawn cannot fall back to offer", "withdrawn", "offer", false},
|
||||
{"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false},
|
||||
{"withdrawn cannot repeat", "withdrawn", "withdrawn", false},
|
||||
// The one ordering asymmetry between the two terminals: withdrawn
|
||||
// ranks above rejected, so this single pair is allowed.
|
||||
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
|
||||
|
||||
{"an unknown new status is never applied", "applied", "hired", false},
|
||||
{"an empty new status is never applied", "applied", "", false},
|
||||
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
|
||||
{"a recognised status takes over from an unknown current status", "ghosted", "applied", true},
|
||||
{"a recognised status takes over from an empty current status", "", "offer", true},
|
||||
{"unknown to unknown stays put", "ghosted", "hired", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := statusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the claim the other tests rest on: rejected and withdrawn really are
|
||||
// the top of the ranking, so adding a stage below them cannot silently make
|
||||
// them non-terminal.
|
||||
func TestTerminalStatusesRankHighest(t *testing.T) {
|
||||
for status, order := range statusOrder {
|
||||
if status == "rejected" || status == "withdrawn" {
|
||||
continue
|
||||
}
|
||||
if order >= statusOrder["rejected"] {
|
||||
t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
|
||||
// ("Interview", "on hold") out of the status column: an unrecognised value
|
||||
// stored verbatim makes statusAdvances treat the row's current status as
|
||||
// unknown, which switches the forward-only rule off for that row entirely.
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"a tracked status passes through", "interviewing", "interviewing"},
|
||||
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
|
||||
{"surrounding whitespace is trimmed", " offer ", "offer"},
|
||||
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
|
||||
{"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"},
|
||||
{"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"},
|
||||
{"empty falls back rather than storing a blank status", "", "applied"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := NormalizeStatus(c.in); got != c.want {
|
||||
t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -393,17 +394,23 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Window start = when the last email was *processed*, not when it was
|
||||
// received. Those differ by up to one sync interval, which is deliberate:
|
||||
// it overlaps the windows so nothing that arrived mid-sync is missed. The
|
||||
// overlap re-fetches a few emails, and the ProcessedEmail dedup below is
|
||||
// what stops them being handled twice. On a cold database (no processed
|
||||
// emails at all) it falls back to the last 24 hours, so the pipeline
|
||||
// never tries to ingest an entire mailbox.
|
||||
// Window start comes from the newest email we have ever *received* (one of
|
||||
// two clocks in play) rather than from when we processed it: receive time
|
||||
// lags processing time by up to one sync duration, and a later window
|
||||
// anchored to processing time would start AFTER mail that arrived just at
|
||||
// the previous fetch — a permanent hole (the overlap the code always meant
|
||||
// to have is produced only when both edges speak the same clock).
|
||||
// Anchoring on ReceivedAt keeps the window behind the fetch, the
|
||||
// ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a
|
||||
// cold database it falls back to the last 24 hours so the pipeline never
|
||||
// tries to ingest an entire mailbox.
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil {
|
||||
since = latest.CreatedAt
|
||||
if err := s.DB.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil {
|
||||
// Pull the window back one slack period so mail delivered a second or
|
||||
// two after the last fetch (or indexed late by the provider) is still
|
||||
// inside the next window; dedup makes re-processing it harmless.
|
||||
since = latest.ReceivedAt.Add(-fetchSlack)
|
||||
}
|
||||
|
||||
// Pull the window back to cover any still-retryable failure. Without this
|
||||
@@ -411,9 +418,15 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
// is written now, so the next window starts after it — and the retry
|
||||
// below could never see the email again. Rows predating ReceivedAt have
|
||||
// a zero value and are ignored rather than dragging the window to 0001.
|
||||
//
|
||||
// Old failures are age-capped: attempts only advance when the email is
|
||||
// actually re-fetched, so a message that has left the mailbox would stay
|
||||
// under the cap forever and rewind every sync on this day's fetch. After
|
||||
// maxRewindAge the email is treated as gone, like any abandoned retry.
|
||||
var oldestRetryable models.ProcessedEmail
|
||||
if err := s.DB.
|
||||
Where("action = ? AND attempts < ? AND received_at > ?", "error", maxEmailAttempts, time.Time{}).
|
||||
Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?",
|
||||
"error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)).
|
||||
Order("received_at ASC").
|
||||
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
|
||||
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
|
||||
@@ -456,7 +469,17 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
|
||||
// The row carries the outcome either way. On failure the attempt
|
||||
// counter advances, so repeated failures walk the row towards the cap
|
||||
// and it eventually stops being retried.
|
||||
// and it eventually stops being retried. A cancelled sync (the admin
|
||||
// closed the tab mid-backlog, or nginx cut the request) is not a
|
||||
// failure of the email, though: attempts must not advance for it, or
|
||||
// two closed tabs would strand a healthy email at the cap and skip it
|
||||
// forever. Writing nothing preserves the existing row untouched, so it
|
||||
// is simply retried at the next sync.
|
||||
if processErr != nil && errors.Is(processErr, context.Canceled) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
record := models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
@@ -647,12 +670,22 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
// wording the same role slightly differently therefore creates a second
|
||||
// application rather than updating the first. The most recent match wins
|
||||
// when there are several.
|
||||
// The lookup is Unscoped: a deleted-with-notes row is stored, not purged
|
||||
// (see models.JobApplication), so invisibility here makes the matcher
|
||||
// believe the application never existed and a follow-up email in the same
|
||||
// thread re-creates it — the admin deletes it, it comes back. A hit on a
|
||||
// deleted row instead becomes a suppression: nothing is updated, nothing
|
||||
// is created, and the pipeline leaves the deletion to stand.
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
Order("created_at DESC").
|
||||
First(&existing).Error == nil
|
||||
|
||||
if found && existing.DeletedAt.Valid {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if found && analysis.Action == "update" {
|
||||
return s.updateJobApplication(&existing, &analysis)
|
||||
}
|
||||
@@ -665,12 +698,25 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
// NormalizeStatus coerces Claude's status guess into the tracked vocabulary,
|
||||
// lowering the case it occasionally drifts on and rejecting anything outside
|
||||
// statusOrder. An unrecognised status stored verbatim would disable the
|
||||
// forward-only guard for that row (updateJobApplication allows any recognised
|
||||
// status over an unknown one), so the safe fallback is the pipeline's default.
|
||||
func NormalizeStatus(s string) string {
|
||||
lowered := strings.ToLower(strings.TrimSpace(s))
|
||||
if _, ok := statusOrder[lowered]; ok {
|
||||
return lowered
|
||||
}
|
||||
return "applied"
|
||||
}
|
||||
|
||||
// createJobApplication inserts a new application from Claude's analysis.
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
JobTitle: analysis.JobTitle,
|
||||
Status: analysis.Status,
|
||||
Status: NormalizeStatus(analysis.Status),
|
||||
Location: analysis.Location,
|
||||
URL: analysis.URL,
|
||||
Notes: analysis.Notes,
|
||||
@@ -698,16 +744,22 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards through statusOrder. Emails commonly arrive out of order (a
|
||||
// delayed "thanks for applying" after an interview invite), and this is what
|
||||
// stops a stale email dragging an application backwards.
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
newOrder, newExists := statusOrder[analysis.Status]
|
||||
currentOrder, currentExists := statusOrder[existing.Status]
|
||||
// statusAdvances reports whether next is a forward move from current through
|
||||
// statusOrder. Emails commonly arrive out of order (a delayed "thanks for
|
||||
// applying" after an interview invite), and this is what stops a stale email
|
||||
// dragging an application backwards. An unknown next status is never applied;
|
||||
// an unknown current status is treated as "anywhere before the start", so any
|
||||
// recognised status can take over from it.
|
||||
func statusAdvances(current, next string) bool {
|
||||
nextOrder, nextExists := statusOrder[next]
|
||||
currentOrder, currentExists := statusOrder[current]
|
||||
return nextExists && (!currentExists || nextOrder > currentOrder)
|
||||
}
|
||||
|
||||
// Only update if the new status represents progression
|
||||
if !newExists || (currentExists && newOrder <= currentOrder) {
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards (see statusAdvances).
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
if !statusAdvances(existing.Status, analysis.Status) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
@@ -853,6 +905,18 @@ func StripMarkdownFence(raw string) string {
|
||||
// outage two further chances across subsequent syncs.
|
||||
const maxEmailAttempts = 3
|
||||
|
||||
// fetchSlack pulls each sync's window edge back by this much so mail that was
|
||||
// delayed between fetch and filter (or index-registered late) is still caught
|
||||
// by the next window. Consumers pay for it with deliberate re-fetches, which
|
||||
// the ProcessedEmail dedup makes free.
|
||||
const fetchSlack = 30 * time.Second
|
||||
|
||||
// maxRewindAge stops a stuck retry from pinning the window open forever. A
|
||||
// failed email is only rewound for while it is younger than this; past that it
|
||||
// has probably been deleted from the mailbox or fallen out of the provider's
|
||||
// returns, so re-fetching for it would never yield anything.
|
||||
const maxRewindAge = 7 * 24 * time.Hour
|
||||
|
||||
// retryableFailure reports whether a previously recorded email should be
|
||||
// processed again. Only failures are retried, and only while they have
|
||||
// attempts left; anything that succeeded is terminal.
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// These tests cover only the pure helpers of the email sync: body cleaning,
|
||||
// truncation, fence stripping, timestamp parsing, the retry predicate and the
|
||||
// filter. Everything else in email_sync.go — token acquisition, the Graph
|
||||
// paging loop, processEmail and the create/update paths — needs either a live
|
||||
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
|
||||
// in a test run, so they are deliberately not exercised here.
|
||||
//
|
||||
// matchesFilter is a method but reads no field of the receiver (it matches
|
||||
// against the package-level subjectKeywords/senderDomains), which is why a
|
||||
// zero-value &EmailSyncService{} is a legitimate receiver below.
|
||||
|
||||
func TestCleanEmailBody(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
contentType string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"html tags are stripped and entities decoded",
|
||||
"<p>Hi Adam & team</p><b>thanks</b>",
|
||||
"html",
|
||||
"Hi Adam & team thanks",
|
||||
},
|
||||
{
|
||||
"contentType match is case-insensitive",
|
||||
"<p>hello</p>",
|
||||
"HTML",
|
||||
"hello",
|
||||
},
|
||||
{
|
||||
// Entities are only decoded on the HTML path, so plain text keeps
|
||||
// them verbatim rather than being silently rewritten.
|
||||
"text bodies are not entity-decoded",
|
||||
"a & b",
|
||||
"text",
|
||||
"a & b",
|
||||
},
|
||||
{
|
||||
"runs of spaces and tabs collapse to one space",
|
||||
"one \t two",
|
||||
"text",
|
||||
"one two",
|
||||
},
|
||||
{
|
||||
"three or more newlines collapse to a blank line",
|
||||
"a\n\n\n\n\nb",
|
||||
"text",
|
||||
"a\n\nb",
|
||||
},
|
||||
{
|
||||
"signature marker cuts the tail",
|
||||
"body text\n-- \nAdam French\n07000",
|
||||
"text",
|
||||
"body text",
|
||||
},
|
||||
{
|
||||
"Sent from my iPhone is treated as a signature",
|
||||
"see attached\nSent from my iPhone",
|
||||
"text",
|
||||
"see attached",
|
||||
},
|
||||
{
|
||||
// idx > 0, not >= 0: a body that is nothing but a signature would
|
||||
// otherwise be blanked entirely, losing the only content there is.
|
||||
"a body starting with a signature marker is left intact",
|
||||
"Sent from my iPhone\nreal content",
|
||||
"text",
|
||||
"Sent from my iPhone\nreal content",
|
||||
},
|
||||
{
|
||||
"quoted lines are dropped",
|
||||
"my reply\n> their mail\n > indented quote\nmore reply",
|
||||
"text",
|
||||
"my reply\nmore reply",
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := cleanEmailBody(c.content, c.contentType); got != c.want {
|
||||
t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The 4000-byte cap is what bounds the prompt cost, so it gets its own test:
|
||||
// the cut is by bytes and is applied before the final TrimSpace.
|
||||
func TestCleanEmailBodyCap(t *testing.T) {
|
||||
got := cleanEmailBody(strings.Repeat("a", 5000), "text")
|
||||
if len(got) != 4000 {
|
||||
t.Fatalf("len = %d, want 4000", len(got))
|
||||
}
|
||||
|
||||
// A body exactly at the cap must pass through untouched.
|
||||
exact := strings.Repeat("b", 4000)
|
||||
if got := cleanEmailBody(exact, "text"); got != exact {
|
||||
t.Fatalf("body at the cap was modified: len = %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
s string
|
||||
maxLen int
|
||||
want string
|
||||
}{
|
||||
{"shorter than the cap is unchanged", "abc", 10, "abc"},
|
||||
{"exactly at the cap is unchanged", "abcde", 5, "abcde"},
|
||||
{"longer is cut to the cap", "abcdef", 3, "abc"},
|
||||
{"zero cap yields the empty string", "abc", 0, ""},
|
||||
{"empty input", "", 5, ""},
|
||||
// Bytes, not runes: the cut can land mid-rune. Asserted so the
|
||||
// behaviour is a documented choice rather than a lurking surprise.
|
||||
{"multi-byte runes are cut by byte", "é", 1, "\xc3"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := truncate(c.s, c.maxLen); got != c.want {
|
||||
t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownFence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
|
||||
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
|
||||
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
|
||||
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
|
||||
{"empty input", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StripMarkdownFence(c.raw); got != c.want {
|
||||
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReceivedAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want time.Time
|
||||
}{
|
||||
{"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)},
|
||||
{"empty means no timestamp", "", time.Time{}},
|
||||
{"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}},
|
||||
{"a date without a time is not RFC3339", "2024-03-15", time.Time{}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := parseReceivedAt(c.raw); !got.Equal(c.want) {
|
||||
t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryableFailure(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
attempts int
|
||||
want bool
|
||||
}{
|
||||
{"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true},
|
||||
{"a failure at the cap is abandoned", "error", maxEmailAttempts, false},
|
||||
{"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false},
|
||||
{"a success is terminal even with attempts left", "created", 0, false},
|
||||
{"a skip is terminal too", "skipped", 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts}
|
||||
if got := retryableFailure(row); got != c.want {
|
||||
t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesFilter(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
subject string
|
||||
sender string
|
||||
want bool
|
||||
}{
|
||||
{"subject keyword anywhere in the line", "Your application to Acme", "[email protected]", true},
|
||||
{"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "[email protected]", true},
|
||||
{"sender on a tracked ATS domain", "hello", "[email protected]", true},
|
||||
{"sender on a subdomain of a tracked domain", "hello", "[email protected]", true},
|
||||
{"sender domain match is case-insensitive", "hello", "[email protected]", true},
|
||||
// The rule is an @ or . boundary, so a lookalike domain that merely
|
||||
// ends in the same letters must not match.
|
||||
{"lookalike domain does not match", "hello", "[email protected]", false},
|
||||
{"neither subject nor sender matches", "lunch tomorrow?", "[email protected]", false},
|
||||
}
|
||||
|
||||
s := &EmailSyncService{}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
email := graphMessage{Subject: c.subject}
|
||||
email.From.EmailAddress.Address = c.sender
|
||||
if got := s.matchesFilter(email); got != c.want {
|
||||
t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Covered here: the pure logic in ratelimit.go, notes.go and gitea.go —
|
||||
// sliding-window arithmetic, the path-traversal guard, and the two-stage JSON
|
||||
// decoding of a Gitea feed entry (from a hand-written fixture).
|
||||
//
|
||||
// Deliberately not covered:
|
||||
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
|
||||
// logic beyond the request is the empty-feed nil,nil case, and testing it
|
||||
// would mean either a network or an injected client that does not exist.
|
||||
// - claude.go: InitClaude is a single SDK constructor with no validation and
|
||||
// no prompt building; there is nothing to assert that is not the SDK's.
|
||||
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
|
||||
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
|
||||
// directly and there is no injectable clock), so the expiry case below
|
||||
// uses a deliberately tiny window rather than a long sleep.
|
||||
|
||||
func TestRateLimiterAllow(t *testing.T) {
|
||||
t.Run("calls up to max are allowed", func(t *testing.T) {
|
||||
rl := NewRateLimiter(3, time.Minute)
|
||||
for i := 1; i <= 3; i++ {
|
||||
if !rl.Allow("ip") {
|
||||
t.Fatalf("call %d denied, want allowed", i)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the call after max is denied", func(t *testing.T) {
|
||||
rl := NewRateLimiter(2, time.Minute)
|
||||
rl.Allow("ip")
|
||||
rl.Allow("ip")
|
||||
if rl.Allow("ip") {
|
||||
t.Fatal("third call allowed, want denied")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a denied attempt is not recorded, so it cannot extend the lockout", func(t *testing.T) {
|
||||
rl := NewRateLimiter(1, time.Minute)
|
||||
rl.Allow("ip")
|
||||
for i := 0; i < 5; i++ {
|
||||
rl.Allow("ip")
|
||||
}
|
||||
// One timestamp only: the rejected hammering must not have been stored.
|
||||
if got := len(rl.attempts["ip"]); got != 1 {
|
||||
t.Fatalf("stored %d attempts, want 1", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keys are limited independently", func(t *testing.T) {
|
||||
rl := NewRateLimiter(1, time.Minute)
|
||||
rl.Allow("a")
|
||||
if !rl.Allow("b") {
|
||||
t.Fatal("second key denied, want allowed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("attempts older than the window stop counting", func(t *testing.T) {
|
||||
rl := NewRateLimiter(1, 5*time.Millisecond)
|
||||
rl.Allow("ip")
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if !rl.Allow("ip") {
|
||||
t.Fatal("denied after the window elapsed, want allowed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("max of zero denies everything", func(t *testing.T) {
|
||||
rl := NewRateLimiter(0, time.Minute)
|
||||
if rl.Allow("ip") {
|
||||
t.Fatal("call allowed with max 0, want denied")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotesParsePath(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
notes := InitNotes(&NotesConfig{Dir: base})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string // relative to base; ignored when wantErr
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty path is the wiki index", "", "Index.md", false},
|
||||
{"bare slash is the wiki index", "/", "Index.md", false},
|
||||
{"a plain file resolves inside the dir", "/Notes.md", "Notes.md", false},
|
||||
{"a nested file resolves inside the dir", "/private/Secret.md", "private/Secret.md", false},
|
||||
{"embedded .. that stays inside is fine", "/a/../b.md", "b.md", false},
|
||||
{"traversal above the base is rejected", "/../escape.md", "", true},
|
||||
{"deep traversal is rejected", "/a/../../escape.md", "", true},
|
||||
{"the base dir itself is rejected, only children are servable", "/.", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, err := notes.ParsePath(c.in)
|
||||
if c.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ParsePath(%q) = %q, want error", c.in, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParsePath(%q) errored: %v", c.in, err)
|
||||
}
|
||||
if want := filepath.Join(base, c.want); got != want {
|
||||
t.Fatalf("ParsePath(%q) = %q, want %q", c.in, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The sibling-directory case is the reason ParsePath appends a separator
|
||||
// before the prefix check, so it gets its own test with real neighbouring dirs.
|
||||
func TestNotesParsePathRejectsSiblingPrefix(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
base := filepath.Join(parent, "notes")
|
||||
if err := os.Mkdir(base, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(parent, "notes-private"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
notes := InitNotes(&NotesConfig{Dir: base})
|
||||
if got, err := notes.ParsePath("/../notes-private/Secret.md"); err == nil {
|
||||
t.Fatalf("ParsePath resolved into a sibling dir: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCommitMessage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"first commit message of a push event",
|
||||
`{"Commits":[{"Message":"fix nginx template\n"},{"Message":"second"}]}`,
|
||||
"fix nginx template\n",
|
||||
},
|
||||
{"push event with no commits", `{"Commits":[]}`, ""},
|
||||
{"non-push event whose Content is a different shape", `"some string"`, ""},
|
||||
{"empty Content, as sent for events with no payload", "", ""},
|
||||
{"malformed JSON is swallowed rather than surfaced", `{"Commits":`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := ParseCommitMessage(c.in); got != c.want {
|
||||
t.Fatalf("ParseCommitMessage(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the struct tags against a rename: Gitea's feed uses capitalised keys
|
||||
// inside Content but snake_case at the top level, which is easy to "tidy" wrongly.
|
||||
func TestGiteaFeedResponseDecoding(t *testing.T) {
|
||||
const fixture = `[{
|
||||
"act_user": {"avatar_url": "http://gitea:3000/avatars/1", "login": "adamf"},
|
||||
"repo": {"full_name": "adamf/web_server", "html_url": "http://gitea:3000/adamf/web_server"},
|
||||
"op_type": "commit_repo",
|
||||
"content": "{\"Commits\":[{\"Message\":\"add tests\"}]}",
|
||||
"created": "2026-09-22T10:30:00Z",
|
||||
"unknown_field": 1
|
||||
}]`
|
||||
|
||||
var items []GiteaFeedResponse
|
||||
if err := json.Unmarshal([]byte(fixture), &items); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("got %d entries, want 1", len(items))
|
||||
}
|
||||
|
||||
got := items[0]
|
||||
if got.ActUser.AvatarURL != "http://gitea:3000/avatars/1" {
|
||||
t.Errorf("AvatarURL = %q", got.ActUser.AvatarURL)
|
||||
}
|
||||
if got.Repo.FullName != "adamf/web_server" {
|
||||
t.Errorf("FullName = %q", got.Repo.FullName)
|
||||
}
|
||||
if got.Repo.HTMLURL != "http://gitea:3000/adamf/web_server" {
|
||||
t.Errorf("HTMLURL = %q", got.Repo.HTMLURL)
|
||||
}
|
||||
if got.OpType != "commit_repo" {
|
||||
t.Errorf("OpType = %q", got.OpType)
|
||||
}
|
||||
if !got.Created.Equal(time.Date(2026, 9, 22, 10, 30, 0, 0, time.UTC)) {
|
||||
t.Errorf("Created = %v", got.Created)
|
||||
}
|
||||
// Content is the nested JSON string ParseCommitMessage then decodes.
|
||||
if msg := ParseCommitMessage(got.Content); msg != "add tests" {
|
||||
t.Errorf("ParseCommitMessage(Content) = %q, want %q", msg, "add tests")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user