Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 7 additions & 0 deletions crates/openhuman-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ name = "security_native_fixture"
path = "../../tests/security_native_fixture.rs"
required-features = ["security-module"]

[[test]]
# TinyComputer end to end with its staged release (TS-E2E-010); each test runs
# by exact name after scripts/ci/ts-e2e-stage-modules.sh.
name = "ts_e2e_tinycomputer"
path = "../../tests/ts_e2e_tinycomputer.rs"
required-features = ["security-module"]

[[test]]
# TinySecurity from a pinned release (no local-file source) serves later loads.
name = "security_release_reuse_fixture"
Expand Down
82 changes: 56 additions & 26 deletions crates/openhuman-core/src/modules/browser_egress_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,32 @@ fn registered_scopes() -> &'static parking_lot::Mutex<Vec<BrowserScope>> {
SCOPES.get_or_init(|| parking_lot::Mutex::new(Vec::new()))
}

/// Register the browser's destination-only policy from the authenticated host
/// context and return the immutable id and generation for TinyComputer config.
/// The policy id and generation TinyComputer's config names. TinyBus fixes a
/// callback-bound module's config when it loads and refuses any change, while
/// the TinySecurity policy behind it is re-registered every
/// [`BROWSER_POLICY_REFRESH_AFTER`]. So the config carries this stable alias,
/// and each callback maps it to the current policy.
pub(crate) const BROWSER_POLICY_ALIAS: &str = "openhuman-browser-egress";
pub(crate) const BROWSER_POLICY_ALIAS_GENERATION: u64 = 1;

/// The `browser.egress` value TinyComputer is loaded and refreshed with.
pub(crate) fn browser_dial_alias() -> Value {
serde_json::json!({
"policy_id": BROWSER_POLICY_ALIAS,
"generation": BROWSER_POLICY_ALIAS_GENERATION,
})
}

/// Make sure the browser's destination-only policy is registered for this
/// host context, then return the stable alias for TinyComputer config.
pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Result<Value, String> {
current_browser_policy(config).await?;
Ok(browser_dial_alias())
}

/// The id and generation of the current browser policy, registering a new one
/// when the cached registration is stale.
async fn current_browser_policy(config: &crate::config::Config) -> Result<(String, u64), String> {
let client = super::security::client(config)
.await
.map_err(|error| error.to_string())?;
Expand Down Expand Up @@ -63,10 +86,7 @@ pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Resul
&privacy_key,
std::time::Instant::now(),
) {
return Ok(serde_json::json!({
"policy_id": id,
"generation": generation,
}));
return Ok((id.to_owned(), generation));
}
}
let registered_at = std::time::Instant::now();
Expand Down Expand Up @@ -105,10 +125,7 @@ pub(crate) async fn browser_dial_config(config: &crate::config::Config) -> Resul
if scopes.len() > 64 {
scopes.remove(0);
}
Ok(serde_json::json!({
"policy_id": policy_id.0,
"generation": info.generation,
}))
Ok((policy_id.0, info.generation))
}

fn find_reusable_policy<'a>(
Expand Down Expand Up @@ -143,11 +160,8 @@ fn find_reusable_policy<'a>(
.map(|(id, generation, ..)| (id.as_str(), *generation))
}

