Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Fix pre-1.0.7 CSP, photo timeout env, CSV dates, and CSV neutralization

sassanix80e304f66592
diff --git a/backend/__init__.py b/backend/__init__.py
index 20f5946..455ede1 100644
--- a/backend/__init__.py
+++ b/backend/__init__.py
@@ -180,6 +180,10 @@ def ensure_owner_exists():
# font and images from the buymeacoffee and Google Fonts hosts,
# version-checker.js fetches the latest release from api.github.com,
# and style.css uses an Unsplash photo as a page background.
+# upgrade-insecure-requests is intentionally omitted: self-hosted
+# installs on plain HTTP (LAN IP, localhost, Unraid, Proxmox, TrueNAS)
+# would otherwise have browsers rewrite same-origin subresources to
+# https:// and fail to load.
_CONTENT_SECURITY_POLICY = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; "
@@ -191,8 +195,7 @@ _CONTENT_SECURITY_POLICY = (
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
- "frame-ancestors 'self'; "
- "upgrade-insecure-requests"
+ "frame-ancestors 'self'"
)
diff --git a/backend/config.py b/backend/config.py
index 27a35ab..2eb5e79 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -127,6 +127,29 @@ class Config:
logger.info(f"Max upload file size set to: {max_upload_mb}MB")
return max_upload_mb
+
+ DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS = 60
+
+ @staticmethod
+ def _get_photo_fetch_timeout_seconds():
+ raw = os.environ.get('PHOTO_FETCH_TIMEOUT_SECONDS', '').strip()
+ if not raw:
+ return Config.DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS
+ try:
+ timeout = float(raw)
+ except ValueError:
+ logger.warning(
+ f"PHOTO_FETCH_TIMEOUT_SECONDS={raw!r} was not a valid number, "
+ f"defaulting to {Config.DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS}s."
+ )
+ return Config.DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS
+ if timeout != timeout or timeout in (float('inf'), float('-inf')) or timeout <= 0:
+ logger.warning(
+ f"PHOTO_FETCH_TIMEOUT_SECONDS={raw!r} must be positive and finite, "
+ f"defaulting to {Config.DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS}s."
+ )
+ return Config.DEFAULT_PHOTO_FETCH_TIMEOUT_SECONDS
+ return timeout
# Email Configuration
EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS = 24
@@ -220,6 +243,7 @@ class Config:
# Set upload configuration
max_upload_mb = Config._get_max_upload_mb()
app.config['MAX_CONTENT_LENGTH'] = max_upload_mb * 1024 * 1024
+ app.config['PHOTO_FETCH_TIMEOUT_SECONDS'] = Config._get_photo_fetch_timeout_seconds()
# Log configuration status
logger.info("Application configuration initialized successfully")
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 90e6f87..5cb1d50 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -21,7 +21,9 @@ CSV_DATE_FORMATS = (
'%b %d, %Y', # Mar 15, 2024
'%B %d, %Y', # March 15, 2024
'%d %b, %Y', # 15 Mar, 2024
+ '%d %B, %Y', # 15 March, 2024
'%b %d %Y', # Mar 15 2024
+ '%B %d %Y', # March 15 2024
)
diff --git a/frontend/js/components/importExport.js b/frontend/js/components/importExport.js
index a5f76a1..3e5a08a 100644
--- a/frontend/js/components/importExport.js
+++ b/frontend/js/components/importExport.js
@@ -11,9 +11,11 @@ import { formatDateYYYYMMDD } from '../lib/dates.js';
// re-imported export round-trips to the stored value.
export function neutralizeCsvFormula(value) {
const text = String(value);
- const first = text.trimStart()[0];
- if (first === '=' || first === '+' || first === '-' || first === '@'
- || first === '\t' || first === '\r') {
+ const firstNonSpace = text.replace(/^ +/, '')[0];
+ const firstNonWhitespace = text.trimStart()[0];
+ if (firstNonSpace === '\t' || firstNonSpace === '\r'
+ || firstNonWhitespace === '=' || firstNonWhitespace === '+'
+ || firstNonWhitespace === '-' || firstNonWhitespace === '@') {
return '\t' + text;
}
return text;
diff --git a/frontend/status.js b/frontend/status.js
index 3a6110d..bdc34bd 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -801,9 +801,11 @@
// round-trips to the stored value.
const neutralizeCsvFormula = (value) => {
const text = String(value);
- const first = text.trimStart()[0];
- if (first === '=' || first === '+' || first === '-' || first === '@'
- || first === '\t' || first === '\r') {
+ const firstNonSpace = text.replace(/^ +/, '')[0];
+ const firstNonWhitespace = text.trimStart()[0];
+ if (firstNonSpace === '\t' || firstNonSpace === '\r'
+ || firstNonWhitespace === '=' || firstNonWhitespace === '+'
+ || firstNonWhitespace === '-' || firstNonWhitespace === '@') {
return '\t' + text;
}
return text;
diff --git a/nginx.conf b/nginx.conf
index 56c746f..0fcb06e 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -13,7 +13,7 @@ server {
# Locations below that define their own add_header directives do
# not inherit these, so the HTML location repeats them.
add_header X-Frame-Options "SAMEORIGIN" always;
- add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests" always;
+ add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Suppress the nginx version number in error pages and the Server
@@ -130,7 +130,7 @@ server {
# Repeated: locations with their own add_header do not inherit
# the server-level security headers (CFG-07a/b/d).
add_header X-Frame-Options "SAMEORIGIN" always;
- add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests" always;
+ add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
diff --git a/tests/test_csv_date_formats.py b/tests/test_csv_date_formats.py
index a842902..9712b7a 100644
--- a/tests/test_csv_date_formats.py
+++ b/tests/test_csv_date_formats.py
@@ -27,7 +27,9 @@ def test_accepted_formats():
assert parse_unambiguous_date("Mar 15, 2024") == date(2024, 3, 15)
assert parse_unambiguous_date("March 15, 2024") == date(2024, 3, 15)
assert parse_unambiguous_date("15 Mar, 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("15 March, 2024") == date(2024, 3, 15)
assert parse_unambiguous_date("Mar 15 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("March 15 2024") == date(2024, 3, 15)
assert parse_unambiguous_date("5 Mar 2024") == date(2024, 3, 5)
assert parse_unambiguous_date("15 mar 2024") == date(2024, 3, 15)
assert parse_unambiguous_date(" 2024-03-15 ") == date(2024, 3, 15)
diff --git a/tests/test_csv_formula_neutralization.py b/tests/test_csv_formula_neutralization.py
index fb36c09..d22b741 100644
--- a/tests/test_csv_formula_neutralization.py
+++ b/tests/test_csv_formula_neutralization.py
@@ -6,8 +6,13 @@ neutralize such values with a tab prefix, which the importer strips
on re-import, so an export round-trips to the stored value. These
pins fail if an exporter quotes a field without neutralizing it.
"""
+import re
+import shutil
+import subprocess
from pathlib import Path
+import pytest
+
REPO = Path(__file__).resolve().parent.parent
@@ -26,3 +31,61 @@ def test_both_exporters_neutralize_formulas():
for trigger in ("'='", "'+'", "'-'", "'@'", "'\\t'", "'\\r'"):
assert trigger in main, trigger
assert trigger in status, trigger
+
+
+def _extract_neutralizer_js(source, pattern):
+ match = re.search(pattern, source, re.S)
+ assert match, f"could not extract neutralizeCsvFormula with {pattern}"
+ return match.group(0)
+
+
+def test_neutralize_csv_formula_behavior_in_both_exporters():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is not installed")
+
+ main_src = (REPO / "frontend" / "js" / "components"
+ / "importExport.js").read_text()
+ status_src = (REPO / "frontend" / "status.js").read_text()
+
+ main_fn = _extract_neutralizer_js(
+ main_src, r"export function neutralizeCsvFormula\(value\)\s*\{.*?\n\}"
+ ).replace("export ", "", 1)
+ status_fn = _extract_neutralizer_js(
+ status_src, r"const neutralizeCsvFormula = \(value\) => \{.*?\n\s*\};"
+ )
+
+ script = """
+ const cases = [
+ ['=1+1', '\\t=1+1'],
+ ['+1+1', '\\t+1+1'],
+ ['-1+1', '\\t-1+1'],
+ ['@SUM(1,2)', '\\t@SUM(1,2)'],
+ [' =1+1', '\\t =1+1'],
+ ['\\n=1+1', '\\t\\n=1+1'],
+ ['\\tfoo', '\\t\\tfoo'],
+ [' \\tfoo', '\\t \\tfoo'],
+ ['\\t=1+1', '\\t\\t=1+1'],
+ ['\\rfoo', '\\t\\rfoo'],
+ [' \\rfoo', '\\t \\rfoo'],
+ ['Widget', 'Widget'],
+ [' Widget', ' Widget'],
+ ['123', '123'],
+ ['', ''],
+ ];
+ for (const [input, expected] of cases) {
+ const actual = neutralizeCsvFormula(input);
+ if (actual !== expected) {
+ throw new Error(
+ `Input ${JSON.stringify(input)}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
+ );
+ }
+ }
+ """
+
+ for name, fn_code in (("importExport.js", main_fn), ("status.js", status_fn)):
+ r = subprocess.run(
+ [node, "-e", fn_code + "\n" + script],
+ capture_output=True, text=True,
+ )
+ assert r.returncode == 0, f"{name}: {r.stderr}"
diff --git a/tests/test_photo_url.py b/tests/test_photo_url.py
index 763ef12..3ffbc75 100644
--- a/tests/test_photo_url.py
+++ b/tests/test_photo_url.py
@@ -222,6 +222,7 @@ def test_slow_drip_fetch_times_out(app):
server = ThreadingHTTPServer(("127.0.0.1", 0), _DripHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
+ previous_timeout = app.config.get("PHOTO_FETCH_TIMEOUT_SECONDS")
try:
url = f"http://127.0.0.1:{server.server_address[1]}/drip.png"
app.config["ALLOW_PRIVATE_PHOTO_URLS"] = True
@@ -232,6 +233,33 @@ def test_slow_drip_fetch_times_out(app):
download_product_photo(url)
assert time.monotonic() - start < 10
finally:
- app.config.pop("PHOTO_FETCH_TIMEOUT_SECONDS", None)
+ if previous_timeout is None:
+ app.config.pop("PHOTO_FETCH_TIMEOUT_SECONDS", None)
+ else:
+ app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] = previous_timeout
app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
server.shutdown()
+
+
+def test_photo_fetch_timeout_env_var(monkeypatch):
+ from flask import Flask
+ from backend.config import Config
+
+ monkeypatch.delenv("PHOTO_FETCH_TIMEOUT_SECONDS", raising=False)
+ assert Config._get_photo_fetch_timeout_seconds() == 60
+
+ monkeypatch.setenv("PHOTO_FETCH_TIMEOUT_SECONDS", "15")
+ assert Config._get_photo_fetch_timeout_seconds() == 15.0
+
+ monkeypatch.setenv("PHOTO_FETCH_TIMEOUT_SECONDS", "2.5")
+ assert Config._get_photo_fetch_timeout_seconds() == 2.5
+
+ for invalid in ("", " ", "0", "-5", "abc", "nan", "inf", "-inf"):
+ monkeypatch.setenv("PHOTO_FETCH_TIMEOUT_SECONDS", invalid)
+ assert Config._get_photo_fetch_timeout_seconds() == 60, invalid
+
+ monkeypatch.setenv("PHOTO_FETCH_TIMEOUT_SECONDS", "12")
+ probe_app = Flask(__name__)
+ probe_app.config["TESTING"] = True
+ Config.init_app(probe_app)
+ assert probe_app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] == 12.0
diff --git a/tests/test_security_headers.py b/tests/test_security_headers.py
index c48512d..49d2365 100644
--- a/tests/test_security_headers.py
+++ b/tests/test_security_headers.py
@@ -60,3 +60,9 @@ def test_csp_blocks_plugins_and_foreign_framing():
assert "frame-ancestors 'self'" in _CONTENT_SECURITY_POLICY
assert "base-uri 'self'" in _CONTENT_SECURITY_POLICY
assert "form-action 'self'" in _CONTENT_SECURITY_POLICY
+
+
+def test_csp_does_not_force_https_for_plain_http_installs():
+ # Plain-HTTP self-hosted installs (LAN IPs, localhost, Unraid,
+ # Proxmox, TrueNAS) break if browsers rewrite subresources to https.
+ assert "upgrade-insecure-requests" not in _CONTENT_SECURITY_POLICY