Skip to content

Commit

Permalink
Changes: Add aliyun ram auth plugin demo and doc (#248)
Browse files Browse the repository at this point in the history
* chore: Add example for aliyun ram auth plugin and improve the doc.
* fix: remove invalid test case in auth_by_aliyun_ram
  • Loading branch information
luoxiner committed Sep 20, 2024
1 parent 90c8d49 commit f01abed
Show file tree
Hide file tree
Showing 3 changed files with 173 additions and 18 deletions.
73 changes: 66 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ nacos-sdk = { version = "0.4", features = ["default"] }
// Attention! "public" is "", it is recommended to customize the namespace with clear meaning.
.namespace("")
.app_name("simple_app"),
// .auth_username("TODO")
// .auth_password("TODO")
.auth_username("username")
.auth_password("password")
)
// .enable_auth_plugin_http()
.enable_auth_plugin_http()
.build()?;

// example get a config
Expand Down Expand Up @@ -79,10 +79,10 @@ nacos-sdk = { version = "0.4", features = ["default"] }
// Attention! "public" is "", it is recommended to customize the namespace with clear meaning.
.namespace("")
.app_name("simple_app"),
// .auth_username("TODO")
// .auth_password("TODO")
.auth_username("username")
.auth_password("password")
)
// .enable_auth_plugin_http()
.enable_auth_plugin_http()
.build()?;

pub struct ExampleInstanceChangeListener;
Expand Down Expand Up @@ -121,6 +121,65 @@ See them in `nacos_sdk::api::props::ClientProps` or `nacos_sdk::api::constants::
e.g.
- env `NACOS_CLIENT_COMMON_THREAD_CORES` to set nacos-client-thread-pool num, default 1
- env `NACOS_CLIENT_NAMING_PUSH_EMPTY_PROTECTION` for naming empty data notify protection, default true
- env `NACOS_CLIENT_USERNAME` to set http auth username
- env `NACOS_CLIENT_PASSWORD` to set http auth password
- env `NACOS_CLIENT_ACCESS_KEY` to set Aliyun ram access-key
- env `NACOS_CLIENT_SECRET_KEY` to set Aliyun ram access-secret

### AuthPlugin Features
- > Set access-key, access-secret via Environment variables are recommended.
- auth-by-http
- support http auth via username and password
- how to use
- enable auth-by-http(default is enabled)
```toml
[dependencies]
nacos-sdk = { version = "0.4", features = ["default"] }
```
- Set username and password via environment variables
```shell
export NACOS_CLIENT_USERNAME=you_username
export NACOS_CLIENT_PASSWORD=you_password
```
- Enable auth-by-http in your code
```rust
ConfigServiceBuilder::new(
ClientProps::new()
.server_addr("localhost:8848"))
.enable_auth_plugin_http()

NamingServiceBuilder::new(
ClientProps::new()
.server_addr("localhost:8848"))
.enable_auth_plugin_http()
.build()
```
- auth-by-aliyun
- support aliyun ram auth via access-key and access-secret
- how to use
- enable auth-by-aliyun feature in toml
```toml
[dependencies]
nacos-sdk = { version = "0.4", features = ["default", "auth-by-aliyun"] }
```
- Set accessKey and secretKey via environment variables
```shell
export NACOS_CLIENT_ACCESS_KEY=you_access_key
export NACOS_CLIENT_SECRET_KEY=you_secret_key
```
- Enable aliyun ram auth plugin in code by enable_auth_plugin_aliyun
```rust
ConfigServiceBuilder::new(
ClientProps::new()
.server_addr("localhost:8848"))
.enable_auth_plugin_aliyun()

