* Make backend tests wait on conditions instead of durations The backend workflow has a long tail of runs that fail once and pass on a rerun. Every one of them comes down to a test assuming an operation finishes within some duration rather than waiting for the state it needs. Three were reproducible and each was reproduced against the old code before being changed: TestServerAuthHooks minted a token that lived one second and never tested expiry, so a slow runner turned the first POST into a 401; TestServerApp_AnonMode saw "connection refused" because waitForHTTPServerStart returned silently after three seconds and left a later assertion to fail with something unrelated; TestFsStore_Cleanup slept 200ms against a 300ms ttl that Cleanup widens to 400ms with its commit grace, so roughly 100ms of stall collected an image meant to survive. Fixed sleeps before asserting on asynchronous work are replaced with polls on the condition itself, using require.Eventually and require.EventuallyWithT, and require.Never where the assertion is that something did not happen. Polling closures assert on the CollectT they are handed rather than on t, since testify runs them on another goroutine, and polls that issue HTTP requests stay under the rate limit on the routes they poll through. Where a test needs time to have passed, the clock input is pinned instead: staging ages are stamped with os.Chtimes on both sides of the cleanup boundary right before each call, which also makes the 100ms commit grace an exact case rather than something no assertion reaches, and the RSS tests set store.Comment.Timestamp explicitly rather than racing the wall clock into the first 100ms of a second so pubDate matches. chooseUnusedPort takes a port from the kernel's ephemeral range. Picking at random out of a fixed 10000-port window let two package binaries, which go test ./... runs concurrently, land on the same number between the probe closing and the server binding. The start helpers fail naming the port they waited on, and the SSL tests wait on the redirect port as well as the TLS one. Arbitrary budgets that nothing tests are gone: ten HTTP clients with a one-second timeout against bolt-backed import and export, the "should take about 100msec" assertions, and a one-second bound on noticing an already cancelled context. Shutdown stays bounded at ten seconds so a hang is still caught. Two assertions get stronger. TestServerAuthHooks accepted 403 or 401 from a blocked user, an alternative that existed only because the short token could expire mid-test; it is deterministically 403 now. TestAdmin_BlockedList asserted two users blocked while one carried the same 150ms ttl the next step waits to lapse, so the halves raced each other. goleak stops reporting the regexp2 clock goroutine, which chroma pulls in for syntax highlighting and which lives for up to a second after the last match with a timeout; it ends on its own but a binary finishing inside that window was reported as leaking, and this suite now finishes sooner. The ignore for net/http.(*Server).Shutdown goes the other way: it no longer matches anything, with both packages run fifteen times each under CPU oversubscription to confirm. Two gaps the change would otherwise have opened are covered directly rather than left to the side effects that used to cover them. The one-second token was the only thing exercising the authenticator's ClaimsUpd hook on refresh, so TestServerApp_ClaimsUpd now calls the hook itself and checks admin, blocked, email and restricted-name impersonation, including the two pass-through cases. Lifting the open-route limit removed the last incidental exercise of the rate limiter, so TestRateLimiter drives a burst past the allowance and checks the refusals and that the limit is per client. Both run without a wall clock, and both were confirmed to fail when the behaviour they cover is removed. Production code is untouched. The two sleeps outside test code, the 429 backoff in cmd/cleanup.go and the submit poll in store/image/image.go, are left alone: no CI failure implicates them. Test sleeps drop from 67 to 21, all of them either inside a testing/synctest bubble or a poll interval. The suite runs in about 22 seconds instead of 46, mostly because TestPublic_FindCommentsCtrl_ConsistentCount no longer paces a hundred subtests with an 80ms sleep each to stay under the open route limit. The 300s per-package budget now matches across both workflows, the race_test target and the documented command, and CLAUDE.md records the convention. with '#' will be ignored, and an empty message aborts the commit. # # Date: Sat Aug 22 01:12:31 2026 +0100 # # interactive rebase in progress; onto7c312da1# Last command done (1 command done): # reword deb6cbf1 # Make backend tests wait on conditions instead of durations # Next command to do (1 remaining command): # reword 262e6dc2 # Apply go fix under Go 1.27 # You are currently editing a commit while rebasing branch 'fix/backend-test-flakiness' on '7c312da1'. # # Changes to be committed: .github/workflows/release.yml # modified: CLAUDE.md # modified: Makefile modified: backend/_example/memory_store/server/rpc_test.go # modified: backend/app/cmd/import_test.go # modified: backend/app/cmd/server_test.go # modified: backend/app/main_test.go # modified: backend/app/rest/api/admin_test.go # modified: backend/app/rest/api/middleware_test.go # modified: backend/app/rest/api/migrator_test.go # modified: backend/app/rest/api/rest_private_test.go # modified: backend/app/rest/api/rest_public_test.go # modified: backend/app/rest/api/rest_test.go # modified: backend/app/rest/api/rss_test.go # modified: backend/app/rest/proxy/image_test.go # modified: backend/app/store/image/fs_store_test.go # modified: backend/app/store/service/service_test.go # modified: docs/backlog/api-tests-deadlock-on-macos.md # * Apply go fix under Go 1.27 Go 1.27 extends go fix with the modernizers, so `go fix ./...` now rewrites patterns the language has since replaced. Running it across all three modules produces this: legacy sync/atomic calls on plain integers become the atomic types (notify.Service.closed, image.Service.term and submitCount, and several test counters), reverse index loops become slices.Backward, a Split-then-index becomes strings.Cut, counted loops become range over an int, and interface{} becomes any in the e2e suite. The example module needed no changes. The e2e module is behind a build tag, so it only matches with `go fix -tags e2e ./...`. One knock-on: prealloc can see the bound of a loop once it is written as range over an int, so the slice it feeds is now preallocated. with '#' will be ignored, and an empty message aborts the commit. # # Date: Sat Aug 22 01:32:09 2026 +0100 # # interactive rebase in progress; onto7c312da1# Last commands done (2 commands done): # reword deb6cbf1 262e6dc2 # Apply go fix under Go 1.27 # No commands remaining. # You are currently editing a commit while rebasing branch 'fix/backend-test-flakiness' on '7c312da1'. # # Changes to be committed: backend/app/migrator/native.go # modified: backend/app/notify/notify.go backend/app/rest/api/rest_private_test.go # modified: backend/app/store/comment.go # modified: backend/app/store/image/image.go # modified: backend/app/store/service/service_test.go # modified: backend/app/store/service/title_test.go # modified: e2e/e2e_test.go # modified: e2e/widgets_test.go #
194 lines
7.0 KiB
Go
194 lines
7.0 KiB
Go
package store
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/microcosm-cc/bluemonday"
|
|
)
|
|
|
|
// Comment represents a single comment with optional reference to its parent
|
|
type Comment struct {
|
|
ID string `json:"id" bson:"_id"`
|
|
ParentID string `json:"pid"`
|
|
Text string `json:"text"`
|
|
Orig string `json:"orig,omitempty"` // important: never render this as HTML! It's not sanitized.
|
|
User User `json:"user"`
|
|
Locator Locator `json:"locator"`
|
|
Score int `json:"score"`
|
|
Votes map[string]bool `json:"votes,omitempty"`
|
|
VotedIPs map[string]VotedIPInfo `json:"voted_ips,omitempty"` // voted ips (hashes) with TS
|
|
Vote int `json:"vote"` // vote for the current user, -1/1/0.
|
|
Controversy float64 `json:"controversy,omitempty"`
|
|
Timestamp time.Time `json:"time" bson:"time"`
|
|
Edit *Edit `json:"edit,omitempty" bson:"edit,omitempty"` // pointer to have empty default in json response
|
|
Pin bool `json:"pin,omitempty" bson:"pin,omitempty"`
|
|
Deleted bool `json:"delete,omitempty" bson:"delete"`
|
|
Imported bool `json:"imported,omitempty" bson:"imported"`
|
|
PostTitle string `json:"title,omitempty" bson:"title"`
|
|
}
|
|
|
|
// Locator keeps site and url of the post
|
|
type Locator struct {
|
|
SiteID string `json:"site,omitempty" bson:"site"`
|
|
URL string `json:"url"`
|
|
}
|
|
|
|
// Edit indication
|
|
type Edit struct {
|
|
Timestamp time.Time `json:"time" bson:"time"`
|
|
Summary string `json:"summary"`
|
|
}
|
|
|
|
// PostInfo holds summary for given post url
|
|
type PostInfo struct {
|
|
URL string `json:"url,omitempty"` // can be attached to site-wide comments but won't be set then
|
|
Count int `json:"count"`
|
|
CountLeft int `json:"count_left"` // used only with returning search results limited by number, otherwise zero
|
|
LastComment string `json:"last_comment,omitempty"` // used only with returning search results limited by number
|
|
ReadOnly bool `json:"read_only,omitempty" bson:"read_only,omitempty"` // can be attached to site-wide comments but won't be set then
|
|
FirstTS time.Time `json:"first_time" bson:"first_time,omitempty"`
|
|
LastTS time.Time `json:"last_time" bson:"last_time,omitempty"`
|
|
}
|
|
|
|
// BlockedUser holds id and ts for blocked user
|
|
type BlockedUser struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Until time.Time `json:"time"`
|
|
}
|
|
|
|
// VotedIPInfo keeps timestamp and voting value (direction). Used as VotedIPs value
|
|
type VotedIPInfo struct {
|
|
Timestamp time.Time
|
|
Value bool
|
|
}
|
|
|
|
// DeleteMode defines how much comment info will be erased
|
|
type DeleteMode int
|
|
|
|
// DeleteMode enum
|
|
const (
|
|
SoftDelete DeleteMode = 0
|
|
HardDelete DeleteMode = 1
|
|
)
|
|
|
|
// Maximum length for URL text shortening.
|
|
const shortURLLen = 48
|
|
const snippetLen = 200
|
|
|
|
// PrepareUntrusted pre-processes a comment received from untrusted source by clearing all
|
|
// autogen fields and reset everything users not supposed to provide
|
|
func (c *Comment) PrepareUntrusted() {
|
|
c.ID = "" // don't allow user to define ID, force auto-gen
|
|
c.Timestamp = time.Time{} // reset time, force auto-gen
|
|
c.Votes = make(map[string]bool)
|
|
c.VotedIPs = make(map[string]VotedIPInfo)
|
|
c.Score = 0
|
|
c.Controversy = 0
|
|
c.Edit = nil
|
|
c.Pin = false
|
|
c.Deleted = false
|
|
c.Imported = false
|
|
}
|
|
|
|
// SetDeleted clears comment info, reset to deleted state. hard flag will clear all user info as well
|
|
func (c *Comment) SetDeleted(mode DeleteMode) {
|
|
c.Text = ""
|
|
c.Orig = ""
|
|
c.Score = 0
|
|
c.Controversy = 0
|
|
c.Votes = map[string]bool{}
|
|
c.VotedIPs = make(map[string]VotedIPInfo)
|
|
c.Edit = nil
|
|
c.Deleted = true
|
|
c.Pin = false
|
|
|
|
if mode == HardDelete {
|
|
c.User.Name = "deleted"
|
|
c.User.ID = "deleted"
|
|
c.User.Picture = ""
|
|
c.User.IP = ""
|
|
}
|
|
}
|
|
|
|
// Sanitize clean dangerous html/js from the comment.
|
|
// Comment.Orig which is used to store the original comment text is not sanitized
|
|
// as we expect to never render it as HTML and render Comment.Text instead
|
|
func (c *Comment) Sanitize() {
|
|
p := bluemonday.UGCPolicy()
|
|
p.AllowAttrs("class").Matching(regexp.MustCompile("^chroma$")).OnElements("pre")
|
|
// special case for embedding the quotes from Twitter
|
|
p.AllowAttrs("class").Matching(regexp.MustCompile("^twitter-tweet$")).OnElements("blockquote")
|
|
// this is list of <span> tag classes which could be produced by chroma code renderer
|
|
// source: https://github.com/alecthomas/chroma/blob/c263f6f/types.go#L209-L306
|
|
const codeSpanClassRegex = "^(bg|chroma|line|ln|lnt|hl|lntable|lntd|lnlinks|cl|w|err|x|k|kc" +
|
|
"|kd|kn|kp|kr|kt|n|na|nb|bp|nc|no|nd|ni|ne|nf|fm|py|nl|nn|nx|nt|nv|vc|vg" +
|
|
"|vi|vm|l|ld|s|sa|sb|sc|dl|sd|s2|se|sh|si|sx|sr|s1|ss|m|mb|mf|mh|mi|il" +
|
|
"|mo|o|ow|p|c|ch|cm|cp|cpf|c1|cs|g|gd|ge|gr|gh|gi|go|gp|gs|gu|gt|gl)$"
|
|
p.AllowAttrs("class").Matching(regexp.MustCompile(codeSpanClassRegex)).OnElements("span")
|
|
p.AllowAttrs("loading").Matching(regexp.MustCompile("^(lazy|eager)$")).OnElements("img")
|
|
c.Text = p.Sanitize(c.Text)
|
|
c.User.ID = template.HTMLEscapeString(c.User.ID)
|
|
c.User.Name = c.SanitizeText(c.User.Name)
|
|
c.User.Picture = c.SanitizeAsURL(c.User.Picture)
|
|
c.Locator.URL = c.SanitizeAsURL(c.Locator.URL)
|
|
c.PostTitle = c.SanitizeText(c.PostTitle)
|
|
}
|
|
|
|
// Snippet from comment's text
|
|
func (c *Comment) Snippet(limit int) string {
|
|
if limit <= 0 {
|
|
limit = snippetLen
|
|
}
|
|
cleanText := strings.ReplaceAll(c.Text, "\n", " ")
|
|
size := len([]rune(cleanText))
|
|
if size < limit {
|
|
return cleanText
|
|
}
|
|
snippet := []rune(cleanText)[:limit]
|
|
// go back in snippet and found the first space
|
|
for i, s := range slices.Backward(snippet) {
|
|
if s == ' ' {
|
|
snippet = snippet[:i]
|
|
break
|
|
}
|
|
}
|
|
// don't add a space if comment is just a one single word which has been truncated.
|
|
if len(snippet) == limit {
|
|
return string(snippet) + "..."
|
|
}
|
|
return string(snippet) + " ..."
|
|
}
|
|
|
|
var reHref = regexp.MustCompile(`<a\s+(?:[^>]*?\s+)?href="([^"]*)"`)
|
|
|
|
// SanitizeAsURL drops dangerous code from a url.
|
|
// It wraps input with href to trigger bluemonday sanitizer and cleans href after sanitizing done
|
|
func (c *Comment) SanitizeAsURL(inp string) string {
|
|
h := fmt.Sprintf(`<a href=%q>`, inp)
|
|
clean := bluemonday.UGCPolicy().Sanitize(h)
|
|
if match := reHref.FindStringSubmatch(clean); len(match) > 1 {
|
|
return match[1]
|
|
}
|
|
return "" // this shouldn't happen as we build the href
|
|
}
|
|
|
|
func (c *Comment) escapeHTMLWithSome(inp string) string {
|
|
res := template.HTMLEscapeString(inp)
|
|
res = strings.ReplaceAll(res, "&", "&")
|
|
res = strings.ReplaceAll(res, """, "\"")
|
|
res = strings.ReplaceAll(res, "'", "'")
|
|
return res
|
|
}
|
|
|
|
// SanitizeText used to sanitize any input string, and removes any HTML tags
|
|
func (c *Comment) SanitizeText(inp string) string {
|
|
clean := bluemonday.StrictPolicy().Sanitize(inp)
|
|
return strings.TrimSpace(c.escapeHTMLWithSome(clean))
|
|
}
|