Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
8e20e08
test(network): characterise which connections policy reloads should c…
mr-miles Nov 7, 2026
2884ff3
fix(network): keep connections open across policy reloads that do not…
mr-miles Nov 7, 2026
8eaf79d
test(network): cover connection revalidation and credential versioning
mr-miles Nov 7, 2026
f61047c
test(network): rewrite the characterisation tests for the new APIs
mr-miles Nov 7, 2026
fc9083c
test(network): relays set up across an unrelated reload should start
mr-miles Nov 15, 2026
c49f000
fix(network): re-evaluate a reload that lands during relay setup
mr-miles Nov 15, 2026
9ef375c
refactor(network): split pinning out of direct transparent TCP handling
mr-miles Nov 15, 2026
ccb1dfd
test(network): policy DNS answers should follow the current policy, n…
mr-miles Nov 15, 2026
184cc5d
fix(network): judge policy DNS answers by the current policy, not the…
mr-miles Nov 15, 2026
ecdb312
test(network): kept policy DNS answers give no access the current pol…
mr-miles Nov 15, 2026
c39614a
docs(rfc): policy DNS mappings are judged by the current policy
mr-miles Nov 15, 2026
8ef9c7c
fix(network): refresh a policy DNS mapping that expires during author…
mr-miles Nov 20, 2026
099e7a1
docs(policies): placeholders outlive policy changes and their TTL
mr-miles Nov 20, 2026
06a17c4
fix(network): adapt relay tests to current process identity
johntmyers Nov 20, 2026
e970fb2
fix(network): preserve MCP observations after idle policy reloads
johntmyers Nov 20, 2026
61332a5
fix(network): preserve credential invalidation across reloads
johntmyers Nov 21, 2026
763dd76
test(network): adapt IPv6 coverage to persistent DNS mappings
johntmyers Nov 24, 2026
be9adeb
fix(network): integrate connection revalidation with policy backends
johntmyers Nov 24, 2026
297661e
fix(network): borrow DNS service in Linux transparent relay
johntmyers Nov 24, 2026
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
963 changes: 939 additions & 24 deletions crates/openshell-core/src/provider_credentials.rs

Large diffs are not rendered by default.

184 changes: 181 additions & 3 deletions crates/openshell-core/src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,102 @@ pub struct SecretResolver {
denied_env_keys: HashSet<String>,
identity_bound_env_keys: HashSet<String>,
revision_fallback_allowed_revisions: HashMap<String, Arc<HashSet<u64>>>,
/// Where to report that this resolver handed out a real secret.
use_record: Option<ResolverUseRecord>,
}

/// Version that never matches a live credential version.
///
/// Recorded for a value served from an older generation, which by definition
/// is no longer current, so the connection closes at its next check.
pub const STALE_CREDENTIAL_VERSION: u64 = 0;

/// Records which provider credentials a connection injected, by version.
///
/// The supervisor attaches one marker per proxied connection. Every resolver
/// derived for that connection reports each real secret it hands out, and
/// token-grant injection reports each grant before adding it. An empty marker
/// means the connection has never carried a provider credential upstream, so
/// no credential change can leave it holding stale material.
///
/// The provider credential state owns one version per credential, assigned
/// by comparing content whenever its snapshot changes; a connection keeps only
/// the version it used:
///
/// - static credentials by environment key;
/// - token grants by `provider:credential` identity.
///
/// A use that cannot be attributed to a credential is recorded under its raw
/// placeholder or key at [`STALE_CREDENTIAL_VERSION`], so the connection
/// closes on the next credential check rather than never.
///
/// Each key keeps its first recorded version. Recording is a superset by
/// design: some callers resolve to validate rather than to send, which can
/// only make a connection close more often.
#[derive(Debug, Default)]
pub struct CredentialUseMarker {
uses: std::sync::Mutex<CredentialUses>,
}

/// The credentials one connection has injected; see [`CredentialUseMarker`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CredentialUses {
/// Static credential environment key to the version sent.
pub static_versions: std::collections::BTreeMap<String, u64>,
/// Token grant `provider:credential` identity to the version injected.
pub grant_versions: std::collections::BTreeMap<String, u64>,
}

impl CredentialUses {
/// Whether nothing has been injected.
pub fn is_empty(&self) -> bool {
self.static_versions.is_empty() && self.grant_versions.is_empty()
}
}

impl CredentialUseMarker {
/// Record that version `version` of the static credential `env_key` was sent.
pub fn record_static(&self, env_key: &str, version: u64) {
self.with_uses(|uses| {
uses.static_versions
.entry(env_key.to_owned())
.or_insert(version);
});
}

/// Record that version `version` of the token grant `identity` was used.
pub fn record_grant(&self, identity: &str, version: u64) {
self.with_uses(|uses| {
uses.grant_versions
.entry(identity.to_owned())
.or_insert(version);
});
}

/// A copy of everything recorded so far.
pub fn uses(&self) -> CredentialUses {
self.uses
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}

fn with_uses(&self, update: impl FnOnce(&mut CredentialUses)) {
// A poisoned lock still holds a valid record; never lose a use.
let mut uses = self
.uses
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
update(&mut uses);
}
}

