#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeMap, collections::BTreeSet, vec::Vec};
#[cfg(feature = "std")]
use std::{collections::BTreeMap, collections::BTreeSet, vec::Vec};
use der::asn1::ObjectIdentifier;
use x509_cert::ext::pkix::certpolicy::{CertificatePolicies, PolicyQualifierInfo};
use x509_cert::ext::pkix::PolicyMappings;
use crate::{PolicyTreeNode, OID_ANY_POLICY};
#[derive(Clone, Debug)]
struct PolicyNode {
valid_policy: ObjectIdentifier,
expected_policy_set: Vec<ObjectIdentifier>,
qualifiers: Vec<PolicyQualifierInfo>,
parents: Vec<ObjectIdentifier>,
}
impl PolicyNode {
fn new(
valid_policy: ObjectIdentifier,
qualifiers: Vec<PolicyQualifierInfo>,
parents: Vec<ObjectIdentifier>,
) -> Self {
Self {
valid_policy,
expected_policy_set: vec![valid_policy],
qualifiers,
parents,
}
}
fn has_any_policy_parent(&self) -> bool {
self.parents.contains(&OID_ANY_POLICY)
}
}
#[derive(Clone, Debug)]
pub(crate) struct PolicyGraph {
levels: Vec<Vec<PolicyNode>>,
}
pub(crate) fn any_policy_qualifiers(cp: &CertificatePolicies) -> Vec<PolicyQualifierInfo> {
cp.0.iter()
.find(|pi| pi.policy_identifier == OID_ANY_POLICY)
.and_then(|pi| pi.policy_qualifiers.clone())
.unwrap_or_default()
}
impl PolicyGraph {
pub(crate) fn new() -> Self {
Self {
levels: vec![vec![PolicyNode::new(
OID_ANY_POLICY,
Vec::new(),
Vec::new(),
)]],
}
}
fn depth(&self) -> usize {
self.levels.len() - 1
}
fn deepest(&self) -> &[PolicyNode] {
self.levels.last().map_or(&[][..], Vec::as_slice)
}
fn deepest_mut(&mut self) -> &mut Vec<PolicyNode> {
let last = self.levels.len() - 1;
&mut self.levels[last]
}
pub(crate) fn add_certificate_policies(
&mut self,
cp: &CertificatePolicies,
may_expand_any_policy: bool,
) -> bool {
let parents = self.deepest();
let mut expecting: BTreeMap<ObjectIdentifier, Vec<ObjectIdentifier>> = BTreeMap::new();
for parent in parents {
for ep in &parent.expected_policy_set {
expecting.entry(*ep).or_default().push(parent.valid_policy);
}
}
let any_parent = parents.iter().any(|p| p.valid_policy == OID_ANY_POLICY);
let mut level: Vec<PolicyNode> = Vec::new();
let mut present: BTreeSet<ObjectIdentifier> = BTreeSet::new();
let mut asserts_any_policy = false;
for pi in &cp.0 {
let p = pi.policy_identifier;
if p == OID_ANY_POLICY {
asserts_any_policy = true;
continue;
}
if present.contains(&p) {
continue;
}
let node_parents = match expecting.get(&p) {
Some(ps) => ps.clone(),
None if any_parent => vec![OID_ANY_POLICY],
None => continue,
};
let qualifiers = pi.policy_qualifiers.clone().unwrap_or_default();
level.push(PolicyNode::new(p, qualifiers, node_parents));
present.insert(p);
}
if asserts_any_policy && may_expand_any_policy {
let ap_q = any_policy_qualifiers(cp);
for parent in parents {
for ep in &parent.expected_policy_set {
if present.insert(*ep) {
let node_parents = expecting.get(ep).cloned().unwrap_or_default();
level.push(PolicyNode::new(*ep, ap_q.clone(), node_parents));
}
}
}
}
self.levels.push(level);
self.prune_above_deepest();
self.deepest().is_empty()
}
pub(crate) fn apply_policy_mappings(
&mut self,
pm: &PolicyMappings,
mapping_allowed: bool,
any_policy_qualifiers: &[PolicyQualifierInfo],
) -> bool {
let mut order: Vec<ObjectIdentifier> = Vec::new();
let mut targets: BTreeMap<ObjectIdentifier, Vec<ObjectIdentifier>> = BTreeMap::new();
for m in &pm.0 {
let sdps = targets.entry(m.issuer_domain_policy).or_insert_with(|| {
order.push(m.issuer_domain_policy);
Vec::new()
});
if !sdps.contains(&m.subject_domain_policy) {
sdps.push(m.subject_domain_policy);
}
}
if mapping_allowed {
let level = self.deepest_mut();
let has_any = level.iter().any(|n| n.valid_policy == OID_ANY_POLICY);
for idp in order {
let sdps = targets.remove(&idp).unwrap_or_default();
if let Some(node) = level.iter_mut().find(|n| n.valid_policy == idp) {
node.expected_policy_set = sdps;
} else if has_any {
let mut node =
PolicyNode::new(idp, any_policy_qualifiers.to_vec(), vec![OID_ANY_POLICY]);
node.expected_policy_set = sdps;
level.push(node);
}
}
false
} else {
self.deepest_mut()
.retain(|n| !targets.contains_key(&n.valid_policy));
self.prune_above_deepest();
self.deepest().is_empty()
}
}
pub(crate) fn intersect_user_policy_set(&mut self, user_set: &[ObjectIdentifier]) -> bool {
let n = self.depth();
for d in 1..=n {
let (above, rest) = self.levels.split_at_mut(d);
let alive: BTreeSet<ObjectIdentifier> =
above[d - 1].iter().map(|p| p.valid_policy).collect();
rest[0].retain_mut(|node| {
if node.has_any_policy_parent()
&& node.valid_policy != OID_ANY_POLICY
&& !user_set.contains(&node.valid_policy)
{
return false;
}
node.parents.retain(|p| alive.contains(p));
!node.parents.is_empty()
});
}
if let Some(pos) = self.levels[n]
.iter()
.position(|nd| nd.valid_policy == OID_ANY_POLICY)
{
let any_leaf = self.levels[n].remove(pos);
let vpns: BTreeSet<ObjectIdentifier> = self
.levels
.iter()
.flatten()
.filter(|nd| nd.has_any_policy_parent())
.map(|nd| nd.valid_policy)
.collect();
for p in user_set {
if vpns.contains(p) {
continue;
}
let level = &mut self.levels[n];
if let Some(existing) = level.iter_mut().find(|nd| nd.valid_policy == *p) {
existing.parents.push(OID_ANY_POLICY);
} else {
level.push(PolicyNode::new(
*p,
any_leaf.qualifiers.clone(),
vec![OID_ANY_POLICY],
));
}
}
}
self.prune_above_deepest();
self.deepest().is_empty()
}
fn prune_above_deepest(&mut self) {
for d in (1..self.levels.len().saturating_sub(1)).rev() {
let referenced: BTreeSet<ObjectIdentifier> = self.levels[d + 1]
.iter()
.flat_map(|c| c.parents.iter().copied())
.collect();
self.levels[d].retain(|n| referenced.contains(&n.valid_policy));
}
}
pub(crate) fn into_public(self) -> Vec<PolicyTreeNode> {
self.levels
.into_iter()
.enumerate()
.flat_map(|(depth, level)| {
level.into_iter().map(move |n| PolicyTreeNode {
depth,
valid_policy: n.valid_policy,
expected_policy_set: n.expected_policy_set,
qualifiers: n.qualifiers,
parent_policies: n.parents,
})
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use x509_cert::ext::pkix::certpolicy::PolicyInformation;
const P1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.99.1");
const P2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.99.2");
const SHARED: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.99.9");
fn policies(oids: &[ObjectIdentifier]) -> CertificatePolicies {
CertificatePolicies(
oids.iter()
.map(|o| PolicyInformation {
policy_identifier: *o,
policy_qualifiers: None,
})
.collect(),
)
}
#[test]
fn any_policy_expansion_never_duplicates_a_policy_at_one_depth() {
let mut g = PolicyGraph::new();
assert!(!g.add_certificate_policies(&policies(&[P1, P2]), true));
let level = g.levels.last_mut().expect("depth 1 exists");
assert_eq!(level.len(), 2, "two policies asserted, two nodes");
for node in level.iter_mut() {
node.expected_policy_set = vec![SHARED];
}
assert!(!g.add_certificate_policies(&policies(&[OID_ANY_POLICY]), true));
let deepest = g.levels.last().expect("depth 2 exists");
let mut seen = BTreeSet::new();
for node in deepest {
assert!(
seen.insert(node.valid_policy),
"policy {} has more than one node at this depth: {deepest:#?}",
node.valid_policy
);
}
assert_eq!(
deepest.len(),
1,
"both parents expect only SHARED, so the level is one node: {deepest:#?}"
);
assert_eq!(
deepest[0].parents.len(),
2,
"the one node must list both parents: {deepest:#?}"
);
}
}