Skip to content
Open
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
16 changes: 5 additions & 11 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{str::FromStr, sync::Arc};

use anyhow::Error;
use axum::{
Router,
extract::{Path, Request, State},
Expand Down Expand Up @@ -66,11 +65,7 @@ pub async fn log_handler(
.into_response();
};
// Maintain hickory_proto::dnssec=error filter when changing log level
let env_filter = EnvFilter::new(format!(
"{},{}",
log_level,
crate::log::LOG_LEVEL_OVERRIDES
));
let env_filter = EnvFilter::new(format!("{},{}", log_level, crate::log::LOG_LEVEL_OVERRIDES));
let _ = state.log_handle.modify(|f| *f = env_filter);

"Ok\n".into_response()
Expand Down Expand Up @@ -98,7 +93,7 @@ pub fn setup_api_router(
healthy: Arc<dyn Healthy>,
shutdown_token: CancellationToken,
waf_layer: Option<WafLayer>,
) -> Result<Router, Error> {
) -> Router {
let cors_layer = cors::layer(cli.cors.cors_max_age, cli.cors.cors_allow_origin.clone())
.allow_methods([Method::HEAD, Method::GET]);

Expand All @@ -117,10 +112,10 @@ pub fn setup_api_router(

// Enable WAF if requested
if let Some(v) = waf_layer {
router = router.nest("/waf", waf::create_router(v).layer(auth))
router = router.nest("/waf", waf::create_router(v).layer(auth));
}

Ok(router.layer(cors_layer).with_state(state))
router.layer(cors_layer).with_state(state)
}

#[cfg(test)]
Expand All @@ -144,8 +139,7 @@ mod test {
crate::log::LOG_LEVEL_OVERRIDES
)));
let healthy = Arc::new(HealthManager::default());
let router =
setup_api_router(&cli, reload_handle, healthy, CancellationToken::new(), None).unwrap();
let router = setup_api_router(&cli, reload_handle, healthy, CancellationToken::new(), None);

// Bad header
let mut req = Request::builder()
Expand Down
9 changes: 8 additions & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![allow(clippy::struct_field_names)]
#![allow(clippy::struct_excessive_bools)]

use std::{net::SocketAddr, path::PathBuf, time::Duration};

