Skip to content

Commit be9adeb

Browse files
committed
fix(network): integrate connection revalidation with policy backends
Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com>
1 parent 763dd76 commit be9adeb

21 files changed

Lines changed: 527 additions & 280 deletions

File tree

‎crates/openshell-policy-cedar-runtime/src/backend.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ impl PolicyBackend for CedarOnlyEngine {
4545
fn current_generation(&self) -> u64 {
4646
self.current_generation()
4747
}
48+
fn publish_credential_change(&self) -> Result<u64> {
49+
self.publish_credential_change()
50+
}
4851
fn generation_guard(&self, expected: u64) -> Result<PolicyGenerationGuard> {
4952
self.generation_guard(expected)
5053
}

‎crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,15 @@ impl CedarOnlyEngine {
651651
})
652652
}
653653

654+
/// Invalidate relays and configuration guards after credential revocation.
655+
/// The loaded policy and any quarantine remain unchanged.
656+
pub fn publish_credential_change(&self) -> Result<u64> {
657+
self.middleware.change_configuration(|| {
658+
let _guard = self.write_engine()?;
659+
Ok((self.advance_generation(), true))
660+
})
661+
}
662+
654663
/// Reactivates the active policy after a quarantine.
655664
///
656665
/// Returns the current Cedar generation, advanced only if a quarantine

‎crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2460,3 +2460,26 @@ fn destination_control_plane_checks_recognize_bracketed_ip_literals() {
24602460
);
24612461
}
24622462
}
2463+
2464+
#[test]
2465+
fn credential_publication_invalidates_relays_and_configuration_without_ending_quarantine() {
2466+
let cedar = Arc::new(CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"));
2467+
let engine = openshell_policy_runtime_interface::PolicyEngine::from(Arc::clone(&cedar));
2468+
for quarantined in [false, true] {
2469+
if quarantined {
2470+
cedar.enter_fail_closed("revocation test").unwrap();
2471+
}
2472+
let generation = engine.current_generation();
2473+
let input = middleware_input("api.example.com");
2474+
let connection = engine
2475+
.connection_generation_guard(input, generation, None)
2476+
.unwrap();
2477+
let configuration = engine.configuration_generation_guard().unwrap();
2478+
let tunnel = engine.tunnel_engine(generation).unwrap();
2479+
assert_eq!(engine.publish_credential_change().unwrap(), generation + 1);
2480+
assert!(connection.is_stale());
2481+
assert!(configuration.is_stale());
2482+
assert!(tunnel.is_stale());
2483+
assert_eq!(cedar.fail_closed_reason().is_some(), quarantined);
2484+
}
2485+
}

‎crates/openshell-policy-runtime-interface/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,9 @@ before service connections begin and commits policy, middleware, and credentials
1111
together. Request and address authorizers remain bound to the policy generation
1212
that admitted their connection. The relay keeps credentials and I/O state outside
1313
the policy-visible `L7PolicyContext`.
14+
15+
`PolicyBackend::connection_generation_guard` defaults to a strict generation
16+
check. Backends may attach a `ConnectionRevalidator` to follow publications that
17+
preserve an established connection's contract. Guard clones share the pin;
18+
ordinary configuration guards remain strict. The backend must reject intervening
19+
policy narrowing and quarantines, even if a later publication restores access.

‎crates/openshell-policy-runtime-interface/src/policy_types.rs‎

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@ pub struct EgressAuthorization {
354354
}
355355

356356
/// Input for a network access policy evaluation.
357+
#[derive(Clone, Debug)]
357358
pub struct NetworkInput {
358359
pub host: String,
359360
pub port: u16,
@@ -367,12 +368,20 @@ pub struct NetworkInput {
367368
pub cmdline_paths: Vec<PathBuf>,
368369
}
369370

371+
/// Backend-owned validation of an established connection across policy publications.
372+
/// Implementations must reject any intervening narrowing, including quarantines.
373+
pub trait ConnectionRevalidator: std::fmt::Debug + Send + Sync {
374+
fn follow(&self, pin: &AtomicU64, live: &AtomicU64) -> bool;
375+
fn pinned_policy_hash(&self, generation: u64) -> Option<String>;
376+
}
377+
370378
/// Generation guard captured when an HTTP tunnel or request path starts.
371379
#[derive(Clone, Debug)]
372380
pub struct PolicyGenerationGuard {
373-
captured_generation: u64,
381+
captured_generation: Arc<AtomicU64>,
374382
current_generation: Arc<AtomicU64>,
375383
generation_rx: watch::Receiver<u64>,
384+
revalidator: Option<Arc<dyn ConnectionRevalidator>>,
376385
}
377386

378387
/// Builds a [`PolicyGenerationGuard`] for any state holding a plain
@@ -398,23 +407,40 @@ pub fn generation_guard_for(
398407
));
399408
}
400409
Ok(PolicyGenerationGuard {
401-
captured_generation: current_generation_value,
410+
captured_generation: Arc::new(AtomicU64::new(current_generation_value)),
402411
current_generation: Arc::clone(current_generation),
403412
generation_rx: generation_tx.subscribe(),
413+
revalidator: None,
404414
})
405415
}
406416

