OwnPay icon indicating copy to clipboard operation
OwnPay copied to clipboard

[BUG] Security and Bug reports

Open fattain-naime opened this issue 3 weeks ago • 1 comments

Security findings

  1. Password reset bypasses the project’s own password policy — Medium, confirmed src/Service/Auth/PasswordResetService.php:34 sets MIN_PASSWORD_LENGTH = 8, and the reset controller performs no additional complexity check (AuthController.php:434). Staff creation/change (StaffController.php:178,318) and the installer require 12 characters and multiple character classes. A user can therefore reset a strong account password to an 8-character password and bypass the documented policy. Recommend a single shared policy validator used by installer, staff CRUD and reset.

  2. SVG upload sanitiser is blacklist-based — Medium (privileged stored-XSS), confirmed FilesystemService::isSvgMalicious() (:251) blocks <script, <!entity/<!doctype, javascript: and on…= attributes, but does not block foreignObject, xlink:href, data: URIs or CSS imports. SVG is explicitly allowed and uploaded to the web root (ALLOWED_EXTENSIONS, storePublicUpload). Because these files are served inline as image/svg+xml, a staff member with branding/logo upload rights can attempt a stored XSS against superadmins who open the asset directly. Browser rendering usually neutralises scripts, so impact is context-dependent; a robust fix is to sanitise with a DOM/allowlist parser or rasterise brand logos.

  3. Path-containment prefix check is incomplete — Low (latent), confirmed FilesystemService::resolveSafe() (:201-214) uses str_starts_with($fullPath, $baseReal) without a trailing separator. A sibling such as /app/storage-backup passes the check for base /app/storage. Current call sites only use storeUpload/storePublicUpload, so I did not find a reachable read/delete path today; fix it before any caller starts accepting stored paths.

  4. Committed vendor is stale and vulnerable — Medium/Low, confirmed composer.lock pins symfony/filesystem v8.1.11 (not affected), but the committed vendor/ contains v7.4.17, which composer audit flags. It is a dev-only dependency, so no production RCE, but the checked-in runtime artifact does not match the lock and cannot be regenerated in the shipped image.

  5. Platform-wide webhook HMAC/replay middleware is dead code — Low/Medium, confirmed RequestSignatureMiddleware implements timestamp tolerance, nonce replay protection and fail-closed cache behaviour, but grep finds no reference outside its own file. The webhook route group only runs IpAllowlistMiddleware, and an empty IP_ALLOWLIST disables that middleware by design. Actual authentication relies on each adapter’s verifyWebhook(); 109 implement it, but replay protection is then adapter-specific. Either wire the middleware into /webhook/{gateway} or delete it and document that replay protection is the adapter’s responsibility.

  6. Global-view authorization is permission-based, not strictly superadmin — Informational BrandController allows non-superadmins with brands.access_all into the All Brands view; several controllers then use forAllTenants(). I spot-checked FeeRuleController, DashboardController, WebhookController and RolesController: writes are correctly gated by isSuperadmin() && isGlobalView() or requireActiveBrand(), and role escalation is blocked. This appears intentional, but brands.access_all is effectively “read all tenants”, so it should be treated as a platform-owner permission and covered by an explicit integration test.

