Skip to content

Commit

Permalink
Merge pull request #8822 from microsoft/danmihai1/cargo-clippy
Browse files Browse the repository at this point in the history
genpolicy: cargo clippy fixes
  • Loading branch information
fidencio committed Jan 15, 2024
2 parents 73cf31b + 681cb16 commit 0dc00ae
Show file tree
Hide file tree
Showing 11 changed files with 175 additions and 202 deletions.
6 changes: 3 additions & 3 deletions src/tools/genpolicy/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@ impl yaml::K8sResource for List {
}

fn serialize(&mut self, policy: &str) -> String {
let policies: Vec<&str> = policy.split(":").collect();
let policies: Vec<&str> = policy.split(':').collect();
let len = policies.len();
assert!(len == self.resources.len());

self.items.clear();
for i in 0..len {
let yaml = self.resources[i].serialize(policies[i]);
for (i, p) in policies.iter().enumerate().take(len) {
let yaml = self.resources[i].serialize(p);
let document = serde_yaml::Deserializer::from_str(&yaml);
let doc_value = Value::deserialize(document).unwrap();
self.items.push(doc_value.clone());
Expand Down
82 changes: 1 addition & 81 deletions src/tools/genpolicy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
// SPDX-License-Identifier: Apache-2.0
//

use clap::Parser;
use env_logger;
use log::{debug, info};

mod config_map;
Expand All @@ -31,88 +29,10 @@ mod verity;
mod volume;
mod yaml;

#[derive(Debug, Parser)]
struct CommandLineOptions {
#[clap(
short,
long,
help = "Kubernetes input/output YAML file path. stdin/stdout get used if this option is not specified."
)]
yaml_file: Option<String>,

#[clap(
short,
long,
help = "Optional Kubernetes config map YAML input file path"
)]
config_map_file: Option<String>,

#[clap(
short = 'j',
long,
default_value_t = String::from("genpolicy-settings.json"),
help = "genpolicy settings file name"
)]
settings_file_name: String,

#[clap(
short,
long,
default_value_t = String::from("."),
help = "Path to the rules.rego and settings input files"
)]
input_files_path: String,

#[clap(
short,
long,
help = "Create and use a cache of container image layer contents and dm-verity information (in ./layers_cache/)"
)]
use_cached_files: bool,

#[clap(
short,
long,
help = "Print the output Rego policy text to standard output"
)]
raw_out: bool,

#[clap(
short,
long,
help = "Print the base64 encoded output Rego policy to standard output"
)]
base64_out: bool,

#[clap(
short,
long,
help = "Ignore unsupported input Kubernetes YAML fields. This is not recommeded unless you understand exactly how genpolicy works!"
)]
silent_unsupported_fields: bool,
}

