Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ async fn prepare_cedarling_with_jwt_validation(
source: cedarling::PolicyStoreSource::Yaml(
serde_yaml_ng::to_string(&policy_store).expect("serialize policy store to YAML"),
),
..Default::default()
},
jwt_config: JwtConfig {
jwks: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ async fn prepare_cedarling() -> Result<Cedarling, InitCedarlingError> {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ static BSCONFIG: LazyLock<BootstrapConfig> = LazyLock::new(|| BootstrapConfig {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand All @@ -112,6 +113,7 @@ static BSCONFIG_WITH_DATA_POLICY: LazyLock<BootstrapConfig> = LazyLock::new(|| B
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_WITH_DATA.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/benches/startup_benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ static BSCONFIG_LOCAL: LazyLock<BootstrapConfig> = LazyLock::new(|| BootstrapCon
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/examples/authorize_unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
..Default::default()
},
jwt_config: JwtConfig {
jwks: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ async fn initialize_cedarling() -> Result<Cedarling, Box<dyn std::error::Error>>
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
..Default::default()
},
jwt_config: JwtConfig {
jwks: None,
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/examples/lock_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
..Default::default()
},
jwt_config: JwtConfig {
jwks: None,
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/examples/log_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ async fn init_cedarling_multi_issuer(
source: cedarling::PolicyStoreSource::Yaml(
serde_yaml_ng::to_string(&policy_store).expect("serialize policy store to YAML"),
),
..Default::default()
},
jwt_config: JwtConfig {
jwks: None,
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/examples/profiling_unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ async fn init_cedarling() -> Cedarling {
},
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
73 changes: 72 additions & 1 deletion jans-cedarling/cedarling/src/authz/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,17 @@ pub(crate) struct MetricsCollector {

/// Swapped wholesale on each snapshot; read lock for record_*, write lock for snapshot
interval: RwLock<Box<IntervalState>>,

// These counters are emitted on every snapshot regardless of telemetry
// interval (they reflect long-running worker state, not per-interval
// activity). See `crate::init::policy_store_refresh`.
policy_store_refresh_last_attempt_secs: AtomicI64,
policy_store_refresh_last_success_secs: AtomicI64,
policy_store_refresh_consecutive_failures: AtomicI64,
/// Integer-enum encoding of the last [`crate::init::policy_store_refresh::RefreshOutcome`]
/// `0` means "no attempt yet"; see `RefreshOutcome` for the
/// per-outcome values.
policy_store_refresh_last_outcome: AtomicI64,
}

impl MetricsCollector {
Expand All @@ -285,6 +296,10 @@ impl MetricsCollector {
init_time: now,
policy_count: AtomicI64::new(saturating_usize_to_i64(initial_policy_count)),
interval: RwLock::new(Box::new(IntervalState::new(now))),
policy_store_refresh_last_attempt_secs: AtomicI64::new(0),
policy_store_refresh_last_success_secs: AtomicI64::new(0),
policy_store_refresh_consecutive_failures: AtomicI64::new(0),
policy_store_refresh_last_outcome: AtomicI64::new(0),
}
}

Expand All @@ -294,6 +309,40 @@ impl MetricsCollector {
init_time: Utc::now(),
policy_count: AtomicI64::new(0),
interval: RwLock::new(Box::new(IntervalState::new(Utc::now()))),
policy_store_refresh_last_attempt_secs: AtomicI64::new(0),
policy_store_refresh_last_success_secs: AtomicI64::new(0),
policy_store_refresh_consecutive_failures: AtomicI64::new(0),
policy_store_refresh_last_outcome: AtomicI64::new(0),
}
}

/// Records a refresh-worker tick outcome. Always runs regardless of
/// `enabled`, since refresh state should be observable even if telemetry
/// emission to Lock is disabled.
pub(crate) fn record_policy_store_refresh(
&self,
outcome: crate::init::policy_store_refresh::RefreshOutcome,
) {
let now_secs = Utc::now().timestamp();
self.policy_store_refresh_last_attempt_secs
.store(now_secs, Ordering::Relaxed);
self.policy_store_refresh_last_outcome
.store(outcome as i64, Ordering::Relaxed);

match outcome {
crate::init::policy_store_refresh::RefreshOutcome::Success
| crate::init::policy_store_refresh::RefreshOutcome::NotModified => {
self.policy_store_refresh_last_success_secs
.store(now_secs, Ordering::Relaxed);
self.policy_store_refresh_consecutive_failures
.store(0, Ordering::Relaxed);
},
crate::init::policy_store_refresh::RefreshOutcome::HttpError
| crate::init::policy_store_refresh::RefreshOutcome::NetworkError
| crate::init::policy_store_refresh::RefreshOutcome::ParseError => {
self.policy_store_refresh_consecutive_failures
.fetch_add(1, Ordering::Relaxed);
},
}
}

Expand Down Expand Up @@ -555,7 +604,29 @@ impl MetricsCollector {
.expect(ERROR_COUNTERS_LOCK_POISONED)
.clone();

let ops = old.to_operational_stats(now, self.init_time, &self.policy_count);
let mut ops = old.to_operational_stats(now, self.init_time, &self.policy_count);

// Inject policy-store refresh state into the snapshot.
ops.insert(
"policy_store_refresh.last_attempt_secs".to_string(),
self.policy_store_refresh_last_attempt_secs
.load(Ordering::Relaxed),
);
ops.insert(
"policy_store_refresh.last_success_secs".to_string(),
self.policy_store_refresh_last_success_secs
.load(Ordering::Relaxed),
);
ops.insert(
"policy_store_refresh.consecutive_failures".to_string(),
self.policy_store_refresh_consecutive_failures
.load(Ordering::Relaxed),
);
ops.insert(
"policy_store_refresh.last_outcome".to_string(),
self.policy_store_refresh_last_outcome
.load(Ordering::Relaxed),
);

MetricsSnapshot {
policy_stats,
Expand Down
6 changes: 4 additions & 2 deletions jans-cedarling/cedarling/src/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl Cedarling {
&self,
request: RequestUnsigned,
) -> Result<AuthorizeResult, AuthorizeError> {
self.instance.authz.authorize_unsigned(&request)
self.instance.authz.load().authorize_unsigned(&request)
}

/// Authorize multi-issuer request.
Expand All @@ -64,7 +64,7 @@ impl Cedarling {
&self,
request: crate::authz::request::AuthorizeMultiIssuerRequest,
) -> Result<MultiIssuerAuthorizeResult, AuthorizeError> {
self.instance.authz.authorize_multi_issuer(&request)
self.instance.authz.load().authorize_multi_issuer(&request)
}

/// Returns metadata for all policies whose scope constraints are compatible
Expand All @@ -77,6 +77,7 @@ impl Cedarling {
) -> Result<Vec<PolicyMetadata>, AuthorizeError> {
self.instance
.authz
.load()
.get_matching_policies_unsigned(principal, actions, resources)
}

Expand All @@ -90,6 +91,7 @@ impl Cedarling {
) -> Result<Vec<PolicyMetadata>, AuthorizeError> {
self.instance
.authz
.load()
.get_matching_policies_multi_issuer(tokens, actions, resources)
}

Expand Down
11 changes: 9 additions & 2 deletions jans-cedarling/cedarling/src/bootstrap_config/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ impl BootstrapConfig {
// Case: get the policy store from a JSON string
(Some(policy_store), None, None) => PolicyStoreConfig {
source: PolicyStoreSource::Json(policy_store),
refresh_interval_secs: raw.policy_store_refresh_interval_secs,
},
// Case: get the policy store from a URI (auto-detect .cjar archives)
(None, Some(policy_store_uri), None) => {
Expand All @@ -72,7 +73,10 @@ impl BootstrapConfig {
} else {
PolicyStoreSource::LockServer(policy_store_uri)
};
PolicyStoreConfig { source }
PolicyStoreConfig {
source,
refresh_interval_secs: raw.policy_store_refresh_interval_secs,
}
},
// Case: get the policy store from a local file or directory
(None, None, Some(raw_path)) => {
Expand All @@ -96,7 +100,10 @@ impl BootstrapConfig {
)?,
}
};
PolicyStoreConfig { source }
PolicyStoreConfig {
source,
refresh_interval_secs: raw.policy_store_refresh_interval_secs,
}
},
// Case: multiple polict stores were set
_ => Err(BootstrapConfigLoadingError::ConflictingPolicyStores)?,
Expand Down
1 change: 1 addition & 0 deletions jans-cedarling/cedarling/src/bootstrap_config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ impl Default for BootstrapConfig {
source: PolicyStoreSource::Yaml(
"cedar_version: v4.0.0\npolicy_stores: {}\n".to_string(),
),
..Default::default()
},
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,41 @@ use crate::bootstrap_config::BootstrapConfigLoadingError;
pub struct PolicyStoreConfig {
/// Specifies the source from which the policy will be read.
pub source: PolicyStoreSource,

/// Base refresh interval in seconds for URL-based policy store sources
/// (`CjarUrl`, `LockServer`). `0` disables background refresh and preserves
/// the load-once-at-startup behavior. Ignored for local sources. A server
/// `Cache-Control: max-age` / `Expires` hint may *shorten* the next
/// interval but never lengthens it.
#[serde(default)]
pub refresh_interval_secs: u64,
}

impl PolicyStoreConfig {
/// Minimum refresh interval, in seconds — anything smaller is clamped up to
/// this value to avoid a busy-poll against the upstream.
pub const MIN_REFRESH_INTERVAL_SECS: u64 = 5;

/// True if the source is a remote URL and refresh is enabled.
#[must_use]
pub fn refresh_enabled(&self) -> bool {
self.refresh_interval_secs > 0
&& matches!(
self.source,
PolicyStoreSource::CjarUrl(_) | PolicyStoreSource::LockServer(_)
)
}
}

impl Default for PolicyStoreConfig {
fn default() -> Self {
Self {
source: PolicyStoreSource::Yaml(
"cedar_version: v4.0.0\npolicy_stores: {}\n".to_string(),
),
refresh_interval_secs: 0,
}
}
}

/// Raw policy store config
Expand Down Expand Up @@ -129,6 +164,9 @@ impl TryFrom<PolicyStoreConfigRaw> for PolicyStoreConfig {
),
_ => PolicyStoreSource::FileYaml("policy-store.yaml".into()),
};
Ok(Self { source })
Ok(Self {
source,
..Default::default()
})
}
}
17 changes: 13 additions & 4 deletions jans-cedarling/cedarling/src/bootstrap_config/raw_config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use super::default_values::{
default_enabled_feature_toggle, default_http_client_max_retries,
default_http_client_retry_delay_secs, default_jti, default_jwks_refresh_min_interval,
default_log_channel_capacity, default_log_max_retries,
default_status_list_refresh_interval_max, default_token_cache_capacity,
default_token_cache_max_ttl, default_true,
default_status_list_refresh_interval_max,
default_token_cache_capacity, default_token_cache_max_ttl, default_true,
};
#[cfg(not(target_arch = "wasm32"))]
use super::default_values::{
Expand All @@ -20,8 +20,8 @@ use super::default_values::{
use super::feature_types::{FeatureToggle, LoggerType};
use super::json_util::{
deserialize_jwks_refresh_interval, deserialize_jwks_refresh_min_interval,
deserialize_or_parse_string_as_json, deserialize_status_list_refresh_interval_max,
parse_option_string,
deserialize_or_parse_string_as_json, deserialize_policy_store_refresh_interval,
deserialize_status_list_refresh_interval_max, parse_option_string,
};
use crate::jwt_config::{TrustedIssuerLoaderTypeRaw, WorkersCount};
use crate::log::LogLevel;
Expand Down Expand Up @@ -422,6 +422,15 @@ pub struct BootstrapConfigRaw {
)]
#[serde(deserialize_with = "deserialize_status_list_refresh_interval_max")]
pub status_list_refresh_interval_max: u64,

/// Base refresh interval, in seconds, for periodic background refresh of
/// remote policy stores (`CjarUrl` / `LockServer`). `0` disables refresh and
/// preserves the load-once-at-startup behavior. Non-zero values below `5`
/// are clamped to `5`. A server `Cache-Control: max-age` / `Expires` hint
/// can *shorten* the next interval but never extends it.
#[serde(rename = "CEDARLING_POLICY_STORE_REFRESH_INTERVAL", default)]
#[serde(deserialize_with = "deserialize_policy_store_refresh_interval")]
pub policy_store_refresh_interval_secs: u64,
}

impl Default for BootstrapConfigRaw {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use serde::{Deserialize, Deserializer};
use serde_json::Value;

use crate::bootstrap_config::policy_store_config::PolicyStoreConfig;
use crate::jwt_config::{normalize_status_list_refresh_interval_max, MIN_JWKS_REFRESH_SECS};

/// Custom parser for an Option<String> which returns `None` if the string is empty.
Expand Down Expand Up @@ -88,6 +89,23 @@ where
Ok(value.max(MIN_JWKS_REFRESH_SECS))
}

/// Normalize the policy-store refresh interval. `0` means "disabled" and is left
/// alone. Non-zero values below `MIN_REFRESH_INTERVAL_SECS` are clamped up to
/// avoid a busy-poll against the upstream.
pub(super) fn deserialize_policy_store_refresh_interval<'de, D>(
deserializer: D,
) -> Result<u64, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: u64 = deserialize_or_parse_string_as_json(deserializer)?;
Ok(if value == 0 {
0
} else {
value.max(PolicyStoreConfig::MIN_REFRESH_INTERVAL_SECS)
})
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading