PraisonAI icon indicating copy to clipboard operation
PraisonAI copied to clipboard

fix(sandbox): correct sandlock integration semantics and fail loud

Open congwang-mk opened this issue 7 months ago β€’ 12 comments

Summary

The SandlockSandbox wrapper in src/praisonai/praisonai/sandbox/sandlock.py has several latent correctness and security issues. A caller who asks for kernel-level isolation could silently get weaker isolation, resource limits get dropped on the floor, and the timeout classifier never actually fires for real timeouts.

This PR fixes the integration to match sandlock's actual API, removes the silent fallback that violated the caller's explicit security choice, and strengthens the test suite accordingly.

What's fixed

  • Network policy intent is now explicit. sandlock uses tri-state semantics for net_allow_hosts (None = unrestricted, [] = deny all, [...] = allowlist). The previous code passed None to a Sequence[str] field when network was enabled and [] when disabled β€” semantically backwards and type-invalid. Rewritten to pass net_connect=[\"0-65535\"] when enabled or net_allow_hosts=[] when disabled. TCP-level deny-all defaults handle the rest.

  • stdout / stderr are now str, not bytes. sandlock returns bytes from Sandbox.run(); PraisonAI's SandboxResult is typed str. Added a _decode() helper with errors=\"replace\" so downstream consumers never see binary artefacts or crash on .lower() / .split().

  • max_cpu is now actually passed. limits.cpu_percent was silently ignored. Added max_cpu=limits.cpu_percent to the Policy construction.

  • execute_file() passes the script by path. The old implementation slurped the file into python3 -c <code> which is subject to ARG_MAX. Now it invokes [interp, abs_path, *args] directly and adds the script's parent directory to the Landlock read allowlist via a new extra_readable parameter on _create_policy.

  • Timeout detection uses sandlock's structural sentinel. sandlock exposes ExitStatus::Timeout as exit_code == -1 (see sandlock/_sdk.py around line 1475). Sandbox.run() does not populate result.error on timeout β€” only pipelines do β€” so string-matching is unreliable. Switching to exit_code == -1 works uniformly and matches how sandlock itself detects timeouts.

  • Context manager around Sandbox. with self._sandlock.Sandbox(policy) as sb: guarantees cleanup even if .run() raises mid-flight.

  • fs_readable is filtered to paths that exist. Landlock fails at spawn time if any allowlisted path is missing, so the hardcoded list β€” which included /usr/local/lib/python3 β€” caused sandlock_spawn failed on most hosts. The test_real_sandlock_integration test was silently failing on baseline for this reason; it now passes.

Breaking change β€” silent fallback removed

SandlockSandbox.execute/run_command/execute_file used to fall back to SubprocessSandbox whenever landlock_abi_version() < 1, logging only a warning. This violates the caller's explicit choice of kernel-level isolation: a SandlockSandbox that isn't actually using Landlock is a security footgun, and a warning in the logs is not a consent mechanism.

__init__ now raises RuntimeError if Landlock support is missing. The three fallback branches in execute(), run_command(), and execute_file() are removed.

Callers who want graceful degradation should catch ImportError / RuntimeError and construct SubprocessSandbox explicitly:

```python try: sb = SandlockSandbox(cfg) except (ImportError, RuntimeError): sb = SubprocessSandbox(cfg) ```

This is a deliberate fail-loud change β€” the previous behavior would silently weaken the security guarantees of any caller running on a kernel <5.13 or in a container with seccomp stripped.

Test plan

  • [x] test_raises_when_landlock_unavailable replaces the two old fallback tests and asserts RuntimeError at construction time.
  • [x] test_sandlock_execution_timeout mocks exit_code = -1 (the sentinel) instead of patching time.time.
  • [x] test_sandlock_execution_failure sets result.error = None explicitly (reflects real Sandbox.run() behavior).
  • [x] test_policy_creation_with_minimal_limits strengthened to verify max_cpu, net_allow_hosts=[] deny-all, and that net_connect is left unset so TCP deny-all defaults apply.
  • [x] test_real_sandlock_integration now actually passes (previously failed on baseline due to the /usr/local/lib/python3 hardcoded path).
  • [x] 10/10 unit tests pass: `pytest src/praisonai/tests/unit/sandbox/test_sandlock_sandbox.py`
  • [x] End-to-end smoke test against real sandlock confirmed: basic execute, network-blocked execute, execute_file with args, and a forced real timeout all behave correctly.

Files changed

  • `src/praisonai/praisonai/sandbox/sandlock.py` β€” all fixes
  • `src/praisonai/tests/unit/sandbox/test_sandlock_sandbox.py` β€” updated tests

πŸ€– Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added startup-time Landlock support validation with explicit error messaging when unsupported.
  • Improvements

    • Enhanced timeout detection for sandboxed processes.
    • Improved stdout/stderr handling with proper UTF-8 decoding.
    • Refined network isolation policy configuration.
    • Changed script execution method for improved compatibility and access control.

congwang-mk avatar Apr 13 '26 00:04 congwang-mk

πŸ“ Walkthrough

Walkthrough

The changes enhance the Sandlock sandbox implementation with runtime Landlock availability validation, extended filesystem allowlisting via extra_readable paths, restructured network policy logic, UTF-8 I/O decoding, and exit-code-based timeout detection. Helper functions are modified to execute scripts via interpreter instead of -c mode and no longer fall back to subprocess when sandlock is unavailable.

Changes

Cohort / File(s) Summary
Sandlock Sandbox Core Implementation
src/praisonai/praisonai/sandbox/sandlock.py
Added landlock_abi_version() check in __init__ to raise RuntimeError when unsupported; extended _create_policy() and _run_sandlocked() to accept extra_readable paths; refactored filesystem allowlist to filter existing directories; reworked network policy to use net_connect for enabled networks and net_allow_hosts=[] for denial; added _decode() for UTF-8 I/O conversion; replaced timeout detection with exit_code == -1 sentinel; updated execute(), execute_file(), and run_command() to remove subprocess fallback and use interpreter-based execution with script parent directory read access.
Sandlock Sandbox Tests
src/praisonai/tests/unit/sandbox/test_sandlock_sandbox.py
Updated initialization test to expect RuntimeError when Landlock ABI version is unsupported; revised policy assertions to expect max_cpu and strict network isolation (net_allow_hosts == [], no net_connect); modified timeout and failure tests to mock exit_code = -1 for timeout detection and use byte-valued stdout/stderr with error = None.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • #1255: Directly modifies the same SandlockSandbox class implementation, introducing Landlock startup checks and policy construction changes.
  • #1259: Updates Landlock availability checking via landlock_abi_version >= 1 and modifies exit-code-based result handling, overlapping with core behavioral changes.

Poem

🐰 A sandbox strengthened, Landlock now checked,
Paths filtered clean, no surprises wrecked,
Exit codes whisper when timeouts arise,
Scripts run safer 'neath security's eyes. πŸ”’βœ¨

πŸš₯ Pre-merge checks | βœ… 3
βœ… Passed checks (3 passed)
Check name Status Explanation
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title accurately describes the main fix: correcting sandlock integration semantics and enforcing early failure when support is missing.
Docstring Coverage βœ… Passed Docstring coverage is 94.12% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Apr 13 '26 00:04 coderabbitai[bot]

@copilot Do a thorough review of this PR. Read ALL existing reviewer comments above from Qodo, Coderabbit, and Gemini first β€” incorporate their findings.

Review areas:

  1. Bloat check: Are changes minimal and focused? Any unnecessary code or scope creep?
  2. Security: Any hardcoded secrets, unsafe eval/exec, missing input validation?
  3. Performance: Any module-level heavy imports? Hot-path regressions?
  4. Tests: Are tests included? Do they cover the changes adequately?
  5. Backward compat: Any public API changes without deprecation?
  6. Code quality: DRY violations, naming conventions, error handling?
  7. Address reviewer feedback: If Qodo, Coderabbit, or Gemini flagged valid issues, include them in your review
  8. Suggest specific improvements with code examples where possible

MervinPraison avatar Apr 13 '26 00:04 MervinPraison

Greptile Summary

This PR fixes multiple correctness and security issues in SandlockSandbox: the constructor now raises RuntimeError on unsupported kernels instead of silently falling back to SubprocessSandbox, the timeout sentinel switches from duration-comparison to sandlock's structural exit_code == -1, and stdout/stderr are properly decoded from bytes.

  • Constructor fail-loud + API fixes: __init__ raises immediately when landlock_abi_version() < min_landlock_abi(), removing three fallback branches. Network policy switches from the inverted net_allow_hosts field to net_allow; max_cpu is now passed; missing Landlock paths are filtered at build time to prevent spawn failures.
  • execute_file rewrite: Scripts are now invoked directly as [interp, abs_path, *args] instead of slurped through python3 -c, avoiding ARG_MAX. Only the script file itself (not its parent directory) is added to the Landlock read allowlist.
  • Test suite: Fallback tests replaced with test_raises_when_landlock_unavailable; timeout mock updated to use exit_code = -1; integration test skip condition updated to match the constructor's min_landlock_abi() guard.

Confidence Score: 5/5

Safe to merge; the fail-loud constructor, correct timeout sentinel, and filtered Landlock path allowlist are all well-reasoned changes that improve security and correctness.

The changes are internally consistent and well-documented. The execute_file rewrite (the most logic-heavy new path) is correct but lacks dedicated unit tests; coverage of this path would strengthen confidence in future regressions. All other new paths (constructor guard, bytes decode, net_allow semantics) are covered by the updated test suite.

The rewritten execute_file path in sandlock.py has no corresponding unit test in the test file.

Important Files Changed

Filename Overview
src/praisonai/praisonai/sandbox/sandlock.py Core sandbox implementation rewritten: fail-loud constructor guard, context-managed Sandbox, bytes-to-str decode helper, exit_code==-1 timeout sentinel, filtered Landlock path allowlist, and direct execute_file invocation. Changes are well-reasoned and documented.
src/praisonai/tests/unit/sandbox/test_sandlock_sandbox.py Test suite updated to match new constructor semantics (RuntimeError instead of silent fallback), bytes mock values, and direct kwargs assertions. Integration test skip condition now correctly mirrors the constructor guard. No test covers the rewritten execute_file path.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant SandlockSandbox
    participant _run_sandlocked
    participant SandlockSDK

    Caller->>SandlockSandbox: __init__()
    SandlockSandbox->>SandlockSDK: landlock_abi_version()
    SandlockSDK-->>SandlockSandbox: abi
    SandlockSandbox->>SandlockSDK: min_landlock_abi()
    SandlockSDK-->>SandlockSandbox: min_abi
    alt "abi < min_abi"
        SandlockSandbox-->>Caller: raise RuntimeError
    else "abi >= min_abi"
        SandlockSandbox-->>Caller: sandbox ready
    end

    Caller->>SandlockSandbox: execute / execute_file / run_command
    SandlockSandbox->>_run_sandlocked: cmd, limits, env, working_dir, extra_readable
    _run_sandlocked->>_run_sandlocked: _build_sandbox_kwargs
    _run_sandlocked->>SandlockSDK: "with Sandbox(**kwargs) as sb"
    _run_sandlocked->>SandlockSDK: "sb.run(cmd, timeout=...)"
    SandlockSDK-->>_run_sandlocked: result
    alt result.success
        _run_sandlocked-->>Caller: SandboxResult(COMPLETED)
    else "result.exit_code == -1"
        _run_sandlocked-->>Caller: SandboxResult(TIMEOUT)
    else
        _run_sandlocked-->>Caller: SandboxResult(FAILED)
    end

Reviews (4): Last reviewed commit: "fix(sandbox): address reviewer feedback ..." | Re-trigger Greptile

greptile-apps avatar Apr 13 '26 00:04 greptile-apps

@claude You are the FINAL architecture reviewer. Read ALL comments above from Gemini, Qodo, CodeRabbit, and Copilot carefully before responding.

Phase 1: Review per AGENTS.md

  1. Protocol-driven: check heavy implementations vs core SDK
  2. Backward compatible: ensure zero feature regressions
  3. Performance: no hot-path regressions

Phase 2: FIX Valid Issues 4. For any VALID bugs or architectural flaws found by Gemini, CodeRabbit, Qodo, Copilot, or any other reviewer: implement the fix 5. Push all code fixes directly to THIS branch (do NOT create a new PR) 6. Comment a summary of exact files modified and what you skipped

Phase 3: Final Verdict 7. If all issues are resolved, approve the PR / close the Issue 8. If blocking issues remain, request changes / leave clear action items

MervinPraison avatar Apr 13 '26 00:04 MervinPraison

Claude finished @MervinPraison's task β€”β€” View job


Architecture Review and Analysis

CRITICAL LIMITATION: This is a PR from a FORK - I cannot push fixes directly to this branch. I can only provide review feedback.

Todo List:

  • [x] Read AGENTS.md architecture guidelines
  • [x] Review sandlock integration changes for architectural compliance
  • [x] Analyze all reviewer feedback (Gemini, CodeRabbit, Qodo, Copilot)
  • [x] Assess security and performance implications
  • [x] Provide final verdict and recommendations

Phase 1: Architecture Review per AGENTS.md

βœ… Protocol-driven Design: This change is appropriately placed in the wrapper (praisonai/) not the core SDK (praisonaiagents/). The sandbox implementation is a heavy integration that belongs in the wrapper layer per AGENTS.md guidelines.

βœ… Backward Compatible: The changes don't break public APIs. The breaking change (removing silent fallback) is intentional and documented.

βœ… Performance: No hot-path regressions - sandlock is lazy-imported and only affects those explicitly choosing SandlockSandbox.

Phase 2: Valid Issues Found by Reviewers

I've analyzed all reviewer feedback and identified 2 CRITICAL BUGS that need immediate attention:

1. CRITICAL: Incorrect Kernel Version (src/praisonai/praisonai/sandbox/sandlock.py:88)

  • Issue: Error message claims >= 6.12 but Landlock ABI v1 was introduced in Linux 5.13
  • Impact: Users on kernels 5.13-6.12 will get misleading error messages
  • Fix Required:
# Line 88: Change this
">= 6.12 with CONFIG_SECURITY_LANDLOCK=y"
# To this  
">= 5.13 with CONFIG_SECURITY_LANDLOCK=y"

2. HIGH: Filesystem Root Exposure Risk (src/praisonai/praisonai/sandbox/sandlock.py:390)

  • Issue: execute_file unconditionally adds os.path.dirname(abs_path) to readable paths
  • Impact: If script is at filesystem root (/script.py), this exposes entire root filesystem (/)
  • Fix Required:
# Lines 378-391: Replace with this logic
abs_path = os.path.realpath(file_path)
script_dir = os.path.dirname(abs_path)
extra_read = [script_dir] if script_dir and script_dir != "/" else []
interp = "bash" if file_path.endswith((".sh", ".bash")) else "python3"
cmd: List[str] = [interp, abs_path]
if args:
    cmd.extend(args)

return await self._run_sandlocked(
    cmd,
    execution_id=execution_id,
    limits=limits,
    env=env,
    working_dir=self._temp_dir,
    extra_readable=extra_read,  # Changed from [os.path.dirname(abs_path)]
)

3. MEDIUM: Test Fragility (src/praisonai/tests/unit/sandbox/test_sandlock_sandbox.py:104-106)

  • Issue: Mock tests don't set success=True explicitly, relying on Mock() truthiness
  • Fix Required:
# Lines 104-106: Add explicit success flag
mock_result.exit_code = 0
mock_result.stdout = b"Hello, World!"  # Use bytes like real sandlock
mock_result.stderr = b""
mock_result.success = True  # Add this line

Phase 3: Final Verdict

❌ REQUEST CHANGES - The PR has 2 critical bugs that must be fixed before merge:

  1. Kernel version misinformation - This is factually incorrect and will confuse users
  2. Security vulnerability - Root filesystem exposure is a serious security issue

Recommendations for PR Author (@congwang-mk)

Please address these issues:

  1. Fix the kernel version in the error message (line 88)
  2. Add filesystem root protection in execute_file (line 390)
  3. Improve test robustness by setting explicit success=True (line 106)

The overall approach and architecture are sound - this is quality defensive security work that properly fails loud instead of silently degrading security. The fixes needed are straightforward but critical for safety.

Architecture Assessment: βœ… APPROVED with required fixes

The sandlock integration follows PraisonAI architectural principles:

  • Proper layer separation (wrapper vs core)
  • Fail-loud security philosophy
  • Protocol-driven design
  • No performance regressions
  • Comprehensive test coverage

Note: Since this is a fork PR, I cannot push the fixes directly. The PR author must implement these changes.

@congwang-mk just a gentle reminder to fix this issue. Thank you

MervinPraison avatar May 01 '26 05:05 MervinPraison

@congwang-mk just a gentle reminder to fix this issue. Thank you

MervinPraison avatar Jun 12 '26 09:06 MervinPraison

@claude

Merge review β€” blocked (fork PR, stale CI)

  • mergeStateStatus: UNSTABLE
  • Only CodeRabbit + GitGuardian checks present β€” no review or test-windows on current head
  • Branch fix/sandlock-integration is 2 months stale vs main

Fix list:

  1. Rebase onto latest main and resolve conflicts in sandlock.py.
  2. Trigger review + test-windows CI (maintainer may need to approve workflow for fork).
  3. Confirm unit tests in test_sandlock_sandbox.py still pass after rebase.

Wrapper/sandbox layer βœ… | unit tests present βœ…

MervinPraison avatar Jun 12 '26 14:06 MervinPraison

Claude finished @MervinPraison's task β€”β€” View job


PR Merge Review - Sandlock Integration ❌

CRITICAL FINDING: Multiple Unresolved Issues from April Review

  • [x] Read AGENTS.md architecture guidelines
  • [x] Check branch conflicts with main
  • [x] Analyze existing reviewer feedback (CodeRabbit, Greptile, Gemini, Copilot)
  • [x] Review sandlock integration against previous Claude feedback
  • [x] Assess critical bugs from April review
  • [x] Provide final merge recommendation

RECOMMENDATION: DO NOT MERGE

Critical Issues (BLOCKING)

1. 🚨 INCORRECT KERNEL VERSION (sandlock.py:92)

Status: UNFIXED from April review

# Line 92 - WRONG kernel version
">= 6.12 with CONFIG_SECURITY_LANDLOCK=y"
# Should be:  
">= 5.13 with CONFIG_SECURITY_LANDLOCK=y"
  • Impact: Users on kernels 5.13-6.11 get misleading error messages
  • All reviewers flagged this: CodeRabbit, Greptile, previous Claude review
  • Still not fixed 2 months later

2. πŸ”’ SECURITY VULNERABILITY (sandlock.py:395)

Status: PARTIALLY FIXED but still vulnerable

# Line 395 - Still passes abs_path directly
extra_readable=[abs_path],
  • Original issue: execute_file passed entire parent directory to readable allowlist
  • Partial fix: Now passes file path instead of directory
  • Remaining vulnerability: No validation against filesystem root exposure
  • Should check: if os.path.dirname(abs_path) == "/" then handle specially

3. πŸ“Š TEST COVERAGE GAP (test_sandlock_sandbox.py:253)

Status: LOGIC ERROR in integration test

# Lines 253-254 - Wrong ABI threshold  
if sandlock.landlock_abi_version() < 1:
    pytest.skip("Landlock not supported")
  • Issue: Test skips on ABI < 1, but constructor requires ABI >= 6
  • Result: Test may hard-fail on intermediate-ABI kernels instead of clean skip
  • Greptile identified this mismatch

Secondary Issues

4. Exception Handling (sandlock.py:282)

  • Broad except Exception without logging - acceptable but not ideal
  • CodeRabbit suggested narrowing to specific exceptions

5. Mock Test Consistency (test_sandlock_sandbox.py:123-124)

  • Mock uses bytes (correct) but doesn't set success=True explicitly
  • Minor test hygiene issue

What Was Fixed βœ…

  • Network policy semantics: Correctly uses net_allow array format
  • Timeout detection: Uses exit_code == -1 sentinel correctly
  • Bytes decoding: Added _decode() helper for UTF-8 conversion
  • Context manager: Added proper with Sandbox() cleanup
  • CPU limits: Now passes max_cpu parameter
  • Path filtering: Filters fs_readable to existing paths only
  • Fail-loud behavior: Removed silent fallback to subprocess

Branch Status Assessment

  • 80+ files diverged from main (massive scope creep)
  • 2 months stale - significant rebase conflicts expected
  • No CI runs on current head (fork limitations)
  • mergeStateStatus: UNSTABLE

Next Steps Required

  1. Author must fix the 3 critical issues above
  2. Rebase onto latest main and resolve conflicts
  3. Trigger CI workflows (maintainer approval needed for fork)
  4. Address all reviewer feedback from April

This is quality defensive security work with excellent fail-loud architecture, but the critical bugs make it unsafe to merge in current state.

Final Verdict: ❌ BLOCK MERGE until critical issues resolved

@claude Stale CI β€” required workflows missing on HEAD (2026-06-12 audit)

Status: mergeStateStatus=UNSTABLE; head commit (ec8b347) only shows GitGuardian (pass). No recent review, test-windows, or other required PR workflows on this SHA.

Fix:

  1. Rebase onto current origin/main and push to trigger a full workflow matrix:
    git fetch origin && git rebase origin/main && git push --force-with-lease
    
  2. If rebase is clean but jobs still skip: use Actions β†’ Re-run all jobs on the latest workflow run for this branch, or push an empty commit.
  3. After CI runs, fix any sandbox/sandlock test failures in fix(sandbox) scope and ensure all required checks green before merge.

Do not merge until standard PR checks have run and passed on the latest commit.

MervinPraison avatar Jun 12 '26 22:06 MervinPraison

Claude finished @MervinPraison's task β€”β€” View job


PR Status Assessment - Sandlock Integration ❌

CRITICAL LIMITATION: This is a PR from a FORK - I cannot push fixes directly to this branch. I can only provide review feedback.

Todo List:

  • [x] Check current git status and branch divergence
  • [x] Read AGENTS.md architecture guidelines
  • [x] Analyze sandlock integration changes for architectural compliance
  • [x] Review all reviewer feedback (Gemini, CodeRabbit, Qodo, Copilot)
  • [x] Assess security and performance implications
  • [x] Provide final verdict and recommendations

RECOMMENDATION: DO NOT MERGE

Critical Issues (BLOCKING)

1. 🚨 INCORRECT KERNEL VERSION (sandlock.py:92)

Status: UNFIXED from April review

# Line 92 - WRONG kernel version
">= 6.12 with CONFIG_SECURITY_LANDLOCK=y"
# Should be:  
">= 5.13 with CONFIG_SECURITY_LANDLOCK=y"
  • Impact: Users on kernels 5.13-6.11 get misleading error messages
  • All reviewers flagged this: CodeRabbit, Greptile, previous Claude review
  • Still not fixed 2 months later

2. πŸ”’ SECURITY VULNERABILITY (sandlock.py:395)

Status: PARTIALLY FIXED but still vulnerable

# Line 395 - Still passes abs_path directly
extra_readable=[abs_path],
  • Original issue: execute_file passed entire parent directory to readable allowlist
  • Partial fix: Now passes file path instead of directory
  • Remaining vulnerability: No validation against filesystem root exposure
  • Should check: if os.path.dirname(abs_path) == "/" then handle specially

3. πŸ“Š TEST COVERAGE GAP (test_sandlock_sandbox.py:253)

Status: LOGIC ERROR in integration test

# Lines 253-254 - Wrong ABI threshold  
if sandlock.landlock_abi_version() < 1:
    pytest.skip("Landlock not supported")
  • Issue: Test skips on ABI < 1, but constructor requires ABI >= 6
  • Result: Test may hard-fail on intermediate-ABI kernels instead of clean skip
  • Greptile identified this mismatch

Secondary Issues

4. Exception Handling (sandlock.py:282)

  • Broad except Exception without logging - acceptable but not ideal
  • CodeRabbit suggested narrowing to specific exceptions

5. Mock Test Consistency (test_sandlock_sandbox.py:123-124)

  • Mock uses bytes (correct) but doesn't set success=True explicitly
  • Minor test hygiene issue

What Was Fixed βœ…

  • Network policy semantics: Correctly uses net_allow array format
  • Timeout detection: Uses exit_code == -1 sentinel correctly
  • Bytes decoding: Added _decode() helper for UTF-8 conversion
  • Context manager: Added proper with Sandbox() cleanup
  • CPU limits: Now passes max_cpu parameter
  • Path filtering: Filters fs_readable to existing paths only
  • Fail-loud behavior: Removed silent fallback to subprocess

Branch Status Assessment

  • 57 commits diverged from main (significant scope creep)
  • 2 months stale - significant rebase conflicts expected
  • No CI runs on current head (fork limitations)
  • mergeStateStatus: UNSTABLE

Architecture Assessment: βœ… APPROVED with required fixes

The sandlock integration follows PraisonAI architectural principles:

  • Proper layer separation (wrapper vs core)
  • Fail-loud security philosophy
  • Protocol-driven design
  • No performance regressions
  • Comprehensive test coverage

Next Steps Required

  1. Author must fix the 3 critical issues above
  2. Rebase onto latest main and resolve conflicts
  3. Trigger CI workflows (maintainer approval needed for fork)
  4. Address all reviewer feedback from April

This is quality defensive security work with excellent fail-loud architecture, but the critical bugs make it unsafe to merge in current state.

Final Verdict: ❌ BLOCK MERGE until critical issues resolved


Note: Since this is a fork PR, I cannot push the fixes directly. The PR author must implement these changes.

@MervinPraison β€” rebased onto latest main (was 74 commits behind, clean rebase) and addressed the reviewer feedback. Full breakdown of what changed and, importantly, what I deliberately did not change and why.

Fixed

  • Test ABI-skip mismatch (Greptile) β€” test_real_sandlock_integration skipped on landlock_abi_version() < 1, but the constructor raises when abi < min_landlock_abi() (= 6). On an intermediate-ABI kernel (1–5) the test wouldn't skip and would hard-fail in __init__ instead of skipping cleanly. Now skips below sandlock.min_landlock_abi().
  • Write-dir not readable (Gemini, MEDIUM) β€” Landlock does not grant read from write. The sandboxed process couldn't read its own working/temp dir. Writable dirs are now mirrored into the read allowlist. Verified with a real-sandlock write-then-read-back smoke test.
  • Broad except swallowed the traceback (CodeRabbit, BLE001) β€” added logger.exception(...) so the underlying cause is logged before returning a FAILED result.

Not changed β€” and why

  • Kernel version in the error message (>= 6.12, flagged as "should be 5.13") β€” this is now correct and I've left it. The flag refers to an earlier revision that gated on abi < 1; ABI v1 shipped in kernel 5.13, so back then 5.13 was right. The code was since changed to gate on sandlock.min_landlock_abi(), which returns 6 β€” and Landlock ABI v6 shipped in Linux 6.12. So 6.12 matches the actual requirement; changing it to 5.13 would understate the real minimum and mislead users on 5.13–6.11 kernels into thinking SandlockSandbox will work for them when the constructor will reject it. (Verified: min_landlock_abi() == 6 on this host.)
  • execute_file "root exposure" β€” already addressed in an earlier commit: it passes the single resolved script path to the read allowlist (extra_readable=[abs_path]), not the parent directory, so a script at /script.py can never expose /. No dirname == "/" guard is needed because no dirname is added.
  • Mock success=True/bytes β€” already present in the success test (the result mock sets success = True and byte-valued stdout/stderr).

Verification

  • pytest tests/unit/sandbox/test_sandlock_sandbox.py β†’ 11/11 pass on the rebased tree.
  • Real-sandlock smoke test (ABI 8 kernel): execute, execute_file with args, and write-then-read in the working dir all return COMPLETED.

congwang-mk avatar Jun 13 '26 00:06 congwang-mk