Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor generator code #507

Merged
merged 2 commits into from
Jan 2, 2025
Merged
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
3 changes: 1 addition & 2 deletions cedar-drt/fuzz/fuzz_targets/rbac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use cedar_policy_core::entities::Entities;
use cedar_policy_core::extensions::Extensions;
use cedar_policy_generators::err::Result;
use cedar_policy_generators::hierarchy::{
AttributesMode, EntityUIDGenMode, HierarchyGenerator, HierarchyGeneratorMode,
AttributesMode, HierarchyGenerator, HierarchyGeneratorMode,
};
use cedar_policy_generators::policy::GeneratedLinkedPolicy;
use cedar_policy_generators::rbac::{RBACHierarchy, RBACPolicy, RBACRequest};
Expand Down Expand Up @@ -136,7 +136,6 @@ impl<'a> Arbitrary<'a> for FuzzTargetInput {
mode: HierarchyGeneratorMode::Arbitrary {
attributes_mode: AttributesMode::NoAttributesOrTags,
},
uid_gen_mode: EntityUIDGenMode::default(),
num_entities: cedar_policy_generators::hierarchy::NumEntities::RangePerEntityType(
0..=4,
),
Expand Down
1 change: 0 additions & 1 deletion cedar-policy-generators/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ serde_json = { version = "1.0" }
smol_str = { version = "0.3", features = ["serde", "arbitrary"] }
rand = "0.8.5"
anyhow = "1.0.72"
nanoid = "0.4.0"
serde_with = "3.4.0"
thiserror = "2.0"

Expand Down
9 changes: 2 additions & 7 deletions cedar-policy-generators/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
use crate::abac::{AttrValue, AvailableExtensionFunctions, ConstantPool, Type, UnknownPool};
use crate::collections::HashMap;
use crate::err::{while_doing, Error, Result};
use crate::hierarchy::{
arbitrary_specified_uid, generate_uid_with_type, EntityUIDGenMode, Hierarchy,
};
use crate::hierarchy::{arbitrary_specified_uid, generate_uid_with_type, Hierarchy};
use crate::schema::{
attrs_from_attrs_or_context, entity_type_name_to_schema_type, lookup_common_type,
uid_for_action_name, Schema,
Expand Down Expand Up @@ -50,9 +48,6 @@ pub struct ExprGenerator<'a> {
/// If this is present, any literal UIDs included in generated `Expr`s will
/// (usually) exist in the hierarchy.
pub hierarchy: Option<&'a Hierarchy>,
/// For any entity UIDs that are generated as part of the expression.
/// As of this writing, this is only used when `hierarchy` is `None`.
pub uid_gen_mode: EntityUIDGenMode,
}

impl<'a> ExprGenerator<'a> {
Expand Down Expand Up @@ -2473,7 +2468,7 @@ impl<'a> ExprGenerator<'a> {
u: &mut Unstructured<'_>,
) -> Result<ast::EntityUID> {
match self.hierarchy {
None => generate_uid_with_type(ty.clone(), &self.uid_gen_mode, u),
None => generate_uid_with_type(ty.clone(), u),
Some(hierarchy) => hierarchy.arbitrary_uid_with_type(ty, u),
}
}
Expand Down
51 changes: 4 additions & 47 deletions cedar-policy-generators/src/hierarchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ use cedar_policy_core::ast::{self, Eid, Entity, EntityUID};
use cedar_policy_core::entities::{Entities, NoEntitiesSchema, TCComputation};
use cedar_policy_core::extensions::Extensions;
use cedar_policy_validator::json_schema;
use nanoid::nanoid;
use smol_str::SmolStr;

/// EntityUIDs with the mappings to their indices in the container.
Expand Down Expand Up @@ -312,8 +311,6 @@ impl From<Entities> for Hierarchy {
pub struct HierarchyGenerator<'a, 'u> {
/// Mode for hierarchy generation, e.g., whether to conform to a schema
pub mode: HierarchyGeneratorMode<'a>,
/// Mode for generating entity uids
pub uid_gen_mode: EntityUIDGenMode,
/// How many entities to generate for the hierarchy
pub num_entities: NumEntities,
/// `Unstructured` used for making random choices
Expand All @@ -331,32 +328,6 @@ impl<'a, 'u> std::fmt::Debug for HierarchyGenerator<'a, 'u> {
}
}

#[derive(Debug, Clone)]
/// Modes of entity uid generation
pub enum EntityUIDGenMode {
/// By calling `arbitrary`
Arbitrary,
/// By calling `nanoid`
Nanoid(usize),
}

impl EntityUIDGenMode {
/// The default nanoid length is 8
pub fn default_nanoid_len() -> usize {
8
}
/// Use nanoid with the default length
pub fn default_nanoid_mode() -> Self {
Self::Nanoid(Self::default_nanoid_len())
}
}

impl Default for EntityUIDGenMode {
fn default() -> Self {
Self::Arbitrary
}
}

/// Modes of hierarchy generation
#[derive(Debug)]
pub enum HierarchyGeneratorMode<'a> {
Expand Down Expand Up @@ -423,16 +394,9 @@ pub(crate) fn arbitrary_specified_uid(u: &mut Unstructured<'_>) -> Result<ast::E
/// actually exists (yet) in any given hierarchy.
pub(crate) fn generate_uid_with_type(
ty: ast::EntityType,
mode: &EntityUIDGenMode,
u: &mut Unstructured<'_>,
) -> Result<ast::EntityUID> {
let eid: Eid = match mode {
EntityUIDGenMode::Arbitrary => u.arbitrary()?,
EntityUIDGenMode::Nanoid(n) => {
let n = *n;
Eid::new(nanoid!(n))
}
};
let eid = u.arbitrary()?;
Ok(ast::EntityUID::from_components(ty, eid, None))
}

Expand Down Expand Up @@ -465,11 +429,7 @@ impl<'a, 'u> HierarchyGenerator<'a, 'u> {
Some((*r.start()).try_into().unwrap()),
Some((*r.end()).try_into().unwrap()),
|u| {
uids.insert(generate_uid_with_type(
name.clone(),
&self.uid_gen_mode,
u,
)?);
uids.insert(generate_uid_with_type(name.clone(), u)?);
Ok(std::ops::ControlFlow::Continue(()))
},
)?;
Expand All @@ -478,9 +438,7 @@ impl<'a, 'u> HierarchyGenerator<'a, 'u> {
NumEntities::ExactlyPerEntityType(num_entities_per_type) => {
// generate `num_entities` entity UIDs of this type
(1..=*num_entities_per_type)
.map(|_| {
generate_uid_with_type(name.clone(), &self.uid_gen_mode, self.u)
})
.map(|_| generate_uid_with_type(name.clone(), self.u))
.collect::<Result<_>>()?
}
NumEntities::Exactly(num_entities) => {
Expand All @@ -493,8 +451,7 @@ impl<'a, 'u> HierarchyGenerator<'a, 'u> {
if self.u.is_empty() {
return Err(Error::NotEnoughData);
}
let uid =
generate_uid_with_type(name.clone(), &self.uid_gen_mode, self.u)?;
let uid = generate_uid_with_type(name.clone(), self.u)?;
uids.insert(uid);
}
uids
Expand Down
143 changes: 0 additions & 143 deletions cedar-policy-generators/src/main.rs

This file was deleted.

28 changes: 5 additions & 23 deletions cedar-policy-generators/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ use crate::abac::{
use crate::collections::{HashMap, HashSet};
use crate::err::{while_doing, Error, Result};
use crate::expr::ExprGenerator;
use crate::hierarchy::{
EntityUIDGenMode, Hierarchy, HierarchyGenerator, HierarchyGeneratorMode, NumEntities,
};
use crate::hierarchy::{Hierarchy, HierarchyGenerator, HierarchyGeneratorMode, NumEntities};
use crate::policy::{ActionConstraint, GeneratedPolicy, PrincipalOrResourceConstraint};
use crate::request::Request;
use crate::settings::ABACSettings;
Expand Down Expand Up @@ -827,6 +825,7 @@ impl Schema {
///
/// The input is [`json_schema::Fragment<RawName>`], meaning that entity and common
/// type names may not yet be fully qualified.
#[deprecated = "this function may not work after cedar-policy/cedar#1060; refer to cedar-policy/cedar-spec#496"]
pub fn from_raw_schemafrag(
schemafrag: json_schema::Fragment<RawName>,
settings: ABACSettings,
Expand Down Expand Up @@ -878,7 +877,6 @@ impl Schema {
unknown_pool: &self.unknown_pool,
ext_funcs: &self.ext_funcs,
hierarchy,
uid_gen_mode: EntityUIDGenMode::default(),
}
}

Expand Down Expand Up @@ -1137,23 +1135,6 @@ impl Schema {
pub fn arbitrary_hierarchy(&self, u: &mut Unstructured<'_>) -> Result<Hierarchy> {
HierarchyGenerator {
mode: HierarchyGeneratorMode::SchemaBased { schema: self },
uid_gen_mode: EntityUIDGenMode::default(),
num_entities: NumEntities::RangePerEntityType(1..=self.settings.max_width),
u,
extensions: Extensions::all_available(),
}
.generate()
}

/// Get an arbitrary Hierarchy conforming to the schema but with nanoid uids.
pub fn arbitrary_hierarchy_with_nanoid_uids(
&self,
nanoid_len: usize,
u: &mut Unstructured<'_>,
) -> Result<Hierarchy> {
HierarchyGenerator {
mode: HierarchyGeneratorMode::SchemaBased { schema: self },
uid_gen_mode: EntityUIDGenMode::Nanoid(nanoid_len),
num_entities: NumEntities::RangePerEntityType(1..=self.settings.max_width),
u,
extensions: Extensions::all_available(),
Expand Down Expand Up @@ -1825,7 +1806,7 @@ impl TryFrom<Schema> for ValidatorSchema {
#[cfg(test)]
mod tests {
use super::Schema;
use crate::{hierarchy::EntityUIDGenMode, settings::ABACSettings};
use crate::settings::ABACSettings;
use arbitrary::Unstructured;
use cedar_policy_core::entities::Entities;
use cedar_policy_core::extensions::Extensions;
Expand Down Expand Up @@ -2287,6 +2268,7 @@ mod tests {
}
}

#[allow(deprecated)]
fn generate_hierarchy_from_schema(
rng: &mut ThreadRng,
fragment: json_schema::Fragment<RawName>,
Expand All @@ -2297,7 +2279,7 @@ mod tests {
let schema = Schema::from_raw_schemafrag(fragment.clone(), TEST_SETTINGS, &mut u)
.expect("failed to generate schema!");
let h = schema
.arbitrary_hierarchy_with_nanoid_uids(EntityUIDGenMode::default_nanoid_len(), &mut u)
.arbitrary_hierarchy(&mut u)
.expect("failed to generate hierarchy!");
let vschema =
ValidatorSchema::try_from(schema).expect("failed to convert to ValidatorSchema");
Expand Down
Loading