#[tokio::main]
async fn main() {
env_logger::init();

let args = CommandLineOptions::parse();

let mut config_map_files = Vec::new();
if let Some(config_map_file) = &args.config_map_file {
config_map_files.push(config_map_file.clone());
}

let config = utils::Config::new(
args.use_cached_files,
args.yaml_file,
&args.input_files_path,
&args.settings_file_name,
&config_map_files,
args.silent_unsupported_fields,
args.raw_out,
args.base64_out,
);
let config = utils::Config::new();

debug!("Creating policy from yaml, settings, and rules.rego files...");
let mut policy = policy::AgentPolicy::from_files(&config).await.unwrap();
Expand Down
15 changes: 7 additions & 8 deletions src/tools/genpolicy/src/mount_and_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ pub fn get_policy_mounts(
};

for s_mount in settings_mounts {
if keep_settings_mount(settings, &s_mount, &yaml_container.volumeMounts) {
if keep_settings_mount(settings, s_mount, &yaml_container.volumeMounts) {
let mut mount = s_mount.clone();
adjust_termination_path(&mut mount, &yaml_container);
adjust_termination_path(&mut mount, yaml_container);

if mount.source.is_empty() && mount.type_.eq("bind") {
if let Some(file_name) = Path::new(&mount.destination).file_name() {
Expand All @@ -54,12 +54,11 @@ pub fn get_policy_mounts(
policy_mount.options = mount.options.iter().map(String::from).collect();
} else {
// Add a new mount.
if !is_pause_container {
if s_mount.destination.eq("/etc/hostname")
|| s_mount.destination.eq("/etc/resolv.conf")
{
mount.options.push(rootfs_access.to_string());
}
if !is_pause_container
&& (s_mount.destination.eq("/etc/hostname")
|| s_mount.destination.eq("/etc/resolv.conf"))
{
mount.options.push(rootfs_access.to_string());
}
p_mounts.push(mount);
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/genpolicy/src/no_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl yaml::K8sResource for NoPolicyResource {
}

fn generate_policy(&self, _agent_policy: &policy::AgentPolicy) -> String {
return "".to_string();
"".to_string()
}

fn serialize(&mut self, _policy: &str) -> String {
Expand Down
6 changes: 3 additions & 3 deletions src/tools/genpolicy/src/pod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ impl Container {
capabilities.Permitted.clear();
capabilities.Effective.clear();
} else {
let cap = "CAP_".to_string() + &c;
let cap = "CAP_".to_string() + c;

capabilities.Bounding.retain(|x| !x.eq(&cap));
capabilities.Permitted.retain(|x| !x.eq(&cap));
Expand All @@ -739,7 +739,7 @@ impl Container {
}
if let Some(add) = &yaml_capabilities.add {
for c in add {
let cap = "CAP_".to_string() + &c;
let cap = "CAP_".to_string() + c;

if !capabilities.Bounding.contains(&cap) {
capabilities.Bounding.push(cap.clone());
Expand Down Expand Up @@ -779,7 +779,7 @@ fn compress_capabilities(capabilities: &mut Vec<String>, defaults: &policy::Comm
""
};

if default_caps.len() != 0 {
if !default_caps.is_empty() {
capabilities.clear();
capabilities.push(default_caps.to_string());
}
Expand Down
24 changes: 9 additions & 15 deletions src/tools/genpolicy/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ impl AgentPolicy {

if let Some(config_map_files) = &config.config_map_files {
for file in config_map_files {
config_maps.push(config_map::ConfigMap::new(&file)?);
config_maps.push(config_map::ConfigMap::new(file)?);
}
}

Expand Down Expand Up @@ -429,26 +429,20 @@ impl AgentPolicy {
.create(true)
.open(yaml_file)
.unwrap()
.write_all(&yaml_string.as_bytes())
.write_all(yaml_string.as_bytes())
.unwrap();
} else {
// When input YAML came through stdin, print the output YAML to stdout.
std::io::stdout()
.write_all(&yaml_string.as_bytes())
.unwrap();
std::io::stdout().write_all(yaml_string.as_bytes()).unwrap();
}
}

pub fn generate_policy(&self, resource: &dyn yaml::K8sResource) -> String {
let yaml_containers = resource.get_containers();
let mut policy_containers = Vec::new();

for i in 0..yaml_containers.len() {
policy_containers.push(self.get_container_policy(
resource,
&yaml_containers[i],
i == 0,
));
for (i, yaml_container) in yaml_containers.iter().enumerate() {
policy_containers.push(self.get_container_policy(resource, yaml_container, i == 0));
}

let policy_data = policy::PolicyData {
Expand Down Expand Up @@ -698,8 +692,8 @@ fn substitute_env_variables(env: &mut Vec<String>) {
for i in 0..env.len() {
let components: Vec<&str> = env[i].split('=').collect();
if components.len() == 2 {
if let Some((start, end)) = find_subst_target(&components[1]) {
if let Some(new_value) = substitute_variable(&components[1], start, end, env) {
if let Some((start, end)) = find_subst_target(components[1]) {
if let Some(new_value) = substitute_variable(components[1], start, end, env) {
let new_var = format!("{}={new_value}", &components[0]);
debug!("Replacing env variable <{}> with <{new_var}>", &env[i]);
env[i] = new_var;
Expand All @@ -719,7 +713,7 @@ fn find_subst_target(env_value: &str) -> Option<(usize, usize)> {
if let Some(mut start) = env_value.find("$(") {
start += 2;
if env_value.len() > start {
if let Some(end) = env_value[start..].find(")") {
if let Some(end) = env_value[start..].find(')') {
return Some((start, start + end));
}
}
Expand All @@ -735,7 +729,7 @@ fn substitute_variable(
env: &Vec<String>,
) -> Option<String> {
// Variables generated by this application.
let internal_vars = vec![
let internal_vars = [
"bundle-id",
"host-ip",
"node-name",
Expand Down

0 comments on commit 0dc00ae

Please sign in to comment.