Skip to content

Isolate security_helperTest filesystem tests from real .env #4700

Closed

Description

@jekkos

Summary

CodeRabbit review of PR #4656 flags that tests/helpers/security_helperTest.php writes to the repository's real filesystem paths — ROOTPATH/.env, ROOTPATH/.env.lock, and WRITEPATH/backup/.env.bak — rather than isolated, test-specific paths.

This is a known limitation documented in the test file's header comment: ROOTPATH / WRITEPATH are CI4 path constants that are resolved once at bootstrap and cannot be redirected per test, so the filesystem-touching helpers are exercised against the actual project .env.

Why it matters

  • Parallel / multi-process test runs can interleave writes. If any test runner or developer workflow runs the suite concurrently (e.g. a future --processes/max-workers configuration, or local development where a live app is running next to a test), reads of .env in one test can be clobbered by writes in another.
  • tearDown() restore is best-effort only. It restores state on normal completion but cannot protect against a test that calls exit()/hard process termination, or against a crash mid-write. A failed test can leave .env in a partial/rotated state.
  • Test order sensitivity. Tests that rotate the encryption key or write throttle.key depend on the .env captured in setUp(); any external change between capture and restore defeats the safeguard.

Proposed approach (either/or)

CodeRabbit suggests one of:

  1. Thread test-specific paths through the helper interfaces. Add ?string $configPath = null, ?string $backupPath = null (etc.) parameters to the helpers that touch the filesystem (checkEncryption, checkThrottleEncryption, rotateEncryptionKey, provisionThrottleKey, abortEncryptionConversion, removeBackup, backupEnvFile, writeEnvKey, atomicWriteFile, lockEnvFile), defaulting to the current ROOTPATH/WRITEPATH values so existing callers don't change. Tests then pass a sys_get_temp_dir()-based path and clean up in tearDown().
  2. Run the affected tests in a process-isolated application copy. Use PHPUnit's runInSeparateProcess (with a sys_get_temp_dir() sandbox) or a dedicated CI job that copies the repo to temp before running this test class.

Option 1 is the more explicit and testable approach and keeps the CI job structure unchanged.

Out of scope

  • Changing config('Encryption') key handling (already covered per-test by setUp()/tearDown()).
  • The throttle.key env-var shuffling (already covered by the same per-test restoreThrottleKey() helper).

Acceptance criteria

  • security_helperTest.php no longer writes to ROOTPATH/.env, ROOTPATH/.env.lock, or WRITEPATH/backup/.
  • A sys_get_temp_dir()-based sandbox (or an isolated process) is used for all filesystem-touching tests.
  • tearDown() removes the sandbox; no stray temp files remain.
  • A parallel-run smoke test (PHPUnit --processes 2) passes with the modified helper signatures.
  • All existing assertions remain valid (no behaviour change to checkEncryption, checkThrottleEncryption, rotateEncryptionKey, provisionThrottleKey, abortEncryptionConversion, or removeBackup).

References

