# Security Review — charity-analytics

**Date:** 2026-07-09
**Scope:** Static review of the Laravel/Livewire/Filament application and the Python ETL loaders at the repo root. No code was executed, no database was touched, no exploits were written. Every finding below was confirmed by reading the cited file and line in this session.

---

## Summary

| Severity | Count |
|---|---|
| Critical | 0 |
| High | 2 |
| Medium | 5 |
| Low | 8 |
| Informational | 1 |

**No Critical findings.** The application's core defensive posture is genuinely good: there is no SQL injection anywhere (every raw-SQL site is parameterized or built from allowlisted values), CSRF protection is intact, there is no command injection, imported charity text is escaped at every rendering sink, and the admin panel enforces app-based 2FA with no self-registration route. The serious problems are concentrated in two places: the **network trust boundary of the Python loaders**, and a handful of **admin-side input validation gaps** that turn an admin session into a stored-XSS vector.

### Fix these first

1. **[H1] Re-enable TLS certificate verification in the Python loaders.** All four download paths disable it (`CERT_NONE`, `check_hostname=False`, `curl --insecure`). Any on-path attacker can replace an entire national regulator dataset, including choosing which URLs get downloaded next. This is the single highest-leverage fix — it also demotes H2, M4, and L3 from remotely-triggerable to admin-only.
2. **[H2] Sanitize the URL-derived directory name in `bulk_load.py` before extracting into it or `rmtree`-ing it.** A URL ending in `/..` resolves the extraction directory to the system temp root, which is then passed to `shutil.rmtree(..., ignore_errors=True)`.
3. **[M1] Add real server-side validation to the admin colour picker.** `ColorPicker->hex()` sets a display format, not a validation rule — the value is then emitted raw inside a `<style>` block on *every public page*.

---

## Findings

### H1 — TLS certificate verification disabled on every network fetch
**Severity: High** — an on-path attacker fully controls the contents of a 2.88M-row production table, and controls which URLs are fetched next.