407417
impl PolicyGenerationGuard {
418+
/// Attach a backend-owned connection contract. Ordinary guards remain strict.
419+
#[must_use]
420+
pub fn with_revalidator(mut self, revalidator: Option<Arc<dyn ConnectionRevalidator>>) -> Self {
421+
self.revalidator = revalidator;
422+
self
423+
}
424+
425+
pub fn pinned_policy_hash(&self) -> Option<String> {
426+
self.revalidator
427+
.as_ref()?
428+
.pinned_policy_hash(self.captured_generation())
429+
}
430+
408431
pub fn captured_generation(&self) -> u64 {
409-
self.captured_generation
432+
self.captured_generation.load(Ordering::Acquire)
410433
}
411434

412435
pub fn current_generation(&self) -> u64 {
413436
self.current_generation.load(Ordering::Acquire)
414437
}
415438

416439
pub fn is_stale(&self) -> bool {
417-
self.current_generation() != self.captured_generation
440+
self.revalidator.as_ref().map_or_else(
441+
|| self.current_generation() != self.captured_generation(),
442+
|revalidator| !revalidator.follow(&self.captured_generation, &self.current_generation),
443+
)
418444
}
419445

420446
pub fn ensure_current(&self) -> Result<()> {
@@ -428,10 +454,10 @@ impl PolicyGenerationGuard {
428454
Ok(())
429455
}
430456

431-
/// Wait until the policy generation changes.
457+
/// Wait until the authorizing policy no longer applies.
432458
///
433-
/// Relay boundaries use this to close even an idle or raw stream as soon
434-
/// as a new generation (including fail-closed quarantine) is published.
459+
/// Plain guards close on every publication; connection guards may follow
460+
/// unrelated changes, but must close on a quarantine or relevant narrowing.
435461
pub async fn wait_until_stale(&self) {
436462
let mut receiver = self.generation_rx.clone();
437463
while !self.is_stale() {

‎crates/openshell-policy-runtime-interface/src/runtime.rs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,18 @@ pub trait PolicyBackend: Send + Sync {
102102
fn label(&self) -> &'static str;
103103
fn authorize_egress(&self, input: &NetworkInput) -> Result<EgressAuthorization>;
104104
fn current_generation(&self) -> u64;
105+
/// Notify established relays after credentials change outside a policy commit.
106+
fn publish_credential_change(&self) -> Result<u64>;
105107
fn generation_guard(&self, expected: u64) -> Result<PolicyGenerationGuard>;
108+
/// Pin a relay; backends without connection contracts close on every change.
109+
fn connection_generation_guard(
110+
self: Arc<Self>,
111+
_input: NetworkInput,
112+
expected: u64,
113+
_credentials: Option<&openshell_core::provider_credentials::ProviderCredentialState>,
114+
) -> Result<PolicyGenerationGuard> {
115+
self.generation_guard(expected)
116+
}
106117
fn with_current_generation(
107118
&self,
108119
expected: u64,
@@ -178,6 +189,16 @@ impl PolicyEngine {
178189
})?;
179190
Ok(result)
180191
}
192+
pub fn connection_generation_guard(
193+
&self,
194+
input: NetworkInput,
195+
expected: u64,
196+
credentials: Option<&openshell_core::provider_credentials::ProviderCredentialState>,
197+
) -> Result<PolicyGenerationGuard> {
198+
self.0
199+
.clone()
200+
.connection_generation_guard(input, expected, credentials)
201+
}
181202
pub fn passthrough_middleware(&self) -> Result<PassthroughMiddleware<'_>> {
182203
Ok(self.0.passthrough_snapshot()?.map_or_else(
183204
|| PassthroughMiddleware::Live(self),
@@ -248,6 +269,11 @@ impl TunnelPolicyEngine {
248269
evaluator: Box::new(evaluator),
249270
}
250271
}
272+
#[must_use]
273+
pub fn with_generation_guard(mut self, guard: PolicyGenerationGuard) -> Self {
274+
self.generation_guard = guard;
275+
self
276+
}
251277
pub fn captured_generation(&self) -> u64 {
252278
self.generation_guard.captured_generation()
253279
}

‎crates/openshell-supervisor-network/README.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,12 @@ transparent connections lazily refresh expired, policy-backed mappings through
5353
the same trusted resolver and destination-validation path as sandbox DNS
5454
queries. Refreshes for one address share a lock; failed refreshes back off for
5555
one second and never authorize expired upstream addresses.
56-
`PolicyDnsService::lookup_for_connect` owns refresh coordination and returns
57-
the resulting mapping; the underlying store stays synchronous. Observation-only
58-
mappings, wrong ports, and mappings from a previous policy generation cannot refresh.
59-
Refresh eligibility uses the authored ports, independently of which ports the
60-
latest DNS addresses satisfied. Dispatch reauthorizes mapped connections and
61-
rebuilds their connectors from current pins instead of retaining staged pins
62-
across a refresh.
56+
`PolicyDnsService::lookup_for_connect` and `lookup_for_pin` coordinate refreshes;
57+
the underlying store stays synchronous. Observation-only mappings cannot refresh.
58+
A synthetic address identifies a name and address family across policy reloads.
59+
Each connection is authorized by the current policy, and its destination rules
60+
filter the mapping's pinned addresses. Dispatch rebuilds connectors from current
61+
pins instead of retaining staged pins across a refresh.
6362

6463
## Reserved destinations
6564

@@ -133,6 +132,11 @@ backend once at startup. `opa::OpaEngine` implements the YAML backend here;
133132
`openshell-policy-cedar-runtime` implements Cedar in a separate crate.
134133

135134
The proxy, relay, and policy DNS use shared decisions and generation guards.
135+
YAML relays attach a connection revalidator that compares full Rego endpoint
136+
rules across every intervening generation and checks credentials the connection
137+
used. Unrelated changes re-pin the connection; narrowing, quarantine, expired
138+
history, or a used credential's rotation closes it. Ordinary guards and Cedar
139+
connections retain strict invalidation on reload.
136140
An admitted connection carries an opaque destination authorizer that checks
137141
resolved addresses against the same policy snapshot. Networking applies its
138142
always-blocked address checks before the authorizer and blocks control-plane

‎crates/openshell-supervisor-network/src/conformance_support.rs‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,20 +95,16 @@ pub async fn dns_answers_outcome(
9595
Ok(resolved) => resolved,
9696
Err(refusal) => return refusal,
9797
};
98-
let Ok(mapping) = store.lookup(
99-
answer.address,
100-
port,
101-
answer.policy_generation,
102-
std::time::Instant::now(),
103-
) else {
98+
let Ok(mapping) = store.lookup_intent(answer.address, port, std::time::Instant::now()) else {
10499
return "no mapping for port".to_string();
105100
};
101+
if mapping.record.is_observation() {
102+
return "no mapping for port".to_string();
103+
}
106104
let mut pinned: Vec<String> = mapping
107105
.record
108-
.contracts
106+
.pinned_addresses
109107
.iter()
110-
.filter(|contract| contract.port == mapping.port)
111-
.flat_map(|contract| contract.pinned_addresses.iter())
112108
.map(ToString::to_string)
113109
.collect();
114110
pinned.sort();

‎crates/openshell-supervisor-network/src/l7/relay.rs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4521,8 +4521,9 @@ where
45214521
.as_ref()
45224522
.filter(|_| ctx.token_grant_resolver.is_some())
45234523
.and_then(EndpointObservationSender::capture);
4524-
let middleware_selection =
4524+
let mut middleware_selection =
45254525
middleware.map(|mw| mw.select(&middleware_network_input(ctx), generation_guard));
4526+
let selected_generation = generation_guard.captured_generation();
45264527
let inspected = matches!(
45274528
&middleware_selection,
45284529
Some(Ok(Some((chain, _)))) if !chain.is_empty()
@@ -4565,6 +4566,19 @@ where
45654566
return Ok(());
45664567
}
45674568

4569+
if generation_guard.captured_generation() != selected_generation
4570+
|| matches!(&middleware_selection, Some(Ok(None)))
4571+
{
4572+
middleware_selection =
4573+
middleware.map(|mw| mw.select(&middleware_network_input(ctx), generation_guard));
4574+
// Parsing already used the original selection's inspection mode.
4575+
if let Some(Ok(Some((chain, _)))) = &middleware_selection
4576+
&& chain.is_empty() == inspected
4577+
{
4578+
return Ok(());
4579+
}
4580+
}
4581+
45684582
request_count += 1;
45694583

45704584
// Build the logging representation without materializing a secret.
@@ -16511,7 +16525,11 @@ network_policies:
1651116525
&mut relay_upstream,
1651216526
&ctx,
1651316527
&generation_guard,
16514-
Some(relay_engine.as_ref()),
16528+
Some(
16529+
&PolicyEngine::from(relay_engine)
16530+
.passthrough_middleware()
16531+
.unwrap(),
16532+
),
1651516533
)
1651616534
.await
1651716535
});

0 commit comments

Comments
 (0)