NamingServiceBuilder::new(
ClientProps::new()
.server_addr("localhost:8848"))
.enable_auth_plugin_aliyun()
.build()
```

## 开发说明
- Build with `cargo build`
Expand Down Expand Up @@ -181,7 +240,7 @@ gRPC 交互的 Payload 和 Metadata 由 `Protocol Buffers` 序列化,具体的
#### Common 通用能力
- [x] 创建参数,自定义传参 + ENV 环境变量读取,后者优先级高;ENV 统一前缀,例如 `NACOS_CLIENT_CONFIG_*` 于配置管理, `NACOS_CLIENT_NAMING_*` 于服务注册
- [x] 通用客户端请求交互,Request/Response 通用 gRPC 逻辑,提供给 Config/Naming
- [x] Auth 鉴权;账密登陆 username/password,TODO accessKey/secretKey
- [x] Auth 鉴权;账密登陆 username/password,阿里云RAM鉴权 accessKey/secretKey
- [x] 通用日志,`tracing::info!()`
- [ ] Monitor,`opentelemetry`
- [ ] 数据落盘与加载(用于服务端宕机弱依赖)
Expand Down
107 changes: 107 additions & 0 deletions examples/aliyun_ram_app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
use nacos_sdk::api::config::{ConfigService, ConfigServiceBuilder};
use nacos_sdk::api::naming::{NamingService, NamingServiceBuilder, ServiceInstance};
use nacos_sdk::api::props::ClientProps;
use std::time::Duration;
use tokio::time::sleep;

/// Aliyun Ram plugin support
///
/// Notice:
/// accessKey and secretKey are sensitive data, don't encode them in you code
/// directly, inject it via environment variables are recommended.
///
/// Example run preparations:
/// 1. inject you accessKey and secretKey via environment variables by following command
/// export NACOS_CLIENT_ACCESS_KEY=you_access_key
/// export NACOS_CLIENT_SECRET_KEY=you_secret_key
///
/// 2. run command
/// cargo run --example aliyun_ram_app --features default,auth-by-aliyun

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "auth-by-aliyun")]
run_config_demo().await;

#[cfg(feature = "auth-by-aliyun")]
run_naming_demo().await;
Ok(())
}

#[cfg(feature = "auth-by-aliyun")]
async fn run_naming_demo() {
let server_addr = "localhost:8848";

/// NamingService
let mut naming_client = NamingServiceBuilder::new(ClientProps::new().server_addr(server_addr))
.enable_auth_plugin_aliyun()
.build()
.unwrap();

let mut instance = ServiceInstance::default();
instance.ip = "localhost".to_string();
instance.port = 8080;

println!("Register localhost:8080 to service(name: test, group: test)");
naming_client
.register_instance("test".to_owned(), Some("test".to_owned()), instance)
.await
.unwrap();

println!("Get All instance from service(name:test, group: test)");
let instances = naming_client
.get_all_instances(
"test".to_string(),
Some("test".to_string()),
Vec::new(),
false,
)
.await
.unwrap();
assert_eq!(1, instances.len());
assert_eq!("localhost", instances[0].ip);
assert_eq!(8080, instances[0].port);
}

#[cfg(feature = "auth-by-aliyun")]
async fn run_config_demo() {
let server_addr = "localhost:8848";

/// Config service
let mut config_client = ConfigServiceBuilder::new(ClientProps::new().server_addr(server_addr))
.enable_auth_plugin_aliyun()
.build()
.unwrap();

println!(
"Publish config dataId = {}, group = {}, content = {}",
"test", "test", "test=test"
);
config_client
.publish_config(
"test".to_string(),
"test".to_string(),
"test=test".to_string(),
Some("properties".to_string()),
)
.await
.unwrap();

println!("Waiting...");
sleep(Duration::from_secs(5)).await;

let response = config_client
.get_config("test".to_string(), "test".to_string())
.await
.unwrap();
println!(
"Get config from nacos for dataId = {}, group = {}, content = {}",
"test",
"test",
response.content()
);
assert_eq!("test=test", response.content());
assert_eq!("properties", response.content_type());
assert_eq!("test", response.group());
assert_eq!("test", response.data_id());
}
11 changes: 0 additions & 11 deletions src/api/plugin/auth/auth_by_aliyun_ram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,15 +495,6 @@ mod test {
);
}

#[test]
fn test_final_signing_key_string_with_default_info() {
let sign_data = calculate_v4_signing_key_util::final_signing_key_string_with_default_info(
"test",
"cn-hangzhou",
);
assert_eq!("lHVX6NEPs3+EKxO3g2iklCwbseQnAWz5nLce9Lm0Po4=", sign_data)
}

struct TestNamingEventListener {
instance_now: ArcSwap<Vec<ServiceInstance>>,
}
Expand All @@ -527,8 +518,6 @@ mod test {
ClientProps::new()
.namespace(std::env::var("NAMESPACE").unwrap_or("".to_string()))
.server_addr(std::env::var("SERVER_ADDR").unwrap())
.auth_ext(ACCESS_KEY, std::env::var("AK").unwrap())
.auth_ext(ACCESS_SECRET, std::env::var("SK").unwrap())
}

fn make_service_instance(ip: &str, port: i32) -> ServiceInstance {
Expand Down

0 comments on commit f01abed

Please sign in to comment.