/// A resolver's link to its connection's [`CredentialUseMarker`].
#[derive(Clone)]
struct ResolverUseRecord {
marker: Arc<CredentialUseMarker>,
/// Static credential versions of that installation.
static_versions: Arc<HashMap<String, u64>>,
}

#[derive(Clone)]
Expand All @@ -266,6 +362,76 @@ impl fmt::Debug for SecretResolver {
}

impl SecretResolver {
/// Report every real secret this resolver hands out to `marker`.
///
/// `static_versions` is the version of each static credential in the
/// installation the resolver was built from.
#[must_use]
pub fn with_use_marker(
mut self,
marker: Arc<CredentialUseMarker>,
static_versions: Arc<HashMap<String, u64>>,
) -> Self {
self.use_record = Some(ResolverUseRecord {
marker,
static_versions,
});
self
}

/// Each environment key's current-generation value.
///
/// Only canonical entries are read; revision-scoped and stable-handle
/// placeholders alias them or carry older generations.
pub(crate) fn canonical_values(&self) -> impl Iterator<Item = (&str, &str)> {
self.by_placeholder
.iter()
.filter_map(|(placeholder, secret)| {
let key = placeholder.strip_prefix(PLACEHOLDER_PREFIX)?;
(placeholder_env_key(placeholder) == Some(key))
.then_some((key, secret.value.as_ref()))
})
}

/// The current-generation value of `env_key`, if configured.
pub(crate) fn canonical_value(&self, env_key: &str) -> Option<&str> {
self.by_placeholder
.get(&placeholder_for_env_key(env_key))
.map(|secret| secret.value.as_ref())
}

/// Report that this resolver handed out `served` for `placeholder`.
///
/// The use is current when `served` is its key's current value, whichever
/// placeholder form named it: canonical, stable handle, the current
/// revision, a retained revision whose value has not changed since, or an
/// aged-out revision that fell back. Revisions are sandbox-wide, so an older
/// revision usually means another provider changed, not this credential.
/// A retained revision whose value has changed, or a key with no current
/// value, records [`STALE_CREDENTIAL_VERSION`]; so does a placeholder with
/// no recognisable key, under the placeholder itself.
fn note_use(&self, placeholder: &str, served: &str) {
let Some(record) = &self.use_record else {
return;
};
let Some(env_key) = placeholder_env_key(placeholder) else {
record
.marker
.record_static(placeholder, STALE_CREDENTIAL_VERSION);
return;
};
let version = if self.canonical_value(env_key) == Some(served) {
record
.static_versions
.get(env_key)
.copied()
.unwrap_or(STALE_CREDENTIAL_VERSION)
} else {
STALE_CREDENTIAL_VERSION
};
record.marker.record_static(env_key, version);
}

#[cfg_attr(not(test), allow(dead_code))]
pub fn from_provider_env(
provider_env: HashMap<String, String>,
Expand Down Expand Up @@ -354,6 +520,7 @@ impl SecretResolver {
denied_env_keys: HashSet::new(),
identity_bound_env_keys: HashSet::new(),
revision_fallback_allowed_revisions: HashMap::new(),
use_record: None,
})
};
(
Expand Down Expand Up @@ -412,6 +579,7 @@ impl SecretResolver {
denied_env_keys: HashSet::new(),
identity_bound_env_keys: HashSet::new(),
revision_fallback_allowed_revisions: HashMap::new(),
use_record: None,
}),
)
}
Expand Down Expand Up @@ -442,6 +610,7 @@ impl SecretResolver {
denied_env_keys,
identity_bound_env_keys,
revision_fallback_allowed_revisions,
use_record: None,
})
}
}
Expand Down Expand Up @@ -478,6 +647,7 @@ impl SecretResolver {
denied_env_keys,
identity_bound_env_keys: bound_keys.clone(),
revision_fallback_allowed_revisions,
use_record: self.use_record.clone(),
}
}

Expand Down Expand Up @@ -651,7 +821,11 @@ impl SecretResolver {
let canonical = placeholder_for_env_key(key);
self.by_placeholder.get(&canonical)?
};
resolve_secret_value(secret)
let resolved = resolve_secret_value(secret);
if let Some(served) = resolved {
self.note_use(value, served);
}
resolved
}

/// Resolve the current value for an environment key selected by trusted
Expand All @@ -674,10 +848,14 @@ impl SecretResolver {
});
}
let placeholder = placeholder_for_env_key(key);
Ok(self
let resolved = self
.by_placeholder
.get(&placeholder)
.and_then(resolve_secret_value))
.and_then(resolve_secret_value);
if let Some(served) = resolved {
self.note_use(&placeholder, served);
}
Ok(resolved)
}

