Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion app/scripts/e2e-run-session.sh
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ trap cleanup EXIT
export VITE_BACKEND_URL="http://127.0.0.1:${E2E_MOCK_PORT}"
export BACKEND_URL="http://127.0.0.1:${E2E_MOCK_PORT}"
export OPENHUMAN_E2E_MODE="1"
# Sign-in stores the session through TinySecurity's keyring, which asks the
# user to approve each operation; the e2e-test-support app answers for them.
export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}"
export APPIUM_PORT
# Redirect Telegram Bot API calls to the mock server during E2E runs.
# The mock server (WS-A) serves /bot<token>/* routes on the same port as the
Expand Down Expand Up @@ -382,7 +385,7 @@ if [ "$OS" = "Linux" ] && [ "${E2E_USE_TAURI_DRIVER:-0}" = "1" ]; then
OPENHUMAN_TINYMCP_TEST_MODULE OPENHUMAN_CEF_CACHE_PATH \
OPENHUMAN_SERVICE_MOCK OPENHUMAN_SERVICE_MOCK_STATE_FILE \
OPENHUMAN_TELEGRAM_BOT_API_BASE OPENHUMAN_COMPOSIO_DIRECT_BASE_V2 \
OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 XDG_DATA_HOME; do
OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 OPENHUMAN_TEST_KEYRING_CONSENT XDG_DATA_HOME; do
if declare -p "$env_name" >/dev/null 2>&1; then
printf 'export %s=%q\n' "$env_name" "${!env_name}"
fi
Expand Down
3 changes: 3 additions & 0 deletions app/scripts/e2e-web-session.sh
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ export OPENHUMAN_CORE_TOKEN="$PW_CORE_RPC_TOKEN"
# disclosure choreography. Advertise the compiled tool packs for this harness
# core only; production hosts retain the fail-closed packed default.
export OPENHUMAN_E2E=1
# Sign-in stores the session through TinySecurity's keyring, which asks the
# user to approve each operation; the e2e-test-support core answers for them.
export OPENHUMAN_TEST_KEYRING_CONSENT="${OPENHUMAN_TEST_KEYRING_CONSENT:-approve}"
# The skills registry defaults to a public HermesHub fetch. The browser E2E
# lane must remain deterministic and offline, so serve its compact catalog
# fixture from the local mock backend instead. The registry's fetch guard
Expand Down
42 changes: 40 additions & 2 deletions app/src/hooks/useKeyringOperationApprovals.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { useKeyringOperationApprovals } from './useKeyringOperationApprovals';

Expand All @@ -16,7 +16,10 @@ const off = vi.hoisted(() =>
handlers.get(event)?.delete(cb);
})
);
vi.mock('../services/socketService', () => ({ socketService: { on, off } }));
const isConnected = vi.hoisted(() => vi.fn(() => true));
vi.mock('../services/socketService', () => ({ socketService: { on, off, isConnected } }));
const listPending = vi.hoisted(() => vi.fn(async (): Promise<unknown[]> => []));
vi.mock('../services/keyringApi', () => ({ listPendingKeyringOperations: listPending }));

const EVENTS = ['keyring:access_approval_requested', 'keyring_access_approval_requested'];
const REQUEST = {
Expand All @@ -42,6 +45,12 @@ describe('useKeyringOperationApprovals', () => {
handlers.clear();
on.mockClear();
off.mockClear();
isConnected.mockReset().mockReturnValue(true);
listPending.mockReset().mockResolvedValue([]);
});

afterEach(() => {
vi.useRealTimers();
});

it('subscribes to both Socket.IO aliases', () => {
Expand Down Expand Up @@ -88,4 +97,33 @@ describe('useKeyringOperationApprovals', () => {
expect(off).toHaveBeenCalledWith(event, expect.any(Function));
}
});

it('asks the core for pending requests while no socket is connected', async () => {
vi.useFakeTimers();
isConnected.mockReturnValue(false);
listPending.mockResolvedValue([REQUEST]);
const { result } = renderHook(() => useKeyringOperationApprovals());

await act(async () => {
await vi.advanceTimersByTimeAsync(1_000);
});

expect(listPending).toHaveBeenCalled();
expect(result.current.requests).toEqual([REQUEST]);

// The same request arriving over the socket later is not shown twice.
emit(REQUEST);
expect(result.current.requests).toEqual([REQUEST]);
});

it('does not poll once the socket is connected', async () => {
vi.useFakeTimers();
renderHook(() => useKeyringOperationApprovals());

await act(async () => {
await vi.advanceTimersByTimeAsync(3_000);
});

expect(listPending).not.toHaveBeenCalled();
});
});
18 changes: 18 additions & 0 deletions app/src/hooks/useKeyringOperationApprovals.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { useCallback, useEffect, useState } from 'react';

