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 13 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
38 changes: 38 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
26 changes: 26 additions & 0 deletions rs/boundary_node/rate_limits/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[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-cdk = { workspace = true }
ic-cdk-macros = { workspace = true }
ic-cdk-timers = { workspace = true }
ic-stable-structures = { 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/canister.rs"
14 changes: 14 additions & 0 deletions rs/boundary_node/rate_limits/api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "rate-limits-api"
version.workspace = true
authors.workspace = true
edition.workspace = true
description.workspace = true
documentation.workspace = true

[dependencies]
candid = {workspace = true}
serde = {workspace = true}

[lib]
path = "src/lib.rs"
76 changes: 76 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,76 @@
use candid::CandidType;
use candid::Principal;
use serde::{Deserialize, Serialize};
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 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>,
}
52 changes: 52 additions & 0 deletions rs/boundary_node/rate_limits/canister/access_control.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use candid::Principal;

use crate::storage::API_BOUNDARY_NODE_PRINCIPALS;

const FULL_ACCESS_ID: &str = "";
const FULL_READ_TESTING_ID: &str = ""; // TODO: remove this

pub trait ResolveAccessLevel {
fn get_access_level(&self) -> AccessLevel;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not get_access_level(&self, Principal) -> AccessLevel? Otherwise, I notice below you create a new AccessLevelResolver every time you want to check someone's access level?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it allows me to construct objects nicely in the canister method:

#[query(name = "get_rule_by_id")]
#[candid_method(query)]
fn get_rule_by_id(rule_id: RuleId) -> GetRuleByIdResponse {
    let caller_id = ic_cdk::api::caller();
    let response = with_state(|state| {
        let access_resolver = AccessLevelResolver::new(caller_id);
        let formatter =
            ConfidentialityFormatterFactory::new(access_resolver).create_rule_formatter();
        let fetcher = RuleFetcher::new(state, formatter);
        fetcher.fetch(rule_id)
    })?;
    Ok(response.into())
}

otherwise i'd need to pass caller_id somehow else.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we doing the ACLs so far down the call stack? For example, for add_config or disclose_rules, we should not even instantiate these ConfigAdder and RulesDiscloser objects. The earlier we can reject the call, the better.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO in the canister function it's better to assemble the final object (by either objects composition or using wrappers) and perform just one single call on that object, which executes the whole logic. With this approach we can ensure best testability of the canister. I think this approach is common for canisters. So I would abstain from putting access level call within the canister method. Although it is probably indeed better to introduce wrapper structs: WithLogger, WithAccessLevel, WithMetrics.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For example, for add_config or disclose_rules, we should not even instantiate these ConfigAdder and RulesDiscloser objects.

We might want to log info before/after authorization, so we need a composable and extensible approach.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it allows me to construct objects nicely in the canister method:

Ah, but there's an even nicer way to achieve this:

// Initialize AccessLevelResolver (let's say call it ACCESS_LEVEL_RESOLVER)

#[query(name = "get_rule_by_id")]
#[candid_method(query)]
fn get_rule_by_id(rule_id: RuleId) -> GetRuleByIdResponse {
    let caller_id = ic_cdk::api::caller();

    // use ACCESS_LEVEL_RESOLVER with caller_id
    
    ...
}

I have some examples for doing this here, here as well as here (last one includes stable structures).

Also, we use a similar approach throughout this codebase.

}

#[derive(Debug, thiserror::Error)]
pub enum AccessLevelError {}

#[derive(PartialEq, Eq)]
pub enum AccessLevel {
FullAccess,
FullRead,
RestrictedRead,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should call it something like Default or Unauthorized. Now, it sounds like this is still a special permission and there is something like NoRead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unauthorized could be a valid variant only for add_config()/disclose() operations, however get_config()/get_rule_bu_id() operations are always "authorized" just the access rights can be different. Default sounds a bit vague to me, a comment could resolve it though. Let's discuss it more. I introduced this enum based on the access level to the stored data, it was meant to be agnostic to specific canister methods.

}

#[derive(Clone)]
pub struct AccessLevelResolver {
pub caller_id: Principal,
}

impl AccessLevelResolver {
pub fn new(caller_id: Principal) -> Self {
Self { caller_id }
}
}

impl ResolveAccessLevel for AccessLevelResolver {
fn get_access_level(&self) -> AccessLevel {
let full_access_principal = Principal::from_text(FULL_ACCESS_ID).unwrap();

API_BOUNDARY_NODE_PRINCIPALS.with(|cell| {
let mut full_read_principals = cell.borrow_mut();
// TODO: this is just for testing, remove later
let full_read_id = Principal::from_text(FULL_READ_TESTING_ID).unwrap();
let _ = full_read_principals.insert(full_read_id);

if self.caller_id == full_access_principal {
return AccessLevel::FullAccess;
} else if full_read_principals.contains(&self.caller_id) {
return AccessLevel::FullRead;
}

AccessLevel::RestrictedRead
})
}
}
Loading
Loading