#[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::PolicyMappings;
use x509_cert::ext::pkix::certpolicy::{CertificatePolicies, PolicyQualifierInfo};
use crate::{OID_ANY_POLICY, PolicyTreeNode};
#[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(|node| node.valid_policy == OID_ANY_POLICY)
{
let any_leaf = self.levels[n].remove(pos);
let vpns: BTreeSet<ObjectIdentifier> = self
.levels
.iter()
.flatten()
.filter(|node| node.has_any_policy_parent())
.map(|node| node.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(|node| node.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 P3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.99.3");
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(),
)
}
fn mappings(pairs: &[(ObjectIdentifier, ObjectIdentifier)]) -> PolicyMappings {
PolicyMappings(
pairs
.iter()
.map(|(idp, sdp)| x509_cert::ext::pkix::PolicyMapping {
issuer_domain_policy: *idp,
subject_domain_policy: *sdp,
})
.collect(),
)
}
fn deepest_policies(g: &PolicyGraph) -> Vec<ObjectIdentifier> {
g.deepest().iter().map(|n| n.valid_policy).collect()
}
fn shape(g: &PolicyGraph) -> Vec<Vec<ObjectIdentifier>> {
g.levels
.iter()
.map(|l| l.iter().map(|n| n.valid_policy).collect())
.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:#?}"
);
}
#[test]
fn a_mapping_without_a_node_is_synthesized_only_under_any_policy() {
let mut concrete = PolicyGraph::new();
assert!(!concrete.add_certificate_policies(&policies(&[P1, P2]), true));
assert_eq!(deepest_policies(&concrete), vec![P1, P2]);
assert!(!concrete.apply_policy_mappings(&mappings(&[(P3, SHARED)]), true, &[]));
assert_eq!(
deepest_policies(&concrete),
vec![P1, P2],
"P3 has no node and no anyPolicy parent to be created under"
);
let mut with_any = PolicyGraph::new();
assert!(!with_any.add_certificate_policies(&policies(&[P1, OID_ANY_POLICY]), true));
assert!(
deepest_policies(&with_any).contains(&OID_ANY_POLICY),
"the certificate asserted anyPolicy, so the level has that node"
);
assert!(!with_any.apply_policy_mappings(&mappings(&[(P3, SHARED)]), true, &[]));
let synthesized = with_any
.deepest()
.iter()
.find(|n| n.valid_policy == P3)
.expect("P3 synthesized under anyPolicy");
assert_eq!(
synthesized.parents,
vec![OID_ANY_POLICY],
"§6.1.4(b)(1): the new node descends from the anyPolicy node"
);
assert_eq!(
synthesized.expected_policy_set,
vec![SHARED],
"and expects what the mapping names"
);
}
#[test]
fn the_user_policy_expansion_matches_the_node_carrying_that_policy() {
let mut g = PolicyGraph::new();
assert!(!g.add_certificate_policies(&policies(&[P1, OID_ANY_POLICY]), true));
assert!(!g.apply_policy_mappings(&mappings(&[(P1, P2)]), true, &[]));
assert!(!g.add_certificate_policies(&policies(&[P2, OID_ANY_POLICY]), true));
let p2_before = g
.deepest()
.iter()
.find(|n| n.valid_policy == P2)
.expect("P2 is P1's child at depth 2");
assert_eq!(
p2_before.parents,
vec![P1],
"P2 must reach the leaf through the mapping alone"
);
assert!(!g.intersect_user_policy_set(&[P1, P2]));
let p2: Vec<_> = g
.deepest()
.iter()
.filter(|n| n.valid_policy == P2)
.collect();
assert_eq!(p2.len(), 1, "one node per policy per level, not two");
assert!(
p2[0].parents.contains(&OID_ANY_POLICY),
"the anyPolicy parent joins the node that already carries P2, got {:?}",
p2[0].parents
);
assert!(
p2[0].parents.contains(&P1),
"and does not displace the parent it already had"
);
}
#[test]
fn pruning_removes_intermediate_nodes_with_no_children() {
let mut g = PolicyGraph::new();
assert!(!g.add_certificate_policies(&policies(&[P1, P2]), true));
assert!(!g.add_certificate_policies(&policies(&[P1]), false));
assert_eq!(
shape(&g),
vec![vec![OID_ANY_POLICY], vec![P1], vec![P1]],
"P2 at depth 1 has no child at depth 2 and is deleted"
);
}
}