import { listPendingKeyringOperations } from '../services/keyringApi';
import { socketService } from '../services/socketService';

const EVENT_COLON = 'keyring:access_approval_requested';
const EVENT_UNDERSCORE = 'keyring_access_approval_requested';
/** How often to ask the core for pending requests while no socket is connected. */
const POLL_INTERVAL_MS = 1_000;

export type KeyringOperationAccess = 'read' | 'write' | 'delete';

Expand Down Expand Up @@ -68,10 +71,25 @@ export function useKeyringOperationApprovals(): {
const now = Date.now();
setRequests(current => current.filter(request => request.expires_at_ms > now));
}, 1_000);
// The socket connects only once a session exists, so a keyring write made
// while signing in would never be shown. Until it connects, ask the core.
let polling = false;
const pollTimer = window.setInterval(() => {
if (polling || socketService.isConnected()) return;
polling = true;
listPendingKeyringOperations()
.then(pending => pending.forEach(handleRequest))
// A failed poll is retried on the next tick.
.catch(() => undefined)
.finally(() => {
polling = false;
});
}, POLL_INTERVAL_MS);
return () => {
socketService.off(EVENT_COLON, handleRequest);
socketService.off(EVENT_UNDERSCORE, handleRequest);
window.clearInterval(expiryTimer);
window.clearInterval(pollTimer);
};
}, [handleRequest]);

Expand Down
13 changes: 13 additions & 0 deletions app/src/services/__tests__/keyringApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
decideKeyringConsent,
fetchKeyringStatus,
listPendingKeyringOperations,
respondToKeyringOperation,
retryKeyringProbe,
} from '../keyringApi';
Expand Down Expand Up @@ -55,4 +56,16 @@ describe('keyringApi', () => {
params: { request_id: 'request-1', approved: true },
});
});

it('lists pending keyring operations and tolerates a non-array result', async () => {
const pending = [{ request_id: 'request-1' }];
mockRpc.mockResolvedValueOnce({ result: pending });
await expect(listPendingKeyringOperations()).resolves.toEqual(pending);
expect(mockRpc).toHaveBeenCalledWith({
method: 'openhuman.keyring_consent_list_pending_operations',
});

mockRpc.mockResolvedValueOnce({ result: null });
await expect(listPendingKeyringOperations()).resolves.toEqual([]);
});
});
11 changes: 11 additions & 0 deletions app/src/services/keyringApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,14 @@ export const respondToKeyringOperation = async (
params: { request_id: requestId, approved },
});
};

/**
* Keyring operations waiting for approval. The renderer polls this when it has
* no socket yet (before sign-in), so the approval prompt still reaches it.
*/
export const listPendingKeyringOperations = async (): Promise<unknown[]> => {
const response = await callCoreRpc<{ result: unknown }>({
method: 'openhuman.keyring_consent_list_pending_operations',
});
return Array.isArray(response.result) ? response.result : [];
};
4 changes: 3 additions & 1 deletion crates/openhuman-app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 21 additions & 1 deletion crates/openhuman-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ name = "security_native_fixture"
path = "../../tests/security_native_fixture.rs"
required-features = ["security-module"]

[[test]]
# TinySecurity from a pinned release (no local-file source) serves later loads.
name = "security_release_reuse_fixture"
path = "../../tests/security_release_reuse_fixture.rs"
required-features = ["security-module"]

[[test]]
# Callback-bound modules from a pinned release (no local-file source) load and reload.
name = "callback_module_release_fixture"
path = "../../tests/callback_module_release_fixture.rs"
required-features = ["security-module"]

[[test]]
# Desktop sign-in stores its token through TinySecurity's OS keyring after approval.
name = "desktop_sign_in_fixture"
path = "../../tests/desktop_sign_in_fixture.rs"
required-features = ["security-module"]