fn is_registered(policy_id: &str, generation: u64) -> bool {
registered_scopes()
.lock()
.iter()
.any(|(id, current, ..)| id == policy_id && *current == generation)
fn is_alias(policy_id: &str, generation: u64) -> bool {
policy_id == BROWSER_POLICY_ALIAS && generation == BROWSER_POLICY_ALIAS_GENERATION
}

#[derive(Clone)]
Expand Down Expand Up @@ -193,28 +207,32 @@ impl ConsequenceReviewHost {
#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")]
impl BrowserEgressHost {
async fn authorize(&self, target: BrowserEgressTarget) -> tinybus::Result<BrowserEgressGrant> {
if !is_registered(&target.policy_id, target.expected_generation) {
if !is_alias(&target.policy_id, target.expected_generation) {
return Err(refused());
}
let config = crate::core::runtime::DispatchCtx::ambient()
.load_config()
.await
.map_err(|_| refused())?;
let (policy_id, generation) = current_browser_policy(&config).await.map_err(|error| {
tracing::debug!(%error, "[computer] browser egress policy unavailable for a dial");
refused()
})?;
let client = super::security::client(&config)
.await
.map_err(|_| refused())?;
let response = client
.authorize_browser_dial(tinysecurity_bus::BrowserDialRequest {
policy_id: tinysecurity_bus::EgressPolicyId(target.policy_id),
expected_generation: target.expected_generation,
policy_id: tinysecurity_bus::EgressPolicyId(policy_id),
expected_generation: generation,
session_id: target.session_id,
scheme: target.scheme,
hostname: target.hostname,
port: target.port,
})
.await
.map_err(|_| refused())?;
if response.generation != target.expected_generation {
if response.generation != generation {
return Err(refused());
}
let authorization = response.authorization.ok_or_else(refused)?;
Expand All @@ -227,8 +245,10 @@ impl BrowserEgressHost {
.map(ToString::to_string)
.collect();
let authorization = serde_json::to_string(&authorization).map_err(|_| refused())?;
// TinyComputer checks the grant against the generation its config
// names, which is the alias's.
Ok(BrowserEgressGrant {
generation: response.generation,
generation: BROWSER_POLICY_ALIAS_GENERATION,
authorization,
addresses,
})
Expand All @@ -241,9 +261,10 @@ impl BrowserEgressHost {
let client = security_client().await?;
let authorization = decode_browser_authorization(&request.authorization)?;
let address = request.address.parse().map_err(|_| refused())?;
let request_target = browser_request(request.target, &authorization)?;
let allowed = client
.consume_browser_dial(tinysecurity_bus::ConsumeBrowserDialRequest {
request: browser_request(request.target),
request: request_target,
address,
authorization,
})
Expand Down Expand Up @@ -276,15 +297,24 @@ async fn security_client() -> tinybus::Result<super::security::Client> {
.map_err(|_| refused())
}

fn browser_request(target: BrowserEgressTarget) -> tinysecurity_bus::BrowserDialRequest {
tinysecurity_bus::BrowserDialRequest {
policy_id: tinysecurity_bus::EgressPolicyId(target.policy_id),
expected_generation: target.expected_generation,
/// The TinySecurity request for an aliased target: the policy the grant was
/// issued under, which the authorization records, since the current policy
/// may have rotated since.
fn browser_request(
target: BrowserEgressTarget,
authorization: &tinysecurity_bus::BrowserDialAuthorization,
) -> tinybus::Result<tinysecurity_bus::BrowserDialRequest> {
if !is_alias(&target.policy_id, target.expected_generation) {
return Err(refused());
}
Ok(tinysecurity_bus::BrowserDialRequest {
policy_id: authorization.policy_id.clone(),
expected_generation: authorization.generation,
session_id: target.session_id,
scheme: target.scheme,
hostname: target.hostname,
port: target.port,
}
})
}

fn decode_browser_authorization(
Expand Down
46 changes: 46 additions & 0 deletions crates/openhuman-core/src/modules/browser_egress_host_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,49 @@ async fn browser_egress_callback_refuses_unknown_host_registered_scope() {
.await;
assert!(result.is_err());
}

fn authorization(policy_id: &str, generation: u64) -> tinysecurity_bus::BrowserDialAuthorization {
tinysecurity_bus::BrowserDialAuthorization {
authorization_id: "lease-1".into(),
session_id: "browser-session-test".into(),
scheme: "https".into(),
hostname: "8.8.8.8".into(),
port: 443,
addresses: vec!["8.8.8.8:443".parse().unwrap()],
subject: tinysecurity_bus::SubjectScope {
user: "user-1".into(),
workspace: "workspace-1".into(),
agent: "agent-1".into(),
},
policy_id: tinysecurity_bus::EgressPolicyId(policy_id.into()),
generation,
expires_at_ms: 1,
}
}

#[test]
fn the_config_names_a_stable_alias_not_the_rotating_policy() {
// TinyBus fixes TinyComputer's config at load; a policy id in it would
// change at the first re-registration and every refresh would be refused.
let alias = browser_dial_alias();
assert_eq!(alias["policy_id"], BROWSER_POLICY_ALIAS);
assert_eq!(alias["generation"], BROWSER_POLICY_ALIAS_GENERATION);
assert_eq!(alias, browser_dial_alias());
}

#[test]
fn a_consumed_lease_is_checked_against_the_policy_it_was_issued_under() {
let mut aliased = target(BROWSER_POLICY_ALIAS);
aliased.expected_generation = BROWSER_POLICY_ALIAS_GENERATION;
let request = browser_request(aliased, &authorization("policy-real-7", 9)).unwrap();
assert_eq!(request.policy_id.0, "policy-real-7");
assert_eq!(request.expected_generation, 9);
}

#[test]
fn a_target_that_does_not_name_the_alias_is_refused() {
assert!(browser_request(target("policy-real-7"), &authorization("policy-real-7", 9)).is_err());
let mut stale = target(BROWSER_POLICY_ALIAS);
stale.expected_generation = BROWSER_POLICY_ALIAS_GENERATION + 1;
assert!(browser_request(stale, &authorization("policy-real-7", 9)).is_err());
}
5 changes: 4 additions & 1 deletion crates/openhuman-core/src/modules/desktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@ pub(crate) async fn proxy(config: &Config) -> Result<Proxy, String> {
.map_err(|error| format!("TinyComputer module proxy unavailable: {error}"))
}

fn inject_security_browser_config(
/// Add the security callbacks to TinyComputer's config. The callback-bound
/// load and every refresh in [`proxy`] go through here, so both produce the
/// same bytes and TinyBus accepts the refresh.
pub(super) fn inject_security_browser_config(
configuration: &mut serde_json::Value,
egress: serde_json::Value,
callback_destination: &str,
Expand Down
22 changes: 22 additions & 0 deletions crates/openhuman-core/src/modules/desktop_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,25 @@ fn registry_and_contract_address_agree() {
assert_eq!(record.bus_name, names::INTERFACE);
assert_eq!(record.object_path, names::OBJECT_PATH);
}

#[cfg(feature = "security-module")]
#[tokio::test]
async fn the_callback_bound_load_config_is_what_every_refresh_pushes() {
// TS-E2E-010: TinyBus fixes a callback-bound module's config at load and
// refuses a refresh with different bytes ("scoped callback configuration is
// immutable"), so the load config must already carry `browser.egress`.
let dir = tempfile::tempdir().expect("tempdir");
let config = config_in(dir.path());
let loaded = crate::modules::ops::computer_callback_config(&config, MODULE_ID, ":1.42").await;

let mut refreshed = module_config(&config).await;
inject_security_browser_config(
&mut refreshed,
crate::modules::browser_egress_host::browser_dial_alias(),
":1.42",
);

assert_eq!(loaded, refreshed);
assert_eq!(fingerprint(&loaded), fingerprint(&refreshed));
assert!(loaded["browser"]["egress"].is_object());
}
19 changes: 17 additions & 2 deletions crates/openhuman-core/src/modules/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,10 +358,25 @@ async fn module_config_with_consequence_callback(
config: &Config,
id: &str,
binding: &tinybus::module::HostCallbackBinding,
) -> serde_json::Value {
computer_callback_config(config, id, binding.unique_name().as_str()).await
}

/// TinyComputer's config at its callback-bound load: exactly what
/// `desktop::proxy` pushes before each call, since TinyBus refuses a
/// callback-bound module any config that differs from the one it loaded with.
#[cfg(feature = "security-module")]
pub(super) async fn computer_callback_config(
config: &Config,
id: &str,
callback_destination: &str,
) -> serde_json::Value {
let mut module_config = module_config(config, id).await;
module_config["consequence_host"] =
serde_json::json!({ "destination": binding.unique_name().as_str() });
super::desktop::inject_security_browser_config(
&mut module_config,
super::browser_egress_host::browser_dial_alias(),
callback_destination,
);
module_config
}

Expand Down
101 changes: 101 additions & 0 deletions scripts/ci/ts-e2e-stage-modules.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# Stage registry-pinned module releases for the TinySecurity E2E fixtures (TS-E2E X6).
#
# Usage: source scripts/ci/ts-e2e-stage-modules.sh [id,...]
# default ids: tinysecurity,tinycomputer,tinyconnectors,tinybox,tinyflows
#
# Each archive is downloaded from the URL the compiled registry pins, checked
# against its sha256, and laid out the way an installer bundle is
# (`<dir>/<id>/<version>/<host_key>/`, as security-native-fixture.sh does), so
# callback-bound modules load through the shipped release path.
#
# Exports:
# OPENHUMAN_BUNDLED_MODULES the bundle directory
# OPENHUMAN_TS_E2E_MODULES comma list of the ids that can load on this runner
# A Linux module linking a system library the runner lacks (TinyComputer needs
# libxdo and libasound) is left out of OPENHUMAN_TS_E2E_MODULES with a message;
# tests that need it fail with that reason instead of a dlopen error.
#
# Staging runs in a subshell with strict options, so sourcing leaves the
# caller's shell options alone; only the two exports come back. Any failure
# (an unresolvable module, a download or digest error) exports nothing and
# makes `source` return nonzero, with the reason on stderr.

ts_e2e_stage() (
set -euo pipefail
ids="${1:-tinysecurity,tinycomputer,tinyconnectors,tinybox,tinyflows}"
cache="${OPENHUMAN_TS_E2E_CACHE:-$HOME/.cache/openhuman-ts-e2e}"
bundled="$cache/bundled"
mkdir -p "$cache"
chmod 700 "$cache"
rm -rf "$bundled"

host_key="${OH_MODULE_HOST_KEY:-}"
if [ -z "$host_key" ]; then
case "$(uname -s)-$(uname -m)" in
Linux-x86_64) host_key="ubuntu-24.04-x86_64" ;;
Linux-aarch64 | Linux-arm64) host_key="ubuntu-24.04-arm64" ;;
Darwin-arm64) host_key="macos-15-arm64" ;;
Darwin-*) host_key="macos-15-x86_64" ;;
*) echo "ts-e2e: unsupported host $(uname -s) $(uname -m)" >&2; exit 1 ;;
esac
fi

if ! assets="$(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" "$ids")"; then
echo "ts-e2e: cannot resolve the release assets of $ids for $host_key" >&2
exit 1
fi
if [ -z "$assets" ]; then
echo "ts-e2e: no release assets for $ids on $host_key" >&2
exit 1
fi

loadable=""
while IFS=$'\t' read -r id url archive sha; do
path="$cache/$archive"
curl --fail --location --silent --show-error --retry 4 --retry-delay 2 "$url" --output "$path"
node - "$path" "$sha" <<'NODE'
const { createHash } = require("node:crypto");
const { readFileSync } = require("node:fs");
const [file, expected] = process.argv.slice(2);
const actual = createHash("sha256").update(readFileSync(file)).digest("hex");
if (actual !== expected) {
throw new Error(`ts-e2e module digest mismatch for ${file}: expected ${expected}, got ${actual}`);
}
NODE
version="${archive#"$id"-module-}"
version="${version#"$id"-}"
version="${version%%-"$host_key"*}"
dir="$bundled/$id/$version/$host_key"
mkdir -p "$dir"
cp "$path" "$dir/$archive"
tar --no-same-owner -xzf "$dir/$archive" -C "$dir"
if [[ "$(uname -s)" == Linux ]]; then
if ! deps="$(find "$dir" -name '*.so' -exec ldd {} + 2>&1)"; then
echo "ts-e2e: $id $version staged but not loadable here; ldd failed: $deps" >&2
continue
fi
missing="$(printf '%s\n' "$deps" | awk '/not found/ {print $1}' | sort -u | tr '\n' ' ')"
if [[ -n "$missing" ]]; then
echo "ts-e2e: $id $version staged but not loadable here; runner lacks: $missing" >&2
continue
fi
fi
echo "ts-e2e: staged $id $version" >&2
loadable="${loadable:+$loadable,}$id"
done <<< "$assets"

printf 'export OPENHUMAN_BUNDLED_MODULES=%q\nexport OPENHUMAN_TS_E2E_MODULES=%q\n' "$bundled" "$loadable"
)

if ts_e2e_exports="$(ts_e2e_stage "$@")"; then
eval "$ts_e2e_exports"
unset -f ts_e2e_stage
unset ts_e2e_exports
echo "ts-e2e: OPENHUMAN_BUNDLED_MODULES=$OPENHUMAN_BUNDLED_MODULES OPENHUMAN_TS_E2E_MODULES=$OPENHUMAN_TS_E2E_MODULES" >&2
else
unset -f ts_e2e_stage
unset ts_e2e_exports
echo "ts-e2e: staging failed; nothing exported" >&2
false
fi
Loading
Loading