From bc7432511bef7ef4169f2442b6a99a235397b7a5 Mon Sep 17 00:00:00 2001 From: Eirik A Date: Fri, 22 Mar 2024 19:18:11 +0000 Subject: [PATCH] clippy suggestions and warning removal (#1436) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * clippy suggestions and warning removal Signed-off-by: clux * fix feature issue plus chrono clippy in kube client they have done some questionable deprecations Signed-off-by: clux * fix mixed attribute style on unused imports in tests.. Signed-off-by: clux * missed one.. thankfully can re-use the constant it is for the same purpose so documenting it Signed-off-by: clux * Update kube-runtime/src/reflector/object_ref.rs Co-authored-by: Natalie Klestrup Röijezon Signed-off-by: Eirik A * fmt + comment about mock Signed-off-by: clux --------- Signed-off-by: clux Signed-off-by: Eirik A Co-authored-by: Natalie Klestrup Röijezon --- examples/secret_reflector.rs | 1 + kube-client/Cargo.toml | 2 +- kube-client/src/api/entry.rs | 2 +- kube-client/src/client/auth/mod.rs | 27 ++++++++++++++++++------ kube-client/src/client/auth/oidc.rs | 7 +++--- kube-client/src/client/mod.rs | 2 +- kube-client/src/lib.rs | 2 +- kube-runtime/src/events.rs | 2 -- kube-runtime/src/reflector/object_ref.rs | 3 ++- kube/src/mock_tests.rs | 1 + 10 files changed, 32 insertions(+), 17 deletions(-) diff --git a/examples/secret_reflector.rs b/examples/secret_reflector.rs index bbbc03128..ac46998e9 100644 --- a/examples/secret_reflector.rs +++ b/examples/secret_reflector.rs @@ -10,6 +10,7 @@ use tracing::*; /// Example way to read secrets #[derive(Debug)] +#[allow(dead_code)] // we only gather data in this ex, we don't print the secrets enum Decoded { /// Usually secrets are just short utf8 encoded strings Utf8(String), diff --git a/kube-client/Cargo.toml b/kube-client/Cargo.toml index 6a27b8e53..1e36fba07 100644 --- a/kube-client/Cargo.toml +++ b/kube-client/Cargo.toml @@ -20,7 +20,7 @@ default = ["client"] rustls-tls = ["rustls", "rustls-pemfile", "hyper-rustls"] openssl-tls = ["openssl", "hyper-openssl"] ws = ["client", "tokio-tungstenite", "rand", "kube-core/ws", "tokio/macros"] -kubelet-debug = ["ws"] +kubelet-debug = ["ws", "kube-core/kubelet-debug"] oauth = ["client", "tame-oauth"] oidc = ["client", "form_urlencoded"] gzip = ["client", "tower-http/decompression-gzip"] diff --git a/kube-client/src/api/entry.rs b/kube-client/src/api/entry.rs index 4c2a90bb3..70d7d61cd 100644 --- a/kube-client/src/api/entry.rs +++ b/kube-client/src/api/entry.rs @@ -227,7 +227,7 @@ impl<'a, K> OccupiedEntry<'a, K> { Some(_) => (), } match &mut meta.namespace { - ns @ None => *ns = self.api.namespace.clone(), + ns @ None => ns.clone_from(&self.api.namespace), Some(ns) if Some(ns.as_str()) != self.api.namespace.as_deref() => { return Err(CommitValidationError::NamespaceMismatch { object_namespace: Some(ns.clone()), diff --git a/kube-client/src/client/auth/mod.rs b/kube-client/src/client/auth/mod.rs index 073b5825d..aa4e692f0 100644 --- a/kube-client/src/client/auth/mod.rs +++ b/kube-client/src/client/auth/mod.rs @@ -130,12 +130,12 @@ impl TokenFile { path: path.as_ref().to_owned(), token: SecretString::from(token), // Try to reload at least once a minute - expires_at: Utc::now() + Duration::seconds(60), + expires_at: Utc::now() + SIXTY_SEC, }) } fn is_expiring(&self) -> bool { - Utc::now() + Duration::seconds(10) > self.expires_at + Utc::now() + TEN_SEC > self.expires_at } /// Get the cached token. Returns `None` if it's expiring. @@ -153,12 +153,27 @@ impl TokenFile { if let Ok(token) = std::fs::read_to_string(&self.path) { self.token = SecretString::from(token); } - self.expires_at = Utc::now() + Duration::seconds(60); + self.expires_at = Utc::now() + SIXTY_SEC; } self.token.expose_secret() } } +// Questionable decisions by chrono: https://github.com/chronotope/chrono/issues/1491 +macro_rules! const_unwrap { + ($e:expr) => { + match $e { + Some(v) => v, + None => panic!(), + } + }; +} + +/// Common constant for checking if an auth token is close to expiring +pub const TEN_SEC: chrono::TimeDelta = const_unwrap!(Duration::try_seconds(10)); +/// Common duration for time between reloads +const SIXTY_SEC: chrono::TimeDelta = const_unwrap!(Duration::try_seconds(60)); + // See https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/client-go/plugin/pkg/client/auth // for the list of auth-plugins supported by client-go. // We currently support the following: @@ -205,7 +220,7 @@ impl RefreshableToken { let mut locked_data = data.lock().await; // Add some wiggle room onto the current timestamp so we don't get any race // conditions where the token expires while we are refreshing - if Utc::now() + Duration::seconds(60) >= locked_data.1 { + if Utc::now() + SIXTY_SEC >= locked_data.1 { // TODO Improve refreshing exec to avoid `Auth::try_from` match Auth::try_from(&locked_data.2)? { Auth::None | Auth::Basic(_, _) | Auth::Bearer(_) | Auth::Certificate(_, _) => { @@ -410,7 +425,7 @@ fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result>() .map_err(Error::MalformedTokenExpirationDate)?; - if Utc::now() + Duration::seconds(60) < expiry_date { + if Utc::now() + SIXTY_SEC < expiry_date { return Ok(ProviderToken::GcpCommand(access_token.clone(), Some(expiry_date))); } } @@ -621,7 +636,7 @@ mod test { #[tokio::test] #[ignore = "fails on windows mysteriously"] async fn exec_auth_command() -> Result<(), Error> { - let expiry = (Utc::now() + Duration::seconds(60 * 60)).to_rfc3339(); + let expiry = (Utc::now() + SIXTY_SEC).to_rfc3339(); let test_file = format!( r#" apiVersion: v1 diff --git a/kube-client/src/client/auth/oidc.rs b/kube-client/src/client/auth/oidc.rs index 0c3d5cbd0..e4aeff4e2 100644 --- a/kube-client/src/client/auth/oidc.rs +++ b/kube-client/src/client/auth/oidc.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; -use chrono::{Duration, TimeZone, Utc}; +use super::TEN_SEC; +use chrono::{TimeZone, Utc}; use form_urlencoded::Serializer; use http::{ header::{HeaderValue, AUTHORIZATION, CONTENT_TYPE}, @@ -148,8 +149,6 @@ pub struct Oidc { impl Oidc { /// Config key for the ID token. const CONFIG_ID_TOKEN: &'static str = "id-token"; - /// How many seconds before ID token expiration we want to refresh it. - const EXPIRY_DELTA_SECONDS: i64 = 10; /// Check whether the stored ID token can still be used. fn token_valid(&self) -> Result { @@ -166,7 +165,7 @@ impl Oidc { .earliest() .ok_or(errors::IdTokenError::InvalidExpirationTimestamp)?; - let valid = Utc::now() + Duration::seconds(Self::EXPIRY_DELTA_SECONDS) < timestamp; + let valid = Utc::now() + TEN_SEC < timestamp; Ok(valid) } diff --git a/kube-client/src/client/mod.rs b/kube-client/src/client/mod.rs index 3b615697d..48476145c 100644 --- a/kube-client/src/client/mod.rs +++ b/kube-client/src/client/mod.rs @@ -9,7 +9,7 @@ //! retrieve the resources served by the kubernetes API. use either::{Either, Left, Right}; use futures::{self, AsyncBufRead, StreamExt, TryStream, TryStreamExt}; -use http::{self, Request, Response, StatusCode}; +use http::{self, Request, Response}; use hyper::Body; use k8s_openapi::apimachinery::pkg::apis::meta::v1 as k8s_meta_v1; pub use kube_core::response::Status; diff --git a/kube-client/src/lib.rs b/kube-client/src/lib.rs index fac0dbe38..d91c73930 100644 --- a/kube-client/src/lib.rs +++ b/kube-client/src/lib.rs @@ -129,8 +129,8 @@ pub use kube_core as core; // Can be run with `cargo test -p kube-client --lib features=rustls-tls,ws -- --ignored` #[cfg(all(feature = "client", feature = "config"))] #[cfg(test)] +#[allow(unused_imports)] // varying test imports depending on feature mod test { - #![allow(unused_imports)] use crate::{ api::{AttachParams, AttachedProcess}, client::ConfigExt, diff --git a/kube-runtime/src/events.rs b/kube-runtime/src/events.rs index cf9f53218..5e0d9dd6f 100644 --- a/kube-runtime/src/events.rs +++ b/kube-runtime/src/events.rs @@ -247,8 +247,6 @@ impl Recorder { #[cfg(test)] mod test { - #![allow(unused_imports)] - use k8s_openapi::api::{ core::v1::{Event as K8sEvent, Service}, rbac::v1::ClusterRole, diff --git a/kube-runtime/src/reflector/object_ref.rs b/kube-runtime/src/reflector/object_ref.rs index e89094fd4..47e8b2d2f 100644 --- a/kube-runtime/src/reflector/object_ref.rs +++ b/kube-runtime/src/reflector/object_ref.rs @@ -1,8 +1,9 @@ use derivative::Derivative; use k8s_openapi::{api::core::v1::ObjectReference, apimachinery::pkg::apis::meta::v1::OwnerReference}; +#[cfg(doc)] use kube_client::core::ObjectMeta; use kube_client::{ api::{DynamicObject, Resource}, - core::{api_version_from_group_version, ObjectMeta}, + core::api_version_from_group_version, }; use std::{ borrow::Cow, diff --git a/kube/src/mock_tests.rs b/kube/src/mock_tests.rs index c8d7c3b0e..86cd9547e 100644 --- a/kube/src/mock_tests.rs +++ b/kube/src/mock_tests.rs @@ -61,6 +61,7 @@ async fn timeout_after_1s(handle: tokio::task::JoinHandle<()>) { /// Scenarios we test for in ApiServerVerifier above enum Scenario { PaginatedList, + #[allow(dead_code)] // remove when/if we start doing better mock tests that use this RadioSilence, }