[[test]]
# Loads tinydocs from the linked executable and calls GenerateDocx end to end.
# `scripts/test-rust-e2e.sh --suite tinydocs_linked_e2e` enables its local-only
Expand Down Expand Up @@ -478,7 +496,9 @@ uuid = { version = "1", features = ["v4"] }
# the library crates' own manifests (`default-features = false`; the gates come
# from this crate's features through `openhuman-rpc`), so the dev graphs unify
# and `cargo test -p` reuses one core build.
openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false }
# `test-keyring-consent` answers the credential store's keyring prompts in the
# in-process tests; dev-dependency features never reach the shipped binary.
openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false, features = ["test-keyring-consent"] }
openhuman-embed = { workspace = true }
openhuman-tinyhumans = { workspace = true }
tinymemory-tools = { path = "../../vendor/tinymemory/crates/tinymemory-tools" }
Expand Down
4 changes: 4 additions & 0 deletions crates/openhuman-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,10 @@ channels = ["modules"]
# build (app/scripts/e2e-build.sh) flips it on. Shipped binaries never have
# this feature so the wipe RPC isn't even registered, let alone reachable.
e2e-test-support = []
# Answers the credential store's keyring prompts in the in-process integration
# tests (`OPENHUMAN_TEST_KEYRING_CONSENT`). Only the CLI's core dev-dependency
# enables it; no product build or default may (check-feature-forwarding.mjs).
test-keyring-consent = []
# Library-side gate for the embedded-RSS benchmark (#5046): the one prompt
# renderer hook in `agent/prompts/render_helpers` (and the mock provider) that
# the benchmark bins need. Default-OFF and absent from
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl Drop for NativeSecurityAudit {
fn drop(&mut self) {
if !self.recorded {
self.record(
crate::security::approval::ExecutionOutcome::Failure,
crate::security::approval::ExecutionOutcome::Aborted,
Some("tool execution ended before reporting a result".to_string()),
);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/openhuman-core/src/artifacts/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ pub(crate) async fn resolve_file(
Ok(file)
}

async fn check_protected_artifact_path(path: &Path) -> Result<(), String> {
pub(super) async fn check_protected_artifact_path(path: &Path) -> Result<(), String> {
if SecurityPolicy::is_always_forbidden_async(path).await {
return Err("[artifacts] file is in a protected location".into());
}
Expand Down
4 changes: 4 additions & 0 deletions crates/openhuman-core/src/artifacts/production_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,12 @@ async fn a_completion_that_records_nothing_fails_the_record_too() {
}

#[cfg(unix)]
#[cfg(feature = "security-module")]
#[tokio::test]
async fn a_saved_version_the_card_cannot_show_succeeds_and_says_so() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
use std::os::unix::fs::PermissionsExt;

// The CI container runs as root, which bypasses the file mode bits used
Expand Down
19 changes: 11 additions & 8 deletions crates/openhuman-core/src/artifacts/tiny_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,7 @@ async fn import_legacy_file(
legacy: &FileRef,
key: &str,
) -> anyhow::Result<FileRef> {
let source = roots.resolve(&legacy.key).await?;
let bytes = tokio::fs::read(&source.path).await?;
let (source, bytes) = roots.read(&legacy.key).await?;
let media_type = legacy
.media_type
.as_deref()
Expand Down Expand Up @@ -306,11 +305,10 @@ impl LegacyUiBridge {
if let Some(file) = latest.file.as_ref() {
self.write_file_version(file, &dest).await?
} else {
let source = self.source_roots.resolve(&latest.body).await?;
let (source, bytes) = self.source_roots.read(&latest.body).await?;
if same_file(&source.path, &dest) {
tokio::fs::metadata(&dest).await?.len()
} else {
let bytes = tokio::fs::read(&source.path).await?;
self.write_visible_file(&dest, &bytes, source.media_type.as_deref())
.await?
}
Expand Down Expand Up @@ -460,11 +458,16 @@ fn contains(folder: &Path, inside: &Path) -> bool {
canon(inside).starts_with(canon(folder))
}

/// [`file_roots`] as the crate's folders. Protected-path policy is checked in
/// the async artifact resolver through TinySecurity; this synchronous adapter
/// carries only the trusted-root list.
/// [`file_roots`] as the crate's folders, guarded by TinySecurity's
/// protected-path policy. The crate runs the guard on the canonical path and
/// keeps that file open while it reads, so a protected file's bytes are never
/// read and a swapped path cannot be read in its place.
pub fn guarded_roots(roots: Vec<PathBuf>) -> tiny_artifacts::FileRoots {
tiny_artifacts::FileRoots::new(roots)
tiny_artifacts::FileRoots::new(roots).with_async_guard(|path| async move {
super::files::check_protected_artifact_path(&path)
.await
.err()
})
}

/// The artifact service for one workspace: OpenHuman's store and UI bridge,
Expand Down
Loading
Loading