fix: address performance and security findings
- Add PostgreSQL-backed backend and frontend tests to CI - Harden Android API logging and disable app backups - Update the performance report with resolved findings
This commit is contained in:
1 parent
a84a36349b
commit
937f51b4fb
35 files changed
+2566
-332
No files matched your search
+18
-8
@@ -7,6 +7,16 @@ APP_VERSION=dev
|
||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||
COOKIE_SECURE=false
|
||||
|
||||
# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and
|
||||
# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the
|
||||
# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16
|
||||
TRUSTED_PROXIES=
|
||||
|
||||
# Set to "true" in production. Plain HTTP requests are refused unless they arrive
|
||||
# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https.
|
||||
# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning.
|
||||
PRODUCTION=false
|
||||
|
||||
#################################################################
|
||||
# Authentication (AuthGuard)
|
||||
#################################################################
|
||||
@@ -38,8 +48,8 @@ COOKIE_SECURE=false
|
||||
# see Core/ProjectConfigurator/README.md's "Pushing core service info to
|
||||
# other projects". That push is itself authenticated with this secret, so it
|
||||
# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A
|
||||
# push never overrides AUTH_DISABLED=true; it only ever retargets an
|
||||
# already-enabled AuthGuard connection.
|
||||
# push never overrides AUTH_DISABLED=true; it only ever retargets an
|
||||
# already-enabled AuthGuard connection.
|
||||
|
||||
#################################################################
|
||||
# PostgreSQL configuration
|
||||
@@ -62,9 +72,9 @@ DB_INIT_RETRY_MAX_ATTEMPTS=0
|
||||
SYNC_MAX_FUTURE_SKEW_MS=0
|
||||
|
||||
# Notification retention period in milliseconds (default: 7 days)
|
||||
NOTIF_RETENTION_MS=604800000
|
||||
|
||||
# Required shared-service authentication secret.
|
||||
SECRET=change-me-to-a-long-random-value
|
||||
# Set true only for local development or a standalone deployment.
|
||||
AUTH_DISABLED=false
|
||||
NOTIF_RETENTION_MS=604800000
|
||||
|
||||
# Required shared-service authentication secret.
|
||||
SECRET=change-me-to-a-long-random-value
|
||||
# Set true only for local development or a standalone deployment.
|
||||
AUTH_DISABLED=false
|
||||
+53
-1
@@ -24,6 +24,7 @@ docker run -d --name collabtable-server --restart unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||
-e AUTHGUARD_URL=https://auth.example.com \
|
||||
-e SECRET=<long-random-shared-secret> \
|
||||
-e COOKIE_SECURE=false \
|
||||
collabtable-server
|
||||
```
|
||||
@@ -41,6 +42,10 @@ go test ./...
|
||||
go run .
|
||||
```
|
||||
|
||||
`go test ./...` skips the tests that need a database. To run them, set `TEST_DATABASE_URL` to a
|
||||
disposable PostgreSQL (a `postgres://` URL, never your real `DATABASE_URL`). Each test creates
|
||||
its own schema in it and drops the schema afterwards.
|
||||
|
||||
To build the dashboard for the embedded production binary:
|
||||
|
||||
```bash
|
||||
@@ -112,7 +117,19 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
|
||||
- `PORT` — HTTP port, default `8080`
|
||||
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS. It marks only the cookies CollabTable
|
||||
clears on logout as `Secure`; the session cookie's attributes are set by AuthGuard.
|
||||
- `TRUSTED_PROXIES` — comma-separated IP addresses or CIDR ranges of reverse proxies, default
|
||||
unset (no proxy trusted). `X-Forwarded-For` is read for the client IP, used by the rate limits,
|
||||
only when the socket peer is in this list; `X-Forwarded-Proto` is honoured the same way.
|
||||
- `PRODUCTION` — set `true` for a production deployment, default `false`. Plain HTTP requests
|
||||
get 403 unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends
|
||||
`X-Forwarded-Proto: https` (`/health` stays open). Requires `TRUSTED_PROXIES`. With it unset,
|
||||
the server logs a warning that TLS is off.
|
||||
- `SECRET` — shared secret for the internal endpoints. Required unless `AUTH_DISABLED=true`:
|
||||
without it the auth status endpoint reports the missing secret and auth-gated routes return 500.
|
||||
- `ALLOWED_ORIGINS` — comma-separated browser origins allowed to call the API cross-origin with
|
||||
credentials, default unset (no CORS headers; the dashboard is same-origin).
|
||||
- `DATABASE_URL` — PostgreSQL connection string, required
|
||||
- `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service
|
||||
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
||||
@@ -129,6 +146,41 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
The Go server initializes the existing CollabTable tables in place, so switching from the
|
||||
previous server does not require a data export or schema conversion.
|
||||
|
||||
## Rate limits
|
||||
|
||||
The auth routes are throttled in process, per client IP (see `TRUSTED_PROXIES` for how the IP is
|
||||
resolved): setup, login, TOTP and token regeneration allow 30 requests per minute, after which
|
||||
the server answers 429 with `Retry-After`. Failed logins (401) are also counted per account
|
||||
identifier, and an account is locked for its 15-minute window after 10 failures. Anyone who knows
|
||||
an account name can therefore lock that account out for the window. Limits are per instance and
|
||||
reset on restart. AuthGuard applies its own limits; confirm them separately.
|
||||
The sync API is not throttled per request, because the bearer token is 256 bits and devices
|
||||
sync often.
|
||||
|
||||
## Security headers
|
||||
|
||||
Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
|
||||
`Referrer-Policy: strict-origin-when-cross-origin` and `Content-Security-Policy: frame-ancestors
|
||||
'none'`. The dashboard page (`index.html`, including the fallback for deep links) gets a full
|
||||
Content-Security-Policy instead: scripts only from this origin plus the page's own inline
|
||||
bootstrap script, whose hash is read from the embedded `index.html` at request time, so it
|
||||
follows every dashboard build. Styles allow `'unsafe-inline'` because the page shell uses a style
|
||||
attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
|
||||
|
||||
## Access model
|
||||
|
||||
There is one shared data set. Lists, fields, items and values have no owner and no per-list
|
||||
roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard
|
||||
user can see all of them. Tokens are per account only so that each can be regenerated on its own.
|
||||
Deleting an item, field or list removes its values for good, while the rows themselves are soft
|
||||
deleted. Per-list access would need a membership table checked in every handler; that has not
|
||||
been decided.
|
||||
|
||||
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
||||
ProjectConfigurator), the dashboard data and user management need no session. Sync tokens are a
|
||||
separate matter: a caller without a session can only mint a token for the placeholder identity,
|
||||
and the sync API refuses that identity.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+7
-4
@@ -139,6 +139,9 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
// getAPITokenUserID answers 0 for an unknown token. 0 is also the
|
||||
// placeholder identity used when login is off, so tokens minted without
|
||||
// a session are refused here as well (see handleTokenRegenerate).
|
||||
if userID == 0 {
|
||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||
return
|
||||
@@ -173,10 +176,10 @@ func hashToken(token string) string {
|
||||
// view/regenerate the bearer token its own devices use against the sync API.
|
||||
// The caller's identity is resolved via sharedauth.UserFromContext, populated
|
||||
// by the s.auth.Require wrapper server.go mounts these routes behind -- in
|
||||
// auth-disabled mode that middleware always resolves to sharedauth's fixed
|
||||
// placeholder identity (ID 0), so a token minted in that mode is real and
|
||||
// functional, just scoped to that one shared identity rather than a
|
||||
// per-account AuthGuard identity, matching the pre-migration behavior.
|
||||
// auth-disabled mode, or while login is switched off, that middleware always
|
||||
// resolves to sharedauth's fixed placeholder identity (ID 0). A token minted
|
||||
// for it is stored, but requireAPIToken never accepts identity 0, so a caller
|
||||
// without a session cannot turn it into access to the sync API.
|
||||
func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := sharedauth.UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// parseTrustedProxies reads TRUSTED_PROXIES, a comma-separated list of IP
|
||||
// addresses and CIDR ranges for reverse proxies whose forwarding headers may be
|
||||
// believed. An empty value trusts no proxy.
|
||||
func parseTrustedProxies(value string) ([]*net.IPNet, error) {
|
||||
var networks []*net.IPNet
|
||||
for _, entry := range strings.Split(value, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
}
|
||||
if ip := net.ParseIP(entry); ip != nil {
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
ip = v4
|
||||
}
|
||||
networks = append(networks, &net.IPNet{IP: ip, Mask: net.CIDRMask(8*len(ip), 8*len(ip))})
|
||||
continue
|
||||
}
|
||||
_, network, err := net.ParseCIDR(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("TRUSTED_PROXIES entry %q is neither an IP address nor a CIDR range", entry)
|
||||
}
|
||||
networks = append(networks, network)
|
||||
}
|
||||
return networks, nil
|
||||
}
|
||||
|
||||
// clientIP returns the address a request is attributed to, for rate limits and
|
||||
// logs. The socket peer is used unless it is a trusted proxy. Only then is
|
||||
// X-Forwarded-For read, walking from the nearest hop outwards and stopping at
|
||||
// the first address that is not itself a trusted proxy. A malformed chain falls
|
||||
// back to the peer, so an unknown caller cannot choose the address it appears as.
|
||||
func clientIP(r *http.Request, trusted []*net.IPNet) string {
|
||||
peer := remoteHost(r.RemoteAddr)
|
||||
peerIP := net.ParseIP(peer)
|
||||
if peerIP == nil || !inNetworks(peerIP, trusted) {
|
||||
return peer
|
||||
}
|
||||
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||
var leftmost net.IP
|
||||
for i := len(hops) - 1; i >= 0; i-- {
|
||||
hop := net.ParseIP(strings.TrimSpace(hops[i]))
|
||||
if hop == nil {
|
||||
return peer
|
||||
}
|
||||
if !inNetworks(hop, trusted) {
|
||||
return hop.String()
|
||||
}
|
||||
leftmost = hop
|
||||
}
|
||||
if leftmost != nil {
|
||||
return leftmost.String()
|
||||
}
|
||||
return peer
|
||||
}
|
||||
|
||||
// requestIsHTTPS reports whether the client's connection was encrypted: either
|
||||
// TLS terminated in this process, or a trusted proxy reported https through
|
||||
// X-Forwarded-Proto. The header is ignored from any other peer.
|
||||
func requestIsHTTPS(r *http.Request, trusted []*net.IPNet) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
peerIP := net.ParseIP(remoteHost(r.RemoteAddr))
|
||||
if peerIP == nil || !inNetworks(peerIP, trusted) {
|
||||
return false
|
||||
}
|
||||
protos := strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")
|
||||
return strings.EqualFold(strings.TrimSpace(protos[len(protos)-1]), "https")
|
||||
}
|
||||
|
||||
func remoteHost(remoteAddr string) string {
|
||||
host, _, err := net.SplitHostPort(remoteAddr)
|
||||
if err != nil {
|
||||
return remoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func inNetworks(ip net.IP, networks []*net.IPNet) bool {
|
||||
for _, network := range networks {
|
||||
if network.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func mustTrusted(t *testing.T, value string) []*net.IPNet {
|
||||
t.Helper()
|
||||
networks, err := parseTrustedProxies(value)
|
||||
if err != nil {
|
||||
t.Fatalf("parseTrustedProxies(%q) error = %v", value, err)
|
||||
}
|
||||
return networks
|
||||
}
|
||||
|
||||
func TestParseTrustedProxiesAcceptsAddressesAndRanges(t *testing.T) {
|
||||
networks := mustTrusted(t, " 10.0.0.5, 192.168.2.0/24 ,, fd00::1 ")
|
||||
if len(networks) != 3 {
|
||||
t.Fatalf("parsed %d networks, want 3", len(networks))
|
||||
}
|
||||
for _, ip := range []string{"10.0.0.5", "192.168.2.77", "fd00::1"} {
|
||||
if !inNetworks(net.ParseIP(ip), networks) {
|
||||
t.Fatalf("%s should be trusted", ip)
|
||||
}
|
||||
}
|
||||
for _, ip := range []string{"10.0.0.6", "192.168.3.1", "fd00::2"} {
|
||||
if inNetworks(net.ParseIP(ip), networks) {
|
||||
t.Fatalf("%s should not be trusted", ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTrustedProxiesEmptyTrustsNothing(t *testing.T) {
|
||||
networks := mustTrusted(t, "")
|
||||
if len(networks) != 0 {
|
||||
t.Fatalf("empty TRUSTED_PROXIES parsed %d networks, want none", len(networks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTrustedProxiesRejectsGarbage(t *testing.T) {
|
||||
for _, value := range []string{"proxy.local", "10.0.0.0/33", "10.0.0.1/", "999.1.1.1"} {
|
||||
if _, err := parseTrustedProxies(value); err == nil {
|
||||
t.Fatalf("parseTrustedProxies(%q) returned no error", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPUsesSocketPeerUnlessPeerIsTrusted(t *testing.T) {
|
||||
trusted := mustTrusted(t, "10.0.0.1")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
remoteAddr string
|
||||
forwarded string
|
||||
trusted []*net.IPNet
|
||||
want string
|
||||
}{
|
||||
{name: "untrusted peer ignores forwarded header", remoteAddr: "192.0.2.9:4000", forwarded: "203.0.113.7", trusted: trusted, want: "192.0.2.9"},
|
||||
{name: "no trusted proxies at all", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: nil, want: "10.0.0.1"},
|
||||
{name: "trusted peer uses forwarded client", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: trusted, want: "203.0.113.7"},
|
||||
{name: "trusted peer without header uses peer", remoteAddr: "10.0.0.1:4000", forwarded: "", trusted: trusted, want: "10.0.0.1"},
|
||||
{name: "chain skips trusted hops", remoteAddr: "10.0.0.1:4000", forwarded: "198.51.100.4, 203.0.113.7, 10.0.0.1", trusted: trusted, want: "203.0.113.7"},
|
||||
{name: "spoofed leftmost entry is not used", remoteAddr: "10.0.0.1:4000", forwarded: "1.2.3.4, 203.0.113.7", trusted: trusted, want: "203.0.113.7"},
|
||||
{name: "malformed entry falls back to peer", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7, not-an-ip", trusted: trusted, want: "10.0.0.1"},
|
||||
{name: "all hops trusted returns leftmost", remoteAddr: "10.0.0.1:4000", forwarded: "10.0.0.1, 10.0.0.1", trusted: trusted, want: "10.0.0.1"},
|
||||
{name: "IPv6 forwarded client is normalised", remoteAddr: "10.0.0.1:4000", forwarded: "2001:DB8::7", trusted: trusted, want: "2001:db8::7"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil)
|
||||
request.RemoteAddr = tc.remoteAddr
|
||||
if tc.forwarded != "" {
|
||||
request.Header.Set("X-Forwarded-For", tc.forwarded)
|
||||
}
|
||||
if got := clientIP(request, tc.trusted); got != tc.want {
|
||||
t.Fatalf("clientIP() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestIsHTTPSHonoursTLSOrTrustedProxyOnly(t *testing.T) {
|
||||
trusted := mustTrusted(t, "10.0.0.1")
|
||||
|
||||
direct := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
direct.TLS = &tls.ConnectionState{}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
remoteAddr string
|
||||
proto string
|
||||
tlsConn bool
|
||||
want bool
|
||||
}{
|
||||
{name: "plain request", remoteAddr: "192.0.2.9:4000", want: false},
|
||||
{name: "terminated here", remoteAddr: "192.0.2.9:4000", tlsConn: true, want: true},
|
||||
{name: "trusted proxy reports https", remoteAddr: "10.0.0.1:4000", proto: "https", want: true},
|
||||
{name: "trusted proxy reports http", remoteAddr: "10.0.0.1:4000", proto: "http", want: false},
|
||||
{name: "untrusted peer claims https", remoteAddr: "192.0.2.9:4000", proto: "https", want: false},
|
||||
{name: "last proto hop decides", remoteAddr: "10.0.0.1:4000", proto: "https, http", want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
request.RemoteAddr = tc.remoteAddr
|
||||
if tc.proto != "" {
|
||||
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||
}
|
||||
if tc.tlsConn {
|
||||
request.TLS = direct.TLS
|
||||
}
|
||||
if got := requestIsHTTPS(request, trusted); got != tc.want {
|
||||
t.Fatalf("requestIsHTTPS() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
scriptElement = regexp.MustCompile(`(?is)<script\b([^>]*)>(.*?)</script\s*>`)
|
||||
scriptSrcAttribute = regexp.MustCompile(`(?i)\bsrc\s*=`)
|
||||
// A browser reads a CR or CRLF in the HTML source as LF, and hashes that.
|
||||
htmlNewlines = strings.NewReplacer("\r\n", "\n", "\r", "\n")
|
||||
)
|
||||
|
||||
// inlineScriptHashes returns a CSP hash source for every inline <script> in the
|
||||
// page. SvelteKit's static build puts one bootstrap script in index.html, and its
|
||||
// text changes with every build, so the hash is read from the page being served
|
||||
// instead of being configured.
|
||||
func inlineScriptHashes(page []byte) []string {
|
||||
var hashes []string
|
||||
for _, match := range scriptElement.FindAllSubmatch(page, -1) {
|
||||
if scriptSrcAttribute.Match(match[1]) || len(match[2]) == 0 {
|
||||
continue
|
||||
}
|
||||
sum := sha256.Sum256([]byte(htmlNewlines.Replace(string(match[2]))))
|
||||
hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'")
|
||||
}
|
||||
return hashes
|
||||
}
|
||||
|
||||
// dashboardCSP is the Content-Security-Policy for the dashboard page. Scripts may
|
||||
// only come from this origin or be the page's own inline bootstrap script, so an
|
||||
// injected script does not run. Styles keep 'unsafe-inline' because the page
|
||||
// shell uses a style attribute; the bundle has no eval, workers or external URLs.
|
||||
func dashboardCSP(page []byte) string {
|
||||
scriptSrc := append([]string{"script-src 'self'"}, inlineScriptHashes(page)...)
|
||||
return strings.Join([]string{
|
||||
"default-src 'self'",
|
||||
strings.Join(scriptSrc, " "),
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
}, "; ")
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func scriptHash(text string) string {
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
|
||||
}
|
||||
|
||||
func TestInlineScriptHashesCoversOnlyInlineScripts(t *testing.T) {
|
||||
const bootstrap = "\n\t{\n\t\tconst element = document.currentScript.parentElement;\n\t}\n"
|
||||
page := `<html><head><script src="/_app/start.js"></script>
|
||||
<script type="module" crossorigin src="/_app/other.js"></script><script></script></head>
|
||||
<body><script>` + bootstrap + `</script></body></html>`
|
||||
|
||||
got := inlineScriptHashes([]byte(page))
|
||||
if len(got) != 1 || got[0] != scriptHash(bootstrap) {
|
||||
t.Fatalf("inlineScriptHashes() = %v, want only %s", got, scriptHash(bootstrap))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInlineScriptHashesNormalizesNewlinesLikeABrowser(t *testing.T) {
|
||||
got := inlineScriptHashes([]byte("<script>a();\r\nb();\rc();</script>"))
|
||||
if len(got) != 1 || got[0] != scriptHash("a();\nb();\nc();") {
|
||||
t.Fatalf("inlineScriptHashes() = %v, want the hash of the LF-normalized text", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardCSPAllowsOnlyOwnAndHashedScripts(t *testing.T) {
|
||||
const bootstrap = "start();"
|
||||
policy := dashboardCSP([]byte("<body><script>" + bootstrap + "</script></body>"))
|
||||
|
||||
directives := map[string]string{}
|
||||
for _, part := range strings.Split(policy, "; ") {
|
||||
name, value, _ := strings.Cut(part, " ")
|
||||
directives[name] = value
|
||||
}
|
||||
if want := "'self' " + scriptHash(bootstrap); directives["script-src"] != want {
|
||||
t.Fatalf("script-src = %q, want %q", directives["script-src"], want)
|
||||
}
|
||||
for name, want := range map[string]string{
|
||||
"default-src": "'self'",
|
||||
"object-src": "'none'",
|
||||
"base-uri": "'self'",
|
||||
"frame-ancestors": "'none'",
|
||||
} {
|
||||
if directives[name] != want {
|
||||
t.Fatalf("%s = %q, want %q", name, directives[name], want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(directives["script-src"], "unsafe") {
|
||||
t.Fatalf("script-src = %q, must not allow unsafe-inline or unsafe-eval", directives["script-src"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardCSPWithoutInlineScriptAllowsOnlyOwnOrigin(t *testing.T) {
|
||||
policy := dashboardCSP([]byte("<html></html>"))
|
||||
if !strings.Contains(policy, "script-src 'self';") {
|
||||
t.Fatalf("policy = %q, want script-src limited to 'self'", policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAFileServerSendsDashboardCSPOnThePageOnly(t *testing.T) {
|
||||
const bootstrap = "start();"
|
||||
root := fstest.MapFS{
|
||||
"index.html": {Data: []byte("<html><body><script>" + bootstrap + "</script></body></html>")},
|
||||
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
|
||||
}
|
||||
// Behind withSecurityHeaders, as in main: the page's policy replaces the
|
||||
// frame-ancestors-only default instead of being added to it.
|
||||
handler := withSecurityHeaders(spaFileServer(root))
|
||||
|
||||
for _, path := range []string{"/", "/index.html", "/lists/123"} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
values := recorder.Header().Values("Content-Security-Policy")
|
||||
if len(values) != 1 || !strings.Contains(values[0], scriptHash(bootstrap)) || !strings.Contains(values[0], "frame-ancestors 'none'") {
|
||||
t.Fatalf("GET %s Content-Security-Policy = %q, want one full policy with the bootstrap hash", path, values)
|
||||
}
|
||||
}
|
||||
|
||||
asset := httptest.NewRecorder()
|
||||
handler.ServeHTTP(asset, httptest.NewRequest(http.MethodGet, "/_app/immutable/app.abc.js", nil))
|
||||
if got := asset.Header().Get("Content-Security-Policy"); got != "frame-ancestors 'none'" {
|
||||
t.Fatalf("asset Content-Security-Policy = %q, want the frame-ancestors default", got)
|
||||
}
|
||||
}
|
||||
+191
-65
@@ -220,6 +220,132 @@ func boolInt(value bool) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
// fieldDefaults fills in the field type and alignment that clients may leave out.
|
||||
func fieldDefaults(fieldType, alignment string) (string, string) {
|
||||
if fieldType == "" {
|
||||
fieldType = "TEXT"
|
||||
}
|
||||
if alignment == "" {
|
||||
alignment = "start"
|
||||
}
|
||||
return fieldType, alignment
|
||||
}
|
||||
|
||||
// The upsert helpers below write one row each and report whether the write was
|
||||
// applied. A write older than the stored row loses (last writer wins by client
|
||||
// timestamp) and changes nothing, so callers skip the cascade and notification
|
||||
// for it.
|
||||
func upsertList(ctx context.Context, executor queryExecutor, list List, createdAt, updatedAt int64) (bool, error) {
|
||||
result, err := executor.Exec(ctx, `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
WHERE EXCLUDED.updatedat >= lists.updatedat
|
||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
func upsertField(ctx context.Context, executor queryExecutor, field Field, createdAt, updatedAt int64) (bool, error) {
|
||||
fieldType, alignment := fieldDefaults(field.FieldType, field.Alignment)
|
||||
result, err := executor.Exec(ctx, `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
fieldtype = EXCLUDED.fieldtype,
|
||||
fieldoptions = EXCLUDED.fieldoptions,
|
||||
alignment = EXCLUDED.alignment,
|
||||
"order" = EXCLUDED."order",
|
||||
updatedat = EXCLUDED.updatedat,
|
||||
isdeleted = EXCLUDED.isdeleted
|
||||
WHERE EXCLUDED.updatedat >= fields.updatedat
|
||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
func upsertItem(ctx context.Context, executor queryExecutor, item Item, createdAt, updatedAt int64) (bool, error) {
|
||||
result, err := executor.Exec(ctx, `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
WHERE EXCLUDED.updatedat >= items.updatedat
|
||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
// upsertValue also ignores a value that names a different item or field than the
|
||||
// stored row, so a write cannot move a value onto another cell.
|
||||
func upsertValue(ctx context.Context, executor queryExecutor, value ItemValue, updatedAt int64) (bool, error) {
|
||||
result, err := executor.Exec(ctx, `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
WHERE EXCLUDED.updatedat >= item_values.updatedat
|
||||
AND item_values.itemid = EXCLUDED.itemid
|
||||
AND item_values.fieldid = EXCLUDED.fieldid
|
||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
// cascadeDeleteList removes the children of a deleted list: its fields and items
|
||||
// are soft-deleted and their values are hard-deleted. The REST and sync delete
|
||||
// paths both call it, so they leave the same state behind.
|
||||
func cascadeDeleteList(ctx context.Context, tx pgx.Tx, listID string, updatedAt int64) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID)
|
||||
return err
|
||||
}
|
||||
|
||||
// cascadeDeleteField removes the values of a deleted field. When no active field
|
||||
// remains in the list, the list's items are deleted too, and the returned flag
|
||||
// reports that.
|
||||
func cascadeDeleteField(ctx context.Context, tx pgx.Tx, fieldID, listID string, updatedAt int64) (bool, error) {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE fieldid = $1`, fieldID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(ctx, `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, listID).Scan(&remaining); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if remaining > 0 {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// cascadeDeleteItem removes the values of a deleted item.
|
||||
func cascadeDeleteItem(ctx context.Context, tx pgx.Tx, itemID string) error {
|
||||
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid = $1`, itemID)
|
||||
return err
|
||||
}
|
||||
|
||||
type listMutation struct {
|
||||
List
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
@@ -237,8 +363,8 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var request listMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.Name == "" {
|
||||
@@ -285,8 +411,8 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
Name string `json:"name"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
@@ -308,16 +434,28 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodDelete:
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
if err := cascadeDeleteList(r.Context(), tx, id, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
||||
}
|
||||
}
|
||||
@@ -338,20 +476,15 @@ func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request fieldMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
@@ -386,16 +519,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
Order int `json:"order"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
@@ -421,7 +549,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
||||
_ = decodeJSON(w, r, &request) // DELETE bodies are optional.
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
var field Field
|
||||
cascade := false
|
||||
@@ -434,23 +562,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
|
||||
cascade, err = cascadeDeleteField(r.Context(), tx, id, field.ListID, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
cascade = true
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -488,8 +604,8 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request itemMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" {
|
||||
@@ -538,27 +654,25 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
||||
ItemValue
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
|
||||
applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
// An older write than the stored value changes nothing, so it notifies no one.
|
||||
var listID string
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
if applied {
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
}
|
||||
var value ItemValue
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
@@ -584,7 +698,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||
_ = decodeJSON(r, &request)
|
||||
_ = decodeJSON(w, r, &request)
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
@@ -606,19 +720,31 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
item, err := scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cascadeDeleteItem(r.Context(), tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, itemErr := s.getItem(r.Context(), id)
|
||||
if itemErr == nil {
|
||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFieldDefaultsFillMissingValues(t *testing.T) {
|
||||
fieldType, alignment := fieldDefaults("", "")
|
||||
if fieldType != "TEXT" || alignment != "start" {
|
||||
t.Fatalf("fieldDefaults(empty) = (%q, %q), want (TEXT, start)", fieldType, alignment)
|
||||
}
|
||||
fieldType, alignment = fieldDefaults("NUMBER", "end")
|
||||
if fieldType != "NUMBER" || alignment != "end" {
|
||||
t.Fatalf("fieldDefaults(set) = (%q, %q), want (NUMBER, end)", fieldType, alignment)
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,10 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
||||
CREATE INDEX IF NOT EXISTS idx_lists_updatedat ON lists(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// These tests run the handlers against a real PostgreSQL. Set TEST_DATABASE_URL
|
||||
// to a postgres:// URL of a database the tests may write to; without it they are
|
||||
// skipped. Each test works in its own schema, which it drops afterwards, so the
|
||||
// database can be shared. TEST_DATABASE_URL must not be the service's own
|
||||
// DATABASE_URL.
|
||||
|
||||
const (
|
||||
testBearer = "test-device-token"
|
||||
// Realistic millisecond timestamps in the past, so normalizeTimestamp leaves
|
||||
// them alone. Later writes use t0 plus an offset.
|
||||
t0 = int64(1_700_000_000_000)
|
||||
)
|
||||
|
||||
// testDB returns a DB on a fresh schema of TEST_DATABASE_URL, with the tables
|
||||
// created by initSchema.
|
||||
func testDB(t *testing.T) *DB {
|
||||
t.Helper()
|
||||
base := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL"))
|
||||
if base == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set; database-backed tests need a PostgreSQL they may write to")
|
||||
}
|
||||
if base == strings.TrimSpace(os.Getenv("DATABASE_URL")) {
|
||||
t.Fatal("TEST_DATABASE_URL must not be the same database as DATABASE_URL")
|
||||
}
|
||||
parsed, err := url.Parse(base)
|
||||
if err != nil {
|
||||
t.Fatalf("TEST_DATABASE_URL is not a URL: %v", err)
|
||||
}
|
||||
|
||||
suffix := make([]byte, 6)
|
||||
if _, err := rand.Read(suffix); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "collabtable_test_" + hex.EncodeToString(suffix)
|
||||
|
||||
ctx := context.Background()
|
||||
admin, err := pgx.Connect(ctx, base)
|
||||
if err != nil {
|
||||
t.Fatalf("connect to TEST_DATABASE_URL: %v", err)
|
||||
}
|
||||
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||
_ = admin.Close(ctx)
|
||||
t.Fatalf("create schema: %v", err)
|
||||
}
|
||||
|
||||
query := parsed.Query()
|
||||
query.Set("search_path", schema)
|
||||
parsed.RawQuery = query.Encode()
|
||||
db, err := connectDB(ctx, parsed.String())
|
||||
if err != nil {
|
||||
t.Fatalf("connectDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
db.close()
|
||||
_, _ = admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
|
||||
_ = admin.Close(ctx)
|
||||
})
|
||||
if err := db.initSchema(ctx); err != nil {
|
||||
t.Fatalf("initSchema: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// testUserID owns testBearer. It is not 0: identity 0 is the placeholder used
|
||||
// when login is off, and the sync API never accepts it.
|
||||
const testUserID = 1
|
||||
|
||||
// testAPI serves the real routes over a test database. Auth is disabled, and the
|
||||
// sync API accepts testBearer.
|
||||
type testAPI struct {
|
||||
t *testing.T
|
||||
db *DB
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
func newTestAPI(t *testing.T) *testAPI {
|
||||
t.Helper()
|
||||
db := testDB(t)
|
||||
server := &Server{
|
||||
db: db,
|
||||
auth: newAuthService(db, "", false, true),
|
||||
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webFS)
|
||||
if err := db.regenerateAPIToken(context.Background(), testUserID, hashToken(testBearer)); err != nil {
|
||||
t.Fatalf("seed API token: %v", err)
|
||||
}
|
||||
return &testAPI{t: t, db: db, mux: mux}
|
||||
}
|
||||
|
||||
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
||||
a.t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body == nil {
|
||||
reader = bytes.NewReader(nil)
|
||||
} else {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
a.t.Fatalf("encode request: %v", err)
|
||||
}
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
request := httptest.NewRequest(method, path, reader)
|
||||
request.Header.Set("Authorization", "Bearer "+testBearer)
|
||||
if device != "" {
|
||||
request.Header.Set("X-Device-Id", device)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
a.mux.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||
a.t.Helper()
|
||||
recorder := a.do(method, path, device, body)
|
||||
if recorder.Code != wantStatus {
|
||||
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||
}
|
||||
return recorder
|
||||
}
|
||||
|
||||
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||
t.Helper()
|
||||
var value T
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {
|
||||
t.Fatalf("decode %q: %v", recorder.Body.String(), err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
||||
a.t.Helper()
|
||||
request.DeviceID = device
|
||||
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
||||
}
|
||||
|
||||
func (a *testAPI) count(query string, args ...any) int {
|
||||
a.t.Helper()
|
||||
var n int
|
||||
if err := a.db.pool.QueryRow(context.Background(), query, args...).Scan(&n); err != nil {
|
||||
a.t.Fatalf("%s: %v", query, err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (a *testAPI) notifications(eventType, entityType, entityID string) int {
|
||||
a.t.Helper()
|
||||
return a.count(`SELECT count(*) FROM notifications WHERE eventtype = $1 AND entitytype = $2 AND entityid = $3`, eventType, entityType, entityID)
|
||||
}
|
||||
|
||||
// cascadeState summarizes a list and its children, so two delete paths can be
|
||||
// compared: the list's isdeleted flag, deleted/total fields and items, and the
|
||||
// number of values left on the list's items.
|
||||
func (a *testAPI) cascadeState(listID string) string {
|
||||
a.t.Helper()
|
||||
return fmt.Sprintf("list=%d fields=%d/%d items=%d/%d values=%d",
|
||||
a.count(`SELECT isdeleted FROM lists WHERE id = $1`, listID),
|
||||
a.count(`SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 1`, listID),
|
||||
a.count(`SELECT count(*) FROM fields WHERE listid = $1`, listID),
|
||||
a.count(`SELECT count(*) FROM items WHERE listid = $1 AND isdeleted = 1`, listID),
|
||||
a.count(`SELECT count(*) FROM items WHERE listid = $1`, listID),
|
||||
a.count(`SELECT count(*) FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID),
|
||||
)
|
||||
}
|
||||
|
||||
func testList(id, name string, updatedAt int64, deleted bool) List {
|
||||
return List{ID: id, Name: name, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||
}
|
||||
|
||||
func testField(id, listID, name string, updatedAt int64, deleted bool) Field {
|
||||
return Field{ID: id, ListID: listID, Name: name, FieldType: "TEXT", Alignment: "start", CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||
}
|
||||
|
||||
func testItem(id, listID string, updatedAt int64, deleted bool) Item {
|
||||
return Item{ID: id, ListID: listID, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||
}
|
||||
|
||||
func testValue(id, itemID, fieldID, value string, updatedAt int64) ItemValue {
|
||||
return ItemValue{ID: id, ItemID: itemID, FieldID: fieldID, Value: value, UpdatedAt: Timestamp(updatedAt)}
|
||||
}
|
||||
|
||||
// seedList pushes a list with two fields, one item and a value in each field, all
|
||||
// stamped t0+10, as one device's first sync. Its IDs are prefix-list, prefix-f1,
|
||||
// prefix-f2, prefix-item, prefix-v1 and prefix-v2.
|
||||
func (a *testAPI) seedList(device, prefix string) {
|
||||
a.t.Helper()
|
||||
at := t0 + 10
|
||||
a.sync(device, SyncRequest{
|
||||
Lists: []List{testList(prefix+"-list", "Groceries", at, false)},
|
||||
Fields: []Field{testField(prefix+"-f1", prefix+"-list", "Name", at, false), testField(prefix+"-f2", prefix+"-list", "Qty", at, false)},
|
||||
Items: []Item{testItem(prefix+"-item", prefix+"-list", at, false)},
|
||||
ItemValues: []ItemValue{
|
||||
testValue(prefix+"-v1", prefix+"-item", prefix+"-f1", "milk", at),
|
||||
testValue(prefix+"-v2", prefix+"-item", prefix+"-f2", "2", at),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
||||
db := testDB(t)
|
||||
if err := db.initSchema(context.Background()); err != nil {
|
||||
t.Fatalf("second initSchema() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
|
||||
// A device that has never synced gets everything.
|
||||
full := api.sync("tablet", SyncRequest{})
|
||||
if len(full.Lists) != 1 || len(full.Fields) != 2 || len(full.Items) != 1 || len(full.ItemValues) != 2 {
|
||||
t.Fatalf("first sync returned lists=%d fields=%d items=%d values=%d, want 1/2/1/2", len(full.Lists), len(full.Fields), len(full.Items), len(full.ItemValues))
|
||||
}
|
||||
if full.ServerTimestamp <= 0 {
|
||||
t.Fatalf("serverTimestamp = %d, want a positive time", full.ServerTimestamp)
|
||||
}
|
||||
if len(full.OrphanItemValues) != 0 {
|
||||
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
||||
}
|
||||
|
||||
// The delta filter is "updated at or after the cursor".
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
||||
}
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 10)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
||||
t.Fatalf("sync at the change time returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||
}
|
||||
|
||||
// The REST reads see the same data.
|
||||
lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||
if len(lists) != 1 || lists[0].Name != "Groceries" {
|
||||
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
||||
}
|
||||
values := decodeBody[[]ItemValue](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||
if len(values) != 2 {
|
||||
t.Fatalf("GET item values = %+v, want 2", values)
|
||||
}
|
||||
|
||||
// The first push is announced to the other device, and not back to its sender.
|
||||
toTablet := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "tablet", nil, http.StatusOK))
|
||||
if len(toTablet.Notifications) == 0 {
|
||||
t.Fatal("tablet got no notifications for the phone's push")
|
||||
}
|
||||
for _, event := range toTablet.Notifications {
|
||||
if event.DeviceIDOrigin != "phone" {
|
||||
t.Fatalf("notification origin = %q, want phone", event.DeviceIDOrigin)
|
||||
}
|
||||
}
|
||||
toPhone := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "phone", nil, http.StatusOK))
|
||||
if len(toPhone.Notifications) != 0 {
|
||||
t.Fatalf("phone got its own notifications back: %+v", toPhone.Notifications)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
push := func(name string, updatedAt int64) {
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("l1", name, updatedAt, false)}})
|
||||
}
|
||||
name := func() string {
|
||||
return decodeBody[List](t, api.mustDo(http.MethodGet, "/api/lists/l1", "", nil, http.StatusOK)).Name
|
||||
}
|
||||
|
||||
push("v2", t0+2000)
|
||||
events := api.notifications("updated", "list", "l1")
|
||||
|
||||
push("v1", t0+1000)
|
||||
if got := name(); got != "v2" {
|
||||
t.Fatalf("name after an older write = %q, want v2", got)
|
||||
}
|
||||
if got := api.notifications("updated", "list", "l1"); got != events {
|
||||
t.Fatalf("an ignored write added %d notification(s)", got-events)
|
||||
}
|
||||
|
||||
push("v3", t0+3000)
|
||||
if got := name(); got != "v3" {
|
||||
t.Fatalf("name after a newer write = %q, want v3", got)
|
||||
}
|
||||
push("v3b", t0+3000)
|
||||
if got := name(); got != "v3b" {
|
||||
t.Fatalf("name after a write with the same timestamp = %q, want v3b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
||||
|
||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||
if got := api.cascadeState("g-list"); got != kept {
|
||||
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
||||
}
|
||||
if got := api.notifications("deleted", "list", "g-list"); got != 0 {
|
||||
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
||||
}
|
||||
|
||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
||||
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
||||
}
|
||||
if got := api.notifications("deleted", "list", "g-list"); got != 1 {
|
||||
t.Fatalf("deleted notifications = %d, want 1", got)
|
||||
}
|
||||
|
||||
// The tombstone travels to other devices, but the REST list read hides it.
|
||||
delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)})
|
||||
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
||||
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
||||
}
|
||||
if lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists) != 0 {
|
||||
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletingTheLastFieldDeletesTheItems(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Fields: []Field{testField("g-f1", "g-list", "Name", t0+20, true)}})
|
||||
if got, want := api.cascadeState("g-list"), "list=0 fields=1/2 items=0/1 values=1"; got != want {
|
||||
t.Fatalf("state after deleting one of two fields = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// Through REST this time. The response says the items went with it.
|
||||
answer := decodeBody[map[string]any](t, api.mustDo(http.MethodDelete, "/api/fields/g-f2", "phone", nil, http.StatusOK))
|
||||
if answer["cascadeItemsDeleted"] != true {
|
||||
t.Fatalf("DELETE last field answer = %v, want cascadeItemsDeleted true", answer)
|
||||
}
|
||||
if got, want := api.cascadeState("g-list"), "list=0 fields=2/2 items=1/1 values=0"; got != want {
|
||||
t.Fatalf("state after deleting the last field = %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTAndSyncDeletesLeaveTheSameState(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "rest")
|
||||
api.seedList("phone", "sync")
|
||||
|
||||
api.mustDo(http.MethodDelete, "/api/lists/rest-list", "phone", nil, http.StatusOK)
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("sync-list", "Groceries", time.Now().UnixMilli(), true)}})
|
||||
|
||||
const want = "list=1 fields=2/2 items=1/1 values=0"
|
||||
if got := api.cascadeState("rest-list"); got != want {
|
||||
t.Fatalf("REST delete left %s, want %s", got, want)
|
||||
}
|
||||
if got := api.cascadeState("sync-list"); got != want {
|
||||
t.Fatalf("sync delete left %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// Item deletes agree as well.
|
||||
api.seedList("phone", "ri")
|
||||
api.seedList("phone", "si")
|
||||
api.mustDo(http.MethodDelete, "/api/items/ri-item", "phone", nil, http.StatusOK)
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("si-item", "si-list", time.Now().UnixMilli(), true)}})
|
||||
const wantItem = "list=0 fields=0/2 items=1/1 values=0"
|
||||
if got := api.cascadeState("ri-list"); got != wantItem {
|
||||
t.Fatalf("REST item delete left %s, want %s", got, wantItem)
|
||||
}
|
||||
if got := api.cascadeState("si-list"); got != wantItem {
|
||||
t.Fatalf("sync item delete left %s, want %s", got, wantItem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncCannotMoveAValueOntoAnotherCell(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("g-item2", "g-list", t0+10, false)}})
|
||||
|
||||
// Same value id, newer timestamp, but naming another item and another field.
|
||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item2", "g-f2", "hijacked", t0+50)}})
|
||||
|
||||
var itemID, fieldID, value string
|
||||
if err := api.db.pool.QueryRow(context.Background(), `SELECT itemid, fieldid, value FROM item_values WHERE id = 'g-v1'`).Scan(&itemID, &fieldID, &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if itemID != "g-item" || fieldID != "g-f1" || value != "milk" {
|
||||
t.Fatalf("stored value = (%s, %s, %q), want it unchanged at (g-item, g-f1, milk)", itemID, fieldID, value)
|
||||
}
|
||||
if got := api.notifications("listContentUpdated", "value", "g-v1"); got != 1 {
|
||||
t.Fatalf("notifications for the value = %d, want only the original push", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncReportsValuesItCannotPlaceAndStubsMissingItems(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
|
||||
answer := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{
|
||||
testValue("lost", "g-item", "no-such-field", "x", t0+20),
|
||||
testValue("late", "item-not-pushed-yet", "g-f1", "y", t0+20),
|
||||
}})
|
||||
if len(answer.OrphanItemValues) != 1 || answer.OrphanItemValues[0].ID != "lost" || answer.OrphanItemValues[0].Reason != "missingField" {
|
||||
t.Fatalf("orphanItemValues = %+v, want only lost with reason missingField", answer.OrphanItemValues)
|
||||
}
|
||||
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'lost'`); got != 0 {
|
||||
t.Fatal("a value for a missing field was stored")
|
||||
}
|
||||
// A value for an item the server has not seen yet creates the item in the
|
||||
// field's list, so the value is kept.
|
||||
if got := api.count(`SELECT count(*) FROM items WHERE id = 'item-not-pushed-yet' AND listid = 'g-list' AND isdeleted = 0`); got != 1 {
|
||||
t.Fatalf("stub item rows = %d, want 1", got)
|
||||
}
|
||||
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'late'`); got != 1 {
|
||||
t.Fatalf("value rows for the stubbed item = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedNotificationDoesNotAbortTheMutation(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
if _, err := api.db.pool.Exec(context.Background(), `DROP TABLE notifications`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Every notification insert now fails. The sync still commits its data.
|
||||
api.sync("phone", SyncRequest{Lists: []List{testList("l1", "Kept", t0+10, false)}})
|
||||
if got := api.count(`SELECT count(*) FROM lists WHERE id = 'l1'`); got != 1 {
|
||||
t.Fatal("the list was rolled back because its notification failed")
|
||||
}
|
||||
|
||||
// So does a REST delete, which runs in a transaction.
|
||||
api.mustDo(http.MethodDelete, "/api/lists/l1", "phone", nil, http.StatusOK)
|
||||
if got := api.count(`SELECT isdeleted FROM lists WHERE id = 'l1'`); got != 1 {
|
||||
t.Fatal("the REST delete was rolled back because its notification failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
write := func(value string, updatedAt int64) ItemValue {
|
||||
return decodeBody[ItemValue](t, api.mustDo(http.MethodPost, "/api/items/values", "phone",
|
||||
testValue("g-v1", "g-item", "g-f1", value, updatedAt), http.StatusOK))
|
||||
}
|
||||
|
||||
if got := write("oat milk", t0+30); got.Value != "oat milk" {
|
||||
t.Fatalf("newer write answered %q, want oat milk", got.Value)
|
||||
}
|
||||
if got := write("stale", t0+20); got.Value != "oat milk" || int64(got.UpdatedAt) != t0+30 {
|
||||
t.Fatalf("older write answered %+v, want the stored oat milk at t0+30", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
get := func(etag string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||
if etag != "" {
|
||||
request.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
api.mux.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
first := get("")
|
||||
if first.Code != http.StatusOK {
|
||||
t.Fatalf("GET /web/data status = %d, want 200; body %s", first.Code, first.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Lists []struct {
|
||||
ID string `json:"id"`
|
||||
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
|
||||
} `json:"lists"`
|
||||
Stats map[string]int `json:"stats"`
|
||||
}
|
||||
if err := json.Unmarshal(first.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Lists) != 1 || payload.Lists[0].EffectiveUpdatedAt != t0+10 || payload.Stats["values"] != 2 {
|
||||
t.Fatalf("payload = %+v, want one list effective at t0+10 and two values", payload)
|
||||
}
|
||||
|
||||
etag := first.Header().Get("ETag")
|
||||
if etag == "" {
|
||||
t.Fatal("GET /web/data sent no ETag")
|
||||
}
|
||||
if again := get(etag); again.Code != http.StatusNotModified {
|
||||
t.Fatalf("unchanged data status = %d, want 304", again.Code)
|
||||
}
|
||||
|
||||
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item", "g-f1", "oat milk", t0+40)}})
|
||||
if changed := get(etag); changed.Code != http.StatusOK {
|
||||
t.Fatalf("changed data status = %d, want 200", changed.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegeneratingAnAccountsTokenReplacesTheOldOne(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
const fresh = "replacement-device-token"
|
||||
if err := api.db.regenerateAPIToken(context.Background(), testUserID, hashToken(fresh)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if old := api.do(http.MethodGet, "/api/lists", "", nil); old.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("old token status = %d, want 401", old.Code)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+fresh)
|
||||
recorder := httptest.NewRecorder()
|
||||
api.mux.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("new token status = %d, want 200", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// With login off (AUTH_DISABLED, or the login-required override) a caller with no
|
||||
// session can reach token regeneration, but only as the placeholder identity 0.
|
||||
// A token minted that way must not open the sync API.
|
||||
func TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
|
||||
answer := decodeBody[map[string]string](t, api.mustDo(http.MethodPost, "/api/auth/token/regenerate", "", nil, http.StatusOK))
|
||||
minted := answer["token"]
|
||||
if minted == "" {
|
||||
t.Fatalf("regenerate answer = %v, want a token", answer)
|
||||
}
|
||||
if got := api.count(`SELECT count(*) FROM api_tokens WHERE user_id = 0`); got != 1 {
|
||||
t.Fatalf("tokens stored for identity 0 = %d, want 1", got)
|
||||
}
|
||||
|
||||
for _, probe := range []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/lists"},
|
||||
{http.MethodPost, "/api/sync"},
|
||||
} {
|
||||
request := httptest.NewRequest(probe.method, probe.path, strings.NewReader("{}"))
|
||||
request.Header.Set("Authorization", "Bearer "+minted)
|
||||
recorder := httptest.NewRecorder()
|
||||
api.mux.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s %s with a session-less token status = %d, want 401", probe.method, probe.path, recorder.Code)
|
||||
}
|
||||
}
|
||||
// And it did not disturb the real account's token.
|
||||
api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)
|
||||
}
|
||||
|
||||
func TestSetupClaimCanBeTakenOnceAndReopened(t *testing.T) {
|
||||
db := testDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
claimed, err := db.IsSetupClaimed(ctx)
|
||||
if err != nil || claimed {
|
||||
t.Fatalf("IsSetupClaimed() on a new database = %v, %v, want false", claimed, err)
|
||||
}
|
||||
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
|
||||
t.Fatalf("first TryClaimSetup() = %v, %v, want true", won, err)
|
||||
}
|
||||
if won, err := db.TryClaimSetup(ctx); err != nil || won {
|
||||
t.Fatalf("second TryClaimSetup() = %v, %v, want false", won, err)
|
||||
}
|
||||
if err := db.UnclaimSetup(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
|
||||
t.Fatalf("TryClaimSetup() after UnclaimSetup() = %v, %v, want true", won, err)
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,31 @@ func enqueueNotification(
|
||||
return err
|
||||
}
|
||||
|
||||
// enqueueNotificationInTx writes a notification inside a savepoint. PostgreSQL
|
||||
// aborts the whole transaction after any failing statement, so without the
|
||||
// savepoint a failed notification insert would make the data mutation's commit
|
||||
// fail too.
|
||||
func enqueueNotificationInTx(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
deviceID string,
|
||||
eventType string,
|
||||
entityType string,
|
||||
entityID string,
|
||||
listID string,
|
||||
createdAt int64,
|
||||
) error {
|
||||
savepoint, err := tx.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := enqueueNotification(ctx, savepoint, deviceID, eventType, entityType, entityID, listID, createdAt); err != nil {
|
||||
_ = savepoint.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
return savepoint.Commit(ctx)
|
||||
}
|
||||
|
||||
func nullableString(value string) any {
|
||||
if value == "" {
|
||||
return nil
|
||||
@@ -48,6 +73,8 @@ func nullableString(value string) any {
|
||||
return value
|
||||
}
|
||||
|
||||
// ignoreNotificationError logs a failed notification. Use it only for
|
||||
// notifications written by enqueueNotificationInTx or outside a transaction.
|
||||
func ignoreNotificationError(err error) {
|
||||
if err != nil {
|
||||
// Notifications are an acceleration path for clients that poll. A failed
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Budgets for the credential-bearing auth routes. Client IPs are resolved with
|
||||
// clientIP, so they honour X-Forwarded-For only from TRUSTED_PROXIES.
|
||||
const (
|
||||
authIPLimit = 30
|
||||
authIPWindow = time.Minute
|
||||
loginFailureLimit = 10
|
||||
loginFailureWindow = 15 * time.Minute
|
||||
// loginBodyLimit matches the body cap AuthGuard's login handler reads.
|
||||
loginBodyLimit = 128 * 1024
|
||||
// rateLimiterMaxKeys bounds memory held for distinct keys.
|
||||
rateLimiterMaxKeys = 10000
|
||||
)
|
||||
|
||||
// rateLimiter counts events per key in fixed windows. It lives in process, so
|
||||
// the budgets apply to one server instance.
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
window time.Duration
|
||||
maxKeys int
|
||||
now func() time.Time
|
||||
counts map[string]*rateWindow
|
||||
}
|
||||
|
||||
type rateWindow struct {
|
||||
start time.Time
|
||||
count int
|
||||
}
|
||||
|
||||
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
|
||||
return &rateLimiter{
|
||||
limit: limit,
|
||||
window: window,
|
||||
maxKeys: rateLimiterMaxKeys,
|
||||
now: time.Now,
|
||||
counts: make(map[string]*rateWindow),
|
||||
}
|
||||
}
|
||||
|
||||
// Blocked reports whether key has spent its budget in the current window, and
|
||||
// how long until that window ends.
|
||||
func (l *rateLimiter) Blocked(key string) (bool, time.Duration) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := l.now()
|
||||
window, ok := l.counts[key]
|
||||
if !ok || now.Sub(window.start) >= l.window || window.count < l.limit {
|
||||
return false, 0
|
||||
}
|
||||
return true, window.start.Add(l.window).Sub(now)
|
||||
}
|
||||
|
||||
// Hit counts one event for key in the current window.
|
||||
func (l *rateLimiter) Hit(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := l.now()
|
||||
window, ok := l.counts[key]
|
||||
if !ok || now.Sub(window.start) >= l.window {
|
||||
if !ok && len(l.counts) >= l.maxKeys {
|
||||
l.evictLocked(now)
|
||||
}
|
||||
window = &rateWindow{start: now}
|
||||
l.counts[key] = window
|
||||
}
|
||||
window.count++
|
||||
}
|
||||
|
||||
// evictLocked drops expired windows. If every window is still live, it clears
|
||||
// the map rather than let memory grow without bound. That can reset budgets
|
||||
// under a flood of distinct keys, which is the cost of a bounded map.
|
||||
func (l *rateLimiter) evictLocked(now time.Time) {
|
||||
for key, window := range l.counts {
|
||||
if now.Sub(window.start) >= l.window {
|
||||
delete(l.counts, key)
|
||||
}
|
||||
}
|
||||
if len(l.counts) >= l.maxKeys {
|
||||
clear(l.counts)
|
||||
}
|
||||
}
|
||||
|
||||
// writeRateLimited answers 429 with a Retry-After in whole seconds.
|
||||
func writeRateLimited(w http.ResponseWriter, retryAfter time.Duration) {
|
||||
seconds := int(math.Ceil(retryAfter.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(seconds))
|
||||
writeJSONError(w, http.StatusTooManyRequests, "Too many attempts. Try again later.")
|
||||
}
|
||||
|
||||
// authRateLimits holds the budgets for the auth routes. A fresh set is built
|
||||
// per route registration, so tests start with empty counters.
|
||||
type authRateLimits struct {
|
||||
trusted []*net.IPNet
|
||||
ip *rateLimiter
|
||||
failures *rateLimiter
|
||||
}
|
||||
|
||||
func newAuthRateLimits(trusted []*net.IPNet) *authRateLimits {
|
||||
return &authRateLimits{
|
||||
trusted: trusted,
|
||||
ip: newRateLimiter(authIPLimit, authIPWindow),
|
||||
failures: newRateLimiter(loginFailureLimit, loginFailureWindow),
|
||||
}
|
||||
}
|
||||
|
||||
// perClient counts every request against the client's IP and refuses it once
|
||||
// the IP has spent its budget. Used on setup, TOTP and token regeneration.
|
||||
func (l *authRateLimits) perClient(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
key := clientIP(r, l.trusted)
|
||||
if blocked, retryAfter := l.ip.Blocked(key); blocked {
|
||||
writeRateLimited(w, retryAfter)
|
||||
return
|
||||
}
|
||||
l.ip.Hit(key)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// login applies two budgets. Every attempt counts against the client IP. Failed
|
||||
// attempts (401) count against the account named in the body, so guessing one
|
||||
// password is capped even when the attacker rotates addresses.
|
||||
func (l *authRateLimits) login(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
key := clientIP(r, l.trusted)
|
||||
if blocked, retryAfter := l.ip.Blocked(key); blocked {
|
||||
writeRateLimited(w, retryAfter)
|
||||
return
|
||||
}
|
||||
l.ip.Hit(key)
|
||||
|
||||
account := loginAccount(r)
|
||||
if account != "" {
|
||||
if blocked, retryAfter := l.failures.Blocked(account); blocked {
|
||||
writeRateLimited(w, retryAfter)
|
||||
return
|
||||
}
|
||||
}
|
||||
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(recorder, r)
|
||||
if account != "" && recorder.status == http.StatusUnauthorized {
|
||||
l.failures.Hit(account)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// loginAccount returns the normalised identifier from a login body and restores
|
||||
// the body for the handler. It returns "" when the body names no account.
|
||||
func loginAccount(r *http.Request) string {
|
||||
if r.Body == nil {
|
||||
return ""
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, loginBodyLimit))
|
||||
_ = r.Body.Close()
|
||||
r.Body = io.NopCloser(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var input struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if json.Unmarshal(raw, &input) != nil {
|
||||
return ""
|
||||
}
|
||||
identifier := strings.TrimSpace(input.Identifier)
|
||||
if identifier == "" {
|
||||
identifier = strings.TrimSpace(input.Email)
|
||||
}
|
||||
return strings.ToLower(identifier)
|
||||
}
|
||||
|
||||
// statusRecorder notes the status code a handler writes, so login can tell a
|
||||
// rejected password from other outcomes.
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (w *statusRecorder) WriteHeader(status int) {
|
||||
if !w.wroteHeader {
|
||||
w.status = status
|
||||
w.wroteHeader = true
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusRecorder) Write(p []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return w.ResponseWriter.Write(p)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRateLimiterBlocksAfterLimitAndResetsWithWindow(t *testing.T) {
|
||||
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
|
||||
limiter := newRateLimiter(3, time.Minute)
|
||||
limiter.now = func() time.Time { return now }
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
if blocked, _ := limiter.Blocked("a"); blocked {
|
||||
t.Fatalf("hit %d blocked before the budget was spent", i+1)
|
||||
}
|
||||
limiter.Hit("a")
|
||||
}
|
||||
blocked, retryAfter := limiter.Blocked("a")
|
||||
if !blocked {
|
||||
t.Fatal("fourth attempt was not blocked")
|
||||
}
|
||||
if retryAfter != time.Minute {
|
||||
t.Fatalf("retryAfter = %s, want 1m0s", retryAfter)
|
||||
}
|
||||
if blocked, _ := limiter.Blocked("b"); blocked {
|
||||
t.Fatal("budget for one key blocked another key")
|
||||
}
|
||||
|
||||
now = now.Add(30 * time.Second)
|
||||
if blocked, retryAfter := limiter.Blocked("a"); !blocked || retryAfter != 30*time.Second {
|
||||
t.Fatalf("mid-window Blocked() = %v, %s; want true, 30s", blocked, retryAfter)
|
||||
}
|
||||
|
||||
now = now.Add(31 * time.Second)
|
||||
if blocked, _ := limiter.Blocked("a"); blocked {
|
||||
t.Fatal("budget did not reset when the window ended")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimiterBoundsDistinctKeys(t *testing.T) {
|
||||
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
|
||||
limiter := newRateLimiter(5, time.Minute)
|
||||
limiter.maxKeys = 4
|
||||
limiter.now = func() time.Time { return now }
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
limiter.Hit("ip-" + strconv.Itoa(i))
|
||||
if len(limiter.counts) > limiter.maxKeys {
|
||||
t.Fatalf("tracked %d keys, want at most %d", len(limiter.counts), limiter.maxKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// Once the windows have expired, a new key evicts them instead of clearing live ones.
|
||||
now = now.Add(2 * time.Minute)
|
||||
limiter.Hit("fresh")
|
||||
if len(limiter.counts) != 1 {
|
||||
t.Fatalf("after expiry tracked %d keys, want 1", len(limiter.counts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerClientBudgetCountsEveryRequest(t *testing.T) {
|
||||
limits := newAuthRateLimits(nil)
|
||||
reached := 0
|
||||
handler := limits.perClient(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
reached++
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
for i := 0; i < authIPLimit+1; i++ {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/auth/totp/enable", nil))
|
||||
if i < authIPLimit && recorder.Code != http.StatusOK {
|
||||
t.Fatalf("request %d status = %d, want 200", i+1, recorder.Code)
|
||||
}
|
||||
if i == authIPLimit {
|
||||
if recorder.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("request %d status = %d, want 429", i+1, recorder.Code)
|
||||
}
|
||||
if recorder.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("429 response has no Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
if reached != authIPLimit {
|
||||
t.Fatalf("handler ran %d times, want %d", reached, authIPLimit)
|
||||
}
|
||||
}
|
||||
|
||||
// loginRequest sends one login attempt from the given address and returns the status.
|
||||
func loginRequest(handler http.Handler, remoteAddr, forwardedFor, body string) int {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body))
|
||||
request.RemoteAddr = remoteAddr
|
||||
if forwardedFor != "" {
|
||||
request.Header.Set("X-Forwarded-For", forwardedFor)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder.Code
|
||||
}
|
||||
|
||||
func TestLoginLocksAccountAfterFailuresAcrossAddresses(t *testing.T) {
|
||||
limits := newAuthRateLimits(nil)
|
||||
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// The handler must still see the body that the limiter read.
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
if !strings.Contains(string(raw), `"password":"wrong"`) {
|
||||
t.Errorf("handler body = %q, want the original login body", raw)
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
|
||||
body := `{"identifier":" Alice@Example.com ","password":"wrong"}`
|
||||
for i := 0; i < loginFailureLimit; i++ {
|
||||
// A new address each time, so only the per-account budget can trip.
|
||||
addr := "198.51.100." + strconv.Itoa(i+1) + ":5000"
|
||||
if status := loginRequest(handler, addr, "", body); status != http.StatusUnauthorized {
|
||||
t.Fatalf("failed attempt %d status = %d, want 401", i+1, status)
|
||||
}
|
||||
}
|
||||
if status := loginRequest(handler, "203.0.113.50:5000", "", body); status != http.StatusTooManyRequests {
|
||||
t.Fatalf("attempt after lockout status = %d, want 429", status)
|
||||
}
|
||||
other := `{"identifier":"bob@example.com","password":"wrong"}`
|
||||
if status := loginRequest(handler, "203.0.113.51:5000", "", other); status != http.StatusUnauthorized {
|
||||
t.Fatalf("different account status = %d, want 401", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSuccessesDoNotCountAgainstAccount(t *testing.T) {
|
||||
limits := newAuthRateLimits(nil)
|
||||
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
body := `{"email":"carol@example.com","password":"right"}`
|
||||
for i := 0; i < loginFailureLimit+5; i++ {
|
||||
if status := loginRequest(handler, "198.51.100.9:5000", "", body); status != http.StatusOK {
|
||||
t.Fatalf("successful attempt %d status = %d, want 200", i+1, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginIPBudgetUsesForwardedClientOnlyFromTrustedProxy(t *testing.T) {
|
||||
trusted := mustTrusted(t, "10.0.0.1")
|
||||
body := `{"identifier":"someone","password":"x"}`
|
||||
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
|
||||
// Behind the trusted proxy, each forwarded client has its own budget.
|
||||
proxied := newAuthRateLimits(trusted).login(ok)
|
||||
for i := 0; i < authIPLimit+10; i++ {
|
||||
forwarded := "203.0.113." + strconv.Itoa(i+1)
|
||||
if status := loginRequest(proxied, "10.0.0.1:5000", forwarded, body); status != http.StatusOK {
|
||||
t.Fatalf("forwarded client %s status = %d, want 200", forwarded, status)
|
||||
}
|
||||
}
|
||||
|
||||
// A caller that is not a trusted proxy cannot pick its own address.
|
||||
direct := newAuthRateLimits(trusted).login(ok)
|
||||
statuses := make(map[int]int)
|
||||
for i := 0; i < authIPLimit+10; i++ {
|
||||
forwarded := "203.0.113." + strconv.Itoa(i+1)
|
||||
statuses[loginRequest(direct, "192.0.2.9:5000", forwarded, body)]++
|
||||
}
|
||||
if statuses[http.StatusTooManyRequests] == 0 {
|
||||
t.Fatalf("forged X-Forwarded-For bypassed the IP budget: %v", statuses)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterRoutesLimitsLoginPerClient(t *testing.T) {
|
||||
// Auth is disabled, so login answers 200 without touching the database.
|
||||
server := &Server{auth: newAuthService(nil, "", false, true)}
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webFS)
|
||||
|
||||
body := `{"identifier":"admin","password":"x"}`
|
||||
for i := 0; i < authIPLimit; i++ {
|
||||
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusOK {
|
||||
t.Fatalf("attempt %d status = %d, want 200", i+1, status)
|
||||
}
|
||||
}
|
||||
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusTooManyRequests {
|
||||
t.Fatalf("attempt over the budget status = %d, want 429", status)
|
||||
}
|
||||
if status := loginRequest(mux, "192.0.2.21:5000", "", body); status != http.StatusOK {
|
||||
t.Fatalf("other client status = %d, want 200", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithHTTPSRequiredRefusesPlainHTTP(t *testing.T) {
|
||||
trusted := mustTrusted(t, "10.0.0.1")
|
||||
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
handler := withHTTPSRequired(trusted, ok)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
remoteAddr string
|
||||
proto string
|
||||
want int
|
||||
}{
|
||||
{name: "plain request refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", want: http.StatusForbidden},
|
||||
{name: "health probe stays open", path: "/health", remoteAddr: "192.0.2.9:5000", want: http.StatusOK},
|
||||
{name: "trusted proxy over https allowed", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "https", want: http.StatusOK},
|
||||
{name: "trusted proxy over http refused", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "http", want: http.StatusForbidden},
|
||||
{name: "untrusted https claim refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", proto: "https", want: http.StatusForbidden},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||
request.RemoteAddr = tc.remoteAddr
|
||||
if tc.proto != "" {
|
||||
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.want {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+27
-2
@@ -2,10 +2,35 @@ package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegisterRoutes(t *testing.T) {
|
||||
server := &Server{auth: newAuthService(nil, "", false, false)}
|
||||
server.registerRoutes(http.NewServeMux(), webFS)
|
||||
// Auth is disabled and there is no database, so these checks only touch
|
||||
// routes that answer before any query runs.
|
||||
server := &Server{auth: newAuthService(nil, "", false, true)}
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webFS)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{name: "health is public", method: http.MethodGet, path: "/health", want: http.StatusOK},
|
||||
{name: "sync needs a bearer token", method: http.MethodPost, path: "/api/sync", want: http.StatusUnauthorized},
|
||||
{name: "lists need a bearer token", method: http.MethodGet, path: "/api/lists", want: http.StatusUnauthorized},
|
||||
{name: "managed users pass the role gate when auth is disabled", method: http.MethodGet, path: "/api/auth/users", want: http.StatusOK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
mux.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil))
|
||||
if recorder.Code != tc.want {
|
||||
t.Fatalf("%s %s status = %d, want %d", tc.method, tc.path, recorder.Code, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+187
-24
@@ -1,12 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
@@ -36,8 +38,19 @@ type Server struct {
|
||||
internalServiceSecret string
|
||||
coreConfig *coreconfig.Store
|
||||
carrierNode *carriernodeclient.Client
|
||||
syncSlots chan struct{}
|
||||
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
|
||||
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
|
||||
trustedProxies []*net.IPNet
|
||||
}
|
||||
|
||||
// Request body limits per route. Sync pushes can carry many rows at once, so
|
||||
// they keep the larger limit; single-entity writes get the smaller one.
|
||||
const (
|
||||
jsonBodyLimit = 2 << 20
|
||||
syncBodyLimit = 50 << 20
|
||||
)
|
||||
|
||||
func main() {
|
||||
port := envOrDefault("PORT", "8080")
|
||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
@@ -47,6 +60,19 @@ func main() {
|
||||
}
|
||||
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
||||
|
||||
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
||||
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
||||
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
||||
if production && len(trustedProxies) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
@@ -104,6 +130,8 @@ func main() {
|
||||
internalServiceSecret: internalServiceSecret,
|
||||
coreConfig: coreConfig,
|
||||
carrierNode: carrierNode,
|
||||
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||
trustedProxies: trustedProxies,
|
||||
}
|
||||
|
||||
webRoot, err := fs.Sub(webFS, "web")
|
||||
@@ -115,9 +143,17 @@ func main() {
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webRoot)
|
||||
|
||||
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
||||
if production {
|
||||
handler = withHTTPSRequired(trustedProxies, handler)
|
||||
fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
||||
} else {
|
||||
fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(mux),
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
@@ -163,6 +199,10 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
||||
}
|
||||
|
||||
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// Budgets for setup, login, TOTP and token regeneration, keyed by client IP
|
||||
// (and by account for failed logins). See ratelimit.go.
|
||||
limits := newAuthRateLimits(s.trustedProxies)
|
||||
|
||||
// Health and auth bootstrap routes are intentionally public.
|
||||
mux.HandleFunc("GET /health", s.handleHealth)
|
||||
mux.HandleFunc("GET /api/info", s.handleInfo)
|
||||
@@ -170,22 +210,23 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
|
||||
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
|
||||
mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup)))
|
||||
mux.Handle("POST /api/auth/login", limits.login(http.HandlerFunc(s.auth.Login)))
|
||||
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
|
||||
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
|
||||
mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))
|
||||
mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))
|
||||
mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))
|
||||
mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))
|
||||
// Managed-user routes check the caller's role here, not only in AuthGuard.
|
||||
mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))))
|
||||
mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))))
|
||||
mux.Handle("POST /api/auth/totp/enable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify))))
|
||||
mux.Handle("POST /api/auth/totp/disable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable))))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate)))
|
||||
mux.Handle("POST /api/auth/token/regenerate", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate))))
|
||||
|
||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
@@ -250,12 +291,24 @@ func envOrDefault(name, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
|
||||
return decodeJSONLimit(w, r, target, jsonBodyLimit)
|
||||
}
|
||||
|
||||
// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails
|
||||
// with *http.MaxBytesError, which writeDecodeError turns into 413.
|
||||
func decodeJSONLimit(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
|
||||
func writeDecodeError(w http.ResponseWriter, err error, message string) {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
writeJSONError(w, http.StatusRequestEntityTooLarge, "Request body too large")
|
||||
return
|
||||
}
|
||||
return nil
|
||||
writeJSONError(w, http.StatusBadRequest, message)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
@@ -271,17 +324,42 @@ func writeJSONError(w http.ResponseWriter, status int, message string) {
|
||||
})
|
||||
}
|
||||
|
||||
func withCORS(next http.Handler) http.Handler {
|
||||
// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser
|
||||
// origins that may call the API cross-origin with credentials. It is empty by
|
||||
// default: the dashboard is same-origin and needs no CORS headers.
|
||||
func allowedOriginsFromEnv() []string {
|
||||
var origins []string
|
||||
for _, origin := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") {
|
||||
if origin = strings.TrimSpace(origin); origin != "" {
|
||||
origins = append(origins, origin)
|
||||
}
|
||||
}
|
||||
return origins
|
||||
}
|
||||
|
||||
// withCORS sends CORS headers only for origins in allowedOrigins. Any other
|
||||
// origin gets no Access-Control-Allow-Origin and no credentials header, so a
|
||||
// browser refuses its cross-origin reads.
|
||||
func withCORS(allowedOrigins []string, next http.Handler) http.Handler {
|
||||
allowed := make(map[string]bool, len(allowedOrigins))
|
||||
for _, origin := range allowedOrigins {
|
||||
allowed[origin] = true
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
}
|
||||
permitted := origin != "" && allowed[origin]
|
||||
if permitted {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
if permitted {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
@@ -289,6 +367,82 @@ func withCORS(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// withSecurityHeaders sets headers that stop the dashboard and API from being
|
||||
// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the
|
||||
// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set
|
||||
// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security.
|
||||
func withSecurityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
headers := w.Header()
|
||||
headers.Set("X-Content-Type-Options", "nosniff")
|
||||
headers.Set("X-Frame-Options", "DENY")
|
||||
headers.Set("Content-Security-Policy", "frame-ancestors 'none'")
|
||||
headers.Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// withHTTPSRequired is the PRODUCTION=true profile: a request that did not
|
||||
// arrive over TLS, directly or through a trusted proxy, gets 403. The health
|
||||
// probe is exempt so local container checks keep working.
|
||||
func withHTTPSRequired(trusted []*net.IPNet, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/health" || requestIsHTTPS(r, trusted) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusForbidden, "HTTPS is required on this server")
|
||||
})
|
||||
}
|
||||
|
||||
// gzipResponseWriter compresses a response body when the client accepts gzip.
|
||||
// Responses that carry no body (204, 304) are passed through unchanged.
|
||||
type gzipResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
gzipWriter *gzip.Writer
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) WriteHeader(status int) {
|
||||
if w.wroteHeader {
|
||||
return
|
||||
}
|
||||
w.wroteHeader = true
|
||||
// Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream.
|
||||
if status != http.StatusNoContent && status != http.StatusNotModified && status != http.StatusPartialContent {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
w.Header().Del("Content-Length")
|
||||
w.gzipWriter = gzip.NewWriter(w.ResponseWriter)
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) Write(p []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
if w.gzipWriter == nil {
|
||||
return w.ResponseWriter.Write(p)
|
||||
}
|
||||
return w.gzipWriter.Write(p)
|
||||
}
|
||||
|
||||
// withGzip compresses responses for clients that send Accept-Encoding: gzip.
|
||||
func withGzip(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Vary", "Accept-Encoding")
|
||||
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
compressed := &gzipResponseWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(compressed, r)
|
||||
if compressed.gzipWriter != nil {
|
||||
_ = compressed.gzipWriter.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func spaFileServer(root fs.FS) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(root))
|
||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -298,6 +452,8 @@ func spaFileServer(root fs.FS) http.Handler {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Content-Security-Policy", dashboardCSP(data))
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
@@ -311,6 +467,13 @@ func spaFileServer(root fs.FS) http.Handler {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
// SvelteKit names its content-hashed bundle files under _app/immutable/, so
|
||||
// those can be cached for a long time. Everything else is revalidated.
|
||||
if strings.HasPrefix(cleanPath, "_app/immutable/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func TestWithCORSAllowsOnlyListedOrigins(t *testing.T) {
|
||||
const listed = "https://dashboard.example.com"
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
allowed []string
|
||||
origin string
|
||||
want string
|
||||
}{
|
||||
{name: "listed origin is echoed", allowed: []string{listed}, origin: listed, want: listed},
|
||||
{name: "unlisted origin gets no header", allowed: []string{listed}, origin: "https://evil.example", want: ""},
|
||||
{name: "no allow list means no CORS", allowed: nil, origin: listed, want: ""},
|
||||
{name: "no origin header means no CORS", allowed: []string{listed}, origin: "", want: ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
if tc.origin != "" {
|
||||
request.Header.Set("Origin", tc.origin)
|
||||
}
|
||||
withCORS(tc.allowed, next).ServeHTTP(recorder, request)
|
||||
|
||||
if got := recorder.Header().Get("Access-Control-Allow-Origin"); got != tc.want {
|
||||
t.Fatalf("Access-Control-Allow-Origin = %q, want %q", got, tc.want)
|
||||
}
|
||||
wantCredentials := ""
|
||||
if tc.want != "" {
|
||||
wantCredentials = "true"
|
||||
}
|
||||
if got := recorder.Header().Get("Access-Control-Allow-Credentials"); got != wantCredentials {
|
||||
t.Fatalf("Access-Control-Allow-Credentials = %q, want %q", got, wantCredentials)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithCORSPreflightAllowsPatchForListedOrigin(t *testing.T) {
|
||||
const listed = "https://dashboard.example.com"
|
||||
handler := withCORS([]string{listed}, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodOptions, "/api/auth/users/1", nil)
|
||||
request.Header.Set("Origin", listed)
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusNoContent {
|
||||
t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent)
|
||||
}
|
||||
if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, "PATCH") {
|
||||
t.Fatalf("Access-Control-Allow-Methods = %q, want PATCH included", methods)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithSecurityHeadersSetsFramingAndSniffingDefaults(t *testing.T) {
|
||||
handler := withSecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
|
||||
want := map[string]string{
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Content-Security-Policy": "frame-ancestors 'none'",
|
||||
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||
}
|
||||
for name, value := range want {
|
||||
if got := recorder.Header().Get(name); got != value {
|
||||
t.Fatalf("%s = %q, want %q", name, got, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithGzipCompressesOnlyWhenAccepted(t *testing.T) {
|
||||
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}))
|
||||
|
||||
accepted := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||
request.Header.Set("Accept-Encoding", "gzip, deflate")
|
||||
handler.ServeHTTP(accepted, request)
|
||||
if got := accepted.Header().Get("Content-Encoding"); got != "gzip" {
|
||||
t.Fatalf("Content-Encoding = %q, want gzip", got)
|
||||
}
|
||||
reader, err := gzip.NewReader(accepted.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("gzip.NewReader() error = %v", err)
|
||||
}
|
||||
body, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("reading gzip body error = %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(string(body)); got != `{"ok":true}` {
|
||||
t.Fatalf("decompressed body = %q, want the JSON document", got)
|
||||
}
|
||||
|
||||
plain := httptest.NewRecorder()
|
||||
handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/web/data", nil))
|
||||
if got := plain.Header().Get("Content-Encoding"); got != "" {
|
||||
t.Fatalf("Content-Encoding without Accept-Encoding = %q, want none", got)
|
||||
}
|
||||
if got := strings.TrimSpace(plain.Body.String()); got != `{"ok":true}` {
|
||||
t.Fatalf("plain body = %q, want the JSON document", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithGzipLeavesNotModifiedWithoutBody(t *testing.T) {
|
||||
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("ETag", `W/"abc"`)
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
}))
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||
request.Header.Set("Accept-Encoding", "gzip")
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusNotModified {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusNotModified)
|
||||
}
|
||||
if got := recorder.Header().Get("Content-Encoding"); got != "" {
|
||||
t.Fatalf("Content-Encoding on 304 = %q, want none", got)
|
||||
}
|
||||
if recorder.Body.Len() != 0 {
|
||||
t.Fatalf("304 body length = %d, want 0", recorder.Body.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAFileServerCachesHashedAssetsLong(t *testing.T) {
|
||||
root := fstest.MapFS{
|
||||
"index.html": {Data: []byte("<html></html>")},
|
||||
"favicon.svg": {Data: []byte("<svg></svg>")},
|
||||
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
|
||||
}
|
||||
handler := spaFileServer(root)
|
||||
|
||||
cases := []struct {
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{path: "/", want: "no-cache"},
|
||||
{path: "/favicon.svg", want: "no-cache"},
|
||||
{path: "/_app/immutable/app.abc.js", want: "public, max-age=31536000, immutable"},
|
||||
{path: "/lists/123", want: "no-cache"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.path, func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, tc.path, nil))
|
||||
if got := recorder.Header().Get("Cache-Control"); got != tc.want {
|
||||
t.Fatalf("Cache-Control = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONLimitRejectsOversizedBodies(t *testing.T) {
|
||||
type payload struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
small := httptest.NewRecorder()
|
||||
var ok payload
|
||||
if err := decodeJSONLimit(small, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{"name":"a"}`)), &ok, 64); err != nil {
|
||||
t.Fatalf("decodeJSONLimit() within limit error = %v", err)
|
||||
}
|
||||
|
||||
large := httptest.NewRecorder()
|
||||
var tooBig payload
|
||||
body := `{"name":"` + strings.Repeat("a", 256) + `"}`
|
||||
err := decodeJSONLimit(large, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(body)), &tooBig, 64)
|
||||
if err == nil {
|
||||
t.Fatal("decodeJSONLimit() over limit returned no error")
|
||||
}
|
||||
answer := httptest.NewRecorder()
|
||||
writeDecodeError(answer, err, "Invalid JSON body")
|
||||
if answer.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status for oversized body = %d, want %d", answer.Code, http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
|
||||
malformed := httptest.NewRecorder()
|
||||
err = decodeJSONLimit(malformed, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{`)), &tooBig, 64)
|
||||
writeDecodeError(malformed, err, "Invalid JSON body")
|
||||
if malformed.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status for malformed body = %d, want %d", malformed.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
+191
-176
@@ -9,6 +9,10 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
||||
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
||||
const maxConcurrentSyncs = 4
|
||||
|
||||
func syncMaxFutureSkew() int64 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
if value < 0 {
|
||||
@@ -91,16 +95,193 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st
|
||||
return fieldLists, existingItems, nil
|
||||
}
|
||||
|
||||
// changeEventType names a synced change for the notification feed: a tombstone
|
||||
// is "deleted", a first sync reports "created", and anything else "updated".
|
||||
func changeEventType(initialSync, deleted bool) string {
|
||||
if deleted {
|
||||
return "deleted"
|
||||
}
|
||||
if initialSync {
|
||||
return "created"
|
||||
}
|
||||
return "updated"
|
||||
}
|
||||
|
||||
// syncBatch holds what every row of one sync request shares.
|
||||
type syncBatch struct {
|
||||
now int64
|
||||
initialSync bool
|
||||
deviceID string
|
||||
}
|
||||
|
||||
func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) {
|
||||
ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt))
|
||||
}
|
||||
|
||||
// applyLists upserts the pushed lists. A write older than the stored row
|
||||
// changes nothing, so it triggers no cascade or notification.
|
||||
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
||||
for _, list := range lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
||||
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt)
|
||||
|
||||
if list.IsDeleted {
|
||||
if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||
for _, field := range fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt)
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||
for _, item := range items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt)
|
||||
if item.IsDeleted {
|
||||
if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyValues upserts the pushed item values and returns the ones it could not
|
||||
// place. Items are read after applyItems has run, so a request's own item inserts
|
||||
// are visible.
|
||||
func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) {
|
||||
orphans := make([]OrphanValue, 0)
|
||||
// Resolve the fields and items the values refer to once per request, not once
|
||||
// per value.
|
||||
fieldLists, existingItems, err := valueReferences(ctx, tx, values)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now)
|
||||
listID, ok := fieldLists[value.FieldID]
|
||||
if !ok {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
|
||||
if !existingItems[value.ItemID] {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
}
|
||||
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt)
|
||||
}
|
||||
return orphans, nil
|
||||
}
|
||||
|
||||
// applySyncRequest writes everything a device pushed, parents before children.
|
||||
func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) {
|
||||
if err := applyLists(ctx, tx, request.Lists, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyFields(ctx, tx, request.Fields, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyItems(ctx, tx, request.Items, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return applyValues(ctx, tx, request.ItemValues, batch)
|
||||
}
|
||||
|
||||
// changesSince reads what a device has to pull: everything when since is nil,
|
||||
// otherwise the rows updated at or after it. The caller adds the orphan list and
|
||||
// the server timestamp.
|
||||
func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) {
|
||||
lists, err := d.queryLists(ctx, true, since)
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
fields, err := d.queryFields(ctx, true, since, "")
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
items, err := d.queryItems(ctx, true, since, "")
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
values, err := d.queryValues(ctx, since, "")
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
// Bound the number of syncs in flight, so large bodies and transactions cannot
|
||||
// take every database connection at once.
|
||||
select {
|
||||
case s.syncSlots <- struct{}{}:
|
||||
defer func() { <-s.syncSlots }()
|
||||
case <-r.Context().Done():
|
||||
writeJSONError(w, http.StatusServiceUnavailable, "Sync busy")
|
||||
return
|
||||
}
|
||||
|
||||
var request SyncRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
||||
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
|
||||
writeDecodeError(w, err, "Invalid sync request")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
deviceID := requestDeviceID(r, request.DeviceID)
|
||||
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||
orphans := make([]OrphanValue, 0)
|
||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||
if incoming > 0 {
|
||||
@@ -108,154 +289,9 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
for _, list := range request.Lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if list.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
|
||||
|
||||
if list.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, field := range request.Fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
||||
fieldType := field.FieldType
|
||||
if fieldType == "" {
|
||||
fieldType = "TEXT"
|
||||
}
|
||||
alignment := field.Alignment
|
||||
if alignment == "" {
|
||||
alignment = "start"
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
fieldtype = EXCLUDED.fieldtype,
|
||||
fieldoptions = EXCLUDED.fieldoptions,
|
||||
alignment = EXCLUDED.alignment,
|
||||
"order" = EXCLUDED."order",
|
||||
updatedat = EXCLUDED.updatedat,
|
||||
isdeleted = EXCLUDED.isdeleted
|
||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if field.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range request.Items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if item.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
|
||||
if item.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the fields and items the values refer to once per request, not once
|
||||
// per value. Items are read after the item loop above, so this request's own
|
||||
// item inserts are visible.
|
||||
fieldLists, existingItems, err := valueReferences(r.Context(), tx, request.ItemValues)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, value := range request.ItemValues {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
||||
listID, ok := fieldLists[value.FieldID]
|
||||
if !ok {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
|
||||
if !existingItems[value.ItemID] {
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
|
||||
}
|
||||
return nil
|
||||
var err error
|
||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
||||
@@ -267,33 +303,12 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
if lastSync != 0 {
|
||||
since = &lastSync
|
||||
}
|
||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
||||
response, err := s.db.changesSince(r.Context(), since)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, SyncResponse{
|
||||
Lists: lists,
|
||||
Fields: fields,
|
||||
Items: items,
|
||||
ItemValues: values,
|
||||
OrphanItemValues: orphans,
|
||||
ServerTimestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
response.OrphanItemValues = orphans
|
||||
response.ServerTimestamp = time.Now().UnixMilli()
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
@@ -25,3 +25,24 @@ func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
|
||||
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeEventTypeNamesEachChange(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
initialSync bool
|
||||
deleted bool
|
||||
want string
|
||||
}{
|
||||
{name: "first sync creates", initialSync: true, want: "created"},
|
||||
{name: "later edit updates", initialSync: false, want: "updated"},
|
||||
{name: "tombstone is deleted on first sync", initialSync: true, deleted: true, want: "deleted"},
|
||||
{name: "tombstone is deleted later", initialSync: false, deleted: true, want: "deleted"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := changeEventType(tc.initialSync, tc.deleted); got != tc.want {
|
||||
t.Fatalf("changeEventType(%v, %v) = %q, want %q", tc.initialSync, tc.deleted, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user