use ::http::HeaderValue;
Expand Down Expand Up @@ -570,10 +573,14 @@ pub struct RateLimit {
pub struct Prerender {
/// Domains that are eligible for pre-prender.
/// If no domains specified - pre-render is not active.
/// This also matches all subdomains one level below,
/// e.g. if domain "foo" is specified then "bar.foo" is also matched,
/// while "baz.bar.foo" is not.
#[clap(env, long)]
pub prerender_domains: Vec<FQDN>,

/// URL of the server-side renderer
/// URL of the server-side renderer.
/// Argument "?url=..." is appended to it with an encoded URL to pre-render.
#[clap(env, long)]
pub prerender_url: Option<Uri>,

Expand Down
6 changes: 3 additions & 3 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,10 @@ pub async fn main(
.context("unable to setup Axum router")?;

// Set up HTTP router (redirecting to HTTPS or serving all endpoints)
let http_router = if !cli.listen.listen_insecure_serve_http_only {
Router::new().fallback(redirect_to_https)
} else {
let http_router = if cli.listen.listen_insecure_serve_http_only {
gateway_router.clone()
} else {
Router::new().fallback(redirect_to_https)
};

// Create HTTP server
Expand Down
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
#![deny(clippy::all)]
//#![warn(clippy::pedantic)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![allow(clippy::format_push_string)]
#![allow(clippy::redundant_closure_for_method_calls)]
#![allow(clippy::manual_string_new)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::type_complexity)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::similar_names)]
// Needed for certain macros
#![recursion_limit = "256"]

Expand Down
8 changes: 4 additions & 4 deletions src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,13 @@ pub async fn middleware(
let response_verification_version = ic_status
.as_ref()
.and_then(|x| x.metadata.response_verification_version)
.map(|x| x.to_string())
.unwrap_or_else(|| "none".into());
.map_or_else(|| "none".into(), |x| x.to_string());

let cache_status_str: &'static str = cache_status.into();
// Strum IntoStaticStr doesn't respect to_string macro option, so fall back to allocation for now
let request_type = ctx
.as_ref()
.map(|x| x.request_type.to_string())
.unwrap_or_else(|| "unknown".into());
.map_or_else(|| "unknown".into(), |x| x.request_type.to_string());

// By this time the channel should already have the data
// since the response headers are already received -> request body was for sure read (or an error happened)
Expand Down Expand Up @@ -311,10 +309,12 @@ pub async fn middleware(
.duration_full
.with_label_values(labels)
.observe(duration_full.as_secs_f64());
#[allow(clippy::cast_precision_loss)]
state
.request_size
.with_label_values(labels)
.observe(request_size as f64);
#[allow(clippy::cast_precision_loss)]
state
.response_size
.with_label_values(labels)
Expand Down
6 changes: 4 additions & 2 deletions src/metrics/runner.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::cast_possible_wrap)]

use std::{sync::Arc, time::Instant};

use anyhow::Error;
Expand Down Expand Up @@ -86,7 +88,7 @@ impl MetricsRunner {
}

impl MetricsRunner {
async fn update(&self) -> Result<(), Error> {
fn update(&self) -> Result<(), Error> {
// Record jemalloc memory usage
epoch::advance().unwrap();
self.mem_allocated
Expand Down Expand Up @@ -123,7 +125,7 @@ impl MetricsRunner {
impl Run for MetricsRunner {
async fn run(&self, _: CancellationToken) -> Result<(), Error> {
let start = Instant::now();
if let Err(e) = self.update().await {
if let Err(e) = self.update() {
warn!("Unable to update metrics: {e:#}");
} else {
debug!("Metrics updated in {}ms", start.elapsed().as_millis());
Expand Down
5 changes: 2 additions & 3 deletions src/policy/denylist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,8 @@ impl Denylist {
}

// Load the list
let list = match self.inner.load_full() {
None => return false,
Some(v) => v,
let Some(list) = self.inner.load_full() else {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I think a load would suffice saving the cost of cloning the hashmap.

return false;
};

// See if there's an entry
Expand Down
8 changes: 4 additions & 4 deletions src/policy/domain_canister.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ impl DomainCanisterMatcher {
let domains = match subnet_type {
Some(SubnetType::System) => &self.domains_system,
Some(SubnetType::CloudEngine) => &self.domains_engine,
Some(SubnetType::Application)
| Some(SubnetType::VerifiedApplication)
| Some(SubnetType::Unknown)
Some(
SubnetType::Application | SubnetType::VerifiedApplication | SubnetType::Unknown,
)
| None => &self.domains_app,
};

Expand Down Expand Up @@ -89,7 +89,7 @@ mod tests {
types.insert(subnet_engine, SubnetType::CloudEngine);

Arc::new(ArcSwapOption::new(Some(Arc::new(SubnetsInfo::new(
ranges, types,
ranges, &types,
)))))
}

Expand Down
2 changes: 1 addition & 1 deletion src/policy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ahash::AHashSet;
use anyhow::{Context, Error};
use candid::Principal;

/// Generic function to load a list of principals from a text file into a HashSet
/// Generic function to load a list of principals from a text file into a `AHashSet`
/// Expects a single principal per line.
pub fn load_principal_list(path: &PathBuf) -> Result<AHashSet<Principal>, Error> {
let data = fs::read_to_string(path).context("failed to read file")?;
Expand Down
13 changes: 5 additions & 8 deletions src/routing/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl CustomDomainStorage {
}

// Store the new snapshot
*self.snapshot.write().unwrap() = snapshot.clone();
self.snapshot.write().unwrap().clone_from(&snapshot);

let mut tree: BTreeMap<FQDN, DomainLookup> = BTreeMap::new();

Expand Down Expand Up @@ -208,8 +208,9 @@ impl CustomDomainStorage {
);

// Set metrics
#[allow(clippy::cast_possible_wrap)]
self.metric_count.set(tree.len() as i64);
self.metric_dupes.set(dupes as i64);
self.metric_dupes.set(i64::from(dupes));

// Store it
let inner = CustomDomainStorageInner(tree);
Expand Down Expand Up @@ -392,7 +393,7 @@ mod test {
const TEST_CANISTER_ID_3: &str = "oa7fk-maaaa-aaaam-abgka-cai";

#[test]
fn test_canister_alias() -> Result<(), Error> {
fn test_canister_alias() {
// Bad principal
let a = CanisterAlias::from_str("foo:bar");
assert!(a.is_err());
Expand All @@ -418,8 +419,6 @@ mod test {
// All is good
let a = CanisterAlias::from_str("foo:aaaaa-aa");
assert!(a.is_ok());

Ok(())
}

#[derive(Debug)]
Expand Down Expand Up @@ -706,7 +705,7 @@ mod test {
}

#[test]
fn test_skip_authority_validation() -> Result<(), Error> {
fn test_skip_authority_validation() {
let domains_base = vec![fqdn!("ic0.app")];
let domains_api = vec![];
let aliases = vec![];
Expand Down Expand Up @@ -760,7 +759,5 @@ mod test {
lookup.canister_id,
Some(Principal::from_text("aaaaa-aa").unwrap())
);

Ok(())
}
}
28 changes: 13 additions & 15 deletions src/routing/error_cause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,13 @@ pub enum BackendError {
impl BackendError {
pub fn details(&self) -> Option<String> {
match self {
Self::Dns(x) => Some(x.clone()),
Self::Body(x) => Some(x.clone()),
Self::TLSOther(x) => Some(x.clone()),
Self::TLSCert(x) => Some(x.clone()),
Self::BoundaryNode(x) => Some(x.clone()),
Self::HttpGateway(x) => Some(x.clone()),
Self::Other(x) => Some(x.clone()),
Self::Dns(x)
| Self::Body(x)
| Self::TLSOther(x)
| Self::TLSCert(x)
| Self::BoundaryNode(x)
| Self::HttpGateway(x)
| Self::Other(x) => Some(x.clone()),
_ => None,
}
}
Expand All @@ -142,8 +142,7 @@ pub enum ClientError {
impl ClientError {
pub fn details(&self) -> Option<String> {
match self {
Self::Body(x) => Some(x.clone()),
Self::MalformedRequest(x) => Some(x.clone()),
Self::Body(x) | Self::MalformedRequest(x) => Some(x.clone()),
Self::UnknownDomain(x) => Some(x.to_string()),
Self::DomainCanisterMismatch(x) => {
Some(format!("The canister {x} is not served by this domain"))
Expand Down Expand Up @@ -179,9 +178,8 @@ impl ErrorCause {
match self {
Self::Client(x) => x.details(),
Self::Backend(x) => x.details(),
Self::Canister(CanisterError::IdIncorrect(x)) => Some(x.clone()),
Self::Canister(CanisterError::IdIncorrect(x)) | Self::Other(x) => Some(x.clone()),
Self::RateLimited(x) => Some(x.to_string()),
Self::Other(x) => Some(x.clone()),
_ => None,
}
}
Expand Down Expand Up @@ -446,7 +444,7 @@ impl ErrorClientFacing {
},

// Canister errors
Self::Canister(CanisterError::NotFound(v)) | Self::Canister(CanisterError::RouteNotFound(v)) => {
Self::Canister(CanisterError::NotFound(v) | CanisterError::RouteNotFound(v)) => {
let canister_id = v.map(|x| x.to_string()).unwrap_or_else(|| "unknown".into());

ErrorData {
Expand All @@ -468,10 +466,10 @@ impl ErrorClientFacing {
Self::Canister(CanisterError::Error(e)) => ErrorData {
status_code: StatusCode::SERVICE_UNAVAILABLE,
title: "Canister Error".into(),
description: r#"The canister failed to process your request.
description: r"The canister failed to process your request.
This may be due to an issue with the canister's program, the resources it has allocated, or its configuration.
This is not an ICP issue, but local to this specific canister. You might want to try again in a moment.
If the problem persists, please reach out to the developers or check the ICP developer forum."#.trim().into(),
If the problem persists, please reach out to the developers or check the ICP developer forum.".trim().into(),
details: Some(e.clone()),
icon: CANISTER_ERROR_SVG.into(),
..Default::default()
Expand Down Expand Up @@ -595,7 +593,7 @@ impl IntoResponse for ErrorClientFacing {
.as_ref()
.zip(ctx.authority.as_ref())
.map(|(alternate, authority)| authority.is_subdomain_of(alternate))
== Some(true)
.is_some_and(|x| x)
{
match self {
Self::Client(ClientError::UnknownDomain(_)) => ALTERNATE_ERROR_UNKNOWN_DOMAIN,
Expand Down
2 changes: 1 addition & 1 deletion src/routing/ic/route_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use url::Url;

use crate::Cli;

/// Provides Healthy trait for the RouteProvider
/// Provides Healthy trait for the `RouteProvider`
#[derive(new, Debug)]
pub struct RouteProviderWrapper(Arc<dyn RouteProvider>);

Expand Down
Loading
Loading