Bugs and errors

  1. Installer self-locks when DB_* environment variables exist — High, reproduced InstallerController::isInstalled() (:1041) calls databaseLooksInstalled() (:1068) and self-heals storage/.installed (:1055) as soon as a superadmin row exists. With Docker-injected DB_* variables, this happens immediately after createAdmin, before finalize; finalize then returns “already installed”. Because the marker now exists but .env does not, Kernel throws JWT_SECRET must be set and every request 500s. I had to force the installer with INSTALL_FORCE_KEY and temporary loopback DB settings. Fix: only self-heal after a completed install (marker + valid .env + finalized flag), or make finalize idempotent when the marker was self-healed during the same request.

  2. Fresh installs never seed SMS parsing templates — High, confirmed The installer imports only database/schema.sql (InstallerController.php:296); database/seeds/sms_templates.sql is never executed by the installer or test bootstrap. The installed database has op_sms_templates = 0. Consequences: MFS SMS auto-verification has no bKash/Nagad/Rocket/Upay/SureCash/Tap patterns, and two integration tests fail because they expect those rows (SmsParsingIntegrationTest.php:54,64). This is a shipped-feature failure, not just a test issue.

  3. Docker dev image lacks ext-yaml — Medium, confirmed php -m has no yaml, yet composer install/make dev requires it. The four PHPUnit errors are all DockerDevEnvironmentTest.php:23 calling yaml_parse_file(). The stack only runs because vendor/ is committed. Add libyaml-dev/pecl install yaml (or make the dependency optional) so the documented quickstart and test suite work.

  4. Docker image’s Apache log handling breaks startup — Medium, confirmed The image symlinks /var/log/apache2/*.log to root-owned Docker pipes; Apache running as www-data fails with AH00015. My local docker-compose.override.yml materialises the log files to work around it. This should be fixed in the image/entrypoint, not in every developer’s override.

  5. Environment leakage makes tests order-dependent — Low, confirmed

    • SmsGatewayAddonTest.php:127 expects https://localhost but gets the container’s APP_URL=http://localhost:8080; the assertion depends on host env rather than a forced test value.
    • The Apple Pay/Google Pay tests fail only in the full suite (SecurityRemediationTest.php:91,112). I ran them in isolation under both APP_ENV=testing and APP_ENV=development: 2 tests, 8 assertions, OK. Another suite is leaking global APP_ENV/state; PHPUnit should force it in phpunit.xml or the tests’ setUp.

PHPUnit also reports 99 notices, which are worth triaging but are not failures.


Reported by @ownpay-bot

fattain-naime avatar Nov 09 '26 01:11 fattain-naime

Implementation Plan - Issue #681 ("[BUG] Security and Bug reports")

Consolidated bot report with 6 security findings and 5 bug/error findings. Duplicate check: similar (closed) issues #142 (password reset session invalidation) and #363 (staff 8-char password) overlap findings 1 of each section; treat as follow-ups rather than new work. Several claims in the report are inaccurate against the current tree (see Clarity Check).

1. Clarity Check (gaps / inaccuracies)

  • Finding S1 (password policy): Report claims installer and staff "require 12 chars + multiple classes". Current code enforces only strlen < 8 in InstallerController::createAdmin (:340), StaffController::create (:153) and StaffController::edit (no check at all), and PasswordResetService::MIN_PASSWORD_LENGTH = 8 (:32). The 12-char/multi-class requirement exists only as a frontend strength meter in templates/install/step3.php (:74-79), not enforced server-side. So the real defect is inconsistent/weak enforcement everywhere, not a bypass of an enforced 12-char policy. Decision needed: confirm the target policy (recommend 12 chars + >=3 of {upper, lower, digit, symbol}) and whether to keep 8 for reset (not recommended).
  • Finding S2 (SVG sanitiser): Verified FilesystemService::isSvgMalicious() (:251) is blacklist-based and misses foreignObject, xlink:href, data: URIs, CSS @import/url(). Repro requires a staff account with branding/logo upload rights; impact is context-dependent (browsers neutralise inline scripts). Decision needed: allowlist/DOM sanitiser vs rasterise brand logos (rasterising breaks SVG logos). Note ALLOWED_EXTENSIONS includes svg and storePublicUpload writes to web root.
  • Finding S3 (path containment): Verified resolveSafe() (:201-214) uses str_starts_with($fullPath, $baseReal) without trailing separator; sibling /app/storage-backup passes for base /app/storage. Also the fallback branch (:204-210) strips ../ via str_replace, which is bypassable (....//). No reachable read/delete caller today (only storeUpload/storePublicUpload), so latent. Fix both issues now.
  • Finding S4 (stale vendor): Lock pins symfony/filesystem v7.4.11 in packages-dev (not v8.1.11 as reported). Vendor is committed and composer audit cannot run cleanly in this env. Scope is build/release, not app code. Confirm whether to regenerate vendor in CI image or remove committed vendor.
  • Finding S5 (dead middleware): Verified RequestSignatureMiddleware is unreferenced; webhook group only runs IpAllowlistMiddleware, which no-ops on empty IP_ALLOWLIST. Design decision required: wire middleware into /webhook/{gateway} (needs per-gateway secret resolution, which adapters already do via verifyWebhook()) OR delete and document adapter responsibility. Do not silently leave dead code.
  • Finding S6 (global-view auth): Informational; not a bug. brands.access_all grants read-all-tenants. Writes are gated by isSuperadmin() && isGlobalView() / requireActiveBrand(). Ask: add explicit integration test only; no code change unless product wants stricter gating.
  • Bug B1 (installer self-lock): Verified isInstalled() (:1041) self-heals marker as soon as a superadmin row exists, even mid-install (Docker-injected DB_*). Fix: only self-heal when marker + valid .env + finalized flag, OR make finalize idempotent when marker was self-healed in the same request. Also databaseLooksInstalled() reads $_ENV (not .env), so Docker env vars trigger it.
  • Bug B2 (SMS templates not seeded): Verified importSchema executes only database/schema.sql (:296 in report; actual :231). database/seeds/sms_templates.sql never run. Two integration tests (SmsParsingIntegrationTest :54, :64) fail expecting rows. Fix in importSchema (run sms_templates seed after schema) and test bootstrap.
  • Bug B3 (ext-yaml missing): No Dockerfile in repo; Docker image is external. Out of repo scope unless adding optional yaml fallback. Verify whether DockerDevEnvironmentTest exists anywhere (it does not in this tree). Likely needs infra PR in deploy repo.
  • Bug B4 (Apache log handling): No Dockerfile/entrypoint in repo. Out of repo scope (infra).
  • Bug B5 (env leakage / test order): SmsGatewayAddonTest :122 hardcodes https://localhost but reads host env (APP_URL=http://localhost:8080 in container). Apple/Google Pay tests fail only in full suite (state leak). phpunit.xml pins APP_ENV=testing but not APP_URL. Fix: force APP_URL in phpunit.xml and/or setUp; isolate global state in leaking suite.
  • Missing reproduction: No steps for S2/S5/S6 beyond grep; no expected/actual for B3/B4 beyond environment. Recommend splitting this umbrella issue into per-finding issues before implementation.

2. Scope & Target

Finding Primary files Tests
S1 password policy src/Service/Auth/PasswordResetService.php, src/Controller/Admin/StaffController.php (create :153, edit :261), src/Controller/Install/InstallerController.php (createAdmin :340), new src/Service/Auth/PasswordPolicy.php (or src/Security/) tests/Integration/PasswordResetServiceTest.php, tests/Controller/*Staff*, tests/Integration/InstallerLockTest.php
S2 SVG src/Service/System/FilesystemService.php (isSvgMalicious :251, moveValidatedUpload :96) tests/Security/SecurityRemediationTest.php (provideMaliciousSvgPayloads)
S3 path containment src/Service/System/FilesystemService.php (resolveSafe :201) tests/Service/FilesystemServiceTest.php
S4 vendor composer.lock, vendor/ (build artifact) CI composer audit
S5 middleware config/middleware.php (webhook group :85), src/Middleware/RequestSignatureMiddleware.php, config/routes/web.php (:337) new middleware test
S6 global-view src/Controller/Admin/BrandController.php, FeeRuleController, DashboardController, WebhookController, RolesController new integration test
B1 installer src/Controller/Install/InstallerController.php (isInstalled :726, databaseLooksInstalled :759, finalize :481) tests/Integration/InstallerLockTest.php, InstallerSelfHealTest
B2 SMS seed src/Controller/Install/InstallerController.php (importSchema :231), database/seeds/sms_templates.sql, test bootstrap tests/Integration/SmsParsingIntegrationTest.php
B3/B4 Docker infra repo (not here) DockerDevEnvironmentTest (external)
B5 env leak phpunit.xml (:46-56), tests/Integration/SmsGatewayAddonTest.php (:122), Apple/Google Pay tests in tests/Security/SecurityRemediationTest.php (:74-114) full suite run

3. Step-by-Step Plan

Milestone A - Password policy (S1)

  1. Create src/Service/Auth/PasswordPolicy.php (or src/Security/PasswordPolicy.php) with validate(string $password): ?string returning error message or null; rules: length >= 12, >=3 of 4 character classes. Keep a constant MIN_LENGTH = 12.
  2. Replace checks in StaffController::create (:153), StaffController::edit (add before hashing :261), InstallerController::createAdmin (:340), and PasswordResetService (replace MIN_PASSWORD_LENGTH = 8 with call to policy; update error message).
  3. Update templates/install/step3.php minlength="8" -> minlength="12" and meter thresholds to match.
  4. Register policy in container if needed; inject into controllers/services.

Milestone B - SVG sanitisation (S2)

  1. Replace blacklist with an allowlist/DOM-based check: parse with DOMDocument/SimpleXML, reject elements not in allowlist (svg, g, path, rect, circle, ellipse, line, polyline, polygon, text, tspan, defs, use? decide), reject attributes starting with on, any href/xlink:href containing javascript:/data:, reject foreignObject, script, style with @import/url(, reject processing instructions and DOCTYPE.
  2. Alternatively rasterise brand logos at upload time (breaks SVG fidelity) - recommend DOM allowlist for logos, rasterise for favicons if needed.
  3. Keep isSvgMalicious signature for test compatibility; update provideMaliciousSvgPayloads data provider with new cases (foreignObject, xlink:href javascript, data: URI, CSS import).

Milestone C - Path containment (S3)

  1. Change check to str_starts_with($fullPath, $baseReal . DIRECTORY_SEPARATOR) OR $fullPath === $baseReal.
  2. Remove str_replace traversal stripping in fallback; instead reject if realpath fails or path contains .. segments. Return error or throw.
  3. Add tests for sibling-prefix and ....// bypass.

Milestone D - Installer self-lock (B1)

  1. Add finalized marker or check: self-heal only if .env exists and contains JWT_SECRET= with non-empty value (or a dedicated storage/.finalized flag written in finalize()).
  2. In finalize(), write storage/.finalized after success; isInstalled() treats self-heal as valid only when .finalized exists.
  3. Make finalize() idempotent: if marker self-healed during same request, allow finalize to complete and write final marker.
  4. databaseLooksInstalled() should not treat Docker-injected env as installed during an active install: check for .env.temp or a request-scoped flag; or probe only when no .env.temp? Careful: keep reinstall protection. Recommend: probe only if .env (final) exists.
  5. Keep INSTALL_FORCE_KEY escape hatch.

Milestone E - SMS template seeding (B2)

  1. In importSchema(), after executing schema statements, execute database/seeds/sms_templates.sql (apply same prefix replacement).
  2. Make test bootstrap import the seed (or a dedicated test fixture) so SmsParsingIntegrationTest passes in CI.
  3. Verify sms_templates.sql uses op_ prefix (apply str_replace like schema).

Milestone F - Dead middleware decision (S5)

  1. Option A (recommended): wire RequestSignatureMiddleware into webhook group only if adapters delegate to it; but adapters already implement verifyWebhook(). Prefer Option B: delete RequestSignatureMiddleware and document in docs/ that replay protection is adapter responsibility; OR keep but wire and have adapters call $request signature consistently. Given 109 adapters, recommend documenting + deleting to avoid false security.
  2. If keeping: add nonce replay cache in middleware and wire into group; ensure fail-closed when cache unavailable.

Milestone G - Env leakage (B5)

  1. Add APP_URL to phpunit.xml <php> block (value http://localhost).
  2. Update SmsGatewayAddonTest :122 expectation or make it read from env/config.
  3. For Apple/Google Pay state leak: ensure tests reset APP_ENV/global in setUp/tearDown or pin via phpunit. Run full suite to confirm.

Milestone H - Vendor (S4) and Docker (B3/B4)

  1. Regenerate committed vendor from lock (composer install --no-dev in CI image) or remove vendor from repo and document install. Add composer audit to CI.
  2. Docker image fixes belong in infra repo: add libyaml-dev + pecl install yaml; fix Apache log symlink to create writable files owned by www-data. Track separately.

Milestone I - Global-view test (S6)

  1. Add integration test asserting non-superadmin with brands.access_all can read All Brands but cannot write; role escalation blocked. No code change.

4. Risk & Edge Cases

  • S1: Raising min to 12 will break existing tests using password123 (InstallerLockTest, SetupWizardIntegrationTest). Update test fixtures or they fail. Risk of locking out users on password reset if policy too strict; allow grandfathering? No, reset is new password.
  • S2: DOM allowlist may reject legitimate complex SVGs (gradients, filters). Test with real brand logos. XSS via CSS url() external resources remains if style allowed; recommend stripping <style> entirely.
  • S3: Changing prefix check affects any future caller passing stored paths; ensure no false positives (base path itself).
  • B1: Self-heal change must not weaken reinstall protection for populated DBs; keep force key. Risk: partial installs where .env written but marker not -> treated as not installed (correct, allows finalize retry).
  • B2: Running seed twice must be idempotent (INSERT IGNORE / upsert). Check sms_templates.sql for unique keys.
  • B5: Pinning APP_URL may affect other tests expecting 8080; search first.

5. Verification Checklist

CLI (run from repo root):

  • vendor/bin/parallel-lint src tests
  • vendor/bin/phpstan analyse (timeout >= 120s)
  • vendor/bin/phpunit --testsuite Unit,Service,Security,Controller (DB-free)
  • vendor/bin/phpunit --testsuite Integration (requires MySQL; skip in ephemeral env)
  • vendor/bin/twig-cs-fixer lint templates
  • npm run lint and npm test

Test cases to add/update:

  • PasswordPolicy unit: accept 12+ with 3 classes; reject 8-char, reject missing classes.
  • PasswordResetService: reset with 8-char password now fails; 12-char with classes succeeds.
  • StaffController: create/edit with weak password rejected.
  • FilesystemService: new SVG payloads (foreignObject, xlink:href javascript, data:, CSS import) rejected; safe SVG accepted; sibling-prefix path blocked.
  • Installer: mid-install with DB_* env does not self-lock; finalize succeeds after self-healed marker; .env missing -> not installed.
  • SMS: importSchema seeds sms_templates; SmsParsingIntegrationTest passes.
  • Middleware: webhook group behavior documented/tested.
  • Full suite: no order-dependence; Apple/Google Pay tests pass in full run.

Recommend splitting umbrella issue #681 into per-finding issues before implementation to keep PRs atomic.

Task list (1/6 completed)
  • [x] Create task list and read AGENTS.md / repo conventions
  • [ ] Verify each security finding against current code
  • [ ] Verify each bug finding against current code
  • [ ] Identify scope, affected components, and tests
  • [ ] Formulate plan with clarity check, risks, verification
  • [ ] Post plan via report_progress

Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using beam-free (free) | 𝕏

pullfrog[bot] avatar Nov 09 '26 01:11 pullfrog[bot]