Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 0 additions & 21 deletions .codacy.yml

This file was deleted.

61 changes: 0 additions & 61 deletions .github/workflows/codacy.yml

This file was deleted.

32 changes: 32 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -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"
5 changes: 5 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
94 changes: 23 additions & 71 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -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
11 changes: 6 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
```
Expand Down Expand Up @@ -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` |

Expand Down
12 changes: 8 additions & 4 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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")
Expand Down Expand Up @@ -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":
Expand All @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading