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
2 changes: 2 additions & 0 deletions .github/scripts/ci/fixtures/production-app-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,8 @@ async function verifyManager() {
runtimeProfile: 'rentnerproxy-linux-v1',
appProtocol: '>=1.0.0 <2.0.0',
platformApi: '>=1.0.0 <2.0.0',
// The manager negotiates the lower bound of each range: 1.0.0 for >=1.0.0.
negotiated: { appProtocol: '1.0.0', platformApi: '1.0.0' },
providers: [providerRegistration.profile],
}) + '\n',
)
Expand Down
4 changes: 2 additions & 2 deletions core/Cargo.lock

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

2 changes: 1 addition & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license = "MIT"

[dependencies]
rentnerproxy-app-catalog = "1.0.0"
rentnerproxy-app-contracts = "1.2.0"
rentnerproxy-app-contracts = "1.4.1"
rentnerproxy-app-pipeline = "1.0.0"
rentnerproxy-artifacts = "1.0.0"
aws-lc-rs = "1.19.0"
Expand Down
47 changes: 44 additions & 3 deletions core/src/app_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ pub(crate) use browse::CatalogEntry;
any(target_arch = "x86_64", target_arch = "aarch64")
))]
pub(crate) use package::{UI_ASSET_LIMIT, UI_DOCUMENT_LIMIT, parse_ui_api};
use rentnerproxy_app_contracts::{ContractError, Contracts, ManifestEnvironment};
use rentnerproxy_app_contracts::{
ContractError, Contracts, ManifestEnvironment, NegotiatedVersions,
};
use rentnerproxy_artifacts::{invalid, parse_json, read_file};
use serde::{Deserialize, Serialize};
use serde_json::Value;
Expand Down Expand Up @@ -81,7 +83,7 @@ pub(crate) use transport::{Source, unreachable_source};
/// same values (`web/src/config/app-requirements.config.ts`), so an older platform can check
/// installed apps against a newer release before its image changes.
pub(crate) const RUNTIME_PROFILE: &str = "rentnerproxy-linux-v1";
pub(crate) const PROTOCOL_VERSION: &str = "1.0.0";
pub(crate) const PROTOCOL_VERSION: &str = "1.1.0";

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
Expand Down Expand Up @@ -314,8 +316,23 @@ impl Installer {
manifest: &Value,
environment: &ManifestEnvironment<'_>,
) -> io::Result<()> {
// An app is compatible when it negotiates versions and the manifest passes the check
// against exactly those versions: a range that ends below the offered version, such as
// `>=1.0.0 <1.1.0`, still runs with the version it negotiates.
let negotiated = self
.contracts
.negotiate_versions(manifest, environment)
.map_err(invalid_contract)?;
self.contracts
.check_manifest_compatibility(manifest, environment)
.check_manifest_compatibility(
manifest,
&ManifestEnvironment {
platform_api: &negotiated.platform_api,
app_protocol: &negotiated.app_protocol,
ui_bridge: negotiated.ui_bridge.as_deref(),
..*environment
},
)
.map_err(invalid_contract)?;
if declares_engine_providers(manifest, environment) {
Ok(())
Expand Down Expand Up @@ -374,6 +391,30 @@ fn catalog_outage(error: io::Error, package_answers: impl FnOnce() -> Option<boo
}
}

/// The protocol versions an app negotiates with this platform, from its manifest ranges. Every
/// place that starts or reports an app uses this one answer, which is the shared contract rule.
pub(crate) fn negotiate_manifest_versions(manifest: &Value) -> io::Result<NegotiatedVersions> {
static CONTRACTS: std::sync::LazyLock<Result<Contracts, ContractError>> =
std::sync::LazyLock::new(Contracts::new);
let contracts = CONTRACTS
.as_ref()
.map_err(|_| invalid("Contracts unavailable"))?;
contracts
.negotiate_versions(
manifest,
&ManifestEnvironment {
// Target, profile and engine capabilities are not part of the negotiation.
target: "",
runtime_profile: RUNTIME_PROFILE,
platform_api: PROTOCOL_VERSION,
app_protocol: PROTOCOL_VERSION,
ui_bridge: Some(PROTOCOL_VERSION),
engine_capabilities: &[],
},
)
.map_err(invalid_contract)
}

fn invalid_contract(error: rentnerproxy_app_contracts::ContractError) -> io::Error {
invalid(error.code())
}
Expand Down
106 changes: 83 additions & 23 deletions core/src/app_ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@ pub(crate) const APP_ROOT: &str = "/run/rentnerproxy/apps";
const GATEWAY_SOCKET: &str = "/run/rentnerproxy/app-api/web.sock";
pub(crate) const WEB_UID: u32 = 10002;
const PROFILE: &str = "rentnerproxy-linux-v1";
const VERSION: &str = "1.0.0";
/// The protocol version this platform advertises in the bootstrap descriptor and the platform
/// context. Apps may report any `1.x.y` version up to it that their manifest range admits.
const VERSION: &str = rentnerproxy_app_contracts::PROTOCOL_VERSION;
/// The provider API version of registrations. It is a wire version of its own and does not
/// move with the protocol version.
const PROVIDER_VERSION: &str = "1.0.0";
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(10);
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const PROVIDER_PROFILES: [&str; 6] = [
Expand All @@ -40,6 +45,14 @@ const PROVIDER_PROFILES: [&str; 6] = [
"crowdsec",
];

#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct NegotiatedVersions {
app_protocol: String,
platform_api: String,
ui_bridge: Option<String>,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct LaunchConfig {
Expand All @@ -57,6 +70,8 @@ struct LaunchConfig {
ui_bridge: Option<String>,
startup_timeout_ms: Option<u64>,
process_limit: Option<u8>,
/// The versions the manager negotiated for this app, which must lie inside its ranges.
negotiated: NegotiatedVersions,
/// Provider profiles the signed manifest declares; absent means none.
#[serde(default)]
providers: Vec<String>,
Expand All @@ -71,6 +86,14 @@ impl LaunchConfig {
.ui_bridge
.as_deref()
.is_some_and(|range| !supports_version(range))
|| !admitted_by(&self.negotiated.app_protocol, &self.app_protocol)
|| !admitted_by(&self.negotiated.platform_api, &self.platform_api)
|| match (&self.negotiated.ui_bridge, &self.ui_bridge) {
(Some(version), Some(range)) => !admitted_by(version, range),
(Some(_), None) => true,
// A manifest range without a UI negotiates no bridge version.
(None, _) => false,
}
{
return Err(io::Error::other(
"Unsupported app runtime profile or protocol range",
Expand Down Expand Up @@ -131,32 +154,73 @@ fn record_id(value: &str) -> bool {
})
}

type Version = (u32, u32, u32);

/// A canonical `major.minor.patch` version: numbers without leading zeros and of at most six
/// digits, the form the manifest contract admits.
fn parse_version(text: &str) -> Option<Version> {
fn number(part: &str) -> Option<u32> {
let canonical = part.len() <= 6
&& !part.is_empty()
&& part.bytes().all(|byte| byte.is_ascii_digit())
&& (part.len() == 1 || !part.starts_with('0'));
if canonical { part.parse().ok() } else { None }
}
let mut parts = text.split('.');
let version = (
number(parts.next()?)?,
number(parts.next()?)?,
number(parts.next()?)?,
);
parts.next().is_none().then_some(version)
}

/// Split a manifest range of the form `>=MIN <MAX`.
fn parse_range(range: &str) -> Option<(Version, Version)> {
let (min, max) = range.strip_prefix(">=")?.split_once(" <")?;
Some((parse_version(min)?, parse_version(max)?))
}

/// Whether a manifest range may run on this platform: it names major 1, starts at or below the
/// advertised version and ends above its own start.
fn supports_version(range: &str) -> bool {
let Some(max) = range.strip_prefix(">=1.0.0 <") else {
let (Some((min, max)), Some(advertised)) = (parse_range(range), parse_version(VERSION)) else {
return false;
};
if max == "2.0.0" {
return true;
}
max.strip_prefix("1.")
.and_then(|max| max.split_once('.'))
.is_some_and(|(minor, patch)| {
[minor, patch].iter().all(|part| {
part.len() <= 6
&& !part.is_empty()
&& part.bytes().all(|byte| byte.is_ascii_digit())
&& (part.len() == 1 || !part.starts_with('0'))
}) && (minor != "0" || patch != "0")
})
min.0 == 1 && min <= advertised && min < max && (max.0 == 1 || max == (2, 0, 0))
}

/// Whether `version`, which the manager negotiated, is one this platform serves and the manifest
/// `range` admits: major 1, at most the advertised version and inside the range.
fn admitted_by(version: &str, range: &str) -> bool {
let (Some(version), Some(advertised), Some((min, max))) = (
parse_version(version),
parse_version(VERSION),
parse_range(range),
) else {
return false;
};
version.0 == 1 && version <= advertised && min <= version && version < max
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Versions {
app_protocol: &'static str,
platform_api: &'static str,
app_protocol: String,
platform_api: String,
#[serde(skip_serializing_if = "Option::is_none")]
ui_bridge: Option<&'static str>,
ui_bridge: Option<String>,
}

/// The versions the bootstrap descriptor tells this app: what the manager negotiated from the
/// manifest with the shared contract rule, which validation checked against the ranges.
fn versions(config: &LaunchConfig) -> Versions {
let negotiated = &config.negotiated;
Versions {
app_protocol: negotiated.app_protocol.clone(),
platform_api: negotiated.platform_api.clone(),
ui_bridge: negotiated.ui_bridge.clone(),
}
}

#[derive(Serialize)]
Expand Down Expand Up @@ -261,11 +325,7 @@ async fn run_generation(
installation_id: &config.installation_id,
generation: config.generation,
runtime_profile: PROFILE,
versions: Versions {
app_protocol: VERSION,
platform_api: VERSION,
ui_bridge: config.ui_bridge.as_ref().map(|_| VERSION),
},
versions: versions(&config),
app_socket: &sockets.app_socket,
core_socket: &sockets.core_socket,
app_credential: &app_credential,
Expand Down
10 changes: 6 additions & 4 deletions core/src/app_ipc/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use tokio::{
};

use super::{
Bootstrap, LaunchConfig, PROVIDER_PROFILES, VERSION, filesystem::connect_peer, lease,
Bootstrap, LaunchConfig, PROVIDER_PROFILES, PROVIDER_VERSION, filesystem::connect_peer, lease,
record_id, wire_json,
};

Expand Down Expand Up @@ -512,7 +512,7 @@ struct Operation {
events: bool,
}

static APP_OPERATIONS: LazyLock<[HttpDescriptor; 18]> = LazyLock::new(|| {
static APP_OPERATIONS: LazyLock<[HttpDescriptor; 19]> = LazyLock::new(|| {
[
HttpOperation::GetPlatformContext,
HttpOperation::SubscribeToEvents,
Expand All @@ -532,6 +532,7 @@ static APP_OPERATIONS: LazyLock<[HttpDescriptor; 18]> = LazyLock::new(|| {
HttpOperation::BeginLegacyHandoff,
HttpOperation::ReadLegacyHandoffPart,
HttpOperation::CommitLegacyHandoff,
HttpOperation::AbortLegacyHandoff,
]
.map(HttpOperation::descriptor)
});
Expand Down Expand Up @@ -812,7 +813,8 @@ async fn check_app_ready(
) -> Result<Vec<ProviderRegistration>, Failure> {
let healthy: AppHealth = probe_app(bootstrap, uid, "/app/v1/health").await?;
let ready: AppReady = probe_app(bootstrap, uid, "/app/v1/ready").await?;
if !healthy.healthy || !ready.ready || ready.protocol_version != VERSION {
if !healthy.healthy || !ready.ready || ready.protocol_version != bootstrap.versions.app_protocol
{
return Err(Failure::Retry);
}
registrations(ready.providers, declared).map_err(Failure::Fatal)
Expand All @@ -833,7 +835,7 @@ fn registrations(value: Value, declared: &[String]) -> io::Result<Vec<ProviderRe
.collect::<io::Result<Vec<_>>>()?;
for (index, provider) in providers.iter().enumerate() {
if !record_id(&provider.id)
|| provider.version != VERSION
|| provider.version != PROVIDER_VERSION
|| !declared.contains(&provider.profile)
|| providers[..index]
.iter()
Expand Down
6 changes: 6 additions & 0 deletions core/src/app_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,12 @@ impl Manager {
.get("incidentCategories")
.cloned()
.unwrap_or_else(|| json!([]));
let negotiated = crate::app_install::negotiate_manifest_versions(&package.manifest)?;
registration["versions"] =
json!({"appProtocol": negotiated.app_protocol, "platformApi": negotiated.platform_api});
if let Some(bridge) = negotiated.ui_bridge {
registration["versions"]["uiBridge"] = bridge.into();
}
self.gateway.post("register", registration).await?;
let renewal = runtime::Renewal::start(self.gateway.clone(), who.clone(), deadline);
slot.authority_recorded = Some(true);
Expand Down
5 changes: 4 additions & 1 deletion core/src/app_manager/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ impl Running {
let m = &package.manifest;
let data = Path::new(USERS).join(slot.uid.to_string()).join("data");
let requirements = &m["requires"];
let negotiated = crate::app_install::negotiate_manifest_versions(m)?;
let negotiated = json!({"appProtocol":negotiated.app_protocol,"platformApi":negotiated.platform_api,"uiBridge":negotiated.ui_bridge});
let mut frame = serde_json::to_vec(&json!({
"appId":slot.app_id,"installationId":id,"generation":slot.generation,"uid":slot.uid,"gid":slot.uid,
"executable":package.directory.join("bin/app"), "dataDirectory":data,
Expand All @@ -311,7 +313,8 @@ impl Running {
"platformApi":requirements["platformApi"],"uiBridge":requirements.get("uiBridge"),
"startupTimeoutMs":m["resources"]["startupTimeoutMs"].as_f64().map(|v|v as u64),
"processLimit":m["resources"]["processLimit"].as_f64().map(|v|v as u64),
"providers":m.get("providers").cloned().unwrap_or_else(|| json!([]))
"providers":m.get("providers").cloned().unwrap_or_else(|| json!([])),
"negotiated":negotiated
}))?;
frame.push(b'\n');
let mut command = Command::new(std::env::current_exe()?);
Expand Down
Loading