openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

test(security): cover env-overlay path in load_and_get_security_policy_info

Open obchain opened this issue 6 months ago • 6 comments

Summary

  • Adds a direct unit test for load_and_get_security_policy_info() covering the chained env-overlay → load-with-timeout → policy-info-payload contract for both the OPENHUMAN_MAX_ACTIONS_PER_HOUR=42 and =0 cases (acceptance criteria #1 and #2 of #2688).
  • Uses an RAII EnvGuard so the env restore is panic-safe and cannot leak state into later tests sharing TEST_ENV_LOCK.
  • Includes five ancillary one-line test fixes that unblock CI on main (broken since #2499 / #2690 landed); detailed below so reviewers can split this PR if preferred.

Problem

load_and_get_security_policy_info() is the JSON-RPC entrypoint for openhuman.security_policy_info. The individual links are unit-tested separately (env overlay in config/schema/load_tests.rs, payload shape in two existing tests in ops.rs), but the full chain — env var → load_config_with_timeout → security_policy_info_for_config → JSON payload — was only exercised by the full JSON-RPC smoke. A regression in either link (env precedence, payload serialization) would not be caught by a fast cargo test run.

Additionally, upstream main was failing CI on every commit since b616f48a due to a handful of stale test expectations and one missing struct-default spread; those needed to be unblocked before this PR's own checks could go green.

Solution

Primary change (src/openhuman/security/ops.rs)

  • New #[tokio::test] load_and_get_security_policy_info_reflects_env_overlay.
  • Acquires crate::openhuman::config::TEST_ENV_LOCK (the same mutex load_tests.rs uses) to serialize against other env-mutating tests.
  • Iterates [42, 0], points OPENHUMAN_WORKSPACE at a fresh tempfile::tempdir() per iteration (so the loader does not read or mutate the developer's real ~/.openhuman/), sets OPENHUMAN_MAX_ACTIONS_PER_HOUR, awaits load_and_get_security_policy_info(), and asserts outcome.value["max_actions_per_hour"] == budget.
  • An inline EnvGuard RAII type records the prior env value, sets the test value, and restores the prior on drop — including across panics — so a failed assertion cannot leak state into the next test.

Ancillary main-unblock fixes

Commit File Reason
7629822e src/openhuman/config/ops_tests.rs AutonomySettingsPatch { max_actions_per_hour: Some(64) } was missing 6 fields; struct derives Default, so spread defaults. Broken since #2499.
b3e85784 app/src/utils/__tests__/loopbackOauthListener.test.ts DEFAULT_TIMEOUT_SECS was lowered from 300 to 60 in #2690; the test still asserted 300.
b5780b0e src/openhuman/inference/provider/factory_test.rs hint:summarization is now translated to summarization-v1 (new arm added in #2690); replaced with hint:lightweight so the test still exercises the Some(_) catch-all.
67ea821a src/openhuman/memory/chat.rs Memory workload now resolves through provider_for_role("summarization", …) → summarization-v1 by default; the cloud_llm_model override path stays on reasoning-v1.
465a1dbb src/openhuman/memory/ops/files.rs The memory workspace now also contains SQLite store files (memory.db, memory.db-shm, memory.db-wal); replaced the full-listing equality with two invariant checks (real.md present, alias.md symlink absent) so the test stays scoped to its actual purpose.

Each is a one-line atomic commit so a maintainer can drop them into a separate PR if preferred.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy — happy path (=42) + edge case (=0); failure modes for the underlying load + payload are covered by sibling tests in ops.rs and config/schema/load_tests.rs.
  • [x] Diff coverage ≥ 80% — changed lines are 100% test code, executed by the test itself.
  • [x] Coverage matrix updated — N/A: test-only change, no new feature row.
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related — N/A: test-only change.
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — test uses tempdir + env vars only, no network.
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: test-only change, no user-visible surface.
  • [x] Linked issue closed via Closes #NNN in the ## Related section.

Impact

  • Runtime/platform impact: none — test-only.
  • Performance/security/migration/compatibility: none.

Related

  • Closes: #2688
  • Follow-up PR(s)/TODOs: none

AI Authored PR Metadata (required for Codex/Linear PRs)

Keep this section for AI-authored PRs. For human-only PRs, mark each field N/A.

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: N/A
  • Commit SHA: N/A

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no app/src source changed except the loopback OAuth listener test, which is auto-formatted on save.
  • [x] pnpm typecheck — N/A: no TS source files changed (only a test file).
  • [x] Focused tests: ran the new tokio test for load_and_get_security_policy_info_reflects_env_overlay and the loopback OAuth listener test suite locally.
  • [x] Rust fmt/check (if changed): cargo fmt + cargo check clean on the touched files.
  • [x] Tauri fmt/check (if changed): N/A — no Tauri code changed.

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: none (test-only).
  • User-visible effect: none.

Parity Contract

  • Legacy behavior preserved: yes — no production code touched.
  • Guard/fallback/dispatch parity checks: N/A.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none.
  • Canonical PR: this PR.
  • Resolution: N/A.

Summary by CodeRabbit

  • Tests
    • Added an end-to-end regression test verifying env-driven max-actions-per-hour is respected.
    • Updated OAuth listener fallback test to expect a shorter timeout (60s).
    • Ensured autonomy action-budget tests include defaulted settings when patching.
    • Broadened provider hint tests to accept additional canonical hints.
    • Updated memory tests to default memory workload to summarization (cloud override still uses reasoning).
    • Adjusted file-listing test to assert real file presence and ignore symlinks while allowing extra fixtures.

Review Change Stack

obchain avatar May 26 '26 13:05 obchain

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a Tokio integration test verifying OPENHUMAN_MAX_ACTIONS_PER_HOUR flows through load_and_get_security_policy_info(); updates unit tests for AutonomySettingsPatch defaulting, forwarded-hint passthrough, memory model routing, symlink-tolerant listings, and a TS loopback OAuth timeout expectation.

Changes

Test updates

Layer / File(s) Summary
load_and_get_security_policy_info end-to-end test
src/openhuman/security/ops.rs
Integration test that snapshots/restores env, sets OPENHUMAN_WORKSPACE and OPENHUMAN_MAX_ACTIONS_PER_HOUR (42 and 0), calls load_and_get_security_policy_info(), and asserts the returned JSON's max_actions_per_hour matches each value.
AutonomySettingsPatch default filler
src/openhuman/config/ops_tests.rs
AutonomySettingsPatch struct literal now includes ..Default::default() so unspecified fields use default values when passed to apply_autonomy_settings in the test.
Forwarded hint passthrough test updated
src/openhuman/inference/provider/factory_test.rs
Test cases adjusted and inline doc updated so hint:lightweight is treated as non-canonical/pass-through while canonical hints now include additional values such as summarization.
Memory runtime model routing tests
src/openhuman/memory/chat.rs
Tests updated to expect the memory/summarization workload resolves to summarization-v1 by default and that overriding memory_tree.cloud_llm_model routes the memory workload through legacy cloud-memory which falls back to the reasoning tier (overridden path still asserts reasoning-v1).
Symlink-skipping directory listing test
src/openhuman/memory/ops/files.rs
Test relaxed to assert real.md is present and alias.md is absent, tolerating extra fixture-created files in the directory listing.
Loopback OAuth listener test timeout expectation
app/src/utils/__tests__/loopbackOauthListener.test.ts
Updated the mocked start_loopback_oauth_listener invocation expectation to use timeoutSecs: 60 for the shell-bind-fails fallback test (was 300).

Sequence Diagram(s)

sequenceDiagram
  participant Test
  participant load_and_get_security_policy_info
  participant load_config_with_timeout
  participant security_policy_info_for_config
  Test->>load_and_get_security_policy_info: call
  load_and_get_security_policy_info->>load_config_with_timeout: load config (with env overlay)
  load_config_with_timeout->>security_policy_info_for_config: build policy JSON from config
  security_policy_info_for_config->>load_and_get_security_policy_info: return JSON
  load_and_get_security_policy_info->>Test: return policy JSON (includes autonomy.max_actions_per_hour)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

working, rust-core

Suggested reviewers

  • graycyrus
  • senamakel

Poem

🐰 A rabbit tips its nose and guards the ground,
Sets env and temp dirs so the bits are sound,
Defaults tucked in, hints and models align,
Symlinks skipped, timeout trimmed down fine,
Tests dance green — the garden's safe and round.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Two unrelated fixes were included to unblock upstream CI failures: struct-literal default spread in ops_tests.rs and timeout expectation in loopbackOauthListener.test.ts. Consider splitting the two unrelated unblock-main fixes into a separate PR to keep the main objective (test coverage) isolated from maintenance fixes.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main change: adding test coverage for the env-overlay path in load_and_get_security_policy_info().
Linked Issues check ✅ Passed All objectives from #2688 are met: direct test added [#2688], =0 edge case covered [#2688], env-mutation serialization pattern used [#2688], and diff coverage requirements met [#2688].
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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


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 May 26 '26 13:05 coderabbitai[bot]

Heads-up: the CI failures on 4a519da8 were inherited from upstream main, not introduced by this PR. Two test files were left stale by recent merges and have been red on every commit since:

  • src/openhuman/config/ops_tests.rs:631 — AutonomySettingsPatch { max_actions_per_hour: Some(64) } is missing 6 fields. The struct derives Default, but the literal didn't spread defaults, so the build fails with E0063 (broken since #2499 / b616f48a).
  • app/src/utils/__tests__/loopbackOauthListener.test.ts:31 — asserts timeoutSecs: 300, but DEFAULT_TIMEOUT_SECS was lowered to 60 in #2690 / c42e2496.

Rather than spin a separate unblock-main PR, I've bundled both one-line fixes into this branch as their own atomic commits (4d757ea, 6737eed) so the same push also unblocks main. Happy to split them out if you'd prefer them tracked separately — let me know.

obchain avatar May 26 '26 14:05 obchain

Addressed both points in b117fa9e:

  • =0 edge case: the test now loops [42, 0], each iteration with a fresh tempdir + env guard, and asserts the budget surfaces in outcome.value["max_actions_per_hour"] for both values. Acceptance criterion #2 of #2688 is now covered end-to-end.
  • Panic-safe restore: replaced the manual prior-value bookkeeping with an inline RAII EnvGuard whose Drop impl restores the prior value unconditionally, so a panicking assertion can no longer leak OPENHUMAN_WORKSPACE / OPENHUMAN_MAX_ACTIONS_PER_HOUR into later tests in the same process.

Updated the PR description to spell out the five ancillary main-unblock fixes — they're each one-line atomic commits, happy to split them into a separate PR if you'd prefer.

Re: CI — agree on the flake diagnosis. envelope_memory_handlers_report_counts_and_statuses panics with memory_init: "disk I/O error" under cargo-llvm-cov's instrumentation but passes in the regular test / Rust Core Tests + Quality job; the Windows secrets ACL job died on sccache: An existing connection was forcibly closed by the remote host. (os error 10054). Both look like infra rather than code. I'll re-run the failed jobs after the new commit triggers fresh runs.

obchain avatar May 26 '26 18:05 obchain

@graycyrus rebased on the latest upstream main (76353792) which folds in #2737 (cargo-llvm-cov flake fix) and the upstream-side test patches for factory_test.rs / memory/chat.rs. The =0 edge case from #2688 is locked in by the [42, 0] loop in b117fa9e (now 76353792). Ready for re-review.

obchain avatar May 27 '26 13:05 obchain

@obchain this PR has merge conflicts with main — please rebase/resolve before review.

graycyrus avatar May 27 '26 19:05 graycyrus

This PR has merge conflicts with main — please rebase/resolve before review.

graycyrus avatar May 27 '26 19:05 graycyrus

@graycyrus rebased on the latest upstream main (145e7680). Clean rebase, no conflicts. New head is c4c58d28.

obchain avatar May 28 '26 09:05 obchain

@graycyrus — gentle ping for re-review.

Quick state recap on this PR:

  • CI: all 32 required checks passing (Rust Core Coverage, Windows secrets ACL, Coverage Gate ≥80%, Linux/macOS/Windows E2E — all green on the current tip c4c58d28).
  • Issue #2688 acceptance criteria: covered by the 4 commits on this branch
    • 263ba637 — env-overlay path coverage
    • d5ccc66f — hint forward-list fix (addressing earlier review feedback on hint:summarization)
    • 88f18ee3 — symlink-skip invariant test rewrite
    • c4c58d28 — =0 edge case with panic-safe env guards
  • Independent review pass (analyzed the full diff today): no further code changes recommended. The EnvGuard set_var pattern is safely callable on the pinned Rust 1.93.0 toolchain (edition 2021); the symlink-skip test rewrite correctly asserts the invariant under the new internal-files listing; the =0 edge case exercises the env-overlay parser at load.rs:1415-1426 cleanly via u32::parse.

The PR is mergeable (mergeStateStatus is just BLOCKED on the sticky CHANGES_REQUESTED review decision from the earlier round). Could you take another look when you have a moment? Happy to address anything else you'd like to see — and happy to defer to a follow-up PR if the scope grows.

sanil-23 avatar May 28 '26 12:05 sanil-23

Follow-up to my earlier re-review ping — independent agent pass on the current tip (c4c58d28) surfaced clear evidence the blocking review is now stale. Sharing in case it helps you skim:

CodeRabbit has explicitly confirmed both of its previously-blocking review threads are resolved, including the bot-machine <review_comment_addressed> marker:

  • security/ops.rs:144 — RAII EnvGuard pattern → bot comment 3305960268:

    confirmed — the EnvGuard RAII pattern in the updated file looks correct. The Drop impl fires unconditionally (including on panics), both OPENHUMAN_WORKSPACE and OPENHUMAN_MAX_ACTIONS_PER_HOUR are guarded, and the loop now also covers the N=0 edge case from #2688. All good!

  • security/ops.rs:161 — =0 env-overlay case → bot comment 3305960223:

    confirmed — the updated test in commit b117fa9e covers both cases. […] using the EnvGuard RAII type with a fresh tempfile::tempdir() per iteration ensures panic-safe env restoration and truly independent test cases, which is strictly better than the manual save/restore loop I proposed.

Local verification on c4c58d28 (post main-merge):

Check Result
cargo fmt --check (core + tauri) pass
cargo check --tests (core + tauri) pass
cargo test openhuman::security::ops 4/4 — incl. load_and_get_security_policy_info_reflects_env_overlay
cargo test openhuman::memory::ops::files 8/8 — incl. list_memory_files_skips_symlink_entries
Remote CI on c4c58d28 all 25 checks SUCCESS

The remaining reviewDecision=CHANGES_REQUESTED appears to be sticky from the earlier round (your blocker review pre-dates CodeRabbit's resolution posts). When you have a moment, would you mind dismissing or updating the review so this can merge? Happy to address anything else if there's a remaining concern I missed.

sanil-23 avatar May 28 '26 12:05 sanil-23