feat(nacos): add access control and namespace administration
This commit is contained in:
59 files changed
+4563
-479
No files matched your search
@@ -47,7 +47,7 @@ redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tls-rustl
|
||||
rustls = { version = "0.23", features = ["aws-lc-rs"] }
|
||||
rustls-pemfile = "2.2"
|
||||
tiberius = { version = "0.12.3", default-features = false, features = ["tds73", "chrono", "rust_decimal", "rustls", "sql-browser-tokio"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "socks"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["cookies", "json", "stream", "rustls-tls", "socks"] }
|
||||
prometheus-parse = "=0.2.5"
|
||||
futures = "0.3"
|
||||
mongodb = { version = "3.2.5", features = ["socks5-proxy"] }
|
||||
|
||||
@@ -1044,7 +1044,9 @@ async fn build_sensitive_payload(
|
||||
push_secret(&mut connection_secrets, &config.id, "connection_string", connection_string);
|
||||
}
|
||||
push_mq_external_config_secrets(&mut connection_secrets, config);
|
||||
push_nacos_external_config_secrets(&mut connection_secrets, config);
|
||||
if config.save_password {
|
||||
push_nacos_external_config_secrets(&mut connection_secrets, config);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SensitiveSyncPayload {
|
||||
@@ -1191,7 +1193,7 @@ async fn apply_sensitive_payload(
|
||||
}
|
||||
// Metadata is applied before secrets. Never let an older encrypted snapshot
|
||||
// restore a password after the user chose not to retain it locally.
|
||||
if secret.key == "password"
|
||||
if matches!(secret.key.as_str(), "password" | NACOS_AUTH_PASSWORD_KEY | NACOS_RNACOS_CONSOLE_PASSWORD_KEY)
|
||||
&& connections.iter().any(|config| config.id == secret.connection_id && !config.save_password)
|
||||
{
|
||||
continue;
|
||||
@@ -1601,10 +1603,11 @@ fn parent_collection_paths(remote_path: &str) -> Vec<String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
apply_sensitive_payload, apply_sync_snapshot, build_sync_snapshot, build_sync_snapshot_with_saved_secrets,
|
||||
decrypt_sensitive_payload, encrypt_sensitive_payload, encrypt_snippet_snapshot, finalize_snippet_migration,
|
||||
forget_webdav_sync_secrets_passphrase, gitee_snippet_payload, is_legacy_dbx_snapshot, normalized_remote_path,
|
||||
parent_collection_paths, parse_legacy_dbx_snapshot, parse_snippet_snapshot, prepare_legacy_snippet_snapshot,
|
||||
apply_sensitive_payload, apply_sync_snapshot, build_sensitive_payload, build_sync_snapshot,
|
||||
build_sync_snapshot_with_saved_secrets, decrypt_sensitive_payload, encrypt_sensitive_payload,
|
||||
encrypt_snippet_snapshot, finalize_snippet_migration, forget_webdav_sync_secrets_passphrase,
|
||||
gitee_snippet_payload, is_legacy_dbx_snapshot, normalized_remote_path, parent_collection_paths,
|
||||
parse_legacy_dbx_snapshot, parse_snippet_snapshot, prepare_legacy_snippet_snapshot,
|
||||
resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup, save_snippet_sync_id,
|
||||
save_webdav_sync_secrets_preference, scrub_connection_secrets, snapshot_for_snippet_upload,
|
||||
snippet_file_content, snippet_response_id, snippet_sync_settings, webdav_endpoint_uses_direct_connection,
|
||||
@@ -1612,7 +1615,7 @@ mod tests {
|
||||
SnippetProvider, SnippetSyncClient, SnippetSyncConfig, WebDavClient, WebDavConfig, DEFAULT_SNIPPET_FILE_NAME,
|
||||
};
|
||||
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiConfigItem};
|
||||
use crate::connection_secrets::NACOS_AUTH_PASSWORD_KEY;
|
||||
use crate::connection_secrets::{NACOS_AUTH_PASSWORD_KEY, NACOS_RNACOS_CONSOLE_PASSWORD_KEY};
|
||||
use crate::models::connection::{
|
||||
default_redis_key_separator, ConnectionConfig, DatabaseType, SshTunnelConfig, TransportLayerConfig,
|
||||
};
|
||||
@@ -2609,6 +2612,39 @@ mod tests {
|
||||
}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_never_snapshots_or_restores_nacos_passwords_when_saving_is_disabled() {
|
||||
let source = Storage::open(&temp_db_path("sync-no-save-nacos-source")).await.unwrap();
|
||||
let mut config = nacos_connection("nacos", "transient-secret");
|
||||
config.save_password = false;
|
||||
let payload = build_sensitive_payload(&source, std::slice::from_ref(&config), &[]).await.unwrap();
|
||||
assert!(!payload.connection_secrets.iter().any(|secret| {
|
||||
secret.connection_id == "nacos"
|
||||
&& matches!(secret.key.as_str(), NACOS_AUTH_PASSWORD_KEY | NACOS_RNACOS_CONSOLE_PASSWORD_KEY)
|
||||
}));
|
||||
|
||||
let legacy_payload = SensitiveSyncPayload {
|
||||
connection_secrets: vec![
|
||||
ConnectionSecretSnapshot {
|
||||
connection_id: "nacos".to_string(),
|
||||
key: NACOS_AUTH_PASSWORD_KEY.to_string(),
|
||||
secret: "legacy-primary-secret".to_string(),
|
||||
},
|
||||
ConnectionSecretSnapshot {
|
||||
connection_id: "nacos".to_string(),
|
||||
key: NACOS_RNACOS_CONSOLE_PASSWORD_KEY.to_string(),
|
||||
secret: "legacy-console-secret".to_string(),
|
||||
},
|
||||
],
|
||||
ai_configs: None,
|
||||
ai_config: None,
|
||||
tunnel_profiles: None,
|
||||
};
|
||||
apply_sensitive_payload(&source, &legacy_payload, &[config]).await.unwrap();
|
||||
assert_eq!(source.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap(), None);
|
||||
assert_eq!(source.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_snapshot_round_trips_tunnel_profiles() {
|
||||
let storage = Storage::open(&temp_db_path("tunnel-profiles-src")).await.unwrap();
|
||||
|
||||
@@ -27,6 +27,7 @@ use crate::models::connection::{
|
||||
ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, TransportLayerConfig,
|
||||
};
|
||||
use crate::mongo_oidc::MongoOidcBrowserOpener;
|
||||
use crate::nacos::config::{NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD};
|
||||
use crate::path_utils::expand_tilde;
|
||||
use crate::plugins::{PluginDriverSession, PluginRegistry, PluginRuntimeEnv};
|
||||
use crate::query_cancel::RunningQueries;
|
||||
@@ -3170,7 +3171,28 @@ impl AppState {
|
||||
connection_id: &str,
|
||||
config: &ConnectionConfig,
|
||||
) -> Result<crate::nacos::config::NacosAdminConfig, String> {
|
||||
let nacos_config = crate::nacos::config::NacosAdminConfig::from_connection(config)?;
|
||||
let mut nacos_config = crate::nacos::config::NacosAdminConfig::from_connection(config)?;
|
||||
if !config.save_password {
|
||||
let owner = crate::session_credentials::current_credential_owner().unwrap_or_default();
|
||||
let primary_password = self
|
||||
.session_credentials
|
||||
.get_for_purpose(&owner, connection_id, NACOS_PRIMARY_SESSION_PASSWORD)
|
||||
.or_else(|| self.session_credentials.get(&owner, connection_id));
|
||||
if let (Some(password), crate::nacos::config::NacosAuthConfig::UsernamePassword { password: target, .. }) =
|
||||
(primary_password, &mut nacos_config.auth)
|
||||
{
|
||||
*target = password;
|
||||
}
|
||||
if let (
|
||||
Some(password),
|
||||
crate::nacos::config::NacosRNacosConsoleAuth::UsernamePassword { password: target, .. },
|
||||
) = (
|
||||
self.session_credentials.get_for_purpose(&owner, connection_id, NACOS_CONSOLE_SESSION_PASSWORD),
|
||||
&mut nacos_config.rnacos_console_auth,
|
||||
) {
|
||||
*target = password;
|
||||
}
|
||||
}
|
||||
if !config.has_effective_transport_layers() {
|
||||
return Ok(nacos_config);
|
||||
}
|
||||
@@ -3236,6 +3258,57 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn replace_nacos_session_credential(
|
||||
&self,
|
||||
owner_scope: &str,
|
||||
connection_id: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<(), String> {
|
||||
let username = username.trim();
|
||||
if username.is_empty() || password.is_empty() {
|
||||
return Err("Nacos username and replacement password are required".to_string());
|
||||
}
|
||||
let config = self.configs.read().await.get(connection_id).cloned().ok_or("Connection not found")?;
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return Err("Connection is not a Nacos connection".to_string());
|
||||
}
|
||||
if config.save_password {
|
||||
return Err("Connection saves its password; update the persisted connection instead".to_string());
|
||||
}
|
||||
let nacos_config = crate::nacos::config::NacosAdminConfig::from_connection(&config)?;
|
||||
let primary_matches = matches!(
|
||||
&nacos_config.auth,
|
||||
crate::nacos::config::NacosAuthConfig::UsernamePassword { username: current, .. } if current == username
|
||||
);
|
||||
let console_matches = matches!(
|
||||
&nacos_config.rnacos_console_auth,
|
||||
crate::nacos::config::NacosRNacosConsoleAuth::UsernamePassword { username: current, .. } if current == username
|
||||
);
|
||||
if !primary_matches && !console_matches {
|
||||
return Err(format!("Nacos user {username} is not used by this connection"));
|
||||
}
|
||||
if primary_matches {
|
||||
let _ = self.session_credentials.set(owner_scope, connection_id, password);
|
||||
self.session_credentials.set_for_purpose(
|
||||
owner_scope,
|
||||
connection_id,
|
||||
NACOS_PRIMARY_SESSION_PASSWORD,
|
||||
password,
|
||||
);
|
||||
}
|
||||
if console_matches {
|
||||
self.session_credentials.set_for_purpose(
|
||||
owner_scope,
|
||||
connection_id,
|
||||
NACOS_CONSOLE_SESSION_PASSWORD,
|
||||
password,
|
||||
);
|
||||
}
|
||||
self.nacos_registry.drop_connection(connection_id).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove_stale_connection_pool(&self, pool_key: &str) -> bool {
|
||||
if self.running_queries.is_pool_active(pool_key) {
|
||||
return false;
|
||||
@@ -5114,6 +5187,60 @@ pub fn connection_configs_pool_equivalent(a: &ConnectionConfig, b: &ConnectionCo
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether transient credentials can safely survive a persisted config update.
|
||||
///
|
||||
/// This comparison is intentionally conservative: only presentation, local
|
||||
/// visibility, and runtime-policy fields are ignored. Endpoint, account,
|
||||
/// transport, TLS, driver, and unclassified external-config changes still
|
||||
/// invalidate credentials. Nacos managed namespaces are a local discovery
|
||||
/// scope and therefore do not change which account a transient password
|
||||
/// belongs to.
|
||||
pub fn connection_configs_session_credentials_compatible(a: &ConnectionConfig, b: &ConnectionConfig) -> bool {
|
||||
fn normalize(mut config: ConnectionConfig) -> ConnectionConfig {
|
||||
config.name.clear();
|
||||
config.note.clear();
|
||||
config.driver_label = None;
|
||||
config.default_schema = None;
|
||||
config.visible_databases = None;
|
||||
config.visible_schemas = None;
|
||||
config.show_system_schemas = false;
|
||||
config.color = None;
|
||||
config.docs_notes_path = None;
|
||||
config.connect_timeout_secs = 0;
|
||||
config.query_timeout_secs = 0;
|
||||
config.idle_timeout_secs = 0;
|
||||
config.keepalive_interval_secs = 0;
|
||||
config.redis_key_separator.clear();
|
||||
config.redis_scan_page_size = None;
|
||||
config.redis_database_aliases.clear();
|
||||
config.one_time = false;
|
||||
config.read_only = false;
|
||||
config.is_production = false;
|
||||
config.production_databases.clear();
|
||||
config.database_info = None;
|
||||
|
||||
if config.db_type == DatabaseType::Nacos {
|
||||
if let Some(external) = config.external_config.as_mut().and_then(serde_json::Value::as_object_mut) {
|
||||
external.remove("managedNamespaces");
|
||||
external.remove("managed_namespaces");
|
||||
if !config.save_password {
|
||||
for key in ["auth", "rnacosConsoleAuth", "rnacos_console_auth"] {
|
||||
if let Some(auth) = external.get_mut(key).and_then(serde_json::Value::as_object_mut) {
|
||||
auth.insert("password".to_string(), serde_json::Value::String(String::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !config.save_password {
|
||||
config.password.clear();
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
normalize(a.clone()) == normalize(b.clone())
|
||||
}
|
||||
|
||||
fn pool_key_for_session_role(
|
||||
config: Option<&ConnectionConfig>,
|
||||
base_pool_key: String,
|
||||
@@ -5561,17 +5688,17 @@ async fn detect_ob_oracle_mode(config: &ConnectionConfig, pool: &db::mysql::MySq
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
agent_connect_timeout, connection_configs_pool_equivalent, connection_probe_endpoints,
|
||||
connection_remote_endpoint, connection_url_for_endpoint, database_connection_config,
|
||||
database_connection_config_with_catalog, gaussdb_identifier_quote_from_query_result,
|
||||
gaussdb_m_jdbc_config_for_endpoint, gaussdb_uses_m_jdbc_driver, kafka_single_loopback_bootstrap_endpoint,
|
||||
metadata_connection_config, mysql_metadata_fallback_url, mysql_pool_setup_queries,
|
||||
oceanbase_mysql_setup_queries, prestosql_jdbc_config_for_endpoint, redacted_connection_url_for_endpoint,
|
||||
redis_sentinel_transport_id, redis_sentinel_transport_prefix, sqlserver_legacy_agent_config,
|
||||
sqlserver_legacy_driver_error, sqlserver_uses_legacy_driver, task_client_session_id,
|
||||
upsert_connection_url_param, uses_bare_mysql_pool, uses_tcp_probe, validate_connection_url_params,
|
||||
validate_h2_database_path, AppState, MysqlMode, PoolKind, TxnConnection, GAUSSDB_M_JDBC_DRIVER_CLASS,
|
||||
GAUSSDB_M_JDBC_DRIVER_PROFILE, PRESTOSQL_JDBC_DRIVER_CLASS,
|
||||
agent_connect_timeout, connection_configs_pool_equivalent, connection_configs_session_credentials_compatible,
|
||||
connection_probe_endpoints, connection_remote_endpoint, connection_url_for_endpoint,
|
||||
database_connection_config, database_connection_config_with_catalog,
|
||||
gaussdb_identifier_quote_from_query_result, gaussdb_m_jdbc_config_for_endpoint, gaussdb_uses_m_jdbc_driver,
|
||||
kafka_single_loopback_bootstrap_endpoint, metadata_connection_config, mysql_metadata_fallback_url,
|
||||
mysql_pool_setup_queries, oceanbase_mysql_setup_queries, prestosql_jdbc_config_for_endpoint,
|
||||
redacted_connection_url_for_endpoint, redis_sentinel_transport_id, redis_sentinel_transport_prefix,
|
||||
sqlserver_legacy_agent_config, sqlserver_legacy_driver_error, sqlserver_uses_legacy_driver,
|
||||
task_client_session_id, upsert_connection_url_param, uses_bare_mysql_pool, uses_tcp_probe,
|
||||
validate_connection_url_params, validate_h2_database_path, AppState, MysqlMode, PoolKind, TxnConnection,
|
||||
GAUSSDB_M_JDBC_DRIVER_CLASS, GAUSSDB_M_JDBC_DRIVER_PROFILE, PRESTOSQL_JDBC_DRIVER_CLASS,
|
||||
};
|
||||
use crate::agent_connection::{
|
||||
agent_connect_params, mongo_legacy_error_with_auth_hint, mongo_uses_legacy_driver,
|
||||
@@ -5735,6 +5862,59 @@ mod tests {
|
||||
assert!(connection_configs_pool_equivalent(&a, &a.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_credentials_survive_nacos_scope_and_display_updates() {
|
||||
let mut initial = mysql_config(None);
|
||||
initial.db_type = DatabaseType::Nacos;
|
||||
initial.save_password = false;
|
||||
initial.password = "old-session-secret".to_string();
|
||||
initial.visible_databases = Some(vec!["namespace-a".to_string()]);
|
||||
initial.external_config = Some(serde_json::json!({
|
||||
"implementation": "nacos",
|
||||
"versionMode": "v3",
|
||||
"apiPlane": "admin",
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"managedNamespaces": ["namespace-a"],
|
||||
"auth": {
|
||||
"kind": "usernamePassword",
|
||||
"username": "ordinary-user",
|
||||
"password": "old-session-secret"
|
||||
}
|
||||
}));
|
||||
|
||||
let mut updated = initial.clone();
|
||||
updated.name = "Renamed Nacos".to_string();
|
||||
updated.note = "Local note".to_string();
|
||||
updated.visible_databases = Some(vec!["namespace-a".to_string(), "namespace-b".to_string()]);
|
||||
updated.external_config.as_mut().unwrap()["managedNamespaces"] =
|
||||
serde_json::json!(["namespace-a", "namespace-b"]);
|
||||
updated.external_config.as_mut().unwrap()["auth"]["password"] = serde_json::json!("new-session-secret");
|
||||
|
||||
assert!(connection_configs_session_credentials_compatible(&initial, &updated));
|
||||
|
||||
let mut scrubbed = updated.clone();
|
||||
scrubbed.external_config.as_mut().unwrap()["auth"].as_object_mut().unwrap().remove("password");
|
||||
assert!(connection_configs_session_credentials_compatible(&initial, &scrubbed));
|
||||
|
||||
updated.external_config.as_mut().unwrap()["serverAddr"] = serde_json::json!("http://127.0.0.1:8080");
|
||||
assert!(!connection_configs_session_credentials_compatible(&initial, &updated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_credentials_do_not_survive_nacos_account_updates() {
|
||||
let mut initial = mysql_config(None);
|
||||
initial.db_type = DatabaseType::Nacos;
|
||||
initial.save_password = false;
|
||||
initial.external_config = Some(serde_json::json!({
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"auth": { "kind": "usernamePassword", "username": "user-a", "password": "secret" }
|
||||
}));
|
||||
let mut updated = initial.clone();
|
||||
updated.external_config.as_mut().unwrap()["auth"]["username"] = serde_json::json!("user-b");
|
||||
|
||||
assert!(!connection_configs_session_credentials_compatible(&initial, &updated));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_session_credential_injects_saved_password_only_for_no_save_connections() {
|
||||
let dir = std::env::temp_dir().join(format!("dbx-core-session-cred-{}", std::process::id()));
|
||||
|
||||
@@ -511,14 +511,17 @@ fn validate_replayed_commands(snapshot: &NacosAccessControlSnapshot, commands: &
|
||||
.filter(|(bound_username, _)| bound_username == username)
|
||||
.map(|(_, role)| role.clone())
|
||||
.collect();
|
||||
if matches!(command, StepCommand::DeleteCreatedUser { .. }) && !roles.is_empty() {
|
||||
return Err(format!(
|
||||
"Cannot undo creation of Nacos user {username} because it now has external role bindings: {}",
|
||||
roles.join(", ")
|
||||
));
|
||||
}
|
||||
for role in roles {
|
||||
let member_count = bindings.iter().filter(|(_, bound_role)| bound_role == &role).count();
|
||||
if role == ADMIN_ROLE && member_count <= 1 {
|
||||
return Err("At least one ROLE_ADMIN member must remain".to_string());
|
||||
}
|
||||
if role != ADMIN_ROLE && member_count <= 1 {
|
||||
return Err(format!("Add another member to {role} before deleting its last member"));
|
||||
}
|
||||
}
|
||||
bindings.retain(|(bound_username, _)| bound_username != username);
|
||||
}
|
||||
@@ -632,8 +635,6 @@ fn plan_operation(
|
||||
return Err("At least one ROLE_ADMIN member must remain".to_string());
|
||||
}
|
||||
validate_admin_member_change(snapshot, ¤t_members, &desired_members, confirmation.as_deref())?;
|
||||
} else if desired_members.is_empty() {
|
||||
return Err("A role requires at least one member".to_string());
|
||||
}
|
||||
let desired_permissions: BTreeSet<_> = if role == ADMIN_ROLE {
|
||||
BTreeSet::new()
|
||||
@@ -677,10 +678,8 @@ fn plan_operation(
|
||||
if !snapshot.users.iter().any(|user| user.username == username) {
|
||||
return Err(format!("Nacos user {username} does not exist"));
|
||||
}
|
||||
if snapshot.current_username.as_deref() == Some(username.as_str())
|
||||
&& confirmation.as_deref() != Some(username.as_str())
|
||||
{
|
||||
return Err("Deleting the current account requires typing the current username".to_string());
|
||||
if confirmation.as_deref() != Some(username.as_str()) {
|
||||
return Err("Deleting a user requires typing its username".to_string());
|
||||
}
|
||||
let current: BTreeSet<_> = snapshot
|
||||
.role_bindings
|
||||
@@ -797,7 +796,7 @@ fn validate_role_removals(
|
||||
) -> Result<(), String> {
|
||||
for role in current.difference(desired) {
|
||||
let count = snapshot.role_bindings.iter().filter(|binding| binding.role == *role).count();
|
||||
if count <= 1 {
|
||||
if role == ADMIN_ROLE && count <= 1 {
|
||||
return Err(format!("Add another member to {role} before removing its last member"));
|
||||
}
|
||||
if role == ADMIN_ROLE
|
||||
@@ -817,9 +816,6 @@ fn validate_role_removal_count(role: &str, member_count: usize, mode: RoleRemova
|
||||
if role == ADMIN_ROLE && (mode == RoleRemovalMode::DeleteRole || member_count <= 1) {
|
||||
return Err("At least one ROLE_ADMIN member must remain".to_string());
|
||||
}
|
||||
if role != ADMIN_ROLE && mode == RoleRemovalMode::PreserveRole && member_count <= 1 {
|
||||
return Err(format!("Add another member to {role} before removing its last member"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1217,19 +1213,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_current_account_requires_typed_confirmation_even_without_roles() {
|
||||
let snapshot = snapshot_with_user("nacos");
|
||||
fn deleting_any_user_requires_exact_typed_username_confirmation() {
|
||||
let mut snapshot = snapshot_with_user("alice");
|
||||
snapshot.current_username = None;
|
||||
let error = plan_operation(
|
||||
&snapshot,
|
||||
NacosAccessOperationRequest::DeleteUser { username: "nacos".to_string(), confirmation: None },
|
||||
NacosAccessOperationRequest::DeleteUser {
|
||||
username: "alice".to_string(),
|
||||
confirmation: Some("Alice".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.contains("current account"));
|
||||
assert!(error.contains("typing its username"));
|
||||
|
||||
let (commands, _, _) = plan_operation(
|
||||
&snapshot,
|
||||
NacosAccessOperationRequest::DeleteUser {
|
||||
username: "alice".to_string(),
|
||||
confirmation: Some("alice".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(commands.as_slice(), [StepCommand::DeleteUser { username }] if username == "alice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_regular_role_member_is_rejected() {
|
||||
fn removing_the_last_regular_role_member_preserves_its_permissions() {
|
||||
let mut snapshot = snapshot_with_user("alice");
|
||||
snapshot.current_username = None;
|
||||
snapshot.role_bindings.push(NacosRoleBinding { username: "alice".to_string(), role: "ops".to_string() });
|
||||
snapshot.users[0].roles.push("ops".to_string());
|
||||
snapshot.roles.push(NacosRoleSummary {
|
||||
@@ -1239,7 +1250,7 @@ mod tests {
|
||||
complete: true,
|
||||
administrator: false,
|
||||
});
|
||||
let error = plan_operation(
|
||||
let (commands, _, _) = plan_operation(
|
||||
&snapshot,
|
||||
NacosAccessOperationRequest::UpdateUserRoles {
|
||||
username: "alice".to_string(),
|
||||
@@ -1247,8 +1258,12 @@ mod tests {
|
||||
confirmation: None,
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.contains("last member"));
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
commands.as_slice(),
|
||||
[StepCommand::RemoveRole { username, role, mode: RoleRemovalMode::PreserveRole }]
|
||||
if username == "alice" && role == "ops"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1338,8 +1353,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn role_removal_modes_distinguish_edits_from_role_deletion() {
|
||||
let preserve_error = validate_role_removal_count("ops", 1, RoleRemovalMode::PreserveRole).unwrap_err();
|
||||
assert!(preserve_error.contains("last member"));
|
||||
assert!(validate_role_removal_count("ops", 1, RoleRemovalMode::PreserveRole).is_ok());
|
||||
assert!(validate_role_removal_count("ops", 1, RoleRemovalMode::DeleteRole).is_ok());
|
||||
|
||||
let admin_error = validate_role_removal_count(ADMIN_ROLE, 2, RoleRemovalMode::DeleteRole).unwrap_err();
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
use crate::models::connection::{ConnectionConfig, DatabaseType};
|
||||
|
||||
pub const NACOS_PRIMARY_SESSION_PASSWORD: &str = "nacos-primary-password";
|
||||
pub const NACOS_CONSOLE_SESSION_PASSWORD: &str = "nacos-console-password";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
@@ -33,6 +36,14 @@ pub enum NacosVersionMode {
|
||||
V3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosApiPlane {
|
||||
#[default]
|
||||
Admin,
|
||||
Console,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosMetricsMode {
|
||||
@@ -60,6 +71,8 @@ pub struct NacosAdminConfig {
|
||||
pub implementation: Option<NacosImplementation>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub version_mode: Option<NacosVersionMode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub api_plane: Option<NacosApiPlane>,
|
||||
pub server_addr: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub display_server_addr: String,
|
||||
@@ -99,6 +112,47 @@ pub struct NacosAdminConfig {
|
||||
pub connect_override: Option<NacosConnectOverride>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct NacosTransientPasswords {
|
||||
pub primary: Option<String>,
|
||||
pub console: Option<String>,
|
||||
}
|
||||
|
||||
fn take_username_password(value: Option<&mut serde_json::Value>) -> Option<String> {
|
||||
let auth = value?.as_object_mut()?;
|
||||
if auth.get("kind").and_then(serde_json::Value::as_str) != Some("usernamePassword") {
|
||||
return None;
|
||||
}
|
||||
let password = auth.get_mut("password")?;
|
||||
let secret = password.as_str()?.to_string();
|
||||
*password = serde_json::Value::String(String::new());
|
||||
(!secret.is_empty()).then_some(secret)
|
||||
}
|
||||
|
||||
/// Removes no-save Nacos passwords from a runtime configuration and returns
|
||||
/// them for placement in the owner-scoped in-memory credential store.
|
||||
pub fn take_transient_passwords(config: &mut ConnectionConfig) -> NacosTransientPasswords {
|
||||
if config.db_type != DatabaseType::Nacos || config.save_password {
|
||||
return NacosTransientPasswords::default();
|
||||
}
|
||||
|
||||
let top_level_password = std::mem::take(&mut config.password);
|
||||
let Some(external) = config.external_config.as_mut().and_then(serde_json::Value::as_object_mut) else {
|
||||
return NacosTransientPasswords {
|
||||
primary: (!top_level_password.is_empty()).then_some(top_level_password),
|
||||
console: None,
|
||||
};
|
||||
};
|
||||
|
||||
NacosTransientPasswords {
|
||||
// NacosAdminConfig::from_connection treats external_config as the
|
||||
// canonical source when present, so a stale top-level password must
|
||||
// never override an explicitly empty external auth password.
|
||||
primary: take_username_password(external.get_mut("auth")),
|
||||
console: take_username_password(external.get_mut("rnacosConsoleAuth")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosConnectOverride {
|
||||
@@ -127,6 +181,7 @@ impl NacosAdminConfig {
|
||||
NacosAdminConfig {
|
||||
implementation: None,
|
||||
version_mode: None,
|
||||
api_plane: None,
|
||||
server_addr: format!("{scheme}://{}:{}", cfg.host.trim(), cfg.port),
|
||||
display_server_addr: String::new(),
|
||||
namespace: cfg.database.clone().unwrap_or_default(),
|
||||
@@ -169,6 +224,7 @@ impl NacosAdminConfig {
|
||||
&& !context_path_is_explicit_root
|
||||
&& matches!(self.implementation, Some(NacosImplementation::Nacos))
|
||||
&& matches!(self.version_mode, Some(NacosVersionMode::V3))
|
||||
&& self.api_plane() == NacosApiPlane::Admin
|
||||
{
|
||||
self.context_path = "/nacos".to_string();
|
||||
}
|
||||
@@ -209,6 +265,10 @@ impl NacosAdminConfig {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn api_plane(&self) -> NacosApiPlane {
|
||||
self.api_plane.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn with_server_endpoint(mut self, host: &str, port: u16) -> Result<Self, String> {
|
||||
let mut url =
|
||||
reqwest::Url::parse(&self.server_addr).map_err(|e| format!("Nacos server address is invalid: {e}"))?;
|
||||
@@ -485,6 +545,21 @@ mod tests {
|
||||
assert_eq!(parsed.context_path, "/nacos");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_nacos_v3_console_defaults_to_root_context() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
"implementation": "nacos",
|
||||
"versionMode": "v3",
|
||||
"apiPlane": "console",
|
||||
"serverAddr": "http://127.0.0.1:8080",
|
||||
"auth": { "kind": "none" }
|
||||
}));
|
||||
|
||||
let parsed = NacosAdminConfig::from_connection(&cfg).unwrap();
|
||||
assert_eq!(parsed.api_plane(), NacosApiPlane::Console);
|
||||
assert_eq!(parsed.context_path, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_nacos_v3_root_context_is_preserved() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
@@ -511,6 +586,43 @@ mod tests {
|
||||
assert!(matches!(parsed.auth, NacosAuthConfig::UsernamePassword { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_no_save_external_passwords_without_removing_other_fields() {
|
||||
let mut cfg = connection_with_external(serde_json::json!({
|
||||
"implementation": "rnacos",
|
||||
"serverAddr": "http://127.0.0.1:8848",
|
||||
"managedNamespaces": ["team-a"],
|
||||
"auth": { "kind": "usernamePassword", "username": "primary", "password": "primary-secret" },
|
||||
"rnacosConsoleAuth": { "kind": "usernamePassword", "username": "console", "password": "console-secret" }
|
||||
}));
|
||||
cfg.save_password = false;
|
||||
cfg.password = "stale-top-level-secret".to_string();
|
||||
|
||||
let passwords = take_transient_passwords(&mut cfg);
|
||||
|
||||
assert_eq!(passwords.primary.as_deref(), Some("primary-secret"));
|
||||
assert_eq!(passwords.console.as_deref(), Some("console-secret"));
|
||||
assert!(cfg.password.is_empty());
|
||||
let external = cfg.external_config.as_ref().unwrap();
|
||||
assert_eq!(external["auth"]["password"], "");
|
||||
assert_eq!(external["rnacosConsoleAuth"]["password"], "");
|
||||
assert_eq!(external["managedNamespaces"], serde_json::json!(["team-a"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_legacy_top_level_password_only_without_external_config() {
|
||||
let mut cfg = connection_with_external(serde_json::Value::Null);
|
||||
cfg.external_config = None;
|
||||
cfg.save_password = false;
|
||||
cfg.password = "legacy-secret".to_string();
|
||||
|
||||
let passwords = take_transient_passwords(&mut cfg);
|
||||
|
||||
assert_eq!(passwords.primary.as_deref(), Some("legacy-secret"));
|
||||
assert_eq!(passwords.console, None);
|
||||
assert!(cfg.password.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_server_endpoint_rewrites_only_host_and_port() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
|
||||
+604
-192
File diff suppressed because it is too large.
Load diff
@@ -176,6 +176,7 @@ mod tests {
|
||||
NacosAdminConfig {
|
||||
implementation: Some(NacosImplementation::RNacos),
|
||||
version_mode: None,
|
||||
api_plane: 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(),
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures::{stream, StreamExt};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::nacos::port::{NacosAdmin, NacosNamespaceAuthorizationSnapshot};
|
||||
@@ -11,6 +12,10 @@ const AUTH_PAGE_SIZE: u32 = 500;
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
const CACHE_MAX_CONNECTIONS: usize = 64;
|
||||
const ADMIN_ROLE: &str = "ROLE_ADMIN";
|
||||
// Namespace probing is deliberately reserved for the explicit connection-form
|
||||
// action. Keep enough parallelism for useful feedback without overwhelming a
|
||||
// Nacos server that contains many namespaces.
|
||||
const DISCOVERY_CONCURRENCY: usize = 8;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct NamespaceAccessCacheEntry {
|
||||
@@ -49,6 +54,100 @@ pub async fn list_readable_namespaces(
|
||||
Ok(load_readable_namespaces(connection_id, connection_fingerprint, admin).await?.namespaces)
|
||||
}
|
||||
|
||||
/// Lists namespaces for the explicit connection-form access-scope selector.
|
||||
///
|
||||
/// Authorization metadata provides the fast path. Some ordinary Nacos
|
||||
/// accounts may enumerate namespaces but cannot read that metadata; for that
|
||||
/// case only, this user-initiated operation verifies both configuration and
|
||||
/// service access before offering a namespace. Sidebar loading never calls
|
||||
/// this function, so it cannot trigger an N-per-namespace scan.
|
||||
pub async fn list_displayable_namespaces(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
let namespaces = admin.list_namespaces().await?;
|
||||
match resolve_readable_namespaces(connection_id, connection_fingerprint, admin.clone(), namespaces.clone()).await {
|
||||
Ok(result) => Ok(result.namespaces),
|
||||
Err(error) if is_managed_namespaces_required_error(&error) => {
|
||||
probe_displayable_namespaces(namespaces, admin).await
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_displayable_namespaces(
|
||||
namespaces: Vec<NacosNamespaceInfo>,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
let mut checked = stream::iter(namespaces.into_iter().enumerate().map(|(index, namespace)| {
|
||||
let admin = admin.clone();
|
||||
async move { probe_namespace_access(admin, namespace).await.map(|accessible| (index, accessible)) }
|
||||
}))
|
||||
.buffer_unordered(DISCOVERY_CONCURRENCY)
|
||||
.collect::<Vec<_>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
checked.sort_by_key(|(index, _)| *index);
|
||||
Ok(checked.into_iter().filter_map(|(_, namespace)| namespace).collect())
|
||||
}
|
||||
|
||||
async fn probe_namespace_access(
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
namespace: NacosNamespaceInfo,
|
||||
) -> Result<Option<NacosNamespaceInfo>, String> {
|
||||
let namespace_id = namespace.namespace.clone();
|
||||
match admin
|
||||
.list_configs(NacosConfigQuery {
|
||||
namespace: Some(namespace_id.clone()),
|
||||
group: None,
|
||||
group_contains: false,
|
||||
data_id: None,
|
||||
app_name: None,
|
||||
search: None,
|
||||
page_no: Some(1),
|
||||
page_size: Some(1),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(error) if is_access_denied_error(&error) => return Ok(None),
|
||||
Err(error) => return Err(namespace_probe_error(&namespace_id, "configuration", &error)),
|
||||
}
|
||||
|
||||
match admin
|
||||
.list_services(NacosServiceQuery {
|
||||
namespace: Some(namespace_id.clone()),
|
||||
group_name: None,
|
||||
service_name: None,
|
||||
page_no: Some(1),
|
||||
page_size: Some(1),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(Some(namespace)),
|
||||
Err(error) if is_access_denied_error(&error) => Ok(None),
|
||||
Err(error) => Err(namespace_probe_error(&namespace_id, "service", &error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_access_denied_error(error: &str) -> bool {
|
||||
let error = error.to_ascii_lowercase();
|
||||
error.contains("403")
|
||||
|| error.contains("forbidden")
|
||||
|| error.contains("access denied")
|
||||
|| error.contains("authorization failed")
|
||||
|| error.contains("authfailed")
|
||||
}
|
||||
|
||||
fn namespace_probe_error(namespace: &str, capability: &str, detail: &str) -> String {
|
||||
format!(
|
||||
"NACOS_ERROR[namespaceAccessDetectionFailed]: unable to verify {capability} access for namespace `{namespace}`: {detail}"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn sidebar_snapshot(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
@@ -75,17 +174,53 @@ pub async fn sidebar_snapshot(
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-saved display scope without relying on Nacos role metadata.
|
||||
/// The scope only narrows the namespaces already returned by the server.
|
||||
pub async fn sidebar_snapshot_with_visible_scope(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
visible_scope: Option<&[String]>,
|
||||
) -> Result<NacosNamespaceSidebarSnapshot, String> {
|
||||
let Some(visible_scope) = visible_scope else {
|
||||
return sidebar_snapshot(connection_id, connection_fingerprint, admin).await;
|
||||
};
|
||||
|
||||
let namespaces = admin.list_namespaces().await?;
|
||||
let visible = visible_scope.iter().map(|namespace| namespace_identity(namespace)).collect();
|
||||
Ok(NacosNamespaceSidebarSnapshot {
|
||||
namespaces: filter_namespaces(namespaces, &visible),
|
||||
// A saved display scope only limits the namespace tree. It must not
|
||||
// suppress the independent probe that determines whether the account
|
||||
// can open the user and role workspace.
|
||||
access_control: admin.refresh_access_control_capabilities().await,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_namespace_authorization_error(error: &str) -> bool {
|
||||
error.contains("NACOS_ERROR[managedNamespacesRequired]")
|
||||
|| error.contains("NACOS_ERROR[namespaceAuthorizationUnavailable]")
|
||||
}
|
||||
|
||||
fn is_managed_namespaces_required_error(error: &str) -> bool {
|
||||
error.contains("NACOS_ERROR[managedNamespacesRequired]")
|
||||
}
|
||||
|
||||
async fn load_readable_namespaces(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<ReadableNamespaces, String> {
|
||||
let namespaces = admin.list_namespaces().await?;
|
||||
resolve_readable_namespaces(connection_id, connection_fingerprint, admin, namespaces).await
|
||||
}
|
||||
|
||||
async fn resolve_readable_namespaces(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
namespaces: Vec<NacosNamespaceInfo>,
|
||||
) -> Result<ReadableNamespaces, String> {
|
||||
let Some(username) =
|
||||
admin.current_username().map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
|
||||
else {
|
||||
@@ -420,13 +555,18 @@ mod tests {
|
||||
struct CountingAdmin {
|
||||
namespaces: Vec<NacosNamespaceInfo>,
|
||||
readable_ids: BTreeSet<String>,
|
||||
role_error: bool,
|
||||
permission_error: bool,
|
||||
config_transport_error: bool,
|
||||
service_denied_ids: BTreeSet<String>,
|
||||
explicitly_scoped_ids: Option<Vec<String>>,
|
||||
namespace_calls: AtomicUsize,
|
||||
capability_calls: AtomicUsize,
|
||||
access_control_refresh_calls: AtomicUsize,
|
||||
role_calls: AtomicUsize,
|
||||
permission_calls: AtomicUsize,
|
||||
config_calls: AtomicUsize,
|
||||
service_calls: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CountingAdmin {
|
||||
@@ -441,13 +581,18 @@ mod tests {
|
||||
Self {
|
||||
namespaces,
|
||||
readable_ids,
|
||||
role_error: false,
|
||||
permission_error: false,
|
||||
config_transport_error: false,
|
||||
service_denied_ids: BTreeSet::new(),
|
||||
explicitly_scoped_ids: None,
|
||||
namespace_calls: AtomicUsize::new(0),
|
||||
capability_calls: AtomicUsize::new(0),
|
||||
access_control_refresh_calls: AtomicUsize::new(0),
|
||||
role_calls: AtomicUsize::new(0),
|
||||
permission_calls: AtomicUsize::new(0),
|
||||
config_calls: AtomicUsize::new(0),
|
||||
service_calls: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,6 +602,7 @@ mod tests {
|
||||
+ self.role_calls.load(Ordering::SeqCst)
|
||||
+ self.permission_calls.load(Ordering::SeqCst)
|
||||
+ self.config_calls.load(Ordering::SeqCst)
|
||||
+ self.service_calls.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,6 +624,11 @@ mod tests {
|
||||
self.explicitly_scoped_ids.clone()
|
||||
}
|
||||
|
||||
async fn refresh_access_control_capabilities(&self) -> NacosAccessControlCapabilities {
|
||||
self.access_control_refresh_calls.fetch_add(1, Ordering::SeqCst);
|
||||
self.access_control_capabilities()
|
||||
}
|
||||
|
||||
async fn refresh_namespace_authorization(
|
||||
&self,
|
||||
username: &str,
|
||||
@@ -524,9 +675,16 @@ mod tests {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_configs(&self, _: NacosConfigQuery) -> Result<NacosConfigList, String> {
|
||||
async fn list_configs(&self, query: NacosConfigQuery) -> Result<NacosConfigList, String> {
|
||||
self.config_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Err("per-namespace probes are forbidden in the sidebar path".to_string())
|
||||
if self.config_transport_error {
|
||||
return Err("connection reset by peer".to_string());
|
||||
}
|
||||
let namespace = query.namespace.unwrap_or_default();
|
||||
if !self.readable_ids.contains(&namespace) {
|
||||
return Err("403 Forbidden".to_string());
|
||||
}
|
||||
Ok(NacosConfigList { page_no: 1, page_size: 1, total_count: 0, items: Vec::new() })
|
||||
}
|
||||
|
||||
async fn search_config_content_page(
|
||||
@@ -573,6 +731,9 @@ mod tests {
|
||||
|
||||
async fn list_role_bindings(&self, _: NacosRoleQuery) -> Result<NacosRoleList, String> {
|
||||
self.role_calls.fetch_add(1, Ordering::SeqCst);
|
||||
if self.role_error {
|
||||
return Err("403 Forbidden".to_string());
|
||||
}
|
||||
Ok(NacosRoleList {
|
||||
page_no: 1,
|
||||
page_size: AUTH_PAGE_SIZE,
|
||||
@@ -602,8 +763,13 @@ mod tests {
|
||||
Ok(NacosPermissionList { page_no: 1, page_size: AUTH_PAGE_SIZE, total_count: items.len() as u64, items })
|
||||
}
|
||||
|
||||
async fn list_services(&self, _: NacosServiceQuery) -> Result<NacosServiceList, String> {
|
||||
Err("unused".to_string())
|
||||
async fn list_services(&self, query: NacosServiceQuery) -> Result<NacosServiceList, String> {
|
||||
self.service_calls.fetch_add(1, Ordering::SeqCst);
|
||||
let namespace = query.namespace.unwrap_or_default();
|
||||
if !self.readable_ids.contains(&namespace) || self.service_denied_ids.contains(&namespace) {
|
||||
return Err("403 Forbidden".to_string());
|
||||
}
|
||||
Ok(NacosServiceList { page_no: 1, page_size: 1, total_count: 0, items: Vec::new() })
|
||||
}
|
||||
|
||||
async fn get_service(&self, _: NacosServiceQuery) -> Result<NacosServiceDetail, String> {
|
||||
@@ -755,6 +921,64 @@ mod tests {
|
||||
assert_eq!(admin.total_authorization_calls(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_namespace_detection_probes_config_and_service_when_role_read_is_forbidden() {
|
||||
let connection_id = "displayable-namespaces-role-forbidden";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(4);
|
||||
admin.role_error = true;
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let namespaces =
|
||||
list_displayable_namespaces(connection_id, "server-a".to_string(), admin.clone()).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
namespaces.iter().map(|namespace| namespace.namespace.as_str()).collect::<Vec<_>>(),
|
||||
vec!["team-0", "team-2"]
|
||||
);
|
||||
assert_eq!(admin.namespace_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.capability_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.role_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.permission_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 4);
|
||||
assert_eq!(admin.service_calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_namespace_detection_aborts_on_unexpected_probe_failure() {
|
||||
let connection_id = "displayable-namespaces-probe-failure";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(4);
|
||||
admin.role_error = true;
|
||||
admin.config_transport_error = true;
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let error =
|
||||
list_displayable_namespaces(connection_id, "server-a".to_string(), admin.clone()).await.unwrap_err();
|
||||
|
||||
assert!(error.contains("NACOS_ERROR[namespaceAccessDetectionFailed]"));
|
||||
assert_eq!(admin.namespace_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.role_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.permission_calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_namespace_detection_requires_service_access_too() {
|
||||
let connection_id = "displayable-namespaces-service-denied";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(4);
|
||||
admin.role_error = true;
|
||||
admin.service_denied_ids.insert("team-0".to_string());
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let namespaces =
|
||||
list_displayable_namespaces(connection_id, "server-a".to_string(), admin.clone()).await.unwrap();
|
||||
|
||||
assert_eq!(namespaces.iter().map(|namespace| namespace.namespace.as_str()).collect::<Vec<_>>(), vec!["team-2"]);
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 4);
|
||||
assert_eq!(admin.service_calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn roles_only_sidebar_keeps_access_control_entry_without_widening_namespaces() {
|
||||
let connection_id = "roles-only-sidebar-authorization";
|
||||
@@ -791,6 +1015,36 @@ mod tests {
|
||||
assert!(!snapshot.access_control.list_users.supported);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn visible_sidebar_scope_refreshes_access_control_without_authorization_inference() {
|
||||
let connection_id = "visible-sidebar-scope";
|
||||
invalidate(connection_id);
|
||||
let admin = CountingAdmin::restricted(100);
|
||||
let admin = Arc::new(admin);
|
||||
let visible_scope = vec!["team-2".to_string(), "team-78".to_string()];
|
||||
|
||||
let snapshot = sidebar_snapshot_with_visible_scope(
|
||||
connection_id,
|
||||
"server-a".to_string(),
|
||||
admin.clone(),
|
||||
Some(&visible_scope),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
snapshot.namespaces.iter().map(|namespace| namespace.namespace.as_str()).collect::<Vec<_>>(),
|
||||
vec!["team-2", "team-78"]
|
||||
);
|
||||
assert_eq!(admin.namespace_calls.load(Ordering::SeqCst), 1);
|
||||
assert!(snapshot.access_control.list_users.supported);
|
||||
assert_eq!(admin.access_control_refresh_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(admin.capability_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.role_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.permission_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_is_bound_to_connection_fingerprint_and_namespace_set() {
|
||||
let connection_id = "namespace-cache-test";
|
||||
|
||||
@@ -64,6 +64,9 @@ pub trait NacosAdmin: Send + Sync {
|
||||
async fn list_namespaces(&self) -> Result<Vec<NacosNamespaceInfo>, String>;
|
||||
async fn create_namespace(&self, req: NacosNamespaceCreate) -> Result<(), String>;
|
||||
async fn update_namespace(&self, req: NacosNamespaceUpdate) -> Result<(), String>;
|
||||
async fn delete_namespace(&self, _: String) -> Result<(), String> {
|
||||
Err("Nacos namespace deletion is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn list_configs(&self, query: NacosConfigQuery) -> Result<NacosConfigList, String>;
|
||||
/// Returns `Ok(None)` only when the server does not expose a native
|
||||
/// content-search endpoint. Authentication, throttling and transport
|
||||
|
||||
@@ -6,7 +6,7 @@ use futures::StreamExt;
|
||||
use prometheus_parse::{Labels, Sample, Scrape, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::nacos::config::{NacosAdminConfig, NacosImplementation, NacosMetricsMode};
|
||||
use crate::nacos::config::{NacosAdminConfig, NacosApiPlane, NacosImplementation, NacosMetricsMode};
|
||||
use crate::nacos::types::{
|
||||
NacosPrometheusConfigMetrics, NacosPrometheusNamingMetrics, NacosPrometheusResourceMetrics,
|
||||
NacosPrometheusSnapshot, NacosPrometheusSource, NacosPrometheusTrafficMetrics,
|
||||
@@ -22,6 +22,10 @@ pub(crate) fn endpoint_candidates(cfg: &NacosAdminConfig) -> Result<Vec<String>,
|
||||
NacosMetricsMode::Auto => {}
|
||||
}
|
||||
|
||||
if cfg.api_plane() == NacosApiPlane::Console {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let base = cfg.server_addr.trim_end_matches('/');
|
||||
let context = cfg.context_path.trim_end_matches('/');
|
||||
let raw = match cfg.implementation.as_ref().unwrap_or(&NacosImplementation::Nacos) {
|
||||
@@ -802,6 +806,7 @@ app_memory_usage 1
|
||||
NacosAdminConfig {
|
||||
implementation: Some(implementation),
|
||||
version_mode: None,
|
||||
api_plane: None,
|
||||
server_addr: server_addr.to_string(),
|
||||
display_server_addr: server_addr.to_string(),
|
||||
namespace: String::new(),
|
||||
|
||||
@@ -40,7 +40,11 @@ fn ensure_access_control_operation(
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn nacos_test_connection_core(state: &AppState, conn_id: &str) -> Result<NacosConnectionInfo, String> {
|
||||
pub async fn nacos_test_connection_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
force_access_control_refresh: bool,
|
||||
) -> Result<NacosConnectionInfo, String> {
|
||||
let cfg = state.configs.read().await.get(conn_id).cloned().ok_or("Connection not found")?;
|
||||
if cfg.db_type != DatabaseType::Nacos {
|
||||
return Err("Connection is not a Nacos admin connection".to_string());
|
||||
@@ -49,20 +53,31 @@ pub async fn nacos_test_connection_core(state: &AppState, conn_id: &str) -> Resu
|
||||
// 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?;
|
||||
if force_access_control_refresh {
|
||||
admin.invalidate_access_control_capabilities();
|
||||
}
|
||||
admin.inspect_connection().await
|
||||
}
|
||||
|
||||
pub async fn nacos_list_namespaces_core(state: &AppState, conn_id: &str) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
crate::nacos::namespace_access::list_readable_namespaces(conn_id, fingerprint, admin).await
|
||||
crate::nacos::namespace_access::list_displayable_namespaces(conn_id, fingerprint, admin).await
|
||||
}
|
||||
|
||||
pub async fn nacos_sidebar_snapshot_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
) -> Result<NacosNamespaceSidebarSnapshot, String> {
|
||||
let visible_scope =
|
||||
state.configs.read().await.get(conn_id).ok_or("Connection not found")?.visible_databases.clone();
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
crate::nacos::namespace_access::sidebar_snapshot(conn_id, fingerprint, admin).await
|
||||
crate::nacos::namespace_access::sidebar_snapshot_with_visible_scope(
|
||||
conn_id,
|
||||
fingerprint,
|
||||
admin,
|
||||
visible_scope.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn nacos_create_namespace_core(
|
||||
@@ -72,7 +87,11 @@ pub async fn nacos_create_namespace_core(
|
||||
) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Create Nacos namespace").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.create_namespace(req).await
|
||||
let result = admin.create_namespace(req).await;
|
||||
if result.is_ok() {
|
||||
crate::nacos::namespace_access::invalidate(conn_id);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_update_namespace_core(
|
||||
@@ -82,7 +101,21 @@ pub async fn nacos_update_namespace_core(
|
||||
) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Update Nacos namespace").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.update_namespace(req).await
|
||||
let result = admin.update_namespace(req).await;
|
||||
if result.is_ok() {
|
||||
crate::nacos::namespace_access::invalidate(conn_id);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_delete_namespace_core(state: &AppState, conn_id: &str, namespace_id: String) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Delete Nacos namespace").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let result = admin.delete_namespace(namespace_id).await;
|
||||
if result.is_ok() {
|
||||
crate::nacos::namespace_access::invalidate(conn_id);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_list_configs_core(
|
||||
@@ -571,6 +604,7 @@ mod tests {
|
||||
display_server_addr: "http://127.0.0.1:3848".to_string(),
|
||||
namespace: "public".to_string(),
|
||||
version_mode: Some(NacosVersionMode::Auto),
|
||||
api_plane: None,
|
||||
context_path: "/nacos".to_string(),
|
||||
managed_namespaces: Vec::new(),
|
||||
rnacos_console_addr: String::new(),
|
||||
|
||||
@@ -161,6 +161,8 @@ pub struct NacosServiceCapabilities {
|
||||
pub delete_service: NacosOperationCapability,
|
||||
pub list_instances: NacosOperationCapability,
|
||||
pub update_instance: NacosOperationCapability,
|
||||
#[serde(default)]
|
||||
pub update_instance_health: NacosOperationCapability,
|
||||
pub register_instance: NacosOperationCapability,
|
||||
pub deregister_instance: NacosOperationCapability,
|
||||
}
|
||||
@@ -175,6 +177,7 @@ impl NacosServiceCapabilities {
|
||||
delete_service: NacosOperationCapability::unsupported(reason),
|
||||
list_instances: NacosOperationCapability::supported(),
|
||||
update_instance: NacosOperationCapability::unsupported(reason),
|
||||
update_instance_health: NacosOperationCapability::unsupported(reason),
|
||||
register_instance: NacosOperationCapability::unsupported(reason),
|
||||
deregister_instance: NacosOperationCapability::unsupported(reason),
|
||||
}
|
||||
|
||||
@@ -45,6 +45,18 @@ impl CredentialKey {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, Hash, PartialEq)]
|
||||
struct PurposeCredentialKey {
|
||||
credential: CredentialKey,
|
||||
purpose: String,
|
||||
}
|
||||
|
||||
impl PurposeCredentialKey {
|
||||
fn new(owner_scope: &str, connection_id: &str, purpose: &str) -> Self {
|
||||
Self { credential: CredentialKey::new(owner_scope, connection_id), purpose: purpose.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionCredential {
|
||||
password: String,
|
||||
generation: u64,
|
||||
@@ -53,6 +65,7 @@ struct SessionCredential {
|
||||
#[derive(Default)]
|
||||
struct SessionCredentialState {
|
||||
credentials: HashMap<CredentialKey, SessionCredential>,
|
||||
purpose_credentials: HashMap<PurposeCredentialKey, SessionCredential>,
|
||||
pool_credential_owners: HashMap<String, String>,
|
||||
next_generation: u64,
|
||||
}
|
||||
@@ -62,6 +75,11 @@ pub struct SessionCredentialWriteToken {
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
pub struct PurposeSessionCredentialWriteToken {
|
||||
key: PurposeCredentialKey,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// 当前请求的认证会话作用域(Web 会话 token / 桌面端空串)。
|
||||
///
|
||||
/// 由 Web 鉴权中间件在请求边界通过 [`with_credential_owner`] 注入;未注入(桌面端、
|
||||
@@ -120,6 +138,39 @@ impl SessionCredentialStore {
|
||||
state.credentials.get(&CredentialKey::new(owner_scope, connection_id)).map(|entry| entry.password.clone())
|
||||
}
|
||||
|
||||
/// Stores an additional transient secret for a connection-specific purpose.
|
||||
pub fn set_for_purpose(&self, owner_scope: &str, connection_id: &str, purpose: &str, password: &str) {
|
||||
let _ = self.set_for_purpose_with_token(owner_scope, connection_id, purpose, password);
|
||||
}
|
||||
|
||||
/// Stores a purpose-specific secret and returns a token that can roll back
|
||||
/// this exact write without deleting a newer concurrent value.
|
||||
pub fn set_for_purpose_with_token(
|
||||
&self,
|
||||
owner_scope: &str,
|
||||
connection_id: &str,
|
||||
purpose: &str,
|
||||
password: &str,
|
||||
) -> Option<PurposeSessionCredentialWriteToken> {
|
||||
if purpose.is_empty() || password.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
state.next_generation = state.next_generation.checked_add(1).expect("session credential generation overflow");
|
||||
let key = PurposeCredentialKey::new(owner_scope, connection_id, purpose);
|
||||
let generation = state.next_generation;
|
||||
state.purpose_credentials.insert(key.clone(), SessionCredential { password: password.to_string(), generation });
|
||||
Some(PurposeSessionCredentialWriteToken { key, generation })
|
||||
}
|
||||
|
||||
pub fn get_for_purpose(&self, owner_scope: &str, connection_id: &str, purpose: &str) -> Option<String> {
|
||||
let state = self.state.read().unwrap_or_else(|error| error.into_inner());
|
||||
state
|
||||
.purpose_credentials
|
||||
.get(&PurposeCredentialKey::new(owner_scope, connection_id, purpose))
|
||||
.map(|entry| entry.password.clone())
|
||||
}
|
||||
|
||||
/// 某个 owner 作用域下是否存在本次运行期临时密码。
|
||||
pub fn has(&self, owner_scope: &str, connection_id: &str) -> bool {
|
||||
self.get(owner_scope, connection_id).is_some()
|
||||
@@ -129,6 +180,9 @@ impl SessionCredentialStore {
|
||||
pub fn remove(&self, owner_scope: &str, connection_id: &str) {
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
state.credentials.remove(&CredentialKey::new(owner_scope, connection_id));
|
||||
state.purpose_credentials.retain(|key, _| {
|
||||
key.credential.owner_scope != owner_scope || key.credential.connection_id != connection_id
|
||||
});
|
||||
}
|
||||
|
||||
/// 仅当指定写入仍是当前值时删除,用于连接失败回滚,避免旧 attempt 删除更新密码。
|
||||
@@ -142,11 +196,24 @@ impl SessionCredentialStore {
|
||||
is_current
|
||||
}
|
||||
|
||||
pub fn remove_purpose_if_current(&self, token: &PurposeSessionCredentialWriteToken) -> bool {
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
let is_current = state
|
||||
.purpose_credentials
|
||||
.get(&token.key)
|
||||
.is_some_and(|credential| credential.generation == token.generation);
|
||||
if is_current {
|
||||
state.purpose_credentials.remove(&token.key);
|
||||
}
|
||||
is_current
|
||||
}
|
||||
|
||||
/// 清除某个 owner 作用域下的全部凭据(Web 登出 / 登录会话失效),不影响其他
|
||||
/// 登录会话的凭据。
|
||||
pub fn clear_owner(&self, owner_scope: &str) {
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
state.credentials.retain(|key, _| key.owner_scope != owner_scope);
|
||||
state.purpose_credentials.retain(|key, _| key.credential.owner_scope != owner_scope);
|
||||
}
|
||||
|
||||
/// 全局连接配置被编辑、删除或复用 ID 时,原子清除所有 owner 的临时凭据和
|
||||
@@ -154,6 +221,7 @@ impl SessionCredentialStore {
|
||||
pub fn clear_connection(&self, connection_id: &str) {
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
state.credentials.retain(|key, _| key.connection_id != connection_id);
|
||||
state.purpose_credentials.retain(|key, _| key.credential.connection_id != connection_id);
|
||||
let pool_prefix = format!("{connection_id}:");
|
||||
state
|
||||
.pool_credential_owners
|
||||
@@ -164,6 +232,7 @@ impl SessionCredentialStore {
|
||||
pub fn clear(&self) {
|
||||
let mut state = self.state.write().unwrap_or_else(|error| error.into_inner());
|
||||
state.credentials.clear();
|
||||
state.purpose_credentials.clear();
|
||||
}
|
||||
|
||||
pub fn record_pool_owner(&self, pool_key: &str, owner_scope: &str) {
|
||||
@@ -195,7 +264,7 @@ impl SessionCredentialStore {
|
||||
|
||||
fn credential_count(&self) -> usize {
|
||||
let state = self.state.read().unwrap_or_else(|error| error.into_inner());
|
||||
state.credentials.len()
|
||||
state.credentials.len() + state.purpose_credentials.len()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,6 +357,32 @@ mod tests {
|
||||
assert!(store.has("token-x", "conn-a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purpose_credentials_follow_owner_and_connection_cleanup() {
|
||||
let store = SessionCredentialStore::new();
|
||||
store.set_for_purpose("token-x", "conn-a", "nacos-primary", "new-secret");
|
||||
store.set_for_purpose("token-y", "conn-a", "nacos-primary", "other-secret");
|
||||
|
||||
assert_eq!(store.get_for_purpose("token-x", "conn-a", "nacos-primary").as_deref(), Some("new-secret"));
|
||||
assert_eq!(store.get_for_purpose("token-y", "conn-a", "nacos-primary").as_deref(), Some("other-secret"));
|
||||
store.clear_owner("token-x");
|
||||
assert_eq!(store.get_for_purpose("token-x", "conn-a", "nacos-primary"), None);
|
||||
store.clear_connection("conn-a");
|
||||
assert_eq!(store.get_for_purpose("token-y", "conn-a", "nacos-primary"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_purpose_write_token_cannot_remove_newer_credential() {
|
||||
let store = SessionCredentialStore::new();
|
||||
let first = store.set_for_purpose_with_token("token-x", "conn-a", "nacos-console", "first-secret").unwrap();
|
||||
let second = store.set_for_purpose_with_token("token-x", "conn-a", "nacos-console", "second-secret").unwrap();
|
||||
|
||||
assert!(!store.remove_purpose_if_current(&first));
|
||||
assert_eq!(store.get_for_purpose("token-x", "conn-a", "nacos-console").as_deref(), Some("second-secret"));
|
||||
assert!(store.remove_purpose_if_current(&second));
|
||||
assert_eq!(store.get_for_purpose("token-x", "conn-a", "nacos-console"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_output_hides_password_values() {
|
||||
let store = SessionCredentialStore::new();
|
||||
|
||||
@@ -2513,6 +2513,7 @@ impl Storage {
|
||||
// This preference is an exception: retaining the old password would
|
||||
// make a no-save connection silently authenticate without prompting.
|
||||
persist_secret_in_tx(&tx, &config.id, "password", "")?;
|
||||
delete_secret_prefix_in_tx(&tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
}
|
||||
let mut sanitized = config;
|
||||
sanitized.password = String::new();
|
||||
@@ -2919,6 +2920,31 @@ impl Storage {
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
return Ok(false);
|
||||
}
|
||||
if !config.save_password {
|
||||
let primary_needs_rewrite = nacos_auth_object(config.external_config.as_ref())
|
||||
.filter(|auth| auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword"))
|
||||
.and_then(|auth| auth.get("password").and_then(serde_json::Value::as_str))
|
||||
.is_some_and(|password| !password.is_empty());
|
||||
let console_needs_rewrite = nacos_console_auth_object(config.external_config.as_ref())
|
||||
.filter(|auth| auth.get("kind").and_then(serde_json::Value::as_str) == Some("usernamePassword"))
|
||||
.and_then(|auth| auth.get("password").and_then(serde_json::Value::as_str))
|
||||
.is_some_and(|password| !password.is_empty());
|
||||
scrub_nacos_auth_secrets(config);
|
||||
|
||||
let connection_id = connection_id.to_string();
|
||||
let key_prefix = format!("{NACOS_AUTH_SECRET_PREFIX}%");
|
||||
self.with_conn(move |conn| {
|
||||
conn.execute(
|
||||
"DELETE FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2",
|
||||
params![connection_id, key_prefix],
|
||||
)
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await?;
|
||||
|
||||
return Ok(primary_needs_rewrite || console_needs_rewrite);
|
||||
}
|
||||
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") {
|
||||
@@ -4161,7 +4187,7 @@ fn persist_mq_token_signing_secret_in_tx(
|
||||
}
|
||||
|
||||
fn persist_nacos_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionConfig) -> Result<(), String> {
|
||||
if config.db_type != DatabaseType::Nacos {
|
||||
if config.db_type != DatabaseType::Nacos || !config.save_password {
|
||||
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -4823,6 +4849,24 @@ mod tests {
|
||||
config.external_config.as_ref()?.get("auth")?.get("password")?.as_str()
|
||||
}
|
||||
|
||||
fn nacos_console_auth_password(config: &ConnectionConfig) -> Option<&str> {
|
||||
config.external_config.as_ref()?.get("rnacosConsoleAuth")?.get("password")?.as_str()
|
||||
}
|
||||
|
||||
fn nacos_connection_with_console_auth(
|
||||
id: &str,
|
||||
primary_password: &str,
|
||||
console_password: &str,
|
||||
) -> ConnectionConfig {
|
||||
let mut config = nacos_connection(id, primary_password);
|
||||
config.external_config.as_mut().unwrap()["rnacosConsoleAuth"] = serde_json::json!({
|
||||
"kind": "usernamePassword",
|
||||
"username": "console",
|
||||
"password": console_password
|
||||
});
|
||||
config
|
||||
}
|
||||
|
||||
async fn create_data_dir_with_connection(name: &str, connection_id: &str, token: &str) -> std::path::PathBuf {
|
||||
let data_dir = temp_data_dir(name);
|
||||
let storage = Storage::open(&data_dir.join("dbx.db")).await.unwrap();
|
||||
@@ -5263,6 +5307,76 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_connections_does_not_persist_nacos_passwords_when_save_password_is_false() {
|
||||
let path = temp_db_path("nacos-auth-no-save");
|
||||
let storage = Storage::open(&path).await.unwrap();
|
||||
let mut config = nacos_connection_with_console_auth("nacos", "primary-secret", "console-secret");
|
||||
config.save_password = false;
|
||||
|
||||
storage.save_connections(&[config]).await.unwrap();
|
||||
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap(), None);
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap(), None);
|
||||
let loaded = storage.load_connections().await.unwrap();
|
||||
assert_eq!(nacos_auth_password(&loaded[0]), Some(""));
|
||||
assert_eq!(nacos_console_auth_password(&loaded[0]), Some(""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_nacos_password_saving_off_removes_all_stored_auth_secrets() {
|
||||
let path = temp_db_path("nacos-auth-disable-save");
|
||||
let storage = Storage::open(&path).await.unwrap();
|
||||
let mut config = nacos_connection_with_console_auth("nacos", "primary-secret", "console-secret");
|
||||
storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
|
||||
assert!(storage.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap().is_some());
|
||||
assert!(storage.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap().is_some());
|
||||
|
||||
config.save_password = false;
|
||||
storage.save_connections(&[config]).await.unwrap();
|
||||
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap(), None);
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_sync_removes_nacos_auth_secrets_when_password_saving_is_disabled() {
|
||||
let path = temp_db_path("nacos-auth-no-save-metadata-sync");
|
||||
let storage = Storage::open(&path).await.unwrap();
|
||||
let mut config = nacos_connection_with_console_auth("nacos", "primary-secret", "console-secret");
|
||||
storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
|
||||
|
||||
config.save_password = false;
|
||||
storage.save_connection_metadata_preserving_secrets(&[config]).await.unwrap();
|
||||
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap(), None);
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap(), None);
|
||||
let loaded = storage.load_connections().await.unwrap();
|
||||
assert_eq!(nacos_auth_password(&loaded[0]), Some(""));
|
||||
assert_eq!(nacos_console_auth_password(&loaded[0]), Some(""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_connections_cleans_legacy_nacos_passwords_when_saving_is_disabled() {
|
||||
let path = temp_db_path("nacos-auth-no-save-legacy-cleanup");
|
||||
let storage = Storage::open(&path).await.unwrap();
|
||||
let mut config = nacos_connection_with_console_auth("nacos", "legacy-primary-secret", "legacy-console-secret");
|
||||
config.save_password = false;
|
||||
insert_raw_connection(&storage, &config).await;
|
||||
storage.set_secret("nacos", NACOS_AUTH_PASSWORD_KEY, "stale-primary-secret").await.unwrap();
|
||||
storage.set_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY, "stale-console-secret").await.unwrap();
|
||||
|
||||
let loaded = storage.load_connections().await.unwrap();
|
||||
|
||||
assert_eq!(nacos_auth_password(&loaded[0]), Some(""));
|
||||
assert_eq!(nacos_console_auth_password(&loaded[0]), Some(""));
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_AUTH_PASSWORD_KEY).await.unwrap(), None);
|
||||
assert_eq!(storage.get_secret("nacos", NACOS_RNACOS_CONSOLE_PASSWORD_KEY).await.unwrap(), None);
|
||||
let raw_json = raw_connection_json(&storage, "nacos").await;
|
||||
assert!(!raw_json.contains("legacy-primary-secret"));
|
||||
assert!(!raw_json.contains("legacy-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