diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5d4be1c5f2..15d3195927 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -210,6 +210,46 @@ jobs: - name: Test run: make -C clients/openframe-client test + build-rust-common: + name: "Build Rust common (${{ matrix.os }})" + needs: changes + if: fromJSON(needs.changes.outputs.changes || '{}').rust == 'true' + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Prepare Rust tools + uses: ./.github/steps/rust-setup + with: + path: clients/openframe-common + components: clippy,rustfmt + shared-key: openframe-common-${{ matrix.os }} + + - name: Install cargo-hack + uses: taiki-e/install-action@v2 + with: + tool: cargo-hack@0.6.46 + fallback: none + + - name: Lint (cargo fmt --check + cargo clippy -D warnings) + run: make -C clients/openframe-common lint + + - name: Check every feature combination + run: make -C clients/openframe-common hack + + - name: Test + run: make -C clients/openframe-common test + cleanup: name: Cleanup if: github.event_name == 'pull_request' && github.event.pull_request.state != 'open' diff --git a/clients/.githooks/pre-commit b/clients/.githooks/pre-commit index be519da68c..3c0c5970d5 100755 --- a/clients/.githooks/pre-commit +++ b/clients/.githooks/pre-commit @@ -1,9 +1,10 @@ #!/usr/bin/env bash -# OpenFrame Rust client: verify formatting before committing. -# Only fires when staged changes touch Rust sources under clients/. +# OpenFrame Rust crates: verify formatting before committing. +# Only fires for the crates under clients/ whose Rust sources are staged. set -euo pipefail -if ! git diff --cached --name-only | grep -qE '^clients/.*\.rs$'; then +crates="$(git diff --cached --name-only --diff-filter=ACMR | sed -nE 's#^clients/([^/]+)/.*\.rs$#\1#p' | sort -u)" +if [ -z "$crates" ]; then exit 0 fi @@ -12,6 +13,9 @@ if ! command -v cargo >/dev/null 2>&1; then exit 0 fi -cd "$(git rev-parse --show-toplevel)/clients/openframe-client" -echo "[pre-commit] cargo fmt --all -- --check" -cargo fmt --all -- --check +root="$(git rev-parse --show-toplevel)" +for crate in $crates; do + cd "$root/clients/$crate" + echo "[pre-commit] $crate: cargo fmt --all -- --check" + cargo fmt --all -- --check +done diff --git a/clients/.githooks/pre-push b/clients/.githooks/pre-push index 1c0a5b4053..7c09a38e98 100755 --- a/clients/.githooks/pre-push +++ b/clients/.githooks/pre-push @@ -1,7 +1,7 @@ #!/usr/bin/env bash -# OpenFrame Rust client: run clippy (deny warnings) before pushing. -# Only fires when the pushed commits touch the Rust client; skips gracefully -# when cargo is unavailable so non-Rust contributors are not blocked. +# OpenFrame Rust crates: run every crate's clippy target (deny warnings) before pushing, +# since one crate builds on another. Only fires when the pushed commits touch Rust under +# clients/; skips gracefully without cargo or make so non-Rust contributors are not blocked. set -euo pipefail root="$(git rev-parse --show-toplevel)" @@ -23,11 +23,13 @@ if ! echo "$changed" | grep -qE '\.(rs|toml)$'; then exit 0 fi -if ! command -v cargo >/dev/null 2>&1; then - echo "[pre-push] cargo not found; skipping Rust clippy check." >&2 +if ! command -v cargo >/dev/null 2>&1 || ! command -v make >/dev/null 2>&1; then + echo "[pre-push] cargo or make not found; skipping Rust clippy check." >&2 exit 0 fi -cd "$root/clients/openframe-client" -echo "[pre-push] cargo clippy --all-targets -- -D warnings" -OPENFRAME_VERSION="${OPENFRAME_VERSION:-0.0.0-dev}" cargo clippy --all-targets -- -D warnings +for manifest in "$root"/clients/*/Cargo.toml; do + crate="$(dirname "$manifest")" + echo "[pre-push] $(basename "$crate"): make clippy" + make -C "$crate" clippy +done diff --git a/clients/README.md b/clients/README.md index 6d636b15c9..1585878d13 100644 --- a/clients/README.md +++ b/clients/README.md @@ -14,10 +14,14 @@ clients/ ├── Makefile # hook setup only: `make -C clients setup-hooks` ├── rustfmt.toml # formatting config (applies to every crate below it) ├── .githooks/ # pre-commit (fmt) + pre-push (clippy) -└── openframe-client/ # the standalone library crate (openframe-agent-lib) - ├── Cargo.toml # incl. [lints.clippy] policy +├── openframe-client/ # the standalone library crate (openframe-agent-lib) +│ ├── Cargo.toml # incl. [lints.clippy] policy +│ ├── Cargo.lock +│ └── Makefile # fmt / fmt-check / clippy / lint / build / test +└── openframe-common/ # code shared by the agent and the desktop apps + ├── Cargo.toml # opt-in parts behind cargo features ├── Cargo.lock - └── Makefile # fmt / fmt-check / clippy / lint / build / test + └── Makefile # fmt / fmt-check / clippy / lint / hack / test ``` ## One-time setup @@ -29,12 +33,14 @@ make -C clients setup-hooks This enables the committed git hooks: -- **pre-commit** → `cargo fmt --all -- --check` (fails on unformatted Rust). -- **pre-push** → `cargo clippy --all-targets -- -D warnings`. +- **pre-commit** → `cargo fmt --all -- --check` in each crate with staged Rust. +- **pre-push** → `make clippy` in every crate (`-D warnings`). -Both hooks only fire when the change touches the Rust client, and skip cleanly -if `cargo` is not installed, so they do not get in the way of Java-only work. -CI (`.github/workflows/rust-client.yml`) runs the same gate authoritatively. +Both hooks only fire when the change touches Rust under `clients/`, and skip +cleanly if `cargo` (or `make`, for pre-push) is not installed, so they do not get +in the way of Java-only work. CI (`.github/workflows/build.yml`) runs the same +checks on PRs with the `build` label and in the merge queue. They are not +required checks: `main` requires only `Flamingo Code Review / reviewed`. Requires a stable Rust toolchain (`rustup` recommended) with the `rustfmt` and `clippy` components. diff --git a/clients/openframe-client/Cargo.lock b/clients/openframe-client/Cargo.lock index 4aed3517ea..5d48d5bd7c 100644 --- a/clients/openframe-client/Cargo.lock +++ b/clients/openframe-client/Cargo.lock @@ -1530,7 +1530,6 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" name = "openframe-agent-lib" version = "0.1.0" dependencies = [ - "aes-gcm", "anyhow", "async-nats", "async-trait", @@ -1550,6 +1549,7 @@ dependencies = [ "libc", "log", "nix", + "openframe-common", "plist", "redb", "regex", @@ -1578,6 +1578,17 @@ dependencies = [ "zip", ] +[[package]] +name = "openframe-common" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "base64 0.21.7", + "serde", + "serde_json", +] + [[package]] name = "openssl" version = "0.10.81" diff --git a/clients/openframe-client/Cargo.toml b/clients/openframe-client/Cargo.toml index ca67f90d1f..c7ae5cb252 100644 --- a/clients/openframe-client/Cargo.toml +++ b/clients/openframe-client/Cargo.toml @@ -101,8 +101,6 @@ zip = "0.6" tempfile = "3.10" semver = "1.0" sys-info = "0.9" -aes-gcm = "0.10" -base64 = "0.21" log = "0.4.27" clap = { version = "4.5", features = ["derive", "env", "std", "cargo", "string"] } whoami = "1.4" @@ -119,6 +117,7 @@ async-nats = { git = "https://github.com/flamingo-stack/nats.rs.git", rev = "3cf rustls-pemfile = "1.0" redb = "2" regex = "1.11.1" +openframe-common = { path = "../openframe-common", features = ["shared-token"] } [target.'cfg(windows)'.dependencies] winreg = "0.52" @@ -131,6 +130,9 @@ windows = { version = "0.52", features = ["Win32_Foundation", "Win32_System_Thre libc = "0.2" nix = { version = "0.29", features = ["user"] } +[dev-dependencies] +base64 = "0.21" + [build-dependencies] embed-resource = "2.4" diff --git a/clients/openframe-client/src/lib.rs b/clients/openframe-client/src/lib.rs index 5df2699556..4d701936f2 100644 --- a/clients/openframe-client/src/lib.rs +++ b/clients/openframe-client/src/lib.rs @@ -62,7 +62,6 @@ use crate::services::agent_configuration_service::AgentConfigurationService; use crate::services::deactivation_service::DeactivationService; use crate::services::delivery_results::DeliveryResults; use crate::services::device_data_fetcher::DeviceDataFetcher; -use crate::services::encryption_service::EncryptionService; use crate::services::execution_service::ExecutionService; use crate::services::feature_flags_service::FeatureFlagsService; use crate::services::github_download_service::GithubDownloadService; @@ -295,12 +294,8 @@ impl Client { deactivation_service.clone(), ); - // Initialize encryption service - let encryption_service = EncryptionService::new(); - // Initialize shared token service - let shared_token_service = - SharedTokenService::new(directory_manager.clone(), encryption_service.clone()); + let shared_token_service = SharedTokenService::new(directory_manager.clone()); // Initialize authentication service let auth_service = AgentAuthService::new( diff --git a/clients/openframe-client/src/listener/command/integration_tests.rs b/clients/openframe-client/src/listener/command/integration_tests.rs index 271cd1dfea..2559dd2620 100644 --- a/clients/openframe-client/src/listener/command/integration_tests.rs +++ b/clients/openframe-client/src/listener/command/integration_tests.rs @@ -15,7 +15,7 @@ use super::{ use crate::config::update_config::DEV_CLIENT_VERSION; use crate::models::{ DeliveryRef, DeliveryResult, DeliveryResultMessage, FailReason, Feature, FeatureFlagsState, - InstalledAgentMessage, InstalledAsset, InstalledTool, OpenFrameClientUpdateMessage, PackageRef, + InstalledAsset, InstalledTool, OpenFrameClientUpdateMessage, PackageRef, PackageUpdateStatusMessage, ToolRecordState, UpdateStatus, }; use crate::platform::{DirectoryManager, DmgExtractor}; @@ -44,6 +44,7 @@ use crate::services::{ use crate::test_support::{connection_manager, NatsServer}; use crate::utils::in_progress::InProgress; use crate::utils::latch::Latch; +use openframe_common::protocol::InstalledAgentMessage; const MACHINE: &str = "it-machine"; const BOUND: Duration = Duration::from_secs(10); diff --git a/clients/openframe-client/src/models/.installed_agent_message.md b/clients/openframe-client/src/models/.installed_agent_message.md deleted file mode 100644 index 8f1986d419..0000000000 --- a/clients/openframe-client/src/models/.installed_agent_message.md +++ /dev/null @@ -1,22 +0,0 @@ - -Defines a serializable message struct representing an installed agent's identity, used for agent registration or status reporting. - -## Key Components - -- **`InstalledAgentMessage`** — Public struct with `camelCase` JSON serialization containing: - - `agent_type: String` — The type/category of the installed agent - - `version: String` — The agent's version string - -## Usage Example - -```rust -use openframe_oss_lib::InstalledAgentMessage; - -let msg = InstalledAgentMessage { - agent_type: "monitoring".to_string(), - version: "1.2.0".to_string(), -}; - -let json = serde_json::to_string(&msg).unwrap(); -// Output: {"agentType":"monitoring","version":"1.2.0"} -``` \ No newline at end of file diff --git a/clients/openframe-client/src/models/mod.rs b/clients/openframe-client/src/models/mod.rs index dc1707c13d..2f8f8dcbcf 100644 --- a/clients/openframe-client/src/models/mod.rs +++ b/clients/openframe-client/src/models/mod.rs @@ -9,7 +9,6 @@ pub mod execution; pub mod feature_flags; pub mod hostname_report_message; pub mod initial_configuration; -pub mod installed_agent_message; pub mod installed_tool; pub mod machine_heartbeat_message; pub mod machine_timezone_message; @@ -50,7 +49,6 @@ pub use feature_flags::{ }; pub use hostname_report_message::HostnameReportMessage; pub use initial_configuration::InitialConfiguration; -pub use installed_agent_message::InstalledAgentMessage; pub use installed_tool::{ Installation, InstalledAsset, InstalledTool, ToolRecordState, CHAT_TOOL_AGENT_ID, }; diff --git a/clients/openframe-client/src/services/.encryption_service.md b/clients/openframe-client/src/services/.encryption_service.md deleted file mode 100644 index 0af9925eba..0000000000 --- a/clients/openframe-client/src/services/.encryption_service.md +++ /dev/null @@ -1,33 +0,0 @@ - -Provides AES-256-GCM symmetric encryption for string data, returning Base64-encoded ciphertext with a prepended random nonce. - -## Key Components - -- **`EncryptionService`** — A zero-sized, cloneable service struct that wraps AES-256-GCM encryption logic. -- **`EncryptionService::new()`** — Constructor; also available via `Default::default()`. -- **`EncryptionService::encrypt(&self, data: &str) -> Result`** — Encrypts a plaintext string using AES-256-GCM with a 12-byte random nonce (via `OsRng`). Returns a Base64-encoded string of `[nonce (12 bytes) || ciphertext]`. -- **`KEY`** — Hardcoded 32-byte static key constant. ⚠️ Marked with a `TODO` to replace with a dynamically generated key before production use. - -## Usage Example - -```rust -use encryption_service::EncryptionService; - -fn main() -> anyhow::Result<()> { - let svc = EncryptionService::new(); - - let plaintext = "sensitive-api-token"; - let encrypted = svc.encrypt(plaintext)?; - - // encrypted is Base64(nonce[12] || ciphertext) - println!("Encrypted: {}", encrypted); - - Ok(()) -} -``` - -## ⚠️ Security Notes - -- The static key `"12345678901234567890123456789012"` is **not safe for production**. It must be replaced with a securely generated and stored key (e.g., from a KMS or environment secret). -- A fresh 12-byte nonce is generated per encryption call via `OsRng`, which is cryptographically secure. -- The `#![allow(deprecated)]` suppresses warnings from `aes-gcm 0.10`'s transitive dependency on `generic-array 0.x`; this should be removed once the upstream crate is updated. \ No newline at end of file diff --git a/clients/openframe-client/src/services/encryption_service.rs b/clients/openframe-client/src/services/encryption_service.rs deleted file mode 100644 index e894e5558f..0000000000 --- a/clients/openframe-client/src/services/encryption_service.rs +++ /dev/null @@ -1,46 +0,0 @@ -// aes-gcm 0.10 re-exports the deprecated generic-array 0.x; silence until the dep is bumped. -#![allow(deprecated)] - -use aes_gcm::{ - aead::{generic_array::GenericArray, rand_core::RngCore, Aead, KeyInit, OsRng}, - Aes256Gcm, -}; -use anyhow::Result; -use base64::{engine::general_purpose, Engine as _}; - -#[derive(Clone)] -pub struct EncryptionService; - -impl Default for EncryptionService { - fn default() -> Self { - Self::new() - } -} - -impl EncryptionService { - // TODO: use generated key - const KEY: &'static str = "12345678901234567890123456789012"; - - pub fn new() -> Self { - Self - } - - pub fn encrypt(&self, data: &str) -> Result { - let key = Aes256Gcm::new_from_slice(Self::KEY.as_bytes()) - .map_err(|e| anyhow::anyhow!("Failed to create encryption key: {}", e))?; - - let mut nonce_bytes = [0u8; 12]; - OsRng.fill_bytes(&mut nonce_bytes); - let nonce = GenericArray::from_slice(&nonce_bytes); - - let ciphertext = key - .encrypt(nonce, data.as_bytes()) - .map_err(|e| anyhow::anyhow!("Failed to encrypt data: {}", e))?; - - let mut combined = nonce_bytes.to_vec(); - combined.extend_from_slice(&ciphertext); - - let base64_encoded = general_purpose::STANDARD.encode(combined); - Ok(base64_encoded) - } -} diff --git a/clients/openframe-client/src/services/installed_agent_message_publisher.rs b/clients/openframe-client/src/services/installed_agent_message_publisher.rs index caf81c1d52..18cb82a913 100644 --- a/clients/openframe-client/src/services/installed_agent_message_publisher.rs +++ b/clients/openframe-client/src/services/installed_agent_message_publisher.rs @@ -1,6 +1,6 @@ -use crate::models::InstalledAgentMessage; use crate::services::nats_message_publisher::NatsMessagePublisher; use anyhow::Context; +use openframe_common::protocol::InstalledAgentMessage; #[derive(Clone)] pub struct InstalledAgentMessagePublisher { diff --git a/clients/openframe-client/src/services/mod.rs b/clients/openframe-client/src/services/mod.rs index ac663bf1dd..0728648a9b 100644 --- a/clients/openframe-client/src/services/mod.rs +++ b/clients/openframe-client/src/services/mod.rs @@ -6,7 +6,6 @@ pub mod deactivation_service; pub mod delivery_results; pub mod deregistration_service; pub mod device_data_fetcher; -pub mod encryption_service; pub mod execution_service; pub mod feature_flags_service; pub mod github_download_service; @@ -56,7 +55,6 @@ pub use agent_configuration_service::AgentConfigurationService; pub use agent_registration_service::AgentRegistrationService; pub use deactivation_service::DeactivationService; pub use deregistration_service::DeregistrationService; -pub use encryption_service::EncryptionService; pub use github_download_service::GithubDownloadService; pub use hostname_report_publisher::HostnameReportPublisher; pub use initial_configuration_service::InitialConfigurationService; diff --git a/clients/openframe-client/src/services/openframe_client_update_service_tests.rs b/clients/openframe-client/src/services/openframe_client_update_service_tests.rs index ae7a4e8ae7..bcea95043c 100644 --- a/clients/openframe-client/src/services/openframe_client_update_service_tests.rs +++ b/clients/openframe-client/src/services/openframe_client_update_service_tests.rs @@ -2,7 +2,6 @@ use super::*; use crate::clients::AuthClient; use crate::models::DownloadConfiguration; use crate::platform::DmgExtractor; -use crate::services::encryption_service::EncryptionService; use crate::services::installed_agent_message_publisher::InstalledAgentMessagePublisher; use crate::services::local_tls_config_provider::LocalTlsConfigProvider; use crate::services::nats_connection_manager::NatsConnectionManager; @@ -50,7 +49,7 @@ fn fixture() -> Fixture { deactivation.clone(), ), config.clone(), - SharedTokenService::new(directories.clone(), EncryptionService::new()), + SharedTokenService::new(directories.clone()), ); let nats = NatsConnectionManager::new( "nats://127.0.0.1:9".into(), diff --git a/clients/openframe-client/src/services/shared_token_service.rs b/clients/openframe-client/src/services/shared_token_service.rs index 91f6cb5bb8..3fb0e370ef 100644 --- a/clients/openframe-client/src/services/shared_token_service.rs +++ b/clients/openframe-client/src/services/shared_token_service.rs @@ -1,25 +1,21 @@ use crate::platform::directories::DirectoryManager; -use crate::services::EncryptionService; use crate::utils::fs::atomic_write; use anyhow::Result; +use openframe_common::auth::shared_token; #[derive(Clone)] pub struct SharedTokenService { dir_manager: DirectoryManager, - encryption_service: EncryptionService, } impl SharedTokenService { - pub fn new(dir_manager: DirectoryManager, encryption_service: EncryptionService) -> Self { - Self { - dir_manager, - encryption_service, - } + pub fn new(dir_manager: DirectoryManager) -> Self { + Self { dir_manager } } pub fn update(&self, token: String) -> Result<()> { - let token_file_path = self.dir_manager.secured_dir().join("shared_token.enc"); - let encrypted_token = self.encryption_service.encrypt(&token)?; + let token_file_path = self.dir_manager.secured_dir().join(shared_token::FILE_NAME); + let encrypted_token = shared_token::encrypt(shared_token::KEY.as_bytes(), &token)?; atomic_write(&token_file_path, encrypted_token)?; Ok(()) } diff --git a/clients/openframe-client/src/services/token_refresh_run_manager.rs b/clients/openframe-client/src/services/token_refresh_run_manager.rs index e7a0856a4c..af876485fd 100644 --- a/clients/openframe-client/src/services/token_refresh_run_manager.rs +++ b/clients/openframe-client/src/services/token_refresh_run_manager.rs @@ -7,7 +7,7 @@ use tracing::{debug, error, info, warn}; use crate::models::AgentTokenResponse; use crate::services::deactivation_service::DeactivationService; use crate::services::AgentAuthService; -use crate::utils::jwt; +use openframe_common::auth::jwt; /// Device-vs-server clock difference worth a warning. const SKEW_WARN: Duration = Duration::from_secs(5 * 60); diff --git a/clients/openframe-client/src/services/token_refresh_run_manager_tests.rs b/clients/openframe-client/src/services/token_refresh_run_manager_tests.rs index cc795db2ab..bdf853279c 100644 --- a/clients/openframe-client/src/services/token_refresh_run_manager_tests.rs +++ b/clients/openframe-client/src/services/token_refresh_run_manager_tests.rs @@ -3,7 +3,6 @@ use crate::clients::AuthClient; use crate::platform::directories::DirectoryManager; use crate::services::agent_configuration_service::AgentConfigurationService; use crate::services::shared_token_service::SharedTokenService; -use crate::services::EncryptionService; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use std::sync::Mutex; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -339,7 +338,7 @@ async fn registered_manager(dir: &tempfile::TempDir, base_url: String) -> TokenR .unwrap(); let deactivation = DeactivationService::new(&dm); let auth_client = AuthClient::new(base_url, reqwest::Client::new(), deactivation.clone()); - let shared = SharedTokenService::new(dm, EncryptionService::new()); + let shared = SharedTokenService::new(dm); let auth = AgentAuthService::new(auth_client, config, shared); TokenRefreshRunManager::new(auth, deactivation).with_timing(FAST) } diff --git a/clients/openframe-client/src/services/tool_command_params_resolver.rs b/clients/openframe-client/src/services/tool_command_params_resolver.rs index 31760edfba..dd495b1a7e 100644 --- a/clients/openframe-client/src/services/tool_command_params_resolver.rs +++ b/clients/openframe-client/src/services/tool_command_params_resolver.rs @@ -1,6 +1,7 @@ use crate::platform::DirectoryManager; use crate::services::{AgentConfigurationService, InitialConfigurationService}; use anyhow::Result; +use openframe_common::auth::shared_token; use regex::Regex; use std::sync::LazyLock; @@ -55,10 +56,7 @@ impl ToolCommandParamsResolver { // Resolve standard placeholders .map(|arg| { arg.replace(Self::SERVER_URL_PLACEHOLDER, &server_url) - .replace( - Self::OPENFRAME_SECRET_PLACEHOLDER, - "12345678901234567890123456789012", - ) + .replace(Self::OPENFRAME_SECRET_PLACEHOLDER, shared_token::KEY) .replace(Self::OPENFRAME_TOKEN_PATH_PLACEHOLDER, &token_path) .replace(Self::MACHINE_ID_PLACEHOLDER, &machine_id) }) @@ -70,7 +68,7 @@ impl ToolCommandParamsResolver { fn build_token_path(&self) -> String { self.directory_manager .secured_dir() - .join("shared_token.enc") + .join(shared_token::FILE_NAME) .to_string_lossy() .to_string() } diff --git a/clients/openframe-client/src/test_support.rs b/clients/openframe-client/src/test_support.rs index c48ba53ec1..cd91534fff 100644 --- a/clients/openframe-client/src/test_support.rs +++ b/clients/openframe-client/src/test_support.rs @@ -10,7 +10,6 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::clients::AuthClient; use crate::platform::directories::DirectoryManager; use crate::services::backend_call_retry::RetryTiming; -use crate::services::encryption_service::EncryptionService; use crate::services::local_tls_config_provider::LocalTlsConfigProvider; use crate::services::nats_connection_manager::NatsConnectionManager; use crate::services::shared_token_service::SharedTokenService; @@ -124,7 +123,7 @@ pub(crate) fn connection_manager( deactivation.clone(), ), config.clone(), - SharedTokenService::new(directories.clone(), EncryptionService::new()), + SharedTokenService::new(directories.clone()), ); NatsConnectionManager::new( url, diff --git a/clients/openframe-client/src/utils.rs b/clients/openframe-client/src/utils.rs index 4177a094ef..e176ed60b9 100644 --- a/clients/openframe-client/src/utils.rs +++ b/clients/openframe-client/src/utils.rs @@ -1,7 +1,6 @@ pub mod failure_log_backoff; pub mod fs; pub mod in_progress; -pub mod jwt; pub mod latch; pub mod timed_permit_pool; pub mod version_comparator; diff --git a/clients/openframe-client/src/utils/.jwt.md b/clients/openframe-client/src/utils/.jwt.md deleted file mode 100644 index 64c13edf8f..0000000000 --- a/clients/openframe-client/src/utils/.jwt.md +++ /dev/null @@ -1,36 +0,0 @@ - -Lightweight JWT utility for extracting the `exp` and `iat` claims from a token's payload without performing signature verification. - -## Key Components - -| Item | Kind | Description | -|---|---|---| -| `token_times_unix` | `pub fn` | Decodes a JWT's `exp` (required) and `iat` (optional) claims from the payload segment as Unix timestamps, returning `None` for malformed tokens or a missing `exp` | -| `JwtTimes` | `pub struct` | `exp: i64`, `iat: Option`; `ttl_secs()` returns the issuer-granted lifetime (`exp − iat`) when `iat` is present and the lifetime is positive | - -## Usage Example - -```rust -use openframe::utils::jwt::token_times_unix; - -let token = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2OTk5OTY0MDAsImV4cCI6MTcwMDAwMDAwMH0.sig"; - -match token_times_unix(token) { - Some(times) => match times.ttl_secs() { - Some(ttl) => println!("Token lives {ttl}s, expires at Unix timestamp {}", times.exp), - None => println!("Token expires at Unix timestamp {} (no iat)", times.exp), - }, - None => eprintln!("Malformed token or missing exp claim"), -} -``` - -## Behaviour Notes - -- **No signature verification** — intended for scheduling and expiry pre-checks only; always verify the signature through a proper JWT library before trusting any claims. -- **Lifetime, not wall clock** — `ttl_secs()` is server-relative (`exp − iat`), which is what a refresh timer should use; comparing `exp` with the device clock breaks when that clock is skewed. -- **Strict segment validation** — requires exactly three `.`-separated parts (`header.payload.signature`); tokens with fewer or extra segments return `None`. -- **Tolerant Base64 padding** — trailing `=` padding is stripped before decoding to handle both padded and unpadded URL-safe Base64 variants. - -## Source - -[`jwt.rs`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/jwt.rs) diff --git a/clients/openframe-common/Cargo.lock b/clients/openframe-common/Cargo.lock new file mode 100644 index 0000000000..57f4271bca --- /dev/null +++ b/clients/openframe-common/Cargo.lock @@ -0,0 +1,309 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "anyhow" +version = "1.0.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openframe-common" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "serde", + "serde_json", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" diff --git a/clients/openframe-common/Cargo.toml b/clients/openframe-common/Cargo.toml new file mode 100644 index 0000000000..b07c0da962 --- /dev/null +++ b/clients/openframe-common/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "openframe-common" +version = "0.1.0" +edition = "2021" +authors = ["Flamingo Team"] +description = "OpenFrame - code shared by the agent and the desktop apps" +license-file = "../../LICENSE.md" +repository = "https://github.com/flamingo-stack/openframe-oss-lib" + +[lints.clippy] +all = { level = "warn", priority = -1 } +correctness = "deny" +suspicious = "deny" + +[features] +shared-token = ["dep:aes-gcm", "dep:anyhow"] + +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +base64 = "0.21" +aes-gcm = { version = "0.10", optional = true } +anyhow = { version = "1.0", optional = true } diff --git a/clients/openframe-common/Makefile b/clients/openframe-common/Makefile new file mode 100644 index 0000000000..8b077e696b --- /dev/null +++ b/clients/openframe-common/Makefile @@ -0,0 +1,25 @@ +# Makefile for the openframe-common crate + +CARGO ?= cargo + +.PHONY: fmt fmt-check clippy lint hack test clean + +fmt: + $(CARGO) fmt --all + +fmt-check: + $(CARGO) fmt --all -- --check + +clippy: + $(CARGO) clippy --all-targets --all-features --locked -- -D warnings + +lint: fmt-check clippy + +hack: + $(CARGO) hack --feature-powerset clippy --all-targets --locked -- -D warnings + +test: + $(CARGO) test --all-features --locked + +clean: + $(CARGO) clean diff --git a/clients/openframe-common/src/auth.rs b/clients/openframe-common/src/auth.rs new file mode 100644 index 0000000000..6d94e3ad18 --- /dev/null +++ b/clients/openframe-common/src/auth.rs @@ -0,0 +1,3 @@ +pub mod jwt; +#[cfg(feature = "shared-token")] +pub mod shared_token; diff --git a/clients/openframe-client/src/utils/jwt.rs b/clients/openframe-common/src/auth/jwt.rs similarity index 100% rename from clients/openframe-client/src/utils/jwt.rs rename to clients/openframe-common/src/auth/jwt.rs diff --git a/clients/openframe-client/src/utils/jwt_tests.rs b/clients/openframe-common/src/auth/jwt_tests.rs similarity index 100% rename from clients/openframe-client/src/utils/jwt_tests.rs rename to clients/openframe-common/src/auth/jwt_tests.rs diff --git a/clients/openframe-common/src/auth/shared_token.rs b/clients/openframe-common/src/auth/shared_token.rs new file mode 100644 index 0000000000..74db9c9f0e --- /dev/null +++ b/clients/openframe-common/src/auth/shared_token.rs @@ -0,0 +1,53 @@ +// aes-gcm 0.10 re-exports the deprecated generic-array 0.x; silence until the dep is bumped. +#![allow(deprecated)] + +use aes_gcm::{ + aead::{generic_array::GenericArray, rand_core::RngCore, Aead, KeyInit, OsRng}, + Aes256Gcm, +}; +use anyhow::Result; +use base64::{engine::general_purpose, Engine as _}; + +// TODO: use generated key +pub const KEY: &str = "12345678901234567890123456789012"; +pub const FILE_NAME: &str = "shared_token.enc"; + +const NONCE_LEN: usize = 12; + +pub fn encrypt(key: &[u8], plaintext: &str) -> Result { + let cipher = Aes256Gcm::new_from_slice(key) + .map_err(|e| anyhow::anyhow!("Failed to create encryption key: {}", e))?; + + let mut nonce_bytes = [0u8; NONCE_LEN]; + OsRng.fill_bytes(&mut nonce_bytes); + let nonce = GenericArray::from_slice(&nonce_bytes); + + let ciphertext = cipher + .encrypt(nonce, plaintext.as_bytes()) + .map_err(|e| anyhow::anyhow!("Failed to encrypt data: {}", e))?; + + let mut combined = nonce_bytes.to_vec(); + combined.extend_from_slice(&ciphertext); + + Ok(general_purpose::STANDARD.encode(combined)) +} + +pub fn decrypt(key: &[u8], encrypted: &str) -> Result { + let combined = general_purpose::STANDARD + .decode(encrypted) + .map_err(|e| anyhow::anyhow!("Failed to decode base64: {}", e))?; + anyhow::ensure!(combined.len() >= NONCE_LEN, "Encrypted data too short"); + + let (nonce_bytes, ciphertext) = combined.split_at(NONCE_LEN); + let cipher = Aes256Gcm::new_from_slice(key) + .map_err(|e| anyhow::anyhow!("Failed to create cipher: {}", e))?; + let plaintext = cipher + .decrypt(GenericArray::from_slice(nonce_bytes), ciphertext) + .map_err(|e| anyhow::anyhow!("Failed to decrypt: {}", e))?; + + String::from_utf8(plaintext).map_err(|e| anyhow::anyhow!("Failed to convert to UTF-8: {}", e)) +} + +#[cfg(test)] +#[path = "shared_token_tests.rs"] +mod tests; diff --git a/clients/openframe-common/src/auth/shared_token_tests.rs b/clients/openframe-common/src/auth/shared_token_tests.rs new file mode 100644 index 0000000000..90331b49c1 --- /dev/null +++ b/clients/openframe-common/src/auth/shared_token_tests.rs @@ -0,0 +1,38 @@ +use super::*; + +const DEPLOYED_FORMAT_CIPHERTEXT: &str = + "EwCjbTco/441ksHsFzmFlUSR/Ulg3cEI2WqcDdiUP93ehIkT9A4C5Vap7BgV8AOP14PENg=="; + +#[test] +fn decrypts_the_format_deployed_agents_write() { + assert_eq!( + decrypt(KEY.as_bytes(), DEPLOYED_FORMAT_CIPHERTEXT).unwrap(), + "header.payload.signature" + ); +} + +#[test] +fn encrypts_to_base64_of_nonce_ciphertext_and_tag() { + let plaintext = "header.payload.signature"; + let encrypted = encrypt(KEY.as_bytes(), plaintext).unwrap(); + + let raw = general_purpose::STANDARD.decode(&encrypted).unwrap(); + assert_eq!(raw.len(), NONCE_LEN + plaintext.len() + 16); + assert_eq!(decrypt(KEY.as_bytes(), &encrypted).unwrap(), plaintext); +} + +#[test] +fn decrypt_rejects_another_key() { + assert!(decrypt(&[7u8; 32], DEPLOYED_FORMAT_CIPHERTEXT).is_err()); +} + +#[test] +fn decrypt_rejects_input_shorter_than_the_nonce() { + let short = general_purpose::STANDARD.encode([0u8; NONCE_LEN - 1]); + assert!(decrypt(KEY.as_bytes(), &short).is_err()); +} + +#[test] +fn decrypt_rejects_text_that_is_not_base64() { + assert!(decrypt(KEY.as_bytes(), "not base64!").is_err()); +} diff --git a/clients/openframe-common/src/lib.rs b/clients/openframe-common/src/lib.rs new file mode 100644 index 0000000000..c97d711b98 --- /dev/null +++ b/clients/openframe-common/src/lib.rs @@ -0,0 +1,2 @@ +pub mod auth; +pub mod protocol; diff --git a/clients/openframe-client/src/models/installed_agent_message.rs b/clients/openframe-common/src/protocol.rs similarity index 79% rename from clients/openframe-client/src/models/installed_agent_message.rs rename to clients/openframe-common/src/protocol.rs index 11831c2dba..e86c006d03 100644 --- a/clients/openframe-client/src/models/installed_agent_message.rs +++ b/clients/openframe-common/src/protocol.rs @@ -6,3 +6,7 @@ pub struct InstalledAgentMessage { pub agent_type: String, pub version: String, } + +#[cfg(test)] +#[path = "protocol_tests.rs"] +mod tests; diff --git a/clients/openframe-common/src/protocol_tests.rs b/clients/openframe-common/src/protocol_tests.rs new file mode 100644 index 0000000000..878adaa57d --- /dev/null +++ b/clients/openframe-common/src/protocol_tests.rs @@ -0,0 +1,14 @@ +use super::*; + +#[test] +fn installed_agent_message_keeps_its_wire_shape() { + let message = InstalledAgentMessage { + agent_type: "openframe-client".to_string(), + version: "1.5.103".to_string(), + }; + + assert_eq!( + serde_json::to_string(&message).unwrap(), + r#"{"agentType":"openframe-client","version":"1.5.103"}"# + ); +}