Skip to content

Commit

Permalink
clippy suggestions and warning removal (#1436)
Browse files Browse the repository at this point in the history
* clippy suggestions and warning removal

Signed-off-by: clux <[email protected]>

* fix feature issue plus chrono clippy in kube client

they have done some questionable deprecations

Signed-off-by: clux <[email protected]>

* fix mixed attribute style on unused imports in tests..

Signed-off-by: clux <[email protected]>

* missed one.. thankfully can re-use the constant

it is for the same purpose so documenting it

Signed-off-by: clux <[email protected]>

* Update kube-runtime/src/reflector/object_ref.rs

Co-authored-by: Natalie Klestrup Röijezon <[email protected]>
Signed-off-by: Eirik A <[email protected]>

* fmt + comment about mock

Signed-off-by: clux <[email protected]>

---------

Signed-off-by: clux <[email protected]>
Signed-off-by: Eirik A <[email protected]>
Co-authored-by: Natalie Klestrup Röijezon <[email protected]>
  • Loading branch information
clux and nightkr authored Mar 22, 2024
1 parent 959986a commit bc74325
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 17 deletions.
1 change: 1 addition & 0 deletions examples/secret_reflector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion kube-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/api/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
27 changes: 21 additions & 6 deletions kube-client/src/client/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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(_, _) => {
Expand Down Expand Up @@ -410,7 +425,7 @@ fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result<ProviderToke
let expiry_date = expiry
.parse::<DateTime<Utc>>()
.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)));
}
}
Expand Down Expand Up @@ -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
Expand Down
7 changes: 3 additions & 4 deletions kube-client/src/client/auth/oidc.rs
Original file line number Diff line number Diff line change
@@ -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},
Expand Down Expand Up @@ -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<bool, errors::IdTokenError> {
Expand All @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 0 additions & 2 deletions kube-runtime/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion kube-runtime/src/reflector/object_ref.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
1 change: 1 addition & 0 deletions kube/src/mock_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand Down

0 comments on commit bc74325

Please sign in to comment.