Skip to content

Commit

Permalink
test: add integration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
fabriziosestito committed Dec 5, 2023
1 parent ce9ba62 commit 7563bf5
Show file tree
Hide file tree
Showing 7 changed files with 457 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/admission_review.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use policy_evaluator::admission_response::AdmissionResponse;

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AdmissionReview {
pub struct AdmissionReview {
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,

Expand Down
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
mod admission_review;
mod api;
mod communication;
pub mod config;
mod metrics;
mod policy_downloader;
mod raw_review;
mod server;
mod worker;
mod worker_pool;

pub mod admission_review;
pub mod config;
pub mod raw_review;

use anyhow::{anyhow, Result};
use lazy_static::lazy_static;
use opentelemetry::global::shutdown_tracer_provider;
Expand Down
8 changes: 4 additions & 4 deletions src/raw_review.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ use serde::{Deserialize, Serialize};

/// A review request that contains a raw json value.
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct RawReviewRequest {
pub(crate) request: serde_json::Value,
pub struct RawReviewRequest {
pub request: serde_json::Value,
}

/// A review response from a raw policy evaluation.
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct RawReviewResponse {
pub(crate) response: AdmissionResponse,
pub struct RawReviewResponse {
pub response: AdmissionResponse,
}

impl RawReviewResponse {
Expand Down
85 changes: 85 additions & 0 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use policy_server::config::{Config, Policy, PolicyMode};

use reqwest::blocking::Client;
use std::{
collections::{BTreeSet, HashMap},
net::SocketAddr,
sync::Once,
thread,
};
use tempfile::tempdir;

static INIT: Once = Once::new();
static URL: &str = "http://127.0.0.1:3001";

pub(crate) fn setup() {
INIT.call_once(|| {
let policies = HashMap::from([
(
"pod-privileged".to_owned(),
Policy {
url: "ghcr.io/kubewarden/tests/pod-privileged:v0.2.1".to_owned(),
policy_mode: PolicyMode::Protect,
allowed_to_mutate: None,
settings: None,
context_aware_resources: BTreeSet::new(),
},
),
(
"raw-mutation".to_owned(),
Policy {
url: "ghcr.io/kubewarden/tests/raw-mutation-policy:v0.1.0".to_owned(),
policy_mode: PolicyMode::Protect,
allowed_to_mutate: Some(true),
settings: Some(HashMap::from([
(
"forbiddenResources".to_owned(),
vec!["banana", "carrot"].into(),
),
("defaultResource".to_owned(), "hay".into()),
])),
context_aware_resources: BTreeSet::new(),
},
),
]);

let config = Config {
addr: SocketAddr::from(([127, 0, 0, 1], 3001)),
sources: None,
policies,
policies_download_dir: tempdir().unwrap().into_path(),
ignore_kubernetes_connection_failure: true,
always_accept_admission_reviews_on_namespace: None,
policy_evaluation_limit: None,
tls_config: None,
pool_size: 2,
metrics_enabled: true,
sigstore_cache_dir: tempdir().unwrap().into_path(),
verification_config: None,
log_level: "info".to_owned(),
log_fmt: "json".to_owned(),
log_no_color: false,
daemon: false,
daemon_pid_file: "policy_server.pid".to_owned(),
daemon_stdout_file: None,
daemon_stderr_file: None,
};

thread::spawn(move || {
policy_server::run(config).unwrap();
});

loop {
let client = Client::new();
if let Ok(resp) = client.get(format!("{}/readiness", URL)).send() {
if resp.status().is_success() {
break;
}
}
}
});
}

pub(crate) fn url(path: &str) -> String {
format!("{}{}", URL, path)
}
177 changes: 177 additions & 0 deletions tests/data/pod_with_privileged_containers.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
{
"apiVersion": "admission.k8s.io/v1",
"kind": "AdmissionReview",
"request": {
"uid": "1299d386-525b-4032-98ae-1949f69f9cfc",
"kind": {
"group": "",
"version": "v1",
"kind": "Pod"
},
"resource": {
"group": "",
"version": "v1",
"resource": "pods"
},
"requestKind": {
"group": "",
"version": "v1",
"kind": "Pod"
},
"requestResource": {
"group": "",
"version": "v1",
"resource": "pods"
},
"name": "nginx",
"namespace": "default",
"operation": "CREATE",
"userInfo": {
"username": "kubernetes-admin",
"groups": ["system:masters", "system:authenticated"]
},
"object": {
"kind": "Pod",
"apiVersion": "v1",
"metadata": {
"name": "nginx",
"namespace": "default",
"uid": "04dc7a5e-e1f1-4e34-8d65-2c9337a43e64",
"creationTimestamp": "2020-11-12T15:18:36Z",
"labels": {
"env": "test"
},
"annotations": {
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"env\":\"test\"},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"imagePullPolicy\":\"IfNotPresent\",\"name\":\"nginx\"}],\"tolerations\":[{\"effect\":\"NoSchedule\",\"key\":\"example-key\",\"operator\":\"Exists\"}]}}\n"
},
"managedFields": [
{
"manager": "kubectl",
"operation": "Update",
"apiVersion": "v1",
"time": "2020-11-12T15:18:36Z",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {}
},
"f:labels": {
".": {},
"f:env": {}
}
},
"f:spec": {
"f:containers": {
"k:{\"name\":\"nginx\"}": {
".": {},
"f:image": {},
"f:imagePullPolicy": {},
"f:name": {},
"f:resources": {},
"f:terminationMessagePath": {},
"f:terminationMessagePolicy": {}
}
},
"f:dnsPolicy": {},
"f:enableServiceLinks": {},
"f:restartPolicy": {},
"f:schedulerName": {},
"f:securityContext": {},
"f:terminationGracePeriodSeconds": {},
"f:tolerations": {}
}
}
}
]
},
"spec": {
"volumes": [
{
"name": "default-token-pvpz7",
"secret": {
"secretName": "default-token-pvpz7"
}
}
],
"containers": [
{
"name": "sleeping-sidecar",
"image": "alpine",
"command": ["sleep", "1h"],
"resources": {},
"volumeMounts": [
{
"name": "default-token-pvpz7",
"readOnly": true,
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
}
],
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"imagePullPolicy": "IfNotPresent"
},
{
"name": "nginx",
"image": "nginx",
"resources": {},
"volumeMounts": [
{
"name": "default-token-pvpz7",
"readOnly": true,
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
}
],
"securityContext": {
"privileged": true
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"imagePullPolicy": "IfNotPresent"
}
],
"restartPolicy": "Always",
"terminationGracePeriodSeconds": 30,
"dnsPolicy": "ClusterFirst",
"serviceAccountName": "default",
"serviceAccount": "default",
"securityContext": {},
"schedulerName": "default-scheduler",
"tolerations": [
{
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"effect": "NoExecute",
"tolerationSeconds": 300
},
{
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"effect": "NoExecute",
"tolerationSeconds": 300
},
{
"key": "dedicated",
"operator": "Equal",
"value": "tenantA",
"effect": "NoSchedule"
}
],
"priority": 0,
"enableServiceLinks": true,
"preemptionPolicy": "PreemptLowerPriority"
},
"status": {
"phase": "Pending",
"qosClass": "BestEffort"
}
},
"oldObject": null,
"dryRun": false,
"options": {
"kind": "CreateOptions",
"apiVersion": "meta.k8s.io/v1"
}
}
}
3 changes: 3 additions & 0 deletions tests/data/raw_review.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"request": { "user": "tonio", "action": "eats", "resource": "banana" }
}
Loading

0 comments on commit 7563bf5

Please sign in to comment.