diff --git a/core/src/app_install/grants.rs b/core/src/app_install/grants.rs index b8d736332..1d3e72ae5 100644 --- a/core/src/app_install/grants.rs +++ b/core/src/app_install/grants.rs @@ -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"; @@ -82,8 +86,8 @@ pub(crate) struct Grant { pub permission_key: Option, } -/// 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")] @@ -107,6 +111,23 @@ pub(crate) struct ApprovedGrant { pub permission_key: Option, } +impl ApprovedGrant { + fn to_grant(&self, installation_id: &str) -> Option { + 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; @@ -180,6 +201,14 @@ fn derive(manifest: &Value) -> (Vec, 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, } @@ -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::, _>>()?; let mut targets = BTreeSet::new(); let exact = grants.iter().all(|grant| { @@ -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::>>() else { return false; @@ -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 diff --git a/core/src/app_ipc/gateway.rs b/core/src/app_ipc/gateway.rs index e286c899f..f7a59ea87 100644 --- a/core/src/app_ipc/gateway.rs +++ b/core/src/app_ipc/gateway.rs @@ -603,7 +603,7 @@ static APP_OPERATIONS: LazyLock<[HttpDescriptor; 19]> = LazyLock::new(|| { .map(HttpOperation::descriptor) }); -fn operation(request: &Request) -> Result { +fn operation(request: &Request) -> Result { let uri = request.uri(); if request.version() != Version::HTTP_11 || uri.scheme().is_some() @@ -617,6 +617,12 @@ fn operation(request: &Request) -> Result { 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())) @@ -627,6 +633,22 @@ fn operation(request: &Request) -> Result { }) } +#[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; diff --git a/core/src/app_manager/ui/operation_policy.rs b/core/src/app_manager/ui/operation_policy.rs index ce1207bb5..b8543d61a 100644 --- a/core/src/app_manager/ui/operation_policy.rs +++ b/core/src/app_manager/ui/operation_policy.rs @@ -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, @@ -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!( diff --git a/core/tests/private/app_install/grants.rs b/core/tests/private/app_install/grants.rs index 30e0abd5b..51182fa1d 100644 --- a/core/tests/private/app_install/grants.rs +++ b/core/tests/private/app_install/grants.rs @@ -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!( @@ -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"), @@ -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": [], diff --git a/core/tests/private/app_manager/lifecycle/published_greeting/distribution_gates.rs b/core/tests/private/app_manager/lifecycle/published_greeting/distribution_gates.rs index 968fb6353..779da1c07 100644 --- a/core/tests/private/app_manager/lifecycle/published_greeting/distribution_gates.rs +++ b/core/tests/private/app_manager/lifecycle/published_greeting/distribution_gates.rs @@ -60,9 +60,8 @@ fn escalated_catalog(current: &[u8]) -> Vec { 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!( diff --git a/core/tests/private/app_ui_operation_policy.rs b/core/tests/private/app_ui_operation_policy.rs index fa316e2c7..33a0f94ae 100644 --- a/core/tests/private/app_ui_operation_policy.rs +++ b/core/tests/private/app_ui_operation_policy.rs @@ -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", ), ( @@ -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] diff --git a/web/src/config/docker-discovery.config.ts b/web/src/config/docker-discovery.config.ts index 302fe2a29..0bcca5a11 100644 --- a/web/src/config/docker-discovery.config.ts +++ b/web/src/config/docker-discovery.config.ts @@ -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, diff --git a/web/src/lib/AppCatalog/grantApproval.ts b/web/src/lib/AppCatalog/grantApproval.ts index 2d23b67a0..5413619c4 100644 --- a/web/src/lib/AppCatalog/grantApproval.ts +++ b/web/src/lib/AppCatalog/grantApproval.ts @@ -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', @@ -37,6 +38,7 @@ const grantScopes = { installation: 'installation', proxyHosts: 'proxyHosts', allProxyHosts: 'allProxyHosts', + dockerConnections: 'dockerConnections', providerProfiles: 'providerProfiles', secretReferences: 'secretReferences', } as const diff --git a/web/src/lib/Language/Locales/de.json b/web/src/lib/Language/Locales/de.json index ca136d4e8..959cd70e5 100644 --- a/web/src/lib/Language/Locales/de.json +++ b/web/src/lib/Language/Locales/de.json @@ -359,6 +359,7 @@ "proxyHostsRead": "Proxy-Hosts lesen", "upstreamProbe": "Erreichbarkeit von Upstreams prüfen", "upstreamMonitoring": "Upstreams fortlaufend überwachen", + "dockerInventoryObserve": "Docker-Inventar lesen", "notificationsPublish": "Benachrichtigungen senden", "notificationsIncidents": "Benachrichtigungs-Incidents melden", "auditRecord": "Einträge ins Audit-Protokoll schreiben", @@ -368,6 +369,7 @@ "unknown": "Funktion {{id}}" }, "scope": { + "dockerConnections": "Für die von der Plattform verwaltete Docker-Verbindung", "installation": "Für diese App", "proxyHosts": "Für die ausgewählten Proxy-Hosts", "providerProfiles": "Provider-Profil {{resource}}", diff --git a/web/src/lib/Language/Locales/en.json b/web/src/lib/Language/Locales/en.json index 67fd0fe60..fddab121e 100644 --- a/web/src/lib/Language/Locales/en.json +++ b/web/src/lib/Language/Locales/en.json @@ -359,6 +359,7 @@ "proxyHostsRead": "Read proxy hosts", "upstreamProbe": "Check upstream reachability", "upstreamMonitoring": "Monitor upstreams continuously", + "dockerInventoryObserve": "Read Docker inventory", "notificationsPublish": "Send notifications", "notificationsIncidents": "Raise notification incidents", "auditRecord": "Write audit log entries", @@ -368,6 +369,7 @@ "unknown": "Capability {{id}}" }, "scope": { + "dockerConnections": "For the Docker connection managed by the platform", "installation": "For this app", "proxyHosts": "For the proxy hosts you select", "providerProfiles": "Provider profile {{resource}}", diff --git a/web/src/lib/Language/Locales/es.json b/web/src/lib/Language/Locales/es.json index 13d612461..9d0f1aaf4 100644 --- a/web/src/lib/Language/Locales/es.json +++ b/web/src/lib/Language/Locales/es.json @@ -361,6 +361,7 @@ "proxyHostsRead": "Leer hosts proxy", "upstreamProbe": "Comprobar la disponibilidad de los upstreams", "upstreamMonitoring": "Supervisar los upstreams de forma continua", + "dockerInventoryObserve": "Leer el inventario de Docker", "notificationsPublish": "Enviar notificaciones", "notificationsIncidents": "Notificar incidentes", "auditRecord": "Escribir entradas de auditoría", @@ -370,6 +371,7 @@ "unknown": "Función {{id}}" }, "scope": { + "dockerConnections": "Para la conexión de Docker gestionada por la plataforma", "installation": "Para esta aplicación", "proxyHosts": "Para los hosts proxy que selecciones", "providerProfiles": "Perfil de proveedor {{resource}}", diff --git a/web/src/lib/Language/Locales/fr.json b/web/src/lib/Language/Locales/fr.json index fea55866e..62ee20aa9 100644 --- a/web/src/lib/Language/Locales/fr.json +++ b/web/src/lib/Language/Locales/fr.json @@ -361,6 +361,7 @@ "proxyHostsRead": "Lire les hôtes proxy", "upstreamProbe": "Vérifier la joignabilité des upstreams", "upstreamMonitoring": "Surveiller les upstreams en continu", + "dockerInventoryObserve": "Lire l’inventaire Docker", "notificationsPublish": "Envoyer des notifications", "notificationsIncidents": "Signaler des incidents de notification", "auditRecord": "Écrire dans le journal d’audit", @@ -370,6 +371,7 @@ "unknown": "Fonctionnalité {{id}}" }, "scope": { + "dockerConnections": "Pour la connexion Docker gérée par la plateforme", "installation": "Pour cette application", "proxyHosts": "Pour les hôtes proxy que vous sélectionnez", "providerProfiles": "Profil de fournisseur {{resource}}", diff --git a/web/src/lib/Language/Locales/it.json b/web/src/lib/Language/Locales/it.json index f1bc3ae27..02afaad65 100644 --- a/web/src/lib/Language/Locales/it.json +++ b/web/src/lib/Language/Locales/it.json @@ -361,6 +361,7 @@ "proxyHostsRead": "Leggere gli host proxy", "upstreamProbe": "Verificare la raggiungibilità degli upstream", "upstreamMonitoring": "Monitorare gli upstream in modo continuo", + "dockerInventoryObserve": "Leggere l’inventario Docker", "notificationsPublish": "Inviare notifiche", "notificationsIncidents": "Segnalare incidenti di notifica", "auditRecord": "Scrivere voci nel registro di audit", @@ -370,6 +371,7 @@ "unknown": "Funzionalità {{id}}" }, "scope": { + "dockerConnections": "Per la connessione Docker gestita dalla piattaforma", "installation": "Per questa app", "proxyHosts": "Per gli host proxy che selezioni", "providerProfiles": "Profilo provider {{resource}}", diff --git a/web/src/lib/Language/Locales/nl.json b/web/src/lib/Language/Locales/nl.json index bb650f2b0..b515b5d02 100644 --- a/web/src/lib/Language/Locales/nl.json +++ b/web/src/lib/Language/Locales/nl.json @@ -340,6 +340,7 @@ "proxyHostsRead": "Proxyhosts lezen", "upstreamProbe": "Bereikbaarheid van upstreams controleren", "upstreamMonitoring": "Upstreams doorlopend bewaken", + "dockerInventoryObserve": "Docker-inventaris lezen", "notificationsPublish": "Meldingen versturen", "notificationsIncidents": "Meldingsincidenten melden", "auditRecord": "Vermeldingen in het auditlogboek schrijven", @@ -349,6 +350,7 @@ "unknown": "Functie {{id}}" }, "scope": { + "dockerConnections": "Voor de Docker-verbinding die door het platform wordt beheerd", "installation": "Voor deze app", "proxyHosts": "Voor de proxyhosts die je selecteert", "providerProfiles": "Providerprofiel {{resource}}", diff --git a/web/src/lib/Language/Locales/pl.json b/web/src/lib/Language/Locales/pl.json index b38a12f10..03513a272 100644 --- a/web/src/lib/Language/Locales/pl.json +++ b/web/src/lib/Language/Locales/pl.json @@ -363,6 +363,7 @@ "proxyHostsRead": "Odczyt hostów proxy", "upstreamProbe": "Sprawdzanie dostępności upstreamów", "upstreamMonitoring": "Ciągłe monitorowanie upstreamów", + "dockerInventoryObserve": "Odczyt inwentarza Dockera", "notificationsPublish": "Wysyłanie powiadomień", "notificationsIncidents": "Zgłaszanie incydentów powiadomień", "auditRecord": "Zapisywanie wpisów w dzienniku audytu", @@ -372,6 +373,7 @@ "unknown": "Funkcja {{id}}" }, "scope": { + "dockerConnections": "Dla połączenia z Dockerem zarządzanego przez platformę", "installation": "Dla tej aplikacji", "proxyHosts": "Dla wybranych hostów proxy", "providerProfiles": "Profil dostawcy {{resource}}", diff --git a/web/src/lib/Language/Locales/pt.json b/web/src/lib/Language/Locales/pt.json index 2af5b076b..bbb43c384 100644 --- a/web/src/lib/Language/Locales/pt.json +++ b/web/src/lib/Language/Locales/pt.json @@ -361,6 +361,7 @@ "proxyHostsRead": "Ler hosts proxy", "upstreamProbe": "Verificar a acessibilidade dos upstreams", "upstreamMonitoring": "Monitorar os upstreams continuamente", + "dockerInventoryObserve": "Ler o inventário do Docker", "notificationsPublish": "Enviar notificações", "notificationsIncidents": "Reportar incidentes de notificação", "auditRecord": "Escrever entradas no registo de auditoria", @@ -370,6 +371,7 @@ "unknown": "Funcionalidade {{id}}" }, "scope": { + "dockerConnections": "Para a conexão com o Docker gerenciada pela plataforma", "installation": "Para esta aplicação", "proxyHosts": "Para os hosts proxy que selecionar", "providerProfiles": "Perfil de fornecedor {{resource}}", diff --git a/web/src/server/AppRuntime/Types/gateway.types.ts b/web/src/server/AppRuntime/Types/gateway.types.ts index f3fcc5b18..28d3e1d7f 100644 --- a/web/src/server/AppRuntime/Types/gateway.types.ts +++ b/web/src/server/AppRuntime/Types/gateway.types.ts @@ -3,6 +3,7 @@ import type { AppRuntimeCredentials } from './authority.types.ts' export type AppRuntimeOperation = | 'context' | 'authorization' + | 'dockerInventory' | 'listHosts' | 'updateHost' | 'probe' diff --git a/web/src/server/AppRuntime/authority-policy.server.ts b/web/src/server/AppRuntime/authority-policy.server.ts index 1db333adf..cbaa399e9 100644 --- a/web/src/server/AppRuntime/authority-policy.server.ts +++ b/web/src/server/AppRuntime/authority-policy.server.ts @@ -1,5 +1,9 @@ import '@tanstack/react-start/server-only' +import { + APP_DOCKER_CONNECTION_ID, + APP_DOCKER_INVENTORY_CAPABILITY, +} from '@/config/docker-discovery.config.ts' import { PERMISSIONS } from '@/config/permissions.config.ts' import type { PermissionKey } from '@/config/Types/permissions-config.types.ts' import { @@ -72,6 +76,8 @@ export function isAppRuntimeGrantTarget( appProviderProfileSchema.safeParse(resourceId).success) && // A grant for all proxy hosts names no host, only the fixed resource. (capability.scope !== 'allProxyHosts' || resourceId === ALL_PROXY_HOSTS_RESOURCE) && + (capability.scope !== APP_DOCKER_INVENTORY_CAPABILITY.scope || + resourceId === APP_DOCKER_CONNECTION_ID) && (isAppRuntimeSupportCapability(capability) || appGrantCapabilitySchema.safeParse(capability).success) ) diff --git a/web/src/server/AppRuntime/docker-inventory.server.ts b/web/src/server/AppRuntime/docker-inventory.server.ts new file mode 100644 index 000000000..dac6d56ac --- /dev/null +++ b/web/src/server/AppRuntime/docker-inventory.server.ts @@ -0,0 +1,53 @@ +import '@tanstack/react-start/server-only' + +import { APP_DOCKER_CONNECTION_ID } from '@/config/docker-discovery.config.ts' +import { dockerDiscoveryController } from '@/server/Controller/docker-discovery.server.ts' +import { AppRuntimeProblem } from './problem.ts' +import { AppRuntimeAuthorityError } from './Types/authority.types.ts' + +/** Project the controller's cached inventory under a current grant. */ +export async function readGrantedAppDockerInventory( + authorize: () => Promise, + signal: AbortSignal, + status = dockerDiscoveryController.status, +) { + async function requireFreshAuthorization() { + signal.throwIfAborted() + const expiresAt = await authorize() + signal.throwIfAborted() + if (expiresAt.getTime() <= Date.now()) throw new AppRuntimeAuthorityError('unauthorized') + } + + await requireFreshAuthorization() + let snapshot: Awaited> + try { + snapshot = await status(signal) + } catch { + signal.throwIfAborted() + throw new AppRuntimeProblem( + 503, + 'unavailable', + 'The configured Docker inventory is unavailable.', + ) + } + const inventory = { + connectionId: APP_DOCKER_CONNECTION_ID, + configurationRevision: snapshot.configuration.revision, + configured: snapshot.configuration.settings.endpoint !== null, + enabled: snapshot.configuration.settings.enabled, + status: snapshot.status, + stale: snapshot.stale, + error: snapshot.error, + candidates: snapshot.candidates.map( + ({ containerId, sourceId, domains, target, issues }) => ({ + containerId, + sourceId, + domains, + target, + issues, + }), + ), + } + await requireFreshAuthorization() + return inventory +} diff --git a/web/src/server/AppRuntime/gateway.server.ts b/web/src/server/AppRuntime/gateway.server.ts index 042c3349f..7bc13e484 100644 --- a/web/src/server/AppRuntime/gateway.server.ts +++ b/web/src/server/AppRuntime/gateway.server.ts @@ -23,6 +23,7 @@ const unauthorized = new AppRuntimeProblem(401, 'unauthorized', 'App API credent const directRoutes = new Map([ ['GET /platform/v1/context', 'context'], ['POST /platform/v1/authorization', 'authorization'], + ['GET /platform/v1/docker-inventory', 'dockerInventory'], ['POST /platform/v1/proxy-hosts/query', 'listHosts'], ['POST /platform/v1/proxy-hosts/owned', 'updateHost'], ['POST /platform/v1/diagnostics/upstream', 'probe'], diff --git a/web/src/server/AppRuntime/services.server.ts b/web/src/server/AppRuntime/services.server.ts index bd5a75614..61ac6ad52 100644 --- a/web/src/server/AppRuntime/services.server.ts +++ b/web/src/server/AppRuntime/services.server.ts @@ -4,6 +4,10 @@ import { sql } from 'drizzle-orm' import { setTimeout as delay } from 'node:timers/promises' import type { z } from 'zod' +import { + APP_DOCKER_CONNECTION_ID, + APP_DOCKER_INVENTORY_CAPABILITY, +} from '@/config/docker-discovery.config.ts' import { getAuthDatabase } from '@/server/Auth/Core/database.server.ts' import type { AuthTransaction } from '@/server/Auth/Core/Types/database.types.ts' import { @@ -18,6 +22,7 @@ import { readAppRuntimeContextInTransaction, readAppRuntimeProviderInTransaction, readAppRuntimeSecretInTransaction, + requireAppRuntimeAuthorization, resolveAppRuntimePrincipalInTransaction, } from './authority.server.ts' import { @@ -31,6 +36,7 @@ import { appUpstreamProbe, appUpstreamProbeBatch, } from './contract.ts' +import { readGrantedAppDockerInventory } from './docker-inventory.server.ts' import { replayAppRuntimeEventsInTransaction } from './events.server.ts' import { listAppProxyHosts, probeAppProxyUpstream } from './hosts.server.ts' import { probeAppProxyUpstreams } from './upstream-probes.server.ts' @@ -219,6 +225,25 @@ export function executeAppRuntimeCall( }) }) } + case 'dockerInventory': + return json( + await readGrantedAppDockerInventory( + () => + transact(async (transaction) => { + const principal = await resolveAppRuntimePrincipalInTransaction( + transaction, + credentials, + ) + requireAppRuntimeAuthorization( + principal, + APP_DOCKER_INVENTORY_CAPABILITY, + APP_DOCKER_CONNECTION_ID, + ) + return principal.expiresAt + }), + signal, + ), + ) case 'listHosts': return json( await listAppProxyHosts( diff --git a/web/src/tests/features/AppCatalog/catalog-install-ui.test.tsx b/web/src/tests/features/AppCatalog/catalog-install-ui.test.tsx index e9b94d191..d5e00a346 100644 --- a/web/src/tests/features/AppCatalog/catalog-install-ui.test.tsx +++ b/web/src/tests/features/AppCatalog/catalog-install-ui.test.tsx @@ -612,6 +612,43 @@ test('installs a release with capabilities only after the Owner approves its acc } }) +test('asks the Owner to approve the fixed Docker inventory connection', async () => { + const capability = { id: 'docker.inventory.observe.v1', scope: 'dockerConnections' } + const inventory = { capability, resourceId: 'platform-docker', allowService: true } + snapshot = { + ...ready, + entries: [{ ...ready.entries[0]!, grants: [inventory, ...requesting()] }], + } + apps = [] + const post = spyOn(globalThis, 'fetch').mockResolvedValue( + Response.json(pending, { status: 202 }), + ) + const { button, unmount } = await mountCatalog() + try { + await waitFor(() => button('Install')?.disabled === false) + await act(async () => button('Install')!.click()) + await waitFor(() => dialogButton('Approve and install')?.disabled === false) + expect(openDialog()!.textContent).toContain('Read Docker inventory') + expect(openDialog()!.textContent).toContain( + 'For the Docker connection managed by the platform', + ) + expect(openDialog()!.querySelector('button[role="combobox"]')).toBeNull() + expect(post).not.toHaveBeenCalled() + + await act(async () => dialogButton('Approve and install')!.click()) + await waitFor(() => post.mock.calls.length === 1) + expect(post).toHaveBeenCalledWith( + APP_CATALOG_INSTALL_PATH, + expect.objectContaining({ + body: JSON.stringify({ ...selection, approval: [inventory, ...requesting()] }), + }), + ) + } finally { + await unmount() + post.mockRestore() + } +}) + test('approves all proxy hosts instead of selecting them', async () => { snapshot = { ...ready, diff --git a/web/src/tests/lib/AppCatalog/grant-approval.test.ts b/web/src/tests/lib/AppCatalog/grant-approval.test.ts index 3e6830b8e..a69015723 100644 --- a/web/src/tests/lib/AppCatalog/grant-approval.test.ts +++ b/web/src/tests/lib/AppCatalog/grant-approval.test.ts @@ -23,6 +23,8 @@ const read = { id: 'proxy.hosts.read.v1', scope: 'proxyHosts' } const notify = { id: 'notifications.publish.v1', scope: 'installation' } const provider = { id: 'app.provider.register', scope: 'providerProfiles' } const audit = { id: 'app.audit.record', scope: 'installation' } +const inventory = { id: 'docker.inventory.observe.v1', scope: 'dockerConnections' } +const missingHost = () => false const requested: CatalogRequestedGrant[] = [ { capability: read, allowService: true }, @@ -80,6 +82,25 @@ describe('catalog grant approval', () => { }) }) + test('submits the fixed Docker connection without a host selection', () => { + const resourceId = 'platform-docker' + const draft = grantDraft( + [{ capability: inventory, resourceId, allowService: true }], + ['view'], + ) + expect(draft[0]).toMatchObject({ resourceId, selectable: false, allHostsAvailable: false }) + expect(grantDraftComplete(draft, missingHost)).toBe(true) + const narrowed = updateGrantDraft(draft, 0, { + allowService: false, + permissionKey: 'view', + resources: HOSTS, + allHosts: true, + }) + expect(grantApproval(narrowed, missingHost)).toEqual([ + { capability: inventory, resourceId, allowService: false, permissionKey: 'view' }, + ]) + }) + test('preselects a previous approval where it still applies', () => { const previous: CatalogGrant[] = [ { capability: read, resourceId: HOST_B, allowService: false, permissionKey: 'view' }, @@ -109,13 +130,12 @@ describe('catalog grant approval', () => { test('names capabilities and scopes, and separates support grants', () => { expect(grantNameKey(read)).toBe('proxyHostsRead') - expect( - grantNameKey({ id: 'docker.inventory.observe.v1', scope: 'dockerConnections' }), - ).toBe('unknown') + expect(grantNameKey(inventory)).toBe('dockerInventoryObserve') expect(grantNameKey({ id: 'constructor', scope: 'installation' })).toBe('unknown') expect(grantScopeKey(provider)).toBe('providerProfiles') expect(grantScopeKey({ id: read.id, scope: 'allProxyHosts' })).toBe('allProxyHosts') - expect(grantScopeKey({ id: read.id, scope: 'dockerConnections' })).toBe('unknown') + expect(grantScopeKey(inventory)).toBe('dockerConnections') + expect(grantScopeKey({ id: read.id, scope: 'unknownScope' })).toBe('unknown') expect([read, notify, provider, audit].map(isSupportGrant)).toEqual([ false, false, diff --git a/web/src/tests/server/AppRuntime/authority.test.ts b/web/src/tests/server/AppRuntime/authority.test.ts index 651c718f8..7ca4dfd07 100644 --- a/web/src/tests/server/AppRuntime/authority.test.ts +++ b/web/src/tests/server/AppRuntime/authority.test.ts @@ -1,5 +1,9 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { + APP_DOCKER_CONNECTION_ID, + APP_DOCKER_INVENTORY_CAPABILITY, +} from '@/config/docker-discovery.config.ts' import { PERMISSIONS } from '@/config/permissions.config.ts' import { APP_RUNTIME_SUPPORT_CAPABILITIES, @@ -69,6 +73,42 @@ const userPrincipal: AppRuntimePrincipal = { } describe('app runtime authorization', () => { + test('binds Docker inventory visibility to the configured connection and current access', () => { + const capability = APP_DOCKER_INVENTORY_CAPABILITY + const resourceId = APP_DOCKER_CONNECTION_ID + const grant = { capability, resourceId, allowService: true } + expect(isAppRuntimeGrantTarget(capability, resourceId, installationId)).toBe(true) + expect(isAppRuntimeGrantTarget(capability, 'other-connection', installationId)).toBe(false) + expect( + isAppRuntimeAuthorized( + { ...servicePrincipal, grants: [grant] }, + capability, + resourceId, + ), + ).toBe(true) + expect( + isAppRuntimeAuthorized( + { ...servicePrincipal, grants: [{ ...grant, allowService: false }] }, + capability, + resourceId, + ), + ).toBe(false) + expect( + isAppRuntimeAuthorized({ ...userPrincipal, grants: [grant] }, capability, resourceId), + ).toBe(false) + expect( + isAppRuntimeAuthorized( + { + ...userPrincipal, + grants: [grant], + permissions: [...userPrincipal.permissions, PERMISSIONS.DOCKER_DISCOVERY_VIEW], + }, + capability, + resourceId, + ), + ).toBe(true) + }) + test('requires the exact capability scope and resource and explicit autonomous permission', () => { expect(isAppRuntimeAuthorized(servicePrincipal, readCapability, 'host-a')).toBe(true) expect(isAppRuntimeAuthorized(servicePrincipal, readCapability, 'host-b')).toBe(false) diff --git a/web/src/tests/server/AppRuntime/docker-inventory.test.ts b/web/src/tests/server/AppRuntime/docker-inventory.test.ts new file mode 100644 index 000000000..f441e7be9 --- /dev/null +++ b/web/src/tests/server/AppRuntime/docker-inventory.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from 'bun:test' +import type { DockerDiscoverySnapshot } from '@/lib/DockerDiscovery/Types/docker-discovery.types.ts' +import { readGrantedAppDockerInventory } from '@/server/AppRuntime/docker-inventory.server.ts' +import { AppRuntimeAuthorityError } from '@/server/AppRuntime/Types/authority.types.ts' + +const signal = new AbortController().signal +const activeLease = () => Promise.resolve(new Date(Date.now() + 60_000)) +const observedHost = { + containerId: 'a'.repeat(64), + sourceId: 'label:fixture', + domains: ['fixture.example'], + target: { scheme: 'https', address: '192.0.2.10', port: 443, network: 'test-proxy' }, + issues: [], +} as const +const snapshot = { + configuration: { + version: 1, + revision: 3, + settings: { enabled: true, endpoint: 'http://controller-fixture.example:2375' }, + }, + status: 'ready', + stale: false, + error: null, + candidates: [ + { + ...observedHost, + domains: [...observedHost.domains], + issues: [...observedHost.issues], + certificateId: '0193c005-0000-7000-8000-000000000022', + accessPolicyId: '0193c005-0000-7000-8000-000000000023', + upstreamTlsServerName: 'backend.fixture.example', + }, + ], +} satisfies DockerDiscoverySnapshot + +describe('app Docker inventory projection', () => { + test('checks authority around the read and returns only the bounded projection', async () => { + const calls: string[] = [] + const result = await readGrantedAppDockerInventory( + () => { + calls.push('authorize') + return activeLease() + }, + signal, + (receivedSignal) => { + expect(receivedSignal).toBe(signal) + calls.push('read') + return Promise.resolve(snapshot) + }, + ) + expect(calls).toEqual(['authorize', 'read', 'authorize']) + expect(result).toEqual({ + connectionId: 'platform-docker', + configurationRevision: 3, + configured: true, + enabled: true, + status: 'ready', + stale: false, + error: null, + candidates: [{ ...observedHost, domains: [...observedHost.domains], issues: [] }], + }) + }) + + test('denies access before consulting the controller', async () => { + const denied = new AppRuntimeAuthorityError('forbidden') + let attempted = false + await expect( + readGrantedAppDockerInventory( + () => Promise.reject(denied), + signal, + () => { + attempted = true + return Promise.resolve(snapshot) + }, + ), + ).rejects.toBe(denied) + expect(attempted).toBe(false) + }) + + test('withholds observations when the grant is revoked during the controller read', async () => { + const denied = new AppRuntimeAuthorityError('forbidden') + let revoked = false + await expect( + readGrantedAppDockerInventory( + () => (revoked ? Promise.reject(denied) : activeLease()), + signal, + () => { + revoked = true + return Promise.resolve(snapshot) + }, + ), + ).rejects.toBe(denied) + }) + + test('withholds the snapshot if authority expires during the final check', async () => { + let checked = false + await expect( + readGrantedAppDockerInventory( + () => { + if (checked) return Promise.resolve(new Date(0)) + checked = true + return activeLease() + }, + signal, + () => Promise.resolve(snapshot), + ), + ).rejects.toMatchObject({ code: 'unauthorized' }) + }) + + test('returns a safe error when the controller is unavailable', async () => { + await expect( + readGrantedAppDockerInventory(activeLease, signal, () => + Promise.reject(new Error('private controller failure')), + ), + ).rejects.toThrow('The configured Docker inventory is unavailable.') + }) +}) diff --git a/web/src/tests/server/AppRuntime/gateway.test.ts b/web/src/tests/server/AppRuntime/gateway.test.ts index 661ed26e2..c66af2110 100644 --- a/web/src/tests/server/AppRuntime/gateway.test.ts +++ b/web/src/tests/server/AppRuntime/gateway.test.ts @@ -29,6 +29,18 @@ function fixture() { } describe('private app gateway', () => { + test('dispatches the broker-authenticated Docker inventory read', async () => { + const { gateway, calls } = fixture() + const path = 'http://app-api/platform/v1/docker-inventory' + expect((await gateway(new Request(path))).status).toBe(401) + expect((await gateway(new Request(path, { method: 'POST', headers }))).status).toBe(404) + expect((await gateway(new Request(path, { headers }))).status).toBe(204) + expect(calls).toHaveLength(1) + expect(calls[0]?.operation).toBe('dockerInventory') + expect(calls[0]?.credentials).toEqual({ identity }) + expect(calls[0]?.resourceId).toBeUndefined() + }) + test('finishes a cancelled request while its handler still waits for admission', async () => { const shutdown = new AbortController() const client = new AbortController()