**Where:**
- [bulk_load.py:100-101](bulk_load.py#L100-L101) — `ctx.check_hostname = False` / `ctx.verify_mode = ssl.CERT_NONE`, used by the chunked downloader and the urllib one-shot fallback.
- [bulk_load.py:201](bulk_load.py#L201) — the curl fast path passes `--insecure`, alongside `--location` (so it follows redirects to arbitrary hosts, still unverified).
- [load_ccew.py:51](load_ccew.py#L51) — `_SSL_CTX` with `CERT_NONE`, used both to scrape the Charity Commission download page and to fetch the ZIPs.
- [load_cra.py:76](load_cra.py#L76) and [load_cra.py:142](load_cra.py#L142) — the CKAN API call and the dataset download.

**The problem.** Certificate and hostname verification are switched off for every outbound HTTPS request the ETL makes. The loaders therefore have no way to tell the real regulator apart from anyone who can position themselves on the network path — a hostile Wi-Fi network during a manual run, a compromised resolver, or another tenant on the shared cPanel host.

**How it could be exploited.** An attacker who can intercept traffic responds to the download request in place of the regulator. Three consequences follow. First, they choose the contents of the `charities` table: names, missions, and the free text that feeds the 4R keyword scoring. Second, `load_cra.py:fetch_package` asks the CKAN API *which URLs to download*, so a forged API response lets the attacker redirect the loader to fetch anything it likes. Third, the attacker-supplied archive is what feeds the extraction pipeline, which converts the resource-exhaustion issues below (M4, L3) from "an admin has to do something odd" into "a network attacker can do it."

**Remediation.** Delete every `check_hostname = False`, `verify_mode = ssl.CERT_NONE`, and the `--insecure` flag. Use `ssl.create_default_context()` unmodified. If a specific regulator genuinely ships a broken chain, pin that one host's CA bundle with `ctx.load_verify_locations()` rather than disabling verification process-wide. Where the regulator publishes a checksum for the archive, verify it after download.

---

### H2 — URL basename used unsanitized as a filesystem path, then passed to `rmtree`
**Severity: High** — a single-character quirk in an import URL causes recursive deletion of the system temp directory on the host running the queue worker.

**Where:**
- [bulk_load.py:338](bulk_load.py#L338) — `name = url.split("/")[-1].split("?")[0].replace(".zip", "") or url`
- [bulk_load.py:425-426](bulk_load.py#L425-L426) — `zip_path = base_tmp / f"{name}.zip"` and `extract_dir = base_tmp / name`
- [bulk_load.py:487](bulk_load.py#L487) — `shutil.rmtree(extract_dir, ignore_errors=True)`
- Same shape in the direct-file branch at [bulk_load.py:391](bulk_load.py#L391), and in [load_cra.py:531](load_cra.py#L531) (`fname = url.rsplit("/", 1)[-1]`), where the URL comes from the MITM-able CKAN response described in H1.

**The problem.** `name` is derived from the last path segment of the import URL with no validation. It is then joined onto the temp base directory to form both the download target and the extraction directory. Because `pathlib` join semantics resolve `..` relative to the base, a name of `..` makes `extract_dir` the *parent* of the intended staging directory — the shared system temp root.

**How it could be exploited.** An admin enters (or is tricked, via CSRF or XSS against their session, into entering) an import URL whose path ends in a segment that resolves to `..`. Filament's `->url()` rule at [DataImport.php:143-148](app/Filament/Pages/DataImport.php#L143-L148) checks URL *format*, not path shape, so this passes validation. The archive is extracted into the shared temp directory rather than an isolated subdirectory, and then at the end of the job `shutil.rmtree(extract_dir, ignore_errors=True)` recursively deletes everything under it that the process has permission to remove. On a shared host running the queue worker, that includes in-flight temp files belonging to the same OS user. `ignore_errors=True` means the destruction is silent. Even without the `..` case, an attacker-chosen `name` can collide with and overwrite other files staged in the same directory.

Note this is admin-gated, not anonymous — which is why it is High and not Critical.

**Remediation.** Validate the derived name before it is ever used as a path component: reject anything not matching `^[A-Za-z0-9._-]+$`, and explicitly reject the empty string, `.`, and `..`. Then, before extracting or deleting, assert containment: `extract_dir.resolve().is_relative_to(base_tmp.resolve())`. Apply the same treatment to `load_cra.py:531`.

---

### M1 — Admin colour values rendered unescaped into a `<style>` block on every public page, with no server-side validation
**Severity: Medium** — a stored XSS sink on every public page; requires an admin session (or any future write path to `site_colors`) to reach.

**Where:**
- [resources/views/layouts/app.blade.php:12](resources/views/layouts/app.blade.php#L12) — `<style>{!! app(\App\Services\SiteColors::class)->toCssCustomProperties() !!}</style>`
- [app/Services/SiteColors.php:97-112](app/Services/SiteColors.php#L97-L112) — `$lines[] = "  --{$name}: {$hex};";` emits the stored value raw. Only the derived `-rgb` variant is regex-checked, by `hexToRgbTriple()`.
- [app/Filament/Pages/EditColors.php:119-125](app/Filament/Pages/EditColors.php#L119-L125) — `ColorPicker::make(...)->hex()->required()`

**The problem.** The admin colour editor relies on `->hex()` for validation. It does not validate. Confirmed in `vendor/filament/forms/src/Components/ColorPicker.php:30-35`: `hex()` calls `$this->format('hex')` and returns — it sets the picker's *display format*. The actual validation rule lives in a different method (`CanBeValidated::hexColor()`, which applies the `hex_color` rule at `vendor/filament/forms/src/Components/Concerns/CanBeValidated.php:238`) and is never called here. So the value that reaches the database is whatever the Livewire request body contained, and `toCssCustomProperties()` interpolates it directly into a `<style>` element that is rendered on every page of the public site.

**How it could be exploited.** An attacker who can submit one Livewire request as an authenticated admin — via a crafted request, or via any future code path that writes `site_colors` without going through the form — stores a value containing a CSS-block terminator followed by markup. Because the output is unescaped and inside `<style>`, that markup escapes the style element and lands in the document of every public visitor. The cached-forever `site_colors` value (`SiteColors::CACHE_KEY`) makes the payload persistent. The value never has to look like a colour.

**Remediation.** Two changes, both cheap. Add the real rule to the field: `->rules(['hex_color'])`. And defend at the output boundary, where it matters most: in `toCssCustomProperties()`, skip or normalize any value that does not match `/^#[0-9a-fA-F]{3,8}$/` before emitting it. The class already has this regex logic in `hexToRgbTriple()` — it just isn't applied to the `--{$name}` line.

---

### M2 — Weak default admin credentials shipped in `.env.example`, seeded pre-verified
**Severity: Medium** — a copy-paste deploy yields a working admin account with a publicly-known password; 2FA does not save you here.

**Where:**
- [.env.example:7-9](.env.example#L7-L9) — `ADMIN_PASSWORD=test124`, `ADMIN_EMAIL=admin@example.com`
- [.env.example:4](.env.example#L4) — `APP_DEBUG=true`
- [database/seeders/AdminUserSeeder.php:29-44](database/seeders/AdminUserSeeder.php#L29-L44) — `User::firstOrCreate([...], [..., 'email_verified_at' => now()])`
- [DEPLOY_CPANEL.md:124](DEPLOY_CPANEL.md#L124) — the deploy runbook begins with `cp .env.example .env`

**The problem.** The committed environment template contains a concrete, working admin password rather than a blank or an obvious placeholder. The seeder is deliberately written to be safe when `ADMIN_PASSWORD` is unset (it no-ops with a warning) — but the template sets it. An operator who follows the runbook's `cp .env.example .env` and misses the later instruction to change it (`DEPLOY_CPANEL.md:146` does say `set-a-strong-one`) ends up with `admin@example.com` / `test124`, pre-verified, on a public host.

**How it could be exploited.** The password is in a public repository. An attacker browses to `/admin` and logs in. The panel's mandatory 2FA (`AdminPanelProvider.php:34-37`) does not help: a freshly seeded account has no TOTP secret enrolled, so the first person to log in is the person who enrols it. The attacker gets 2FA; the legitimate operator gets locked out.

**Remediation.** Blank the value in `.env.example` (`ADMIN_PASSWORD=`) and set `APP_DEBUG=false` there too, so the insecure state is the one that requires deliberate action. Harden the seeder to refuse known-weak values, or have it generate a random password and print it once. Rotate the credential on any host where this template was used verbatim.

---

### M3 — MySQL password passed on the command line
**Severity: Medium** — the DB password is readable from the process table for the multi-hour lifetime of an import, on a documented shared-hosting deploy target.

**Where:**
- [app/Jobs/ProcessImportBatch.php:57](app/Jobs/ProcessImportBatch.php#L57) — `'--password', config('irs.db_password', ''),`
- `bulk_load.py:326, 349, 407, 478` — re-passed as `"--password", args.password` to each loader subprocess.

**The problem.** The password appears in the argument vector of two long-lived processes simultaneously (the `bulk_load.py` parent and its loader child), where any local user who can read `/proc/<pid>/cmdline` or run `ps` can see it. The job's own comment notes these runs last from ten minutes to hours, and `$timeout = 0`. The documented deploy target is shared cPanel hosting, where co-tenants are exactly the threat model that makes this matter; unless the kernel is configured with `hidepid`, the process table is world-readable.

**How it could be exploited.** A co-tenant on the shared host polls `ps` during an import window and reads the credential. Note the `.env` in the working tree has `DB_USERNAME=root` with the password line commented out, so on a host configured that way the exposure is of a root credential.

**Remediation.** Pass the password through the child process's environment instead of argv. Symfony's `Process` accepts an `env` array; `bulk_load.py` can read it with `os.environ` and forward it the same way to its own children (`subprocess.run(..., env=...)`). `MYSQL_PWD` or a custom variable both work. A mode-0600 MySQL option file is the other standard answer. Keep `--password` only as a documented fallback for interactive manual runs.

---

### M4 — No size limits on downloads or archive extraction
**Severity: Medium** — resource exhaustion of the queue-worker host; remotely triggerable while H1 stands.

**Where:**
- `bulk_load.py:253-267` — `_extract_zip` (shells to `unzip -o`, or `shutil.unpack_archive`) with no cap on entry count or uncompressed size.
- [load_ccew.py:157](load_ccew.py#L157) — `zf.extractall(tmp_dir)`, same.
- [load_ccew.py:47](load_ccew.py#L47) — `csv.field_size_limit(sys.maxsize)` removes the 128 KB field cap entirely.
- `load_to_mysql.py:1461-1471` — every parsed IRS record accumulates in one in-memory `records` list before any insert.

**The problem.** Nothing bounds how much data an archive is allowed to expand into. A ZIP whose entries decompress to a very large size will fill the disk or exhaust memory; a single CSV field is permitted to grow to `sys.maxsize`; and the IRS path holds every parsed record in memory at once, so memory scales with archive contents rather than with batch size.

**How it could be exploited.** Normally this requires an admin to point the importer at a hostile archive. But because certificate verification is off (H1), an on-path attacker can substitute a compressed bomb for the legitimate regulator ZIP during a routine, legitimate import. The queue worker OOMs or the disk fills.

**Remediation.** Check `Content-Length` and enforce a maximum download size. Before extracting, sum `ZipInfo.file_size` across members and enforce both an absolute cap and a compression-ratio cap. Set `csv.field_size_limit` to a defensible bound (10 MB comfortably covers the CCEW description blobs the comment cites) rather than `sys.maxsize`. Stream IRS records into batched inserts instead of building one list.

---

### M5 — Image uploads accept SVG onto the public disk
**Severity: Medium** — stored XSS in the site's own origin, reachable by direct navigation to the uploaded file; requires an admin session to plant.

**Where:**
- [app/Filament/Resources/Charities/CharityResource.php:113-118](app/Filament/Resources/Charities/CharityResource.php#L113-L118) — `FileUpload::make('logo_path')->image()->disk('public')->directory('charity-logos')`
- [app/Filament/RichContent/CustomBlocks/ColumnsBlock.php:56-63](app/Filament/RichContent/CustomBlocks/ColumnsBlock.php#L56-L63) — same pattern into `charity-descriptions`
- [app/Models/Charity.php:26-29](app/Models/Charity.php#L26-L29) — rich-editor attachments, also `->fileAttachmentsDisk('public')`

**The problem.** Confirmed in `vendor/filament/forms/src/Components/FileUpload.php:127-131`: `->image()` expands to `acceptedFileTypes(['image/*'])`. The `image/*` wildcard includes `image/svg+xml`. SVG is not an inert raster format — it is an XML document that may contain script, and browsers execute that script when the file is navigated to directly. No `maxSize()` is set on either field either, so the effective limit is Livewire's default.

**How it could be exploited.** An admin (or anyone with a foothold in an admin session) uploads an SVG as a charity logo. Rendering it inside an `<img>` tag, as `⚡charitydetail.blade.php:184` does, is safe — browsers do not run script in `<img>`-sourced SVG. The risk is the file's own `/storage/...` URL, which is publicly served from the application's origin. Anyone induced to open that URL directly executes the attacker's script with the site's origin, and with whatever session cookies the victim holds for it.

**Remediation.** Replace `->image()` with an explicit allowlist: `->acceptedFileTypes(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])`. Add an explicit `->maxSize(...)`. If SVG logos are a product requirement, serve the uploads directory with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, or from a separate origin that shares no cookies with the app.

---

### L1 — Navigation URLs accept `javascript:` schemes
**Severity: Low** — admin-authored stored XSS, one click from a visitor; no validation stands between the form and the `href`.

**Where:**
- [app/Filament/Resources/NavigationItemResource.php:77-83](app/Filament/Resources/NavigationItemResource.php#L77-L83) — `TextInput::make('url')->maxLength(500)`, with no `->url()` rule and no scheme check
- [app/Models/NavigationItem.php:46-53](app/Models/NavigationItem.php#L46-L53) — `getHrefAttribute()` returns `$this->url` verbatim
- [resources/views/components/navigation.blade.php:27](resources/views/components/navigation.blade.php#L27) and [:43](resources/views/components/navigation.blade.php#L43) — `href="{{ $item->href }}"`

**The problem.** The field accepts any string up to 500 characters, because the helper text invites both internal paths and external URLs and no rule was attached. Blade's `{{ }}` escaping is doing its job here — it prevents attribute breakout — but it does nothing about the URL *scheme*. A stored `javascript:`-scheme URL is a perfectly well-formed attribute value that executes when a visitor clicks the nav item.

**Remediation.** Validate the scheme: `->rules(['url:http,https'])` for absolute URLs, or a custom rule accepting only `https?://…` and site-relative paths beginning with `/`. A Content-Security-Policy (see L6) would blunt this as well.

---

### L2 — XML parsed with `xml.etree.ElementTree`
**Severity: Low** — classic XXE is not reachable; residual entity-expansion DoS depends on the host's libexpat version.

**Where:** [load_to_mysql.py:22](load_to_mysql.py#L22) (`import xml.etree.ElementTree as ET`) and [load_to_mysql.py:1076](load_to_mysql.py#L1076) (`tree = ET.parse(filepath)`, wrapped in `except ET.ParseError: return None`).

**What is *not* a problem.** ElementTree's expat backend does not resolve external entities or fetch external DTDs. An undefined entity raises `ParseError`, which is caught and the file skipped. File disclosure and SSRF via XXE are therefore off the table here — worth stating plainly, because "ElementTree parsing untrusted XML" is a pattern that usually is a problem.

**What remains.** Internal entity expansion ("billion laughs") is a memory and CPU denial of service on interpreters that bundle libexpat older than 2.4. `IRS_PYTHON_BIN` is operator-configurable (`config/irs.php`), so the interpreter is not pinned; older Python 3.8/3.9 installs are plausible on cPanel. The input is a ZIP that, per H1, can be substituted in transit.

**Remediation.** Parse with `defusedxml.ElementTree.parse` — a drop-in replacement. Alternatively, document and enforce Python ≥3.10 with libexpat ≥2.4 in the deploy runbook.

---

### L3 — `Charity`, `ImportBatch`, and `CharityGroup` are fully unguarded
**Severity: Low** — not exploitable today; there is no request path that mass-assigns these models.

**Where:** [app/Models/Charity.php:19](app/Models/Charity.php#L19), [app/Models/ImportBatch.php:9](app/Models/ImportBatch.php#L9), [app/Models/CharityGroup.php:12](app/Models/CharityGroup.php#L12) — all `protected $guarded = [];`

**The problem.** Every column is mass-assignable, including `score_*`, `is_featured`, `is_self_entered`, and the identity keys. Today all writes arrive through Filament schemas whose field lists are fixed server-side, or through the ETL, so nothing reaches these models from a request body. The exposure is latent: the day someone writes `->fill($request->all())`, or adds a Filament field without thinking about it, roughly ninety columns become writable at once.

Worth noting the contrast — `NavigationItem`, `ColumnTooltip`, `SiteColor`, and `User` all correctly declare `$fillable`. `User` additionally uses `#[Fillable]` and `#[Hidden]` attributes to keep `password`, `remember_token`, and both two-factor columns out of both mass assignment and serialization.

**Remediation.** Enumerate `$fillable` for the columns an admin form actually edits. At minimum, guard `id`, `country_code`, `registration_number`, `tax_year`, and the `score_*` family.

---

### L4 — Every authenticated user can access the admin panel; no policies or gates exist
**Severity: Low** — currently vacuous, because "user" and "admin" are the same set.

**Where:** [app/Models/User.php:34-37](app/Models/User.php#L34-L37) — `public function canAccessPanel(Panel $panel): bool { return true; }`. There is no `app/Policies/` directory and no `Gate::define` anywhere in `app/`.

**The problem.** Panel access is unconditional. This is safe right now only because of two facts that hold today and are not enforced anywhere: the panel exposes `->login()` but no registration route ([AdminPanelProvider.php:31](app/Providers/Filament/AdminPanelProvider.php#L31)), and users are created only by `AdminUserSeeder`. The moment a second, lower-privilege user exists — a read-only reviewer, say — they inherit full control of imports, deletes, colours, and navigation.

**Remediation.** Gate on an explicit `is_admin` column or an email allowlist now, while the assumption still holds and the change is a two-line diff.

---

### L5 — `trustProxies(at: '*')`
**Severity: Low** — permits header spoofing that degrades rate limiting and log forensics.

**Where:** [bootstrap/app.php:14](bootstrap/app.php#L14) — `$middleware->trustProxies(at: '*');`

**The problem.** Trusting all upstream proxies means Laravel believes `X-Forwarded-For` and `X-Forwarded-Proto` from any client that can reach the application directly. A spoofed `X-Forwarded-For` defeats IP-keyed throttling (including Filament's login throttle) and poisons access logs; a spoofed `X-Forwarded-Proto: https` can convince the app a plaintext request was secure. This is an understandable default behind Docker's nginx or a cPanel reverse proxy — but `*` is broader than either needs.

**Remediation.** Pin to the actual proxy addresses or CIDRs. Where the upstream address genuinely is not knowable (some shared hosts), document that and rely on the proxy to strip client-supplied forwarding headers.

---

### L6 — Minimal security headers
**Severity: Low** — no single header here is a vulnerability; collectively their absence removes the defense-in-depth that would blunt M1, M5, and L1.

**Where:** [app/Http/Middleware/SetSecurityHeaders.php:15](app/Http/Middleware/SetSecurityHeaders.php#L15) — the middleware sets `Referrer-Policy: strict-origin` and nothing else.

**The problem.** There is no `X-Frame-Options` or CSP `frame-ancestors`, so both the public site and the admin panel can be framed (clickjacking). There is no `X-Content-Type-Options: nosniff`, which compounds M5 by allowing content-type sniffing on uploaded files. There is no CSP at all, so any of the three XSS sinks above executes unimpeded. There is no HSTS.

**Remediation.** In the existing middleware, add `X-Frame-Options: SAMEORIGIN`, `X-Content-Type-Options: nosniff`, and — once HTTPS is guaranteed in production — `Strict-Transport-Security`. A Content-Security-Policy is the highest-value addition; even a `script-src 'self'` policy would neutralize M1 and L1 outright.

---

### L7 — Import URLs are fetched without host restriction (SSRF)
**Severity: Low** — admin-gated, and the response is parsed rather than returned to the requester.

**Where:** [app/Filament/Pages/DataImport.php:143-148](app/Filament/Pages/DataImport.php#L143-L148) — `TextInput::make('url')->url()`, whose value flows to [ProcessImportBatch.php:67-69](app/Jobs/ProcessImportBatch.php#L67-L69) and then to `bulk_load.py`.

**The problem.** The only constraint on an import URL is Laravel's generic `url` format rule. The loader will therefore fetch `http://127.0.0.1:…`, link-local metadata addresses, or intranet hosts, from inside the deployment's network position. Because `curl` is invoked with `--location`, a permitted external URL can also redirect into that same internal space. There is no command injection risk here — `ProcessImportBatch.php:75` uses Symfony `Process` with an argument array, so no shell interprets the URL — and the fetched body is parsed as a ZIP or CSV rather than echoed back, which bounds what an attacker learns.

**Remediation.** Tighten the rule to `url:https`, and — since the set of legitimate sources is small, fixed, and already known to the code — validate the host against an allowlist of the five regulator domains.

---

### L8 — Miscellaneous hardening
**Severity: Low**

- **Database name interpolated into DDL.** [load_to_mysql.py:1432](load_to_mysql.py#L1432) — `f"CREATE DATABASE IF NOT EXISTS \`{args.database}\`"`. Identifiers cannot be bound as parameters, so this is not straightforwardly avoidable, but a backtick in the value breaks the quoting. The value comes from `config('irs.db_name')` — operator config, never request data — so this is hardening, not an exploitable injection. Validate with `re.fullmatch(r"[A-Za-z0-9_]+", args.database)` and abort otherwise.
- **Docker default root password.** [docker-compose.yml:50](docker-compose.yml#L50) — `MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:-rootsecret}`. Mitigated: the mysql service publishes no host ports, and nginx binds `127.0.0.1:8080` only ([docker-compose.yml:30](docker-compose.yml#L30)). Remove the literal fallback so a missing variable fails loudly.
- **No Python dependency manifest.** There is no `requirements.txt`, `pyproject.toml`, or `Pipfile` anywhere in the repo. `pymysql` (`loader_common.py:18-21`) and `mysql.connector` (`load_to_mysql.py:25`) are imported bare; everything else is stdlib. Whatever `pip install pymysql` resolves on the host is trusted, and there is no way to reproduce or audit the runtime — which is precisely what L2 would need in order to answer "which libexpat is this?". Add a pinned `requirements.txt` and reference it from the `load-charity-data` skill and the deploy runbook.
- **No length capping on IRS-path strings.** `load_to_mysql.py` writes `name`, `city`, `ceo_name`, `ceo_title`, and `mission` straight from XML with no truncation, unlike the other loaders which consistently use `to_str(..., max_len)` from `loader_common.py`. Values are parameterized, so this is not injection — but a field longer than its column aborts the entire 500-row `executemany` batch under strict SQL mode, silently dropping 499 good rows because of one malformed filing.
- **No application rate limiting on public routes.** [routes/web.php](routes/web.php) declares no `throttle` middleware. The homepage search runs a `LIKE '%…%'` per debounced keystroke ([⚡homepage.blade.php:38-40](resources/views/pages/⚡homepage.blade.php#L38-L40)), though it is bounded to the featured subset, so the load is modest. Filament's login has built-in throttling (`rateLimit(5)`, verified in `vendor/filament/filament/src/Auth/Pages/Login.php:72`). Consider adding `throttle` to the public routes regardless.

---

### Informational — Self-XSS via localStorage in `score-overrides.js`

[resources/js/score-overrides.js](resources/js/score-overrides.js) stores user-entered custom metric names in `localStorage` and later interpolates them into `innerHTML` template literals — for example `${label}` at line 891, sourced from `getCustomLabel()`. Only `"` is escaped, at line 824. Because this data never crosses a server round-trip and never reaches another user, it is self-XSS and not a vulnerability. Still worth using `textContent` when building these fragments, so the pattern doesn't get copied into a context where the data *is* shared.

---

## What is already solid

These classes were examined specifically and found to be handled correctly. Knowing where the floor is holding is as useful as knowing where it isn't.

**SQL injection — clean, across both halves.** Every raw-SQL site in the Laravel app was opened and checked:
- `CharityResource.php:363-366` — the MySQL FULLTEXT search binds its parameter: `whereRaw('MATCH(name) AGAINST(? IN BOOLEAN MODE)', [$terms])`, with punctuation stripped beforehand.
- `⚡homepage.blade.php:42-47` — the one `orderByRaw` interpolates `$dir`, which is forced to exactly `'asc'` or `'desc'` on the preceding line; the sort column passes through a `match` allowlist, and the `sort()` action separately allowlists its argument at lines 23-24.
- `RescoreCharities.php:73-96` — the bulk `CASE WHEN` update is assembled only from `(int)`-cast ids, `(float)`-cast numbers (`sqlNumOrNull`), and an enum allowlist (`sqlStrEnum`). Nothing string-typed reaches the SQL.
- `ProcessImportBatch.php:220-242`, `RecoverStrandedImports.php:63`, `NavigationItemResource.php:111-113` — fully static SQL.
- `CharityScoreCalculator.php` contains no SQL at all; the public charity lookups use bound Eloquent `where` clauses.

On the Python side, every insert is parameterized: `loader_common.py:49-51` builds `INSERT_SQL` with `%(col)s` placeholders from the hardcoded `SHARED_COLUMNS` constant, executed via `cur.executemany`. CSV headers and sheet names — the obvious source of attacker-controlled identifiers — are used only as Python dict keys, never interpolated into SQL.

**Command injection — none.** `ProcessImportBatch.php:75` uses Symfony `Process` with an argument array; no shell is involved, so an import URL containing shell metacharacters is inert. Across all seven Python scripts there is not one `shell=True`, `os.system`, `eval`, `exec`, `pickle`, or `yaml.load`. Every `subprocess.run` passes an argv list.

**CSRF — intact.** No `validateCsrfTokens` exclusions in `bootstrap/app.php`. `routes/web.php` contains only GET and Livewire routes. The Filament panel's middleware stack explicitly includes `PreventRequestForgery` ([AdminPanelProvider.php:57](app/Providers/Filament/AdminPanelProvider.php#L57)). Session cookies default to `http_only` and `SameSite=lax` (`config/session.php:185,202`).

**XSS on imported data — escaped at every sink.** This is the class that matters most for a site whose content comes from five external regulators, and it is handled carefully. All charity fields render through `{{ }}`. The keyword-highlighting closures — the one place where HTML is deliberately constructed around imported text — escape *before* wrapping: `e($text)` then `e($m[0])` in [resources/views/filament/charities/scores/religious.blade.php:15-23](resources/views/filament/charities/scores/religious.blade.php#L15-L23), the same pattern at [resources/views/partials/scores/religious.blade.php:24-35](resources/views/partials/scores/religious.blade.php#L24-L35). JSON-LD is emitted with `JSON_HEX_TAG | JSON_HEX_AMP` ([⚡charitydetail.blade.php:128](resources/views/pages/⚡charitydetail.blade.php#L128)); chart data goes through `Js::from()` (line 144); `sortIcon()` returns only constant SVG.

**The one raw-HTML sink is sanitized.** `{!! $charity->renderRichContent('description') !!}` ([⚡charitydetail.blade.php:400](resources/views/pages/⚡charitydetail.blade.php#L400)) resolves through Filament's `RichContentRenderer::toHtml()`, which is `Str::sanitizeHtml($this->toUnsafeHtml())` (`vendor/filament/forms/src/Components/RichEditor/RichContentRenderer.php:498-501`) — a macro bound to Symfony's `HtmlSanitizerInterface` (`vendor/filament/support/src/SupportServiceProvider.php:300-302`), which is why `ezyang/htmlpurifier` is a direct dependency. The custom `ColumnsBlock` renders through it too, and its own view escapes all text and clamps `width` with `(int)` plus min/max. Separately: no loader writes the `description` column, so imported data never reaches this sink at all.

**Authorization on the sensitive flows.** The self-entered charity wizard enforces its invariant server-side: `abort_unless((bool) $this->source->is_self_entered, 403)` at [AddTaxYear.php:33](app/Filament/Resources/Charities/Pages/AddTaxYear.php#L33). The destructive delete is gated by `->visible(fn () => (bool) $this->record->is_self_entered)` ([EditCharity.php:119-127](app/Filament/Resources/Charities/Pages/EditCharity.php#L119-L127)), and this *is* enforced server-side, not merely hidden in the UI — Filament's `InteractsWithActions::callMountedAction` refuses to run a disabled action, and `CanBeDisabled::isDisabled()` returns true whenever the action is hidden. Self-entered registration numbers are UUIDs ([CreateCharity.php:35](app/Filament/Resources/Charities/Pages/CreateCharity.php#L35)), not guessable sequential ids. No IDOR was found: the public charity pages expose data that is public by design.

**Authentication hardening.** The admin panel requires app-based 2FA unconditionally (`multiFactorAuthentication(providers: [AppAuthentication::make()], isRequired: true)`), requires email verification outside local, and exposes no self-registration route. `two_factor_secret` and `two_factor_recovery_codes` are `encrypted` casts and `#[Hidden]`. Passwords are hashed with argon2id, and `AppServiceProvider.php:26` sets a default password rule of `min(8)->max(256)->uncompromised()` — the `uncompromised()` check against breach corpora is a nice touch that many codebases skip.

**Secrets are not in git.** `.env` is untracked and, per `git log --diff-filter=A -- .env`, never was; `git ls-files` shows only `.env.example`. `.gitignore` covers `.env` and `auth.json`. The working-tree `.env` does hold a real `APP_KEY` and a real admin password, and has `APP_DEBUG=true` / `SESSION_SECURE_COOKIE=false` — but `APP_ENV=local` and `APP_URL=http://localhost` identify it as a development file, and `config/session.php:172` defaults `secure` to *true* when the variable is absent, so a production `.env` copied from the template inherits the safe value. Rotate the key and password anyway if that pair has ever been used on a live host.

**Dependencies are current.** `composer.lock` pins laravel/framework v13.2.0, livewire/livewire v4.2.2, filament/filament v5.4.1, symfony/http-kernel v8.0.7. These are current-generation releases; no applicable published advisory is known to me as of this review. Note that the historical Livewire v3 `update`-endpoint RCE and the Filament v3 advisories do not apply to these major versions. I did not run `composer audit`, which requires network access — worth running in CI on a schedule, since this snapshot ages.

**Nothing to misconfigure in CORS or API auth.** There is no `config/cors.php`, no API routes, no Sanctum or Passport, and no broadcast endpoints. The entire public attack surface is three GET routes in `routes/web.php` and the Livewire update endpoint.

**Log and output injection into the admin UI.** Loader stdout is displayed escaped inside `<pre>{{ $batch->output }}</pre>`, and the progress lines the job parses back out of that stream are matched against a strict regex ([ProcessImportBatch.php:169](app/Jobs/ProcessImportBatch.php#L169)) before being written to the database. A hostile filename in a regulator archive cannot inject markup into the admin's import modal.
