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
66 changes: 38 additions & 28 deletions core/src/app_install/grants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ pub(crate) const MAX_GRANTS: usize = 128;
const INSTALLATION: &str = "installation";
const PROVIDER_PROFILES: &str = "providerProfiles";
const PROXY_HOSTS: &str = "proxyHosts";
const DOCKER_CONNECTIONS: &str = "dockerConnections";
const DOCKER_INVENTORY: &str = "docker.inventory.observe.v1";
/// The single Docker connection managed by the platform.
pub(crate) const PLATFORM_DOCKER_RESOURCE: &str = "platform-docker";
/// Every platform proxy host, including hosts created after the approval. Only the Owner chooses
/// it, in place of selected hosts, and only for capabilities that read or probe hosts.
const ALL_PROXY_HOSTS: &str = "allProxyHosts";
Expand Down Expand Up @@ -82,8 +86,8 @@ pub(crate) struct Grant {
pub permission_key: Option<String>,
}

/// One grant a release requests. A selectable scope has no resource: the Owner picks at least
/// one. The core fills the installation itself.
/// One grant a release requests. The core preselects fixed resources and fills in the
/// installation itself. For a selectable scope, the Owner picks at least one resource.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
Expand All @@ -107,6 +111,23 @@ pub(crate) struct ApprovedGrant {
pub permission_key: Option<String>,
}

impl ApprovedGrant {
fn to_grant(&self, installation_id: &str) -> Option<Grant> {
let resource_id = match (self.capability.scope.as_str(), self.resource_id.as_deref()) {
(INSTALLATION, None) => installation_id,
(DOCKER_CONNECTIONS, Some(PLATFORM_DOCKER_RESOURCE)) => PLATFORM_DOCKER_RESOURCE,
(DOCKER_CONNECTIONS, _) | (_, None) => return None,
(_, Some(resource_id)) => resource_id,
};
Some(Grant {
capability: self.capability.clone(),
resource_id: resource_id.to_owned(),
allow_service: self.allow_service,
permission_key: self.permission_key.clone(),
})
}
}