/// Resolve a placeholder while preserving endpoint-denial information.
Expand Down
3 changes: 3 additions & 0 deletions crates/openshell-policy-cedar-runtime/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ impl PolicyBackend for CedarOnlyEngine {
fn current_generation(&self) -> u64 {
self.current_generation()
}
fn publish_credential_change(&self) -> Result<u64> {
self.publish_credential_change()
}
fn generation_guard(&self, expected: u64) -> Result<PolicyGenerationGuard> {
self.generation_guard(expected)
}
Expand Down
9 changes: 9 additions & 0 deletions crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,15 @@ impl CedarOnlyEngine {
})
}

/// Invalidate relays and configuration guards after credential revocation.
/// The loaded policy and any quarantine remain unchanged.
pub fn publish_credential_change(&self) -> Result<u64> {
self.middleware.change_configuration(|| {
let _guard = self.write_engine()?;
Ok((self.advance_generation(), true))
})
}

/// Reactivates the active policy after a quarantine.
///
/// Returns the current Cedar generation, advanced only if a quarantine
Expand Down
23 changes: 23 additions & 0 deletions crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2460,3 +2460,26 @@ fn destination_control_plane_checks_recognize_bracketed_ip_literals() {
);
}
}

#[test]
fn credential_publication_invalidates_relays_and_configuration_without_ending_quarantine() {
let cedar = Arc::new(CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"));
let engine = openshell_policy_runtime_interface::PolicyEngine::from(Arc::clone(&cedar));
for quarantined in [false, true] {
if quarantined {
cedar.enter_fail_closed("revocation test").unwrap();
}
let generation = engine.current_generation();
let input = middleware_input("api.example.com");
let connection = engine
.connection_generation_guard(input, generation, None)
.unwrap();
let configuration = engine.configuration_generation_guard().unwrap();
let tunnel = engine.tunnel_engine(generation).unwrap();
assert_eq!(engine.publish_credential_change().unwrap(), generation + 1);
assert!(connection.is_stale());
assert!(configuration.is_stale());
assert!(tunnel.is_stale());
assert_eq!(cedar.fail_closed_reason().is_some(), quarantined);
}
}
6 changes: 6 additions & 0 deletions crates/openshell-policy-runtime-interface/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ before service connections begin and commits policy, middleware, and credentials
together. Request and address authorizers remain bound to the policy generation
that admitted their connection. The relay keeps credentials and I/O state outside
the policy-visible `L7PolicyContext`.

`PolicyBackend::connection_generation_guard` defaults to a strict generation
check. Backends may attach a `ConnectionRevalidator` to follow publications that
preserve an established connection's contract. Guard clones share the pin;
ordinary configuration guards remain strict. The backend must reject intervening
policy narrowing and quarantines, even if a later publication restores access.
40 changes: 33 additions & 7 deletions crates/openshell-policy-runtime-interface/src/policy_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ pub struct EgressAuthorization {
}

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

/// Backend-owned validation of an established connection across policy publications.
/// Implementations must reject any intervening narrowing, including quarantines.
pub trait ConnectionRevalidator: std::fmt::Debug + Send + Sync {
fn follow(&self, pin: &AtomicU64, live: &AtomicU64) -> bool;
fn pinned_policy_hash(&self, generation: u64) -> Option<String>;
}

/// Generation guard captured when an HTTP tunnel or request path starts.
#[derive(Clone, Debug)]
pub struct PolicyGenerationGuard {
captured_generation: u64,
captured_generation: Arc<AtomicU64>,
current_generation: Arc<AtomicU64>,
generation_rx: watch::Receiver<u64>,
revalidator: Option<Arc<dyn ConnectionRevalidator>>,
}

/// Builds a [`PolicyGenerationGuard`] for any state holding a plain
Expand All @@ -398,23 +407,40 @@ pub fn generation_guard_for(
));
}
Ok(PolicyGenerationGuard {
captured_generation: current_generation_value,
captured_generation: Arc::new(AtomicU64::new(current_generation_value)),
current_generation: Arc::clone(current_generation),
generation_rx: generation_tx.subscribe(),
revalidator: None,
})
}

impl PolicyGenerationGuard {
/// Attach a backend-owned connection contract. Ordinary guards remain strict.
#[must_use]
pub fn with_revalidator(mut self, revalidator: Option<Arc<dyn ConnectionRevalidator>>) -> Self {
self.revalidator = revalidator;
self
}

pub fn pinned_policy_hash(&self) -> Option<String> {
self.revalidator
.as_ref()?
.pinned_policy_hash(self.captured_generation())
}

pub fn captured_generation(&self) -> u64 {
self.captured_generation
self.captured_generation.load(Ordering::Acquire)
}

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

pub fn is_stale(&self) -> bool {
self.current_generation() != self.captured_generation
self.revalidator.as_ref().map_or_else(
|| self.current_generation() != self.captured_generation(),
|revalidator| !revalidator.follow(&self.captured_generation, &self.current_generation),
)
}

pub fn ensure_current(&self) -> Result<()> {
Expand All @@ -428,10 +454,10 @@ impl PolicyGenerationGuard {
Ok(())
}

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