feat(nacos): add r-nacos compatibility
This commit is contained in:
31 files changed
+2481
-168
No files matched your search
@@ -12,7 +12,7 @@ use sha2::{Digest, Sha256};
|
||||
use crate::ai::AiConfigItem;
|
||||
use crate::connection_secrets::{
|
||||
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY,
|
||||
MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
|
||||
MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
|
||||
};
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
|
||||
use crate::saved_sql::SavedSqlLibrary;
|
||||
@@ -37,6 +37,7 @@ const SECRET_KEYS: &[&str] = &[
|
||||
MQ_AUTH_CLIENT_SECRET_KEY,
|
||||
MQ_TOKEN_SIGNING_KEY,
|
||||
NACOS_AUTH_PASSWORD_KEY,
|
||||
NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
|
||||
];
|
||||
const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
|
||||
const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
|
||||
@@ -720,16 +721,25 @@ fn push_nacos_external_config_secrets(secrets: &mut Vec<ConnectionSecretSnapshot
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return;
|
||||
}
|
||||
let Some(auth) = config
|
||||
if let Some(auth) = config
|
||||
.external_config
|
||||
.as_ref()
|
||||
.and_then(|external_config| external_config.get("auth"))
|
||||
.and_then(serde_json::Value::as_object)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
push_json_secret(secrets, &config.id, NACOS_AUTH_PASSWORD_KEY, auth, "password");
|
||||
{
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
push_json_secret(secrets, &config.id, NACOS_AUTH_PASSWORD_KEY, auth, "password");
|
||||
}
|
||||
}
|
||||
if let Some(auth) = config
|
||||
.external_config
|
||||
.as_ref()
|
||||
.and_then(|external_config| external_config.get("rnacosConsoleAuth"))
|
||||
.and_then(serde_json::Value::as_object)
|
||||
{
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
push_json_secret(secrets, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, auth, "password");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -760,17 +770,25 @@ fn scrub_nacos_auth_secrets(config: &mut ConnectionConfig) {
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return;
|
||||
}
|
||||
let Some(auth) = config
|
||||
if let Some(auth) = config
|
||||
.external_config
|
||||
.as_mut()
|
||||
.and_then(|external_config| external_config.get_mut("auth"))
|
||||
.and_then(serde_json::Value::as_object_mut)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") && auth.contains_key("password")
|
||||
{
|
||||
scrub_json_secret(auth, "password");
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
scrub_json_secret(auth, "password");
|
||||
}
|
||||
}
|
||||
if let Some(auth) = config
|
||||
.external_config
|
||||
.as_mut()
|
||||
.and_then(|external_config| external_config.get_mut("rnacosConsoleAuth"))
|
||||
.and_then(serde_json::Value::as_object_mut)
|
||||
{
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
scrub_json_secret(auth, "password");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2027,7 +2027,63 @@ impl AppState {
|
||||
}
|
||||
|
||||
let (host, port) = self.connection_host_port(connection_id, config).await?;
|
||||
nacos_config.with_server_endpoint(&host, port)
|
||||
let nacos_config = nacos_config.with_server_endpoint(&host, port)?;
|
||||
if nacos_config.rnacos_console_addr.is_empty() {
|
||||
return Ok(nacos_config);
|
||||
}
|
||||
|
||||
let console_url = reqwest::Url::parse(&nacos_config.rnacos_console_addr)
|
||||
.map_err(|error| format!("r-nacos console address is invalid: {error}"))?;
|
||||
let console_host = console_url
|
||||
.host_str()
|
||||
.filter(|host| !host.is_empty())
|
||||
.ok_or_else(|| "r-nacos console address does not include a host".to_string())?;
|
||||
let console_port = console_url
|
||||
.port_or_known_default()
|
||||
.ok_or_else(|| "r-nacos console address does not include a port".to_string())?;
|
||||
let transport_layers = self.resolved_transport_layers(config).await?;
|
||||
if transport_layers.is_empty() {
|
||||
return Ok(nacos_config);
|
||||
}
|
||||
let console_transport_id = rnacos_console_transport_id(connection_id);
|
||||
let local_port = match db::transport_layer_tunnel::start_transport_layers(
|
||||
&console_transport_id,
|
||||
&transport_layers,
|
||||
console_host,
|
||||
console_port,
|
||||
&self.tunnels,
|
||||
&self.proxy_tunnels,
|
||||
&self.http_tunnels,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(port) => port,
|
||||
Err(error) => {
|
||||
db::transport_layer_tunnel::stop_transport_layers(
|
||||
&console_transport_id,
|
||||
transport_layers.len(),
|
||||
&self.tunnels,
|
||||
&self.proxy_tunnels,
|
||||
&self.http_tunnels,
|
||||
)
|
||||
.await;
|
||||
return Err(format!("r-nacos console transport failed: {error}"));
|
||||
}
|
||||
};
|
||||
match nacos_config.with_rnacos_console_endpoint("127.0.0.1", local_port) {
|
||||
Ok(nacos_config) => Ok(nacos_config),
|
||||
Err(error) => {
|
||||
db::transport_layer_tunnel::stop_transport_layers(
|
||||
&console_transport_id,
|
||||
transport_layers.len(),
|
||||
&self.tunnels,
|
||||
&self.proxy_tunnels,
|
||||
&self.http_tunnels,
|
||||
)
|
||||
.await;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_stale_connection_pool(&self, pool_key: &str) -> bool {
|
||||
@@ -2797,6 +2853,14 @@ impl AppState {
|
||||
&self.http_tunnels,
|
||||
)
|
||||
.await;
|
||||
db::transport_layer_tunnel::stop_transport_layers(
|
||||
&rnacos_console_transport_id(connection_id),
|
||||
layer_count,
|
||||
&self.tunnels,
|
||||
&self.proxy_tunnels,
|
||||
&self.http_tunnels,
|
||||
)
|
||||
.await;
|
||||
self.tunnels.stop_tunnel(connection_id).await;
|
||||
self.proxy_tunnels.stop_tunnel(connection_id).await;
|
||||
self.http_tunnels.stop_tunnel(connection_id).await;
|
||||
@@ -3249,6 +3313,10 @@ fn connection_remote_endpoint(config: &ConnectionConfig) -> (String, u16) {
|
||||
}
|
||||
}
|
||||
|
||||
fn rnacos_console_transport_id(connection_id: &str) -> String {
|
||||
format!("{connection_id}:rnacos-console")
|
||||
}
|
||||
|
||||
fn parse_mq_admin_host_port(config: &ConnectionConfig) -> Option<(String, u16)> {
|
||||
let value = config
|
||||
.external_config
|
||||
@@ -5670,6 +5738,7 @@ for line in sys.stdin:
|
||||
config.port = 10840;
|
||||
config.external_config = Some(serde_json::json!({
|
||||
"serverAddr": "http://192.168.2.51:10840",
|
||||
"rnacosConsoleAddr": "http://192.168.2.51:10848",
|
||||
"namespace": "public",
|
||||
"contextPath": "",
|
||||
"auth": { "kind": "none" }
|
||||
@@ -5691,8 +5760,11 @@ for line in sys.stdin:
|
||||
|
||||
assert!(nacos_config.server_addr.starts_with("http://127.0.0.1:"));
|
||||
assert_ne!(nacos_config.server_addr, "http://192.168.2.51:10840");
|
||||
assert!(nacos_config.rnacos_console_addr.starts_with("http://127.0.0.1:"));
|
||||
assert_ne!(nacos_config.rnacos_console_addr, "http://192.168.2.51:10848");
|
||||
assert!(nacos_config.connect_override.is_none());
|
||||
state.proxy_tunnels.stop_tunnel("proxied-nacos:transport:0").await;
|
||||
state.proxy_tunnels.stop_tunnel("proxied-nacos:rnacos-console:transport:0").await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ pub const MQ_TOKEN_SIGNING_SECRET_PREFIX: &str = "mq.token_signing.";
|
||||
pub const MQ_TOKEN_SIGNING_KEY: &str = "mq.token_signing.key";
|
||||
pub const NACOS_AUTH_SECRET_PREFIX: &str = "nacos.auth.";
|
||||
pub const NACOS_AUTH_PASSWORD_KEY: &str = "nacos.auth.password";
|
||||
pub const NACOS_RNACOS_CONSOLE_PASSWORD_KEY: &str = "nacos.auth.rnacos_console_password";
|
||||
|
||||
pub trait ConnectionSecretStore {
|
||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
|
||||
|
||||
@@ -14,9 +14,42 @@ pub enum NacosAuthConfig {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosImplementation {
|
||||
#[default]
|
||||
Nacos,
|
||||
#[serde(rename = "rnacos")]
|
||||
RNacos,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosVersionMode {
|
||||
#[default]
|
||||
Auto,
|
||||
V2,
|
||||
V3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum NacosRNacosConsoleAuth {
|
||||
#[default]
|
||||
Inherit,
|
||||
UsernamePassword {
|
||||
username: String,
|
||||
password: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAdminConfig {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub implementation: Option<NacosImplementation>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub version_mode: Option<NacosVersionMode>,
|
||||
pub server_addr: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub display_server_addr: String,
|
||||
@@ -24,6 +57,17 @@ pub struct NacosAdminConfig {
|
||||
pub namespace: String,
|
||||
#[serde(default)]
|
||||
pub context_path: String,
|
||||
/// Optional r-nacos authenticated-console address. This is separate from
|
||||
/// the OpenAPI server address because r-nacos exposes console-only APIs
|
||||
/// (including config history) on its console service, normally port 10848.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub rnacos_console_addr: String,
|
||||
/// `None` preserves legacy records where supplying a console address
|
||||
/// implicitly enabled configuration history.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rnacos_history_enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub rnacos_console_auth: NacosRNacosConsoleAuth,
|
||||
#[serde(default)]
|
||||
pub auth: NacosAuthConfig,
|
||||
#[serde(default)]
|
||||
@@ -53,10 +97,15 @@ impl NacosAdminConfig {
|
||||
} else {
|
||||
let scheme = if cfg.ssl { "https" } else { "http" };
|
||||
NacosAdminConfig {
|
||||
implementation: None,
|
||||
version_mode: None,
|
||||
server_addr: format!("{scheme}://{}:{}", cfg.host.trim(), cfg.port),
|
||||
display_server_addr: String::new(),
|
||||
namespace: cfg.database.clone().unwrap_or_default(),
|
||||
context_path: String::new(),
|
||||
rnacos_console_addr: String::new(),
|
||||
rnacos_history_enabled: None,
|
||||
rnacos_console_auth: NacosRNacosConsoleAuth::Inherit,
|
||||
auth: if cfg.username.trim().is_empty() {
|
||||
NacosAuthConfig::None
|
||||
} else {
|
||||
@@ -71,16 +120,29 @@ impl NacosAdminConfig {
|
||||
}
|
||||
|
||||
pub fn validate(mut self) -> Result<Self, String> {
|
||||
self.server_addr = self.server_addr.trim().trim_end_matches('/').to_string();
|
||||
self.server_addr = normalize_endpoint_url(&self.server_addr, "Nacos server address")?;
|
||||
if self.server_addr.is_empty() {
|
||||
return Err("Nacos server address is empty".to_string());
|
||||
}
|
||||
if self.display_server_addr.trim().is_empty() {
|
||||
self.display_server_addr = self.server_addr.clone();
|
||||
} else {
|
||||
self.display_server_addr = self.display_server_addr.trim().trim_end_matches('/').to_string();
|
||||
self.display_server_addr = normalize_endpoint_url(&self.display_server_addr, "Nacos display address")?;
|
||||
}
|
||||
self.context_path = normalize_context_path(&self.context_path);
|
||||
self.rnacos_console_addr = if self.rnacos_console_addr.trim().is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
normalize_endpoint_url(&self.rnacos_console_addr, "r-nacos console address")?
|
||||
};
|
||||
if !self.rnacos_console_addr.is_empty() {
|
||||
// Normalization above validates the URL and rejects userinfo.
|
||||
}
|
||||
if let NacosRNacosConsoleAuth::UsernamePassword { username, .. } = &self.rnacos_console_auth {
|
||||
if username.trim().is_empty() {
|
||||
return Err("r-nacos console username is empty".to_string());
|
||||
}
|
||||
}
|
||||
if self.page_size == 0 {
|
||||
self.page_size = default_page_size();
|
||||
}
|
||||
@@ -102,6 +164,55 @@ impl NacosAdminConfig {
|
||||
self.connect_override = None;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn with_rnacos_console_endpoint(mut self, host: &str, port: u16) -> Result<Self, String> {
|
||||
let mut url = reqwest::Url::parse(&self.rnacos_console_addr)
|
||||
.map_err(|e| format!("r-nacos console address is invalid: {e}"))?;
|
||||
url.set_host(Some(host)).map_err(|_| format!("r-nacos console address host is invalid: {host}"))?;
|
||||
url.set_port(Some(port)).map_err(|_| format!("r-nacos console address port is invalid: {port}"))?;
|
||||
self.rnacos_console_addr = url.to_string().trim_end_matches('/').to_string();
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn rnacos_history_enabled(&self) -> bool {
|
||||
self.rnacos_history_enabled.unwrap_or(!self.rnacos_console_addr.is_empty())
|
||||
}
|
||||
|
||||
pub fn effective_rnacos_console_credentials(&self) -> Result<(&str, &str), String> {
|
||||
match &self.rnacos_console_auth {
|
||||
NacosRNacosConsoleAuth::Inherit => match &self.auth {
|
||||
NacosAuthConfig::UsernamePassword { username, password } if !username.trim().is_empty() => {
|
||||
Ok((username, password))
|
||||
}
|
||||
_ => Err("r-nacos console credentials are unavailable".to_string()),
|
||||
},
|
||||
NacosRNacosConsoleAuth::UsernamePassword { username, password } => {
|
||||
if username.trim().is_empty() {
|
||||
return Err("r-nacos console username is empty".to_string());
|
||||
}
|
||||
Ok((username, password))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_effective_rnacos_console_credentials(&self) -> bool {
|
||||
match &self.rnacos_console_auth {
|
||||
NacosRNacosConsoleAuth::Inherit => {
|
||||
matches!(&self.auth, NacosAuthConfig::UsernamePassword { username, .. } if !username.trim().is_empty())
|
||||
}
|
||||
NacosRNacosConsoleAuth::UsernamePassword { username, .. } => !username.trim().is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_endpoint_url(value: &str, label: &str) -> Result<String, String> {
|
||||
let mut url = reqwest::Url::parse(value.trim()).map_err(|e| format!("{label} is invalid: {e}"))?;
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err(format!("{label} must not contain embedded credentials"));
|
||||
}
|
||||
url.set_query(None);
|
||||
url.set_fragment(None);
|
||||
Ok(url.to_string().trim_end_matches('/').to_string())
|
||||
}
|
||||
|
||||
pub fn normalize_context_path(path: &str) -> String {
|
||||
@@ -192,6 +303,38 @@ mod tests {
|
||||
assert_eq!(parsed.namespace, "public");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_rnacos_console_address() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"rnacosConsoleAddr": " http://127.0.0.1:10848/ ",
|
||||
}));
|
||||
|
||||
let parsed = NacosAdminConfig::from_connection(&cfg).unwrap();
|
||||
assert_eq!(parsed.rnacos_console_addr, "http://127.0.0.1:10848");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_optional_profile_fields_and_rejects_endpoint_userinfo() {
|
||||
let parsed = NacosAdminConfig::from_connection(&connection_with_external(serde_json::json!({
|
||||
"implementation": "rnacos",
|
||||
"versionMode": "auto",
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"rnacosConsoleAddr": "http://127.0.0.1:10848/rnacos/",
|
||||
"rnacosHistoryEnabled": true,
|
||||
"rnacosConsoleAuth": { "kind": "usernamePassword", "username": "console", "password": "secret" }
|
||||
})))
|
||||
.unwrap();
|
||||
assert!(parsed.rnacos_history_enabled());
|
||||
assert_eq!(parsed.effective_rnacos_console_credentials().unwrap().0, "console");
|
||||
|
||||
let err = NacosAdminConfig::from_connection(&connection_with_external(serde_json::json!({
|
||||
"serverAddr": "http://user:secret@127.0.0.1:8848"
|
||||
})))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("must not contain embedded credentials"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_external_context_path_defaults_to_root() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
@@ -230,4 +373,18 @@ mod tests {
|
||||
assert_eq!(parsed.context_path, "/console");
|
||||
assert!(parsed.connect_override.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_rnacos_console_endpoint_rewrites_only_host_and_port() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
"serverAddr": "https://192.168.2.51:8848",
|
||||
"rnacosConsoleAddr": "https://192.168.2.51:10848/gateway",
|
||||
"auth": { "kind": "none" }
|
||||
}));
|
||||
|
||||
let parsed =
|
||||
NacosAdminConfig::from_connection(&cfg).unwrap().with_rnacos_console_endpoint("127.0.0.1", 49153).unwrap();
|
||||
|
||||
assert_eq!(parsed.rnacos_console_addr, "https://127.0.0.1:49153/gateway");
|
||||
}
|
||||
}
|
||||
+1116
-47
File diff suppressed because it is too large.
Load diff
@@ -14,28 +14,56 @@ pub mod types;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
use crate::nacos::config::NacosAdminConfig;
|
||||
use crate::nacos::http::NacosOpenApiAdmin;
|
||||
use crate::nacos::http::{
|
||||
new_rnacos_console_session, NacosOpenApiAdmin, RNacosConsoleSessionHandle, RNACOS_CONSOLE_SESSION_CACHE_SECS,
|
||||
};
|
||||
use crate::nacos::port::NacosAdmin;
|
||||
|
||||
pub use crate::nacos::config::{NacosAdminConfig as NacosConfig, NacosAuthConfig};
|
||||
pub use crate::nacos::types::*;
|
||||
|
||||
type NacosAdminEntry = (NacosAdminConfig, Arc<dyn NacosAdmin>);
|
||||
/// Values that bind a console token to one r-nacos login context. Deliberately
|
||||
/// exclude unrelated Nacos settings such as namespace and page size, so those
|
||||
/// edits do not force users through another CAPTCHA challenge.
|
||||
///
|
||||
/// This is also the cache key rather than the DBX connection ID: one r-nacos
|
||||
/// console session authorizes every configuration in the same instance, even
|
||||
/// when the UI reaches it through a different connection context.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
struct RNacosConsoleSessionScope {
|
||||
address: String,
|
||||
username: String,
|
||||
password_fingerprint: [u8; 32],
|
||||
tls_skip_verify: bool,
|
||||
}
|
||||
|
||||
struct RNacosConsoleSessionEntry {
|
||||
session: RNacosConsoleSessionHandle,
|
||||
expires_at: Instant,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct NacosAdminRegistry {
|
||||
instances: RwLock<HashMap<String, NacosAdminEntry>>,
|
||||
build_locks: RwLock<HashMap<String, Arc<Mutex<()>>>>,
|
||||
rnacos_console_sessions: RwLock<HashMap<RNacosConsoleSessionScope, RNacosConsoleSessionEntry>>,
|
||||
}
|
||||
|
||||
impl NacosAdminRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self { instances: RwLock::new(HashMap::new()), build_locks: RwLock::new(HashMap::new()) }
|
||||
Self {
|
||||
instances: RwLock::new(HashMap::new()),
|
||||
build_locks: RwLock::new(HashMap::new()),
|
||||
rnacos_console_sessions: RwLock::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_or_build(&self, cfg: &ConnectionConfig) -> Result<Arc<dyn NacosAdmin>, String> {
|
||||
@@ -66,7 +94,8 @@ impl NacosAdminRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
let admin = build_admin(cfg.clone())?;
|
||||
let rnacos_console_session = self.rnacos_console_session(&cfg).await;
|
||||
let admin = build_admin(cfg.clone(), rnacos_console_session)?;
|
||||
self.instances.write().await.insert(connection_id.to_string(), (cfg, admin.clone()));
|
||||
Ok(admin)
|
||||
}
|
||||
@@ -77,15 +106,113 @@ impl NacosAdminRegistry {
|
||||
}
|
||||
|
||||
pub async fn build_transient_config(&self, cfg: NacosAdminConfig) -> Result<Arc<dyn NacosAdmin>, String> {
|
||||
build_admin(cfg)
|
||||
build_admin(cfg, new_rnacos_console_session())
|
||||
}
|
||||
|
||||
pub async fn drop_connection(&self, connection_id: &str) {
|
||||
self.instances.write().await.remove(connection_id);
|
||||
self.build_locks.write().await.remove(connection_id);
|
||||
}
|
||||
|
||||
async fn rnacos_console_session(&self, cfg: &NacosAdminConfig) -> RNacosConsoleSessionHandle {
|
||||
let Some(scope) = rnacos_console_session_scope(cfg) else {
|
||||
return new_rnacos_console_session();
|
||||
};
|
||||
let mut sessions = self.rnacos_console_sessions.write().await;
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, entry| entry.expires_at > now);
|
||||
if let Some(entry) = sessions.get(&scope) {
|
||||
return entry.session.clone();
|
||||
}
|
||||
let session = new_rnacos_console_session();
|
||||
// Bound cache retention even when a user removes every matching DBX
|
||||
// connection. Tokens expire independently inside the session; this
|
||||
// entry is retained for one additional token lifetime to allow reuse.
|
||||
sessions.insert(
|
||||
scope,
|
||||
RNacosConsoleSessionEntry {
|
||||
session: session.clone(),
|
||||
expires_at: now + Duration::from_secs(RNACOS_CONSOLE_SESSION_CACHE_SECS * 2),
|
||||
},
|
||||
);
|
||||
session
|
||||
}
|
||||
}
|
||||
|
||||
fn build_admin(cfg: NacosAdminConfig) -> Result<Arc<dyn NacosAdmin>, String> {
|
||||
Ok(Arc::new(NacosOpenApiAdmin::new(cfg)?))
|
||||
fn rnacos_console_session_scope(cfg: &NacosAdminConfig) -> Option<RNacosConsoleSessionScope> {
|
||||
if cfg.rnacos_console_addr.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (username, password) = cfg.effective_rnacos_console_credentials().ok()?;
|
||||
Some(RNacosConsoleSessionScope {
|
||||
address: cfg.rnacos_console_addr.clone(),
|
||||
username: username.to_string(),
|
||||
password_fingerprint: Sha256::digest(password.as_bytes()).into(),
|
||||
tls_skip_verify: cfg.tls_skip_verify,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_admin(
|
||||
cfg: NacosAdminConfig,
|
||||
rnacos_console_session: RNacosConsoleSessionHandle,
|
||||
) -> Result<Arc<dyn NacosAdmin>, String> {
|
||||
Ok(Arc::new(NacosOpenApiAdmin::new_with_rnacos_console_session(cfg, rnacos_console_session)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::nacos::config::{NacosImplementation, NacosRNacosConsoleAuth};
|
||||
|
||||
fn rnacos_config(username: &str, password: &str) -> NacosAdminConfig {
|
||||
NacosAdminConfig {
|
||||
implementation: Some(NacosImplementation::RNacos),
|
||||
version_mode: None,
|
||||
server_addr: "http://127.0.0.1:8848".to_string(),
|
||||
display_server_addr: "http://127.0.0.1:8848".to_string(),
|
||||
namespace: "public".to_string(),
|
||||
context_path: "/nacos".to_string(),
|
||||
rnacos_console_addr: "http://127.0.0.1:10848".to_string(),
|
||||
rnacos_history_enabled: Some(true),
|
||||
rnacos_console_auth: NacosRNacosConsoleAuth::UsernamePassword {
|
||||
username: username.to_string(),
|
||||
password: password.to_string(),
|
||||
},
|
||||
auth: NacosAuthConfig::None,
|
||||
tls_skip_verify: false,
|
||||
page_size: 20,
|
||||
connect_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shares_console_session_across_non_auth_connection_changes() {
|
||||
let registry = NacosAdminRegistry::new();
|
||||
let config = rnacos_config("admin", "admin");
|
||||
let first = registry.rnacos_console_session(&config).await;
|
||||
|
||||
let mut namespace_changed = config.clone();
|
||||
namespace_changed.namespace = "tenant-a".to_string();
|
||||
let second = registry.rnacos_console_session(&namespace_changed).await;
|
||||
|
||||
assert!(Arc::ptr_eq(&first, &second));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaces_console_session_when_credentials_change() {
|
||||
let registry = NacosAdminRegistry::new();
|
||||
let first = registry.rnacos_console_session(&rnacos_config("admin", "admin")).await;
|
||||
let second = registry.rnacos_console_session(&rnacos_config("admin", "new-password")).await;
|
||||
|
||||
assert!(!Arc::ptr_eq(&first, &second));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shares_console_session_across_connection_contexts_for_the_same_instance() {
|
||||
let registry = NacosAdminRegistry::new();
|
||||
let first = registry.rnacos_console_session(&rnacos_config("admin", "admin")).await;
|
||||
let second = registry.rnacos_console_session(&rnacos_config("admin", "admin")).await;
|
||||
|
||||
assert!(Arc::ptr_eq(&first, &second));
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ pub trait NacosAdmin: Send + Sync {
|
||||
async fn list_config_history(&self, query: NacosConfigHistoryQuery) -> Result<NacosConfigHistoryList, String>;
|
||||
async fn get_config_history(&self, key: NacosConfigHistoryKey) -> Result<NacosConfigItem, String>;
|
||||
async fn rollback_config(&self, req: NacosConfigRollbackRequest) -> Result<(), String>;
|
||||
async fn get_rnacos_console_captcha(&self) -> Result<NacosRNacosConsoleCaptcha, String>;
|
||||
async fn login_rnacos_console(&self, captcha: Option<String>) -> Result<(), String>;
|
||||
async fn list_services(&self, query: NacosServiceQuery) -> Result<NacosServiceList, String>;
|
||||
async fn list_instances(&self, query: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String>;
|
||||
async fn update_instance(&self, req: NacosInstanceUpdate) -> Result<(), String>;
|
||||
|
||||
@@ -8,7 +8,9 @@ pub async fn nacos_test_connection_core(state: &AppState, conn_id: &str) -> Resu
|
||||
return Err("Connection is not a Nacos admin connection".to_string());
|
||||
}
|
||||
let admin_config = state.nacos_admin_config_for_connection(conn_id, &cfg).await?;
|
||||
let admin = state.nacos_registry.build_transient_config(admin_config).await?;
|
||||
// Keep this probe on the connection's shared adapter so an r-nacos console
|
||||
// session verified for configuration history can also expose its version.
|
||||
let admin = state.nacos_registry.get_or_build_config(conn_id, admin_config).await?;
|
||||
admin.test_connection().await
|
||||
}
|
||||
|
||||
@@ -95,6 +97,23 @@ pub async fn nacos_rollback_config_core(
|
||||
admin.rollback_config(req).await
|
||||
}
|
||||
|
||||
pub async fn nacos_get_rnacos_console_captcha_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
) -> Result<NacosRNacosConsoleCaptcha, String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.get_rnacos_console_captcha().await
|
||||
}
|
||||
|
||||
pub async fn nacos_login_rnacos_console_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
captcha: Option<String>,
|
||||
) -> Result<(), String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.login_rnacos_console(captcha).await
|
||||
}
|
||||
|
||||
pub async fn nacos_list_services_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
|
||||
@@ -5,6 +5,8 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct NacosCapabilities {
|
||||
pub supports_config_management: bool,
|
||||
pub supports_config_history: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub history_unavailable_reason: Option<String>,
|
||||
pub supports_service_management: bool,
|
||||
pub supports_instance_update: bool,
|
||||
pub supports_raw_api: bool,
|
||||
@@ -15,6 +17,7 @@ impl Default for NacosCapabilities {
|
||||
Self {
|
||||
supports_config_management: true,
|
||||
supports_config_history: true,
|
||||
history_unavailable_reason: None,
|
||||
supports_service_management: true,
|
||||
supports_instance_update: true,
|
||||
supports_raw_api: true,
|
||||
@@ -22,6 +25,17 @@ impl Default for NacosCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// A short-lived challenge returned by the authenticated r-nacos console.
|
||||
/// The corresponding server-side CAPTCHA token stays in the adapter process;
|
||||
/// only the image is returned to the desktop client.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosRNacosConsoleCaptcha {
|
||||
pub required: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosConnectionInfo {
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::ai::{AiChatMessage, AiConfig, AiConfigItem, AiConversation, AiProvide
|
||||
use crate::connection_secrets::{
|
||||
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX,
|
||||
MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY,
|
||||
NACOS_AUTH_SECRET_PREFIX,
|
||||
NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
|
||||
};
|
||||
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
|
||||
use crate::history::{
|
||||
@@ -659,11 +659,15 @@ fn scrub_nacos_auth_secrets(config: &mut ConnectionConfig) {
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return;
|
||||
}
|
||||
let Some(auth) = nacos_auth_object_mut(config.external_config.as_mut()) else {
|
||||
return;
|
||||
};
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
scrub_json_secret(auth, "password");
|
||||
if let Some(auth) = nacos_auth_object_mut(config.external_config.as_mut()) {
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
scrub_json_secret(auth, "password");
|
||||
}
|
||||
}
|
||||
if let Some(auth) = nacos_console_auth_object_mut(config.external_config.as_mut()) {
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
scrub_json_secret(auth, "password");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2320,14 +2324,21 @@ impl Storage {
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(auth) = nacos_auth_object_mut(config.external_config.as_mut()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) != Some("usernamePassword") {
|
||||
return Ok(false);
|
||||
let mut rewritten = false;
|
||||
if let Some(auth) = nacos_auth_object_mut(config.external_config.as_mut()) {
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
rewritten |=
|
||||
hydrate_mq_json_secret(self, connection_id, NACOS_AUTH_PASSWORD_KEY, auth, "password").await?;
|
||||
}
|
||||
}
|
||||
|
||||
hydrate_mq_json_secret(self, connection_id, NACOS_AUTH_PASSWORD_KEY, auth, "password").await
|
||||
if let Some(auth) = nacos_console_auth_object_mut(config.external_config.as_mut()) {
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
rewritten |=
|
||||
hydrate_mq_json_secret(self, connection_id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, auth, "password")
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(rewritten)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3280,39 +3291,37 @@ fn persist_nacos_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &Con
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(auth) = nacos_auth_object(config.external_config.as_ref()) else {
|
||||
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword") {
|
||||
replace_nacos_auth_secret_in_tx(tx, &config.id, NACOS_AUTH_PASSWORD_KEY, auth, "password")?;
|
||||
let primary_auth = nacos_auth_object(config.external_config.as_ref())
|
||||
.filter(|auth| auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword"));
|
||||
let primary = primary_auth
|
||||
.and_then(|auth| auth.get("password").and_then(serde_json::Value::as_str))
|
||||
.filter(|secret| !secret.is_empty());
|
||||
let console_auth = nacos_console_auth_object(config.external_config.as_ref())
|
||||
.filter(|auth| auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword"));
|
||||
let console = console_auth
|
||||
.and_then(|auth| auth.get("password").and_then(serde_json::Value::as_str))
|
||||
.filter(|secret| !secret.is_empty());
|
||||
let existing_primary = if primary.is_none() && primary_auth.is_some() {
|
||||
get_secret_in_tx(tx, &config.id, NACOS_AUTH_PASSWORD_KEY)?
|
||||
} else {
|
||||
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
None
|
||||
};
|
||||
let existing_console = if console.is_none() && console_auth.is_some() {
|
||||
get_secret_in_tx(tx, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
if let Some(secret) = primary.or(existing_primary.as_deref()) {
|
||||
persist_secret_in_tx(tx, &config.id, NACOS_AUTH_PASSWORD_KEY, secret)?;
|
||||
}
|
||||
if let Some(secret) = console.or(existing_console.as_deref()) {
|
||||
persist_secret_in_tx(tx, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, secret)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace_nacos_auth_secret_in_tx(
|
||||
tx: &rusqlite::Transaction<'_>,
|
||||
connection_id: &str,
|
||||
key: &str,
|
||||
auth: &serde_json::Map<String, serde_json::Value>,
|
||||
field: &str,
|
||||
) -> Result<(), String> {
|
||||
let current = auth.get(field).and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty());
|
||||
let existing = if current.is_none() { get_secret_in_tx(tx, connection_id, key)? } else { None };
|
||||
delete_secret_prefix_in_tx(tx, connection_id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
match current {
|
||||
Some(secret) => persist_secret_in_tx(tx, connection_id, key, secret),
|
||||
None => match existing {
|
||||
Some(secret) => persist_secret_in_tx(tx, connection_id, key, &secret),
|
||||
None => Ok(()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_json_secret_if_present_in_tx(
|
||||
tx: &rusqlite::Transaction<'_>,
|
||||
connection_id: &str,
|
||||
@@ -3384,6 +3393,16 @@ fn nacos_auth_object_mut(
|
||||
value?.get_mut("auth")?.as_object_mut()
|
||||
}
|
||||
|
||||
fn nacos_console_auth_object(value: Option<&serde_json::Value>) -> Option<&serde_json::Map<String, serde_json::Value>> {
|
||||
value?.get("rnacosConsoleAuth")?.as_object()
|
||||
}
|
||||
|
||||
fn nacos_console_auth_object_mut(
|
||||
value: Option<&mut serde_json::Value>,
|
||||
) -> Option<&mut serde_json::Map<String, serde_json::Value>> {
|
||||
value?.get_mut("rnacosConsoleAuth")?.as_object_mut()
|
||||
}
|
||||
|
||||
fn is_api_key_auth_kind(kind: &str) -> bool {
|
||||
matches!(kind, "apiKey" | "api_key" | "apikey")
|
||||
}
|
||||
@@ -3417,6 +3436,7 @@ mod tests {
|
||||
maybe_import_user_data_db, DataDbImportResult, DesktopIconTheme, DesktopSettings, McpGlobalPolicy,
|
||||
McpGlobalPolicyState, Storage, MCP_GLOBAL_POLICY_KEY,
|
||||
};
|
||||
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
|
||||
use crate::connection_secrets::{
|
||||
MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
|
||||
};
|
||||
@@ -4097,6 +4117,39 @@ mod tests {
|
||||
assert_eq!(nacos_auth_password(&loaded[0]), Some("nacos-secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_connections_moves_separate_rnacos_console_password_to_secret_table() {
|
||||
let path = temp_db_path("rnacos-console-auth-secret");
|
||||
let storage = Storage::open(&path).await.unwrap();
|
||||
let mut config = nacos_connection("rnacos", "");
|
||||
config.external_config = Some(serde_json::json!({
|
||||
"implementation": "rnacos",
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"rnacosConsoleAddr": "http://127.0.0.1:10848/rnacos",
|
||||
"rnacosHistoryEnabled": true,
|
||||
"auth": { "kind": "none" },
|
||||
"rnacosConsoleAuth": { "kind": "usernamePassword", "username": "console", "password": "console-secret" }
|
||||
}));
|
||||
|
||||
storage.save_connections(&[config]).await.unwrap();
|
||||
let raw_json = raw_connection_json(&storage, "rnacos").await;
|
||||
assert!(!raw_json.contains("console-secret"));
|
||||
assert_eq!(
|
||||
storage.get_secret("rnacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap().as_deref(),
|
||||
Some("console-secret")
|
||||
);
|
||||
let loaded = storage.load_connections().await.unwrap();
|
||||
assert_eq!(
|
||||
loaded[0]
|
||||
.external_config
|
||||
.as_ref()
|
||||
.and_then(|value| value.get("rnacosConsoleAuth"))
|
||||
.and_then(|auth| auth.get("password"))
|
||||
.and_then(serde_json::Value::as_str),
|
||||
Some("console-secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_connections_migrates_legacy_nacos_auth_password_out_of_config_json() {
|
||||
let path = temp_db_path("nacos-auth-legacy-migration");
|
||||
|
||||
Reference in new issue
Block a user