Activity

  1. added
    php
    CodeIgniter4
    on Sep 14, 2026
  2. jekkos commented on Sep 15, 2026

    @jekkos
    MemberAuthor

    Plan drafted and a proposal posted: #4656 (comment)

    Chosen approach (pending objecttothis sign-off):

    • Introduce a Config\SecurityEnv config class holding envPath / backupPath / lockPath.
    • Replace the 11 hardcoded ROOTPATH / WRITEPATH literals in app/Helpers/security_helper.php with config('SecurityEnv') reads (no function signatures change).
    • Rewire tests/helpers/security_helperTest.php to redirect the three props to a unique per-run sandbox under sys_get_temp_dir() in setUp() and restore the defaults in tearDown().

    Implementation is staged locally but not committed/pushed until objecttothis signs off.

  3. objecttothis commented on Sep 15, 2026

    @objecttothis
    Member

    Plan drafted and a proposal posted: #4656 (comment)

    Chosen approach (pending objecttothis sign-off):

    • Introduce a Config\SecurityEnv config class holding envPath / backupPath / lockPath.
    • Replace the 11 hardcoded ROOTPATH / WRITEPATH literals in app/Helpers/security_helper.php with config('SecurityEnv') reads (no function signatures change).
    • Rewire tests/helpers/security_helperTest.php to redirect the three props to a unique per-run sandbox under sys_get_temp_dir() in setUp() and restore the defaults in tearDown().

    Implementation is staged locally but not committed/pushed until objecttothis signs off.

    It looks like a sound approach to me. I'd be interested in knowing if @coderabbitai sees any potential drawbacks.

  4. coderabbitai commented on Sep 15, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    
    printf '%s\n' '== Candidate files =='
    fd -a '^(security_helper\.php|security_helperTest\.php)$' . || true
    
    printf '%s\n' '== Configuration classes =='
    fd -a -e php . app | rg '/Config/|app/Config/' | head -80 || true
    
    printf '%s\n' '== security_helper outline =='
    ast-grep outline app/Helpers/security_helper.php --items all 2>/dev/null || true
    
    printf '%s\n' '== security_helperTest outline =='
    ast-grep outline tests/helpers/security_helperTest.php --items all 2>/dev/null || true
    
    printf '%s\n' '== security helper paths and configuration calls =='
    rg -n -C 3 'ROOTPATH|WRITEPATH|config\s*\(' app/Helpers/security_helper.php tests/helpers/security_helperTest.php 2>/dev/null || true
    
    printf '%s\n' '== Existing config classes that expose paths =='
    rg -n -C 2 'public\s+\??string\s+\$.*Path|public\s+\??string\s+\$.*path|ROOTPATH|WRITEPATH' app/Config -g '*.php' 2>/dev/null | head -200 || true
    
    printf '%s\n' '== Test framework setup/teardown patterns =='
    rg -n -C 3 'function setUp\s*\(|function tearDown\s*\(|setUp\(\)|tearDown\(\)' tests -g '*.php' | head -220 || true

    Length of output: 25665


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    
    printf '%s\n' '== security_helper.php =='
    cat -n app/Helpers/security_helper.php
    
    printf '%s\n' '== Dependency and test configuration =='
    for file in composer.json phpunit.xml phpunit.xml.dist; do
      if [ -f "$file" ]; then
        printf '\n-- %s --\n' "$file"
        cat -n "$file"
      fi
    done
    
    printf '%s\n' '== Configuration service resets and config mutation in tests =='
    rg -n -C 4 '(Config::reset|config\([^)]+\)->[A-Za-z_][A-Za-z0-9_]*\s*=|Services::reset)' tests app -g '*.php' | head -300 || true
    
    printf '%s\n' '== Proposed GitHub comment =='
    gh api repos/opensourcepos/opensourcepos/issues/comments/5682594254 --jq '.body' || true

    Length of output: 23177


    @objecttothis, the approach is sound. Config\SecurityEnv provides a small, testable seam without changing the helper API.

    I see three items to specify before implementation:

    1. Derive the backup directory from backupPath.

      checkEncryption() currently creates WRITEPATH . '/backup'. After the change, it should use dirname($securityEnv->backupPath). Otherwise, a redirected backupPath can still depend on or create the real WRITEPATH/backup directory.

    2. Define the .env.example behavior for a redirected envPath.

      The proposal keeps ROOTPATH . '.env.example'. This is safe for the default production paths. It is not fully sandboxed when a test deletes its sandbox .env to test initialization.

      Either add examplePath to SecurityEnv, or derive it from dirname($envPath). The test can then seed a sandbox .env.example when it tests the copy path. If the project must always use the shipped example file, document that as an explicit exception.

    3. Restore configuration state even when setup fails.

      config('SecurityEnv') is shared mutable state. tearDown() should restore all three properties before it removes the sandbox. The test should also avoid leaving the shared configuration redirected if setup fails after mutation. A small setup guard or try/finally cleanup path can cover this case.

    The unique sys_get_temp_dir() sandbox prevents collisions between separate PHPUnit processes. It does not make the shared SecurityEnv instance safe for concurrent tests in the same PHP process. PHPUnit normally runs tests sequentially within a worker, so this is acceptable if these tests do not use in-process concurrency.

    The .env pre-seed is appropriate for most tests. Add at least one test that removes the sandbox .env and verifies the intended initialization behavior.

    You are interacting with an AI system.

  5. objecttothis commented on Sep 15, 2026

    @objecttothis
    Member

    @jekkos let's move on it the way you've described.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CodeIgniter4enhancementphptechnical debt

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions