nacos_sdk/api/plugin/auth/
mod.rs1#[cfg(feature = "auth-by-http")]
2mod auth_by_http;
3#[cfg(feature = "auth-by-http")]
4pub use auth_by_http::*;
5
6#[cfg(feature = "auth-by-aliyun")]
7mod auth_by_aliyun_ram;
8#[cfg(feature = "auth-by-aliyun")]
9pub use auth_by_aliyun_ram::*;
10
11use std::{collections::HashMap, sync::Arc, time::Duration};
12use tracing::{Instrument, debug, debug_span, info};
13
14use crate::common::executor;
15
16#[async_trait::async_trait]
19pub trait AuthPlugin: Send + Sync {
20 async fn login(&self, server_list: Vec<String>, auth_context: AuthContext);
22
23 fn get_login_identity(&self, resource: RequestResource) -> LoginIdentityContext;
25}
26
27#[derive(Clone, Default)]
28pub struct AuthContext {
29 pub(crate) params: HashMap<String, String>,
30}
31
32impl AuthContext {
33 pub fn add_param(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
35 self.params.insert(key.into(), val.into());
36 self
37 }
38
39 pub fn add_params(mut self, map: HashMap<String, String>) -> Self {
41 self.params.extend(map);
42 self
43 }
44}
45
46#[derive(Clone, Default)]
47pub struct LoginIdentityContext {
48 pub(crate) contexts: HashMap<String, String>,
49}
50
51impl LoginIdentityContext {
52 pub fn add_context(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
54 self.contexts.insert(key.into(), val.into());
55 self
56 }
57
58 pub fn add_contexts(mut self, map: HashMap<String, String>) -> Self {
60 self.contexts.extend(map);
61 self
62 }
63}
64
65#[derive(Default)]
67pub(crate) struct NoopAuthPlugin {
68 login_identity: LoginIdentityContext,
69}
70
71#[async_trait::async_trait]
72impl AuthPlugin for NoopAuthPlugin {
73 #[allow(unused_variables)]
74 async fn login(&self, server_list: Vec<String>, auth_context: AuthContext) {
75 }
77
78 fn get_login_identity(&self, _: RequestResource) -> LoginIdentityContext {
79 self.login_identity.clone()
81 }
82}
83
84pub async fn init_auth_plugin(
85 auth_plugin: Arc<dyn AuthPlugin>,
86 server_list: Vec<String>,
87 auth_params: HashMap<String, String>,
88 id: String,
89) {
90 info!("init auth task");
91 let auth_context = AuthContext::default().add_params(auth_params);
92 auth_plugin
94 .login(server_list.clone(), auth_context.clone())
95 .in_current_span()
96 .await;
97 info!("init auth finish");
98
99 executor::spawn(
100 async move {
101 info!("auth plugin task start.");
103 loop {
104 auth_plugin
105 .login(server_list.clone(), auth_context.clone())
106 .in_current_span()
107 .await;
108 debug!("auth_plugin schedule at fixed delay");
109 tokio::time::sleep(Duration::from_secs(30)).await;
110 }
111 }
112 .instrument(debug_span!("auth_task", id = id)),
113 );
114}
115
116#[derive(Debug, Default)]
117pub struct RequestResource {
118 pub request_type: String,
119 pub namespace: Option<String>,
120 pub group: Option<String>,
121 pub resource: Option<String>,
122}