Skip to content

test(security): add integration test for load_and_get_security_policy_info env override#2696

Closed
PranavAgarkar07 wants to merge 1 commit into
tinyhumansai:mainfrom
PranavAgarkar07:pr/2688-security-policy-env-test
Closed

test(security): add integration test for load_and_get_security_policy_info env override#2696
PranavAgarkar07 wants to merge 1 commit into
tinyhumansai:mainfrom
PranavAgarkar07:pr/2688-security-policy-env-test

Conversation

@PranavAgarkar07
Copy link
Copy Markdown
Contributor

@PranavAgarkar07 PranavAgarkar07 commented May 26, 2026

Summary

Adds a focused integration test that exercises the env-var -> config -> RPC payload path through load_and_get_security_policy_info().

Problem

Issue #2688 identifies that the load_and_get_security_policy_info function has no integration test that verifies the full chain: process environment -> Config::load_or_init -> apply_env_overlay -> SecurityPolicy -> JSON-RPC payload.

Solution

Adds load_and_get_security_policy_info_reflects_env_override: sets OPENHUMAN_MAX_ACTIONS_PER_HOUR=42 via process env, calls the real load_and_get_security_policy_info(), and asserts outcome.value[max_actions_per_hour] == 42.

Key design choices:

  • Uses TEST_ENV_LOCK (the project-wide env-mutation serialization primitive) to prevent races with sibling tests.
  • Uses tempfile::tempdir() for workspace isolation so the test is hermetic and CI-safe.
  • Cleans up env vars (OPENHUMAN_WORKSPACE, OPENHUMAN_MAX_ACTIONS_PER_HOUR) in reverse order via remove_var.
  • Async (#[tokio::test]) because load_and_get_security_policy_info is async.
  • Follows the existing pattern from config/ops_tests.rs and composio/bus_tests.rs.

Checklist

  • Tests pass (pre-existing ops_tests.rs::apply_autonomy_settings_updates_action_budget compilation error blocks full cargo test --lib, but cargo check --lib succeeds and the new test logic is structurally equivalent to existing env-mutation patterns)
  • cargo fmt --check passes
  • New test follows project conventions (env lock, tempdir, unsafe set_var)

Closes #2688

Summary by CodeRabbit

  • Tests
    • Added test coverage to verify environment variable overrides function correctly for security policy configuration.

Review Change Stack

…_info env override

Adds a tokio::test that exercises the full chain through
load_config_with_timeout -> Config::load_or_init -> apply_env_overlay
by setting OPENHUMAN_MAX_ACTIONS_PER_HOUR=42 via real process env
and asserting the value propagates into the security_policy_info RPC
payload.

Uses TEST_ENV_LOCK for env-mutation serialization and tempfile for
workspace isolation so the test is hermetic and CI-safe.

Closes tinyhumansai#2688
@PranavAgarkar07 PranavAgarkar07 requested a review from a team May 26, 2026 13:51
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 26, 2026

📝 Walkthrough

Walkthrough

This PR adds a single async integration test to src/openhuman/security/ops.rs that verifies the full chain from environment variables through config loading to security policy generation, ensuring that OPENHUMAN_MAX_ACTIONS_PER_HOUR overrides are correctly reflected in the returned JSON payload.

Changes

Environment Override Integration Test

Layer / File(s) Summary
Environment override reflection test
src/openhuman/security/ops.rs
New async Tokio test load_and_get_security_policy_info_reflects_env_override validates that setting OPENHUMAN_MAX_ACTIONS_PER_HOUR=42 in the environment results in the security policy JSON containing max_actions_per_hour: 42. Uses the test environment lock for serialization, creates a temporary workspace, sets the env var, invokes load_and_get_security_policy_info(), asserts the value, and cleans up to maintain test isolation.

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A test hops in with lock in paw,
Sets the hour limit to forty-two,
Through config paths it skips with glee,
And verifies what it should do!
Env vars tamed, the test is clean. 🔐✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR partially meets acceptance criteria. It adds a test for env override [#2688], but does not include a test for the =0 edge case as required by the acceptance criteria. Add a second test case that verifies OPENHUMAN_MAX_ACTIONS_PER_HOUR=0 surfaces as zero in the RPC payload to satisfy the =0 edge case requirement.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding an integration test for load_and_get_security_policy_info that verifies environment variable overrides.
Out of Scope Changes check ✅ Passed The changes are narrowly focused on adding the integration test requested in #2688 with no out-of-scope modifications detected.
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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openhuman/security/ops.rs`:
- Around line 109-123: The test sets OPENHUMAN_WORKSPACE and
OPENHUMAN_MAX_ACTIONS_PER_HOUR but only removes them after assertions, so
failures leak env state; create a small drop guard (e.g., struct EnvGuard) that
captures the names (and optionally the previous values) and implements Drop to
remove/restore OPENHUMAN_WORKSPACE and OPENHUMAN_MAX_ACTIONS_PER_HOUR, then
instantiate that guard immediately after setting the env vars in the test in
src/openhuman/security/ops.rs so load_and_get_security_policy_info() can run and
the guard’s Drop will always run even if the test panics.
- Around line 98-124: The test
load_and_get_security_policy_info_reflects_env_override only asserts the 42
case; add a second edge-case assertion for OPENHUMAN_MAX_ACTIONS_PER_HOUR=0 by
setting the env var to "0", calling load_and_get_security_policy_info() again,
and asserting outcome.value["max_actions_per_hour"] equals serde_json::json!(0);
keep using the same TEST_ENV_LOCK and ensure you remove the env vars in the
existing cleanup block (or restore previous values) to avoid leaking the 0
override.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c5002d39-09d9-41bc-9aa3-4e7f2047dcff

📥 Commits

Reviewing files that changed from the base of the PR and between 87f8ef4 and 9b4e37a.

📒 Files selected for processing (1)
  • src/openhuman/security/ops.rs

Comment on lines +98 to +124
#[tokio::test]
async fn load_and_get_security_policy_info_reflects_env_override() {
// Serializes env-mutation with sibling tests that touch
// OPENHUMAN_WORKSPACE or OPENHUMAN_MAX_ACTIONS_PER_HOUR.
let _lock = crate::openhuman::config::TEST_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());

let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path().to_str().unwrap().to_string();

unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
}

let outcome = load_and_get_security_policy_info()
.await
.expect("load_and_get_security_policy_info should succeed");

assert_eq!(outcome.value["max_actions_per_hour"], serde_json::json!(42));

unsafe {
std::env::remove_var("OPENHUMAN_WORKSPACE");
std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add the missing OPENHUMAN_MAX_ACTIONS_PER_HOUR=0 edge-case assertion.

The linked issue acceptance criteria explicitly asks to verify the zero-value path as well. This test currently validates only 42, so the requested regression guard is still incomplete.

Suggested addition
 #[tokio::test]
 async fn load_and_get_security_policy_info_reflects_env_override() {
@@
     assert_eq!(outcome.value["max_actions_per_hour"], serde_json::json!(42));
+
+    unsafe {
+        std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "0");
+    }
+    let zero_outcome = load_and_get_security_policy_info()
+        .await
+        .expect("load_and_get_security_policy_info should succeed for zero override");
+    assert_eq!(
+        zero_outcome.value["max_actions_per_hour"],
+        serde_json::json!(0)
+    );
@@
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[tokio::test]
async fn load_and_get_security_policy_info_reflects_env_override() {
// Serializes env-mutation with sibling tests that touch
// OPENHUMAN_WORKSPACE or OPENHUMAN_MAX_ACTIONS_PER_HOUR.
let _lock = crate::openhuman::config::TEST_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path().to_str().unwrap().to_string();
unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
}
let outcome = load_and_get_security_policy_info()
.await
.expect("load_and_get_security_policy_info should succeed");
assert_eq!(outcome.value["max_actions_per_hour"], serde_json::json!(42));
unsafe {
std::env::remove_var("OPENHUMAN_WORKSPACE");
std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
}
}
#[tokio::test]
async fn load_and_get_security_policy_info_reflects_env_override() {
// Serializes env-mutation with sibling tests that touch
// OPENHUMAN_WORKSPACE or OPENHUMAN_MAX_ACTIONS_PER_HOUR.
let _lock = crate::openhuman::config::TEST_ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path().to_str().unwrap().to_string();
unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
}
let outcome = load_and_get_security_policy_info()
.await
.expect("load_and_get_security_policy_info should succeed");
assert_eq!(outcome.value["max_actions_per_hour"], serde_json::json!(42));
unsafe {
std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "0");
}
let zero_outcome = load_and_get_security_policy_info()
.await
.expect("load_and_get_security_policy_info should succeed for zero override");
assert_eq!(
zero_outcome.value["max_actions_per_hour"],
serde_json::json!(0)
);
unsafe {
std::env::remove_var("OPENHUMAN_WORKSPACE");
std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openhuman/security/ops.rs` around lines 98 - 124, The test
load_and_get_security_policy_info_reflects_env_override only asserts the 42
case; add a second edge-case assertion for OPENHUMAN_MAX_ACTIONS_PER_HOUR=0 by
setting the env var to "0", calling load_and_get_security_policy_info() again,
and asserting outcome.value["max_actions_per_hour"] equals serde_json::json!(0);
keep using the same TEST_ENV_LOCK and ensure you remove the env vars in the
existing cleanup block (or restore previous values) to avoid leaking the 0
override.

Comment on lines +109 to +123
unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
}

let outcome = load_and_get_security_policy_info()
.await
.expect("load_and_get_security_policy_info should succeed");

assert_eq!(outcome.value["max_actions_per_hour"], serde_json::json!(42));

unsafe {
std::env::remove_var("OPENHUMAN_WORKSPACE");
std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make env cleanup panic-safe to prevent cross-test contamination.

Right now cleanup only runs at Line 120 after assertions. If the test fails earlier, OPENHUMAN_WORKSPACE / OPENHUMAN_MAX_ACTIONS_PER_HOUR can leak and cause flaky follow-up tests. Use a drop guard so cleanup always executes.

Suggested fix
 #[tokio::test]
 async fn load_and_get_security_policy_info_reflects_env_override() {
@@
-    unsafe {
-        std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
-        std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
-    }
+    struct EnvCleanup;
+    impl Drop for EnvCleanup {
+        fn drop(&mut self) {
+            unsafe {
+                std::env::remove_var("OPENHUMAN_WORKSPACE");
+                std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
+            }
+        }
+    }
+    let _cleanup = EnvCleanup;
+
+    unsafe {
+        std::env::set_var("OPENHUMAN_WORKSPACE", &workspace);
+        std::env::set_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR", "42");
+    }
@@
-    unsafe {
-        std::env::remove_var("OPENHUMAN_WORKSPACE");
-        std::env::remove_var("OPENHUMAN_MAX_ACTIONS_PER_HOUR");
-    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openhuman/security/ops.rs` around lines 109 - 123, The test sets
OPENHUMAN_WORKSPACE and OPENHUMAN_MAX_ACTIONS_PER_HOUR but only removes them
after assertions, so failures leak env state; create a small drop guard (e.g.,
struct EnvGuard) that captures the names (and optionally the previous values)
and implements Drop to remove/restore OPENHUMAN_WORKSPACE and
OPENHUMAN_MAX_ACTIONS_PER_HOUR, then instantiate that guard immediately after
setting the env vars in the test in src/openhuman/security/ops.rs so
load_and_get_security_policy_info() can run and the guard’s Drop will always run
even if the test panics.

Copy link
Copy Markdown
Contributor

@graycyrus graycyrus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good test — exercises the right env → config → RPC chain and follows the project's serialization pattern (TEST_ENV_LOCK, tempdir isolation). The approach is sound.

However, CI is red on this PR and I've got a couple of blocking issues to sort out before we can land it.

Change summary

File What changed
src/openhuman/security/ops.rs New integration test load_and_get_security_policy_info_reflects_env_override — sets OPENHUMAN_MAX_ACTIONS_PER_HOUR=42 via env, calls load_and_get_security_policy_info(), asserts the value flows through.

Findings

Severity File Issue
major ops.rs CI red — Rust Core Tests + Quality fails. Test never verified to pass.
major ops.rs Missing =0 edge case required by issue #2688 (CodeRabbit flagged — see their inline comment for the fix)
minor ops.rs:109-123 Env cleanup isn't panic-safe (CodeRabbit flagged — drop guard suggestion is the right fix)

Fix the CI issue (or demonstrate the new test passes in isolation), add the =0 assertion, and adopt the drop guard pattern — then this is good to go.


assert_eq!(outcome.value["max_actions_per_hour"], json!(77));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[major] The test / Rust Core Tests + Quality CI job fails, and your own checklist notes a pre-existing compilation error in apply_autonomy_settings_updates_action_budget blocks cargo test --lib. That means this test was never actually verified to pass.

I need one of:

  1. Fix the pre-existing compilation error in this PR (preferred — you're already in this file), or
  2. Show output from cargo test --lib -p openhuman -- load_and_get_security_policy_info_reflects_env_override proving the new test passes when run in isolation.

Shipping an unverified test defeats the purpose of the issue.

@graycyrus
Copy link
Copy Markdown
Contributor

@PranavAgarkar07 unresolved review feedback — please address before we review.

@graycyrus
Copy link
Copy Markdown
Contributor

Unresolved review feedback from coderabbitai[bot] — please address before we review.

Copy link
Copy Markdown
Contributor

@graycyrus graycyrus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I already reviewed this on May 26 and flagged three issues that need to be addressed:

[major] CI is still red — Rust Core Tests + Quality fails due to a pre-existing compilation error in a sibling test. The new test itself was never verified to pass. You'll need to fix the upstream error first before this can merge.

[major] Missing =0 edge case — Issue #2688 acceptance criteria require a test that verifies the behavior when OPENHUMAN_MAX_ACTIONS_PER_HOUR=0. This test only checks the happy path (=42). Add an assertion for the zero case.

[minor] Env cleanup not panic-safe — The remove_var calls at lines 127-128 won't run if an assertion panics above them. Use a drop guard pattern or a finally-equivalent to ensure cleanup always runs.

Please address these three items and push a new commit. I'll re-review once CI is green and all feedback is incorporated.

@oxoxDev oxoxDev assigned oxoxDev and unassigned oxoxDev May 28, 2026
@sanil-23
Copy link
Copy Markdown
Contributor

Closing as superseded by #2695 for issue #2688.

Both PRs add a test for load_and_get_security_policy_info, but #2695 covers more ground (env-overlay path, =0 edge case with panic-safe env guards, and two tangent test-stability fixes) and currently has all CI checks green — this PR is showing failures on Rust Core Coverage, Rust Core Tests + Quality, Frontend Coverage, and Windows secrets ACL.

Thanks for the contribution! If there's a piece of coverage in this branch that #2695 doesn't capture, happy to look at a follow-up scoped to that delta.

@sanil-23 sanil-23 closed this May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add direct integration test for load_and_get_security_policy_info

4 participants