/// The release requests a capability that this appliance cannot grant.
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct Unapprovable;
Expand Down Expand Up @@ -180,6 +201,14 @@ fn derive(manifest: &Value) -> (Vec<RequestedGrant>, bool) {
};
for capability in capabilities {
match (capability["id"].as_str(), capability["scope"].as_str()) {
(Some(DOCKER_INVENTORY), Some(DOCKER_CONNECTIONS))
if capability.get("resourceId").is_none() =>
{
add(
(DOCKER_INVENTORY, DOCKER_CONNECTIONS),
Some(PLATFORM_DOCKER_RESOURCE),
);
}
(Some(id), Some(scope)) if APPROVABLE.contains(&(id, scope)) => add((id, scope), None),
_ => approvable = false,
}
Expand Down Expand Up @@ -212,19 +241,7 @@ pub(crate) fn decide(
}
let mut grants = approval
.iter()
.map(|item| {
let resource_id = match (item.capability.scope.as_str(), &item.resource_id) {
(INSTALLATION, None) => installation_id.to_owned(),
(_, Some(resource_id)) => resource_id.clone(),
(_, None) => return Err(ApprovalRequired),
};
Ok(Grant {
capability: item.capability.clone(),
resource_id,
allow_service: item.allow_service,
permission_key: item.permission_key.clone(),
})
})
.map(|item| item.to_grant(installation_id).ok_or(ApprovalRequired))
.collect::<Result<Vec<_>, _>>()?;
let mut targets = BTreeSet::new();
let exact = grants.iter().all(|grant| {
Expand Down Expand Up @@ -366,19 +383,7 @@ pub(crate) fn same_decision(
) -> bool {
let Some(mut decided) = approval
.iter()
.map(|item| {
let resource_id = match (item.capability.scope.as_str(), &item.resource_id) {
(INSTALLATION, None) => installation_id.to_owned(),
(_, Some(resource_id)) => resource_id.clone(),
(_, None) => return None,
};
Some(Grant {
capability: item.capability.clone(),
resource_id,
allow_service: item.allow_service,
permission_key: item.permission_key.clone(),
})
})
.map(|item| item.to_grant(installation_id))
.collect::<Option<Vec<_>>>()
else {
return false;
Expand Down Expand Up @@ -489,6 +494,11 @@ fn serves(request: &RequestedGrant, grant: &Grant, installation_id: &str) -> boo
) {
(INSTALLATION, _) => grant.resource_id == installation_id,
(PROVIDER_PROFILES, _) => request.resource_id.as_ref() == Some(&grant.resource_id),
(DOCKER_CONNECTIONS, _) => {
grant.capability.id == DOCKER_INVENTORY
&& request.resource_id.as_deref() == Some(PLATFORM_DOCKER_RESOURCE)
&& grant.resource_id == PLATFORM_DOCKER_RESOURCE
}
(PROXY_HOSTS, ALL_PROXY_HOSTS) => {
DYNAMIC_HOST_CAPABILITIES.contains(&grant.capability.id.as_str())
&& grant.resource_id == ALL_HOSTS
Expand Down
24 changes: 23 additions & 1 deletion core/src/app_ipc/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ static APP_OPERATIONS: LazyLock<[HttpDescriptor; 19]> = LazyLock::new(|| {
.map(HttpOperation::descriptor)
});

fn operation(request: &Request<Incoming>) -> Result<Operation, Problem> {
fn operation<T>(request: &Request<T>) -> Result<Operation, Problem> {
let uri = request.uri();
if request.version() != Version::HTTP_11
|| uri.scheme().is_some()
Expand All @@ -617,6 +617,12 @@ fn operation(request: &Request<Incoming>) -> Result<Operation, Problem> {
Method::POST => HttpMethod::Post,
_ => return Err(Problem::Route),
};
if method == HttpMethod::Get && uri.path() == "/platform/v1/docker-inventory" {
return Ok(Operation {
json: false,
events: false,
});
}
let descriptor = APP_OPERATIONS
.iter()
.find(|operation| operation.method == method && route_matches(operation, uri.path()))
Expand All @@ -627,6 +633,22 @@ fn operation(request: &Request<Incoming>) -> Result<Operation, Problem> {
})
}

#[cfg(test)]
#[test]
fn docker_inventory_is_a_bodyless_read() {
let path = "/platform/v1/docker-inventory";
let read = Request::get(path).body(()).unwrap();
assert!(matches!(
operation(&read),
Ok(Operation {
json: false,
events: false
})
));
let write = Request::post(path).body(()).unwrap();
assert!(matches!(operation(&write), Err(Problem::Route)));
}

fn route_matches(operation: &HttpDescriptor, path: &str) -> bool {
if operation.path_parameter.is_none() {
return path == operation.path;
Expand Down
3 changes: 2 additions & 1 deletion core/src/app_manager/ui/operation_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::HashSet;
use serde::Deserialize;
use serde_json::Value;

use crate::app_install::grants::{Capability, Grant};
use crate::app_install::grants::{Capability, Grant, PLATFORM_DOCKER_RESOURCE};

use super::{
super::valid_id,
Expand Down Expand Up @@ -117,6 +117,7 @@ pub(super) fn valid_declared_grant(
&& (policy.support || capabilities.contains(&grant.capability.id))
&& valid_id(resource)
&& (scope != "installation" || resource == installation_id)
&& (scope != "dockerConnections" || resource == PLATFORM_DOCKER_RESOURCE)
&& (scope != ALL_PROXY_HOSTS || resource == ALL_HOSTS)
&& (scope != "providerProfiles"
|| (matches!(
Expand Down
128 changes: 126 additions & 2 deletions core/tests/private/app_install/grants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,130 @@ fn the_incident_capability_is_approvable_for_the_installation() {
}));
}

#[test]
fn docker_inventory_requires_approval_for_the_platform_connection() {
let inventory = manifest(
json!([{"id": "docker.inventory.observe.v1", "scope": "dockerConnections"}]),
json!([]),
);
let requested = requested(&inventory).unwrap();
assert_eq!(
requested,
[
item(
"docker.inventory.observe.v1",
"dockerConnections",
Some("platform-docker")
),
item("app.events.subscribe", "installation", None),
item("app.audit.record", "installation", None),
]
);
assert_eq!(
approve(&inventory, None, &[], None, ID),
Err(ApprovalRequired)
);

let mut approval = [
approved(
"docker.inventory.observe.v1",
"dockerConnections",
Some("platform-docker"),
),
approved("app.events.subscribe", "installation", None),
approved("app.audit.record", "installation", None),
];
approval[0].allow_service = false;
approval[0].permission_key = Some("view".into());
let decided = approve(&inventory, Some(&approval), &[], None, ID).unwrap();
assert!(decided.explicit);
assert!(decided.grants.contains(&Grant {
allow_service: false,
permission_key: Some("view".into()),
..grant(
"docker.inventory.observe.v1",
"dockerConnections",
"platform-docker"
)
}));
assert!(same_decision(&approval, &decided.grants, ID));
assert!(within(&inventory, &decided.grants, ID));
assert_eq!(
carry(&decided.grants, &requested, &keys(), ID),
Some(decided.grants)
);
approval[0].allow_service = true;
assert!(
decide(&requested, &keys(), &approval, ID)
.unwrap()
.iter()
.any(|grant| {
grant.capability.id == "docker.inventory.observe.v1" && grant.allow_service
})
);
approval[0].permission_key = Some("unlisted".into());
assert_eq!(
decide(&requested, &keys(), &approval, ID),
Err(ApprovalRequired)
);
}

#[test]
fn docker_inventory_refuses_other_scopes_and_resources() {
for scope in ["installation", "proxyHosts", "allProxyHosts"] {
let inventory = manifest(
json!([{"id": "docker.inventory.observe.v1", "scope": scope}]),
json!([]),
);
assert_eq!(requested(&inventory), Err(Unapprovable));
}
let named = manifest(
json!([{
"id": "docker.inventory.observe.v1", "scope": "dockerConnections", "resourceId": "local"
}]),
json!([]),
);
assert_eq!(requested(&named), Err(Unapprovable));

let inventory = manifest(
json!([{"id": "docker.inventory.observe.v1", "scope": "dockerConnections"}]),
json!([]),
);
let requested = requested(&inventory).unwrap();
let mut approval = [
approved("docker.inventory.observe.v1", "dockerConnections", None),
approved("app.events.subscribe", "installation", None),
approved("app.audit.record", "installation", None),
];
for resource in [None, Some("local"), Some("*"), Some("all"), Some(HOST)] {
approval[0].resource_id = resource.map(Into::into);
assert_eq!(
decide(&requested, &keys(), &approval, ID),
Err(ApprovalRequired),
"{resource:?}"
);
if let Some(resource) = resource {
let invalid = grant("docker.inventory.observe.v1", "dockerConnections", resource);
assert!(!serves(&requested[0], &invalid, ID));
assert!(!within(&inventory, std::slice::from_ref(&invalid), ID));
assert!(!same_decision(
&approval,
&[
invalid,
grant("app.events.subscribe", "installation", ID),
grant("app.audit.record", "installation", ID)
],
ID
));
}
}
approval[0] = approved("docker.inventory.observe.v1", "allProxyHosts", Some("all"));
assert_eq!(
decide(&requested, &keys(), &approval, ID),
Err(ApprovalRequired)
);
}

#[test]
fn requested_grants_derive_from_capabilities_and_provider_profiles() {
assert_eq!(
Expand Down Expand Up @@ -167,7 +291,7 @@ fn requested_grants_derive_from_capabilities_and_provider_profiles() {
fn capabilities_without_an_approval_flow_cannot_be_approved() {
for (id, scope) in [
("proxy.hosts.manage-owned.v1", "ownedProxyHosts"),
("docker.inventory.observe.v1", "dockerConnections"),
("docker.inventory.observe.v1", "proxyHosts"),
("dns.challenge.manage.v1", "dnsZones"),
("engine.contributions.submit.v1", "ownedEngineResources"),
("identity.provider.register.v1", "identityProviders"),
Expand Down Expand Up @@ -612,7 +736,7 @@ fn root_and_every_launch_stay_within_the_request() {
);
}
assert!(!within(&manifest, &[secret.clone(), secret], ID));
// A declared capability without an approval flow is not grantable either.
// Docker inventory only permits the platform-managed connection.
let docker = json!({
"capabilities": [{"id": "docker.inventory.observe.v1", "scope": "dockerConnections"}],
"providers": [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ fn escalated_catalog(current: &[u8]) -> Vec<u8> {
for package in release["packages"].as_array_mut().unwrap() {
let manifest = &mut package["manifest"];
manifest["version"] = ESCALATED_VERSION.into();
// Docker inventory has no platform endpoint yet, so no Owner can approve it.
manifest["capabilities"] =
json!([{"id": "docker.inventory.observe.v1", "scope": "dockerConnections"}]);
// Access logs have no app platform endpoint yet, so no Owner can approve it.
manifest["capabilities"] = json!([{"id": "access.logs.read.v1", "scope": "proxyHosts"}]);
// A distinct identity keeps the cached 1.0.1 archive from satisfying this release,
// so any staging attempt would have to request its release asset.
let identity = format!(
Expand Down
15 changes: 14 additions & 1 deletion core/tests/private/app_ui_operation_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fn scoped_capabilities_use_their_own_platform_permission_and_declared_provider_p
(
"docker.inventory.observe.v1",
"dockerConnections",
"local",
"platform-docker",
"docker_discovery.view",
),
(
Expand Down Expand Up @@ -127,6 +127,19 @@ fn scoped_capabilities_use_their_own_platform_permission_and_declared_provider_p
&["custom".into()],
&[]
));
let other_connection = grant(
"docker.inventory.observe.v1",
"dockerConnections",
"other-connection",
None,
);
assert!(!valid_declared_grant(
&other_connection,
INSTALLATION,
&["docker.inventory.observe.v1".into()],
&[],
&[]
));
}

#[test]
Expand Down
6 changes: 6 additions & 0 deletions web/src/config/docker-discovery.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { PERMISSIONS } from './permissions.config.ts'

export const APP_DOCKER_CONNECTION_ID = 'platform-docker'
export const APP_DOCKER_INVENTORY_CAPABILITY = {
id: 'docker.inventory.observe.v1',
scope: 'dockerConnections',
} as const

export const DOCKER_DISCOVERY_WORKER = {
fallbackMs: 60_000,
coalesceMs: 500,
Expand Down
2 changes: 2 additions & 0 deletions web/src/lib/AppCatalog/grantApproval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const grantNames = {
'proxy.hosts.read.v1': 'proxyHostsRead',
'diagnostics.upstream.probe.v1': 'upstreamProbe',
'diagnostics.upstream.probe.v2': 'upstreamMonitoring',
'docker.inventory.observe.v1': 'dockerInventoryObserve',
'notifications.publish.v1': 'notificationsPublish',
'notifications.incidents.manage.v1': 'notificationsIncidents',
'app.audit.record': 'auditRecord',
Expand All @@ -37,6 +38,7 @@ const grantScopes = {
installation: 'installation',
proxyHosts: 'proxyHosts',
allProxyHosts: 'allProxyHosts',
dockerConnections: 'dockerConnections',
providerProfiles: 'providerProfiles',
secretReferences: 'secretReferences',
} as const
Expand Down
Loading