From 4050f7311b42c88dfc8d7ff97c25091c23000455 Mon Sep 17 00:00:00 2001 From: driedel Date: Thu, 17 Sep 2026 19:18:34 -0300 Subject: [PATCH 1/5] ci(security): replace Codacy scan with CodeQL The Codacy Analysis CLI bundles three outdated linters (Pylint 1.9.5, Pylint-python3 2.6.0, Prospector 1.2.0) that reported every issue 2-3x and produced hundreds of false positives on modern Python syntax. Replace it with the native github/codeql-action workflow (Python) and drop the now-unused .codacy.yml engine config. --- .codacy.yml | 21 ------------- .github/workflows/codacy.yml | 61 ------------------------------------ .github/workflows/codeql.yml | 32 +++++++++++++++++++ 3 files changed, 32 insertions(+), 82 deletions(-) delete mode 100644 .codacy.yml delete mode 100644 .github/workflows/codacy.yml create mode 100644 .github/workflows/codeql.yml diff --git a/.codacy.yml b/.codacy.yml deleted file mode 100644 index 4738b19..0000000 --- a/.codacy.yml +++ /dev/null @@ -1,21 +0,0 @@ ---- -# Codacy configuration for make-it-static -# https://docs.codacy.com/repositories-configure/codacy-configuration-file/ - -engines: - bandit: - # .bandit configures skips (e.g., B101 assert_used in pytest). - enabled: true - pylint: - enabled: true - pylintpython3: - enabled: true - prospector: - enabled: true - -# Global paths to ignore. -exclude_paths: - - ".git/**" - - "__pycache__/**" - - "**/__pycache__/**" - - "*.egg-info/**" diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml deleted file mode 100644 index 77709b1..0000000 --- a/.github/workflows/codacy.yml +++ /dev/null @@ -1,61 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow checks out code, performs a Codacy security scan -# and integrates the results with the -# GitHub Advanced Security code scanning feature. For more information on -# the Codacy security scan action usage and parameters, see -# https://github.com/codacy/codacy-analysis-cli-action. -# For more information on Codacy Analysis CLI in general, see -# https://github.com/codacy/codacy-analysis-cli. - -name: Codacy Security Scan - -on: - push: - branches: [ "main" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main" ] - schedule: - - cron: '37 1 * * 6' - -permissions: - contents: read - -jobs: - codacy-security-scan: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - name: Codacy Security Scan - runs-on: ubuntu-latest - steps: - # Checkout the repository to the GitHub Actions runner - - name: Checkout code - uses: actions/checkout@v4 - - # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis - - name: Run Codacy Analysis CLI - uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b - with: - # Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository - # You can also omit the token and run the tools that support default configurations - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} - verbose: true - output: results.sarif - format: sarif - # Adjust severity of non-security issues - gh-code-scanning-compat: true - # Force 0 exit code to allow SARIF file generation - # This will handover control about PR rejection to the GitHub side - max-allowed-issues: 2147483647 - - # Upload the SARIF file generated in the previous step - - name: Upload SARIF results file - uses: github/codeql-action/upload-sarif@v3 - with: - sarif_file: results.sarif diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..0c27851 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,32 @@ +name: CodeQL + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + schedule: + - cron: '37 1 * * 6' + +permissions: + contents: read + +jobs: + analyze: + name: Analyze (python) + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + steps: + - uses: actions/checkout@v4 + + - uses: github/codeql-action/init@v3 + with: + languages: python + + # Python does not require a build step — go straight to analysis. + - uses: github/codeql-action/analyze@v3 + with: + category: "/language:python" From 13ef97624a7b88d4b62dc259692334904d9df277 Mon Sep 17 00:00:00 2001 From: driedel Date: Thu, 17 Sep 2026 19:18:41 -0300 Subject: [PATCH 2/5] ci(tests): add blocking pylint step Run modern Pylint (3.x) with all dependencies installed so import resolution works, and tighten .pylintrc: docstring, line-length and complexity rules are now enforced, with pragmatic DESIGN thresholds and justified disables (test patching patterns, per-file error tolerance, compiled Rust extensions). --- .github/workflows/tests.yml | 5 ++ .pylintrc | 94 +++++++++---------------------------- 2 files changed, 28 insertions(+), 71 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index af616a4..032604c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -28,6 +28,11 @@ jobs: pip install -r worker/requirements.txt pip install -r tests/requirements.txt + - name: Lint with pylint + run: | + pip install "pylint==3.3.*" + pylint api worker tests + - name: Run tests run: | pytest tests/ -v \ diff --git a/.pylintrc b/.pylintrc index 541418e..3df0df9 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,101 +1,53 @@ +# Pylint configuration for the make-it-static codebase. +# Modern Pylint (3.x) run with all service dependencies installed (see tests.yml). +# The project has no package structure: tests import `main` (from api/) and the +# worker modules directly, relying on sys.path setup from tests/conftest.py. +# Mirror that here (absolute paths — relative ones break astroid's import +# resolution for site-packages) so pylint can resolve those imports. + [MAIN] -# Python version to target. py-version = 3.12 +init-hook = 'import sys, os; sys.path[:0] = [os.path.join(os.getcwd(), "api"), os.path.join(os.getcwd(), "worker")]' -# Ensure pylint can resolve api/ and worker/ imports the same way pytest does. -init-hook = 'import sys; from pathlib import Path; sys.path.insert(0, str(Path(".").resolve() / "api")); sys.path.insert(0, str(Path(".").resolve() / "worker"))' - -# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the -# number of processors available to use, and will cap on 4 to avoid I/O errors. +# Use multiple processes to speed up Pylint (0 = auto-detect, capped at 4). jobs = 0 -# Control the amount of potential inferred values when inferring a single object. -# This can help the performance when dealing with large functions or complex, -# nested conditions. -limit-inference-results = 100 - # Files or directories to be skipped. They should be base names, not paths. ignore = .git,__pycache__,.venv,venv [MESSAGES CONTROL] -# Disable the message, report, category or checker with the given id(s). disable = - # Docstrings: the project does not require docstrings on every module/class/function. - missing-module-docstring, - missing-class-docstring, - missing-function-docstring, - # Naming conventions: too noisy for small scripts and pytest fixtures/helpers. - invalid-name, - # Style/formatting: handled by the project author, not by lint failures. - line-too-long, - # Imports inside functions are acceptable (e.g., lazy imports in tests/workers). + # tests/test_api.py intentionally patches redis/rq before importing main import-outside-toplevel, - # Many false positives with typed containers and optional types. - unsubscriptable-object, - # Similar/duplicate code is common in tests and worker scripts. + # the pipeline deliberately continues on per-file errors (postprocess/optimize) + broad-exception-caught, + # test option dicts and HTML fixtures legitimately repeat across test files duplicate-code, - # Broad excepts are intentionally used at worker/job boundaries. - broad-except, - # Too-many-* rules are too strict for this small webhook/worker codebase. - too-many-locals, - too-many-arguments, - too-many-positional-arguments, - too-many-statements, - too-many-branches, - too-many-nested-blocks, - too-many-instance-attributes, - too-few-public-methods, - # pytest fixtures trigger this. + # many false positives with typed containers and optional types + unsubscriptable-object, + # pytest fixtures trigger this redefined-outer-name, - # String statements are used as module-level notes. - pointless-string-statement, - # raise-missing-from is good practice but not enforced here. - raise-missing-from, -[REPORTS] -# Set the output format. Available formats are text, parseable, colorized, json2. -output-format = colorized - -# Tells whether to display a full report or only the messages. -reports = no +[FORMAT] +max-line-length = 100 +max-module-lines = 1000 [BASIC] -# Good variable names which should always be accepted, separated by a comma. good-names = i,j,k,ex,Run,_,id,fn,fp -[FORMAT] -# Maximum number of characters on a single line. -max-line-length = 120 - -# Maximum number of lines in a module. -max-module-lines = 1000 - [DESIGN] -# Maximum number of arguments for function / method. +# The pipeline functions track several counters/paths; these thresholds keep +# them enforceable without forcing artificial restructuring. max-args = 10 - -# Maximum number of locals for function / method body. max-locals = 20 - -# Maximum number of return / yield for function / method body. max-returns = 10 - -# Maximum number of statements in function / method body. max-statements = 60 - -# Maximum number of parents for a class (see R0901). max-parents = 7 - -# Maximum number of attributes for a class (see R0902). max-attributes = 10 - -# Minimum number of public methods for a class (see R0903). min-public-methods = 0 - -# Maximum number of public methods for a class (see R0904). max-public-methods = 30 [TYPECHECK] -# List of members which are set dynamically and missed by pylint inference -# engine, and so shouldn't trigger E1101 when accessed. +# Members set dynamically or provided by compiled extensions that astroid +# cannot introspect (minify_html is a Rust extension). generated-members = boto3.client, boto3.resource, minify_html.minify From 533f231e959a5ba8659e2862962fbf31f95ff338 Mon Sep 17 00:00:00 2001 From: driedel Date: Thu, 17 Sep 2026 19:18:48 -0300 Subject: [PATCH 3/5] refactor(worker): extract helpers to satisfy pylint complexity rules - jobs.py: add _fetch() shared by the three wget call sites, _base_origin(), _elementor_targets(), and split deploy_page into _scrape/_postprocess/_deploy pipeline steps - optimize.py: add _find_local_assets(), _save_as_modern_format() and _fix_css_format_hints() - postprocess.py: split main() into _clean_html_files/_clean_css_files and move the module docstring above the imports No behavior changes; pipeline messages and ordering are preserved. --- worker/jobs.py | 196 ++++++++++++++++++++++++------------------ worker/optimize.py | 122 +++++++++++++++----------- worker/postprocess.py | 97 +++++++++++++-------- 3 files changed, 245 insertions(+), 170 deletions(-) diff --git a/worker/jobs.py b/worker/jobs.py index 7b2fe0f..6757c6f 100644 --- a/worker/jobs.py +++ b/worker/jobs.py @@ -51,6 +51,23 @@ def _make_workdir(post_id: int) -> pathlib.Path: return pathlib.Path(tempfile.mkdtemp(prefix=prefix)) +def _fetch(url: str, dest: pathlib.Path) -> bool: + """Downloads url into dest with wget; returns True on success (dest removed on failure).""" + dest.parent.mkdir(parents=True, exist_ok=True) + result = subprocess.run( # nosec B603 + [ + "/usr/bin/wget", "-q", "--timeout=30", "--tries=3", + "-O", str(dest), url, + ], + capture_output=True, + check=False, + ) + if result.returncode == 0: + return True + dest.unlink(missing_ok=True) + return False + + def _safe_path(workdir: pathlib.Path, *parts: str) -> pathlib.Path | None: """Joins path parts and ensures the resolved result stays within workdir.""" target = workdir.joinpath(*parts).resolve() @@ -72,6 +89,12 @@ def url_to_prefix(url: str) -> str: return urlparse(url).path.strip("/") +def _base_origin(url: str) -> str: + """Returns scheme://netloc for a URL (assets are fetched from the origin host).""" + parsed = urlparse(url) + return f"{parsed.scheme}://{parsed.netloc}" + + def download_dynamic_cdn_assets(workdir: pathlib.Path, extra_cdn: list[str]) -> int: """ Downloads CDN assets that are injected via JavaScript strings (invisible to wget). @@ -115,18 +138,11 @@ def download_dynamic_cdn_assets(workdir: pathlib.Path, extra_cdn: list[str]) -> if local_path is None or local_path.exists(): continue - local_path.parent.mkdir(parents=True, exist_ok=True) - result = subprocess.run( # nosec B603 - ["/usr/bin/wget", "-q", "--timeout=30", "--tries=3", "-O", str(local_path), full_url], - capture_output=True, - check=False, - ) - if result.returncode == 0: + if _fetch(full_url, local_path): print(f"[job] dynamic CDN asset downloaded: {full_url}") downloaded += 1 else: print(f"[job] warning: failed to download dynamic CDN asset {full_url}") - local_path.unlink(missing_ok=True) return downloaded @@ -157,8 +173,7 @@ def download_webpack_chunks(workdir: pathlib.Path, origin_url: str) -> int: extracts hashed chunk filenames, and downloads any missing ones from the origin. Must be called BEFORE postprocess so the files are present for S3 upload. """ - parsed = urlparse(origin_url) - base_origin = f"{parsed.scheme}://{parsed.netloc}" + base_origin = _base_origin(origin_url) seen: set[str] = set() downloaded = 0 @@ -189,21 +204,23 @@ def download_webpack_chunks(workdir: pathlib.Path, origin_url: str) -> int: continue seen.add(chunk_url) - result = subprocess.run( # nosec B603 - ["/usr/bin/wget", "-q", "--timeout=30", "--tries=3", "-O", str(safe_local), chunk_url], - capture_output=True, - check=False, - ) - if result.returncode == 0: + if _fetch(chunk_url, safe_local): print(f"[job] webpack chunk downloaded: {chunk_url}") downloaded += 1 else: print(f"[job] warning: failed to download webpack chunk {chunk_url}") - local_path.unlink(missing_ok=True) return downloaded +def _elementor_targets(text: str): + """Yields (asset_rel_path, version) for each AssetsLoader lib/ path found in text.""" + for m in _ELEMENTOR_ASSET.finditer(text): + rel_stem, version = m.group(1), m.group(2) + ext = ".js" if ".js" in m.group(0) else ".css" + yield f"lib/{rel_stem}.min{ext}", version + + def download_elementor_dynamic_assets(workdir: pathlib.Path, origin_url: str) -> int: """ Downloads Elementor AssetsLoader scripts/styles not referenced in HTML attributes. @@ -217,8 +234,7 @@ def download_elementor_dynamic_assets(workdir: pathlib.Path, origin_url: str) -> The file is saved with the clean name (no ?ver= query) since S3/CloudFront strips query strings when looking up objects. """ - parsed = urlparse(origin_url) - base_origin = f"{parsed.scheme}://{parsed.netloc}" + base_origin = _base_origin(origin_url) seen: set[str] = set() downloaded = 0 @@ -239,10 +255,7 @@ def download_elementor_dynamic_assets(workdir: pathlib.Path, origin_url: str) -> assets_dir = js_file.parent.parent.relative_to(workdir) - for m in _ELEMENTOR_ASSET.finditer(text): - rel_stem, version = m.group(1), m.group(2) - ext = ".js" if ".js" in m.group(0) else ".css" - asset_rel = f"lib/{rel_stem}.min{ext}" + for asset_rel, version in _elementor_targets(text): local_path = _safe_path(workdir, assets_dir, asset_rel) asset_url = f"{base_origin}/{assets_dir}/{asset_rel}?ver={version}" @@ -254,18 +267,11 @@ def download_elementor_dynamic_assets(workdir: pathlib.Path, origin_url: str) -> continue seen.add(asset_url) - local_path.parent.mkdir(parents=True, exist_ok=True) - result = subprocess.run( # nosec B603 - ["/usr/bin/wget", "-q", "--timeout=30", "--tries=3", "-O", str(local_path), asset_url], - capture_output=True, - check=False, - ) - if result.returncode == 0: + if _fetch(asset_url, local_path): print(f"[job] Elementor asset downloaded: {asset_url}") downloaded += 1 else: print(f"[job] warning: failed to download Elementor asset {asset_url}") - local_path.unlink(missing_ok=True) return downloaded @@ -285,6 +291,75 @@ def _build_opt_cmd(workdir: pathlib.Path, opts: dict) -> list[str]: return cmd +def _scrape(url: str, workdir: pathlib.Path, extra_cdn: list[str]) -> None: + """ + Pipeline step 1: scrape the page into workdir with wget. + + Also downloads CDN assets injected via JavaScript strings (createElement + + .href/.src = 'https://cdn/...'), which are invisible to wget. Must run before + postprocess so the files exist once URLs are rewritten to local paths. + """ + print(f"[job] step 1/4: scraping {url}", flush=True) + scrape_cmd = ["bash", "/app/scrape.sh", url, str(workdir)] + if extra_cdn: + scrape_cmd.append(",".join(extra_cdn)) + scrape = _run(scrape_cmd, timeout=300) + if scrape.returncode != 0: + raise RuntimeError(f"scrape failed (rc={scrape.returncode}):\n{scrape.stdout[-2000:]}") + + if extra_cdn: + dyn = download_dynamic_cdn_assets(workdir, extra_cdn) + print(f"[job] {dyn} dynamic CDN asset(s) downloaded", flush=True) + + +def _postprocess(workdir: pathlib.Path, hostname: str, url: str, extra_cdn: list[str]) -> None: + """ + Pipeline steps 2/2b/2c: clean up HTML, then fetch runtime-only assets. + + Strips absolute references to the origin host and each extra CDN. The webpack + and Elementor passes run AFTER postprocess so runtime files renamed by it + (e.g. webpack.runtime.min.js@ver=3.26.3 → .min.js) are found by the *.js glob. + """ + print("[job] step 2/4: postprocessing HTML", flush=True) + postprocess = _run(["python", "/app/postprocess.py", str(workdir), hostname] + extra_cdn) + if postprocess.returncode != 0: + print("[job] warning: postprocess failed, continuing anyway", flush=True) + + wc = download_webpack_chunks(workdir, url) + print(f"[job] {wc} webpack chunk(s) downloaded", flush=True) + + ea = download_elementor_dynamic_assets(workdir, url) + print(f"[job] {ea} Elementor dynamic asset(s) downloaded", flush=True) + + +def _deploy( + workdir: pathlib.Path, + hostname: str, + page_path: str, + cloudfront_distribution_id: str, +) -> dict: + """ + Pipeline steps 4/5: upload to S3 and invalidate CloudFront. + + The top-level S3 prefix is the hostname, which isolates different sites in the + same bucket: workdir/blog/page/index.html → bucket/{hostname}/blog/page/index.html. + In production, set the Origin Path of each CloudFront distribution to "/{hostname}". + CloudFront distribution priority: payload value → CLOUDFRONT_DISTRIBUTION_ID env var. + """ + print("[job] step 4/4: uploading to S3", flush=True) + bucket = os.environ["S3_BUCKET"] + uploaded = sync_to_s3(local_dir=workdir, bucket=bucket, prefix=hostname) + print(f"[job] {uploaded} file(s) uploaded to s3://{bucket}/{hostname}/") + + dist_id = cloudfront_distribution_id or os.environ.get("CLOUDFRONT_DISTRIBUTION_ID", "") + invalidation_paths = [f"/{page_path}/*"] if page_path else ["/*"] + invalidation_id = invalidate_cloudfront( + distribution_id=dist_id, + paths=invalidation_paths, + ) + return {"files_uploaded": uploaded, "invalidation_id": invalidation_id, "bucket": bucket} + + def deploy_page( url: str, post_id: int, @@ -314,36 +389,8 @@ def deploy_page( print(f"[job] started: url={url} post_id={post_id} site={hostname} workdir={workdir}") try: - # 1. scrape - print(f"[job] step 1/4: scraping {url}", flush=True) - scrape_cmd = ["bash", "/app/scrape.sh", url, str(workdir)] - if extra_cdn: - scrape_cmd.append(",".join(extra_cdn)) - scrape = _run(scrape_cmd, timeout=300) - if scrape.returncode != 0: - raise RuntimeError(f"scrape failed (rc={scrape.returncode}):\n{scrape.stdout[-2000:]}") - - # 1b. CDN assets loaded via JS (createElement + .href/.src = 'https://cdn/...') - if extra_cdn: - dyn = download_dynamic_cdn_assets(workdir, extra_cdn) - print(f"[job] {dyn} dynamic CDN asset(s) downloaded", flush=True) - - # 2. HTML cleanup — remove absolute references to origin host and each extra CDN - print("[job] step 2/4: postprocessing HTML", flush=True) - postprocess = _run(["python", "/app/postprocess.py", str(workdir), hostname] + extra_cdn) - if postprocess.returncode != 0: - print("[job] warning: postprocess failed, continuing anyway", flush=True) - - # 2b. webpack lazy-loaded chunks — runs after postprocess so that webpack runtime - # files have been renamed (e.g. webpack.runtime.min.js@ver=3.26.3 → .min.js) - # and are found by the *.js glob used to detect chunk maps. - wc = download_webpack_chunks(workdir, url) - print(f"[job] {wc} webpack chunk(s) downloaded", flush=True) - - # 2c. Elementor AssetsLoader assets (dialog.js, swiper.js, …) — loaded at runtime - # via template literals; never appear as literal src= attributes in HTML. - ea = download_elementor_dynamic_assets(workdir, url) - print(f"[job] {ea} Elementor dynamic asset(s) downloaded", flush=True) + _scrape(url, workdir, extra_cdn) + _postprocess(workdir, hostname, url, extra_cdn) # 3. optimization (CSS/JS bundle + minification) print("[job] step 3/4: optimizing assets", flush=True) @@ -351,24 +398,7 @@ def deploy_page( if opt.returncode != 0: print("[job] warning: optimize failed, continuing anyway", flush=True) - # 4. S3 upload - print("[job] step 4/4: uploading to S3", flush=True) - # Top-level prefix = hostname → isolates different sites in the same bucket: - # workdir/blog/page/index.html → bucket/{hostname}/blog/page/index.html - # workdir/assets/style.css → bucket/{hostname}/assets/style.css - # In production, set the Origin Path of each CloudFront distribution to "/{hostname}". - bucket = os.environ["S3_BUCKET"] - uploaded = sync_to_s3(local_dir=workdir, bucket=bucket, prefix=hostname) - print(f"[job] {uploaded} file(s) uploaded to s3://{bucket}/{hostname}/") - - # 5. CloudFront invalidation - # Priority: cloudfront_distribution_id from payload → CLOUDFRONT_DISTRIBUTION_ID env var - dist_id = cloudfront_distribution_id or os.environ.get("CLOUDFRONT_DISTRIBUTION_ID", "") - invalidation_paths = [f"/{page_path}/*"] if page_path else ["/*"] - invalidation_id = invalidate_cloudfront( - distribution_id=dist_id, - paths=invalidation_paths, - ) + deploy_result = _deploy(workdir, hostname, page_path, cloudfront_distribution_id) result = { "ok": True, @@ -376,14 +406,12 @@ def deploy_page( "post_id": post_id, "site": hostname, "prefix": page_path or "/", - "files_uploaded": uploaded, - "invalidation_id": invalidation_id, - "bucket": bucket, + **deploy_result, } print(f"[job] OK: {result}") return result - except subprocess.TimeoutExpired: - raise RuntimeError("scrape timed out (300s)") + except subprocess.TimeoutExpired as exc: + raise RuntimeError("scrape timed out (300s)") from exc finally: shutil.rmtree(workdir, ignore_errors=True) diff --git a/worker/optimize.py b/worker/optimize.py index 13c4d54..7e443a6 100644 --- a/worker/optimize.py +++ b/worker/optimize.py @@ -35,6 +35,7 @@ def _rewrite_css_urls(css_content: str, css_path: Path, bundle_path: Path, root: bundle_dir = bundle_path.parent.resolve() def rewrite(match): + """Rewrites a single url() match to be relative to the bundle's location.""" raw = match.group(1).strip() if (raw.startswith('"') and raw.endswith('"')) or ( raw.startswith("'") and raw.endswith("'") @@ -86,7 +87,27 @@ def _update_refs( if new_text != text: fpath.write_text(new_text, encoding="utf-8") except OSError as exc: - print(f"[optimize] warning: could not update refs in {fpath}: {exc}", file=sys.stderr) + print( + f"[optimize] warning: could not update refs in {fpath}: {exc}", + file=sys.stderr, + ) + + +def _fix_css_format_hints(root: Path, new_name: str, fmt_hint: re.Pattern) -> None: + """Rewrites truetype/opentype format() hints to woff2 in CSS referencing new_name.""" + for css_path in root.rglob("*.css"): + try: + css = css_path.read_text(encoding="utf-8", errors="ignore") + if new_name not in css: + continue + fixed = fmt_hint.sub("format('woff2')", css) + if fixed != css: + css_path.write_text(fixed, encoding="utf-8") + except OSError as exc: + print( + f"[optimize] warning: could not update format hint in {css_path}: {exc}", + file=sys.stderr, + ) def _convert_fonts(root: Path) -> int: @@ -94,7 +115,10 @@ def _convert_fonts(root: Path) -> int: try: from fontTools.ttLib import TTFont except ImportError: - print("[optimize] warning: fonttools not installed — font conversion skipped", file=sys.stderr) + print( + "[optimize] warning: fonttools not installed — font conversion skipped", + file=sys.stderr, + ) return 0 fmt_hint = re.compile(r"""format\(\s*['"](?:truetype|opentype)['"]\s*\)""", re.IGNORECASE) @@ -116,16 +140,7 @@ def _convert_fonts(root: Path) -> int: _update_refs(root, old_name, new_name, (".css", ".html")) # Fix format() hint only in CSS that already references the new woff2 - for css_path in root.rglob("*.css"): - try: - css = css_path.read_text(encoding="utf-8", errors="ignore") - if new_name not in css: - continue - fixed = fmt_hint.sub("format('woff2')", css) - if fixed != css: - css_path.write_text(fixed, encoding="utf-8") - except OSError as exc: - print(f"[optimize] warning: could not update format hint in {css_path}: {exc}", file=sys.stderr) + _fix_css_format_hints(root, new_name, fmt_hint) converted += 1 print(f"[optimize] font: {old_name} → {new_name}") @@ -135,12 +150,30 @@ def _convert_fonts(root: Path) -> int: return converted +def _save_as_modern_format(img, img_path: Path) -> tuple[Path, str] | None: + """Saves img as AVIF, falling back to WebP; returns (new path, format label) or None.""" + for suffix, fmt, save_kw in [ + (".avif", "AVIF", {"quality": 75}), + (".webp", "WEBP", {"quality": 80, "method": 6}), + ]: + candidate = img_path.with_suffix(suffix) + try: + img.save(str(candidate), fmt, **save_kw) + return candidate, fmt + except Exception: + candidate.unlink(missing_ok=True) + return None + + def _convert_images(root: Path) -> int: """Converts raster images to AVIF (or WebP as fallback) and updates references.""" try: from PIL import Image except ImportError: - print("[optimize] warning: Pillow not installed — image conversion skipped", file=sys.stderr) + print( + "[optimize] warning: Pillow not installed — image conversion skipped", + file=sys.stderr, + ) return 0 raster_globs = ("*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.tiff", "*.tif") @@ -162,27 +195,13 @@ def _convert_images(root: Path) -> int: elif img.mode not in ("RGB", "RGBA", "L", "LA"): img = img.convert("RGB") - new_path = None - fmt_label = None - - # Try AVIF; fall back to WebP if unsupported - for suffix, fmt, save_kw in [ - (".avif", "AVIF", {"quality": 75}), - (".webp", "WEBP", {"quality": 80, "method": 6}), - ]: - candidate = img_path.with_suffix(suffix) - try: - img.save(str(candidate), fmt, **save_kw) - new_path = candidate - fmt_label = fmt - break - except Exception: - candidate.unlink(missing_ok=True) - - if new_path is None: + saved = _save_as_modern_format(img, img_path) + + if saved is None: print(f"[optimize] warning: could not convert {old_name}", file=sys.stderr) continue + new_path, fmt_label = saved img_path.unlink() new_name = new_path.name _update_refs(root, old_name, new_name, ref_exts) @@ -203,6 +222,19 @@ def _resolve_asset(ref: str, html_dir: Path, root: Path) -> Path: return (html_dir / clean).resolve() +def _find_local_assets(tags, attr: str, html_dir: Path, root: Path) -> list: + """Collects (tag, absolute path) pairs for tags whose attr references an existing local file.""" + local = [] + for tag in tags: + ref = tag.get(attr, "") + if not ref or ref.startswith(("http://", "https://", "//", "data:")): + continue + abs_path = _resolve_asset(ref, html_dir, root) + if abs_path.exists() and abs_path.is_file(): + local.append((tag, abs_path)) + return local + + def _bundle_css(html_path: Path, soup: BeautifulSoup, root: Path) -> int: """ Bundles local CSS files into a single minified bundle and updates the HTML. @@ -210,15 +242,7 @@ def _bundle_css(html_path: Path, soup: BeautifulSoup, root: Path) -> int: """ html_dir = html_path.parent link_tags = soup.find_all("link", rel="stylesheet") - - local = [] - for tag in link_tags: - href = tag.get("href", "") - if not href or href.startswith(("http://", "https://", "//", "data:")): - continue - abs_path = _resolve_asset(href, html_dir, root) - if abs_path.exists() and abs_path.is_file(): - local.append((tag, abs_path)) + local = _find_local_assets(link_tags, "href", html_dir, root) if not local: return 0 @@ -276,17 +300,12 @@ def _bundle_js(html_path: Path, soup: BeautifulSoup, root: Path) -> int: html_dir = html_path.parent script_tags = soup.find_all("script", src=True) - local = [] - for tag in script_tags: - # ES modules use import/export and cannot be naively concatenated - if tag.get("type") in ("module", "text/javascript;module"): - continue - src = tag.get("src", "") - if not src or src.startswith(("http://", "https://", "//", "data:")): - continue - abs_path = _resolve_asset(src, html_dir, root) - if abs_path.exists() and abs_path.is_file(): - local.append((tag, abs_path)) + # ES modules use import/export and cannot be naively concatenated + concatenable = [ + tag for tag in script_tags + if tag.get("type") not in ("module", "text/javascript;module") + ] + local = _find_local_assets(concatenable, "src", html_dir, root) if not local: return 0 @@ -390,6 +409,7 @@ def optimize_directory( # pylint: disable=too-many-arguments,too-many-positiona def main(): + """CLI entrypoint: parses --no-* flags and runs optimize_directory().""" parser = argparse.ArgumentParser(description="Optimize static site assets") parser.add_argument("output_dir") parser.add_argument("--no-bundle-css", dest="bundle_css", action="store_false") diff --git a/worker/postprocess.py b/worker/postprocess.py index 843589f..a971f06 100644 --- a/worker/postprocess.py +++ b/worker/postprocess.py @@ -1,11 +1,4 @@ #!/usr/bin/env python3 -from __future__ import annotations - -import pathlib -import re -import sys -from urllib.parse import urljoin - """ postprocess.py — cleans up HTML after wget. @@ -15,6 +8,12 @@ - Removes residual absolute references to the origin host. - Strips CMS-specific tags (WordPress emoji, REST links, oEmbed, generator meta). """ +from __future__ import annotations + +import pathlib +import re +import sys +from urllib.parse import urljoin # @ in filename came from wget replacing ? in query strings (--restrict-file-names=windows). # Two forms: @key=value (e.g. style.css@ver=6.4.1) @@ -86,6 +85,7 @@ def apply_renames_to_text_files(output_dir: pathlib.Path, renames: list[tuple[st def build_patterns(origin_host: str, extra_hosts: list[str] | None = None): + """Builds the (pattern, replacement) pairs used to strip hosts and CMS artifacts.""" host_patterns = [ # any http/https:// → relative URL (origin + extra CDNs). # Matches both the plain form (href="https://host/...") and the JSON-escaped form @@ -133,9 +133,11 @@ def absolutize_html_urls(text: str, html_path: pathlib.Path, output_dir: pathlib base_url = "/" + "/".join(parts) + "/" if parts else "/" def is_absolute(url: str) -> bool: + """True for URLs that must not be rewritten (external or already absolute).""" return url.startswith(("http", "https", "//", "#", "data:", "javascript:", "/")) def resolve(url: str) -> str: + """Resolves a relative URL against the page's base path.""" return url if is_absolute(url) else urljoin(base_url, url) def fix_chunk(chunk: str) -> str: @@ -150,6 +152,7 @@ def fix_chunk(chunk: str) -> str: # srcset="url1 w1, url2 w2, ..." def fix_srcset(m: re.Match) -> str: + """Rewrites each candidate URL inside a srcset attribute to an absolute path.""" q = m.group(1) entries = [] for entry in m.group(2).split(","): @@ -177,32 +180,12 @@ def fix_srcset(m: re.Match) -> str: return "".join(fix_chunk(part) if i % 2 == 0 else part for i, part in enumerate(segments)) -def main(): - if len(sys.argv) < 3: - print("usage: postprocess.py [ ...]", file=sys.stderr) - sys.exit(2) - - output_dir = pathlib.Path(sys.argv[1]) - origin_host = sys.argv[2] - extra_hosts = sys.argv[3:] # extra CDN domains whose absolute URLs will also be stripped - - if not output_dir.is_dir(): - print(f"directory does not exist: {output_dir}", file=sys.stderr) - sys.exit(2) - - if extra_hosts: - print(f"[postprocess] stripping URLs from {len(extra_hosts)} extra CDN(s): {', '.join(extra_hosts)}") - - # Step 1: normalize filenames with @ (wget's replacement for ? in query strings) - renames = normalize_query_string_files(output_dir) - if renames: - apply_renames_to_text_files(output_dir, renames) - print(f"[postprocess] {len(renames)} query-string file(s) renamed") - for old, new in renames: - print(f"[postprocess] {old} → {new}") +def _clean_html_files(output_dir: pathlib.Path, patterns: list) -> int: + """ + Strips absolute URLs and CMS artifacts from HTML files and absolutizes relative links. - # Step 2: strip absolute URLs and CMS artifacts from HTML and CSS files - patterns = build_patterns(origin_host, extra_hosts) + Returns the number of modified files. + """ count = 0 for html in output_dir.rglob("*.html"): @@ -222,9 +205,19 @@ def main(): count += 1 print(f"[postprocess] cleaned: {html}") - # CSS files: strip origin/CDN domain URLs (e.g. url("https://origin/...") in @font-face, - # background-image, etc.). HTML-specific WordPress patterns are harmless on CSS — they - # won't match — so we reuse the same patterns list for simplicity. + return count + + +def _clean_css_files(output_dir: pathlib.Path, patterns: list) -> int: + """ + Strips origin/CDN domain URLs from CSS files (e.g. url("https://origin/...") in + @font-face, background-image, etc.). HTML-specific WordPress patterns are harmless + on CSS — they won't match — so we reuse the same patterns list for simplicity. + + Returns the number of modified files. + """ + count = 0 + for css in output_dir.rglob("*.css"): try: text = css.read_text(encoding="utf-8", errors="ignore") @@ -241,6 +234,40 @@ def main(): count += 1 print(f"[postprocess] cleaned: {css}") + return count + + +def main(): + """CLI entrypoint: normalize @ files, strip URLs/CMS artifacts, absolutize links.""" + if len(sys.argv) < 3: + print("usage: postprocess.py [ ...]", file=sys.stderr) + sys.exit(2) + + output_dir = pathlib.Path(sys.argv[1]) + origin_host = sys.argv[2] + extra_hosts = sys.argv[3:] # extra CDN domains whose absolute URLs will also be stripped + + if not output_dir.is_dir(): + print(f"directory does not exist: {output_dir}", file=sys.stderr) + sys.exit(2) + + if extra_hosts: + hosts = ", ".join(extra_hosts) + print(f"[postprocess] stripping URLs from {len(extra_hosts)} extra CDN(s): {hosts}") + + # Step 1: normalize filenames with @ (wget's replacement for ? in query strings) + renames = normalize_query_string_files(output_dir) + if renames: + apply_renames_to_text_files(output_dir, renames) + print(f"[postprocess] {len(renames)} query-string file(s) renamed") + for old, new in renames: + print(f"[postprocess] {old} → {new}") + + # Step 2: strip absolute URLs and CMS artifacts from HTML and CSS files + patterns = build_patterns(origin_host, extra_hosts) + count = _clean_html_files(output_dir, patterns) + count += _clean_css_files(output_dir, patterns) + print(f"[postprocess] {count} file(s) modified") From b3b6a36f5984a7c421f08729a4a2bc83cab04005 Mon Sep 17 00:00:00 2001 From: driedel Date: Thu, 17 Sep 2026 19:18:54 -0300 Subject: [PATCH 4/5] style: add missing docstrings and fix lint warnings - add docstrings to FastAPI handlers, deploy/worker/optimize entrypoints and nested test helpers - raise HTTPException/RuntimeError with explicit exception chaining - blank line before nested defs (E306), idiomatic emptiness and comparison-order asserts in tests --- api/main.py | 12 ++++++++---- tests/test_integration.py | 7 ++++++- tests/test_jobs.py | 2 ++ tests/test_optimize.py | 4 ++-- worker/deploy.py | 4 ++++ worker/worker.py | 1 + 6 files changed, 23 insertions(+), 7 deletions(-) diff --git a/api/main.py b/api/main.py index 2f6e2fd..60f9021 100644 --- a/api/main.py +++ b/api/main.py @@ -68,7 +68,7 @@ def verify_signature(raw_body: bytes, sig_header: str, ts_header: str) -> None: try: ts = int(ts_header) except ValueError: - raise HTTPException(status_code=401, detail="invalid timestamp") + raise HTTPException(status_code=401, detail="invalid timestamp") from None if abs(time.time() - ts) > MAX_SKEW: raise HTTPException(status_code=401, detail="timestamp out of window") @@ -79,6 +79,7 @@ def verify_signature(raw_body: bytes, sig_header: str, ts_header: str) -> None: @app.get("/health") def health(): + """Health check — reports API liveness and Redis connectivity.""" try: redis_conn.ping() redis_ok = True @@ -89,6 +90,7 @@ def health(): @app.post("/publish") async def publish(req: Request): + """Validates the HMAC-signed webhook payload and enqueues a deploy job.""" raw = await req.body() verify_signature( raw_body=raw, @@ -99,7 +101,7 @@ async def publish(req: Request): try: payload = json.loads(raw) except json.JSONDecodeError: - raise HTTPException(status_code=400, detail="invalid json") + raise HTTPException(status_code=400, detail="invalid json") from None url = payload.get("url") post_id = payload.get("post_id") @@ -144,10 +146,11 @@ async def publish(req: Request): @app.delete("/jobs/{job_id}") def cancel_job(job_id: str): + """Cancels a queued or running job (404 if unknown, 409 if already finished).""" try: job = Job.fetch(job_id, connection=redis_conn) except Exception: - raise HTTPException(status_code=404, detail="job not found") + raise HTTPException(status_code=404, detail="job not found") from None status = job.get_status() if status == "queued": @@ -165,10 +168,11 @@ def cancel_job(job_id: str): @app.get("/jobs/{job_id}") def job_status(job_id: str): + """Returns the status, result, and timeline of a job.""" try: job = Job.fetch(job_id, connection=redis_conn) except Exception: - raise HTTPException(status_code=404, detail="job not found") + raise HTTPException(status_code=404, detail="job not found") from None return { "id": job.id, diff --git a/tests/test_integration.py b/tests/test_integration.py index 7046241..6843b35 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -44,7 +44,9 @@ def test_run_command_timeout(): def test_convert_fonts_skips_without_fonttools(monkeypatch, tmp_path): """When fontTools is not importable, _convert_fonts returns 0.""" original_import = __builtins__["__import__"] + def fake_import(name, *args, **kwargs): + """Simulates fontTools.ttLib being unavailable by raising ImportError.""" if name == "fontTools.ttLib": raise ImportError() return original_import(name, *args, **kwargs) @@ -121,7 +123,9 @@ def test_convert_fonts_skips_existing_woff2(tmp_path): def test_convert_images_skips_without_pillow(monkeypatch, tmp_path): """When Pillow is not importable, _convert_images returns 0.""" original_import = __builtins__["__import__"] + def fake_import(name, *args, **kwargs): + """Simulates PIL.Image being unavailable by raising ImportError.""" if name == "PIL.Image": raise ImportError() return original_import(name, *args, **kwargs) @@ -264,7 +268,8 @@ def test_sync_to_s3_uploads_with_correct_content_type(tmp_path): # Check JS cache (macOS mimetypes may report text/javascript) js_call = [c for c in mock_s3.upload_file.call_args_list if "script.js" in str(c)][0] - assert js_call.kwargs["ExtraArgs"]["ContentType"] in ("application/javascript", "text/javascript") + js_types = ("application/javascript", "text/javascript") + assert js_call.kwargs["ExtraArgs"]["ContentType"] in js_types def test_sync_to_s3_empty_prefix(tmp_path): diff --git a/tests/test_jobs.py b/tests/test_jobs.py index f688f85..a3edff7 100644 --- a/tests/test_jobs.py +++ b/tests/test_jobs.py @@ -50,6 +50,7 @@ def test_download_cdn_assets_finds_url_in_html_and_downloads(tmp_path, monkeypat html.write_text("var font = 'https://cdn.example.com/assets/font.woff2';") def mock_run(cmd, **_kwargs): + """Fake subprocess.run that writes the downloaded file to the -O target.""" out_path = Path(cmd[cmd.index("-O") + 1]) out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_bytes(b"fake-data") @@ -93,6 +94,7 @@ def test_download_cdn_assets_deduplicates_urls(tmp_path, monkeypatch): call_count = [] def mock_run(cmd, **_kwargs): + """Fake subprocess.run that records the call and writes a stub file.""" call_count.append(1) out_path = Path(cmd[cmd.index("-O") + 1]) out_path.parent.mkdir(parents=True, exist_ok=True) diff --git a/tests/test_optimize.py b/tests/test_optimize.py index 12cfc73..2fda18e 100644 --- a/tests/test_optimize.py +++ b/tests/test_optimize.py @@ -92,9 +92,9 @@ def test_bundle_css_single_file_minifies_in_place(tmp_path): assert result == 1 bundles = list(tmp_path.glob("bundle.*.css")) - assert len(bundles) == 0 # single file: no bundle created + assert not bundles # single file: no bundle created content = (tmp_path / "style.css").read_text() - assert "body{color:red}" == content + assert content == "body{color:red}" def test_bundle_css_multiple_files_creates_bundle(tmp_path): diff --git a/worker/deploy.py b/worker/deploy.py index eb2dafa..46ee4a7 100644 --- a/worker/deploy.py +++ b/worker/deploy.py @@ -40,6 +40,7 @@ def _s3_client(): def cache_control_for(path: pathlib.Path) -> str: + """Returns the Cache-Control header for a path based on its extension (HTML vs. assets).""" ext = path.suffix.lower() if ext in (".html", ".htm"): return "public, max-age=60, s-maxage=300" @@ -53,6 +54,7 @@ def cache_control_for(path: pathlib.Path) -> str: def content_type_for(path: pathlib.Path) -> str: + """Returns the Content-Type for a path, using the EXTRA_TYPES table before mimetypes.""" ext = path.suffix.lower() if ext in EXTRA_TYPES: return EXTRA_TYPES[ext] @@ -61,6 +63,7 @@ def content_type_for(path: pathlib.Path) -> str: def sync_to_s3(local_dir: pathlib.Path, bucket: str, prefix: str) -> int: + """Uploads every file under local_dir to s3://{bucket}/{prefix}/ with correct headers.""" s3 = _s3_client() count = 0 @@ -86,6 +89,7 @@ def sync_to_s3(local_dir: pathlib.Path, bucket: str, prefix: str) -> int: def invalidate_cloudfront(distribution_id: str, paths: list[str]) -> str | None: + """Creates a CloudFront invalidation for the given paths; None if no distribution is set.""" if not distribution_id: print("[deploy] CLOUDFRONT_DISTRIBUTION_ID not set — skipping invalidation") return None diff --git a/worker/worker.py b/worker/worker.py index 1bafbe6..4e822a7 100644 --- a/worker/worker.py +++ b/worker/worker.py @@ -7,6 +7,7 @@ def main(): + """Connects to Redis and starts the RQ worker on the 'deploys' queue.""" conn = Redis.from_url(os.environ["REDIS_URL"]) queues = [Queue("deploys", connection=conn)] worker = Worker(queues, connection=conn) From f79408332ea1ae4538b361ec83cb2cb01144f621 Mon Sep 17 00:00:00 2001 From: driedel Date: Thu, 17 Sep 2026 19:20:17 -0300 Subject: [PATCH 5/5] docs(agents): refresh CI docs for CodeQL and pylint --- AGENTS.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6ddc8ad..7d1516f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ A client sends a signed `POST /publish` request with a URL and a `post_id`. The - **Object storage (dev)**: MinIO (S3-compatible) - **Static preview (dev)**: nginx with an `envsubst`-processed template - **Container runtime**: Docker / Docker Compose v2 -- **CI / CD**: GitHub Actions (pytest, Codacy security scan, optional EC2 deploy) +- **CI / CD**: GitHub Actions (pytest + pylint, CodeQL security scan, optional EC2 deploy) - **Target Python version**: 3.12 (the Docker images use `python:3.12-slim`) ## Repository layout @@ -84,13 +84,14 @@ A client sends a signed `POST /publish` request with a URL and a `post_id`. The ├── nginx/ │ └── default.conf.template # Local preview nginx config ├── .github/workflows/ -│ ├── tests.yml # pytest on push / PR -│ ├── codacy.yml # Codacy security scan +│ ├── tests.yml # pytest + pylint on push / PR +│ ├── codeql.yml # CodeQL security scan │ └── deploy.yml # Manual EC2 deploy workflow ├── docker-compose.yml # Dev stack with Redis + API + Worker + MinIO + nginx preview ├── docker-compose.prod.yml # Production stack with Redis + API + Worker only ├── docker-compose.wordpress.yml # Example for adding the service to a WordPress project ├── .env.example # Environment variable template +├── .pylintrc # Pylint config (used by the lint step in tests.yml) ├── IAM_POLICY.json # Minimum AWS IAM policy for production └── README.md # Human-facing documentation ``` @@ -308,8 +309,8 @@ The workflow runs tests, rsyncs the repository to `/opt/make-it-static/` on the | Workflow | Trigger | What | |----------|---------|------| -| `tests.yml` | push/PR to `main` | pytest + coverage | -| `codacy.yml` | push/PR to `main` + weekly cron | Codacy security scan | +| `tests.yml` | push/PR to `main` | pytest + coverage, pylint (blocking, 10.00/10 required) | +| `codeql.yml` | push/PR to `main` + weekly cron | CodeQL security scan (SARIF → GitHub code scanning) | | `dockerhub.yml` | manual dispatch + tags `v*.*.*` | Build and push API + Worker images to Docker Hub | | `deploy.yml` | manual dispatch | Run tests, rsync to EC2, restart via `docker-compose.prod.yml` |