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

feat(boundary): setup of rate-limit canister #1961

Draft
wants to merge 40 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
bc2e2bf
chore: add interface definition
Oct 7, 2024
13da21b
chore: rate limit canister
Oct 20, 2024
5127eb5
chore: cargo
Oct 20, 2024
ecf0379
chore: fix cargo
Oct 20, 2024
0e6d348
Automatically updated Cargo*.lock
Oct 20, 2024
51f7d8e
chore: interface.did
Oct 20, 2024
c251521
chore: improve description
Oct 20, 2024
32f32d9
fix: remove redundant interface
Oct 21, 2024
ce21765
fix: RestrictedRead formatting
Oct 21, 2024
851f8d8
chore: add incident_id
Oct 21, 2024
7ed0807
chore: add client e2e tests
Oct 21, 2024
5c554f2
chore: add more calls to the canister client
Oct 21, 2024
47efd9b
fix: names
Oct 21, 2024
d134f46
chore: add test principal
Oct 21, 2024
2dc3dfc
chore: add simple unit test
Oct 21, 2024
fbd6d94
fix: mockall in cargo
Oct 21, 2024
3ac629f
Automatically updated Cargo*.lock
Oct 21, 2024
a4eab8b
chore: simplify canister methods
Oct 21, 2024
3406440
Update rs/boundary_node/rate_limits/canister/add_config.rs
nikolay-komarevskiy Oct 21, 2024
306fc08
chore: add schema for rules
Oct 22, 2024
3cacb9f
Automatically updated Cargo*.lock
Oct 22, 2024
e02f328
fix: clippy
Oct 22, 2024
4b99933
chore: use Duration
Oct 22, 2024
6478c6d
chore: use only wasm compilation for CI
Oct 23, 2024
cca546a
fix: format
Oct 23, 2024
039499d
rename: error
Oct 23, 2024
b67780f
remove: test code
Oct 23, 2024
0d98d46
chore: improve canister client scenario
Oct 23, 2024
5c2d972
Update rs/boundary_node/rate_limits/canister/disclose.rs
nikolay-komarevskiy Oct 24, 2024
cc53441
fix: add field
Oct 24, 2024
ba8103b
remove: some error structs
Oct 24, 2024
381074d
add: fetcher test
Oct 24, 2024
2c54dce
Update rs/boundary_node/rate_limits/canister/confidentiality_formatti…
nikolay-komarevskiy Oct 24, 2024
4dee538
chore: add /metrics
Oct 24, 2024
226cfaa
Automatically updated Cargo*.lock
Oct 24, 2024
6e1906c
fix: clippy
Oct 24, 2024
cacb6ee
fix: return
Oct 24, 2024
7402063
add: bazelification
Oct 24, 2024
0f92fcf
Update rs/boundary_node/rate_limits/canister/confidentiality_formatti…
nikolay-komarevskiy Oct 24, 2024
67cb123
fix: formatting
Oct 25, 2024
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
45 changes: 45 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ members = [
"rs/boundary_node/certificate_issuance/certificate_orchestrator",
"rs/boundary_node/discower_bowndary",
"rs/boundary_node/ic_boundary",
"rs/boundary_node/rate_limits",
"rs/boundary_node/rate_limits/api",
"rs/boundary_node/rate_limits/canister_client",
"rs/boundary_node/systemd_journal_gatewayd_shim",
"rs/canister_client",
"rs/canister_client/sender",
Expand Down
37 changes: 37 additions & 0 deletions rs/boundary_node/rate_limits/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
load("//bazel:canisters.bzl", "rust_canister")

package(default_visibility = ["//visibility:public"])

DEPENDENCIES = [
# Keep sorted.
"//rs/boundary_node/rate_limits/api:rate_limits_api",
"//rs/rust_canisters/http_types",
"@crate_index//:anyhow",
"@crate_index//:bincode",
"@crate_index//:candid",
"@crate_index//:hex",
"@crate_index//:ic-cdk",
"@crate_index//:ic-cdk-timers",
"@crate_index//:ic-metrics-encoder",
"@crate_index//:ic-stable-structures",
"@crate_index//:mockall",
"@crate_index//:serde",
"@crate_index//:serde_json",
"@crate_index//:sha2",
"@crate_index//:thiserror",
]

MACRO_DEPENDENCIES = [
# Keep sorted.
"@crate_index//:ic-cdk-macros",
]

rust_canister(
name = "rate_limit_canister",
srcs = glob(["canister/**/*.rs"]),
crate_name = "rate_limit_canister",
crate_root = "canister/lib.rs",
proc_macro_deps = MACRO_DEPENDENCIES,
service_file = "canister/interface.did",
deps = DEPENDENCIES,
)
29 changes: 29 additions & 0 deletions rs/boundary_node/rate_limits/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[package]
name = "rate_limits"
version.workspace = true
authors.workspace = true
edition.workspace = true
description.workspace = true
documentation.workspace = true

[dependencies]
anyhow = { workspace = true }
bincode = { workspace = true }
candid = { workspace = true }
hex = { workspace = true }
ic-canisters-http-types = { path = "../../rust_canisters/http_types" }
ic-cdk = { workspace = true }
ic-cdk-macros = { workspace = true }
ic-cdk-timers = { workspace = true }
ic-metrics-encoder = "1"
ic-stable-structures = { workspace = true }
mockall = { workspace = true }
rate-limits-api = { path = "./api" }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
thiserror = { workspace = true }

[lib]
crate-type = ["cdylib"]
path = "canister/lib.rs"
24 changes: 24 additions & 0 deletions rs/boundary_node/rate_limits/api/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
load("@rules_rust//rust:defs.bzl", "rust_library")

package(default_visibility = ["//visibility:public"])

DEPENDENCIES = [
# Keep sorted.
"@crate_index//:candid",
"@crate_index//:regex",
"@crate_index//:serde",
"@crate_index//:serde_json",
]

MACRO_DEPENDENCIES = []

ALIASES = {}

rust_library(
name = "rate_limits_api",
srcs = glob(["src/**/*.rs"]),
aliases = ALIASES,
crate_name = "rate_limits_api",
proc_macro_deps = MACRO_DEPENDENCIES,
deps = DEPENDENCIES,
)
17 changes: 17 additions & 0 deletions rs/boundary_node/rate_limits/api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "rate-limits-api"
version.workspace = true
authors.workspace = true
edition.workspace = true
description.workspace = true
documentation.workspace = true

[dependencies]
candid = {workspace = true}
regex = { workspace = true }
serde = {workspace = true}
serde_bytes = { workspace = true }
serde_json = { workspace = true }

[lib]
path = "src/lib.rs"
144 changes: 144 additions & 0 deletions rs/boundary_node/rate_limits/api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
use candid::CandidType;
use candid::Principal;
use schema_versions::v1::RateLimitRule;
use serde::{Deserialize, Serialize};

mod schema_versions;
pub use schema_versions::v1;

pub type Version = u64;
pub type Timestamp = u64;
pub type RuleId = String;
pub type IncidentId = String;
pub type SchemaVersion = u64;

pub type GetConfigResponse = Result<ConfigResponse, String>;
pub type AddConfigResponse = Result<(), String>;
pub type GetRuleByIdResponse = Result<OutputRuleMetadata, String>;
pub type DiscloseRulesResponse = Result<(), String>;

#[derive(CandidType, Deserialize, Debug)]
pub enum DiscloseRulesArg {
RuleIds(Vec<RuleId>),
IncidentIds(Vec<IncidentId>),
}

#[derive(CandidType, Deserialize, Debug)]
pub struct ConfigResponse {
pub version: Version,
pub active_since: Timestamp,
pub config: OutputConfig,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct OutputConfig {
pub schema_version: SchemaVersion,
pub rules: Vec<OutputRule>,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct InputConfig {
pub schema_version: SchemaVersion,
pub rules: Vec<InputRule>,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct InputRule {
pub incident_id: IncidentId,
pub rule_raw: Vec<u8>,
pub description: String,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct OutputRule {
pub id: RuleId,
pub incident_id: IncidentId,
pub rule_raw: Option<Vec<u8>>,
pub description: Option<String>,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct OutputRuleMetadata {
pub id: RuleId,
pub incident_id: IncidentId,
pub rule_raw: Option<Vec<u8>>,
pub description: Option<String>,
pub disclosed_at: Option<Timestamp>,
pub added_in_version: Version,
pub removed_in_version: Option<Version>,
}

#[derive(CandidType, Deserialize, Debug)]
pub struct InitArg {
pub registry_polling_period_secs: u64,
}

#[derive(CandidType, Deserialize, Clone, Copy, PartialEq, Eq)]
pub struct GetApiBoundaryNodeIdsRequest {}

#[derive(CandidType, Serialize, Deserialize, Clone, PartialEq, Debug, Eq)]
pub struct ApiBoundaryNodeIdRecord {
pub id: Option<Principal>,
}

const INDENT: &str = " ";
const DOUBLE_INDENT: &str = " ";

impl std::fmt::Display for ConfigResponse {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
writeln!(f, "\nConfiguration details:")?;
writeln!(f, "{INDENT}Version: {}", self.version)?;
writeln!(f, "{INDENT}Active Since: {}", self.active_since)?;
writeln!(f, "{INDENT}{}", self.config)?;
Ok(())
}
}

impl std::fmt::Display for OutputConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Schema version: {}", self.schema_version)?;
for (i, rule) in self.rules.iter().enumerate() {
writeln!(f, "{DOUBLE_INDENT}Rule {}:", i + 1)?;
writeln!(f, "{DOUBLE_INDENT}ID: {}", rule.id)?;
writeln!(f, "{DOUBLE_INDENT}Incident ID: {}", rule.incident_id)?;
if let Some(ref description) = rule.description {
writeln!(f, "{DOUBLE_INDENT}Description: {description}")?;
}
if let Some(ref rule_raw) = rule.rule_raw {
let decoded_rule = RateLimitRule::from_bytes_json(rule_raw.as_slice()).unwrap();
writeln!(f, "{DOUBLE_INDENT}Rate-limit rule:\n{decoded_rule}")?;
}
}
Ok(())
}
}

impl std::fmt::Display for OutputRuleMetadata {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "\nOutputRuleMetadata")?;
writeln!(f, "{INDENT}ID: {}", self.id)?;
writeln!(
f,
"{INDENT}Disclosed at: {}",
self.disclosed_at
.map(|v| v.to_string())
.unwrap_or_else(|| "None".to_string())
)?;
writeln!(f, "{INDENT}Added in version: {}", self.added_in_version)?;
writeln!(
f,
"{INDENT}Removed in version: {}",
self.removed_in_version
.map(|v| v.to_string())
.unwrap_or_else(|| "None".to_string())
)?;
if let Some(ref description) = self.description {
writeln!(f, "{INDENT}Description: {description}")?;
}
if let Some(ref rule_raw) = self.rule_raw {
let decoded_rule = RateLimitRule::from_bytes_json(rule_raw.as_slice()).unwrap();
writeln!(f, "{INDENT}Rate-limit rule:\n{decoded_rule}")?;
}
Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod v1;
69 changes: 69 additions & 0 deletions rs/boundary_node/rate_limits/api/src/schema_versions/v1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use candid::Principal;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

const DOUBLE_INDENT: &str = " ";

// Defines the rate-limit rule to be stored in the canister
#[derive(Serialize, Deserialize, Debug)]
pub struct RateLimitRule {
pub canister_id: Option<Principal>,
pub subnet_id: Option<Principal>,
#[serde(with = "regex_serde")]
pub methods: Regex,
pub limit: String,
}

impl std::fmt::Display for RateLimitRule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"{DOUBLE_INDENT}Canister ID: {}",
format_principal_option(&self.canister_id)
)?;
writeln!(
f,
"{DOUBLE_INDENT}Subnet ID: {}",
format_principal_option(&self.subnet_id)
)?;
writeln!(f, "{DOUBLE_INDENT}Methods: {}", &self.methods)?;
write!(f, "{DOUBLE_INDENT}Limit: {}", &self.limit)?;
Ok(())
}
}

fn format_principal_option(principal: &Option<Principal>) -> String {
match principal {
Some(p) => p.to_string(),
None => "None".to_string(),
}
}

mod regex_serde {
use super::*;

pub fn serialize<S>(regex: &Regex, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
regex.as_str().serialize(serializer)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Regex, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Regex::new(&s).map_err(serde::de::Error::custom)
}
}

impl RateLimitRule {
pub fn to_bytes_json(&self) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(self)
}

pub fn from_bytes_json(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
}
Loading